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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Fotoapparat/Fotoapparat | fotoapparat/src/main/java/io/fotoapparat/selector/AntiBandingModeSelectors.kt | 1 | 925 | package io.fotoapparat.selector
import io.fotoapparat.parameter.AntiBandingMode
typealias AntiBandingModeSelector = Iterable<AntiBandingMode>.() -> AntiBandingMode?
/**
* @return Selector function which provides an auto anti banding mode if available.
* Otherwise provides `null`.
*/
fun auto(): AntiBandingModeSelector = single(AntiBandingMode.Auto)
/**
* @return Selector function which provides a 50hz banding mode if available.
* Otherwise provides `null`.
*/
fun hz50(): AntiBandingModeSelector = single(AntiBandingMode.HZ50)
/**
* @return Selector function which provides a 60hz anti banding mode if available.
* Otherwise provides `null`.
*/
fun hz60(): AntiBandingModeSelector = single(AntiBandingMode.HZ60)
/**
* @return Selector function which provides a disabled anti banding mode if available.
* Otherwise provides `null`.
*/
fun none(): AntiBandingModeSelector = single(AntiBandingMode.None)
| apache-2.0 | a14661ba8b4ca5c169f8117b00890891 | 28.83871 | 86 | 0.767568 | 3.870293 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/CommentLabel.kt | 5 | 1497 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import javax.swing.JComponent
import javax.swing.SwingConstants
class CommentLabel(@NlsContexts.Label text: String? = null) : JBLabel() {
init {
if (text != null) {
this.text = text
setCopyable(true) // hyperlinks support
}
verticalAlignment = SwingConstants.TOP
isFocusable = false
foreground = UIUtil.getContextHelpForeground()
// taken from com.intellij.openapi.ui.panel.ComponentPanelBuilder.createCommentComponent
if (SystemInfo.isMac) {
val font = this.font
val size = font.size2D
val smallFont = font.deriveFont(size - 2.0f)
this.font = smallFont
}
}
}
fun commentLabel(@NlsContexts.Label text: String, init: JBLabel.() -> Unit = {}) =
CommentLabel(text).apply(init)
fun componentWithCommentAtBottom(component: JComponent, label: String?, gap: Int = 4) = borderPanel {
addToTop(component)
label?.let {
addToCenter(commentLabel(it) {
withBorder(JBUI.Borders.emptyLeft(gap))
})
}
} | apache-2.0 | 0098f3d732ddd4bd87c8eedc471baa9c | 33.837209 | 158 | 0.681363 | 4.216901 | false | false | false | false |
AlexKrupa/kotlin-koans | src/iii_conventions/_30_DestructuringDeclarations.kt | 1 | 552 | package iii_conventions.multiAssignemnt
import util.TODO
import util.doc30
fun todoTask30(): Nothing = TODO(
"""
Task 30.
Read about destructuring declarations and make the following code compile by adding one word (after uncommenting it).
""",
documentation = doc30()
)
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
fun isLeapDay(date: MyDate): Boolean {
val (year, month, dayOfMonth) = date
//
// // 29 February of a leap year
return year % 4 == 0 && month == 2 && dayOfMonth == 29
} | mit | 2f0cc90bc35a23db500b25a47e90e706 | 25.333333 | 125 | 0.668478 | 3.86014 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/service/MicroServiceBuilderBase.kt | 1 | 4775 | package org.maxur.mserv.frame.service
import com.fasterxml.jackson.databind.ObjectMapper
import org.maxur.mserv.core.CompositeBuilder
import org.maxur.mserv.core.EntityRepository
import org.maxur.mserv.core.LocalEntityRepository
import org.maxur.mserv.core.command.BaseCommandHandler
import org.maxur.mserv.core.command.CommandHandler
import org.maxur.mserv.frame.BaseMicroService
import org.maxur.mserv.frame.LocatorConfig
import org.maxur.mserv.frame.MicroService
import org.maxur.mserv.frame.domain.BaseService
import org.maxur.mserv.frame.domain.Holder
import org.maxur.mserv.frame.embedded.EmbeddedService
import org.maxur.mserv.frame.embedded.EmbeddedServiceFactory
import org.maxur.mserv.frame.embedded.grizzly.WebServerGrizzlyFactoryImpl
import org.maxur.mserv.frame.kotlin.Locator
import org.maxur.mserv.frame.runner.CompositePropertiesBuilder
import org.maxur.mserv.frame.runner.CompositeServiceBuilder
import org.maxur.mserv.frame.runner.Hooks
import org.maxur.mserv.frame.runner.LocatorBuilder
import org.maxur.mserv.frame.runner.StringsHolder
import org.maxur.mserv.frame.service.bus.EventBus
import org.maxur.mserv.frame.service.bus.EventBusGuavaImpl
import org.maxur.mserv.frame.service.jackson.ObjectMapperProvider
import org.maxur.mserv.frame.service.properties.Properties
import org.maxur.mserv.frame.service.properties.PropertiesFactory
import org.maxur.mserv.frame.service.properties.PropertiesFactoryHoconImpl
import org.maxur.mserv.frame.service.properties.PropertiesFactoryJsonImpl
import org.maxur.mserv.frame.service.properties.PropertiesFactoryYamlImpl
interface MicroServiceBuilder {
/** List of embedded services.*/
val services: CompositeBuilder<EmbeddedService>
/** List of properties sources.*/
val properties: CompositePropertiesBuilder
/** List of hooks on after start. */
val afterStart: Hooks<BaseService>
/** List of hooks on before stop.*/
val beforeStop: Hooks<BaseService>
/** List of hooks on errors. */
val onError: Hooks<Exception>
/** List of project service packages for service locator lookup. */
var packages: StringsHolder
/** Hold source of microservice name **/
var nameHolder: Holder<String>
/**
* Build Microservice.
* @return new instance of Microservice
*/
fun build(): MicroService
}
/**
* Build the microservice.
*
* @author Maxim Yunusov
* @version 1.0
* @since <pre>11/28/2017</pre>
*/
class MicroServiceBuilderBase(private val locatorBuilder: LocatorBuilder) : MicroServiceBuilder {
/** {@inheritDoc} */
override val services: CompositeBuilder<EmbeddedService> = CompositeServiceBuilder()
/** {@inheritDoc} */
override val properties: CompositePropertiesBuilder = CompositePropertiesBuilder()
/** {@inheritDoc} */
override val afterStart = Hooks.onService()
/** {@inheritDoc} */
override val beforeStop = Hooks.onService()
/** {@inheritDoc} */
override val onError = Hooks.onError()
/** {@inheritDoc} */
override var packages = StringsHolder()
/** {@inheritDoc} */
override var nameHolder = Holder.string("Anonymous")
/** {@inheritDoc} */
override fun build(): MicroService {
val locator: Locator = locatorBuilder
.apply {
packages = [email protected]
}
.build {
initLocator()
}
val service = locator.service(MicroService::class) ?: locator.onConfigurationError()
if (service is BaseMicroService) {
service.name = nameHolder.get(locator)!!
service.afterStart.addAll(afterStart.list)
service.beforeStop.addAll(beforeStop.list)
service.onError.addAll(onError.list)
}
return service
}
private fun LocatorConfig.initLocator() {
bind(this@MicroServiceBuilderBase).to(MicroServiceBuilder::class)
bindFactory(properties::build).to(Properties::class)
bindFactory(services::build).to(EmbeddedService::class)
bindFactory({ locator -> BaseMicroService(locator) }).to(MicroService::class)
bind(ObjectMapperProvider.objectMapper).to(ObjectMapper::class)
bind(WebServerGrizzlyFactoryImpl::class).to(EmbeddedServiceFactory::class).named("grizzly")
bind(PropertiesFactoryHoconImpl::class).to(PropertiesFactory::class).named("hocon")
bind(PropertiesFactoryJsonImpl::class).to(PropertiesFactory::class).named("json")
bind(PropertiesFactoryYamlImpl::class).to(PropertiesFactory::class).named("yaml")
bind(LocalEntityRepository::class).to(EntityRepository::class)
bind(EventBusGuavaImpl::class).to(EventBus::class)
bind(BaseCommandHandler::class).to(CommandHandler::class)
}
} | apache-2.0 | 825e878fa17c40deb881fb440a0bc6f5 | 41.265487 | 99 | 0.735916 | 4.29793 | false | false | false | false |
rbatista/algorithms | challenges/hacker-rank/kotlin/src/main/kotlin/com/raphaelnegrisoli/hackerrank/arrays/MinimumSwaps2.kt | 1 | 700 | /**
* https://www.hackerrank.com/challenges/minimum-swaps-2/
*/
package com.raphaelnegrisoli.hackerrank.arrays
import java.lang.IllegalArgumentException
fun main(args: Array<String>) {
val size = readLine()?.toInt() ?: throw IllegalArgumentException("No size available")
val arr = readLine()?.split(" ")?.map { it.trim().toInt() }?.toTypedArray()
?: throw IllegalArgumentException("No array found")
var swaps = 0
var i = 0
while (i < size) {
if (arr[i] != i + 1) {
val temp = arr[i]
arr[i] = arr[arr[i] -1]
arr[temp - 1] = temp
swaps++
} else {
i++
}
}
println(swaps)
} | mit | d76902114360143669c66adbbe109ae0 | 20.90625 | 89 | 0.55 | 3.743316 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/format/elf/CryptedElf.kt | 1 | 46661 | package com.soywiz.kpspemu.format.elf
import com.soywiz.kmem.*
import com.soywiz.korio.error.*
import com.soywiz.kpspemu.kirk.*
import com.soywiz.kpspemu.util.*
import com.soywiz.krypto.encoding.*
// https://github.com/hrydgard/ppsspp/blob/1f9fabee579422053d49e2de557aec6f20ee4405/Core/ELF/PrxDecrypter.cpp
// From PPSSPP
object CryptedElf {
suspend fun decrypt(input: ByteArray): ByteArray {
val out = ByteArray(input.size)
val size = pspDecryptPRX(input.p_u8(), out.p_u8(), input.size)
if (size < 0) invalidOp("Error decrypting prx")
return out.copyOf(size)
}
private fun ROUNDUP16(x: Int) = (((x) + 15) and 15.inv())
private fun GetTagInfo(checkTag: Int): Keys.TagInfo? = Keys.g_TagInfo.firstOrNull { it.tag == checkTag }
private fun ExtraV2Mangle(buffer1: p_u8, codeExtra: Int) {
val buffer2 = ByteArray(ROUNDUP16(0x14 + 0xA0)).p_u8()
memcpy(buffer2 + 0x14, buffer1, 0xA0)
val pl2 = buffer2.p_u32()
pl2[0] = Kirk.KirkMode.DecryptCbc.id
pl2[1] = 0
pl2[2] = 0
pl2[3] = codeExtra
pl2[4] = 0xA0
sceUtilsBufferCopyWithRange(buffer2, 20 + 0xA0, buffer2, 20 + 0xA0, KIRK_CMD_DECRYPT_IV_0)
// copy result back
memcpy(buffer1, buffer2, 0xA0)
}
private fun Scramble(buf: p_u32, size: Int, code: Int): Int {
buf[0] = Kirk.KirkMode.DecryptCbc.id
buf[1] = 0
buf[2] = 0
buf[3] = code
buf[4] = size
return sceUtilsBufferCopyWithRange(buf.p_u8(), size + 0x14, buf.p_u8(), size + 0x14, KIRK_CMD_DECRYPT_IV_0)
}
private fun DecryptPRX1(pbIn: p_u8, pbOut: p_u8, cbTotal: Int, tag: Int): Int {
val bD0 = ByteArray(0x80).p_u8()
val b80 = ByteArray(0x50).p_u8()
val b00 = ByteArray(0x80).p_u8()
val bB0 = ByteArray(0x20).p_u8()
val pti = GetTagInfo(tag) ?: invalidOp("Missing tag ${tag.hex}")
if (pti.key.size <= 0x10) return -1
val firstZeroIndex = pti.key.data.indexOfFirst { it.toInt() != 0 }
val retsize = ((pbIn + 0xB0).p_u32())[0]
// Scramble the key (!)
//
// NOTE: I can't make much sense out of this code. Scramble seems really odd, appears
// to write to stuff that should be before the actual key.
//val key = ByteArray(0x14 + 0x90).p_u8()
val key = ByteArray(0x90).p_u8()
memcpy(key.p_u8(), pti.key.p_u8(), 0x90)
if (firstZeroIndex < 0) {
Scramble(key.p_u32(), 0x90, pti.code)
}
// build conversion into pbOut
if (pbIn != pbOut) {
memcpy(pbOut, pbIn, cbTotal)
}
memcpy(bD0, pbIn + 0xD0, 0x80)
memcpy(b80, pbIn + 0x80, 0x50)
memcpy(b00, pbIn + 0x00, 0x80)
memcpy(bB0, pbIn + 0xB0, 0x20)
memset(pbOut, 0, 0x150)
memset(pbOut, 0x55, 0x40) // first $40 bytes ignored
// step3 demangle in place
val pl = (pbOut + 0x2C).p_u32()
pl[0] = 5 // number of ulongs in the header
pl[1] = 0
pl[2] = 0
pl[3] = pti.code // initial seed for PRX
pl[4] = 0x70 // size
// redo part of the SIG check (step2)
val buffer1 = ByteArray(0x150).p_u8()
memcpy(buffer1 + 0x00, bD0, 0x80)
memcpy(buffer1 + 0x80, b80, 0x50)
memcpy(buffer1 + 0xD0, b00, 0x80)
if (pti.type != 0) {
ExtraV2Mangle(buffer1 + 0x10, pti.type)
}
memcpy(pbOut + 0x40, buffer1 + 0x40, 0x40)
for (iXOR in 0 until 0x70) {
pbOut[0x40 + iXOR] = pbOut[0x40 + iXOR] xor key[0x14 + iXOR]
}
var ret = sceUtilsBufferCopyWithRange(pbOut + 0x2C, 20 + 0x70, pbOut + 0x2C, 20 + 0x70, KIRK_CMD_DECRYPT_IV_0)
if (ret != 0) {
invalidOp("Error(-1)")
}
for (iXOR in 0x6F downTo 0) { //for (iXOR in 0..0x6F) {
pbOut[0x40 + iXOR] = pbOut[0x2C + iXOR] xor key[0x20 + iXOR]
}
memset(pbOut + 0x80, 0, 0x30) // $40 bytes kept, clean up
pbOut[0xA0] = 1
// copy unscrambled parts from header
memcpy(pbOut + 0xB0, bB0, 0x20) // file size + lots of zeros
memcpy(pbOut + 0xD0, b00, 0x80) // ~PSP header
// step4: do the actual decryption of code block
// point 0x40 bytes into the buffer to key info
ret = sceUtilsBufferCopyWithRange(pbOut, cbTotal, pbOut + 0x40, cbTotal - 0x40, KIRK_CMD_DECRYPT_PRIVATE)
if (ret != 0) {
invalidOp("Error(-2)")
}
// return cbTotal - 0x150; // rounded up size
return retsize
}
private fun DecryptPRX2(inbuf: p_u8, outbuf: p_u8, size: Int, tag: Int): Int {
val pti = GetTagInfo(tag) ?: return -1
// only type2 and type6 can be process by this code.
if (pti.type != 2 && pti.type != 6) {
invalidOp("Error -12")
}
val retsize = (inbuf + 0xB0).p_u32()[0]
val tmp1 = ByteArray(0x150).p_u8()
val tmp2 = ByteArray(ROUNDUP16(0x90 + 0x14)).p_u8()
val tmp3 = ByteArray(ROUNDUP16(0x90 + 0x14)).p_u8()
val tmp4 = ByteArray(ROUNDUP16(0x20)).p_u8()
if (inbuf != outbuf)
memcpy(outbuf, inbuf, size)
if (size < 0x160) {
invalidOp("Error(-2)")
}
if ((size - 0x150) < retsize) {
invalidOp("Error(-4)")
}
memcpy(tmp1, outbuf, 0x150)
val p = tmp2 + 0x14
// Writes 0x90 bytes to tmp2 + 0x14.
for (i in 0 until 9) {
memcpy(p + (i shl 4), pti.key.p_u8(), 0x10)
p[(i shl 4)] = i // really? this is very odd
}
if (Scramble(tmp2.p_u32(), 0x90, pti.code) < 0) {
invalidOp("Error(-5) Scramble")
}
memcpy(outbuf, tmp1 + 0xD0, 0x5C)
memcpy(outbuf + 0x5C, tmp1 + 0x140, 0x10)
memcpy(outbuf + 0x6C, tmp1 + 0x12C, 0x14)
memcpy(outbuf + 0x80, tmp1 + 0x080, 0x30)
memcpy(outbuf + 0xB0, tmp1 + 0x0C0, 0x10)
memcpy(outbuf + 0xC0, tmp1 + 0x0B0, 0x10)
memcpy(outbuf + 0xD0, tmp1 + 0x000, 0x80)
memcpy(tmp3 + 0x14, outbuf + 0x5C, 0x60)
if (Scramble(tmp3.p_u32(), 0x60, pti.code) < 0) {
invalidOp("Error(-6) Scramble")
}
memcpy(outbuf + 0x5C, tmp3, 0x60)
memcpy(tmp3, outbuf + 0x6C, 0x14)
memcpy(outbuf + 0x70, outbuf + 0x5C, 0x10)
if (pti.type == 6) {
memcpy(tmp4, outbuf + 0x3C, 0x20)
memcpy(outbuf + 0x50, tmp4, 0x20)
memset(outbuf + 0x18, 0, 0x38)
} else
memset(outbuf + 0x18, 0, 0x58)
memcpy(outbuf + 0x04, outbuf, 0x04)
outbuf.p_u32()[0] = 0x014C
memcpy(outbuf + 0x08, tmp2, 0x10)
/* sha-1 */
if (sceUtilsBufferCopyWithRange(outbuf, 3000000, outbuf, 3000000, KIRK_CMD_SHA1_HASH) != 0) {
invalidOp("Error(-7)")
}
if (memcmp(outbuf, tmp3, 0x14) != 0) {
invalidOp("Error(-8)")
}
for (i in 0 until 0x40) {
tmp3[i + 0x14] = outbuf[i + 0x80] xor tmp2[i + 0x10]
}
if (Scramble(tmp3.p_u32(), 0x40, pti.code) != 0) {
invalidOp("Error(-9)")
}
for (i in 0 until 0x40) {
outbuf[i + 0x40] = tmp3[i] xor tmp2[i + 0x50]
}
if (pti.type == 6) {
memcpy(outbuf + 0x80, tmp4, 0x20)
memset(outbuf + 0xA0, 0, 0x10)
(outbuf + 0xA4).p_u32()[0] = 1
(outbuf + 0xA0).p_u32()[0] = 1
} else {
memset(outbuf + 0x80, 0, 0x30)
(outbuf + 0xA0).p_u32()[0] = 1
}
memcpy(outbuf + 0xB0, outbuf + 0xC0, 0x10)
memset(outbuf + 0xC0, 0, 0x10)
// The real decryption
if (sceUtilsBufferCopyWithRange(outbuf, size, outbuf + 0x40, size - 0x40, KIRK_CMD_DECRYPT_PRIVATE) != 0) {
invalidOp("Error(-1)")
}
if (retsize < 0x150) {
// Fill with 0
memset(outbuf + retsize, 0, 0x150 - retsize)
}
return retsize
}
private fun pspDecryptPRX(inbuf: p_u8, outbuf: p_u8, size: Int): Int {
val retsize = DecryptPRX1(inbuf, outbuf, size, (inbuf + 0xD0).p_u32()[0])
if (retsize >= 0 || retsize == MISSING_KEY) return retsize
return DecryptPRX2(inbuf, outbuf, size, (inbuf + 0xD0).p_u32()[0])
}
private fun sceUtilsBufferCopyWithRange(
output: p_u8,
outputSize: Int,
input: p_u8,
inputSize: Int,
command: Kirk.CommandEnum
): Int = Kirk.hleUtilsBufferCopyWithRange(output, outputSize, input, inputSize, command)
private val KIRK_CMD_DECRYPT_PRIVATE = Kirk.CommandEnum.DECRYPT_PRIVATE // 0x1
private val KIRK_CMD_DECRYPT_IV_0 = Kirk.CommandEnum.DECRYPT_IV_0 // 0x7
private val KIRK_CMD_SHA1_HASH = Kirk.CommandEnum.SHA1_HASH // 0xB
private val MISSING_KEY = -99
@Suppress("RemoveRedundantCallsOfConversionMethods", "unused", "MemberVisibilityCanPrivate")
object Keys {
@Suppress("ArrayInDataClass")
data class TagInfo(val tag: Int, val skey: ByteArray, val code: Int, val type: Int = 0) {
val key = UByteArray(skey)
}
val g_TagInfo = listOf(
TagInfo(
tag = 0x4C949CF0.toInt(),
skey = Hex.decode("3f6709a14771d69e277c7b32670e658a"),
code = 0x43
), // keys210_vita_k0
TagInfo(
tag = 0x4C9494F0.toInt(),
skey = Hex.decode("76f26c0aca3aba4eac76d240f5c3bff9"),
code = 0x43
), // keys660_k1
TagInfo(
tag = 0x4C9495F0.toInt(),
skey = Hex.decode("7a3e5575b96afc4f3ee3dfb36ce82a82"),
code = 0x43
), // keys660_k2
TagInfo(
tag = 0x4C9490F0.toInt(),
skey = Hex.decode("fa790936e619e8a4a94137188102e9b3"),
code = 0x43
), // keys660_k3
TagInfo(
tag = 0x4C9491F0.toInt(),
skey = Hex.decode("85931fed2c4da453599c3f16f350de46"),
code = 0x43
), // keys660_k8
TagInfo(
tag = 0x4C9493F0.toInt(),
skey = Hex.decode("c8a07098aee62b80d791e6ca4ca9784e"),
code = 0x43
), // keys660_k4
TagInfo(
tag = 0x4C9497F0.toInt(),
skey = Hex.decode("bff834028447bd871c52032379bb5981"),
code = 0x43
), // keys660_k5
TagInfo(
tag = 0x4C9492F0.toInt(),
skey = Hex.decode("d283cc63bb1015e77bc06dee349e4afa"),
code = 0x43
), // keys660_k6
TagInfo(
tag = 0x4C9496F0.toInt(),
skey = Hex.decode("ebd91e053caeab62e3b71f37e5cd68c3"),
code = 0x43
), // keys660_k7
TagInfo(
tag = 0x457B90F0.toInt(),
skey = Hex.decode("ba7661478b55a8728915796dd72f780e"),
code = 0x5B
), // keys660_v1
TagInfo(
tag = 0x457B91F0.toInt(),
skey = Hex.decode("c59c779c4101e48579c87163a57d4ffb"),
code = 0x5B
), // keys660_v7
TagInfo(
tag = 0x457B92F0.toInt(),
skey = Hex.decode("928ca412d65c55315b94239b62b3db47"),
code = 0x5B
), // keys660_v6
TagInfo(
tag = 0x457B93F0.toInt(),
skey = Hex.decode("88af18e9c3aa6b56f7c5a8bf1a84e9f3"),
code = 0x5B
), // keys660_v3
TagInfo(
tag = 0x380290F0.toInt(),
skey = Hex.decode("f94a6b96793fee0a04c88d7e5f383acf"),
code = 0x5A
), // keys660_v2
TagInfo(
tag = 0x380291F0.toInt(),
skey = Hex.decode("86a07d4db36ba2fdf41585702d6a0d3a"),
code = 0x5A
), // keys660_v8
TagInfo(
tag = 0x380292F0.toInt(),
skey = Hex.decode("d1b0aec324361349d649d788eaa49986"),
code = 0x5A
), // keys660_v4
TagInfo(
tag = 0x380293F0.toInt(),
skey = Hex.decode("cb93123831c02d2e7a185cac9293ab32"),
code = 0x5A
), // keys660_v5
TagInfo(
tag = 0x4C948CF0.toInt(),
skey = Hex.decode("017bf0e9be9add5437ea0ec4d64d8e9e"),
code = 0x43
), // keys639_k3
TagInfo(
tag = 0x4C948DF0.toInt(),
skey = Hex.decode("9843ff8568b2db3bd422d04fab5f0a31"),
code = 0x43
), // keys638_k4
TagInfo(
tag = 0x4C948BF0.toInt(),
skey = Hex.decode("91f2029e633230a91dda0ba8b741a3cc"),
code = 0x43
), // keys636_k2
TagInfo(
tag = 0x4C948AF0.toInt(),
skey = Hex.decode("07e308647f60a3366a762144c9d70683"),
code = 0x43
), // keys636_k1
TagInfo(
tag = 0x457B8AF0.toInt(),
skey = Hex.decode("47ec6015122ce3e04a226f319ffa973e"),
code = 0x5B
), // keys636_1
TagInfo(
tag = 0x4C9487F0.toInt(),
skey = Hex.decode("81d1128935c8ea8be0022d2d6a1867b8"),
code = 0x43
), // keys630_k8
TagInfo(
tag = 0x457B83F0.toInt(),
skey = Hex.decode("771c065f53ec3ffc22ce5a27ff78a848"),
code = 0x5B
), // keys630_k7
TagInfo(
tag = 0x4C9486F0.toInt(),
skey = Hex.decode("8ddbdc5cf2702b40b23d0009617c1060"),
code = 0x43
), // keys630_k6
TagInfo(
tag = 0x457B82F0.toInt(),
skey = Hex.decode("873721cc65aeaa5f40f66f2a86c7a1c8"),
code = 0x5B
), // keys630_k5
TagInfo(
tag = 0x457B81F0.toInt(),
skey = Hex.decode("aaa1b57c935a95bdef6916fc2b9231dd"),
code = 0x5B
), // keys630_k4
TagInfo(
tag = 0x4C9485F0.toInt(),
skey = Hex.decode("238d3dae4150a0faf32f32cec727cd50"),
code = 0x43
), // keys630_k3
TagInfo(
tag = 0x457B80F0.toInt(),
skey = Hex.decode("d43518022968fba06aa9a5ed78fd2e9d"),
code = 0x5B
), // keys630_k2
TagInfo(
tag = 0x4C9484F0.toInt(),
skey = Hex.decode("36b0dcfc592a951d802d803fcd30a01b"),
code = 0x43
), // keys630_k1
TagInfo(
tag = 0x457B28F0.toInt(),
skey = Hex.decode("b1b37f76c3fb88e6f860d3353ca34ef3"),
code = 0x5B
), // keys620_e
TagInfo(
tag = 0x457B0CF0.toInt(),
skey = Hex.decode("ac34bab1978dae6fbae8b1d6dfdff1a2"),
code = 0x5B
), // keys620_a
TagInfo(
tag = 0x380228F0.toInt(),
skey = Hex.decode("f28f75a73191ce9e75bd2726b4b40c32"),
code = 0x5A
), // keys620_5v
TagInfo(
tag = 0x4C942AF0.toInt(),
skey = Hex.decode("418a354f693adf04fd3946a25c2df221"),
code = 0x43
), // keys620_5k
TagInfo(
tag = 0x4C9428F0.toInt(),
skey = Hex.decode("f1bc1707aeb7c830d8349d406a8edf4e"),
code = 0x43
), // keys620_5
TagInfo(
tag = 0x4C941DF0.toInt(),
skey = Hex.decode("1d13e95004733dd2e1dab9c1e67b25a7"),
code = 0x43
), // keys620_1
TagInfo(
tag = 0x4C941CF0.toInt(),
skey = Hex.decode("d6bdce1e12af9ae66930deda88b8fffb"),
code = 0x43
), // keys620_0
TagInfo(
tag = 0x4C9422F0.toInt(),
skey = Hex.decode("e145932c53e2ab066fb68f0b6691e71e"),
code = 0x43
), // keys600_2
TagInfo(
tag = 0x4C941EF0.toInt(),
skey = Hex.decode("e35239973b84411cc323f1b8a9094bf0"),
code = 0x43
), // keys600_1
TagInfo(
tag = 0x4C9429F0.toInt(),
skey = Hex.decode("6d72a4ba7fbfd1f1a9f3bb071bc0b366"),
code = 0x43
), // keys570_5k
TagInfo(
tag = 0x457B0BF0.toInt(),
skey = Hex.decode("7b9472274ccc543baedf4637ac014d87"),
code = 0x5B
), // keys505_a
TagInfo(
tag = 0x4C9419F0.toInt(),
skey = Hex.decode("582a4c69197b833dd26161fe14eeaa11"),
code = 0x43
), // keys505_1
TagInfo(
tag = 0x4C9418F0.toInt(),
skey = Hex.decode("2e8e97a28542707318daa08af862a2b0"),
code = 0x43
), // keys505_0
TagInfo(
tag = 0x457B1EF0.toInt(),
skey = Hex.decode("a35d51e656c801cae377bfcdff24da4d"),
code = 0x5B
), // keys500_c
TagInfo(
tag = 0x4C941FF0.toInt(),
skey = Hex.decode("2c8eaf1dff79731aad96ab09ea35598b"),
code = 0x43
), // keys500_2
TagInfo(
tag = 0x4C9417F0.toInt(),
skey = Hex.decode("bae2a31207ff041b64a51185f72f995b"),
code = 0x43
), // keys500_1
TagInfo(
tag = 0x4C9416F0.toInt(),
skey = Hex.decode("eb1b530b624932581f830af4993d75d0"),
code = 0x43
), // keys500_0
TagInfo(
tag = 0x4C9414F0.toInt(),
skey = Hex.decode("45ef5c5ded81998412948fabe8056d7d"),
code = 0x43
), // keys390_0
TagInfo(
tag = 0x4C9415F0.toInt(),
skey = Hex.decode("701b082522a14d3b6921f9710aa841a9"),
code = 0x43
), // keys390_1
TagInfo(
tag = 0x4C9412F0.toInt(),
skey = Hex.decode("26380aaca5d874d132b72abf799e6ddb"),
code = 0x43
), // keys370_0
TagInfo(
tag = 0x4C9413F0.toInt(),
skey = Hex.decode("53e7abb9c64a4b779217b5740adaa9ea"),
code = 0x43
), // keys370_1
TagInfo(
tag = 0x457B10F0.toInt(),
skey = Hex.decode("7110f0a41614d59312ff7496df1fda89"),
code = 0x5B
), // keys370_2
TagInfo(
tag = 0x4C940DF0.toInt(),
skey = Hex.decode("3c2b51d42d8547da2dca18dffe5409ed"),
code = 0x43
), // keys360_0
TagInfo(
tag = 0x4C9410F0.toInt(),
skey = Hex.decode("311f98d57b58954532ab3ae389324b34"),
code = 0x43
), // keys360_1
TagInfo(
tag = 0x4C940BF0.toInt(),
skey = Hex.decode("3b9b1a56218014ed8e8b0842fa2cdc3a"),
code = 0x43
), // keys330_0
TagInfo(
tag = 0x457B0AF0.toInt(),
skey = Hex.decode("e8be2f06b1052ab9181803e3eb647d26"),
code = 0x5B
), // keys330_1
TagInfo(
tag = 0x38020AF0.toInt(),
skey = Hex.decode("ab8225d7436f6cc195c5f7f063733fe7"),
code = 0x5A
), // keys330_2
TagInfo(
tag = 0x4C940AF0.toInt(),
skey = Hex.decode("a8b14777dc496a6f384c4d96bd49ec9b"),
code = 0x43
), // keys330_3
TagInfo(
tag = 0x4C940CF0.toInt(),
skey = Hex.decode("ec3bd2c0fac1eeb99abcffa389f2601f"),
code = 0x43
), // keys330_4
TagInfo(
tag = 0xCFEF09F0.toInt(),
skey = Hex.decode("a241e839665bfabb1b2d6e0e33e5d73f"),
code = 0x62
), // keys310_0
TagInfo(
tag = 0x457B08F0.toInt(),
skey = Hex.decode("a4608fababdea5655d433ad15ec3ffea"),
code = 0x5B
), // keys310_1
TagInfo(
tag = 0x380208F0.toInt(),
skey = Hex.decode("e75c857a59b4e31dd09ecec2d6d4bd2b"),
code = 0x5A
), // keys310_2
TagInfo(
tag = 0xCFEF08F0.toInt(),
skey = Hex.decode("2e00f6f752cf955aa126b4849b58762f"),
code = 0x62
), // keys310_3
TagInfo(
tag = 0xCFEF07F0.toInt(),
skey = Hex.decode("7ba1e25a91b9d31377654ab7c28a10af"),
code = 0x62
), // keys303_0
TagInfo(
tag = 0xCFEF06F0.toInt(),
skey = Hex.decode("9f671a7a22f3590baa6da4c68bd00377"),
code = 0x62
), // keys300_0
TagInfo(
tag = 0x457B06F0.toInt(),
skey = Hex.decode("15076326dbe2693456082a934e4b8ab2"),
code = 0x5B
), // keys300_1
TagInfo(
tag = 0x380206F0.toInt(),
skey = Hex.decode("563b69f729882f4cdbd5de80c65cc873"),
code = 0x5A
), // keys300_2
TagInfo(
tag = 0xCFEF05F0.toInt(),
skey = Hex.decode("cafbbfc750eab4408e445c6353ce80b1"),
code = 0x62
), // keys280_0
TagInfo(
tag = 0x457B05F0.toInt(),
skey = Hex.decode("409bc69ba9fb847f7221d23696550974"),
code = 0x5B
), // keys280_1
TagInfo(
tag = 0x380205F0.toInt(),
skey = Hex.decode("03a7cc4a5b91c207fffc26251e424bb5"),
code = 0x5A
), // keys280_2
TagInfo(
tag = 0x16D59E03.toInt(),
skey = Hex.decode("c32489d38087b24e4cd749e49d1d34d1"),
code = 0x62
), // keys260_0
TagInfo(
tag = 0x76202403.toInt(),
skey = Hex.decode("f3ac6e7c040a23e70d33d82473392b4a"),
code = 0x5B
), // keys260_1
TagInfo(
tag = 0x0F037303.toInt(),
skey = Hex.decode("72b439ff349bae8230344a1da2d8b43c"),
code = 0x5A
), // keys260_2
TagInfo(
tag = 0x4C940FF0.toInt(),
skey = Hex.decode("8002c0bf000ac0bf4003c0bf40000000"),
code = 0x43
), // key_2DA8
TagInfo(
tag = 0x4467415D.toInt(),
skey = Hex.decode("660fcb3b3075e3100a9565c73c938722"),
code = 0x59
), // key_22E0
TagInfo(
tag = 0x00000000.toInt(),
skey = Hex.decode("6a1971f318ded3a26d3bdec7be98e24c"),
code = 0x42
), // key_21C0
TagInfo(
tag = 0x01000000.toInt(),
skey = Hex.decode("50cc03ac3f531afa0aa4342386617f97"),
code = 0x43
), // key_2250
TagInfo(
tag = 0x2E5E10F0.toInt(),
skey = Hex.decode("9d5c5baf8cd8697e519f7096e6d5c4e8"),
code = 0x48
), // key_2E5E10F0
TagInfo(
tag = 0x2E5E12F0.toInt(),
skey = Hex.decode("8a7bc9d6525888ea518360ca1679e207"),
code = 0x48
), // key_2E5E12F0
TagInfo(
tag = 0x2E5E13F0.toInt(),
skey = Hex.decode("ffa468c331cab74cf123ff01653d2636"),
code = 0x48
), // key_2E5E13F0
TagInfo(
tag = 0x2FD30BF0.toInt(),
skey = Hex.decode("d85879f9a422af8690acda45ce60403f"),
code = 0x47
), // key_2FD30BF0
TagInfo(
tag = 0x2FD311F0.toInt(),
skey = Hex.decode("3a6b489686a5c880696ce64bf6041744"),
code = 0x47
), // key_2FD311F0
TagInfo(
tag = 0x2FD312F0.toInt(),
skey = Hex.decode("c5fb6903207acfba2c90f8b84dd2f1de"),
code = 0x47
), // key_2FD312F0
TagInfo(
tag = 0x2FD313F0.toInt(),
skey = Hex.decode("b024c81643e8f01c8c3067733e9635ef"),
code = 0x47
), // key_2FD313F0
TagInfo(
tag = 0xD91605F0.toInt(),
skey = Hex.decode("b88c458bb6e76eb85159a6537c5e8631"),
code = 0x5D,
type = 2
), // key_D91605F0
TagInfo(
tag = 0xD91606F0.toInt(),
skey = Hex.decode("ed10e036c4fe83f375705ef6a44005f7"),
code = 0x5D,
type = 2
), // key_D91606F0
TagInfo(
tag = 0xD91608F0.toInt(),
skey = Hex.decode("5c770cbbb4c24fa27e3b4eb4b4c870af"),
code = 0x5D,
type = 2
), // key_D91608F0
TagInfo(
tag = 0xD91609F0.toInt(),
skey = Hex.decode("d036127580562043c430943e1c75d1bf"),
code = 0x5D,
type = 2
), // key_D91609F0
TagInfo(
tag = 0xD9160AF0.toInt(),
skey = Hex.decode("10a9ac16ae19c07e3b607786016ff263"),
code = 0x5D,
type = 2
), // key_D9160AF0
TagInfo(
tag = 0xD9160BF0.toInt(),
skey = Hex.decode("8383f13753d0befc8da73252460ac2c2"),
code = 0x5D,
type = 2
), // key_D9160BF0
TagInfo(
tag = 0xD91611F0.toInt(),
skey = Hex.decode("61b0c0587157d9fa74670e5c7e6e95b9"),
code = 0x5D,
type = 2
), // key_D91611F0
TagInfo(
tag = 0xD91612F0.toInt(),
skey = Hex.decode("9e20e1cdd788dec0319b10afc5b87323"),
code = 0x5D,
type = 2
), // key_D91612F0
TagInfo(
tag = 0xD91613F0.toInt(),
skey = Hex.decode("ebff40d8b41ae166913b8f64b6fcb712"),
code = 0x5D,
type = 2
), // key_D91613F0
TagInfo(
tag = 0xD91614F0.toInt(),
skey = Hex.decode("fdf7b73c9fd1339511b8b5bb54237385"),
code = 0x5D,
type = 2
), // key_D91614F0
TagInfo(
tag = 0xD91615F0.toInt(),
skey = Hex.decode("c803e34450f1e72a6a0dc361b68e5f51"),
code = 0x5D,
type = 2
), // key_D91615F0
TagInfo(
tag = 0xD91616F0.toInt(),
skey = Hex.decode("5303b86a101998491caf30e4251b6b28"),
code = 0x5D,
type = 2
), // key_D91616F0
TagInfo(
tag = 0xD91617F0.toInt(),
skey = Hex.decode("02fa487375afae0a67892b954b0987a3"),
code = 0x5D,
type = 2
), // key_D91617F0
TagInfo(
tag = 0xD91618F0.toInt(),
skey = Hex.decode("96967cc3f712da621bf69a9a4444bc48"),
code = 0x5D,
type = 2
), // key_D91618F0
TagInfo(
tag = 0xD91619F0.toInt(),
skey = Hex.decode("e032a7086b2b292cd14d5beea8c8b4e9"),
code = 0x5D,
type = 2
), // key_D91619F0
TagInfo(
tag = 0xD9161AF0.toInt(),
skey = Hex.decode("27e5a74952e194673566910ce89a2524"),
code = 0x5D,
type = 2
), // key_D9161AF0
TagInfo(
tag = 0xD91620F0.toInt(),
skey = Hex.decode("521cb45f403b9addacfcea92fdddf590"),
code = 0x5D,
type = 2
), // key_D91620F0
TagInfo(
tag = 0xD91621F0.toInt(),
skey = Hex.decode("d1912ea621142962f6edaecbdda3bafe"),
code = 0x5D,
type = 2
), // key_D91621F0
TagInfo(
tag = 0xD91622F0.toInt(),
skey = Hex.decode("595d784d21b201176c9ab51bdab7f9e6"),
code = 0x5D,
type = 2
), // key_D91622F0
TagInfo(
tag = 0xD91623F0.toInt(),
skey = Hex.decode("aa45eb4f62fbd10d71d562d2f5bfa52f"),
code = 0x5D,
type = 2
), // key_D91623F0
TagInfo(
tag = 0xD91624F0.toInt(),
skey = Hex.decode("61b726af8bf14158836ac49212cbb1e9"),
code = 0x5D,
type = 2
), // key_D91624F0
TagInfo(
tag = 0xD91628F0.toInt(),
skey = Hex.decode("49a4fc66dce76221db18a750d6a8c1b6"),
code = 0x5D,
type = 2
), // key_D91628F0
TagInfo(
tag = 0xD91680F0.toInt(),
skey = Hex.decode("2c229b123674116749d1d18892f6a1d8"),
code = 0x5D,
type = 6
), // key_D91680F0
TagInfo(
tag = 0xD91681F0.toInt(),
skey = Hex.decode("52b6366c8c467f7acc116299c199be98"),
code = 0x5D,
type = 6
), // key_D91681F0
TagInfo(
tag = 0xD82310F0.toInt(),
skey = Hex.decode("9d09fd20f38f10690db26f00ccc5512e"),
code = 0x51
), // keys02G_E
TagInfo(
tag = 0xD8231EF0.toInt(),
skey = Hex.decode("4f445c62b353c430fc3aa45becfe51ea"),
code = 0x51
), // keys03G_E
TagInfo(
tag = 0xD82328F0.toInt(),
skey = Hex.decode("5daa72f226604d1ce72dc8a32f79c554"),
code = 0x51
), // keys05G_E
TagInfo(
tag = 0x279D08F0.toInt(),
skey = Hex.decode("c7277285aba7f7f04cc186cce37f17ca"),
code = 0x61
), // oneseg_310
TagInfo(
tag = 0x279D06F0.toInt(),
skey = Hex.decode("76409e08db9b3ba1478a968ef3f76292"),
code = 0x61
), // oneseg_300
TagInfo(
tag = 0x279D05F0.toInt(),
skey = Hex.decode("23dc3bb5a982d6ea63a36e2b2be9e154"),
code = 0x61
), // oneseg_280
TagInfo(
tag = 0xD66DF703.toInt(),
skey = Hex.decode("224357682f41ce654ca37cc6c4acf360"),
code = 0x61
), // oneseg_260_271
TagInfo(
tag = 0x279D10F0.toInt(),
skey = Hex.decode("12570d8a166d8706037dc88b62a332a9"),
code = 0x61
), // oneseg_slim
TagInfo(
tag = 0x3C2A08F0.toInt(),
skey = Hex.decode("1e2e3849dad41608272ef3bc37758093"),
code = 0x67
), // ms_app_main
TagInfo(
tag = 0xADF305F0.toInt(),
skey = Hex.decode("1299705e24076cd02d06fe7eb30c1126"),
code = 0x60
), // demokeys_280
TagInfo(
tag = 0xADF306F0.toInt(),
skey = Hex.decode("4705d5e3561e819b092f06db6b1292e0"),
code = 0x60
), // demokeys_3XX_1
TagInfo(
tag = 0xADF308F0.toInt(),
skey = Hex.decode("f662396e26224dca026416997b9ae7b8"),
code = 0x60
), // demokeys_3XX_2
TagInfo(
tag = 0x8004FD03.toInt(),
skey = Hex.decode("f4aef4e186ddd29c7cc542a695a08388"),
code = 0x5D,
type = 2
), // ebootbin_271_new
TagInfo(
tag = 0xD91605F0.toInt(),
skey = Hex.decode("b88c458bb6e76eb85159a6537c5e8631"),
code = 0x5D
), // ebootbin_280_new
TagInfo(
tag = 0xD91606F0.toInt(),
skey = Hex.decode("ed10e036c4fe83f375705ef6a44005f7"),
code = 0x5D
), // ebootbin_300_new
TagInfo(
tag = 0xD91608F0.toInt(),
skey = Hex.decode("5c770cbbb4c24fa27e3b4eb4b4c870af"),
code = 0x5D
), // ebootbin_310_new
TagInfo(
tag = 0x0A35EA03.toInt(),
skey = Hex.decode("f948380c9688a7744f65a054c276d9b8"),
code = 0x5E
), // gameshare_260_271
TagInfo(
tag = 0x7B0505F0.toInt(),
skey = Hex.decode("2d86773a56a44fdd3c167193aa8e1143"),
code = 0x5E
), // gameshare_280
TagInfo(
tag = 0x7B0506F0.toInt(),
skey = Hex.decode("781ad28724bda296183f893672909285"),
code = 0x5E
), // gameshare_300
TagInfo(
tag = 0x7B0508F0.toInt(),
skey = Hex.decode("c97d3e0a54816ec7137499746218e7dd"),
code = 0x5E
), // gameshare_310
TagInfo(
tag = 0x380210F0.toInt(),
skey = Hex.decode("322cfa75e47e93eb9f22808557089848"),
code = 0x5A
), // key_380210F0
TagInfo(
tag = 0x380280F0.toInt(),
skey = Hex.decode("970912d3db02bdd8e77451fef0ea6c5c"),
code = 0x5A
), // key_380280F0
TagInfo(
tag = 0x380283F0.toInt(),
skey = Hex.decode("34200c8ea1867984af13ae34776fea89"),
code = 0x5A
), // key_380283F0
TagInfo(
tag = 0x407810F0.toInt(),
skey = Hex.decode("afadcaf1955991ec1b27d04e8af33de7"),
code = 0x6A
), // key_407810F0
TagInfo(
tag = 0xE92410F0.toInt(),
skey = Hex.decode("36ef824e74fb175b141405f3b38a7618"),
code = 0x40
), // drmkeys_6XX_1
TagInfo(
tag = 0x692810F0.toInt(),
skey = Hex.decode("21525d76f6810f152f4a408963a01055"),
code = 0x40
), // drmkeys_6XX_2
TagInfo(
tag = 0x00000000.toInt(),
skey = Hex.decode("bef3217b1d5e9c29715e9c1c4546cb96e01b9b3c3dde85eb22207f4aaa6e20c265320bd5670577554008083cf2551d98f3f6d85fc5b08eee52814d94518627f8faba052733e52084e94a152732aa194840aaa35965cfb32c6d4674f20556653a8ff8b021268db1c55190c1644ec969d6f23570e809593a9d02714e6fce46a9dc1b881684a597b0bac625912472084cb3"),
code = 0x42,
type = 0x00
), // g_key0
TagInfo(
tag = 0x02000000.toInt(),
skey = Hex.decode("32a9fdcc766fc051cfcc6d041e82e1494c023b7d6558da9d25988cccb57de9d1cbd8746887c97134fcb3ed725d36c8813ae361e159db92fcecb10920e44ca9b16b69032fd836e287e98c2b3b84e70503830871f939db39b037ea3b8905684de7bd385c2a13c88db07523b3152545be4690fd0301a2870ea96aa6ab52807bbf8563cee845d316d74d2d0de3f556e43aaf"),
code = 0x45,
type = 0x00
), // g_key2
TagInfo(
tag = 0x03000000.toInt(),
skey = Hex.decode("caf5c8a680c0676d3a4d4f926aa07c049702640858a7d44f875a68bdc201279b352ab6833c536b720cfa22e5b4064bc2ac1c9d457b41c5a8a262ea4f42d71506098d623014ab4fc45e71ff697d83d8d28b0bedbeae576e1e02c4e861067a36be5e2b3f5458c03edb752085becc4d7e1e55ea6415b42578ecad8c53c07f2cf770d0c3e849c57ea9eda4b092f42ab05ee0"),
code = 0x46,
type = 0x00
), // g_key3
TagInfo(
tag = 0x4467415D.toInt(),
skey = Hex.decode("05e080ef9f68543acd9cc943be27771b3800b85c62fe2edd2cf969f3c5940f1619005629c5103cbf6655cef226c6a2ce6f8101b61e48e764bdde340cb09cf298d704c53ff039fbc8d8b32102a236f96300483a9ae332cc6efd0c128e231636b089e6e1aeeb0255741cc6a6e4b43ef2741358fad7eb1619b057843212d297bcd2d8256464a5808332b18ada43c92a124b"),
code = 0x59,
type = 0x59
), // g_key44
TagInfo(
tag = 0x207BBF2F.toInt(),
skey = Hex.decode("0008b533cd5f2ff31f88143c952a8a6ed5effe29e3ea941343d46bbd83c02108d379b3fa65e113e6d354a7f552298b10151e4b0abadeea61df6575550153463bc3ec54ae0933426119ffc970ece50a5b26f19d985f7a989d0e75bc5527ba6ec6e888e92dda0066f7cbdc8203f2f569556212438ed3e38f2887216f659c2ed137b49e532f8e9992a4f75839ed2365e939"),
code = 0x5A,
type = 0x5A
), // g_key20
TagInfo(
tag = 0x3ACE4DCE.toInt(),
skey = Hex.decode("697087671756bd3adcb13ac27d5057ab407f6a06b9f9de24e459f706b124f5dc5e3e79132d025903a2e1e7aafab2b9764003169aba2f8287bb8fe219028a339e9a7e00d8f17a31eade7106637cca670baf92518626353cea8e8c442b5492598bcbe90246da6ce14dbbd564e18ed8ec07f8e5ff99c1008876ed91b05334740484bcdb26b4bb48f9365821144692b49b74"),
code = 0x5B,
type = 0x5B
), // g_key3A
TagInfo(
tag = 0x07000000.toInt(),
skey = Hex.decode("af2f36f96a73820ead3594e9e9870c89bbe84f57ad3436db805d48fe5cb5e9e95b46b5ac"),
code = 0x4A,
type = 0x00
), // g_key_INDEXDAT1xx
TagInfo(
tag = 0x08000000.toInt(),
skey = Hex.decode("ef69cb1812898e15bb0ef9de23fbb04c18ee87366e4a8d8656c7b5191d5516ee6c2dcbe760c647973f1495ce77f45629de4a8203f19d0c2124eb29509fe6df81009bc839918b0cb0c2f92deffc933ae1a8a4948b9dd01d490d406a68e4c7d4cec9b7c89628dcaa1e840b17a4dc5d5d50cfc3a65d2dfa5d0eb519796ec7295ece94dbacaadd0cf7452537a7623d56e6cc"),
code = 0x4B,
type = 0x00
), // g_keyEBOOT1xx
TagInfo(
tag = 0xC0CB167C.toInt(),
skey = Hex.decode("fa368eda4774d95d7498c176af7ee597bd09ab1cc6ba35988192d303cf05b20334e7822863f614e775276eb9c7af8abd29ecd31d6ca1a4ec87ec695f921e988521aefc7c16dde9ba0478a9e6fc02ee2e3d8adf61640531dd49e197963b3f45c256841df9c86bda39f5fee5b3a393c589bc8a5cfb12720b6ccbd30de1a8b2d0984718d65f5723dcf06a160177683b5c0f"),
code = 0x5D,
type = 0x5D
), // g_keyEBOOT2xx
TagInfo(
tag = 0x0B000000.toInt(),
skey = Hex.decode("bf3c60a5412448d7cc6457f60b06901f453ea74e92d151e58a5db7e76e505a462210fb405033272c44da96808e19479977ee8d272e065d7445fa48c1af822583da86db5fcec415cb2fc62425b1c32e6c9ee39b36c41febf71ace511ef43605d7d8394dc313fb1874e14dc8e33cf018b14e8d01a20d77d8e690f320574163f9178fa6a46028dd2713644c9405124c2c0c"),
code = 0x4E,
type = 0x00
), // g_keyUPDATER
TagInfo(
tag = 0x0C000000.toInt(),
skey = Hex.decode("2f10bf1a71d096d5b252c56f1f53f2d4d9cd25f003af9aafcf57cfe0c49454255e67037084c87b90e44e2d000d7a680b4fa43a9e81da8ff58cac26ec9db4c93a37c071344d83f3b01144dc1031ea32a26bfae5e2034b5945871c3ae4d1d9da310370cd08df2f9cfa251d895a34195c9be566f322324a085fd51655699fbe452205d76d4fa1b8b8c400a613bc3bfcb777"),
code = 0x4F,
type = 0x00
), // g_keyDEMOS27X
TagInfo(
tag = 0x0F000000.toInt(),
skey = Hex.decode("bcfe81a3c9d5b9998d0a566c959f3030cc4626795e4eb682ad51391ac42e180ab43161c48a0cc577c6165f322e94d102c48aa30ac60a942a2647036733b12de50721efd2901ec885ba64d1c81dce8dc375a28b940346b80d373647e2dafc74cd663d8e5822e8286d8b541e896df53cf566dbbd0baa86b2c44bbceb2bf41f26fc05e7b8925269eedce542045e217feb8b"),
code = 0x52,
type = 0x00
), // g_keyMEIMG250
TagInfo(
tag = 0x862648D1.toInt(),
skey = Hex.decode("98d6bf1124b3f9d7274952dd865b21166dc34a5017b2435847daa0e5e7a173bb35db15293afd5c3705a970bbcaef2b279107962ebb9907eac8e65ab873f7cac941e60e259e4ae7065d894452a555674653af849a744102e11e03baeeceb980ed725f31bc7f062158583031e806e7d0d23e93d8e6b47fd1d7c49650503b0ba5fd3dae35468a9c48eb2d762d4231328b5a"),
code = 0x52,
type = 0x52
), // g_keyMEIMG260
TagInfo(
tag = 0x207BBF2F.toInt(),
skey = Hex.decode("0008b533cd5f2ff31f88143c952a8a6ed5effe29e3ea941343d46bbd83c02108d379b3fa65e113e6d354a7f552298b10151e4b0abadeea61df6575550153463bc3ec54ae0933426119ffc970ece50a5b26f19d985f7a989d0e75bc5527ba6ec6e888e92dda0066f7cbdc8203f2f569556212438ed3e38f2887216f659c2ed137b49e532f8e9992a4f75839ed2365e939"),
code = 0x5A,
type = 0x5A
), // g_keyUNK1
TagInfo(
tag = 0x09000000.toInt(),
skey = Hex.decode("e8531b72c6313efca2a25bf872acf03caba7ee54cbbf59596b83b854131343bccff29e98b236cef0f84cba9831c971e9c85d37a0a02fe50826d40dac01d6e457c7616ec58ab91aeff4f8d9d108a7e95f079df03e8c1a0cfa5cea1ea9c582f4580203802cc3f6e67ebbbb6affd0d01021887a29d3d31200987bc859dc9257dc7fa65d3fdb87b723fcd38e692212e880b6"),
code = 0x4C,
type = 0x00
), // g_key_GAMESHARE1xx
TagInfo(
tag = 0xBB67C59F.toInt(),
skey = Hex.decode("c757a7943398d39f718350f8290b8b32dab9bc2cc6b91829ba504c94d0e7dcf166390c64083d0bc9ba17adf44bf8a06c677c76f75aa5d3a46a5c084a7170b26bfb388bfab831db3ff296718b4aed9bdb845b6251b481144c08f584f67047b430748eaa93bc79c5908dc86e240212052e2e8474c797d985a1dd3a2b7a6d5b83fe4d188f50134f4cebd393190ed2df96ba"),
code = 0x5E,
type = 0x5E
) // g_key_GAMESHARE2xx
)
}
//@Suppress("ArrayInDataClass")
//data class Header(
// var magic: Int = 0,
// var modAttr: Int = 0,
// var compModAttr: Int = 0,
// var modVerLo: Int = 0,
// var modVerHi: Int = 0,
// var moduleName: String = "",
// var modVersion: Int = 0,
// var nsegments: Int = 0,
// var elfSize: Int = 0,
// var pspSize: Int = 0,
// var bootEntry: Int = 0,
// var modInfoOffset: Int = 0,
// var bssSize: Int = 0,
// var segAlign: CharArray = CharArray(4),
// var segAddress: IntArray = IntArray(4),
// var segSize: IntArray = IntArray(4),
// var reserved: IntArray = IntArray(5),
// var devkitVersion: Int = 0,
// var decMode: Int = 0,
// var pad: Int = 0,
// var overlapSize: Int = 0,
// var aesKey: ByteArray = ByteArray(16),
// var cmacKey: ByteArray = ByteArray(16),
// var cmacHeaderHash: ByteArray = ByteArray(16),
// var compressedSize: Int = 0,
// var compressedOffset: Int = 0,
// var unk1: Int = 0,
// var unk2: Int = 0,
// var cmacDataHash: ByteArray = ByteArray(16),
// var tag: Int = 0,
// var sigcheck: ByteArray = ByteArray(88),
// var sha1Hash: ByteArray = ByteArray(20),
// var keyData: ByteArray = ByteArray(16)
//) {
// companion object : Struct<Header>({ Header() },
// Header::magic AS INT32, // 0000
// Header::modAttr AS UINT16, // 0004
// Header::compModAttr AS UINT16, // 0006
// Header::modVerLo AS UINT8, // 0008
// Header::modVerHi AS UINT8, // 0009
// Header::moduleName AS STRINGZ(28), // 000A
// Header::modVersion AS UINT8, // 0026
// Header::nsegments AS UINT8, // 0027
// Header::elfSize AS INT32, // 0028
// Header::pspSize AS INT32, // 002C
// Header::bootEntry AS INT32, // 0030
// Header::modInfoOffset AS INT32, // 0034
// Header::bssSize AS INT32, // 0038
// Header::segAlign AS CHARARRAY(4), // 003C
// Header::segAddress AS INTARRAY(4), // 0044
// Header::segSize AS INTARRAY(4), // 0054
// Header::reserved AS INTARRAY(5), // 0064
// Header::devkitVersion AS INT32, // 0078
// Header::decMode AS UINT8, // 007C
// Header::pad AS UINT8, // 007D
// Header::overlapSize AS UINT16, // 007E
// Header::aesKey AS BYTEARRAY(16), // 0080
// Header::cmacKey AS BYTEARRAY(16), // 0090
// Header::cmacHeaderHash AS BYTEARRAY(16), // 00A0
// Header::compressedSize AS INT32, // 00B0
// Header::compressedOffset AS INT32, // 00B4
// Header::unk1 AS INT32, // 00B8
// Header::unk2 AS INT32, // 00BC
// Header::cmacDataHash AS BYTEARRAY(16), // 00D0
// Header::tag AS INT32, // 00E0
// Header::sigcheck AS BYTEARRAY(88), // 00E4
// Header::sha1Hash AS BYTEARRAY(20), // 013C
// Header::keyData AS BYTEARRAY(16) // 0150-0160
// )
//}
}
//fun main(args: Array<String>) = Korio {
// val ebootBin = LocalVfs("c:/temp/1/EBOOT.BIN").readAll()
// //val decrypted1 = CryptedElf.decrypt(ebootBin)
// val decrypted2 = CryptedElf.decrypt(ebootBin)
// //LocalVfs("c:/temp/1/EBOOT.BIN.decrypted.kpspemu1").writeBytes(decrypted1)
// LocalVfs("c:/temp/1/EBOOT.BIN.decrypted.kpspemu2").writeBytes(decrypted2)
//}
| mit | c3ac86940074322f3a6f3ab7af4cb679 | 39.539531 | 326 | 0.521378 | 2.968635 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/tv/account/TVHomeAccountCreationFragment.kt | 1 | 2969 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package cx.ring.tv.account
import android.os.Bundle
import androidx.leanback.widget.GuidanceStylist.Guidance
import androidx.leanback.widget.GuidedAction
import cx.ring.R
import cx.ring.account.AccountCreationModelImpl
import dagger.hilt.android.AndroidEntryPoint
import net.jami.account.HomeAccountCreationPresenter
import net.jami.account.HomeAccountCreationView
@AndroidEntryPoint
class TVHomeAccountCreationFragment : JamiGuidedStepFragment<HomeAccountCreationPresenter, HomeAccountCreationView>(),
HomeAccountCreationView {
override fun goToAccountCreation() {
add(parentFragmentManager, TVJamiAccountCreationFragment.newInstance(AccountCreationModelImpl().apply {
isLink = false
}))
}
override fun goToAccountLink() {
add(parentFragmentManager, TVJamiLinkAccountFragment.newInstance(AccountCreationModelImpl().apply {
isLink = true
}))
}
override fun goToAccountConnect() {
//TODO
}
override fun onProvideTheme(): Int {
return R.style.Theme_Ring_Leanback_GuidedStep_First
}
override fun onCreateGuidance(savedInstanceState: Bundle?): Guidance {
val title = getString(R.string.account_creation_home)
val breadcrumb = ""
val description = getString(R.string.help_ring)
val icon = requireContext().getDrawable(R.drawable.ic_jami)
return Guidance(title, description, breadcrumb, icon)
}
override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) {
val context = requireContext()
addAction(context, actions, LINK_ACCOUNT, getString(R.string.account_link_button), "", true)
addAction(context, actions, CREATE_ACCOUNT, getString(R.string.account_create_title), "", true)
}
override fun onGuidedActionClicked(action: GuidedAction) {
when (action.id) {
LINK_ACCOUNT -> presenter.clickOnLinkAccount()
CREATE_ACCOUNT -> presenter.clickOnCreateAccount()
else -> requireActivity().finish()
}
}
companion object {
private const val LINK_ACCOUNT = 0L
private const val CREATE_ACCOUNT = 1L
}
} | gpl-3.0 | 9ac37abc55a633bf554134a99856d303 | 37.076923 | 118 | 0.71674 | 4.646322 | false | false | false | false |
tikivn/android-template | viewHoldersDemo/src/main/java/vn/tale/viewholdersdemo/ViewHoldersDemoActivity.kt | 1 | 2558 | package vn.tale.viewholdersdemo
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.GridLayoutManager.SpanSizeLookup
import kotlinx.android.synthetic.main.activity_view_holders_demo.rvGrid
import viewholders.NoAdapterFactory
import vn.tale.viewholdersdemo.viewholder.ButtonModel
import vn.tale.viewholdersdemo.viewholder.ColorModel
import vn.tale.viewholdersdemo.viewholder.TextModel
import vn.tiki.noadapter2.OnlyAdapter
import java.util.ArrayList
import java.util.Collections
import java.util.Random
class ViewHoldersDemoActivity : AppCompatActivity() {
private lateinit var adapter: OnlyAdapter
private val items = ArrayList<Any>()
private val random = Random()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_view_holders_demo)
val gridLayoutManager = GridLayoutManager(this, 5, GridLayoutManager.VERTICAL, false)
gridLayoutManager.spanSizeLookup = object : SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return if (items[position] is ButtonModel) {
5
} else {
1
}
}
}
rvGrid.layoutManager = gridLayoutManager
rvGrid.setHasFixedSize(true)
adapter = NoAdapterFactory.builder()
.onItemClickListener { view, item, _ ->
if (item is ButtonModel) {
val id = view.id
when (id) {
R.id.btAdd -> {
val randomItem = randomItem(items.size)
items.add(randomItem)
updateList()
}
R.id.btRemove -> {
items.removeAt(items.lastIndex)
updateList()
}
R.id.btShuffle -> {
Collections.shuffle(items)
updateList()
}
}
}
}
.build()
rvGrid.adapter = adapter
// init with controller buttons
init()
}
private fun init() {
items.add(ButtonModel())
updateList()
}
private fun randomColor(): Int {
val r = random.nextInt(256)
val g = random.nextInt(256)
val b = random.nextInt(256)
return android.graphics.Color.rgb(r, g, b)
}
private fun randomItem(i: Int): Any {
return if (i % 3 == 0) {
TextModel("Text #" + i)
} else {
ColorModel(randomColor())
}
}
private fun updateList() {
adapter.setItems(ArrayList(items))
}
}
| apache-2.0 | 709567ee0b4d7aeb1a56b55a70b6dd95 | 26.212766 | 89 | 0.638389 | 4.335593 | false | false | false | false |
KotlinPorts/pooled-client | postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/PostgreSQLConnection.kt | 2 | 13442 | /*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares 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.github.mauricio.async.db.postgresql
import com.github.elizarov.async.async
import com.github.elizarov.async.suspendable
import com.github.mauricio.async.db.QueryResult
import com.github.mauricio.async.db.column.ColumnDecoderRegistry
import com.github.mauricio.async.db.column.ColumnEncoderRegistry
import com.github.mauricio.async.db.exceptions.ConnectionStillRunningQueryException
import com.github.mauricio.async.db.exceptions.InsufficientParametersException
import com.github.mauricio.async.db.general.MutableResultSet
import com.github.mauricio.async.db.postgresql.codec.PostgreSQLConnectionDelegate
import com.github.mauricio.async.db.postgresql.codec.PostgreSQLConnectionHandler
import com.github.mauricio.async.db.postgresql.column.PostgreSQLColumnDecoderRegistry
import com.github.mauricio.async.db.postgresql.column.PostgreSQLColumnEncoderRegistry
import com.github.mauricio.async.db.postgresql.exceptions.*
import com.github.mauricio.async.db.util.*
import com.github.mauricio.async.db.Configuration
import com.github.mauricio.async.db.Connection
import com.github.mauricio.async.db.pool.TimeoutScheduler
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicReference
import com.github.mauricio.async.db.postgresql.messages.backend.*
import com.github.mauricio.async.db.postgresql.messages.frontend.*
import io.netty.channel.EventLoopGroup
import java.util.concurrent.CopyOnWriteArrayList
import com.github.mauricio.async.db.postgresql.util.URLParser
import mu.KLogging
import java.time.Duration
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationDispatcher
import kotlin.coroutines.suspendCoroutine
class PostgreSQLConnection
(
val configuration: Configuration = URLParser.DEFAULT,
val encoderRegistry: ColumnEncoderRegistry = PostgreSQLColumnEncoderRegistry.Instance,
val decoderRegistry: ColumnDecoderRegistry = PostgreSQLColumnDecoderRegistry.Instance,
val group: EventLoopGroup = NettyUtils.DefaultEventLoopGroup,
val executionContext: ContinuationDispatcher = ExecutorServiceUtils.CachedExecutionContext
)
: PostgreSQLConnectionDelegate,
Connection, TimeoutScheduler {
companion object : KLogging() {
val Counter = AtomicLong()
val ServerVersionKey = "server_version"
}
private val connectionHandler = PostgreSQLConnectionHandler(
configuration,
encoderRegistry,
decoderRegistry,
this,
group,
executionContext
)
private val currentCount = Counter.incrementAndGet()
private val preparedStatementsCounter = AtomicInteger()
private val parameterStatus = mutableMapOf<String, String>()
private val parsedStatements = mutableMapOf<String, PreparedStatementHolder>()
private var authenticated = false
private var connectionFuture: Continuation<Connection>? = null
private var connectionFutureFlag = AtomicBoolean(false)
private var recentError = false
private val queryPromiseReference = AtomicReference<Continuation<QueryResult>?>(null)
private var currentQuery: MutableResultSet<PostgreSQLColumnData>? = null
private var currentPreparedStatement: PreparedStatementHolder? = null
private var version = Version(0, 0, 0)
private var notifyListeners = CopyOnWriteArrayList<(NotificationResponse) -> Unit>()
private var queryResult: QueryResult? = null
override fun eventLoopGroup() = group
override fun executionContext() = executionContext
override val isTimeoutedBool = AtomicBoolean(false)
fun isReadyForQuery(): Boolean = this.queryPromise() == null
override suspend fun connect() = suspendCoroutine<Connection> {
cont ->
connectionFuture = cont
async(executionContext) {
try {
this.connectionHandler.connect()
} catch (e: Throwable) {
connectionFutureFlag.set(true)
cont.resumeWithException(e)
}
}
}
override suspend fun disconnect() = suspendable(executionContext) {
connectionHandler.disconnect()
this
}
override fun onTimeout() {
async(executionContext) { disconnect() }
}
override val isConnected: Boolean get() = this.connectionHandler.isConnected()
fun parameterStatuses() = this.parameterStatus.toMap()
override suspend fun sendQuery(query: String): QueryResult {
validateQuery(query)
return addTimeout(configuration.queryTimeout) {
cont ->
setQueryPromise(cont)
write(QueryMessage(query))
}
}
override suspend fun sendPreparedStatement(query: String, values: List<Any?>): QueryResult {
validateQuery(query)
return addTimeout(configuration.queryTimeout) {
cont ->
setQueryPromise(cont)
val holder = this.parsedStatements.getOrPut(query) {
PreparedStatementHolder(query, preparedStatementsCounter.incrementAndGet())
}
if (holder.paramsCount != values.size) {
this.clearQueryPromise()
cont.resumeWithException(InsufficientParametersException(holder.paramsCount, values))
return@addTimeout
}
this.currentPreparedStatement = holder
this.currentQuery = MutableResultSet(holder.columnDatas)
write(
if (holder.prepared)
PreparedStatementExecuteMessage(holder.statementId, holder.realQuery, values, this.encoderRegistry)
else {
holder.prepared = true
PreparedStatementOpeningMessage(holder.statementId, holder.realQuery, values, this.encoderRegistry)
})
}
}
override fun onError(exception: Throwable) {
this.setErrorOnFutures(exception)
}
fun hasRecentError(): Boolean = this.recentError
fun setErrorOnFutures(e: Throwable) {
this.recentError = true
logger.error("Error on connection", e)
val cf = this.connectionFuture
if (cf != null && !connectionFutureFlag.get()) {
try {
connectionFutureFlag.set(true)
cf.resumeWithException(e)
} catch (e: Throwable) {
//nothing, already done
}
}
val cps = this.currentPreparedStatement
if (cps != null) {
parsedStatements.remove(cps.query)
}
failQueryPromise(e)
}
override fun onReadyForQuery() {
if (!connectionFutureFlag.get()) {
try {
connectionFutureFlag.set(true)
connectionFuture!!.resume(this)
} catch (e: Throwable) {
}
}
this.recentError = false
val qr = queryResult
if (qr != null) {
succeedQueryPromise(qr)
}
}
override fun onError(message: ErrorMessage) {
logger.error("Error with message -> {}", message)
val error = GenericDatabaseException(message)
error.fillInStackTrace()
this.setErrorOnFutures(error)
}
override fun onCommandComplete(message: CommandCompleteMessage) {
this.currentPreparedStatement = null
queryResult = QueryResult(message.rowsAffected.toLong(), message.statusMessage, this.currentQuery)
}
override fun onParameterStatus(message: ParameterStatusMessage) {
this.parameterStatus.put(message.key, message.value)
if (ServerVersionKey == message.key) {
this.version = Version(message.value)
}
}
override fun onDataRow(message: DataRowMessage) {
val items = Array<Any?>(message.values.size, {
index ->
val buf = message.values[index]
if (buf == null) {
null
} else {
try {
val columnType = currentQuery!!.columnTypes[index]
decoderRegistry.decode(columnType, buf, configuration.charset)
} finally {
buf.release()
}
}
})
currentQuery!!.addRow(items)
}
override fun onRowDescription(message: RowDescriptionMessage) {
val list = message.columnDatas.toList()
this.currentQuery = MutableResultSet(list)
this.setColumnDatas(list)
}
private fun setColumnDatas(columnDatas: List<PostgreSQLColumnData>) {
this.currentPreparedStatement.let {
if (it != null) {
it.columnDatas = columnDatas
}
}
}
override fun onAuthenticationResponse(message: AuthenticationMessage) {
when (message) {
is AuthenticationOkMessage -> {
logger.debug("Successfully logged in to database")
authenticated = true
}
is AuthenticationChallengeCleartextMessage -> {
write(this.credential(message))
}
is AuthenticationChallengeMD5 -> {
write(this.credential(message))
}
}
}
override fun onNotificationResponse(message: NotificationResponse) {
val iterator = this.notifyListeners.iterator()
while (iterator.hasNext()) {
iterator.next()(message)
}
}
fun registerNotifyListener(listener: (NotificationResponse) -> Unit) {
this.notifyListeners.add(listener)
}
fun unregisterNotifyListener(listener: (NotificationResponse) -> Unit) {
this.notifyListeners.remove(listener)
}
fun clearNotifyListeners() {
this.notifyListeners.clear()
}
private fun credential(authenticationMessage: AuthenticationChallengeMessage): CredentialMessage =
if (configuration.password != null) {
CredentialMessage(
configuration.username,
configuration.password!!,
authenticationMessage.challengeType,
authenticationMessage.salt
)
} else {
throw MissingCredentialInformationException(
this.configuration.username,
this.configuration.password,
authenticationMessage.challengeType)
}
private fun notReadyForQueryError(errorMessage: String, race: Boolean) {
logger.error(errorMessage)
throw ConnectionStillRunningQueryException(
this.currentCount,
race
)
}
fun validateIfItIsReadyForQuery(errorMessage: String) {
if (queryPromise() != null)
notReadyForQueryError(errorMessage, false)
}
private fun validateQuery(query: String) {
this.validateIfItIsReadyForQuery("Can't run query because there is one query pending already")
if (query.isEmpty()) {
throw QueryMustNotBeNullOrEmptyException(query)
}
}
private fun queryPromise(): Continuation<QueryResult>? = queryPromiseReference.get()
private fun setQueryPromise(promise: Continuation<QueryResult>) {
if (!this.queryPromiseReference.compareAndSet(null, promise))
notReadyForQueryError("Can't run query due to a race with another started query", true)
}
private fun clearQueryPromise() =
queryPromiseReference.getAndSet(null)
private fun failQueryPromise(t: Throwable) {
clearQueryPromise().let {
if (it != null) {
logger.error("Setting error on future $t")
it.resumeWithException(t)
}
}
}
private fun succeedQueryPromise(result: QueryResult) {
this.queryResult = null
this.currentQuery = null
clearQueryPromise()?.resume(result)
}
private fun write(message: ClientMessage) {
this.connectionHandler.write(message)
}
override fun toString(): String =
"${this.javaClass.getSimpleName()}{counter=${this.currentCount}}"
//1.1 errors
override suspend fun <A> inTransaction(dispatcher: ContinuationDispatcher?,
f: suspend (conn: Connection) -> A) = super.inTransaction(dispatcher, f)
override suspend fun <T> addTimeout(duration: Duration?, block: (Continuation<T>) -> Unit)
= super.addTimeout(duration, block)
override suspend fun <T> addTimeout(durationMillis: Long?, block: (Continuation<T>) -> Unit)
= super.addTimeout(durationMillis, block)
}
| apache-2.0 | 78623d92350f800bc61f2187e35afc28 | 34.555556 | 123 | 0.656994 | 5.069785 | false | false | false | false |
ColaGom/KtGitCloner | src/main/kotlin/ml/Clustering.kt | 1 | 1103 | package ml
open class Clustering(val k:Int)
{
lateinit var name:String
init {
name = this.javaClass.simpleName
}
var startTime = 0L
val clusters:MutableList<Cluster> = mutableListOf()
open fun clustering(nodeList:List<Node>)
{
startTime = System.currentTimeMillis()
log("start clustering size : ${nodeList.size} k : $k")
}
fun log(msg:String)
{
println("[$name] $msg ${System.currentTimeMillis() - startTime}")
}
fun getSSE() : Double
{
var sse = 0.0
clusters.forEach {
val mean = it.getCentroid().mean(it.getNodes())
if(!mean.isNaN())
sse += Math.pow(mean,2.0)
}
return sse
}
fun getSSE(clusters : List<Cluster>) : Double
{
var sse = 0.0
clusters.forEach {
val mean = it.getCentroid().mean(it.getNodes())
if(!mean.isNaN())
sse += Math.pow(mean,2.0)
}
return sse
}
fun printAnalysis()
{
log("clustering sse : ${getSSE()}")
}
}
| apache-2.0 | ccdb630c6459b9704213a0dd4d6c1058 | 19.054545 | 73 | 0.524025 | 3.883803 | false | false | false | false |
AlmasB/FXGL | fxgl-io/src/main/kotlin/com/almasb/fxgl/net/Writers.kt | 1 | 3899 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.net
import com.almasb.fxgl.core.serialization.Bundle
import com.almasb.fxgl.logging.Logger
import java.io.*
/**
*
* @author Almas Baimagambetov ([email protected])
*/
interface TCPMessageWriter<T> {
@Throws(Exception::class)
fun write(message: T)
}
// we need a factory for tcp message writers since each output stream is valid for a single connection
// therefore we cannot reuse the same message writer for each connection
interface TCPWriterFactory<T> {
fun create(out: OutputStream): TCPMessageWriter<T>
}
interface UDPMessageWriter<T> {
fun write(data: T): ByteArray
}
object Writers {
private val log = Logger.get(javaClass)
private val tcpWriters = hashMapOf<Class<*>, TCPWriterFactory<*>>()
private val udpWriters = hashMapOf<Class<*>, UDPMessageWriter<*>>()
init {
// these are built-in writers
addTCPWriter(Bundle::class.java, object : TCPWriterFactory<Bundle> {
override fun create(out: OutputStream): TCPMessageWriter<Bundle> = BundleTCPMessageWriter(out)
})
addTCPWriter(ByteArray::class.java, object : TCPWriterFactory<ByteArray> {
override fun create(out: OutputStream): TCPMessageWriter<ByteArray> = ByteArrayTCPMessageWriter(out)
})
addTCPWriter(String::class.java, object : TCPWriterFactory<String> {
override fun create(out: OutputStream): TCPMessageWriter<String> = StringTCPMessageWriter(out)
})
addUDPWriter(Bundle::class.java, BundleUDPMessageWriter())
}
fun <T> addTCPWriter(type: Class<T>, factory: TCPWriterFactory<T>) {
tcpWriters[type] = factory
}
fun <T> addUDPWriter(type: Class<T>, writer: UDPMessageWriter<T>) {
udpWriters[type] = writer
}
@Suppress("UNCHECKED_CAST")
fun <T> getTCPWriter(type: Class<T>, out: OutputStream): TCPMessageWriter<T> {
log.debug("Getting TCPMessageWriter for $type")
val writerFactory = tcpWriters[type]
?: throw RuntimeException("No TCP message writer factory for type: $type")
val writer = writerFactory.create(out) as TCPMessageWriter<T>
log.debug("Constructed TCPMessageWriter for $type: " + writer.javaClass.simpleName)
return writer
}
@Suppress("UNCHECKED_CAST")
fun <T> getUDPWriter(type: Class<T>): UDPMessageWriter<T> {
log.debug("Getting UDPMessageWriter for $type")
val writer = udpWriters[type] as? UDPMessageWriter<T>
?: throw RuntimeException("No UDP message writer for type: $type")
log.debug("Constructed UDPMessageWriter for $type: " + writer.javaClass.simpleName)
return writer
}
}
class BundleTCPMessageWriter(out: OutputStream) : TCPMessageWriter<Bundle> {
private val out = ObjectOutputStream(out)
override fun write(message: Bundle) {
out.writeObject(message)
}
}
class ByteArrayTCPMessageWriter(out: OutputStream) : TCPMessageWriter<ByteArray> {
private val out = DataOutputStream(out)
override fun write(message: ByteArray) {
out.writeInt(message.size)
out.write(message)
}
}
class StringTCPMessageWriter(out: OutputStream) : TCPMessageWriter<String> {
private val writer = ByteArrayTCPMessageWriter(out)
override fun write(message: String) {
writer.write(message.toByteArray(Charsets.UTF_16))
}
}
class BundleUDPMessageWriter : UDPMessageWriter<Bundle> {
override fun write(data: Bundle): ByteArray {
return toByteArray(data)
}
private fun toByteArray(data: Serializable): ByteArray {
val baos = ByteArrayOutputStream()
ObjectOutputStream(baos).use { it.writeObject(data) }
return baos.toByteArray()
}
} | mit | dff13b0827205dc32c3808e38fed04c0 | 28.770992 | 112 | 0.686073 | 4.095588 | false | false | false | false |
AlmasB/FXGL | fxgl-samples/src/main/kotlin/sandbox/anim/ScaleAndRotateSample.kt | 1 | 3568 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.anim
import com.almasb.fxgl.animation.Interpolators
import com.almasb.fxgl.app.GameApplication
import com.almasb.fxgl.app.GameSettings
import com.almasb.fxgl.dsl.FXGL.Companion.addUINode
import com.almasb.fxgl.dsl.FXGL.Companion.animationBuilder
import com.almasb.fxgl.dsl.FXGL.Companion.getGameScene
import com.almasb.fxgl.dsl.FXGL.Companion.onKeyDown
import com.almasb.fxgl.dsl.getUIFactoryService
import javafx.beans.binding.Bindings
import javafx.geometry.Point2D
import javafx.scene.input.KeyCode
import javafx.scene.paint.Color
import javafx.scene.shape.Rectangle
import javafx.util.Duration
import java.util.HashMap
class ScaleAndRotateSample : GameApplication() {
private val animations = HashMap<Int, Runnable>()
private var animationSelector = 0
override fun initSettings(settings: GameSettings) {
settings.width = 800
settings.height = 600
settings.title = "Rotation and scale sample"
}
override fun initInput() {
onKeyDown(KeyCode.F, Runnable {
animations[animationSelector++]?.run()
animationSelector %= animations.size
})
}
override fun initGame() {
getGameScene().setBackgroundColor(Color.BLACK)
val rect = Rectangle(400.0, 100.0, Color.WHITE)
addUINode(rect, 200.0, 250.0)
animations[0] = Runnable {
animationBuilder()
.duration(Duration.seconds(2.0))
.interpolator(Interpolators.LINEAR.EASE_IN_OUT())
.repeat(2)
.autoReverse(true)
.rotate(rect)
.origin(Point2D(0.0, 0.0))
.from(0.0)
.to(360.0)
.buildAndPlay()
}
animations[1] = Runnable {
animationBuilder()
.duration(Duration.seconds(2.0))
.interpolator(Interpolators.LINEAR.EASE_IN_OUT())
.repeat(2)
.autoReverse(true)
.scale(rect)
.origin(Point2D(0.0, 0.0))
.from(Point2D(1.0, 1.0))
.to(Point2D(2.0,2.0))
.buildAndPlay()
}
animations[2] = Runnable {
animationBuilder()
.duration(Duration.seconds(2.0))
.interpolator(Interpolators.LINEAR.EASE_IN_OUT())
.repeat(2)
.autoReverse(true)
.rotate(rect)
.from(0.0)
.to(360.0)
.buildAndPlay()
}
animations[3] = Runnable {
animationBuilder()
.duration(Duration.seconds(2.0))
.interpolator(Interpolators.LINEAR.EASE_IN_OUT())
.repeat(2)
.autoReverse(true)
.scale(rect)
.from(Point2D(1.0, 1.0))
.to(Point2D(2.0,2.0))
.buildAndPlay()
}
val text = getUIFactoryService().newText("")
text.textProperty().bind(Bindings.size(rect.transforms).asString("Num transforms: %d"))
addUINode(text, 20.0, 20.0)
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
launch(ScaleAndRotateSample::class.java, args)
}
}
} | mit | ad393e3c74742b4422b68149f6d4eba0 | 30.584071 | 95 | 0.551289 | 4.177986 | false | false | false | false |
carmenlau/chat-SDK-Android | chat_example/src/main/java/io/skygear/chatexample/ConversationsActivity.kt | 1 | 8443 | package io.skygear.chatexample
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import io.skygear.plugins.chat.*
import io.skygear.plugins.chat.ui.ConversationActivity
import io.skygear.skygear.Container
import io.skygear.skygear.Error
import io.skygear.skygear.LambdaResponseHandler
import io.skygear.skygear.LogoutResponseHandler
import org.json.JSONObject
import java.util.*
class ConversationsActivity : AppCompatActivity() {
private val LOG_TAG: String? = "ConversationsActivity"
private val mSkygear: Container
private val mChatContainer: ChatContainer
private val mAdapter: ConversationsAdapter = ConversationsAdapter()
private var mConversationsRv: RecyclerView? = null
init {
mSkygear = Container.defaultContainer(this)
mChatContainer = ChatContainer.getInstance(mSkygear)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_conversations)
mConversationsRv = findViewById<RecyclerView>(R.id.conversations_rv)
mConversationsRv?.adapter = mAdapter
mConversationsRv?.layoutManager = LinearLayoutManager(this)
mAdapter.setOnClickListener {
c -> showOptions(c)
}
}
override fun onResume() {
super.onResume()
getAllConversations()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.conversation, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId) {
R.id.log_out_menu -> {
confirmLogOut()
return true
}
R.id.add_conversation_menu -> {
startActivity(Intent(this, CreateConversationActivity::class.java))
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
fun getAllConversations() {
mChatContainer.getConversations(object : GetCallback<List<Conversation>> {
override fun onSucc(list: List<Conversation>?) {
mAdapter.setConversations(list)
}
override fun onFail(error: Error) {
}
})
}
fun confirmLogOut() {
AlertDialog.Builder(this)
.setTitle(R.string.confirm)
.setMessage(R.string.are_your_sure_to_log_out)
.setPositiveButton(R.string.yes) { dialog, which -> logOut() }
.setNegativeButton(R.string.no, null).show()
}
fun logOut() {
val loading = ProgressDialog(this)
loading.setTitle(R.string.loading)
loading.setMessage(getString(R.string.logging_out))
loading.show()
mSkygear.auth.logout(object : LogoutResponseHandler() {
override fun onLogoutSuccess() {
loading.dismiss()
logoutSuccess()
}
override fun onLogoutFail(error: Error) {
loading.dismiss()
logoutFail()
}
})
}
fun logoutSuccess() {
startActivity(Intent(this, MainActivity::class.java))
finish()
}
fun logoutFail() {
AlertDialog.Builder(this).setTitle(R.string.logout_failed).show()
}
fun showOptions(c: Conversation) {
val builder = AlertDialog.Builder(this)
val items = resources.getStringArray(R.array.conversation_options)
builder.setItems(items, { d, i -> when(i) {
0 -> enter(c)
1 -> viewMeta(c)
2 -> edit(c)
3 -> confirmLeave(c)
4 -> confirmDelete(c)
5 -> updateAdmins(c)
6 -> updateParticipants(c)
} })
val alert = builder.create()
alert.show()
}
fun enter(c: Conversation) {
val i = Intent(this, ConversationActivity::class.java)
i.putExtra(ConversationActivity.ConversationIntentKey, c.toJson().toString())
startActivity(i)
}
fun viewMeta(c: Conversation) {
val f = MetaFragment.newInstance(c)
f.show(supportFragmentManager, "conversation_meta")
}
fun edit(c: Conversation) {
val f = TitleFragment.newInstance(c.title)
f.setOnOkBtnClickedListener { t -> updateTitle(c, t) }
f.show(supportFragmentManager, "update_conversation")
}
fun updateTitle(c: Conversation, t: String) {
mChatContainer.setConversationTitle(c, t, object : SaveCallback<Conversation> {
override fun onSucc(new: Conversation?) {
mAdapter.updateConversation(c, new)
}
override fun onFail(error: Error) {
}
})
}
fun confirmLeave(c: Conversation) {
AlertDialog.Builder(this)
.setTitle(R.string.confirm)
.setMessage(R.string.are_your_sure_to_leave_conversation)
.setPositiveButton(R.string.yes) { dialog, which -> leave(c) }
.setNegativeButton(R.string.no, null).show()
}
fun leave(c: Conversation) {
val failAlert = AlertDialog.Builder(this)
.setTitle("Oops")
.setNeutralButton(R.string.dismiss, null)
.create()
mChatContainer.leaveConversation(c, object : LambdaResponseHandler() {
override fun onLambdaFail(error: Error?) {
val alertMessage = "Fail to leave the conversation: ${error?.message}"
Log.w(LOG_TAG, alertMessage)
failAlert.setMessage(alertMessage)
failAlert.show()
}
override fun onLambdaSuccess(result: JSONObject?) {
Log.i(LOG_TAG, "Successfully leave the conversation")
getAllConversations()
}
} )
}
fun confirmDelete(c: Conversation) {
AlertDialog.Builder(this)
.setTitle(R.string.confirm)
.setMessage(R.string.are_your_sure_to_delete_conversation)
.setPositiveButton(R.string.yes) { dialog, which -> delete(c) }
.setNegativeButton(R.string.no, null).show()
}
fun delete(c: Conversation) {
val failAlert = AlertDialog.Builder(this)
.setTitle("Oops")
.setNeutralButton(R.string.dismiss, null)
.create()
mChatContainer.deleteConversation(c, object : DeleteCallback<Boolean> {
override fun onFail(error: Error) {
val alertMessage = "Fail to delete the conversation: " + error.message
Log.w(LOG_TAG, alertMessage)
failAlert.setMessage(alertMessage)
failAlert.show()
}
override fun onSucc(result: Boolean?) {
Log.i(LOG_TAG, "Successfully delete the conversation")
getAllConversations()
}
} )
}
fun updateAdmins(c: Conversation) {
val f = UserIdsFragment.newInstance(getString(R.string.add_remove_admins), c.adminIds)
f.setOnOkBtnClickedListener { ids ->
mChatContainer.addConversationAdmins(c, ids, object : SaveCallback<Conversation> {
override fun onSucc(new: Conversation?) {
mAdapter.updateConversation(c, new)
}
override fun onFail(error: Error) {
}
})
}
f.show(supportFragmentManager, "update_admins")
}
fun updateParticipants(c: Conversation) {
val f = UserIdsFragment.newInstance(getString(R.string.add_remove_participants), c.participantIds)
f.setOnOkBtnClickedListener { ids ->
mChatContainer.addConversationParticipants(c, ids, object : SaveCallback<Conversation> {
override fun onSucc(new: Conversation?) {
mAdapter.updateConversation(c, new)
}
override fun onFail(error: Error) {
}
})
}
f.show(supportFragmentManager, "update_participants")
}
}
| apache-2.0 | 7ee502b769bbfd65fd04292e7fa993f8 | 32.109804 | 106 | 0.602274 | 4.613661 | false | false | false | false |
ujpv/intellij-rust | toml/src/main/kotlin/org/toml/lang/TomlFileType.kt | 2 | 614 | package org.toml.lang
import com.intellij.icons.AllIcons
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
object TomlFileType : LanguageFileType(TomlLanguage) {
object DEFAULTS {
val EXTENSION = "toml"
val DESCRIPTION = "TOML file"
}
override fun getName() = DEFAULTS.DESCRIPTION
override fun getDescription() = DEFAULTS.DESCRIPTION
override fun getDefaultExtension() = DEFAULTS.EXTENSION
override fun getIcon() = AllIcons.FileTypes.Text!!
override fun getCharset(file: VirtualFile, content: ByteArray) = "UTF-8"
}
| mit | bd55cc46f122b16040bdaea293bbd591 | 29.7 | 76 | 0.742671 | 4.616541 | false | false | false | false |
LorittaBot/Loritta | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/entities/PuddingUserProfile.kt | 1 | 2231 | package net.perfectdreams.loritta.cinnamon.pudding.entities
import kotlinx.datetime.Instant
import net.perfectdreams.loritta.common.achievements.AchievementType
import net.perfectdreams.loritta.cinnamon.pudding.Pudding
import net.perfectdreams.loritta.cinnamon.pudding.data.UserProfile
import net.perfectdreams.loritta.cinnamon.pudding.tables.Profiles
import org.jetbrains.exposed.sql.update
class PuddingUserProfile(
private val pudding: Pudding,
val data: UserProfile
) {
companion object;
val id by data::id
val profileSettingsId by data::profileSettingsId
val money by data::money
val isAfk by data::isAfk
val afkReason by data::afkReason
/**
* Gives an achievement to this user
*
* @param type the achievement type
* @return if true, the achievement was successfully given, if false, the user already has the achievement
*/
suspend fun giveAchievement(type: AchievementType, achievedAt: Instant): Boolean = pudding.users.giveAchievement(
id,
type,
achievedAt
)
suspend fun getRankPositionInSonhosRanking() = pudding.sonhos.getSonhosRankPositionBySonhos(money)
suspend fun enableAfk(reason: String? = null) {
if (!isAfk || this.afkReason != reason) {
pudding.transaction {
Profiles.update({ Profiles.id eq [email protected]() }) {
it[isAfk] = true
it[afkReason] = reason
}
}
}
}
suspend fun disableAfk() {
if (isAfk || this.afkReason != null) {
pudding.transaction {
Profiles.update({ Profiles.id eq [email protected]() }) {
it[isAfk] = false
it[afkReason] = null
}
}
}
}
// Should ALWAYS not be null
suspend fun getProfileSettings() = pudding.users.getProfileSettings(profileSettingsId)!!
/**
* Get the user's current banned state, if it exists and if it is valid
*
* @return the user banned state or null if it doesn't exist
*/
suspend fun getBannedState() = pudding.users.getUserBannedState(id)
} | agpl-3.0 | 8583fce501b6eba81714a8301dd2a8d0 | 31.823529 | 117 | 0.650381 | 4.409091 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/commands/CinnamonApplicationCommandDeclarationWrappers.kt | 1 | 1903 | package net.perfectdreams.loritta.cinnamon.discord.interactions.commands
import net.perfectdreams.discordinteraktions.common.commands.MessageCommandExecutor
import net.perfectdreams.discordinteraktions.common.commands.UserCommandExecutor
import net.perfectdreams.i18nhelper.core.keydata.StringI18nData
import net.perfectdreams.loritta.common.locale.LanguageManager
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.common.commands.CommandCategory
interface CinnamonApplicationCommandDeclarationWrapper
abstract class CinnamonSlashCommandDeclarationWrapper(val languageManager: LanguageManager) : CinnamonApplicationCommandDeclarationWrapper {
abstract fun declaration(): CinnamonSlashCommandDeclarationBuilder
fun slashCommand(label: StringI18nData, category: CommandCategory, description: StringI18nData, block: CinnamonSlashCommandDeclarationBuilder.() -> (Unit))
= slashCommand(this, languageManager, label, description, category, block)
}
abstract class CinnamonUserCommandDeclarationWrapper(val languageManager: LanguageManager) : CinnamonApplicationCommandDeclarationWrapper {
abstract fun declaration(): CinnamonUserCommandDeclarationBuilder
fun userCommand(name: StringI18nData, executor: (LorittaBot) -> (UserCommandExecutor), block: CinnamonUserCommandDeclarationBuilder.() -> (Unit) = {})
= userCommand(this, languageManager, name, executor, block)
}
abstract class CinnamonMessageCommandDeclarationWrapper(val languageManager: LanguageManager) : CinnamonApplicationCommandDeclarationWrapper {
abstract fun declaration(): CinnamonMessageCommandDeclarationBuilder
fun messageCommand(name: StringI18nData, executor: (LorittaBot) -> (MessageCommandExecutor), block: CinnamonMessageCommandDeclarationBuilder.() -> (Unit) = {})
= messageCommand(this, languageManager, name, executor, block)
} | agpl-3.0 | f05ff437f3356c7f3bf48e12f5e62b03 | 60.419355 | 163 | 0.829743 | 5.597059 | false | false | false | false |
googlecodelabs/odml-pathways | product-search/codelab2/android/starter/app/src/main/java/com/google/codelabs/productimagesearch/ImageClickableView.kt | 8 | 6793 | /**
* 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
*
* 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.codelabs.productimagesearch
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatImageView
import com.google.mlkit.vision.objects.DetectedObject
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.pow
/**
* Customize ImageView which can be clickable on some Detection Result Bound.
*/
class ImageClickableView : AppCompatImageView {
companion object {
private const val TAG = "ImageClickableView"
private const val CLICKABLE_RADIUS = 40f
private const val SHADOW_RADIUS = 10f
}
private val dotPaint = createDotPaint()
private var onObjectClickListener: ((cropBitmap: Bitmap) -> Unit)? = null
// This variable is used to hold the actual size of bounding box detection result due to
// the ratio might changed after Bitmap fill into ImageView
private var transformedResults = listOf<TransformedDetectionResult>()
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
/**
* Callback when user click to detection result rectangle.
*/
fun setOnObjectClickListener(listener: ((objectImage: Bitmap) -> Unit)) {
this.onObjectClickListener = listener
}
/**
* Draw white circle at the center of each detected object on the image
*/
fun drawDetectionResults(results: List<DetectedObject>) {
(drawable as? BitmapDrawable)?.bitmap?.let { srcImage ->
// Get scale size based width/height
val scaleFactor =
max(srcImage.width / width.toFloat(), srcImage.height / height.toFloat())
// Calculate the total padding (based center inside scale type)
val diffWidth = abs(width - srcImage.width / scaleFactor) / 2
val diffHeight = abs(height - srcImage.height / scaleFactor) / 2
// Transform the original Bounding Box to actual bounding box based the display size of ImageView.
transformedResults = results.map { result ->
// Calculate to create new coordinates of Rectangle Box match on ImageView.
val actualRectBoundingBox = RectF(
(result.boundingBox.left / scaleFactor) + diffWidth,
(result.boundingBox.top / scaleFactor) + diffHeight,
(result.boundingBox.right / scaleFactor) + diffWidth,
(result.boundingBox.bottom / scaleFactor) + diffHeight
)
val dotCenter = PointF(
(actualRectBoundingBox.right + actualRectBoundingBox.left) / 2,
(actualRectBoundingBox.bottom + actualRectBoundingBox.top) / 2,
)
// Transform to new object to hold the data inside.
// This object is necessary to avoid performance
TransformedDetectionResult(actualRectBoundingBox, result.boundingBox, dotCenter)
}
Log.d(
TAG,
"srcImage: ${srcImage.width}/${srcImage.height} - imageView: ${width}/${height} => scaleFactor: $scaleFactor"
)
// Invalid to re-draw the canvas
// Method onDraw will be called with new data.
invalidate()
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
// Getting detection results and draw the dot view onto detected object.
transformedResults.forEach { result ->
// Draw Dot View
canvas.drawCircle(result.dotCenter.x, result.dotCenter.y, CLICKABLE_RADIUS, dotPaint)
}
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
val touchX = event.x
val touchY = event.y
val index =
transformedResults.indexOfFirst {
val dx = (touchX - it.dotCenter.x).toDouble().pow(2.0)
val dy = (touchY - it.dotCenter.y).toDouble().pow(2.0)
(dx + dy) < CLICKABLE_RADIUS.toDouble().pow(2.0)
}
// If a matching object found, call the objectClickListener
if (index != -1) {
cropBitMapBasedResult(transformedResults[index])?.let {
onObjectClickListener?.invoke(it)
}
}
}
}
return super.onTouchEvent(event)
}
/**
* This function will be used to crop the segment of Bitmap based touching by user.
*/
private fun cropBitMapBasedResult(result: TransformedDetectionResult): Bitmap? {
// Crop image from Original Bitmap with Original Rect Bounding Box
(drawable as? BitmapDrawable)?.bitmap?.let {
return Bitmap.createBitmap(
it,
result.originalBoxRectF.left,
result.originalBoxRectF.top,
result.originalBoxRectF.width(),
result.originalBoxRectF.height()
)
}
return null
}
/**
* Return Dot Paint to draw circle
*/
private fun createDotPaint() = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.WHITE
style = Paint.Style.FILL
setShadowLayer(SHADOW_RADIUS, 0F, 0F, Color.BLACK)
// Force to use software to render by disable hardware acceleration.
// Important: the shadow will not work without this line.
setLayerType(LAYER_TYPE_SOFTWARE, this)
}
}
/**
* This class holds the transformed data
* @property: actualBoxRectF: The bounding box after calculated
* @property: originalBoxRectF: The original bounding box (Before transformed), use for crop bitmap.
*/
data class TransformedDetectionResult(
val actualBoxRectF: RectF,
val originalBoxRectF: Rect,
val dotCenter: PointF
)
| apache-2.0 | 921b507758b6a29d04098d9ad7c12139 | 38.725146 | 125 | 0.634329 | 4.845221 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/appointment/gcal/sync/view.kt | 1 | 6827 | package at.cpickl.gadsu.appointment.gcal.sync
import at.cpickl.gadsu.appointment.Appointment
import at.cpickl.gadsu.appointment.gcal.GCalEvent
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.service.LOG
import at.cpickl.gadsu.view.MainFrame
import at.cpickl.gadsu.view.components.MyEnableValue
import at.cpickl.gadsu.view.components.MyFrame
import at.cpickl.gadsu.view.components.MyTableModel
import at.cpickl.gadsu.view.components.TableColumn
import at.cpickl.gadsu.view.components.inputs.HtmlEditorPane
import at.cpickl.gadsu.view.components.panels.GridPanel
import at.cpickl.gadsu.view.swing.ClosableWindow
import at.cpickl.gadsu.view.swing.addCloseListener
import at.cpickl.gadsu.view.swing.registerCloseOnEscapeOrShortcutW
import at.cpickl.gadsu.view.swing.scrolled
import com.google.common.eventbus.EventBus
import org.joda.time.DateTime
import java.awt.BorderLayout
import java.awt.GridBagConstraints
import javax.inject.Inject
import javax.swing.BorderFactory
import javax.swing.JButton
import javax.swing.JPanel
interface SyncReportWindow : ClosableWindow {
fun start()
fun destroy()
fun initReport(report: SyncReport, clients: List<Client>, gmailConfigured: Boolean)
fun readImportAppointments(): List<ImportAppointment>
fun readDeleteAppointments(): List<Appointment>
fun readUpdateAppointments(): List<Appointment>
}
data class ImportAppointment(
val event: GCalEvent,
var enabled: Boolean,
var sendConfirmation: Boolean,
var selectedClient: Client,
val allClients: List<Client>, // order is specific to this appointment
val isGmailGloballyConfigured: Boolean // kind of a hack
) {
companion object
fun toAppointment(created: DateTime): Appointment {
return Appointment(
id = null, // gadsu appointment.ID is not known yet
clientId = this.selectedClient.id!!,
created = created,
start = this.event.start,
end = this.event.end,
note = this.event.description,
gcalId = this.event.id,
gcalUrl = this.event.url
)
}
}
class SyncReportSwingWindow @Inject constructor(
mainFrame: MainFrame,
bus: EventBus
)
: MyFrame("Sync Bericht"), SyncReportWindow {
private val log = LOG(javaClass)
companion object {
private val COL_LIL = 30
}
private var deleteAppointments = emptyList<Appointment>()
private var updateAppointments = emptyList<Appointment>()
// keep in sync with SyncTable.COL indices!!!
private val model = MyTableModel<ImportAppointment>(listOf(
TableColumn("", { it.enabled }, COL_LIL, COL_LIL, COL_LIL),
TableColumn("Titel", { it.event.summary }, 100, 100),
TableColumn("Klient", { it.selectedClient.preferredName }, 150, 120),
TableColumn("Zeit", { Pair(it.event.start, it.event.end) }, 130, 130, 130),
TableColumn("", { MyEnableValue(
enabled = it.selectedClient.hasMailAndWantsMail && it.isGmailGloballyConfigured,
selected = it.sendConfirmation && it.isGmailGloballyConfigured
) }, COL_LIL, COL_LIL, COL_LIL),
TableColumn("Mail", { it.selectedClient.contact.mail }, 150, 150)
))
private val table = SyncTable(model)
private val btnImport = JButton("Synchronisieren").apply {
addActionListener {
table.cellEditor?.stopCellEditing() // as we are communicating via editor stop events, rather the component's own change event
bus.post(RequestImportSyncEvent())
}
}
private val topText = HtmlEditorPane()
init {
addCloseListener { closeWindow() }
registerCloseOnEscapeOrShortcutW()
contentPane.add(GridPanel().apply {
border = BorderFactory.createEmptyBorder(10, 15, 10, 15)
c.weightx = 1.0
c.weighty = 0.0
c.fill = GridBagConstraints.HORIZONTAL
add(topText)
c.gridy++
c.weighty = 1.0
c.fill = GridBagConstraints.BOTH
add(table.scrolled())
c.gridy++
c.weighty = 0.0
c.fill = GridBagConstraints.NONE
add(JPanel(BorderLayout()).apply {
add(btnImport, BorderLayout.WEST)
add(JButton("Abbrechen").apply { addActionListener { closeWindow() } }, BorderLayout.EAST)
})
})
pack()
setLocationRelativeTo(mainFrame.asJFrame())
rootPane.defaultButton = btnImport
}
override fun readImportAppointments(): List<ImportAppointment> = model.getData()
override fun readDeleteAppointments(): List<Appointment> = deleteAppointments
override fun readUpdateAppointments(): List<Appointment> = updateAppointments
// MINOR @VIEW - outsource logic from proper starting, see PreferencesWindow
override fun start() {
isVisible = true
}
override fun initReport(
report: SyncReport,
clients: List<Client>,
gmailConfigured: Boolean
) {
log.debug("initReport(report={}, clients={}, gmailConfigured={})", report, clients, gmailConfigured)
val defaultSelected = clients.first()
model.resetData(report.importEvents.map { (gcalEvent, suggestedClients) ->
val selectedClient = suggestedClients.firstOrNull() ?: defaultSelected
ImportAppointment(
event = gcalEvent,
enabled = true,
sendConfirmation = selectedClient.hasMailAndWantsMail,
selectedClient = selectedClient,
allClients = clientsOrdered(suggestedClients, clients),
isGmailGloballyConfigured = gmailConfigured)
})
deleteAppointments = report.deleteAppointments
// copy values from GCalEvent to local Appointment
updateAppointments = report.updateAppointments.map {
it.value.copy(
start = it.key.start,
end = it.key.end,
note = it.key.description
)
}
val isSingular = model.size == 1
topText.text = "Folgende${if (isSingular) "r" else ""} ${model.size} Termin${if (isSingular) " kann" else "e können"} importiert werden " +
"(${deleteAppointments.size} zum Löschen, ${updateAppointments.size} zum Updaten):"
}
private fun clientsOrdered(topClients: List<Client>, allClients: List<Client>) =
topClients.union(allClients.minus(topClients)).toList()
override fun closeWindow() {
isVisible = false
}
override fun destroy() {
isVisible = false
dispose()
}
}
| apache-2.0 | c392d7df668dac4bcbffdcdbfa01028b | 35.111111 | 147 | 0.647473 | 4.440468 | false | false | false | false |
asathe/jsonlin | src/test/kotlin/org/sathe/json/JsonTypeTest.kt | 1 | 6598 | package org.sathe.json
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
import java.math.BigDecimal
import java.math.BigInteger
import java.time.LocalDate
import kotlin.test.assertEquals
import kotlin.test.assertFails
import kotlin.test.assertFailsWith
class JsonTypeTest {
@Test
fun canAddEntriesToAJsonObject() {
val obj = obj()
obj
.add("field1", value("value1"))
.add("field2", value("value2"))
assertEquals("""{ "field1" : "value1", "field2" : "value2" }""",
obj.toJson(OneLiner()))
}
@Test
fun canAddEntriesToAJsonArray() {
val arr = array()
arr
.add(value("value1"))
.add(value("value2"))
assertEquals("""[ "value1", "value2" ]""",
arr.toJson(OneLiner()))
}
@Test
fun canBuildAJsonObject() {
val obj = obj()
.add("anInt", 123)
.add("aString", "aValue")
.add("aDecimal", BigDecimal("12.34"))
.add("aBigInt", BigInteger("12345"))
.add("aBool", true)
.add("aList", array(value("123")))
assertThat(obj.integer("anInt"), equalTo(123))
assertThat(obj.string("aString"), equalTo("aValue"))
assertThat(obj.decimal("aDecimal"), equalTo(BigDecimal("12.34")))
assertThat(obj.integer("aBigInt"), equalTo(12345))
assertThat(obj.boolean("aBool"), equalTo(true))
assertThat(obj.list("aList")[0], equalTo(value("123") as JsonType))
}
@Test
fun canExtractSimpleValuesFromAnObject() {
val obj = obj(
"aList" to array("item1", "item2"),
"aString" to "aValue",
"aDecimal" to BigDecimal("12.34"),
"aNull" to null,
"anInt" to 123,
"aBool" to true)
assertThat(obj.string("aString"), equalTo("aValue"))
assertThat(obj.decimal("aDecimal"), equalTo("12.34".toBigDecimal()))
assertThat(obj.integer("anInt"), equalTo(123))
assertThat(obj.boolean("aBool"), equalTo(true))
assertEquals("12.34", obj.string("aDecimal"))
assertEquals("123", obj.string("anInt"))
assertEquals("true", obj.string("aBool"))
assertEquals(JsonNull(), obj.child("aNull"))
assertEquals(BigDecimal("123"), obj.decimal("anInt"))
assertThat(assertFailsWith<JsonException> { obj.string("missing") }.message,
equalTo("No entry for 'missing'"))
assertThat(assertFailsWith<JsonException> { obj.integer("aDecimal") }.message,
equalTo("Expecting an integer but got 12.34 (BigDecimal)"))
assertThat(assertFailsWith<JsonException> { obj.boolean("aDecimal") }.message,
equalTo("Expecting a boolean but got 12.34 (BigDecimal)"))
assertThat(assertFailsWith<ClassCastException> { obj.boolean("aList") }.message,
containsString("class org.sathe.json.JsonArray cannot be cast to class org.sathe.json.JsonValue"))
}
@Test
fun reportsIncorrectTypes() {
val badType = JsonValue(LocalDate.now())
assertThat(assertFails { badType.decimal() }.message,
containsString("Expecting a decimal but got 2020-08-24 (LocalDate)"))
}
@Test
fun wrapsSimpleTypesAsJsonValues() {
val obj = obj()
assertEquals(obj, obj.add("keyString", "value"))
assertEquals(obj, obj.add("keyInt", 123))
assertEquals(obj, obj.add("keyDecimal", BigDecimal("12.34")))
assertEquals(obj, obj.add("keyBigInt", BigInteger("1234")))
assertEquals(obj, obj.add("keyBool", true))
obj.add("keyInt", 124)
assertEquals(value(124), obj.child("keyInt"))
}
@Test
fun canGetListsFromObjects() {
val obj = obj()
obj.add("keyInt", array("moo", "cow"))
assertEquals(array("moo", "cow"), obj.list("keyInt"))
}
@Test
fun canFindAnElementInATree() {
val json = obj("moo" to obj("cow" to value("woo!")))
assertEquals(json.find("moo.cow"), value("woo!"))
}
@Test
fun canFindAnElementInATreeInAList() {
val json = obj("moo" to obj("cow" to array(value("woo!"))))
assertEquals(json.find("moo.cow[0]"), value("woo!"))
}
@Test
fun canFindAnElementWithPathLikeKey() {
val json = obj("moo.cow[1]/bah" to "sheep")
assertEquals(value("sheep"), json.find("moo.cow[1]/bah"))
assertThat(assertFailsWith<JsonException> { json.find("moo.cow[1]") }.message, containsString("Unable to find moo.cow[1]"))
assertThat(assertFailsWith<JsonException> { json.find("moo") }.message, containsString("Unable to find moo"))
}
@Test
fun canFindDeeplyNestedItems() {
val json = obj("moo" to array(obj("cow1" to array(1, 2)), obj("cow2" to array(3, 4))))
assertEquals(obj("cow1" to array(1, 2)), json.find("moo[0]"))
assertEquals(array(1, 2), json.find("moo[0].cow1"))
assertEquals(value(4), json.find("moo[1].cow2[1]"))
}
@Test
fun blowsUpIfNotFoundOnAnObject() {
val json = obj("moo" to array(obj("cow1" to array(1, 2)), obj("cow2" to array(3, 4))))
assertThat(assertFailsWith<JsonException> { json.find("moo[1].cow3[1]") }.message, containsString("Unable to find cow3"))
}
@Test
fun blowsUpIfNotFoundOnAList() {
val json = obj("moo" to array(obj("cow1" to array(1, 2)), obj("cow2" to array(3, 4))))
assertThat(assertFailsWith<JsonException> { json.find("moo[1].cow2[3]") }.message, containsString("Index 3 not found"))
}
@Test
fun returnsTheValueOnAnEmptyPath() {
val json = value("moo")
assertEquals(value("moo"), json.find(""))
}
@Test
fun returnsNulls() {
val json = obj("moo" to null)
assertEquals(JsonNull(), json.find("moo"))
}
@Test
fun canFindPathsInStreamsButConsumesEntriesUpToRequestedIndex() {
val stream = JsonParser("[{\"moo\": \"cow\"}, {\"bah\": \"sheep\"}]").parseAsSequence()
assertEquals(value("cow"), stream.find("[0].moo"))
assertEquals(value("sheep"), stream.find("[0].bah"))
}
@Test
fun blowsUpIfWeHaveAPathOnALeaf() {
val json = value("moo")
assertEquals("Path \"cow\" goes beyond a leaf - found \"moo\"",
assertFailsWith<JsonException> { json.find("cow") }.message)
}
} | apache-2.0 | 95c90755bc2034b47944ae4a2f40ce77 | 33.015464 | 131 | 0.593362 | 3.993947 | false | true | false | false |
Yalantis/Context-Menu.Android | lib/src/main/java/com/yalantis/contextmenu/lib/MenuObject.kt | 1 | 4063 | package com.yalantis.contextmenu.lib
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Parcel
import android.os.Parcelable
import android.widget.ImageView
open class MenuObject(var title: String = "") : Parcelable {
var bgDrawable: Drawable? = null
var bgColor: Int = 0
private set
var bgResource: Int = 0
private set
var drawable: Drawable? = null
var color: Int = 0
private set
var bitmap: Bitmap? = null
private set
var resource: Int = 0
private set
var scaleType: ImageView.ScaleType = ImageView.ScaleType.CENTER_INSIDE
var textColor: Int = 0
var dividerColor: Int = Integer.MAX_VALUE
var menuTextAppearanceStyle: Int = 0
private constructor(parcel: Parcel) : this(parcel.readString() ?: "") {
val bitmapBgDrawable = parcel.readParcelable<Bitmap>(Bitmap::class.java.classLoader)
bgDrawable = if (bitmapBgDrawable == null) {
ColorDrawable(parcel.readInt())
} else {
// TODO create BitmapDrawable with resources
BitmapDrawable(bitmapBgDrawable)
}
bgColor = parcel.readInt()
bgResource = parcel.readInt()
val bitmapDrawable = parcel.readParcelable<Bitmap>(Bitmap::class.java.classLoader)
// TODO create BitmapDrawable with resources
bitmapDrawable?.let { drawable = BitmapDrawable(it) }
color = parcel.readInt()
bitmap = parcel.readParcelable(Bitmap::class.java.classLoader)
resource = parcel.readInt()
scaleType = ImageView.ScaleType.values()[parcel.readInt()]
textColor = parcel.readInt()
dividerColor = parcel.readInt()
menuTextAppearanceStyle = parcel.readInt()
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.apply {
writeString(title)
when (bgDrawable) {
null -> writeParcelable(null, flags)
is BitmapDrawable -> writeParcelable((bgDrawable as BitmapDrawable).bitmap, flags)
is ColorDrawable -> writeInt((bgDrawable as ColorDrawable).color)
}
writeInt(bgColor)
writeInt(bgResource)
when (drawable) {
null -> writeParcelable(null, flags)
is BitmapDrawable -> writeParcelable((drawable as BitmapDrawable).bitmap, flags)
}
writeInt(color)
writeParcelable(bitmap, flags)
writeInt(resource)
writeInt(scaleType.ordinal)
writeInt(textColor)
writeInt(dividerColor)
writeInt(menuTextAppearanceStyle)
}
}
override fun describeContents(): Int = 0
fun setBgDrawable(drawable: ColorDrawable) {
setBgDrawableInternal(drawable)
}
fun setBgDrawable(drawable: BitmapDrawable) {
setBgDrawableInternal(drawable)
}
fun setBgColorValue(value: Int) {
bgColor = value
bgDrawable = null
bgResource = 0
}
fun setBgResourceValue(value: Int) {
bgResource = value
bgDrawable = null
bgColor = 0
}
fun setColorValue(value: Int) {
color = value
drawable = null
bitmap = null
resource = 0
}
fun setBitmapValue(value: Bitmap) {
bitmap = value
drawable = null
color = 0
resource = 0
}
fun setResourceValue(value: Int) {
resource = value
drawable = null
color = 0
bitmap = null
}
private fun setBgDrawableInternal(drawable: Drawable) {
bgDrawable = drawable
bgColor = 0
bgResource = 0
}
companion object CREATOR : Parcelable.Creator<MenuObject> {
override fun createFromParcel(parcel: Parcel): MenuObject = MenuObject(parcel)
override fun newArray(size: Int): Array<MenuObject?> = arrayOfNulls(size)
}
} | apache-2.0 | c187c2d885d02342d4f0955c9e90cede | 27.222222 | 98 | 0.624908 | 4.954878 | false | false | false | false |
googlemaps/codelab-places-101-android-kotlin | solution/app/src/main/java/com/google/codelabs/maps/placesdemo/DetailsActivity.kt | 1 | 2893 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.codelabs.maps.placesdemo
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.google.android.libraries.places.api.Places
import com.google.android.libraries.places.api.model.Place
import com.google.android.libraries.places.api.net.FetchPlaceResponse
import com.google.android.libraries.places.api.net.PlacesClient
import com.google.android.libraries.places.ktx.api.net.awaitFetchPlace
import com.google.android.material.textfield.TextInputEditText
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
@ExperimentalCoroutinesApi
class DetailsActivity : AppCompatActivity() {
private lateinit var placesClient: PlacesClient
private lateinit var detailsButton: Button
private lateinit var detailsInput: TextInputEditText
private lateinit var responseView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
// Set up view objects
detailsInput = findViewById(R.id.details_input)
detailsButton = findViewById(R.id.details_button)
responseView = findViewById(R.id.details_response_content)
// Retrieve a PlacesClient (previously initialized - see DemoApplication)
placesClient = Places.createClient(this)
// Upon button click, fetch and display the Place Details
detailsButton.setOnClickListener {
val placeId = detailsInput.text.toString()
val placeFields = listOf(
Place.Field.NAME,
Place.Field.ID,
Place.Field.LAT_LNG,
Place.Field.ADDRESS
)
lifecycleScope.launch {
try {
val response = placesClient.awaitFetchPlace(placeId, placeFields)
responseView.text = response.prettyPrint()
} catch (e: Exception) {
e.printStackTrace()
responseView.text = e.message
}
}
}
}
}
fun FetchPlaceResponse.prettyPrint(): String {
return StringUtil.stringify(this, false)
} | apache-2.0 | 5acfff73eef4435e00c5143d0e7a23eb | 37.078947 | 85 | 0.70515 | 4.719413 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/util/flatfilenamemapper.kt | 1 | 1418 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.util.FlatFileNameMapper
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IFlatFileNameMapperNested {
fun flattenmapper(
from: String? = null,
to: String? = null)
{
_addFlatFileNameMapper(FlatFileNameMapper().apply {
_init(from, to)
})
}
fun _addFlatFileNameMapper(value: FlatFileNameMapper)
}
fun IFileNameMapperNested.flattenmapper(
from: String? = null,
to: String? = null)
{
_addFileNameMapper(FlatFileNameMapper().apply {
_init(from, to)
})
}
fun FlatFileNameMapper._init(
from: String?,
to: String?)
{
if (from != null)
setFrom(from)
if (to != null)
setTo(to)
}
| apache-2.0 | ff52f3256082f46fec700229908400a9 | 24.781818 | 79 | 0.641749 | 3.801609 | false | false | false | false |
luoyuan800/NeverEnd | dataModel/src/cn/luo/yuan/maze/model/skill/elementalist/ElementBomb.kt | 1 | 2839 | package cn.luo.yuan.maze.model.skill.elementalist
import cn.luo.yuan.maze.model.Data
import cn.luo.yuan.maze.model.HarmAble
import cn.luo.yuan.maze.model.skill.AtkSkill
import cn.luo.yuan.maze.model.skill.SkillAbleObject
import cn.luo.yuan.maze.model.skill.SkillParameter
import cn.luo.yuan.maze.model.skill.UpgradeAble
import cn.luo.yuan.maze.model.skill.result.DoNoThingResult
import cn.luo.yuan.maze.model.skill.result.HarmResult
import cn.luo.yuan.maze.model.skill.result.SkillResult
import cn.luo.yuan.maze.utils.Field
import cn.luo.yuan.maze.utils.StringUtils
/**
* Copyright @Luo
* Created by Gavin Luo on 7/21/2017.
*/
class ElementBomb :AtkSkill(),UpgradeAble {
init {
rate = 2.5f
}
fun setLevel(level: Long) {
this.level = level
}
companion object {
private const val serialVersionUID = Field.SERVER_VERSION
}
private val model = ElementModel(this)
private var level = 1L
override fun getName(): String {
return "元素星爆 X $level"
}
override fun getDisplayName(): String {
val builder = StringBuilder()
builder.append("用你的优雅,亮瞎敌人的双眼。当敌人的属性被你克制时,秒杀敌人!<br>")
builder.append(StringUtils.formatPercentage(rate)).append("概率释放<br>")
builder.append("已经使用:${StringUtils.formatNumber(useTime)}次")
return builder.toString()
}
override fun canMount(parameter: SkillParameter?): Boolean {
return model.canMount(parameter)
}
override fun invoke(parameter: SkillParameter): SkillResult {
val hrs = HarmResult()
val monster:HarmAble = parameter[SkillParameter.TARGET]
val hero : SkillAbleObject = parameter.owner
if(hero is HarmAble){
if(hero.element.restriction(monster.element)){
hrs.harm = monster.currentHp
hrs.addMessage("$name 生效!")
}else{
val rs = DoNoThingResult()
rs.messages.add("$name 无效")
return rs
}
}
return hrs
}
override fun enable(parameter: SkillParameter?) {
isEnable = true
}
override fun getSkillName(): String {
return model.skillName
}
override fun upgrade(parameter: SkillParameter?): Boolean {
if(rate + 1 < Data.RATE_MAX/5){
rate += 1
level ++
return true
}
return false
}
override fun getLevel(): Long {
return level
}
override fun canUpgrade(parameter: SkillParameter?): Boolean {
return rate + 1 < Data.RATE_MAX/5 && model.canUpgrade(parameter)
}
override fun canEnable(parameter: SkillParameter?): Boolean {
return model.canEnable(parameter)
}
} | bsd-3-clause | b299044e5d12d2193e327d96b3f7107d | 28.462366 | 77 | 0.640745 | 3.857746 | false | false | false | false |
FurhatRobotics/example-skills | Quiz/src/main/kotlin/furhatos/app/quiz/questions/questions.kt | 1 | 2223 | package furhatos.app.quiz.questions
import furhatos.app.quiz.AnswerOption
import furhatos.nlu.EnumItem
import furhatos.nlu.TextBuilder
import java.util.*
object QuestionSet {
var count : Int = 0
var current: Question = questionsEnglish[Random().nextInt(questionsEnglish.lastIndex)]
init {
questionsEnglish.shuffle()
}
fun next() {
count++
if (count >= questionsEnglish.size)
count = 0
current = questionsEnglish[count]
AnswerOption().forget()
}
}
/**
* The question class gets the following parameters:
* @text : The question as a String
* @answer : A list containing the correct answer to the question, followed by alternative pronunciations of the correct answer
* @alternatives A list, containing lists of other (wrong) answers. Every other answer is also followed by alternative pronunciations of the correct answer.
*/
class Question(val text: String, answer: List<String>, alternatives: List<List<String>>) {
//All options, used to prime the NLU
var options : MutableList<EnumItem> = mutableListOf()
//Only the first option of the answers, these are correctly spelled, and not alternative.
var primeoptions : MutableList<EnumItem> = mutableListOf()
//init loads the first item of the list into primeoptions
//And loads everything into options
init {
primeoptions.add(EnumItem(AnswerOption(true, answer.first()), answer.first()))
answer.forEach {
options.add(EnumItem(AnswerOption(true, it), it))
}
alternatives.forEach {
primeoptions.add(EnumItem(AnswerOption(false, it.first()), it.first()))
it.forEach {
options.add(EnumItem(AnswerOption(false, it), it))
}
}
options.shuffle()
primeoptions.shuffle()
}
//Returns the well formatted answer options
fun getOptionsString() : String {
var text = TextBuilder()
text.appendList(primeoptions.map { it.wordString }, "or")
return text.toString()
}
//Returns the well formatted answer options
val speechPhrases : List<String>
get() = primeoptions.map { it.wordString ?: "" }
}
| mit | c4fa992cad5100a03f0c254a7d8660ea | 30.757143 | 156 | 0.664417 | 4.472837 | false | false | false | false |
nisrulz/android-examples | WebViewDialogueBox/app/src/main/java/github/nisrulz/example/webviewdialoguebox/MainActivity.kt | 1 | 1431 | package github.nisrulz.example.webviewdialoguebox
import android.app.Dialog
import android.os.Bundle
import android.webkit.WebView
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import github.nisrulz.example.webviewdialoguebox.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
with(binding) {
setContentView(root)
fab.setOnClickListener {
setupDialog()
}
}
}
private fun setupDialog() = Dialog(this).apply {
setContentView(R.layout.dialogue_custom)
val txt = findViewById<TextView>(R.id.textView)
txt.text = "Text in TextView"
val webView = findViewById<WebView>(R.id.webView)
val htmlData = """<html>
<body style='background:black;color:white;padding:2em;'>
I am the WebView inside the Custom Dialog
</body>
</html>"""
webView.loadData(htmlData, "text/html", "utf-8")
val btnOk = findViewById<Button>(R.id.btnDialogOk)
btnOk.setOnClickListener { dismiss() }
show()
}
} | apache-2.0 | 5ea11d2fad7b6fb13a88716f5d20d1c4 | 34.8 | 82 | 0.643606 | 4.867347 | false | false | false | false |
failcoDave/kotlections | src/test/kotlin/net/failco/kotlections/ExtensionTests.kt | 1 | 2115 | /*
* Copyright 2016 David Hull
*
* 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.failco.kotlections
import org.junit.Assert
import org.junit.Test
import java.util.*
import java.util.concurrent.ConcurrentHashMap
class ExtensionTests {
@Test
fun MutableMap_uniquePut() = sharedUniquePutTests("non-concurrent", HashMap<String, String>())
@Test // doesn't test concurrency; impl doesn't affect atomicity, this just makes sure the code path is hit
fun ConcurrentMap_uniquePut() = sharedUniquePutTests("concurrent", ConcurrentHashMap<String, String>())
@Test
fun mapToIntArray() {
val input: Collection<Int> = listOf(2, 8 , -101, 500, 2)
//because this particular list just so happens to be Collection<Int> we can use this convenience method
val expected = input.toIntArray();
val actual = input.mapToIntArray { it }
Assert.assertArrayEquals("arrays not equal", expected, actual);
}
private fun sharedUniquePutTests(msg: String, map: MutableMap<String, String>) {
val dupedKey = "dupedKey"
val origValue = "origValue"
map.uniquePut(dupedKey, origValue)
// didn't throw an exception... so far so good
map.uniquePut("someOtherKey", "whocares")
// try non-unique key, expect exception
try {
map.uniquePut(dupedKey, "someOtherValue")
Assert.fail("$msg -- uniquePut didn't throw an exception will duplicate key")
} catch(e: Exception) {}
Assert.assertEquals("original value was replaced", origValue, map[dupedKey])
}
} | apache-2.0 | fe9447a5ecd851955299feeb7538fc58 | 35.482759 | 111 | 0.69409 | 4.204771 | false | true | false | false |
Ph1b/MaterialAudiobookPlayer | common/src/main/kotlin/de/ph1b/audiobook/common/conductor/DialogController.kt | 1 | 2506 | package de.ph1b.audiobook.common.conductor
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction
import com.bluelinelabs.conductor.changehandler.SimpleSwapChangeHandler
private const val SI_DIALOG = "android:savedDialogState"
/**
* A wrapper that wraps a dialog in a controller
*/
abstract class DialogController(args: Bundle = Bundle()) : Controller(args), LifecycleOwner {
@Suppress("LeakingThis")
private val lifecycleOwner = ControllerLifecycleOwner(this)
override fun getLifecycle(): Lifecycle = lifecycleOwner.lifecycle
val lifecycleScope by LifecycleScopeProperty(lifecycle)
private var dialog: Dialog? = null
private var dismissed = false
final override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
dialog = onCreateDialog(savedViewState).apply {
setOwnerActivity(activity!!)
setOnDismissListener { dismissDialog() }
if (savedViewState != null) {
val dialogState = savedViewState.getBundle(SI_DIALOG)
if (dialogState != null) {
onRestoreInstanceState(dialogState)
}
}
}
// stub view
return View(activity)
}
@CallSuper
override fun onSaveViewState(view: View, outState: Bundle) {
super.onSaveViewState(view, outState)
val dialogState = dialog!!.onSaveInstanceState()
outState.putBundle(SI_DIALOG, dialogState)
}
@CallSuper
override fun onAttach(view: View) {
super.onAttach(view)
dialog!!.show()
}
@CallSuper
override fun onDetach(view: View) {
super.onDetach(view)
dialog!!.hide()
}
@CallSuper
override fun onDestroyView(view: View) {
super.onDestroyView(view)
dialog!!.setOnDismissListener(null)
dialog!!.dismiss()
dialog = null
}
fun showDialog(router: Router) {
dismissed = false
router.pushController(
RouterTransaction.with(this)
.pushChangeHandler(SimpleSwapChangeHandler(false))
)
}
fun dismissDialog() {
if (dismissed) {
return
}
router.popController(this)
dismissed = true
}
protected abstract fun onCreateDialog(savedViewState: Bundle?): Dialog
}
| lgpl-3.0 | 352d333e369d2fc9b5a5f4ceac2a3829 | 25.104167 | 93 | 0.727853 | 4.791587 | false | false | false | false |
googlemaps/android-samples | ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/CircleDemoActivity.kt | 1 | 12607 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.kotlindemos
import android.graphics.Color
import android.graphics.Point
import android.location.Location
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.SeekBar
import android.widget.Spinner
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.Circle
import com.google.android.gms.maps.model.CircleOptions
import com.google.android.gms.maps.model.Dash
import com.google.android.gms.maps.model.Dot
import com.google.android.gms.maps.model.Gap
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PatternItem
import java.util.ArrayList
import java.util.Arrays
/**
* This shows how to draw circles on a map.
*/
class CircleDemoActivity :
AppCompatActivity(),
SeekBar.OnSeekBarChangeListener,
AdapterView.OnItemSelectedListener,
OnMapReadyCallback {
private val DEFAULT_RADIUS_METERS = 1000000.0
private val MAX_WIDTH_PX = 50
private val MAX_HUE_DEGREE = 360
private val MAX_ALPHA = 255
private val PATTERN_DASH_LENGTH = 100
private val PATTERN_GAP_LENGTH = 200
private val sydney = LatLng(-33.87365, 151.20689)
private val dot = Dot()
private val dash = Dash(PATTERN_DASH_LENGTH.toFloat())
private val gap = Gap(PATTERN_GAP_LENGTH.toFloat())
private val patternDotted = Arrays.asList(dot, gap)
private val patternDashed = Arrays.asList(dash, gap)
private val patternMixed = Arrays.asList(dot, gap, dot, dash, gap)
// These are the options for stroke patterns
private val patterns: List<Pair<Int, List<PatternItem>?>> = listOf(
Pair(R.string.pattern_solid, null),
Pair(R.string.pattern_dashed, patternDashed),
Pair(R.string.pattern_dotted, patternDotted),
Pair(R.string.pattern_mixed, patternMixed)
)
private lateinit var map: GoogleMap
private val circles = ArrayList<DraggableCircle>(1)
private var fillColorArgb : Int = 0
private var strokeColorArgb: Int = 0
private lateinit var fillHueBar: SeekBar
private lateinit var fillAlphaBar: SeekBar
private lateinit var strokeWidthBar: SeekBar
private lateinit var strokeHueBar: SeekBar
private lateinit var strokeAlphaBar: SeekBar
private lateinit var strokePatternSpinner: Spinner
private lateinit var clickabilityCheckbox: CheckBox
/**
* This class contains information about a circle, including its markers
*/
private inner class DraggableCircle(center: LatLng, private var radiusMeters: Double) {
private val centerMarker: Marker? = map.addMarker(MarkerOptions().apply {
position(center)
draggable(true)
})
private val radiusMarker: Marker? = map.addMarker(
MarkerOptions().apply {
position(center.getPointAtDistance(radiusMeters))
icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
draggable(true)
})
private val circle: Circle = map.addCircle(
CircleOptions().apply {
center(center)
radius(radiusMeters)
strokeWidth(strokeWidthBar.progress.toFloat())
strokeColor(strokeColorArgb)
fillColor(fillColorArgb)
clickable(clickabilityCheckbox.isChecked)
strokePattern(getSelectedPattern(strokePatternSpinner.selectedItemPosition))
})
fun onMarkerMoved(marker: Marker): Boolean {
when (marker) {
centerMarker -> {
circle.center = marker.position
radiusMarker?.position = marker.position.getPointAtDistance(radiusMeters)
}
radiusMarker -> {
radiusMeters = centerMarker?.position?.distanceFrom(radiusMarker.position)!!
circle.radius = radiusMeters
}
else -> return false
}
return true
}
fun onStyleChange() {
// [circle] is treated as implicit this inside the with block
with(circle) {
strokeWidth = strokeWidthBar.progress.toFloat()
strokeColor = strokeColorArgb
fillColor = fillColorArgb
}
}
fun setStrokePattern(pattern: List<PatternItem>?) {
circle.strokePattern = pattern
}
fun setClickable(clickable: Boolean) {
circle.isClickable = clickable
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_circle_demo)
// Set all the SeekBars
fillHueBar = findViewById<SeekBar>(R.id.fillHueSeekBar).apply {
max = MAX_HUE_DEGREE
progress = MAX_HUE_DEGREE / 2
}
fillAlphaBar = findViewById<SeekBar>(R.id.fillAlphaSeekBar).apply {
max = MAX_ALPHA
progress = MAX_ALPHA / 2
}
strokeWidthBar = findViewById<SeekBar>(R.id.strokeWidthSeekBar).apply {
max = MAX_WIDTH_PX
progress = MAX_WIDTH_PX / 3
}
strokeHueBar = findViewById<SeekBar>(R.id.strokeHueSeekBar).apply {
max = MAX_HUE_DEGREE
progress = 0
}
strokeAlphaBar = findViewById<SeekBar>(R.id.strokeAlphaSeekBar).apply {
max = MAX_ALPHA
progress = MAX_ALPHA
}
strokePatternSpinner = findViewById<Spinner>(R.id.strokePatternSpinner).apply {
adapter = ArrayAdapter(this@CircleDemoActivity,
android.R.layout.simple_spinner_item,
getResourceStrings())
}
clickabilityCheckbox = findViewById(R.id.toggleClickability)
clickabilityCheckbox.setOnClickListener {
toggleClickability(it)
}
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
}
/** Get all the strings of patterns and return them as Array. */
private fun getResourceStrings() = (patterns).map { getString(it.first) }.toTypedArray()
/**
* When the map is ready, move the camera to put the Circle in the middle of the screen,
* create a circle in Sydney, and set the listeners for the map, circles, and SeekBars.
*/
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
// we need to initialise map before creating a circle
with(map) {
moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 4.0f))
setContentDescription(getString(R.string.circle_demo_details))
setOnMapLongClickListener { point ->
// We know the center, let's place the outline at a point 3/4 along the view.
val view: View = supportFragmentManager.findFragmentById(R.id.map)?.view
?: return@setOnMapLongClickListener
val radiusLatLng = map.projection.fromScreenLocation(
Point(view.height * 3 / 4, view.width * 3 / 4))
// Create the circle.
val newCircle = DraggableCircle(point, point.distanceFrom(radiusLatLng))
circles.add(newCircle)
}
setOnMarkerDragListener(object : GoogleMap.OnMarkerDragListener {
override fun onMarkerDragStart(marker: Marker) {
onMarkerMoved(marker)
}
override fun onMarkerDragEnd(marker: Marker) {
onMarkerMoved(marker)
}
override fun onMarkerDrag(marker: Marker) {
onMarkerMoved(marker)
}
})
// Flip the red, green and blue components of the circle's stroke color.
setOnCircleClickListener { c -> c.strokeColor = c.strokeColor xor 0x00ffffff }
}
fillColorArgb = Color.HSVToColor(fillAlphaBar.progress,
floatArrayOf(fillHueBar.progress.toFloat(), 1f, 1f))
strokeColorArgb = Color.HSVToColor(strokeAlphaBar.progress,
floatArrayOf(strokeHueBar.progress.toFloat(), 1f, 1f))
val circle = DraggableCircle(sydney, DEFAULT_RADIUS_METERS)
circles.add(circle)
// Set listeners for all the SeekBar
fillHueBar.setOnSeekBarChangeListener(this)
fillAlphaBar.setOnSeekBarChangeListener(this)
strokeWidthBar.setOnSeekBarChangeListener(this)
strokeHueBar.setOnSeekBarChangeListener(this)
strokeAlphaBar.setOnSeekBarChangeListener(this)
strokePatternSpinner.onItemSelectedListener = this
}
private fun getSelectedPattern(pos: Int): List<PatternItem>? = patterns[pos].second
override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {
if (parent.id == R.id.strokePatternSpinner) {
circles.map { it.setStrokePattern(getSelectedPattern(pos)) }
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
// Don't do anything here.
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
// Don't do anything here.
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
// Don't do anything here.
}
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
// Update the fillColorArgb if the SeekBars for it is changed, otherwise keep the old value
fillColorArgb = when (seekBar) {
fillHueBar -> Color.HSVToColor(Color.alpha(fillColorArgb),
floatArrayOf(progress.toFloat(), 1f, 1f))
fillAlphaBar -> Color.argb(progress, Color.red(fillColorArgb),
Color.green(fillColorArgb), Color.blue(fillColorArgb))
else -> fillColorArgb
}
// Set the strokeColorArgb if the SeekBars for it is changed, otherwise keep the old value
strokeColorArgb = when (seekBar) {
strokeHueBar -> Color.HSVToColor(Color.alpha(strokeColorArgb),
floatArrayOf(progress.toFloat(), 1f, 1f))
strokeAlphaBar -> Color.argb(progress, Color.red(strokeColorArgb),
Color.green(strokeColorArgb), Color.blue(strokeColorArgb))
else -> strokeColorArgb
}
// Apply the style change to all the circles.
circles.map { it.onStyleChange() }
}
private fun onMarkerMoved(marker: Marker) {
circles.forEach { if (it.onMarkerMoved(marker)) return }
}
/** Listener for the Clickable CheckBox, to set if all the circles can be click */
fun toggleClickability(view: View) {
circles.map { it.setClickable((view as CheckBox).isChecked) }
}
}
/**
* Extension function to find the distance from this to another LatLng object
*/
private fun LatLng.distanceFrom(other: LatLng): Double {
val result = FloatArray(1)
Location.distanceBetween(latitude, longitude, other.latitude, other.longitude, result)
return result[0].toDouble()
}
private fun LatLng.getPointAtDistance(distance: Double): LatLng {
val radiusOfEarth = 6371009.0
val radiusAngle = (Math.toDegrees(distance / radiusOfEarth)
/ Math.cos(Math.toRadians(latitude)))
return LatLng(latitude, longitude + radiusAngle)
} | apache-2.0 | 1022e38934b23dea57c0ca252bcb52b6 | 37.322188 | 99 | 0.652177 | 4.766352 | false | false | false | false |
Shynixn/BlockBall | blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/ScoreboardEntity.kt | 1 | 2450 | package com.github.shynixn.blockball.core.logic.persistence.entity
import com.github.shynixn.blockball.api.business.annotation.YamlSerialize
import com.github.shynixn.blockball.api.business.enumeration.PlaceHolder
import com.github.shynixn.blockball.api.persistence.entity.ScoreboardMeta
/**
* Created by Shynixn 2018.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2018 by Shynixn
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* 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.
*/
class ScoreboardEntity : ScoreboardMeta {
/** Title of the scoreboard. */
@YamlSerialize(orderNumber = 1, value = "title")
override var title: String = "&aBlockBall"
/** Is the scoreboard visible. */
@YamlSerialize(orderNumber = 2, value = "enabled")
override var enabled: Boolean = false
/** Lines of the scoreboard being rendered. */
@YamlSerialize(orderNumber = 3, value = "lines")
override val lines: ArrayList<String> = arrayListOf(
""
, "&6Time: "
, PlaceHolder.TIME.placeHolder
, ""
, "&m &r"
, PlaceHolder.RED_COLOR.placeHolder + PlaceHolder.TEAM_RED.placeHolder + ":"
, "&l" + PlaceHolder.RED_GOALS.placeHolder
, ""
, PlaceHolder.BLUE_COLOR.placeHolder + PlaceHolder.TEAM_BLUE.placeHolder + ":"
, "&l" + PlaceHolder.BLUE_GOALS.placeHolder
, "&m &r"
)
} | apache-2.0 | c26c5488a2605faa231d94ad005d1f88 | 42.767857 | 90 | 0.687755 | 4.202401 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/tab/TabAdapter.kt | 1 | 9905 | package jp.toastkid.yobidashi.tab
import android.content.Context
import android.net.Uri
import android.os.Message
import android.view.View
import android.webkit.WebView
import androidx.activity.ComponentActivity
import androidx.annotation.UiThread
import androidx.lifecycle.ViewModelProvider
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.TabListViewModel
import jp.toastkid.lib.image.BitmapCompressor
import jp.toastkid.lib.preference.ColorPair
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.view.thumbnail.ThumbnailGenerator
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.browser.FaviconApplier
import jp.toastkid.yobidashi.browser.archive.IdGenerator
import jp.toastkid.yobidashi.browser.archive.auto.AutoArchive
import jp.toastkid.yobidashi.browser.block.AdRemover
import jp.toastkid.yobidashi.browser.webview.GlobalWebViewPool
import jp.toastkid.yobidashi.browser.webview.WebViewFactoryUseCase
import jp.toastkid.yobidashi.browser.webview.WebViewStateUseCase
import jp.toastkid.yobidashi.browser.webview.factory.WebViewClientFactory
import jp.toastkid.yobidashi.tab.model.ArticleListTab
import jp.toastkid.yobidashi.tab.model.ArticleTab
import jp.toastkid.yobidashi.tab.model.CalendarTab
import jp.toastkid.yobidashi.tab.model.EditorTab
import jp.toastkid.yobidashi.tab.model.PdfTab
import jp.toastkid.yobidashi.tab.model.Tab
import jp.toastkid.yobidashi.tab.model.WebTab
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
/**
* ModuleAdapter of [Tab].
*
* @author toastkidjp
*/
class TabAdapter(
private val contextSupplier: () -> Context,
private val tabEmptyCallback: () -> Unit
) {
private val tabList: TabList = TabList.loadOrInit(contextSupplier())
private val colorPair: ColorPair
private val tabThumbnails: TabThumbnails
private val preferenceApplier: PreferenceApplier
private val autoArchive = AutoArchive.make(contextSupplier())
private val webViewStateUseCase = WebViewStateUseCase.make(contextSupplier())
private val disposables = Job()
private var browserViewModel: BrowserViewModel? = null
private val bitmapCompressor = BitmapCompressor()
private var tabListViewModel: TabListViewModel? = null
private var webViewFactory: WebViewFactoryUseCase? = null
init {
val viewContext = contextSupplier()
tabThumbnails = TabThumbnails.with(contextSupplier())
preferenceApplier = PreferenceApplier(viewContext)
colorPair = preferenceApplier.colorPair()
if (viewContext is ComponentActivity) {
val viewModelProvider = ViewModelProvider(viewContext)
browserViewModel = viewModelProvider.get(BrowserViewModel::class.java)
tabListViewModel = viewModelProvider.get(TabListViewModel::class.java)
webViewFactory = WebViewFactoryUseCase(
webViewClientFactory = WebViewClientFactory(
viewModelProvider.get(ContentViewModel::class.java),
AdRemover.make(viewContext.assets),
FaviconApplier(viewContext),
preferenceApplier,
browserViewModel = viewModelProvider.get(BrowserViewModel::class.java),
currentView = { GlobalWebViewPool.getLatest() }
)
)
}
CoroutineScope(Dispatchers.IO).launch {
tabThumbnails.deleteUnused(tabList.thumbnailNames())
autoArchive.deleteUnused(tabList.archiveIds())
webViewStateUseCase.deleteUnused(tabList.ids())
}
}
private val thumbnailGenerator = ThumbnailGenerator()
/**
* Save new thumbnail asynchronously.
*/
@UiThread
fun saveNewThumbnail(view: View?) {
val currentTab = tabList.currentTab() ?: return
val file = tabThumbnails.assignNewFile(currentTab.thumbnailPath())
if (System.currentTimeMillis() - file.lastModified() < 15_000) {
return
}
val bitmap = thumbnailGenerator(view) ?: return
bitmapCompressor(bitmap, file)
}
/**
* Open new tab with URL string.
*
* @param url URL (default = homeUrl)
*/
fun openNewWebTab(url: String = preferenceApplier.homeUrl) {
val newTab = WebTab.make("New tab: $url", url)
tabList.add(newTab)
setCount()
setIndexByTab(newTab)
}
/**
* Open background tab with URL string.
*
* @param title Tab's title
* @param url Tab's URL
*/
fun openBackgroundTab(title: String, url: String): () -> Unit {
val context = contextSupplier()
val tabTitle =
if (title.isNotBlank()) title
else context.getString(R.string.new_tab)
val newTab = WebTab.make(tabTitle, url)
tabList.add(newTab)
tabList.save()
val webView = webViewFactory?.invoke(context) ?: return { }
webView.loadUrl(url)
GlobalWebViewPool.put(newTab.id(), webView)
setCount()
return { setIndexByTab(newTab) }
}
/**
* Open background tab with URL string.
*
* @param message [Message]
*/
fun openNewWindowWebTab(message: Message) {
val context = contextSupplier()
val title = message.data?.getString("title")
val url = message.data?.getString("url") ?: ""
val tabTitle =
if (title.isNullOrBlank()) context.getString(R.string.new_tab)
else title
val newTab = WebTab.make(tabTitle, url)
tabList.add(newTab)
tabList.save()
val webView = webViewFactory?.invoke(context) ?: return
val transport = message.obj as? WebView.WebViewTransport
transport?.webView = webView
message.sendToTarget()
GlobalWebViewPool.put(newTab.id(), webView)
setIndexByTab(newTab)
setCount()
}
internal fun openNewEditorTab(path: String? = null) {
val editorTab = EditorTab()
if (path != null) {
editorTab.path = path
}
tabList.add(editorTab)
setCount()
setIndexByTab(editorTab)
}
fun openNewPdfTab(uri: Uri) {
val pdfTab = PdfTab()
pdfTab.setPath(uri.toString())
tabList.add(pdfTab)
setCount()
setIndexByTab(pdfTab)
}
fun openNewArticleTab(title: String, onBackground: Boolean = false): Tab {
val articleTab = ArticleTab.make(title)
tabList.add(articleTab)
setCount()
if (!onBackground) {
setIndexByTab(articleTab)
}
return articleTab
}
fun openArticleList() {
val newTab = ArticleListTab.withTitle(contextSupplier().getString(R.string.title_article_viewer))
tabList.add(newTab)
setCount()
setIndexByTab(newTab)
}
fun openCalendar() {
val newTab = CalendarTab.withTitle(contextSupplier().getString(R.string.title_calendar))
tabList.add(newTab)
setCount()
setIndexByTab(newTab)
}
/**
*
* @param tab
*/
private fun setIndexByTab(tab: Tab) {
val newIndex = tabList.indexOf(tab)
if (invalidIndex(newIndex)) {
return
}
tabList.setIndex(newIndex)
}
internal fun replace(tab: Tab) {
setIndexByTab(tab)
}
fun movePreviousTab() {
val current = index()
if (current == 0) {
return
}
tabList.setIndex(current - 1)
}
fun moveNextTab() {
val current = index()
if (tabList.size() <= current) {
return
}
tabList.setIndex(current + 1)
}
private fun invalidIndex(newIndex: Int): Boolean = newIndex < 0 || tabList.size() <= newIndex
/**
* Return current tab count.
*
* @return tab count
*/
fun size(): Int = tabList.size()
/**
* Return specified index tab.
*
* @param index
*
* @return
*/
internal fun getTabByIndex(index: Int): Tab? = tabList.get(index)
/**
* Close specified index' tab.
* @param index
*/
internal fun closeTab(index: Int) {
if (invalidIndex(index)) {
return
}
val tab = tabList.get(index)
if (tab is WebTab) {
autoArchive.delete(IdGenerator().from(tab.getUrl()))
webViewStateUseCase.delete(tab.id())
GlobalWebViewPool.remove(tab.id())
}
tabList.closeTab(index)
tabThumbnails.delete(tab?.thumbnailPath())
setCount()
if (tabList.isEmpty) {
tabEmptyCallback()
}
}
fun index(): Int = tabList.getIndex()
fun saveTabList() {
tabList.save()
}
/**
* Dispose this object's fields.
*/
fun dispose() {
if (!preferenceApplier.doesRetainTabs()) {
tabList.clear()
tabThumbnails.clean()
}
disposables.cancel()
}
internal fun clear() {
tabList.clear()
tabThumbnails.clean()
}
internal fun indexOf(tab: Tab): Int = tabList.indexOf(tab)
internal fun currentTab(): Tab? = tabList.get(index())
internal fun currentTabId(): String = currentTab()?.id() ?: "-1"
fun isEmpty(): Boolean = tabList.isEmpty
fun isNotEmpty(): Boolean = !tabList.isEmpty
override fun toString(): String = tabList.toString()
fun swap(from: Int, to: Int) = tabList.swap(from, to)
fun updateWebTab(idAndHistory: Pair<String, History>?) {
idAndHistory ?: return
tabList.updateWithIdAndHistory(idAndHistory)
}
fun setCount() {
tabListViewModel?.tabCount(size())
}
}
| epl-1.0 | 145c978cf45d3020b08e28c17a9877c2 | 27.627168 | 105 | 0.638364 | 4.498183 | false | false | false | false |
toastkidjp/Yobidashi_kt | editor/src/main/java/jp/toastkid/editor/view/EditorTabUi.kt | 1 | 15119 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.editor.view
import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.net.Uri
import android.text.format.DateFormat
import android.widget.EditText
import android.widget.ScrollView
import androidx.activity.ComponentActivity
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.Dimension
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollDispatcher
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.viewmodel.compose.viewModel
import jp.toastkid.editor.CursorColorSetter
import jp.toastkid.editor.EditTextFinder
import jp.toastkid.editor.EditorContextMenuInitializer
import jp.toastkid.editor.R
import jp.toastkid.editor.load.LoadFromStorageDialogUi
import jp.toastkid.editor.load.StorageFilesFinder
import jp.toastkid.editor.usecase.FileActionUseCase
import jp.toastkid.editor.usecase.MenuActionInvokerUseCase
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.TabListViewModel
import jp.toastkid.lib.intent.GetContentIntentFactory
import jp.toastkid.lib.intent.ShareIntentFactory
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.viewmodel.PageSearcherViewModel
import jp.toastkid.libs.speech.SpeechMaker
import jp.toastkid.ui.dialog.ConfirmDialog
import jp.toastkid.ui.dialog.DestructiveChangeConfirmDialog
import jp.toastkid.ui.dialog.InputFileNameDialogUi
@Composable
fun EditorTabUi(path: String?) {
val context = LocalContext.current as? ComponentActivity ?: return
val preferenceApplier = PreferenceApplier(context)
val editText = remember { EditText(context) }
val nestedScrollDispatcher = remember { NestedScrollDispatcher() }
val finder = EditTextFinder(editText)
val contentViewModel = viewModel(ContentViewModel::class.java, context)
val tabListViewModel = viewModel(TabListViewModel::class.java, context)
val fileActionUseCase = remember {
FileActionUseCase(
context,
contentViewModel,
mutableStateOf(path ?: ""),
{ editText.text.toString() },
{ editText.setText(it) },
{ tabListViewModel.saveEditorTab(it) }
)
}
contentViewModel.replaceAppBarContent {
AppBarContent(
contentViewModel,
fileActionUseCase
)
}
val localLifecycleOwner = LocalLifecycleOwner.current
contentViewModel.toTop.observe(localLifecycleOwner) {
it.getContentIfNotHandled() ?: return@observe
editText.setSelection(0)
}
contentViewModel.toBottom.observe(localLifecycleOwner) {
it.getContentIfNotHandled() ?: return@observe
editText.setSelection(editText.text.length)
}
contentViewModel.share.observe(localLifecycleOwner) {
it.getContentIfNotHandled() ?: return@observe
val title =
if (path?.contains("/") == true) path.substring(path.lastIndexOf("/") + 1)
else path
val content = fileActionUseCase.getText()
if (content.isEmpty()) {
contentViewModel.snackShort(R.string.error_content_is_empty)
return@observe
}
context.startActivity(ShareIntentFactory().invoke(content, title))
}
val browserViewModel = viewModel(BrowserViewModel::class.java, context)
AndroidView(
factory = {
EditorContextMenuInitializer().invoke(
editText,
MenuActionInvokerUseCase(editText, SpeechMaker(it), browserViewModel, contentViewModel)
)
editText.setBackgroundColor(Color.Transparent.toArgb())
editText.setTextColor(preferenceApplier.editorFontColor())
editText.setTextSize(Dimension.SP, preferenceApplier.editorFontSize().toFloat())
editText.typeface = Typeface.MONOSPACE
editText.hint = context.getString(R.string.hint_editor_input)
editText.setHintTextColor(preferenceApplier.editorFontColor())
editText.isNestedScrollingEnabled = true
CursorColorSetter().invoke(
editText,
preferenceApplier.editorCursorColor(ContextCompat.getColor(context, R.color.editor_cursor))
)
editText.highlightColor = preferenceApplier.editorHighlightColor(
ContextCompat.getColor(context, R.color.light_blue_200_dd)
)
fileActionUseCase.readCurrentFile()
val scrollView = ScrollView(editText.context)
scrollView.addView(editText)
scrollView.setOnScrollChangeListener { _, scrollX, scrollY, oldScrollX, oldScrollY ->
nestedScrollDispatcher.dispatchPreScroll(
Offset((oldScrollX - scrollX).toFloat(), (oldScrollY - scrollY).toFloat()),
NestedScrollSource.Fling
)
}
scrollView.overScrollMode = ScrollView.OVER_SCROLL_NEVER
scrollView
},
modifier = Modifier
.fillMaxSize()
.background(Color(preferenceApplier.editorBackgroundColor()))
.nestedScroll(
object : NestedScrollConnection {},
nestedScrollDispatcher
)
.padding(horizontal = 8.dp, vertical = 2.dp)
)
val pageSearcherViewModel = viewModel(PageSearcherViewModel::class.java, context)
pageSearcherViewModel.upward.observe(context) {
val word = it.getContentIfNotHandled() ?: return@observe
finder.findUp(word)
}
pageSearcherViewModel.downward.observe(context, {
val word = it.getContentIfNotHandled() ?: return@observe
finder.findDown(word)
})
pageSearcherViewModel.find.observe(context, {
val word = it.getContentIfNotHandled() ?: return@observe
finder.findDown(word)
})
val dialogState = remember { mutableStateOf(false) }
ConfirmDialog(
dialogState,
context.getString(R.string.confirmation),
context.getString(R.string.message_confirm_exit)
) {
context.finish()
}
BackHandler {
dialogState.value = true
}
val localLifecycle = LocalLifecycleOwner.current.lifecycle
val openInputFileNameDialog = remember { mutableStateOf(false) }
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_PAUSE) {
fileActionUseCase.save(openInputFileNameDialog)
}
}
DisposableEffect(key1 = editText) {
localLifecycle.addObserver(observer)
onDispose {
fileActionUseCase.save(openInputFileNameDialog)
localLifecycle.removeObserver(observer)
contentViewModel.share.removeObservers(localLifecycleOwner)
}
}
contentViewModel.clearOptionMenus()
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(key1 = Unit, block = {
contentViewModel.showAppBar(coroutineScope)
})
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun AppBarContent(
contentViewModel: ContentViewModel,
fileActionUseCase: FileActionUseCase
) {
val context = LocalContext.current as? ComponentActivity ?: return
val preferenceApplier = PreferenceApplier(context)
val openLoadFromStorageDialog = remember { mutableStateOf(false) }
val openInputFileNameDialog = remember { mutableStateOf(false) }
val tabListViewModel = viewModel(TabListViewModel::class.java, context)
val loadAs: ActivityResultLauncher<Intent> =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode != Activity.RESULT_OK) {
return@rememberLauncherForActivityResult
}
it.data?.data?.let { uri ->
fileActionUseCase.readFromFileUri(uri)
openInputFileNameDialog.value = true
}
}
val openConfirmDialog = remember { mutableStateOf(false) }
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.height(72.dp)
.fillMaxWidth()
.horizontalScroll(
rememberScrollState()
)
) {
EditorMenuItem(R.string.load, R.drawable.ic_load) {
loadAs.launch(GetContentIntentFactory()("text/plain"))
}
EditorMenuItem(R.string.save, R.drawable.ic_save) { fileActionUseCase.save(openInputFileNameDialog) }
EditorMenuItem(R.string.save_as, R.drawable.ic_save_as) { openInputFileNameDialog.value = true }
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.width(60.dp)
.fillMaxHeight()
.combinedClickable(
true,
onClick = { contentViewModel.switchTabList() },
onLongClick = { tabListViewModel.openNewTab() }
)
) {
Image(
painterResource(R.drawable.ic_tab),
contentDescription = stringResource(id = R.string.tab_list),
colorFilter = ColorFilter.tint(Color(preferenceApplier.fontColor), BlendMode.SrcIn),
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(12.dp)
)
Text(
text = tabListViewModel.tabCount.value.toString(),
color = Color(preferenceApplier.fontColor),
fontSize = 12.sp,
modifier = Modifier.padding(start = 2.dp, bottom = 2.dp)
)
}
EditorMenuItem(R.string.load_from_storage, R.drawable.ic_load) {
openLoadFromStorageDialog.value = true
}
Text(
text = context.getString(R.string.last_saved) + DateFormat.format(" HH:mm:ss", fileActionUseCase.lastSaved.value),
color = Color(preferenceApplier.fontColor),
fontSize = 14.sp,
maxLines = 2,
modifier = Modifier
.padding(start = 4.dp, end = 4.dp)
.align(Alignment.CenterVertically)
)
Text(
text = context.getString(R.string.message_character_count, fileActionUseCase.getText().length),
color = Color(preferenceApplier.fontColor),
fontSize = 14.sp,
maxLines = 2,
modifier = Modifier
.padding(start = 4.dp, end = 4.dp)
.align(Alignment.CenterVertically)
)
EditorMenuItem(R.string.clear_all, R.drawable.ic_clear_form) {
openConfirmDialog.value = true
}
}
if (openLoadFromStorageDialog.value) {
LoadFromStorageDialogUi(
openDialog = openLoadFromStorageDialog,
files = StorageFilesFinder().invoke(context),
onSelect = { fileActionUseCase.readFromFileUri(Uri.fromFile(it)) }
)
}
InputFileNameDialogUi(
openInputFileNameDialog,
onCommit = {
fileActionUseCase.makeNewFileWithName(it, fileActionUseCase, openInputFileNameDialog)
}
)
DestructiveChangeConfirmDialog(
visibleState = openConfirmDialog,
titleId = R.string.title_clear_text
) {
fileActionUseCase.setText("")
}
}
@Composable
private fun EditorMenuItem(
labelId: Int,
iconId: Int,
onClick: () -> Unit
) {
val preferenceApplier = PreferenceApplier(LocalContext.current)
Column(
modifier = Modifier
.width(60.dp)
.fillMaxHeight()
.clickable {
onClick()
}
.fillMaxWidth(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Icon(
painter = painterResource(id = iconId),
contentDescription = stringResource(id = labelId),
tint = Color(preferenceApplier.fontColor)
)
Spacer(Modifier.requiredWidth(8.dp))
Text(
text = stringResource(id = labelId),
color = Color(preferenceApplier.fontColor),
fontSize = 12.sp,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
}
}
| epl-1.0 | 40f5f247fe6a71c741a5d17b91428ba3 | 36.423267 | 126 | 0.688075 | 5.054831 | false | false | false | false |
MyDogTom/detekt | detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/KtCompiler.kt | 1 | 2012 | package io.gitlab.arturbosch.detekt.core
import io.gitlab.arturbosch.detekt.api.PROJECT
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
import org.jetbrains.kotlin.com.intellij.openapi.util.text.StringUtilRt
import org.jetbrains.kotlin.com.intellij.psi.PsiFileFactory
import org.jetbrains.kotlin.com.intellij.testFramework.LightVirtualFile
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtFile
import java.nio.file.Path
/**
* @author Artur Bosch
*/
open class KtCompiler(val project: Path) {
protected val psiFileFactory: PsiFileFactory = PsiFileFactory.getInstance(PROJECT)
fun compile(subPath: Path): KtFile {
require(subPath.isFile()) { "Given sub path should be a regular file!" }
val relativePath = if (project == subPath) subPath else project.relativize(subPath)
val content = subPath.toFile().readText()
val lineSeparator = content.determineLineSeparator()
val normalizedContent = StringUtilRt.convertLineSeparators(content)
val ktFile = createKtFile(normalizedContent, relativePath)
ktFile.putExtraInformation(lineSeparator, relativePath)
return ktFile
}
private fun KtFile.putExtraInformation(lineSeparator: String, relativePath: Path) {
this.putUserData(LINE_SEPARATOR, lineSeparator)
this.putUserData(RELATIVE_PATH, relativePath.toString())
}
private fun createKtFile(content: String, relativePath: Path) = psiFileFactory.createFileFromText(
relativePath.fileName.toString(), KotlinLanguage.INSTANCE, StringUtilRt.convertLineSeparators(content),
true, true, false, LightVirtualFile(relativePath.toString())) as KtFile
private fun String.determineLineSeparator(): String {
val i = this.lastIndexOf('\n')
if (i == -1) {
return if (this.lastIndexOf('\r') == -1) System.getProperty("line.separator") else "\r"
}
return if (i != 0 && this[i] == '\r') "\r\n" else "\n"
}
companion object {
val LINE_SEPARATOR: Key<String> = Key("lineSeparator")
val RELATIVE_PATH: Key<String> = Key("relativePath")
}
}
| apache-2.0 | 74d839bd84a58bef1bd08b522489ad7f | 37.692308 | 106 | 0.76839 | 3.945098 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/manga/track/SetTrackScoreDialog.kt | 3 | 2803 | package eu.kanade.tachiyomi.ui.manga.track
import android.app.Dialog
import android.os.Bundle
import android.widget.NumberPicker
import com.afollestad.materialdialogs.MaterialDialog
import com.bluelinelabs.conductor.Controller
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.ui.base.controller.DialogController
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class SetTrackScoreDialog<T> : DialogController
where T : Controller, T : SetTrackScoreDialog.Listener {
private val item: TrackItem
constructor(target: T, item: TrackItem) : super(Bundle().apply {
putSerializable(KEY_ITEM_TRACK, item.track)
}) {
targetController = target
this.item = item
}
@Suppress("unused")
constructor(bundle: Bundle) : super(bundle) {
val track = bundle.getSerializable(KEY_ITEM_TRACK) as Track
val service = Injekt.get<TrackManager>().getService(track.sync_id)!!
item = TrackItem(track, service)
}
override fun onCreateDialog(savedViewState: Bundle?): Dialog {
val item = item
val dialog = MaterialDialog.Builder(activity!!)
.title(R.string.score)
.customView(R.layout.track_score_dialog, false)
.positiveText(android.R.string.ok)
.negativeText(android.R.string.cancel)
.onPositive { dialog, _ ->
val view = dialog.customView
if (view != null) {
// Remove focus to update selected number
val np: NumberPicker = view.findViewById(R.id.score_picker)
np.clearFocus()
(targetController as? Listener)?.setScore(item, np.value)
}
}
.show()
val view = dialog.customView
if (view != null) {
val np: NumberPicker = view.findViewById(R.id.score_picker)
val scores = item.service.getScoreList().toTypedArray()
np.maxValue = scores.size - 1
np.displayedValues = scores
// Set initial value
val displayedScore = item.service.displayScore(item.track!!)
if (displayedScore != "-") {
val index = scores.indexOf(displayedScore)
np.value = if (index != -1) index else 0
}
}
return dialog
}
interface Listener {
fun setScore(item: TrackItem, score: Int)
}
private companion object {
const val KEY_ITEM_TRACK = "SetTrackScoreDialog.item.track"
}
} | apache-2.0 | 5724c1ee731b0fee97e7404d02cf5dc5 | 33.0625 | 83 | 0.594006 | 4.625413 | false | false | false | false |
gantsign/restrulz-jvm | com.gantsign.restrulz.validation/src/main/kotlin/com/gantsign/restrulz/validation/LongValidator.kt | 1 | 3898 | /*-
* #%L
* Restrulz
* %%
* Copyright (C) 2017 GantSign Ltd.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.gantsign.restrulz.validation
/**
* Base class for validating long values.
*
* @constructor creates an instance of the long validator with the specified constraints.
* @param minimumValue the minimum permitted value.
* @param maximumValue the maximum permitted value.
* @throws IllegalArgumentException if minimumValue > maximumValue.
*/
@Suppress("unused")
abstract class LongValidator protected constructor(private val minimumValue: Long,
private val maximumValue: Long) {
init {
if (minimumValue > maximumValue) {
throw IllegalArgumentException("Parameter 'minimumValue' ($minimumValue) must be less than or equal to parameter 'maximumValue' ($maximumValue)")
}
}
/**
* Checks that the specified parameter value is valid.
*
* @param parameterName the name of the parameter being validated.
* @param value the value to validate.
* @return the value if valid.
* @throws InvalidArgumentException if the value is invalid.
*/
fun requireValidValue(parameterName: String, value: Long): Long {
if (value < minimumValue) {
throw InvalidArgumentException(parameterName, "$value is less than the minimum permitted value of $minimumValue")
}
if (value > maximumValue) {
throw InvalidArgumentException(parameterName, "$value is greater than the maximum permitted value of $maximumValue")
}
return value
}
/**
* Checks that the specified parameter value is valid or null.
*
* @param parameterName the name of the parameter being validated.
* @param value the value to validate.
* @return the value if valid or null.
* @throws InvalidArgumentException if the value is non-null and invalid.
*/
fun requireValidValueOrNull(parameterName: String, value: Long?): Long? {
if (value === null) {
return value
}
return requireValidValue(parameterName, value)
}
/**
* Checks that the specified parameter value is valid.
*
* @param value the value to validate.
* @param validationHandler the handler for validation failures.
* @return `true` if the value is valid.
*/
fun validateValue(value: Long, validationHandler: ValidationHandler): Boolean {
if (value < minimumValue) {
validationHandler.handleValidationFailure("$value is less than the minimum permitted value of $minimumValue")
return false
}
if (value > maximumValue) {
validationHandler.handleValidationFailure("$value is greater than the maximum permitted value of $maximumValue")
return false
}
return true
}
/**
* Checks that the specified parameter value is valid or null.
*
* @param value the value to validate.
* @param validationHandler the handler for validation failures.
* @return `true` if the value is valid or null.
*/
fun validateValueOrNull(value: Long?, validationHandler: ValidationHandler): Boolean {
if (value === null) {
return true
}
return validateValue(value, validationHandler)
}
}
| apache-2.0 | a2b1e75b26c831638eb1089a0fa8c402 | 35.429907 | 157 | 0.66393 | 4.878598 | false | false | false | false |
umireon/my-random-stuff | xorshift-kotlin/src/main/kotlin/com/github/umireon/my_random_stuff/AbstractRandom.kt | 1 | 846 | package com.github.umireon.my_random_stuff
interface AbstractRandom64 {
fun next(): Long
}
fun AbstractRandom64.nextBoolean(): Boolean = next() < 0
fun AbstractRandom64.nextBytes(bytes: ByteArray) {
val block = bytes.size / 8
for (i in 0 until block) {
var r = next()
for (j in 0 until 8) {
bytes[i * 8 + j] = r.toByte()
r = r ushr 8
}
}
val tail = bytes.size - block * 8
if (tail > 0) {
var r = next()
for (j in 0 until tail) {
bytes[block * 8 + j] = r.toByte()
r = r ushr 8
}
}
}
fun AbstractRandom64.nextDouble(): Double = (next() ushr 11) * 1.1102230246251565e-16
fun AbstractRandom64.nextFloat(): Float = (next() ushr 40) * 5.960464477539063e-08f
fun AbstractRandom64.nextInt(): Int = (next() ushr 32).toInt()
| cc0-1.0 | c0dbddad489afcce68d719e88bede073 | 24.636364 | 85 | 0.573286 | 3.304688 | false | false | false | false |
rock3r/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/OptionalWhenBraces.kt | 1 | 1941 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.hasCommentInside
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
/**
* This rule reports unnecessary braces in when expressions. These optional braces should be removed.
*
* <noncompliant>
* val i = 1
* when (i) {
* 1 -> { println("one") } // unnecessary curly braces since there is only one statement
* else -> println("else")
* }
* </noncompliant>
*
* <compliant>
* val i = 1
* when (i) {
* 1 -> println("one")
* else -> println("else")
* }
* </compliant>
*/
class OptionalWhenBraces(config: Config = Config.empty) : Rule(config) {
override val issue: Issue = Issue(javaClass.simpleName,
Severity.Style,
"Optional braces in when expression",
Debt.FIVE_MINS)
override fun visitWhenExpression(expression: KtWhenExpression) {
for (entry in expression.entries) {
val blockExpression = entry.expression as? KtBlockExpression
if (blockExpression?.hasUnnecessaryBraces() == true) {
report(CodeSmell(issue, Entity.from(entry), issue.description))
}
}
}
private fun KtBlockExpression.hasUnnecessaryBraces(): Boolean {
val singleStatement = statements.singleOrNull()?.takeIf {
!(it is KtLambdaExpression && it.functionLiteral.arrow == null)
}
return singleStatement != null && !hasCommentInside() && lBrace != null && rBrace != null
}
}
| apache-2.0 | 24f71a8b447f3801ade68ab81ae865ba | 33.660714 | 101 | 0.688305 | 4.210412 | false | true | false | false |
igorka48/CleanSocialAppTemplate | view/src/main/kotlin/com/social/com/view/ui/tutorial/TutorialPresenter.kt | 1 | 1435 | package com.social.com.view.ui.tutorial
import android.support.v4.app.Fragment
import com.arellomobile.mvp.InjectViewState
import com.arellomobile.mvp.MvpPresenter
import com.social.com.domain.interactor.DefaultObserver
import com.social.com.domain.interactor.tutorial.GetTutorial
import com.social.com.domain.model.TutorialPage
import com.social.com.view.ui.tutorial.TutorialView
import javax.inject.Inject
@InjectViewState
class TutorialPresenter
internal constructor (): MvpPresenter<TutorialView>() {
lateinit var tutorials: GetTutorial
var currentPage = 0
var pagesCount = 0
companion object {
const val TAG = "TutorialPresenter"
}
fun initData(){
tutorials.execute(TutorialsObserver(), null)
}
fun showdata(pages: List<TutorialPage> ){
viewState.showTutorial(pages)
}
fun pageChanged(page: Int){
currentPage = page
if(page == pagesCount-1){
viewState.tutorialCompleted()
}
}
inner class TutorialsObserver: DefaultObserver<List<TutorialPage>>() {
override fun onNext(t: List<TutorialPage>) {
super.onNext(t)
currentPage = 0
pagesCount = t.size
showdata(t)
}
override fun onComplete() {
super.onComplete()
}
override fun onError(exception: Throwable) {
super.onError(exception)
}
}
}
| apache-2.0 | 91470e691732199762821c935c928a40 | 22.916667 | 74 | 0.663415 | 4.361702 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/tourism_information/AddInformationToTourism.kt | 1 | 1455 | package de.westnordost.streetcomplete.quests.tourism_information
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.OUTDOORS
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.RARE
class AddInformationToTourism : OsmFilterQuestType<TourismInformation>() {
override val elementFilter = "nodes, ways, relations with tourism = information and !information"
override val commitMessage = "Add information type to tourist information"
override val wikiLink = "Tag:tourism=information"
override val icon = R.drawable.ic_quest_information
override val isDeleteElementEnabled = true
override val questTypeAchievements = listOf(RARE, CITIZEN, OUTDOORS)
override fun getTitle(tags: Map<String, String>): Int =
if (tags.containsKey("name"))
R.string.quest_tourism_information_name_title
else
R.string.quest_tourism_information_title
override fun createForm() = AddInformationForm()
override fun applyAnswerTo(answer: TourismInformation, changes: StringMapChangesBuilder) {
changes.add("information", answer.osmValue)
}
}
| gpl-3.0 | 781befb6ebc322ffc684ace14f40808c | 45.935484 | 101 | 0.788316 | 4.693548 | false | false | false | false |
fcostaa/kotlin-designpatterns | designpatterns/gangoffour/src/main/kotlin/com/felipecosta/designpatterns/behavioral/visitor/TreeNodeVisitor.kt | 1 | 1766 | package com.felipecosta.designpatterns.behavioral.visitor
interface TreeNode {
val leftNode: TreeNode?
val rightNode: TreeNode?
val value: Int
fun accept(visitor: TreeVisitor)
}
interface TreeVisitor {
fun visit(treeNode: TreeNode)
}
class TreeNodeImpl(value: Int,
leftTreeNode: TreeNode? = null,
rightTreeNode: TreeNode? = null) : TreeNode {
private var internalValue = value;
private var leftTreeNode: TreeNode? = leftTreeNode
private var rightTreeNode: TreeNode? = rightTreeNode
override val value: Int
get() = internalValue
override val leftNode: TreeNode?
get() = leftTreeNode
override val rightNode: TreeNode?
get() = rightTreeNode
override fun accept(visitor: TreeVisitor) {
visitor.visit(this)
}
}
class PreOrderTreeVisitor() : TreeVisitor {
override fun visit(treeNode: TreeNode) {
val leftNode = treeNode.leftNode
leftNode?.accept(this)
System.out.println("TreeNode Value: ${treeNode.value}")
val rightNode = treeNode.rightNode
rightNode?.accept(this)
}
}
class PostOrderTreeVisitor() : TreeVisitor {
override fun visit(treeNode: TreeNode) {
val rightNode = treeNode.rightNode
rightNode?.accept(this)
System.out.println("TreeNode Value: ${treeNode.value}")
val leftNode = treeNode.leftNode
leftNode?.accept(this)
}
}
fun main(args: Array<String>) {
val leftTreeNode = TreeNodeImpl(10)
val rightTreeNode = TreeNodeImpl(20)
val rootTreeNode = TreeNodeImpl(30, leftTreeNode, rightTreeNode)
PreOrderTreeVisitor().visit(rootTreeNode)
System.out.println("")
PostOrderTreeVisitor().visit(rootTreeNode)
}
| mit | c48f0d3a02ac477f3513823987224782 | 24.594203 | 68 | 0.67214 | 4.296837 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/documentation/BibtexDocumentationProvider.kt | 1 | 1261 | package nl.hannahsten.texifyidea.documentation
import com.intellij.lang.documentation.DocumentationProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import nl.hannahsten.texifyidea.lang.Described
import nl.hannahsten.texifyidea.psi.BibtexKey
/**
* @author Hannah Schellekens
*/
open class BibtexDocumentationProvider : DocumentationProvider {
/**
* The currently active lookup item.
*/
private var lookup: Described? = null
override fun getUrlFor(p0: PsiElement?, p1: PsiElement?): MutableList<String> = ArrayList()
override fun getQuickNavigateInfo(element: PsiElement, originalPsiElement: PsiElement) = when (element) {
is BibtexKey -> StringDeclarationLabel(element).makeLabel()
else -> null
}
override fun getDocumentationElementForLookupItem(manager: PsiManager?, obj: Any?, element: PsiElement?): PsiElement? {
if (obj == null || obj !is Described) {
return null
}
lookup = obj
return element
}
override fun generateDoc(element: PsiElement, element2: PsiElement?) = lookup?.description
override fun getDocumentationElementForLink(manager: PsiManager, string: String, element: PsiElement): PsiElement? = null
} | mit | 486e038ed28b39097481e201318cee90 | 32.210526 | 125 | 0.726408 | 4.85 | false | false | false | false |
renyuneyun/Easer | app/src/main/java/ryey/easer/core/ServiceUtils.kt | 1 | 3833 | /*
* Copyright (c) 2016 - 2019 Rui Zhao <[email protected]>
*
* This file is part of Easer.
*
* Easer 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.
*
* Easer 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 Easer. If not, see <http://www.gnu.org/licenses/>.
*/
package ryey.easer.core
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import ryey.easer.R
import ryey.easer.SettingsUtils
import ryey.easer.core.ui.MainActivity
class ServiceUtils {
companion object {
val EXTRA_RUN_WITH_UI = "ryey.easer.core.ServiceUtils.EXTRA.RUN_WITH_UI"
private val NOTIFICATION_ID = 1
private var startCount = 0
private var stopCount = 0
fun startNotification(service: Service) {
startCount++
if (!SettingsUtils.showNotification(service))
return
val notificationManager = service.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
val builder: NotificationCompat.Builder
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "easer_ind"
val channelName = "Easer Service Indicator"
val importance = NotificationManager.IMPORTANCE_LOW
val notificationChannel = NotificationChannel(channelId, channelName, importance)
notificationManager!!.createNotificationChannel(notificationChannel)
builder = NotificationCompat.Builder(service, channelId)
builder.setAutoCancel(true)
} else {
@Suppress("DEPRECATION")
builder = NotificationCompat.Builder(service)
.setPriority(NotificationCompat.PRIORITY_MIN)
}
val REQ_CODE = 0
val pendingIntent = PendingIntent.getActivity(
service, REQ_CODE, Intent(service, MainActivity::class.java), 0)
builder
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(service.getString(
R.string.text_notification_running_indicator_content,
service.getString(R.string.easer)))
.setOngoing(true)
.setVisibility(NotificationCompat.VISIBILITY_SECRET)
.setContentIntent(pendingIntent)
val indicatorNotification = builder.build()
if (SettingsUtils.runInForeground(service)) {
service.startForeground(NOTIFICATION_ID, indicatorNotification)
} else {
notificationManager!!.notify(NOTIFICATION_ID, indicatorNotification)
}
}
fun stopNotification(service: Service) {
stopCount++
if (!SettingsUtils.showNotification(service))
return
if (SettingsUtils.runInForeground(service)) {
} else {
val notificationManager = service.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
notificationManager!!.cancel(NOTIFICATION_ID)
}
}
}
} | gpl-3.0 | 1816e03cb46c1110d84a8fefe0a8bdd0 | 37.34 | 120 | 0.641795 | 5.151882 | false | false | false | false |
grassrootza/grassroot-android-v2 | app/src/main/java/za/org/grassroot2/view/adapter/GroupsAdapter.kt | 1 | 3385 | package za.org.grassroot2.view.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.jakewharton.rxbinding2.view.RxView
import com.squareup.picasso.Picasso
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import kotlinx.android.synthetic.main.item_group.view.*
import za.org.grassroot2.R
import za.org.grassroot2.model.Group
import za.org.grassroot2.util.LastModifiedFormatter
class GroupsAdapter(private val context: Context, data: List<Group>) : FooterEnabledAdapter<Group>(data) {
private val viewClickSubject = PublishSubject.create<String>()
private val groupImageClickSubject = PublishSubject.create<String>()
val viewClickObservable: Observable<String>
get() = viewClickSubject
val groupImageClickObservable: Observable<String>
get() = groupImageClickSubject
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
super.createFooterEnabledViewHolder(parent, viewType) ?: nonFooterViewHolder(parent)
private fun nonFooterViewHolder(parent: ViewGroup): RecyclerView.ViewHolder =
GroupViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_group, parent, false))
override fun bindRegularViewHolder(vh: RecyclerView.ViewHolder, position: Int) {
val item = items[position]
val holder = vh as GroupViewHolder
if (item != null) {
holder.name!!.text = item.name
holder.count!!.text = holder.count!!.context.resources.getQuantityString(R.plurals.member_count, item.memberCount!!, item.memberCount)
holder.lastModified!!.text = LastModifiedFormatter.lastSeen(context, item.lastTimeChangedServer)
holder.organiser!!.text = "Placeholder"
holder.letter!!.text = item?.name.substring(0, 1)
holder.letter!!.visibility = View.VISIBLE
item.profileImageUrl?.let {
Picasso.get()
.load(it)
.resizeDimen(R.dimen.profile_photo_width, R.dimen.profile_photo_height)
.centerCrop()
.into(holder.image)
}
RxView.clicks(holder.root!!)
.map { o -> item.uid }
.subscribe(viewClickSubject)
RxView.clicks(holder.image!!)
.map { `object` -> item.uid }
.subscribe(groupImageClickSubject)
}
}
fun setImage(imageUrl: String, groupUid: String) {
for (group in items) {
if (group.uid == groupUid) {
group.profileImageUrl = imageUrl
notifyItemChanged(items.indexOf(group))
}
}
}
internal class GroupViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
var root: View = itemView.root
var letter: TextView = itemView.letter
var name: TextView = itemView.name
var organiser: TextView = itemView.organiser
var count: TextView = itemView.count
var lastModified: TextView = itemView.lastModified
var image: ImageView = itemView.image
}
}
| bsd-3-clause | d5a36d0c7fdcbf409c1c76583afb3ab1 | 33.540816 | 146 | 0.664993 | 4.714485 | false | false | false | false |
clangen/musikcube | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/service/system/SystemService.kt | 1 | 28667 | package io.casey.musikcube.remote.service.system
import android.annotation.SuppressLint
import android.app.*
import android.content.*
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.media.AudioManager
import android.os.*
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import android.view.KeyEvent
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.FutureTarget
import com.bumptech.glide.request.RequestFutureTarget
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.Transition
import io.casey.musikcube.remote.Application
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.injection.GlideApp
import io.casey.musikcube.remote.injection.GlideRequest
import io.casey.musikcube.remote.service.playback.Playback
import io.casey.musikcube.remote.service.playback.PlaybackServiceFactory
import io.casey.musikcube.remote.service.playback.PlaybackState
import io.casey.musikcube.remote.service.playback.impl.streaming.StreamingPlaybackService
import io.casey.musikcube.remote.service.websocket.model.ITrack
import io.casey.musikcube.remote.ui.home.activity.MainActivity
import io.casey.musikcube.remote.ui.settings.constants.Prefs
import io.casey.musikcube.remote.ui.shared.extension.fallback
import io.casey.musikcube.remote.ui.shared.extension.getParcelableExtraCompat
import io.casey.musikcube.remote.ui.shared.util.AlbumArtLookup
import io.casey.musikcube.remote.ui.shared.util.Size
import io.casey.musikcube.remote.util.Debouncer
import androidx.core.app.NotificationCompat.Action as NotifAction
const val ENABLE_LOGGING = false
private fun log(format: String, vararg params: Any?) {
if (ENABLE_LOGGING) {
Log.d("musikdroid.Service", String.format(format, *params))
}
}
/**
* a service used to interact with all of the system media-related components -- notifications,
* lock screen controls, and headset events. also holds a partial wakelock to keep the system
* from completely falling asleep during streaming playback.
*/
class SystemService : Service() {
enum class State { Dead, Active, Sleeping }
private var playback: StreamingPlaybackService? = null
private var wakeLock: PowerManager.WakeLock? = null
private var mediaSession: MediaSessionCompat? = null
private var headsetHookPressCount = 0
/* if we pause via headset on some devices, and unpause immediately after,
the runtime will erroneously issue a second KEYCODE_MEDIA_PAUSE command,
instead of KEYCODE_MEDIA_RESUME. to work around this, if we pause from a
headset, we flip this bit for a couple seconds, which will be used as a
hint that we should resume if we get another KEYCODE_MEDIA_PAUSE. */
private var headsetDoublePauseHack = false
private lateinit var powerManager: PowerManager
private lateinit var prefs: SharedPreferences
private val handler = Handler(Looper.getMainLooper())
private val albumArt = AlbumArt()
private val sessionData = SessionMetadata()
override fun onCreate() {
log("onCreate")
state = State.Sleeping
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
NOTIFICATION_CHANNEL,
NOTIFICATION_CHANNEL,
NotificationManager.IMPORTANCE_LOW)
channel.enableVibration(false)
channel.setSound(null, null)
channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL)
notificationManager.createNotificationChannel(channel)
}
prefs = getSharedPreferences(Prefs.NAME, Context.MODE_PRIVATE)
powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
registerReceivers()
wakeupNow()
}
override fun onDestroy() {
log("onDestroy")
state = State.Dead
super.onDestroy()
releaseWakeLock()
unregisterReceivers()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.deleteNotificationChannel(NOTIFICATION_CHANNEL)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
log("onStartCommand")
if (intent != null && intent.action != null) {
when (intent.action) {
ACTION_WAKE_UP -> wakeupNow()
ACTION_SHUT_DOWN -> shutdownNow()
ACTION_SLEEP -> sleepNow()
else -> {
if (handlePlaybackAction(intent.action)) {
wakeupNow()
}
}
}
}
return super.onStartCommand(intent, flags, startId)
}
override fun onBind(intent: Intent): IBinder? = null
private fun wakeupNow() {
log("SystemService WAKE_UP")
val sleeping = playback == null || wakeLock == null
if (playback == null) {
playback = PlaybackServiceFactory.streaming(this)
}
acquireWakeLock()
if (sleeping) {
playback?.connect(playbackListener)
}
checkInitMediaSession()
updateNotificationAndSessionDebouncer.call()
state = State.Active
}
private fun shutdownNow() {
log("SystemService SHUT_DOWN")
deinitMediaSession()
playback?.disconnect(playbackListener)
playback = null
releaseWakeLock()
stopSelf()
}
private fun sleepNow() {
log("SystemService SLEEP")
releaseWakeLock()
playback?.disconnect(playbackListener)
state = State.Sleeping
}
@SuppressLint("WakelockTimeout")
private fun acquireWakeLock() {
if (wakeLock == null) {
wakeLock = powerManager.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, "$SESSION_TAG:")
wakeLock?.let {
it.setReferenceCounted(false)
it.acquire()
wakeLockAcquireTime = System.nanoTime()
}
}
}
private fun releaseWakeLock() {
if (wakeLock != null) {
wakeLock?.release()
wakeLock = null
totalWakeLockTime += (System.nanoTime() - wakeLockAcquireTime)
wakeLockAcquireTime = -1L
}
}
private fun checkInitMediaSession() {
log("checkInitMediaSession: isActive=${mediaSession?.isActive}")
if (mediaSession == null || mediaSession?.isActive != true) {
deinitMediaSession()
val receiver = ComponentName(
packageName, MediaButtonReceiver::class.java.name)
log("checkInitMediaSession: creating new session")
mediaSession = MediaSessionCompat(
this, SESSION_TAG, receiver, null)
.apply {
this.setCallback(mediaSessionCallback)
this.isActive = true
}
}
}
private fun deinitMediaSession() {
log("deinitMediaSession: destroying session")
mediaSession?.release()
mediaSession = null
}
private fun registerReceivers() {
val filter = IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY)
registerReceiver(headsetUnpluggedReceiver, filter)
}
private fun unregisterReceivers() =
try {
unregisterReceiver(headsetUnpluggedReceiver)
}
catch (ex: Exception) {
log("unregisterReceivers: unable to unregister headset (un)plugged BroadcastReceiver")
}
private fun downloadAlbumArtIfNecessary(track: ITrack, duration: Int) {
if (!albumArt.same(track) || (albumArt.request == null && albumArt.bitmap == null)) {
log("downloadAlbumArtIfNecessary: detected different different track")
if (track.artist.isNotBlank() && track.album.isNotBlank()) {
log("downloadAlbumArtIfNecessary: metadata available, attempting to download artwork")
val url = AlbumArtLookup.getUrl(track, Size.Mega)
val request = GlideApp.with(applicationContext)
.asBitmap()
.load(url)
.apply(BITMAP_OPTIONS)
albumArt.reset(track)
albumArt.request = request
albumArt.target = request.into(
object: RequestFutureTarget<Bitmap>(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) {
override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap>?) {
/* make sure the instance's current request is the same as this request. it's
possible we had another download request come in before this one finished */
if (albumArt.request == request) {
log("downloadAlbumArtIfNecessary: artwork downloaded")
albumArt.bitmap = bitmap
albumArt.request = null
updateMediaSession(track, duration)
}
else {
log("downloadAlbumArtIfNecessary: artwork downloaded, but request does not match!")
}
}
override fun onLoadFailed(errorDrawable: Drawable?) {
log("downloadAlbumArtIfNecessary: artwork failed to download. albumArt.request=${albumArt.request}, request=$request")
if (albumArt.request == request) {
albumArt.request = null
}
}
})
}
}
else {
log("downloadAlbumArtIfNecessary: downloadAlbumArt already in flight")
}
}
private fun updateMediaSession(track: ITrack?, duration: Int) {
var currentImage: Bitmap? = null
if (track != null) {
downloadAlbumArtIfNecessary(track, duration)
currentImage = albumArt.bitmap
}
if (!sessionData.matches(track, currentImage, duration)) {
log("updateMediaSession: stale data detected, updating")
sessionData.update(track, currentImage, duration)
log("updateMediaSession: updating with title=${track?.title}, album=${track?.album}, artist=${track?.artist}")
mediaSession?.setMetadata(MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, track?.artist ?: "-")
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, track?.album ?: "-")
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, track?.title ?: "-")
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, sessionData.duration.toLong())
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, sessionData.bitmap)
.build())
}
else {
log("updateMediaSession: data up to date, not updating")
}
}
/* Updating either MediaSession or the NotificationCompat.MediaStyle too quickly (or from different
threads) can spin it into a weird, unsynchronized state. Let's ensure we debounce updates to
these system-provided APIs. */
private val updateNotificationAndSessionDebouncer = object: Debouncer<Unit>(NOTIFICATION_DEBOUNCE_MS) {
override fun onDebounced(last: Unit?) {
mediaSession?.let { session ->
var mediaSessionState = PlaybackStateCompat.STATE_STOPPED
var duration = 0
var position = 0L
var bufferPosition = 0L
var playing: ITrack? = null
playback?.let { pb ->
mediaSessionState = when (pb.state) {
PlaybackState.Playing -> PlaybackStateCompat.STATE_PLAYING
PlaybackState.Buffering -> PlaybackStateCompat.STATE_BUFFERING
PlaybackState.Paused -> PlaybackStateCompat.STATE_PAUSED
PlaybackState.Stopped -> PlaybackStateCompat.STATE_STOPPED
}
playing = pb.playingTrack
duration = (pb.duration * 1000).toInt()
position = (pb.currentTime * 1000).toLong()
bufferPosition = (pb.bufferedTime * 1000).toLong()
}
updateMediaSession(playing, duration)
updateNotification(playing, playback?.state ?: PlaybackState.Stopped)
session.setPlaybackState(PlaybackStateCompat.Builder()
.setState(mediaSessionState, position, 1f)
.setBufferedPosition(bufferPosition)
.setActions(MEDIA_SESSION_ACTIONS)
.build())
}
}
}
private fun scheduleNotificationTimeUpdate() {
handler.removeCallbacks(updateTimeRunnable)
handler.postDelayed(updateTimeRunnable, NOTIFICATION_PLAYHEAD_SYNC_MS)
}
private val updateTimeRunnable = object: Runnable {
override fun run() {
playback?.let { pb ->
when (pb.state) {
PlaybackState.Playing -> {
updateNotificationAndSessionDebouncer.call()
scheduleNotificationTimeUpdate()
}
PlaybackState.Buffering,
PlaybackState.Paused,
PlaybackState.Stopped -> {
}
}
}
}
}
@SuppressLint("UnspecifiedImmutableFlag")
private fun getPendingActivityIntentCompat(intent: Intent) =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.getActivity(applicationContext, 1, intent, PendingIntent.FLAG_IMMUTABLE)
}
else {
PendingIntent.getActivity(applicationContext, 1, intent, 0)
}
@SuppressLint("UnspecifiedImmutableFlag")
private fun getPendingServiceIntentCompat(intent: Intent) =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.getService(applicationContext, 1, intent, PendingIntent.FLAG_IMMUTABLE)
}
else {
PendingIntent.getService(applicationContext, 1, intent, 0)
}
private fun updateNotification(track: ITrack?, state: PlaybackState) {
val contentIntent = getPendingActivityIntentCompat(MainActivity.getStartIntent(this))
val title = fallback(track?.title, "-")
val artist = fallback(track?.artist, "-")
val album = fallback(track?.album, "-")
log("updateNotification: state=$state title=$title, album=$album, artist=$artist")
val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle(title)
.setContentText("$artist - $album")
.setContentIntent(contentIntent)
.setUsesChronometer(false)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true)
if (state == PlaybackState.Stopped) {
notification.addAction(action(
android.R.drawable.ic_media_play,
getString(R.string.button_play), ACTION_NOTIFICATION_PLAY))
notification.setStyle(androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0)
.setMediaSession(mediaSession?.sessionToken))
}
else {
if (state == PlaybackState.Playing) {
notification.addAction(action(
android.R.drawable.ic_media_previous,
getString(R.string.button_prev), ACTION_NOTIFICATION_PREV))
notification.addAction(action(
android.R.drawable.ic_media_pause,
getString(R.string.button_pause), ACTION_NOTIFICATION_PAUSE))
notification.addAction(action(
android.R.drawable.ic_media_next,
getString(R.string.button_next), ACTION_NOTIFICATION_NEXT))
notification.setStyle(androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0, 1, 2)
.setMediaSession(mediaSession?.sessionToken))
}
else {
notification.addAction(action(
android.R.drawable.ic_media_play,
getString(R.string.button_play), ACTION_NOTIFICATION_PLAY))
notification.addAction(action(
android.R.drawable.ic_menu_close_clear_cancel,
getString(R.string.button_close), ACTION_NOTIFICATION_STOP))
notification.setStyle(androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0, 1)
.setMediaSession(mediaSession?.sessionToken))
}
}
notificationManager.cancel(NOTIFICATION_ID)
startForeground(NOTIFICATION_ID, notification.build())
}
private fun action(icon: Int, title: String, intentAction: String): NotifAction {
val intent = Intent(applicationContext, SystemService::class.java).apply { action = intentAction }
return NotifAction.Builder(icon, title, getPendingServiceIntentCompat(intent)).build()
}
private fun handlePlaybackAction(action: String?): Boolean {
this.playback?.let {
when (action) {
ACTION_NOTIFICATION_NEXT -> {
it.next()
return true
}
ACTION_NOTIFICATION_PAUSE -> {
it.pause()
return true
}
ACTION_NOTIFICATION_PLAY -> {
it.resume()
return true
}
ACTION_NOTIFICATION_PREV -> {
it.prev()
return true
}
ACTION_NOTIFICATION_STOP -> {
it.stop()
shutdown()
return true
}
else -> {
}
}
}
return false
}
private val headsetHookDebouncer =
object: Debouncer<Void>(HEADSET_HOOK_DEBOUNCE_MS) {
override fun onDebounced(last: Void?) {
playback?.let {
when (headsetHookPressCount) {
1 -> it.pauseOrResume()
2 -> it.next()
3 -> it.prev()
}
}
headsetHookPressCount = 0
}
}
private val notificationManager: NotificationManager
get() = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
private val headsetDoublePauseHackDebouncer =
object: Debouncer<Void>(HEADSET_DOUBLE_PAUSE_HACK_DEBOUNCE_MS) {
override fun onDebounced(last: Void?) {
headsetDoublePauseHack = false
}
}
private val mediaSessionCallback = object : MediaSessionCompat.Callback() {
override fun onMediaButtonEvent(mediaButtonEvent: Intent?): Boolean {
if (Intent.ACTION_MEDIA_BUTTON == mediaButtonEvent?.action) {
val event =
mediaButtonEvent.getParcelableExtraCompat<KeyEvent>(Intent.EXTRA_KEY_EVENT) ?:
return super.onMediaButtonEvent(mediaButtonEvent)
val keycode = event.keyCode
val action = event.action
if (event.repeatCount == 0 && action == KeyEvent.ACTION_DOWN) {
when (keycode) {
KeyEvent.KEYCODE_HEADSETHOOK -> {
++headsetHookPressCount
headsetHookDebouncer.call()
return true
}
KeyEvent.KEYCODE_MEDIA_STOP -> {
playback?.pause()
shutdown()
return true
}
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
playback?.pauseOrResume()
return true
}
KeyEvent.KEYCODE_MEDIA_NEXT -> {
playback?.next()
return true
}
KeyEvent.KEYCODE_MEDIA_PREVIOUS -> {
playback?.prev()
return true
}
KeyEvent.KEYCODE_MEDIA_PAUSE -> {
if (headsetDoublePauseHack) {
playback?.resume()
headsetDoublePauseHack = false
}
else {
playback?.pause()
headsetDoublePauseHack = true
headsetDoublePauseHackDebouncer.call()
}
return true
}
KeyEvent.KEYCODE_MEDIA_PLAY -> {
playback?.resume()
return true
}
}
}
}
return false
}
override fun onSeekTo(pos: Long) {
playback?.seekTo(pos.toDouble() / 1000.0)
}
override fun onPlay() {
playback?.let {
when (it.queueCount == 0) {
true -> it.playAll()
false -> it.resume()
}
}
}
override fun onPause() {
playback?.pause()
}
override fun onSkipToNext() {
playback?.next()
}
override fun onSkipToPrevious() {
playback?.prev()
}
override fun onFastForward() {
playback?.seekForward()
}
override fun onRewind() {
playback?.seekBackward()
}
}
private val playbackListener = {
/* freaking sigh... */
if (playback?.state == PlaybackState.Playing) {
headsetDoublePauseHack = false
}
scheduleNotificationTimeUpdate()
updateNotificationAndSessionDebouncer.call()
}
private val headsetUnpluggedReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
playback?.let { pb ->
val switchOnDisconnect = prefs.getBoolean(
Prefs.Key.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT,
Prefs.Default.TRANSFER_TO_SERVER_ON_HEADSET_DISCONNECT)
val isPlaying =
(pb.state == PlaybackState.Playing) ||
(pb.state == PlaybackState.Buffering)
pb.pause()
if (switchOnDisconnect && isPlaying) {
Playback.transferPlayback(this@SystemService, Playback.SwitchMode.Transfer)
}
}
}
}
}
private class AlbumArt {
var target: FutureTarget<Bitmap>? = null
var request: GlideRequest<Bitmap>? = null
var bitmap: Bitmap? = null
var track: ITrack? = null
fun reset(t: ITrack? = null) {
log("AlbumArt.reset()")
bitmap = null
request = null
target = null
track = t
}
fun same(other: ITrack?): Boolean =
track != null && other != null && other.externalId == track?.externalId
}
private class SessionMetadata {
var track: ITrack? = null
var bitmap: Bitmap? = null
var duration: Int = 0
fun update(otherTrack: ITrack?, otherBitmap: Bitmap?, otherDuration: Int) {
track = otherTrack
bitmap = otherBitmap
duration = otherDuration
}
fun matches(otherTrack: ITrack?, otherBitmap: Bitmap?, otherDuration: Int): Boolean {
log("updateMediaSession.matches(): " +
"track=$track, " +
"otherTrack=$otherTrack " +
"otherTrack.externalId=${otherTrack?.externalId} " +
"track.externalId=${track?.externalId} " +
"otherBitmap=$otherBitmap " +
"bitmap=$bitmap" +
"otherDuration=$otherDuration " +
"duration=$duration")
val result = (track != null && otherTrack != null) &&
otherTrack.externalId == track?.externalId &&
bitmap === otherBitmap &&
duration == otherDuration
log("updateMediaSession.matches(): result=$result")
return result
}
}
companion object {
private const val SESSION_TAG = "musikdroid.SystemService"
private const val NOTIFICATION_ID = 0xdeadbeef.toInt()
private const val NOTIFICATION_CHANNEL = "musikdroid"
private const val HEADSET_HOOK_DEBOUNCE_MS = 500L
private const val HEADSET_DOUBLE_PAUSE_HACK_DEBOUNCE_MS = 3500L
private const val NOTIFICATION_DEBOUNCE_MS = 750L
private const val NOTIFICATION_PLAYHEAD_SYNC_MS = 10000L
private const val ACTION_NOTIFICATION_PLAY = "io.casey.musikcube.remote.NOTIFICATION_PLAY"
private const val ACTION_NOTIFICATION_PAUSE = "io.casey.musikcube.remote.NOTIFICATION_PAUSE"
private const val ACTION_NOTIFICATION_NEXT = "io.casey.musikcube.remote.NOTIFICATION_NEXT"
private const val ACTION_NOTIFICATION_PREV = "io.casey.musikcube.remote.NOTIFICATION_PREV"
const val ACTION_NOTIFICATION_STOP = "io.casey.musikcube.remote.PAUSE_SHUT_DOWN"
var ACTION_WAKE_UP = "io.casey.musikcube.remote.WAKE_UP"
var ACTION_SHUT_DOWN = "io.casey.musikcube.remote.SHUT_DOWN"
var ACTION_SLEEP = "io.casey.musikcube.remote.SLEEP"
var state = State.Dead
private set
val isWakeLockActive: Boolean
get() { return wakeLockAcquireTime >= 0L }
val wakeLockTime: Double
get() {
val current = when (wakeLockAcquireTime > -1L) {
true -> System.nanoTime() - wakeLockAcquireTime
false -> 0L
}
return (totalWakeLockTime + current).toDouble() / 1_000_000_000.0
}
private val BITMAP_OPTIONS = RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL)
private const val MEDIA_SESSION_ACTIONS =
PlaybackStateCompat.ACTION_PLAY_PAUSE or
PlaybackStateCompat.ACTION_SKIP_TO_NEXT or
PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS or
PlaybackStateCompat.ACTION_STOP or
PlaybackStateCompat.ACTION_SEEK_TO
private var wakeLockAcquireTime = -1L
private var totalWakeLockTime = 0L
fun wakeup() {
val c = Application.instance
ContextCompat.startForegroundService(
c, Intent(c, SystemService::class.java).setAction(ACTION_WAKE_UP))
}
fun shutdown() {
if (state != State.Dead) {
val c = Application.instance
ContextCompat.startForegroundService(
c, Intent(c, SystemService::class.java).setAction(ACTION_SHUT_DOWN))
}
}
fun sleep() {
if (state != State.Dead) {
val c = Application.instance
ContextCompat.startForegroundService(
c, Intent(c, SystemService::class.java).setAction(ACTION_SLEEP))
}
}
}
}
| bsd-3-clause | e10961c8ac97aea5a2ea84888ef1c336 | 37.427614 | 146 | 0.574179 | 5.327448 | false | false | false | false |
juxeii/dztools | java/dzjforex/src/main/kotlin/com/jforex/dzjforex/account/Account.kt | 1 | 1139 | package com.jforex.dzjforex.account
import com.dukascopy.api.IAccount
import com.dukascopy.api.Instrument
import com.dukascopy.api.OfferSide
import com.jforex.dzjforex.misc.ContextDependencies
import com.jforex.kforexutils.misc.asCost
object AccountApi
{
fun <F> ContextDependencies<F>.baseEequity() = delay { account.baseEquity }
fun <F> ContextDependencies<F>.tradeVal() = delay { account.equity - account.baseEquity }
fun <F> ContextDependencies<F>.usedMargin() = delay { account.usedMargin }
fun <F> ContextDependencies<F>.pipCost(instrument: Instrument) = delay {
val pipCost = jfContext
.utils
.convertPipToCurrency(instrument, account.accountCurrency, OfferSide.ASK) * instrument.minTradeAmount
pipCost.asCost()
}
fun <F> ContextDependencies<F>.isTradingAllowed() = delay {
account.accountState == IAccount.AccountState.OK ||
account.accountState == IAccount.AccountState.OK_NO_MARGIN_CALL
}
fun <F> ContextDependencies<F>.accountName() = account.accountId
fun <F> ContextDependencies<F>.isNFAAccount() = account.isGlobal
}
| mit | be559b4af12952928883e3adf469b120 | 34.59375 | 113 | 0.720808 | 3.796667 | false | false | false | false |
hypercube1024/firefly | firefly-net/src/main/kotlin/com/fireflysource/net/http/common/content/handler/AbstractFileContentHandler.kt | 1 | 2979 | package com.fireflysource.net.http.common.content.handler
import com.fireflysource.common.coroutine.asVoidFuture
import com.fireflysource.common.io.closeAsync
import com.fireflysource.common.io.openFileChannelAsync
import com.fireflysource.common.io.writeAwait
import com.fireflysource.common.sys.SystemLogger
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import java.nio.ByteBuffer
import java.nio.file.OpenOption
import java.nio.file.Path
import java.util.concurrent.CompletableFuture
abstract class AbstractFileContentHandler<T>(val path: Path, vararg options: OpenOption) : HttpContentHandler<T> {
companion object {
private val log = SystemLogger.create(AbstractFileContentHandler::class.java)
}
private val inputChannel: Channel<WriteFileMessage> = Channel(Channel.UNLIMITED)
private val scope: CoroutineScope = CoroutineScope(CoroutineName("Firefly-file-content-handler"))
private val writeJob: Job = scope.launch {
val fileChannel = openFileChannelAsync(path, *options).await()
var pos = 0L
suspend fun closeFileChannel() {
try {
fileChannel.closeAsync().join()
} catch (e: Exception) {
log.error(e) { "close file channel exception." }
}
}
suspend fun write(): Boolean {
var closed = false
when (val writeFileMessage = inputChannel.receive()) {
is WriteFileRequest -> {
val buf = writeFileMessage.buffer
flushDataLoop@ while (buf.hasRemaining()) {
val len = fileChannel.writeAwait(buf, pos)
if (len < 0) {
closeFileChannel()
closed = true
}
pos += len
}
}
is EndWriteFile -> {
closeFileChannel()
closed = true
}
}
return closed
}
writeMessageLoop@ while (true) {
val closed = try {
write()
} catch (e: Exception) {
log.error(e) { "read file exception." }
closeFileChannel()
true
}
if (closed) break@writeMessageLoop
}
}
override fun accept(buffer: ByteBuffer, t: T) {
inputChannel.trySend(WriteFileRequest(buffer))
}
override fun closeAsync(): CompletableFuture<Void> =
scope.launch { closeAwait() }.asVoidFuture().thenAccept { scope.cancel() }
override fun close() {
inputChannel.trySend(EndWriteFile)
}
private suspend fun closeAwait() {
close()
writeJob.join()
}
}
sealed interface WriteFileMessage
@JvmInline
value class WriteFileRequest(val buffer: ByteBuffer) : WriteFileMessage
object EndWriteFile : WriteFileMessage
| apache-2.0 | 146b13e6b6ab4e4721bdafeade9a90bc | 31.736264 | 114 | 0.594495 | 4.907743 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/ingestion/processing/job/WorkflowJobProcessingServiceIT.kt | 1 | 17976 | package net.nemerosa.ontrack.extension.github.ingestion.processing.job
import net.nemerosa.ontrack.common.Time
import net.nemerosa.ontrack.common.getOrNull
import net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationProperty
import net.nemerosa.ontrack.extension.git.property.GitBranchConfigurationPropertyType
import net.nemerosa.ontrack.extension.github.ingestion.AbstractIngestionTestSupport
import net.nemerosa.ontrack.extension.github.ingestion.config.model.IngestionConfig
import net.nemerosa.ontrack.extension.github.ingestion.config.model.IngestionConfigJobs
import net.nemerosa.ontrack.extension.github.ingestion.config.model.IngestionConfigSteps
import net.nemerosa.ontrack.extension.github.ingestion.config.model.support.FilterConfig
import net.nemerosa.ontrack.extension.github.ingestion.processing.IngestionEventProcessingResult
import net.nemerosa.ontrack.extension.github.ingestion.processing.config.ConfigLoaderService
import net.nemerosa.ontrack.extension.github.ingestion.processing.config.ConfigLoaderServiceITMockConfig
import net.nemerosa.ontrack.extension.github.ingestion.processing.model.*
import net.nemerosa.ontrack.extension.github.workflow.BuildGitHubWorkflowRun
import net.nemerosa.ontrack.extension.github.workflow.BuildGitHubWorkflowRunProperty
import net.nemerosa.ontrack.extension.github.workflow.BuildGitHubWorkflowRunPropertyType
import net.nemerosa.ontrack.extension.github.workflow.ValidationRunGitHubWorkflowJobPropertyType
import net.nemerosa.ontrack.model.structure.Build
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
@ContextConfiguration(classes = [ConfigLoaderServiceITMockConfig::class])
class WorkflowJobProcessingServiceIT : AbstractIngestionTestSupport() {
@Autowired
private lateinit var workflowJobProcessingService: WorkflowJobProcessingService
@Autowired
private lateinit var configLoaderService: ConfigLoaderService
@BeforeEach
fun before() {
onlyOneGitHubConfig()
ConfigLoaderServiceITMockConfig.defaultIngestionConfig(configLoaderService)
}
@Test
fun `Creation of a simple validation run`() {
project {
branch {
build {
runTest()
}
}
}
}
@Test
fun `Creation of a simple validation run with a very large ID`() {
project {
branch {
build {
runTest(runId = 2218938646L)
}
}
}
}
@Test
fun `Excluding a step based on the ingestion config for step exclusion`() {
ConfigLoaderServiceITMockConfig.customIngestionConfig(
configLoaderService,
IngestionConfig(
steps = IngestionConfigSteps(
filter = FilterConfig(excludes = "publishing.*")
)
)
)
withGitHubIngestionSettings {
project {
branch {
build {
runTest(expectedStep = false)
}
}
}
}
}
@Test
fun `Excluding a step based on the ingestion config for job exclusion`() {
ConfigLoaderServiceITMockConfig.customIngestionConfig(
configLoaderService,
IngestionConfig(
jobs = IngestionConfigJobs(
filter = FilterConfig(excludes = "build")
)
)
)
withGitHubIngestionSettings {
project {
branch {
build {
runTest(expectedStep = false)
}
}
}
}
}
@Test
fun `Creation of a simple validation run and the associated job`() {
ConfigLoaderServiceITMockConfig.customIngestionConfig(
configLoaderService,
IngestionConfig()
)
project {
branch {
build {
runTest(step = null, expectedStep = false, expectedJob = true)
}
}
}
}
@Test
fun `Exclusion of job based on the ingestion config`() {
withGitHubIngestionSettings {
ConfigLoaderServiceITMockConfig.customIngestionConfig(
configLoaderService,
IngestionConfig(
jobs = IngestionConfigJobs(
filter = FilterConfig(excludes = "build")
)
)
)
project {
branch {
build {
runTest(step = null, expectedStep = false, expectedJob = false)
}
}
}
}
}
@Test
fun `Failed status`() {
project {
branch {
build {
runTest(
conclusion = WorkflowJobStepConclusion.failure,
expectedStatus = "FAILED",
)
}
}
}
}
@Test
fun `Ignoring jobs when no run ID has been assigned`() {
project {
branch {
asAdmin {
// Git branch at branch level
setProperty(
this,
GitBranchConfigurationPropertyType::class.java,
GitBranchConfigurationProperty(
branch = "main",
buildCommitLink = null, // Not used
isOverride = false,
buildTagInterval = 0,
)
)
// Trying to process a job & step on a branch where no build has been created
workflowJobProcessingService.setupValidation(
repository = Repository(
name = project.name,
description = null,
htmlUrl = "https://github.com/nemerosa/${project.name}",
owner = Owner(login = "nemerosa"),
),
runId = 1000L,
runAttempt = 1,
job = "any-job",
jobUrl = "uri:job",
step = "any-step",
status = WorkflowJobStepStatus.in_progress,
conclusion = null,
startedAt = Time.now(),
completedAt = null,
)
// Still no build has been created
assertEquals(0, structureService.getBuildCount(this))
}
}
}
}
@Test
fun `Creation of a simple validation run twice`() {
project {
branch {
build {
runTest(runId = 1)
}
build {
runTest(runId = 2)
}
}
}
}
@Test
fun `Job progressing on several payloads`() {
project {
branch {
build {
setupTest(
status = WorkflowJobStepStatus.queued,
conclusion = null,
)
setupTest(
status = WorkflowJobStepStatus.in_progress,
conclusion = null,
)
setupTest(
status = WorkflowJobStepStatus.completed,
conclusion = WorkflowJobStepConclusion.success,
)
setupTest(
status = WorkflowJobStepStatus.completed,
conclusion = WorkflowJobStepConclusion.success,
)
assertNotNull(
structureService.findValidationStampByName(
project.name,
branch.name,
"build-publishing-to-the-repository"
).getOrNull(),
"Validation stamp has been created"
) { vs ->
val runs = structureService.getValidationRunsForBuildAndValidationStamp(
id,
vs.id,
offset = 0,
count = 1
)
assertEquals(1, runs.size, "One and only one run created")
val run = runs.first()
assertEquals("PASSED", run.lastStatusId)
assertNotNull(runInfoService.getRunInfo(run), "Run info has been set") { info ->
assertEquals(60, info.runTime, "Run time = 60 seconds")
assertEquals("github-workflow", info.sourceType)
assertEquals("uri:job", info.sourceUri)
}
assertNotNull(getProperty(run, ValidationRunGitHubWorkflowJobPropertyType::class.java)) { p ->
assertEquals("build", p.job)
assertEquals("run-name", p.name)
assertEquals(1, p.runNumber)
assertEquals("uri:job", p.url)
assertEquals(false, p.running)
}
}
}
}
}
}
private fun Build.runTest(
runId: Long = 1L,
job: String = "build",
step: String? = "Publishing to the repository",
status: WorkflowJobStepStatus = WorkflowJobStepStatus.completed,
conclusion: WorkflowJobStepConclusion? = WorkflowJobStepConclusion.success,
expectedStep: Boolean = true,
expectedVsName: String = normalizeName("$job-$step"),
expectedStatus: String = "PASSED",
expectedJob: Boolean = false,
expectedJobVsName: String = normalizeName(job),
) {
setupTest(
runId = runId,
job = job,
step = step,
status = status,
conclusion = conclusion,
)
asAdmin {
if (expectedStep) {
// Checks the validation stamp has been created
assertNotNull(
structureService.findValidationStampByName(project.name, branch.name, expectedVsName).getOrNull(),
"Validation stamp has been created"
) { vs ->
// Checks the validation run has been created
val runs = structureService.getValidationRunsForBuildAndValidationStamp(
id,
vs.id,
offset = 0,
count = 1
)
assertNotNull(runs.firstOrNull()) { run ->
assertEquals(expectedStatus, run.lastStatusId)
assertNotNull(runInfoService.getRunInfo(run), "Run info has been set") { info ->
assertEquals(60, info.runTime, "Run time = 60 seconds")
assertEquals("github-workflow", info.sourceType)
assertEquals("uri:job", info.sourceUri)
}
assertNotNull(getProperty(run, ValidationRunGitHubWorkflowJobPropertyType::class.java)) { p ->
assertEquals("build", p.job)
assertEquals("run-name", p.name)
assertEquals(1, p.runNumber)
assertEquals("uri:job", p.url)
assertEquals(false, p.running)
}
}
}
} else {
// Checks the validation stamp has NOT been created
assertNull(
structureService.findValidationStampByName(project.name, branch.name, expectedVsName).getOrNull(),
"Validation stamp has not been created"
)
}
// Checks the validation stamp & run for the job
if (expectedJob) {
assertNotNull(
structureService.findValidationStampByName(project.name, branch.name, expectedJobVsName)
.getOrNull(),
"Validation stamp for the job has been created"
) { vs ->
// Checks the validation run has been created
val runs = structureService.getValidationRunsForBuildAndValidationStamp(
id,
vs.id,
offset = 0,
count = 1
)
assertNotNull(runs.firstOrNull()) { run ->
assertEquals(expectedStatus, run.lastStatusId)
assertNotNull(runInfoService.getRunInfo(run), "Run info has been set") { info ->
assertEquals(60, info.runTime, "Run time = 60 seconds")
assertEquals("github-workflow", info.sourceType)
assertEquals("uri:job", info.sourceUri)
}
assertNotNull(getProperty(run, ValidationRunGitHubWorkflowJobPropertyType::class.java)) { p ->
assertEquals("build", p.job)
assertEquals("run-name", p.name)
assertEquals(1, p.runNumber)
assertEquals("uri:job", p.url)
assertEquals(false, p.running)
}
}
}
} else {
assertNull(
structureService.findValidationStampByName(project.name, branch.name, expectedJobVsName)
.getOrNull(),
"Validation stamp for the job has not been created"
)
}
}
}
private fun Build.setupTest(
runId: Long = 1L,
job: String = "build",
step: String? = "Publishing to the repository",
status: WorkflowJobStepStatus = WorkflowJobStepStatus.completed,
conclusion: WorkflowJobStepConclusion? = WorkflowJobStepConclusion.success,
) {
val ref = Time.now()
asAdmin {
// Git branch at branch level
setProperty(
branch,
GitBranchConfigurationPropertyType::class.java,
GitBranchConfigurationProperty(
branch = "main",
buildCommitLink = null, // Not used
isOverride = false,
buildTagInterval = 0,
)
)
// Run ID for the build
setProperty(
this,
BuildGitHubWorkflowRunPropertyType::class.java,
BuildGitHubWorkflowRunProperty(
workflows = listOf(
BuildGitHubWorkflowRun(
runId = runId,
url = "",
name = "run-name",
runNumber = 1,
running = true,
event = "push",
)
)
)
)
workflowJobProcessingService.setupValidation(
repository = Repository(
name = project.name,
description = null,
htmlUrl = "https://github.com/nemerosa/${project.name}",
owner = Owner(login = "nemerosa"),
),
runId = runId,
runAttempt = 1,
job = job,
jobUrl = "uri:job",
step = step,
status = status,
conclusion = conclusion,
startedAt = ref.minusMinutes(1),
completedAt = ref,
)
}
}
@Test
fun `No job being processed when the workflow is ignored`() {
asAdmin {
project {
branch {
// Job payload on a run ID which was never assigned
val details = workflowJobProcessingService.setupValidation(
repository = Repository(
name = project.name,
description = null,
htmlUrl = "https://github.com/nemerosa/${project.name}",
owner = Owner(login = "nemerosa"),
),
runId = 10L,
runAttempt = 1,
job = "build",
jobUrl = "uri:job",
step = null,
status = WorkflowJobStepStatus.in_progress,
conclusion = null,
startedAt = Time.now(),
completedAt = null,
)
// Not processed
assertEquals(IngestionEventProcessingResult.IGNORED, details.result, "Job not processed")
// No build created
assertEquals(0, structureService.getBuildCount(this), "No build created")
}
}
}
}
} | mit | e032a0d15a2d0fadf27fce53a5fa8594 | 38.596916 | 118 | 0.487539 | 5.993998 | false | true | false | false |
goodwinnk/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/driver/ExtendedJTreePathFinder.kt | 1 | 5904 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.driver
import com.intellij.testGuiFramework.cellReader.ExtendedJTreeCellReader
import com.intellij.testGuiFramework.util.FinderPredicate
import com.intellij.testGuiFramework.util.Predicate
import com.intellij.ui.LoadingNode
import org.fest.swing.cell.JTreeCellReader
import org.fest.swing.exception.LocationUnavailableException
import javax.swing.JTree
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
class ExtendedJTreePathFinder(val jTree: JTree) {
private val cellReader: JTreeCellReader = ExtendedJTreeCellReader()
fun findMatchingPath(pathStrings: List<String>): TreePath =
findMatchingPathByPredicate(Predicate.equality, pathStrings)
fun findMatchingPathWithVersion(pathStrings: List<String>): TreePath =
findMatchingPathByPredicate(Predicate.withVersion, pathStrings)
// this is ex-XPath version
fun findMatchingPathByPredicate(predicate: FinderPredicate, pathStrings: List<String>): TreePath {
val model = jTree.model
if (jTree.isRootVisible) {
val childValue = jTree.value(model.root) ?: ""
if (predicate(pathStrings[0], childValue)) {
if (pathStrings.size == 1) return TreePath(arrayOf<Any>(model.root))
return traverseChildren(jTree, model.root, TreePath(model.root), predicate, pathStrings.drop(1)) ?: throw pathNotFound(pathStrings)
}
else {
pathNotFound(pathStrings)
}
}
return traverseChildren(jTree, model.root, TreePath(model.root), predicate, pathStrings) ?: throw pathNotFound(pathStrings)
}
fun exists(pathStrings: List<String>) =
existsByPredicate(Predicate.equality, pathStrings)
fun existsWithVersion(pathStrings: List<String>) =
existsByPredicate(Predicate.withVersion, pathStrings)
fun existsByPredicate(predicate: FinderPredicate, pathStrings: List<String>): Boolean {
return try {
findMatchingPathByPredicate(
pathStrings = pathStrings,
predicate = predicate
)
true
}
catch (e: Exception) {
false
}
}
fun traverseChildren(jTree: JTree,
node: Any,
pathTree: TreePath,
predicate: FinderPredicate,
pathStrings: List<String>): TreePath? {
val childCount = jTree.model.getChildCount(node)
val order = pathStrings[0].getOrder() ?: 0
val original = pathStrings[0].getWithoutOrder()
var currentOrder = 0
for (childIndex in 0 until childCount) {
val child = jTree.model.getChild(node, childIndex)
if (child is LoadingNode)
throw ExtendedJTreeDriver.LoadingNodeException(node = child, treePath = jTree.getPathToNode(node))
val childValue = jTree.value(child) ?: continue
if (predicate(original, childValue)) {
if (currentOrder == order) {
val newPath = TreePath(arrayOf<Any>(*pathTree.path, child))
return if (pathStrings.size == 1) {
newPath
}
else {
traverseChildren(jTree, child, newPath, predicate, pathStrings.subList(1, pathStrings.size))
}
}
else {
currentOrder++
}
}
}
return null
}
private fun JTree.getPathToNode(node: Any): TreePath {
val treeModel = model as DefaultTreeModel
var path = treeModel.getPathToRoot(node as TreeNode)
if (!isRootVisible) path = path.sliceArray(1 until path.size)
return TreePath(path)
}
private fun JTree.value(modelValue: Any): String? {
return cellReader.valueAt(this, modelValue)?.eraseZeroSpaceSymbols()
}
private fun String.eraseZeroSpaceSymbols(): String = replace("\u200B", "")
// function to work with order - so with lines like `abc(0)`
private val orderPattern = Regex("\\(\\d+\\)")
private fun String.getWithoutOrder(): String =
if (this.hasOrder())
this.dropLast(2 + this.getOrder().toString().length)
else this
private fun String.hasOrder(): Boolean =
orderPattern.find(this)?.value?.isNotEmpty() ?: false
// TODO: may be to throw an exception instead of returning null?
private fun String.getOrder(): Int? {
val find: MatchResult = orderPattern.find(this) ?: return null
return find.value.removeSurrounding("(", ")").toInt()
}
// exception wrappers
private fun pathNotFound(path: List<String>): LocationUnavailableException {
throw LocationUnavailableException("Unable to find path \"$path\"")
}
private fun multipleMatchingNodes(pathString: String, parentText: Any): LocationUnavailableException {
throw LocationUnavailableException(
"There is more than one node with value '$pathString' under \"$parentText\"")
}
fun findPathToNode(node: String) = findPathToNodeByPredicate(node, Predicate.equality)
fun findPathToNodeWithVersion(node: String) = findPathToNodeByPredicate(node, Predicate.withVersion)
fun findPathToNodeByPredicate(node: String, predicate: FinderPredicate): TreePath {
// expandNodes()
// Pause.pause(1000) //Wait for EDT thread to finish expanding
val result: MutableList<String> = mutableListOf()
var currentNode = jTree.model.root as DefaultMutableTreeNode
val e = currentNode.preorderEnumeration()
while (e.hasMoreElements()) {
currentNode = e.nextElement() as DefaultMutableTreeNode
if (predicate(currentNode.toString(), node)) {
break
}
}
result.add(0, currentNode.toString())
while (currentNode.parent != null) {
currentNode = currentNode.parent as DefaultMutableTreeNode
result.add(0, currentNode.toString())
}
return findMatchingPathByPredicate(predicate, result)
}
} | apache-2.0 | 7a5f105e21d59e419e6ef9f4d40eded8 | 36.373418 | 140 | 0.70393 | 4.527607 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/controllers/settings/SettingsFragment.kt | 1 | 12102 | package de.xikolo.controllers.settings
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.Bundle
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.content.ContextCompat
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceCategory
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceManager
import de.psdev.licensesdialog.LicensesDialog
import de.xikolo.App
import de.xikolo.BuildConfig
import de.xikolo.R
import de.xikolo.config.Feature
import de.xikolo.controllers.dialogs.ProgressDialogHorizontal
import de.xikolo.controllers.dialogs.ProgressDialogHorizontalAutoBundle
import de.xikolo.controllers.dialogs.StorageMigrationDialog
import de.xikolo.controllers.dialogs.StorageMigrationDialogAutoBundle
import de.xikolo.controllers.login.LoginActivityAutoBundle
import de.xikolo.download.filedownload.FileDownloadHandler
import de.xikolo.extensions.observe
import de.xikolo.managers.PermissionManager
import de.xikolo.managers.UserManager
import de.xikolo.models.Storage
import de.xikolo.utils.extensions.asStorageType
import de.xikolo.utils.extensions.fileCount
import de.xikolo.utils.extensions.getString
import de.xikolo.utils.extensions.getStringArray
import de.xikolo.utils.extensions.internalStorage
import de.xikolo.utils.extensions.sdcardStorage
import de.xikolo.utils.extensions.showToast
import de.xikolo.utils.extensions.storages
import java.util.Calendar
class SettingsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener {
companion object {
val TAG: String = SettingsFragment::class.java.simpleName
}
private var loginOut: Preference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState ?: Bundle())
App.instance.state.login
.observe(this) {
if (it) {
buildLogoutView(loginOut)
} else {
buildLoginView(loginOut)
}
}
}
override fun onResume() {
preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
refreshPipStatus()
super.onResume()
}
override fun onPause() {
preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
super.onPause()
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key.equals(getString(R.string.preference_storage))) {
val newStoragePreference = sharedPreferences?.getString(getString(R.string.preference_storage), getString(R.string.settings_default_value_storage))!!
findPreference<ListPreference>(getString(R.string.preference_storage))?.summary = newStoragePreference
val newStorageType = newStoragePreference.asStorageType
var oldStorageType = Storage.Type.INTERNAL
var oldStorage = App.instance.internalStorage
if (newStorageType == Storage.Type.INTERNAL) {
oldStorageType = Storage.Type.SDCARD
oldStorage = App.instance.sdcardStorage!!
}
// clean up before
oldStorage.clean()
val fileCount = oldStorage.file.fileCount
if (fileCount > 0) {
val dialog = StorageMigrationDialogAutoBundle.builder(oldStorageType).build()
dialog.listener = object : StorageMigrationDialog.Listener {
override fun onDialogPositiveClick() {
val progressDialog = ProgressDialogHorizontalAutoBundle.builder()
.title(getString(R.string.dialog_storage_migration_title))
.message(getString(R.string.dialog_storage_migration_message))
.build()
progressDialog.max = fileCount
progressDialog.show(fragmentManager!!, ProgressDialogHorizontal.TAG)
val migrationCallback = object : Storage.MigrationCallback {
override fun onProgressChanged(count: Int) {
activity?.runOnUiThread { progressDialog.progress = count }
}
override fun onCompleted(success: Boolean) {
activity?.runOnUiThread {
if (success) {
showToast(R.string.dialog_storage_migration_successful)
} else {
showToast(R.string.error_plain)
}
progressDialog.dismiss()
}
}
}
if (newStorageType == Storage.Type.INTERNAL) {
App.instance.sdcardStorage!!.migrateTo(
App.instance.internalStorage,
migrationCallback
)
} else {
App.instance.internalStorage.migrateTo(
App.instance.sdcardStorage!!,
migrationCallback
)
}
}
}
dialog.show(fragmentManager!!, StorageMigrationDialog.TAG)
}
}
}
override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.settings)
val prefs = PreferenceManager.getDefaultSharedPreferences(activity)
findPreference<ListPreference>(getString(R.string.preference_storage))?.summary =
prefs.getString(
getString(R.string.preference_storage),
getString(R.string.settings_default_value_storage)
)!!
findPreference<ListPreference>(getString(R.string.preference_storage))?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { preference, newValue ->
FileDownloadHandler.isDownloadingAnything { isDownloadingAnything ->
if (isDownloadingAnything) {
showToast(R.string.notification_storage_locked)
} else {
val listener = preference.onPreferenceChangeListener
preference.onPreferenceChangeListener = null
(preference as ListPreference).value = newValue as String
preference.onPreferenceChangeListener = listener
}
}
false
}
if (App.instance.storages.size < 2) {
val general = findPreference<PreferenceCategory>(getString(R.string.preference_category_general))
val storagePref = findPreference<ListPreference>(getString(R.string.preference_storage))
general?.removePreference(storagePref)
}
val pipSettings = findPreference<Preference>(getString(R.string.preference_video_pip))
if (!Feature.PIP) {
val video = findPreference<PreferenceCategory>(getString(R.string.preference_category_video_playback_speed))
video?.removePreference(pipSettings)
} else {
pipSettings?.setOnPreferenceClickListener {
try {
val intent = Intent("android.settings.PICTURE_IN_PICTURE_SETTINGS")
val uri = Uri.fromParts("package", activity?.packageName, null)
intent.data = uri
activity?.startActivity(intent)
} catch (e: RuntimeException) {
PermissionManager.startAppInfo(activity)
}
true
}
refreshPipStatus()
}
// programmatically build info preferences
val info = findPreference<PreferenceCategory>(getString(R.string.preference_category_info))!!
val copyright = Preference(preferenceScreen.context)
copyright.title = String.format(getString(R.string.settings_copyright), Calendar.getInstance().get(Calendar.YEAR))
if (Feature.enabled("url_copyright")) {
copyright.setOnPreferenceClickListener { _ ->
openUrl(App.instance.getString("url_copyright"))
true
}
} else {
copyright.isEnabled = false
}
info.addPreference(copyright)
if (Feature.enabled("legal_links_urls")) {
val titles = App.instance.getStringArray("legal_links_titles")
App.instance.getStringArray("legal_links_urls").forEachIndexed { i, url ->
val pref = Preference(preferenceScreen.context)
pref.title = titles[i]
pref.setOnPreferenceClickListener { _ ->
openUrl(url)
true
}
info.addPreference(pref)
}
}
if (Feature.enabled("url_faq")) {
val faq = Preference(preferenceScreen.context)
faq.title = getString(R.string.settings_title_faq)
faq.setOnPreferenceClickListener { _ ->
openUrl(App.instance.getString("url_faq"))
true
}
info.addPreference(faq)
}
val licenses = Preference(preferenceScreen.context)
licenses.title = getString(R.string.settings_title_licenses)
licenses.summary = getString(R.string.settings_summary_licenses)
licenses.setOnPreferenceClickListener {
LicensesDialog.Builder(activity)
.setNotices(R.raw.notices)
.setTitle(R.string.settings_title_licenses)
.build()
.show()
true
}
info.addPreference(licenses)
val buildVersion = Preference(preferenceScreen.context)
buildVersion.title = getString(R.string.settings_title_build)
buildVersion.summary = getString(R.string.settings_summary_build) + " " + BuildConfig.VERSION_NAME
buildVersion.isEnabled = false
info.addPreference(buildVersion)
loginOut = Preference(preferenceScreen.context)
if (UserManager.isAuthorized) {
buildLogoutView(loginOut)
} else {
buildLoginView(loginOut)
}
info.addPreference(loginOut)
}
private fun refreshPipStatus() {
val pipSettings = findPreference<Preference>(getString(R.string.preference_video_pip))
pipSettings?.let {
if (!PermissionManager.hasPipPermission(context)) {
it.summary = getString(R.string.settings_summary_video_pip_unavailable)
} else {
it.summary = ""
}
}
}
private fun buildLoginView(pref: Preference?) {
if (pref != null) {
pref.title = getString(R.string.login)
pref.setOnPreferenceClickListener { _ ->
val intent = LoginActivityAutoBundle.builder().build(activity!!)
startActivity(intent)
true
}
}
}
private fun buildLogoutView(pref: Preference?) {
if (pref != null) {
pref.title = getString(R.string.logout)
pref.setOnPreferenceClickListener { _ ->
UserManager.logout()
showToast(R.string.toast_successful_logout)
true
}
}
}
private fun openUrl(url: String) {
val customTabsIntent = CustomTabsIntent.Builder()
.setToolbarColor(ContextCompat.getColor(App.instance, R.color.apptheme_primary))
.build()
customTabsIntent.launchUrl(activity!!, Uri.parse(url))
}
}
| bsd-3-clause | d99aca4bada3419554138fac47115f3d | 39.474916 | 161 | 0.602876 | 5.592421 | false | false | false | false |
gameofbombs/kt-postgresql-async | postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/PreparedStatementHolder.kt | 2 | 1834 | /*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares 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.github.mauricio.async.db.postgresql
import com.github.mauricio.async.db.postgresql.messages.backend.PostgreSQLColumnData
class PreparedStatementHolder(val query: String, val statementId: Int) {
val realQuery: String
val paramsCount: Int
init {
val result = StringBuilder(query.length + 16)
var offset = 0
var params = 0
while (offset < query.length) {
val next = query.indexOf('?', offset)
if (next == -1) {
result.append(query.substring(offset))
offset = query.length
} else {
result.append(query.substring(offset, next))
offset = next + 1
if (offset < query.length && query[offset] == '?') {
result.append('?')
offset += 1
} else {
result.append('$')
params += 1
result.append(params.toString())
}
}
}
realQuery = result.toString()
paramsCount = params
}
var prepared: Boolean = false
var columnDatas = listOf<PostgreSQLColumnData>()
}
| apache-2.0 | e6150e233c9c13d4fd3ed0868aa200d5 | 32.309091 | 84 | 0.599345 | 4.603015 | false | false | false | false |
yukuku/androidbible | Alkitab/src/main/java/yuku/alkitab/base/IsiActivity.kt | 1 | 118256 | package yuku.alkitab.base
import android.annotation.TargetApi
import android.app.Activity
import android.app.PendingIntent
import android.content.ActivityNotFoundException
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.Point
import android.net.Uri
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.nfc.NfcAdapter
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.format.DateFormat
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import android.text.style.URLSpan
import android.view.Gravity
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.view.ActionMode
import androidx.appcompat.widget.SwitchCompat
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.core.app.ShareCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.ColorUtils
import androidx.core.text.HtmlCompat
import androidx.core.text.buildSpannedString
import androidx.core.text.inSpans
import androidx.core.util.PatternsCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.analytics.FirebaseAnalytics
import java.util.Calendar
import java.util.Date
import java.util.GregorianCalendar
import java.util.Locale
import kotlin.math.roundToLong
import me.toptas.fancyshowcase.FancyShowCaseView
import me.toptas.fancyshowcase.listener.DismissListener
import org.json.JSONException
import org.json.JSONObject
import yuku.afw.storage.Preferences
import yuku.alkitab.base.ac.GotoActivity
import yuku.alkitab.base.ac.MarkerListActivity
import yuku.alkitab.base.ac.MarkersActivity
import yuku.alkitab.base.ac.NoteActivity
import yuku.alkitab.base.ac.SearchActivity
import yuku.alkitab.base.ac.VersionsActivity
import yuku.alkitab.base.ac.base.BaseLeftDrawerActivity
import yuku.alkitab.base.config.AppConfig
import yuku.alkitab.base.dialog.ProgressMarkListDialog
import yuku.alkitab.base.dialog.ProgressMarkRenameDialog
import yuku.alkitab.base.dialog.TypeBookmarkDialog
import yuku.alkitab.base.dialog.TypeHighlightDialog
import yuku.alkitab.base.dialog.VersesDialog
import yuku.alkitab.base.dialog.XrefDialog
import yuku.alkitab.base.model.MVersion
import yuku.alkitab.base.model.MVersionDb
import yuku.alkitab.base.model.MVersionInternal
import yuku.alkitab.base.settings.SettingsActivity
import yuku.alkitab.base.storage.Prefkey
import yuku.alkitab.base.util.AppLog
import yuku.alkitab.base.util.Appearances
import yuku.alkitab.base.util.BackForwardListController
import yuku.alkitab.base.util.ClipboardUtil
import yuku.alkitab.base.util.CurrentReading
import yuku.alkitab.base.util.ExtensionManager
import yuku.alkitab.base.util.FormattedVerseText
import yuku.alkitab.base.util.History
import yuku.alkitab.base.util.InstallationUtil
import yuku.alkitab.base.util.Jumper
import yuku.alkitab.base.util.LidToAri
import yuku.alkitab.base.util.OtherAppIntegration
import yuku.alkitab.base.util.RequestCodes
import yuku.alkitab.base.util.ShareUrl
import yuku.alkitab.base.util.Sqlitil
import yuku.alkitab.base.util.TargetDecoder
import yuku.alkitab.base.util.safeQuery
import yuku.alkitab.base.verses.VerseAttributeLoader
import yuku.alkitab.base.verses.VersesController
import yuku.alkitab.base.verses.VersesControllerImpl
import yuku.alkitab.base.verses.VersesDataModel
import yuku.alkitab.base.verses.VersesListeners
import yuku.alkitab.base.verses.VersesUiModel
import yuku.alkitab.base.widget.AriParallelClickData
import yuku.alkitab.base.widget.DictionaryLinkInfo
import yuku.alkitab.base.widget.Floater
import yuku.alkitab.base.widget.FormattedTextRenderer
import yuku.alkitab.base.widget.GotoButton
import yuku.alkitab.base.widget.LabeledSplitHandleButton
import yuku.alkitab.base.widget.LeftDrawer
import yuku.alkitab.base.widget.MaterialDialogAdapterHelper
import yuku.alkitab.base.widget.MaterialDialogAdapterHelper.showWithAdapter
import yuku.alkitab.base.widget.ParallelClickData
import yuku.alkitab.base.widget.ReferenceParallelClickData
import yuku.alkitab.base.widget.SplitHandleButton
import yuku.alkitab.base.widget.TextAppearancePanel
import yuku.alkitab.base.widget.TwofingerLinearLayout
import yuku.alkitab.base.widget.VerseInlineLinkSpan
import yuku.alkitab.base.widget.VerseRenderer
import yuku.alkitab.base.widget.VerseRendererHelper
import yuku.alkitab.debug.BuildConfig
import yuku.alkitab.debug.R
import yuku.alkitab.model.Book
import yuku.alkitab.model.Marker
import yuku.alkitab.model.PericopeBlock
import yuku.alkitab.model.SingleChapterVerses
import yuku.alkitab.model.Version
import yuku.alkitab.ribka.RibkaReportActivity
import yuku.alkitab.tracking.Tracker
import yuku.alkitab.util.Ari
import yuku.alkitab.util.IntArrayList
import yuku.devoxx.flowlayout.FlowLayout
private const val TAG = "IsiActivity"
private const val EXTRA_verseUrl = "verseUrl"
private const val INSTANCE_STATE_ari = "ari"
class IsiActivity : BaseLeftDrawerActivity(), LeftDrawer.Text.Listener {
var uncheckVersesWhenActionModeDestroyed = true
var needsRestart = false // whether this activity needs to be restarted
private val bGoto_floaterDrag = object : GotoButton.FloaterDragListener {
val floaterLocationOnScreen = intArrayOf(0, 0)
override fun onFloaterDragStart(screenX: Float, screenY: Float) {
floater.show(activeSplit0.book.bookId, chapter_1)
floater.onDragStart(activeSplit0.version.consecutiveBooks)
}
override fun onFloaterDragMove(screenX: Float, screenY: Float) {
floater.getLocationOnScreen(floaterLocationOnScreen)
floater.onDragMove(screenX - floaterLocationOnScreen[0], screenY - floaterLocationOnScreen[1])
}
override fun onFloaterDragComplete(screenX: Float, screenY: Float) {
floater.hide()
floater.onDragComplete(screenX - floaterLocationOnScreen[0], screenY - floaterLocationOnScreen[1])
}
}
private val floater_listener = Floater.Listener { ari ->
jumpToAri(ari)
}
private val splitRoot_listener = object : TwofingerLinearLayout.Listener {
var startFontSize = 0f
var startDx = Float.MIN_VALUE
var chapterSwipeCellWidth = 0f // initted later
var moreSwipeYAllowed = true // to prevent setting and unsetting fullscreen many times within one gesture
override fun onOnefingerLeft() {
Tracker.trackEvent("text_onefinger_left")
bRight_click()
}
override fun onOnefingerRight() {
Tracker.trackEvent("text_onefinger_right")
bLeft_click()
}
override fun onTwofingerStart() {
chapterSwipeCellWidth = 24f * resources.displayMetrics.density
startFontSize = Preferences.getFloat(Prefkey.ukuranHuruf2, resources.getInteger(R.integer.pref_ukuranHuruf2_default).toFloat())
}
override fun onTwofingerScale(scale: Float) {
var nowFontSize = startFontSize * scale
if (nowFontSize < 2f) nowFontSize = 2f
if (nowFontSize > 42f) nowFontSize = 42f
Preferences.setFloat(Prefkey.ukuranHuruf2, nowFontSize)
applyPreferences()
textAppearancePanel?.displayValues()
}
override fun onTwofingerDragX(dx: Float) {
if (startDx == Float.MIN_VALUE) { // just started
startDx = dx
if (dx < 0) {
bRight_click()
} else {
bLeft_click()
}
} else { // more
// more to the left
while (dx < startDx - chapterSwipeCellWidth) {
startDx -= chapterSwipeCellWidth
bRight_click()
}
while (dx > startDx + chapterSwipeCellWidth) {
startDx += chapterSwipeCellWidth
bLeft_click()
}
}
}
override fun onTwofingerDragY(dy: Float) {
if (!moreSwipeYAllowed) return
if (dy < 0) {
Tracker.trackEvent("text_twofinger_up")
setFullScreen(true)
leftDrawer.handle.setFullScreen(true)
} else {
Tracker.trackEvent("text_twofinger_down")
setFullScreen(false)
leftDrawer.handle.setFullScreen(false)
}
moreSwipeYAllowed = false
}
override fun onTwofingerEnd(mode: TwofingerLinearLayout.Mode?) {
startFontSize = 0f
startDx = Float.MIN_VALUE
moreSwipeYAllowed = true
}
}
private lateinit var drawerLayout: DrawerLayout
lateinit var leftDrawer: LeftDrawer.Text
private lateinit var overlayContainer: FrameLayout
lateinit var root: ViewGroup
lateinit var toolbar: Toolbar
private lateinit var nontoolbar: View
lateinit var lsSplit0: VersesController
lateinit var lsSplit1: VersesController
lateinit var splitRoot: TwofingerLinearLayout
lateinit var splitHandleButton: LabeledSplitHandleButton
private lateinit var bGoto: GotoButton
private lateinit var bLeft: ImageButton
private lateinit var bRight: ImageButton
private lateinit var bVersion: TextView
lateinit var floater: Floater
private lateinit var backForwardListController: BackForwardListController<ImageButton, ImageButton>
private var fullscreenReferenceToast: Toast? = null
private var dataSplit0 = VersesDataModel.EMPTY
set(value) {
field = value
lsSplit0.versesDataModel = value
}
private var dataSplit1 = VersesDataModel.EMPTY
set(value) {
field = value
lsSplit1.versesDataModel = value
}
private var uiSplit0 = VersesUiModel.EMPTY
set(value) {
field = value
lsSplit0.versesUiModel = value
}
private var uiSplit1 = VersesUiModel.EMPTY
set(value) {
field = value
lsSplit1.versesUiModel = value
}
var chapter_1 = 0
private var fullScreen = false
val history get() = History
/**
* Can be null for devices without NfcAdapter
*/
private val nfcAdapter: NfcAdapter? by lazy { NfcAdapter.getDefaultAdapter(applicationContext) }
var actionMode: ActionMode? = null
private var dictionaryMode = false
var textAppearancePanel: TextAppearancePanel? = null
/**
* The following "esvsbasal" thing is a personal thing by yuku that doesn't matter to anyone else.
* Please ignore it and leave it intact.
*/
val hasEsvsbAsal by lazy {
try {
packageManager.getApplicationInfo("yuku.esvsbasal", 0)
true
} catch (e: PackageManager.NameNotFoundException) {
false
}
}
/**
* Container class to make sure that the fields are changed simultaneously.
*/
data class ActiveSplit0(
val mv: MVersion,
val version: Version,
val versionId: String,
val book: Book,
)
private var _activeSplit0: ActiveSplit0? = null
/**
* The primary version, ensured to be always non-null.
*/
var activeSplit0: ActiveSplit0
get() {
val _activeSplit0 = this._activeSplit0
if (_activeSplit0 != null) {
return _activeSplit0
}
val version = S.activeVersion()
val new = ActiveSplit0(
mv = S.activeMVersion(),
version = version,
versionId = S.activeVersionId(),
book = version.firstBook
)
this._activeSplit0 = new
return new
}
set(value) {
_activeSplit0 = value
}
/**
* Container class to make sure that the fields are changed simultaneously.
*/
data class ActiveSplit1(
val mv: MVersion,
val version: Version,
val versionId: String,
)
/**
* The secondary version. Set to null if the secondary version is not opened,
* and to non-null if the secondary version is opened.
*/
var activeSplit1: ActiveSplit1? = null
private val parallelListener: (data: ParallelClickData) -> Unit = { data ->
if (data is ReferenceParallelClickData) {
jumpTo(data.reference)
} else if (data is AriParallelClickData) {
val ari = data.ari
jumpToAri(ari)
}
}
private val dictionaryListener: (DictionaryLinkInfo) -> Unit = fun(data: DictionaryLinkInfo) {
val cr = contentResolver
val uri = Uri.parse("content://org.sabda.kamus.provider/define").buildUpon()
.appendQueryParameter("key", data.key)
.appendQueryParameter("mode", "snippet")
.build()
try {
cr.safeQuery(uri, null, null, null, null) ?: run {
OtherAppIntegration.askToInstallDictionary(this)
return
}
} catch (e: Exception) {
MaterialDialog.Builder(this)
.content(R.string.dict_no_results)
.positiveText(R.string.ok)
.show()
return
}.use { c ->
if (c.count == 0) {
MaterialDialog.Builder(this)
.content(R.string.dict_no_results)
.positiveText(R.string.ok)
.show()
} else {
c.moveToNext()
val rendered = HtmlCompat.fromHtml(c.getString(c.getColumnIndexOrThrow("definition")), HtmlCompat.FROM_HTML_MODE_COMPACT)
val sb = if (rendered is SpannableStringBuilder) rendered else SpannableStringBuilder(rendered)
// remove links
for (span in sb.getSpans(0, sb.length, URLSpan::class.java)) {
sb.removeSpan(span)
}
MaterialDialog.Builder(this)
.title(data.orig_text)
.content(sb)
.positiveText(R.string.dict_open_full)
.onPositive { _, _ ->
val intent = Intent("org.sabda.kamus.action.VIEW")
.putExtra("key", data.key)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
OtherAppIntegration.askToInstallDictionary(this)
}
}
.show()
}
}
}
private val pinDropListener = object : VersesController.PinDropListener() {
override fun onPinDropped(presetId: Int, ari: Int) {
Tracker.trackEvent("pin_drop")
val progressMark = S.getDb().getProgressMarkByPresetId(presetId)
if (progressMark != null) {
progressMark.ari = ari
progressMark.modifyTime = Date()
S.getDb().insertOrUpdateProgressMark(progressMark)
}
App.getLbm().sendBroadcast(Intent(ACTION_ATTRIBUTE_MAP_CHANGED))
}
}
private val splitRoot_globalLayout = object : ViewTreeObserver.OnGlobalLayoutListener {
val lastSize = Point()
override fun onGlobalLayout() {
if (lastSize.x == splitRoot.width && lastSize.y == splitRoot.height) {
return // no need to layout now
}
if (activeSplit1 == null) {
return // we are not splitting
}
configureSplitSizes()
lastSize.x = splitRoot.width
lastSize.y = splitRoot.height
}
}
private val reloadAttributeMapReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
reloadBothAttributeMaps()
}
}
private val needsRestartReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
needsRestart = true
}
}
private val lsSplit0_selectedVerses = object : VersesController.SelectedVersesListener() {
override fun onSomeVersesSelected(verses_1: IntArrayList) {
if (activeSplit1 != null) {
// synchronize the selection with the split view
lsSplit1.checkVerses(verses_1, false)
}
if (actionMode == null) {
actionMode = startSupportActionMode(actionMode_callback)
}
actionMode?.invalidate()
}
override fun onNoVersesSelected() {
if (activeSplit1 != null) {
// synchronize the selection with the split view
lsSplit1.uncheckAllVerses(false)
}
actionMode?.finish()
actionMode = null
}
}
private val lsSplit1_selectedVerses = object : VersesController.SelectedVersesListener() {
override fun onSomeVersesSelected(verses_1: IntArrayList) {
// synchronize the selection with the main view
lsSplit0.checkVerses(verses_1, true)
}
override fun onNoVersesSelected() {
lsSplit0.uncheckAllVerses(true)
}
}
private val lsSplit0_verseScroll = object : VersesController.VerseScrollListener() {
override fun onVerseScroll(isPericope: Boolean, verse_1: Int, prop: Float) {
if (!isPericope && activeSplit1 != null) {
lsSplit1.scrollToVerse(verse_1, prop)
}
}
override fun onScrollToTop() {
if (activeSplit1 != null) {
lsSplit1.scrollToTop()
}
}
}
private val lsSplit1_verseScroll = object : VersesController.VerseScrollListener() {
override fun onVerseScroll(isPericope: Boolean, verse_1: Int, prop: Float) {
if (!isPericope) {
lsSplit0.scrollToVerse(verse_1, prop)
}
}
override fun onScrollToTop() {
lsSplit0.scrollToTop()
}
}
val actionMode_callback = object : ActionMode.Callback {
private val MENU_GROUP_EXTENSIONS = Menu.FIRST + 1
private val MENU_EXTENSIONS_FIRST_ID = 0x1000
val extensions = mutableListOf<ExtensionManager.Info>()
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
menuInflater.inflate(R.menu.context_isi, menu)
AppLog.d(TAG, "@@onCreateActionMode")
if (hasEsvsbAsal) {
val esvsb = menu.findItem(R.id.menuEsvsb)
esvsb?.isVisible = true
}
// show book name and chapter
val reference = activeSplit0.book.reference(chapter_1)
mode.title = reference
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val menuAddBookmark = menu.findItem(R.id.menuAddBookmark)
val menuAddNote = menu.findItem(R.id.menuAddNote)
val menuCompare = menu.findItem(R.id.menuCompare)
val selected = lsSplit0.getCheckedVerses_1()
val single = selected.size() == 1
// For unknown reasons the size of selected can be zero and get(0) causes crash.
// https://console.firebase.google.com/u/0/project/alkitab-host-hrd/crashlytics/app/android:yuku.alkitab/issues/cc11d3466c89303f88b9e27ab3fdd534
if (selected.size() == 0) {
AppLog.e(TAG, "@@onPrepareActionMode checked verses is empty.")
mode.finish()
return true
}
var contiguous = true
if (!single) {
var next = selected.get(0) + 1
var i = 1
val len = selected.size()
while (i < len) {
val cur = selected.get(i)
if (next != cur) {
contiguous = false
break
}
next = cur + 1
i++
}
}
menuAddBookmark.isVisible = contiguous
menuAddNote.isVisible = contiguous
menuCompare.isVisible = single
// just "copy" or ("copy primary" "copy secondary" "copy both")
// same with "share".
val menuCopy = menu.findItem(R.id.menuCopy)
val menuCopySplit0 = menu.findItem(R.id.menuCopySplit0)
val menuCopySplit1 = menu.findItem(R.id.menuCopySplit1)
val menuCopyBothSplits = menu.findItem(R.id.menuCopyBothSplits)
val menuShare = menu.findItem(R.id.menuShare)
val menuShareSplit0 = menu.findItem(R.id.menuShareSplit0)
val menuShareSplit1 = menu.findItem(R.id.menuShareSplit1)
val menuShareBothSplits = menu.findItem(R.id.menuShareBothSplits)
val split = activeSplit1 != null
menuCopy.isVisible = !split
menuCopySplit0.isVisible = split
menuCopySplit1.isVisible = split
menuCopyBothSplits.isVisible = split
menuShare.isVisible = !split
menuShareSplit0.isVisible = split
menuShareSplit1.isVisible = split
menuShareBothSplits.isVisible = split
// show selected verses
if (single) {
mode.setSubtitle(R.string.verse_select_one_verse_selected)
} else {
mode.subtitle = getString(R.string.verse_select_multiple_verse_selected, selected.size().toString())
}
val menuGuide = menu.findItem(R.id.menuGuide)
val menuCommentary = menu.findItem(R.id.menuCommentary)
val menuDictionary = menu.findItem(R.id.menuDictionary)
// force-show these items on sw600dp, otherwise never show
val showAsAction = if (resources.configuration.smallestScreenWidthDp >= 600) MenuItem.SHOW_AS_ACTION_ALWAYS else MenuItem.SHOW_AS_ACTION_NEVER
menuGuide.setShowAsActionFlags(showAsAction)
menuCommentary.setShowAsActionFlags(showAsAction)
menuDictionary.setShowAsActionFlags(showAsAction)
// set visibility according to appconfig
val c = AppConfig.get()
menuGuide.isVisible = c.menuGuide
menuCommentary.isVisible = c.menuCommentary
// do not show dictionary item if not needed because of auto-lookup from
menuDictionary.isVisible = c.menuDictionary && !Preferences.getBoolean(getString(R.string.pref_autoDictionaryAnalyze_key), resources.getBoolean(R.bool.pref_autoDictionaryAnalyze_default))
val menuRibkaReport = menu.findItem(R.id.menuRibkaReport)
menuRibkaReport.isVisible = single && checkRibkaEligibility() != RibkaEligibility.None
// extensions
extensions.clear()
extensions.addAll(ExtensionManager.getExtensions())
menu.removeGroup(MENU_GROUP_EXTENSIONS)
for ((i, extension) in extensions.withIndex()) {
if (single || /* not single */ extension.supportsMultipleVerses) {
menu.add(MENU_GROUP_EXTENSIONS, MENU_EXTENSIONS_FIRST_ID + i, 0, extension.label)
}
}
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
val selected = lsSplit0.getCheckedVerses_1()
if (selected.size() == 0) return true
return when (val itemId = item.itemId) {
R.id.menuCopy, R.id.menuCopySplit0, R.id.menuCopySplit1, R.id.menuCopyBothSplits -> {
// copy, can be multiple verses
val reference = referenceFromSelectedVerses(selected, activeSplit0.book)
val activeSplit1 = activeSplit1
val t = if (itemId == R.id.menuCopy || itemId == R.id.menuCopySplit0 || itemId == R.id.menuCopyBothSplits || activeSplit1 == null) {
prepareTextForCopyShare(selected, reference, false)
} else { // menuCopySplit1, do not use split0 reference
val book = activeSplit1.version.getBook(activeSplit0.book.bookId) ?: activeSplit0.book
prepareTextForCopyShare(selected, referenceFromSelectedVerses(selected, book), true)
}
if (itemId == R.id.menuCopyBothSplits && activeSplit1 != null) {
val book = activeSplit1.version.getBook(activeSplit0.book.bookId) ?: activeSplit0.book
appendSplitTextForCopyShare(book, lsSplit1.getCheckedVerses_1(), t)
}
val textToCopy = t[0]
val textToSubmit = t[1]
ShareUrl.make(this@IsiActivity, !Preferences.getBoolean(getString(R.string.pref_copyWithShareUrl_key), resources.getBoolean(R.bool.pref_copyWithShareUrl_default)), textToSubmit, Ari.encode(activeSplit0.book.bookId, chapter_1, 0), selected, reference.toString(), activeSplit0.version, MVersionDb.presetNameFromVersionId(activeSplit0.versionId), object : ShareUrl.Callback {
override fun onSuccess(shareUrl: String) {
ClipboardUtil.copyToClipboard(textToCopy + "\n\n" + shareUrl)
}
override fun onUserCancel() {
ClipboardUtil.copyToClipboard(textToCopy)
}
override fun onError(e: Exception) {
AppLog.e(TAG, "Error in ShareUrl, copying without shareUrl", e)
ClipboardUtil.copyToClipboard(textToCopy)
}
override fun onFinally() {
lsSplit0.uncheckAllVerses(true)
Snackbar.make(root, getString(R.string.alamat_sudah_disalin, reference), Snackbar.LENGTH_SHORT).show()
mode.finish()
}
})
true
}
R.id.menuShare, R.id.menuShareSplit0, R.id.menuShareSplit1, R.id.menuShareBothSplits -> {
// share, can be multiple verses
val reference = referenceFromSelectedVerses(selected, activeSplit0.book)
val activeSplit1 = activeSplit1
val t = if (itemId == R.id.menuShare || itemId == R.id.menuShareSplit0 || itemId == R.id.menuShareBothSplits || activeSplit1 == null) {
prepareTextForCopyShare(selected, reference, false)
} else { // menuShareSplit1, do not use split0 reference
val book = activeSplit1.version.getBook(activeSplit0.book.bookId) ?: activeSplit0.book
prepareTextForCopyShare(selected, referenceFromSelectedVerses(selected, book), true)
}
if (itemId == R.id.menuShareBothSplits && activeSplit1 != null) {
val book = activeSplit1.version.getBook(activeSplit0.book.bookId) ?: activeSplit0.book
appendSplitTextForCopyShare(book, lsSplit1.getCheckedVerses_1(), t)
}
val textToShare = t[0]
val textToSubmit = t[1]
val intent = ShareCompat.IntentBuilder(this@IsiActivity)
.setType("text/plain")
.setSubject(reference.toString())
.intent
ShareUrl.make(this@IsiActivity, !Preferences.getBoolean(getString(R.string.pref_copyWithShareUrl_key), resources.getBoolean(R.bool.pref_copyWithShareUrl_default)), textToSubmit, Ari.encode(activeSplit0.book.bookId, chapter_1, 0), selected, reference.toString(), activeSplit0.version, MVersionDb.presetNameFromVersionId(activeSplit0.versionId), object : ShareUrl.Callback {
override fun onSuccess(shareUrl: String) {
intent.putExtra(Intent.EXTRA_TEXT, textToShare + "\n\n" + shareUrl)
intent.putExtra(EXTRA_verseUrl, shareUrl)
}
override fun onUserCancel() {
intent.putExtra(Intent.EXTRA_TEXT, textToShare)
}
override fun onError(e: Exception) {
AppLog.e(TAG, "Error in ShareUrl, sharing without shareUrl", e)
intent.putExtra(Intent.EXTRA_TEXT, textToShare)
}
override fun onFinally() {
startActivity(Intent.createChooser(intent, getString(R.string.bagikan_alamat, reference)))
lsSplit0.uncheckAllVerses(true)
mode.finish()
}
})
true
}
R.id.menuCompare -> {
val ari = Ari.encode(activeSplit0.book.bookId, [email protected]_1, selected.get(0))
val dialog = VersesDialog.newCompareInstance(ari)
dialog.listener = object : VersesDialog.VersesDialogListener() {
override fun onComparedVerseSelected(ari: Int, mversion: MVersion) {
loadVersion(mversion)
dialog.dismiss()
}
}
// Allow state loss to prevent
// https://console.firebase.google.com/u/0/project/alkitab-host-hrd/crashlytics/app/android:yuku.alkitab/issues/b80d5209ee90ebd9c5eb30f87f19c85f
val ft = supportFragmentManager.beginTransaction()
ft.add(dialog, "compare_dialog")
ft.commitAllowingStateLoss()
true
}
R.id.menuAddBookmark -> {
// contract: this menu only appears when contiguous verses are selected
if (selected.get(selected.size() - 1) - selected.get(0) != selected.size() - 1) {
throw RuntimeException("Non contiguous verses when adding bookmark: $selected")
}
val ari = Ari.encode(activeSplit0.book.bookId, [email protected]_1, selected.get(0))
val verseCount = selected.size()
// always create a new bookmark
val dialog = TypeBookmarkDialog.NewBookmark(this@IsiActivity, ari, verseCount)
dialog.setListener {
lsSplit0.uncheckAllVerses(true)
reloadBothAttributeMaps()
}
dialog.show()
mode.finish()
true
}
R.id.menuAddNote -> {
// contract: this menu only appears when contiguous verses are selected
if (selected.get(selected.size() - 1) - selected.get(0) != selected.size() - 1) {
throw RuntimeException("Non contiguous verses when adding note: $selected")
}
val ari = Ari.encode(activeSplit0.book.bookId, [email protected]_1, selected.get(0))
val verseCount = selected.size()
// always create a new note
startActivityForResult(NoteActivity.createNewNoteIntent(activeSplit0.version.referenceWithVerseCount(ari, verseCount), ari, verseCount), RequestCodes.FromActivity.EditNote2)
mode.finish()
true
}
R.id.menuAddHighlight -> {
val ariBc = Ari.encode(activeSplit0.book.bookId, [email protected]_1, 0)
val colorRgb = S.getDb().getHighlightColorRgb(ariBc, selected)
val listener = TypeHighlightDialog.Listener {
lsSplit0.uncheckAllVerses(true)
reloadBothAttributeMaps()
}
val reference = referenceFromSelectedVerses(selected, activeSplit0.book)
if (selected.size() == 1) {
val ftr = VerseRenderer.FormattedTextResult()
val ari = Ari.encodeWithBc(ariBc, selected.get(0))
val rawVerseText = activeSplit0.version.loadVerseText(ari) ?: ""
val info = S.getDb().getHighlightColorRgb(ari)
VerseRendererHelper.render(ari = ari, text = rawVerseText, ftr = ftr)
TypeHighlightDialog(this@IsiActivity, ari, listener, colorRgb, info, reference, ftr.result)
} else {
TypeHighlightDialog(this@IsiActivity, ariBc, selected, listener, colorRgb, reference)
}
mode.finish()
true
}
R.id.menuEsvsb -> {
val ari = Ari.encode(activeSplit0.book.bookId, [email protected]_1, selected.get(0))
try {
val intent = Intent("yuku.esvsbasal.action.GOTO")
intent.putExtra("ari", ari)
startActivity(intent)
} catch (e: Exception) {
AppLog.e(TAG, "ESVSB starting", e)
}
true
}
R.id.menuGuide -> {
val ari = Ari.encode(activeSplit0.book.bookId, [email protected]_1, 0)
try {
packageManager.getPackageInfo("org.sabda.pedia", 0)
val intent = Intent("org.sabda.pedia.action.VIEW")
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("ari", ari)
startActivity(intent)
} catch (e: PackageManager.NameNotFoundException) {
OtherAppIntegration.openMarket(this@IsiActivity, "org.sabda.pedia")
}
true
}
R.id.menuCommentary -> {
val ari = Ari.encode(activeSplit0.book.bookId, [email protected]_1, selected.get(0))
try {
packageManager.getPackageInfo("org.sabda.tafsiran", 0)
val intent = Intent("org.sabda.tafsiran.action.VIEW")
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("ari", ari)
startActivity(intent)
} catch (e: PackageManager.NameNotFoundException) {
OtherAppIntegration.openMarket(this@IsiActivity, "org.sabda.tafsiran")
}
true
}
R.id.menuDictionary -> {
val ariBc = Ari.encode(activeSplit0.book.bookId, [email protected]_1, 0)
val aris = HashSet<Int>()
var i = 0
val len = selected.size()
while (i < len) {
val verse_1 = selected.get(i)
val ari = Ari.encodeWithBc(ariBc, verse_1)
aris.add(ari)
i++
}
startDictionaryMode(aris)
true
}
R.id.menuRibkaReport -> {
val ribkaEligibility = checkRibkaEligibility()
if (ribkaEligibility != RibkaEligibility.None) {
val ari = Ari.encode(activeSplit0.book.bookId, [email protected]_1, selected.get(0))
val reference: CharSequence?
val verseText: String?
val versionDescription: String?
if (ribkaEligibility == RibkaEligibility.Main) {
reference = activeSplit0.version.reference(ari)
verseText = activeSplit0.version.loadVerseText(ari)
versionDescription = activeSplit0.mv.description
} else {
reference = activeSplit1?.version?.reference(ari)
verseText = activeSplit1?.version?.loadVerseText(ari)
versionDescription = activeSplit1?.mv?.description
}
if (reference != null && verseText != null) {
startActivity(RibkaReportActivity.createIntent(ari, reference.toString(), verseText, versionDescription))
}
}
true
}
in MENU_EXTENSIONS_FIRST_ID until MENU_EXTENSIONS_FIRST_ID + extensions.size -> {
val extension = extensions[itemId - MENU_EXTENSIONS_FIRST_ID]
val intent = Intent(ExtensionManager.ACTION_SHOW_VERSE_INFO)
intent.component = ComponentName(extension.activityInfo.packageName, extension.activityInfo.name)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
// prepare extra "aris"
val aris = IntArray(selected.size())
val ariBc = Ari.encode(activeSplit0.book.bookId, [email protected]_1, 0)
run {
var i = 0
val len = selected.size()
while (i < len) {
val verse_1 = selected.get(i)
val ari = Ari.encodeWithBc(ariBc, verse_1)
aris[i] = ari
i++
}
}
intent.putExtra("aris", aris)
if (extension.includeVerseText) {
// prepare extra "verseTexts"
val verseTexts = arrayOfNulls<String>(selected.size())
var i = 0
val len = selected.size()
while (i < len) {
val verse_1 = selected.get(i)
val verseText = dataSplit0.getVerseText(verse_1)
if (extension.includeVerseTextFormatting) {
verseTexts[i] = verseText
} else {
verseTexts[i] = FormattedVerseText.removeSpecialCodes(verseText)
}
i++
}
intent.putExtra("verseTexts", verseTexts)
}
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
MaterialDialog.Builder(this@IsiActivity)
.content("Error ANFE starting extension\n\n" + extension.activityInfo.packageName + "/" + extension.activityInfo.name)
.positiveText(R.string.ok)
.show()
}
true
}
else -> false
}
}
/**
* @param t [0] is text to copy, [1] is text to submit
*/
fun appendSplitTextForCopyShare(book: Book?, selectedVerses_1: IntArrayList, t: Array<String>) {
if (book == null) return
val referenceSplit = referenceFromSelectedVerses(selectedVerses_1, book)
val a = prepareTextForCopyShare(selectedVerses_1, referenceSplit, true)
t[0] += "\n\n" + a[0]
t[1] += "\n\n" + a[1]
}
override fun onDestroyActionMode(mode: ActionMode) {
actionMode = null
// FIXME even with this guard, verses are still unchecked when switching version while both Fullscreen and Split is active.
// This guard only fixes unchecking of verses when in fullscreen mode.
if (uncheckVersesWhenActionModeDestroyed) {
lsSplit0.uncheckAllVerses(true)
}
}
}
private val splitHandleButton_listener = object : SplitHandleButton.SplitHandleButtonListener {
var first = 0
var handle = 0
var root = 0
var prop = 0f // proportion from top or left
override fun onHandleDragStart() {
splitRoot.setOnefingerEnabled(false)
if (splitHandleButton.orientation == SplitHandleButton.Orientation.vertical) {
first = splitHandleButton.top
handle = splitHandleButton.height
root = splitRoot.height
} else {
first = splitHandleButton.left
handle = splitHandleButton.width
root = splitRoot.width
}
prop = Float.MIN_VALUE // guard against glitches
}
override fun onHandleDragMoveX(dxSinceLast: Float, dxSinceStart: Float) {
val newW = (first + dxSinceStart).toInt()
val maxW = root - handle
val width = if (newW < 0) 0 else if (newW > maxW) maxW else newW
lsSplit0.setViewLayoutSize(width, ViewGroup.LayoutParams.MATCH_PARENT)
prop = width.toFloat() / maxW
}
override fun onHandleDragMoveY(dySinceLast: Float, dySinceStart: Float) {
val newH = (first + dySinceStart).toInt()
val maxH = root - handle
val height = if (newH < 0) 0 else if (newH > maxH) maxH else newH
lsSplit0.setViewLayoutSize(ViewGroup.LayoutParams.MATCH_PARENT, height)
prop = height.toFloat() / maxH
}
override fun onHandleDragStop() {
splitRoot.setOnefingerEnabled(true)
if (prop != Float.MIN_VALUE) {
Preferences.setFloat(Prefkey.lastSplitProp, prop)
}
}
}
private val splitHandleButton_labelPressed = LabeledSplitHandleButton.ButtonPressListener { which ->
when (which) {
LabeledSplitHandleButton.Button.rotate -> {
closeSplitDisplay()
openSplitDisplay()
}
LabeledSplitHandleButton.Button.start -> openVersionsDialog()
LabeledSplitHandleButton.Button.end -> openSplitVersionsDialog()
else -> throw IllegalStateException("should not happen")
}
}
data class IntentResult(
val ari: Int,
val selectVerse: Boolean = false,
val selectVerseCount: Int = 0,
)
override fun onCreate(savedInstanceState: Bundle?) {
AppLog.d(TAG, "@@onCreate start")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_isi)
AppLog.d(TAG, "@@onCreate setCV")
drawerLayout = findViewById(R.id.drawerLayout)
leftDrawer = findViewById(R.id.left_drawer)
leftDrawer.configure(this, drawerLayout)
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
setDisplayShowTitleEnabled(false)
setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp)
}
nontoolbar = findViewById(R.id.nontoolbar)
bGoto = findViewById(R.id.bGoto)
bLeft = findViewById(R.id.bLeft)
bRight = findViewById(R.id.bRight)
bVersion = findViewById(R.id.bVersion)
overlayContainer = findViewById(R.id.overlayContainer)
root = findViewById(R.id.root)
splitRoot = findViewById(R.id.splitRoot)
splitRoot.viewTreeObserver.addOnGlobalLayoutListener(splitRoot_globalLayout)
splitHandleButton = findViewById(R.id.splitHandleButton)
floater = findViewById(R.id.floater)
// If layout is changed, updateToolbarLocation must be updated as well. This will be called in DEBUG to make sure
// updateToolbarLocation is also updated when layout is updated.
if (BuildConfig.DEBUG) {
if (root.childCount != 2 || root.getChildAt(0).id != R.id.toolbar || root.getChildAt(1).id != R.id.nontoolbar) {
throw RuntimeException("Layout changed and this is no longer compatible with updateToolbarLocation")
}
}
updateToolbarLocation()
splitRoot.setListener(splitRoot_listener)
bGoto.setOnClickListener { bGoto_click() }
bGoto.setOnLongClickListener {
bGoto_longClick()
true
}
bGoto.setFloaterDragListener(bGoto_floaterDrag)
bLeft.setOnClickListener { bLeft_click() }
bRight.setOnClickListener { bRight_click() }
bVersion.setOnClickListener { bVersion_click() }
floater.setListener(floater_listener)
// listeners
lsSplit0 = VersesControllerImpl(
findViewById(R.id.lsSplitView0),
"lsSplit0",
VersesDataModel.EMPTY,
VersesUiModel.EMPTY,
VersesListeners(
AttributeListener(), // have to be distinct from lsSplit1
lsSplit0_selectedVerses,
lsSplit0_verseScroll,
parallelListener,
VerseInlineLinkSpanFactory { lsSplit0 },
dictionaryListener,
pinDropListener
)
)
// additional setup for split1
lsSplit1 = VersesControllerImpl(
findViewById(R.id.lsSplitView1),
"lsSplit1",
VersesDataModel.EMPTY,
VersesUiModel.EMPTY,
VersesListeners(
AttributeListener(), // have to be distinct from lsSplit0
lsSplit1_selectedVerses,
lsSplit1_verseScroll,
parallelListener,
VerseInlineLinkSpanFactory { lsSplit1 },
dictionaryListener,
pinDropListener
)
)
// for splitting
splitHandleButton.setListener(splitHandleButton_listener)
splitHandleButton.setButtonPressListener(splitHandleButton_labelPressed)
if (BuildConfig.DEBUG) {
// Runtime assertions: splitRoot must have 3 children;
// lsSplitView0, splitHandleButton, lsSplitView1 in that order.
if (splitRoot.childCount != 3) throw RuntimeException("splitRoot does not have correct children")
if (splitRoot.getChildAt(0) !== splitRoot.findViewById<View>(R.id.lsSplitView0)) throw RuntimeException("splitRoot does not have correct children")
if (splitRoot.getChildAt(1) !== splitRoot.findViewById<View>(R.id.splitHandleButton)) throw RuntimeException("splitRoot does not have correct children")
if (splitRoot.getChildAt(2) !== splitRoot.findViewById<View>(R.id.lsSplitView1)) throw RuntimeException("splitRoot does not have correct children")
}
initNfcIfAvailable()
backForwardListController = BackForwardListController(
group = findViewById(R.id.panelBackForwardList),
onBackButtonNeedUpdate = { button, ari ->
if (ari == 0) {
button.isEnabled = false
button.alpha = 0.2f
} else {
button.isEnabled = true
button.alpha = 1.0f
}
},
onForwardButtonNeedUpdate = { button, ari ->
if (ari == 0) {
button.isEnabled = false
button.alpha = 0.2f
} else {
button.isEnabled = true
button.alpha = 1.0f
}
},
onButtonPreMove = { controller ->
controller.updateCurrentEntry(getCurrentAriForBackForwardList())
},
onButtonPostMove = { ari ->
jumpToAri(
ari = ari,
updateBackForwardListCurrentEntryWithSource = false,
addHistoryEntry = false,
callAttention = false
)
},
referenceDisplayer = { ari -> activeSplit0.version.reference(ari) }
)
val intentResult = if (savedInstanceState != null) {
val ari = savedInstanceState.getInt(INSTANCE_STATE_ari)
if (ari != 0) {
IntentResult(ari)
} else {
null
}
} else {
extractIntent(intent, "IsiActivity#onCreate")
}
val openingAri: Int
val selectVerse: Boolean
val selectVerseCount: Int
if (intentResult == null) {
// restore the last (version; book; chapter and verse).
val lastBookId = Preferences.getInt(Prefkey.lastBookId, 0)
val lastChapter = Preferences.getInt(Prefkey.lastChapter, 0)
val lastVerse = Preferences.getInt(Prefkey.lastVerse, 0)
openingAri = Ari.encode(lastBookId, lastChapter, lastVerse)
selectVerse = false
selectVerseCount = 1
AppLog.d(TAG, "Going to the last: bookId=$lastBookId chapter=$lastChapter verse=$lastVerse")
} else {
openingAri = intentResult.ari
selectVerse = intentResult.selectVerse
selectVerseCount = intentResult.selectVerseCount
}
// Configure active book
run {
val activeBook = activeSplit0.version.getBook(Ari.toBook(openingAri))
if (activeBook != null) {
activeSplit0 = activeSplit0.copy(book = activeBook)
} else {
// can't load last book or bookId 0
val activeBook2 = activeSplit0.version.firstBook
if (activeBook2 != null) {
activeSplit0 = activeSplit0.copy(book = activeBook2)
} else {
// version failed to load, so books also failed to load. Fallback to internal!
val mv = S.getMVersionInternal()
S.setActiveVersion(mv)
val version = S.activeVersion()
val versionId = S.activeVersionId()
val book = version.firstBook // this is assumed to be never null
activeSplit0 = ActiveSplit0(
mv = mv,
version = version,
versionId = versionId,
book = book
)
}
}
}
// first display of active version
displayActiveVersion()
// load chapter and verse
display(Ari.toChapter(openingAri), Ari.toVerse(openingAri))
if (intentResult != null) { // also add to history if not opening the last seen verse
history.add(openingAri)
}
backForwardListController.newEntry(openingAri)
run {
// load last split version. This must be after load book, chapter, and verse.
val lastSplitVersionId = Preferences.getString(Prefkey.lastSplitVersionId, null)
if (lastSplitVersionId != null) {
val splitOrientation = Preferences.getString(Prefkey.lastSplitOrientation)
if (SplitHandleButton.Orientation.horizontal.name == splitOrientation) {
splitHandleButton.orientation = SplitHandleButton.Orientation.horizontal
} else {
splitHandleButton.orientation = SplitHandleButton.Orientation.vertical
}
val splitMv = S.getVersionFromVersionId(lastSplitVersionId)
val splitMvActual = splitMv ?: S.getMVersionInternal()
if (loadSplitVersion(splitMvActual)) {
openSplitDisplay()
displaySplitFollowingMaster(Ari.toVerse(openingAri))
}
}
}
if (selectVerse) {
for (i in 0 until selectVerseCount) {
val verse_1 = Ari.toVerse(openingAri) + i
callAttentionForVerseToBothSplits(verse_1)
}
}
App.getLbm().registerReceiver(reloadAttributeMapReceiver, IntentFilter(ACTION_ATTRIBUTE_MAP_CHANGED))
App.getLbm().registerReceiver(needsRestartReceiver, IntentFilter(ACTION_NEEDS_RESTART))
AppLog.d(TAG, "@@onCreate end")
}
private fun calculateTextSizeMult(versionId: String?): Float {
return if (versionId == null) 1f else S.getDb().getPerVersionSettings(versionId).fontSizeMultiplier
}
private fun callAttentionForVerseToBothSplits(verse_1: Int) {
lsSplit0.callAttentionForVerse(verse_1)
lsSplit1.callAttentionForVerse(verse_1)
}
override fun onDestroy() {
super.onDestroy()
App.getLbm().unregisterReceiver(reloadAttributeMapReceiver)
App.getLbm().unregisterReceiver(needsRestartReceiver)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(INSTANCE_STATE_ari, Ari.encode(activeSplit0.book.bookId, chapter_1, getVerse_1BasedOnScrolls()))
}
/**
* @return non-null if the intent is handled by any of the intent handler (e.g. nfc or VIEW)
*/
private fun extractIntent(intent: Intent, via: String): IntentResult? {
dumpIntent(intent, via)
return tryGetIntentResultFromBeam(intent)
?: tryGetIntentResultFromView(intent)
}
/**
* did we get here from VIEW intent?
*/
private fun tryGetIntentResultFromView(intent: Intent): IntentResult? {
if (intent.action != "yuku.alkitab.action.VIEW") return null
val selectVerse = intent.getBooleanExtra("selectVerse", false)
val selectVerseCount = intent.getIntExtra("selectVerseCount", 1)
return when {
intent.hasExtra("ari") -> {
val ari = intent.getIntExtra("ari", 0)
if (ari != 0) {
IntentResult(ari, selectVerse, selectVerseCount)
} else {
null
}
}
intent.hasExtra("lid") -> {
val lid = intent.getIntExtra("lid", 0)
val ari = LidToAri.lidToAri(lid)
if (ari != 0) {
jumpToAri(ari)
IntentResult(ari, selectVerse, selectVerseCount)
} else {
null
}
}
else -> null
}
}
@Suppress("DEPRECATION")
private fun initNfcIfAvailable() {
nfcAdapter?.setNdefPushMessageCallback({
val obj = JSONObject()
obj.put("ari", Ari.encode(activeSplit0.book.bookId, [email protected]_1, getVerse_1BasedOnScrolls()))
val payload = obj.toString().toByteArray()
val record = NdefRecord(NdefRecord.TNF_MIME_MEDIA, "application/vnd.yuku.alkitab.nfc.beam".toByteArray(), ByteArray(0), payload)
NdefMessage(arrayOf(record, NdefRecord.createApplicationRecord(packageName)))
}, this)
}
private fun getCurrentAriForBackForwardList(): Int {
val bookId = activeSplit0.book.bookId
val chapter_1 = chapter_1
val verse_1 = getVerse_1BasedOnScrolls()
return Ari.encode(bookId, chapter_1, verse_1)
}
private fun updateBackForwardListCurrentEntry(ari: Int = getCurrentAriForBackForwardList()) {
if (ari != 0) {
backForwardListController.updateCurrentEntry(ari)
}
}
/**
* Try to get the verse_1 based on split0, when failed, try to get it from the split1.
*/
private fun getVerse_1BasedOnScrolls(): Int {
val split0verse_1 = lsSplit0.getVerse_1BasedOnScroll()
if (split0verse_1 != 0) return split0verse_1
val split1verse_1 = lsSplit1.getVerse_1BasedOnScroll()
if (split1verse_1 != 0) return split1verse_1
return 1 // default value for verse_1
}
override fun onPause() {
super.onPause()
disableNfcForegroundDispatchIfAvailable()
}
private fun disableNfcForegroundDispatchIfAvailable() {
val _nfcAdapter = this.nfcAdapter
if (_nfcAdapter != null) {
try {
_nfcAdapter.disableForegroundDispatch(this)
} catch (e: IllegalStateException) {
AppLog.e(TAG, "sometimes this happens.", e)
}
}
}
override fun onResume() {
super.onResume()
enableNfcForegroundDispatchIfAvailable()
}
private fun enableNfcForegroundDispatchIfAvailable() {
nfcAdapter?.let { nfcAdapter ->
val pendingIntent = PendingIntent.getActivity(this, 0, Intent(this, IsiActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_IMMUTABLE)
val ndef = IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED)
ndef.addDataType("application/vnd.yuku.alkitab.nfc.beam")
nfcAdapter.enableForegroundDispatch(this, pendingIntent, arrayOf(ndef), null)
}
}
private fun tryGetIntentResultFromBeam(intent: Intent): IntentResult? {
val action = intent.action
if (action != NfcAdapter.ACTION_NDEF_DISCOVERED) return null
val rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
// only one message sent during the beam
if (rawMsgs == null || rawMsgs.isEmpty()) return null
val msg = rawMsgs[0] as NdefMessage
// record 0 contains the MIME type, record 1 is the AAR, if present
val records = msg.records
if (records.isEmpty()) return null
val json = String(records[0].payload)
return try {
val obj = JSONObject(json)
val ari = obj.optInt("ari", -1)
if (ari == -1) null else IntentResult(ari)
} catch (e: JSONException) {
AppLog.e(TAG, "Malformed json from nfc", e)
null
}
}
fun loadVersion(mv: MVersion) {
try {
val version = mv.version ?: throw RuntimeException() // caught below
// we already have some other version loaded, so make the new version open the same book
val bookId = activeSplit0.book.bookId
// Set globally
S.setActiveVersion(mv)
// If a book is not found, get any book
val book = version.getBook(bookId) ?: version.firstBook
activeSplit0 = ActiveSplit0(
mv = mv,
version = version,
versionId = S.activeVersionId(),
book = book
)
displayActiveVersion()
display(chapter_1, getVerse_1BasedOnScrolls(), false)
App.getLbm().sendBroadcast(Intent(ACTION_ACTIVE_VERSION_CHANGED))
} catch (e: Throwable) { // so we don't crash on the beginning of the app
AppLog.e(TAG, "Error opening main version", e)
MaterialDialog.Builder(this)
.content(getString(R.string.version_error_opening, mv.longName))
.positiveText(R.string.ok)
.show()
}
}
private fun displayActiveVersion() {
bVersion.text = activeSplit0.version.initials
splitHandleButton.setLabel1("\u25b2 " + activeSplit0.version.initials)
}
private fun loadSplitVersion(mv: MVersion): Boolean {
try {
val version = mv.version ?: throw RuntimeException() // caught below
activeSplit1 = ActiveSplit1(mv, version, mv.versionId)
splitHandleButton.setLabel2(version.initials + " \u25bc")
configureTextAppearancePanelForSplitVersion()
return true
} catch (e: Throwable) { // so we don't crash on the beginning of the app
AppLog.e(TAG, "Error opening split version", e)
MaterialDialog.Builder(this@IsiActivity)
.content(getString(R.string.version_error_opening, mv.longName))
.positiveText(R.string.ok)
.show()
return false
}
}
private fun configureTextAppearancePanelForSplitVersion() {
textAppearancePanel?.let { textAppearancePanel ->
val activeSplit1 = activeSplit1
if (activeSplit1 == null) {
textAppearancePanel.clearSplitVersion()
} else {
textAppearancePanel.setSplitVersion(activeSplit1.versionId, activeSplit1.version.longName)
}
}
}
private fun consumeKey(keyCode: Int): Boolean {
// Handle dpad left/right, this always goes to prev/next chapter.
if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
bLeft_click()
return true
} else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
bRight_click()
return true
}
// Handle volume up/down, the effect changes based on preferences.
val pressResult = consumeUpDownKey(lsSplit0, keyCode)
if (pressResult is VersesController.PressResult.Left) {
bLeft_click()
return true
}
if (pressResult is VersesController.PressResult.Right) {
bRight_click()
return true
}
if (pressResult is VersesController.PressResult.Consumed) {
if (activeSplit1 != null) {
lsSplit1.scrollToVerse(pressResult.targetVerse_1)
}
return true
}
return false
}
private fun consumeUpDownKey(versesController: VersesController, originalKeyCode: Int): VersesController.PressResult {
var keyCode = originalKeyCode
val volumeButtonsForNavigation = Preferences.getString(R.string.pref_volumeButtonNavigation_key, R.string.pref_volumeButtonNavigation_default)
if (volumeButtonsForNavigation == "pasal" /* chapter */) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
return VersesController.PressResult.Left
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
return VersesController.PressResult.Right
}
} else if (volumeButtonsForNavigation == "ayat" /* verse */) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) keyCode = KeyEvent.KEYCODE_DPAD_DOWN
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) keyCode = KeyEvent.KEYCODE_DPAD_UP
} else if (volumeButtonsForNavigation == "page") {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
return versesController.pageDown()
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
return versesController.pageUp()
}
}
if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
return versesController.verseDown()
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
return versesController.verseUp()
}
return VersesController.PressResult.Nop
}
/**
* Jump to a given verse reference in string format.
*
* If successful, the destination will be added to history.
*/
private fun jumpTo(reference: String) {
if (reference.trim().isEmpty()) return
AppLog.d(TAG, "going to jump to $reference")
val jumper = Jumper(reference)
if (!jumper.parseSucceeded) {
MaterialDialog.Builder(this)
.content(R.string.alamat_tidak_sah_alamat, reference)
.positiveText(R.string.ok)
.show()
return
}
val bookId = jumper.getBookId(activeSplit0.version.consecutiveBooks)
val selected = if (bookId != -1) {
activeSplit0.version.getBook(bookId) ?: activeSplit0.book // not avail, just fallback
} else {
activeSplit0.book
}
updateBackForwardListCurrentEntry()
// set book
activeSplit0 = activeSplit0.copy(book = selected)
val chapter = jumper.chapter
val verse = jumper.verse
val ari_cv = if (chapter == -1 && verse == -1) {
display(1, 1)
} else {
display(chapter, verse)
}
// Add target ari to history
val target_ari = Ari.encode(selected.bookId, ari_cv)
history.add(target_ari)
backForwardListController.newEntry(target_ari)
}
/**
* Jump to a given ari.
*
* If successful, the destination will be added to history.
*/
fun jumpToAri(
ari: Int,
updateBackForwardListCurrentEntryWithSource: Boolean = true,
addHistoryEntry: Boolean = true,
callAttention: Boolean = true,
) {
if (ari == 0) return
val bookId = Ari.toBook(ari)
val book = activeSplit0.version.getBook(bookId)
if (book == null) {
AppLog.w(TAG, "bookId=$bookId not found for ari=$ari")
return
}
if (updateBackForwardListCurrentEntryWithSource) {
updateBackForwardListCurrentEntry()
}
activeSplit0 = activeSplit0.copy(book = book)
val ari_cv = display(Ari.toChapter(ari), Ari.toVerse(ari))
// Add target ari to history
if (addHistoryEntry) {
history.add(ari)
backForwardListController.newEntry(ari)
}
// call attention to the verse only if the displayed verse is equal to the requested verse
if (callAttention && ari == Ari.encode(activeSplit0.book.bookId, ari_cv)) {
callAttentionForVerseToBothSplits(Ari.toVerse(ari))
}
}
fun referenceFromSelectedVerses(selectedVerses: IntArrayList, book: Book): CharSequence {
return when (selectedVerses.size()) {
// should not be possible. So we don't do anything.
0 -> book.reference(this.chapter_1)
1 -> book.reference(this.chapter_1, selectedVerses.get(0))
else -> book.reference(this.chapter_1, selectedVerses)
}
}
/**
* Construct text for copying or sharing (in plain text).
*
* @param isSplitVersion whether take the verse text from the main or from the split version.
* @return [0] text for copying/sharing, [1] text to be submitted to the share url service
*/
fun prepareTextForCopyShare(selectedVerses_1: IntArrayList, reference: CharSequence, isSplitVersion: Boolean): Array<String> {
val res0 = StringBuilder()
val res1 = StringBuilder()
res0.append(reference)
if (Preferences.getBoolean(getString(R.string.pref_copyWithVersionName_key), resources.getBoolean(R.bool.pref_copyWithVersionName_default))) {
// Fallback to primary version for safety
val version = if (isSplitVersion) activeSplit1?.version ?: activeSplit0.version else activeSplit0.version
val versionShortName = version.shortName
if (versionShortName != null) {
res0.append(" (").append(versionShortName).append(")")
}
}
if (Preferences.getBoolean(getString(R.string.pref_copyWithVerseNumbers_key), false) && selectedVerses_1.size() > 1) {
res0.append('\n')
// append each selected verse with verse number prepended
var i = 0
val len = selectedVerses_1.size()
while (i < len) {
val verse_1 = selectedVerses_1.get(i)
val verseText = if (isSplitVersion) dataSplit1.getVerseText(verse_1) else dataSplit0.getVerseText(verse_1)
if (verseText != null) {
val verseTextPlain = FormattedVerseText.removeSpecialCodes(verseText)
res0.append(verse_1)
res1.append(verse_1)
res0.append(' ')
res1.append(' ')
res0.append(verseTextPlain)
res1.append(verseText)
if (i != len - 1) {
res0.append('\n')
res1.append('\n')
}
}
i++
}
} else {
res0.append(" ")
// append each selected verse without verse number prepended
for (i in 0 until selectedVerses_1.size()) {
val verse_1 = selectedVerses_1.get(i)
val verseText = if (isSplitVersion) dataSplit1.getVerseText(verse_1) else dataSplit0.getVerseText(verse_1)
if (verseText != null) {
val verseTextPlain = FormattedVerseText.removeSpecialCodes(verseText)
if (i != 0) {
res0.append('\n')
res1.append('\n')
}
res0.append(verseTextPlain)
res1.append(verseText)
}
}
}
return arrayOf(res0.toString(), res1.toString())
}
fun applyPreferences() {
// make sure S applied variables are set first
S.recalculateAppliedValuesBasedOnPreferences()
// apply background color, and clear window background to prevent overdraw
window.setBackgroundDrawableResource(android.R.color.transparent)
val backgroundColor = S.applied().backgroundColor
root.setBackgroundColor(backgroundColor)
// scrollbar must be visible!
val thumb = if (ColorUtils.calculateLuminance(backgroundColor) > 0.5) {
ActivityCompat.getDrawable(this, R.drawable.scrollbar_handle_material_for_light)
} else {
ActivityCompat.getDrawable(this, R.drawable.scrollbar_handle_material_for_dark)
}
if (thumb != null) {
lsSplit0.setViewScrollbarThumb(thumb)
lsSplit1.setViewScrollbarThumb(thumb)
}
// necessary
val isVerseNumberShown = Preferences.getBoolean(R.string.pref_verseNumberIsShown_key, R.bool.pref_verseNumberIsShown_default)
uiSplit0 = uiSplit0.copy(
textSizeMult = calculateTextSizeMult(activeSplit0.versionId),
isVerseNumberShown = isVerseNumberShown
)
uiSplit1 = uiSplit1.copy(
textSizeMult = calculateTextSizeMult(activeSplit1?.versionId),
isVerseNumberShown = isVerseNumberShown
)
lsSplit0.setViewPadding(SettingsActivity.getPaddingBasedOnPreferences())
lsSplit1.setViewPadding(SettingsActivity.getPaddingBasedOnPreferences())
}
override fun onStop() {
super.onStop()
Preferences.hold()
try {
Preferences.setInt(Prefkey.lastBookId, activeSplit0.book.bookId)
Preferences.setInt(Prefkey.lastChapter, chapter_1)
Preferences.setInt(Prefkey.lastVerse, getVerse_1BasedOnScrolls())
Preferences.setString(Prefkey.lastVersionId, activeSplit0.versionId)
val activeSplit1 = activeSplit1
if (activeSplit1 == null) {
Preferences.remove(Prefkey.lastSplitVersionId)
} else {
Preferences.setString(Prefkey.lastSplitVersionId, activeSplit1.versionId)
Preferences.setString(Prefkey.lastSplitOrientation, splitHandleButton.orientation.name)
}
} finally {
Preferences.unhold()
}
history.save()
}
override fun onStart() {
super.onStart()
applyPreferences()
window.decorView.keepScreenOn = Preferences.getBoolean(R.string.pref_keepScreenOn_key, R.bool.pref_keepScreenOn_default)
if (needsRestart) {
needsRestart = false
recreate()
}
}
override fun onBackPressed() {
when {
textAppearancePanel != null -> {
textAppearancePanel?.hide()
textAppearancePanel = null
}
fullScreen -> {
setFullScreen(false)
leftDrawer.handle.setFullScreen(false)
}
else -> {
super.onBackPressed()
}
}
}
private fun bGoto_click() {
Tracker.trackEvent("nav_goto_button_click")
val r = {
startActivityForResult(GotoActivity.createIntent(activeSplit0.book.bookId, this.chapter_1, getVerse_1BasedOnScrolls()), RequestCodes.FromActivity.Goto)
}
if (!Preferences.getBoolean(Prefkey.history_button_understood, false) && history.size > 0) {
FancyShowCaseView.Builder(this)
.focusOn(bGoto)
.title(getString(R.string.goto_button_history_tip))
.enableAutoTextPosition()
.dismissListener(object : DismissListener {
override fun onDismiss(id: String?) {
Preferences.setBoolean(Prefkey.history_button_understood, true)
r()
}
override fun onSkipped(id: String?) = Unit
})
.closeOnTouch(true)
.build()
.show()
} else {
r()
}
}
private fun bGoto_longClick() {
Tracker.trackEvent("nav_goto_button_long_click")
if (history.size > 0) {
MaterialDialog.Builder(this).showWithAdapter(HistoryAdapter())
Preferences.setBoolean(Prefkey.history_button_understood, true)
} else {
Snackbar.make(root, R.string.recentverses_not_available, Snackbar.LENGTH_SHORT).show()
}
}
class HistoryEntryHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val text1: TextView = itemView.findViewById(android.R.id.text1)
}
inner class HistoryAdapter : MaterialDialogAdapterHelper.Adapter() {
private val timeFormat = DateFormat.getTimeFormat(this@IsiActivity)
private val mediumDateFormat = DateFormat.getMediumDateFormat(this@IsiActivity)
private val thisCreatorId = InstallationUtil.getInstallationId()
private var defaultTextColor = 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val textView = layoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false) as TextView
defaultTextColor = textView.currentTextColor
return HistoryEntryHolder(textView)
}
override fun onBindViewHolder(_holder_: RecyclerView.ViewHolder, position: Int) {
val holder = _holder_ as HistoryEntryHolder
run {
val entry = history.getEntry(position)
holder.text1.text = buildSpannedString {
append(activeSplit0.version.reference(entry.ari))
append(" ")
inSpans(ForegroundColorSpan(0xffaaaaaaL.toInt()), RelativeSizeSpan(0.7f)) {
this.append(formatTimestamp(entry.timestamp))
}
}
if (thisCreatorId == entry.creator_id) {
holder.text1.setTextColor(defaultTextColor)
} else {
holder.text1.setTextColor(ResourcesCompat.getColor(resources, R.color.escape, theme))
}
}
holder.itemView.setOnClickListener {
dismissDialog()
jumpToAri(history.getEntry(holder.bindingAdapterPosition).ari)
}
}
private fun formatTimestamp(timestamp: Long): CharSequence {
run {
val now = System.currentTimeMillis()
val delta = now - timestamp
if (delta <= 200000) {
return getString(R.string.recentverses_just_now)
} else if (delta <= 3600000) {
return getString(R.string.recentverses_min_plural_ago, (delta / 60000.0).roundToLong().toString())
}
}
run {
val now = GregorianCalendar.getInstance()
val that = GregorianCalendar.getInstance()
that.timeInMillis = timestamp
if (now.get(Calendar.YEAR) == that.get(Calendar.YEAR)) {
if (now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR)) {
return getString(R.string.recentverses_today_time, timeFormat.format(that.time))
} else if (now.get(Calendar.DAY_OF_YEAR) == that.get(Calendar.DAY_OF_YEAR) + 1) {
return getString(R.string.recentverses_yesterday_time, timeFormat.format(that.time))
}
}
return mediumDateFormat.format(that.time)
}
}
override fun getItemCount(): Int {
return history.size
}
}
private fun buildMenu(menu: Menu) {
menu.clear()
menuInflater.inflate(R.menu.activity_isi, menu)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
buildMenu(menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
if (menu != null) {
buildMenu(menu)
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
leftDrawer.toggleDrawer()
return true
}
R.id.menuSearch -> {
Tracker.trackEvent("nav_search_click")
menuSearch_click()
return true
}
}
return super.onOptionsItemSelected(item)
}
@TargetApi(19)
fun setFullScreen(yes: Boolean) {
if (fullScreen == yes) return // no change
val decorView = window.decorView
if (yes) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
supportActionBar?.hide()
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
supportActionBar?.show()
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
}
fullScreen = yes
updateToolbarLocation()
}
private fun updateToolbarLocation() {
// 3 kinds of possible layout:
// - fullscreen
// - not fullscreen, toolbar at bottom
// - not fullscreen, toolbar at top
// root contains exactly 2 children: toolbar and nontoolbar.
// Need to move toolbar and nontoolbar in order to accomplish this.
if (!fullScreen) {
root.removeView(toolbar)
root.removeView(nontoolbar)
if (Preferences.getBoolean(R.string.pref_bottomToolbarOnText_key, R.bool.pref_bottomToolbarOnText_default)) {
root.addView(nontoolbar)
root.addView(toolbar)
} else {
root.addView(toolbar)
root.addView(nontoolbar)
}
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus && fullScreen) {
val decorView = window.decorView
decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE
}
}
private fun setShowTextAppearancePanel(yes: Boolean) {
if (!yes) {
textAppearancePanel?.hide()
textAppearancePanel = null
return
}
if (textAppearancePanel == null) { // not showing yet
textAppearancePanel = TextAppearancePanel(
this,
overlayContainer,
object : TextAppearancePanel.Listener {
override fun onValueChanged() {
applyPreferences()
}
override fun onCloseButtonClick() {
textAppearancePanel?.hide()
textAppearancePanel = null
}
},
RequestCodes.FromActivity.TextAppearanceGetFonts,
RequestCodes.FromActivity.TextAppearanceCustomColors
)
configureTextAppearancePanelForSplitVersion()
textAppearancePanel?.show()
}
}
private fun setNightMode(yes: Boolean) {
val previousValue = Preferences.getBoolean(Prefkey.is_night_mode, false)
if (previousValue == yes) return
Preferences.setBoolean(Prefkey.is_night_mode, yes)
applyPreferences()
applyNightModeColors()
textAppearancePanel?.displayValues()
App.getLbm().sendBroadcast(Intent(ACTION_NIGHT_MODE_CHANGED))
}
private fun setFollowSystemTheme(yes: Boolean, cNightMode: SwitchCompat) {
val previousValue = Preferences.getBoolean(Prefkey.follow_system_theme, true)
if (previousValue == yes) return
Preferences.setBoolean(Prefkey.follow_system_theme, yes)
if (yes) {
val systemTheme = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
cNightMode.isChecked = systemTheme == Configuration.UI_MODE_NIGHT_YES
setNightMode(systemTheme == Configuration.UI_MODE_NIGHT_YES)
}
}
private fun openVersionsDialog() {
// If there is no db versions, immediately open manage version screen.
if (S.getDb().listAllVersions().isEmpty()) {
startActivity(VersionsActivity.createIntent())
return
}
S.openVersionsDialog(this, false, activeSplit0.versionId) { mv ->
trackVersionSelect(mv, false)
loadVersion(mv)
}
}
private fun openSplitVersionsDialog() {
S.openVersionsDialog(this, true, activeSplit1?.versionId) { mv ->
if (mv == null) { // closing split version
disableSplitVersion()
} else {
trackVersionSelect(mv, true)
val ok = loadSplitVersion(mv)
if (ok) {
openSplitDisplay()
displaySplitFollowingMaster(getVerse_1BasedOnScrolls())
} else {
disableSplitVersion()
}
}
}
}
private fun trackVersionSelect(mv: MVersion?, isSplit: Boolean) {
if (mv is MVersionDb) {
val preset_name = mv.preset_name
Tracker.trackEvent("versions_dialog_select", "is_split", isSplit, FirebaseAnalytics.Param.ITEM_NAME, preset_name ?: "no_preset_name")
} else if (mv is MVersionInternal) {
Tracker.trackEvent("versions_dialog_select", "is_split", isSplit, FirebaseAnalytics.Param.ITEM_NAME, "internal")
}
}
private fun disableSplitVersion() {
activeSplit1 = null
closeSplitDisplay()
configureTextAppearancePanelForSplitVersion()
}
private fun openSplitDisplay() {
if (splitHandleButton.visibility == View.VISIBLE) {
return // it's already split, no need to do anything
}
configureSplitSizes()
bVersion.visibility = View.GONE
actionMode?.invalidate()
leftDrawer.handle.setSplitVersion(true)
}
fun configureSplitSizes() {
splitHandleButton.visibility = View.VISIBLE
var prop = Preferences.getFloat(Prefkey.lastSplitProp, Float.MIN_VALUE)
if (prop == Float.MIN_VALUE || prop < 0f || prop > 1f) {
prop = 0.5f // guard against invalid values
}
val splitHandleThickness = resources.getDimensionPixelSize(R.dimen.split_handle_thickness)
if (splitHandleButton.orientation == SplitHandleButton.Orientation.vertical) {
splitRoot.orientation = LinearLayout.VERTICAL
val totalHeight = splitRoot.height
val masterHeight = ((totalHeight - splitHandleThickness) * prop).toInt()
run {
// divide the screen space
lsSplit0.setViewLayoutSize(ViewGroup.LayoutParams.MATCH_PARENT, masterHeight)
}
// no need to set height, because it has been set to match_parent, so it takes the remaining space.
lsSplit1.setViewVisibility(View.VISIBLE)
run {
val lp = splitHandleButton.layoutParams
lp.width = ViewGroup.LayoutParams.MATCH_PARENT
lp.height = splitHandleThickness
splitHandleButton.layoutParams = lp
}
} else {
splitRoot.orientation = LinearLayout.HORIZONTAL
val totalWidth = splitRoot.width
val masterWidth = ((totalWidth - splitHandleThickness) * prop).toInt()
run {
// divide the screen space
lsSplit0.setViewLayoutSize(masterWidth, ViewGroup.LayoutParams.MATCH_PARENT)
}
// no need to set width, because it has been set to match_parent, so it takes the remaining space.
lsSplit1.setViewVisibility(View.VISIBLE)
run {
val lp = splitHandleButton.layoutParams
lp.width = splitHandleThickness
lp.height = ViewGroup.LayoutParams.MATCH_PARENT
splitHandleButton.layoutParams = lp
}
}
}
private fun closeSplitDisplay() {
if (splitHandleButton.visibility == View.GONE) {
return // it's already not split, no need to do anything
}
splitHandleButton.visibility = View.GONE
lsSplit1.setViewVisibility(View.GONE)
run { lsSplit0.setViewLayoutSize(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) }
bVersion.visibility = View.VISIBLE
actionMode?.invalidate()
leftDrawer.handle.setSplitVersion(false)
}
private fun menuSearch_click() {
startActivity(SearchActivity.createIntent(activeSplit0.book.bookId))
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == RequestCodes.FromActivity.Goto && resultCode == Activity.RESULT_OK && data != null) {
val result = GotoActivity.obtainResult(data)
if (result != null) {
val ari_cv: Int
updateBackForwardListCurrentEntry()
if (result.bookId == -1) {
// stay on the same book
ari_cv = display(result.chapter_1, result.verse_1)
// call attention to the verse only if the displayed verse is equal to the requested verse
if (Ari.encode(0, result.chapter_1, result.verse_1) == ari_cv) {
callAttentionForVerseToBothSplits(result.verse_1)
}
} else {
// change book
val book = activeSplit0.version.getBook(result.bookId)
if (book != null) {
activeSplit0 = activeSplit0.copy(book = book)
} else { // no book, just chapter and verse.
result.bookId = activeSplit0.book.bookId
}
ari_cv = display(result.chapter_1, result.verse_1)
// select the verse only if the displayed verse is equal to the requested verse
if (Ari.encode(result.bookId, result.chapter_1, result.verse_1) == Ari.encode(activeSplit0.book.bookId, ari_cv)) {
callAttentionForVerseToBothSplits(result.verse_1)
}
}
val target_ari = if (result.verse_1 == 0 && Ari.toVerse(ari_cv) == 1) {
// verse 0 requested, but display method causes it to show verse_1 1.
// However, we want to store verse_1 0 on the history.
Ari.encode(activeSplit0.book.bookId, Ari.toChapter(ari_cv), 0)
} else {
Ari.encode(activeSplit0.book.bookId, ari_cv)
}
// Add target ari to history
history.add(target_ari)
backForwardListController.newEntry(target_ari)
}
} else if (requestCode == RequestCodes.FromActivity.TextAppearanceGetFonts) {
textAppearancePanel?.onActivityResult(requestCode)
} else if (requestCode == RequestCodes.FromActivity.TextAppearanceCustomColors) {
textAppearancePanel?.onActivityResult(requestCode)
} else if (requestCode == RequestCodes.FromActivity.EditNote1 && resultCode == Activity.RESULT_OK) {
reloadBothAttributeMaps()
} else if (requestCode == RequestCodes.FromActivity.EditNote2 && resultCode == Activity.RESULT_OK) {
lsSplit0.uncheckAllVerses(true)
reloadBothAttributeMaps()
}
super.onActivityResult(requestCode, resultCode, data)
}
/**
* Display specified chapter and verse of the active book. By default, all checked verses will be unchecked.
*
* @param uncheckAllVerses whether we want to always make all verses unchecked after this operation.
* @return Ari that contains only chapter and verse. Book always set to 0.
*/
@JvmOverloads
fun display(chapter_1: Int, verse_1: Int, uncheckAllVerses: Boolean = true): Int {
val current_chapter_1 = this.chapter_1
val available_chapter_1 = chapter_1.coerceIn(1, activeSplit0.book.chapter_count)
val available_verse_1 = verse_1.coerceIn(1, activeSplit0.book.verse_counts[available_chapter_1 - 1])
run {
// main
this.uncheckVersesWhenActionModeDestroyed = false
try {
val ok = loadChapterToVersesController(contentResolver, lsSplit0, { dataSplit0 = it }, activeSplit0.version, activeSplit0.versionId, activeSplit0.book, available_chapter_1, current_chapter_1, uncheckAllVerses)
if (!ok) return 0
} finally {
this.uncheckVersesWhenActionModeDestroyed = true
}
// tell activity
this.chapter_1 = available_chapter_1
lsSplit0.scrollToVerse(available_verse_1)
}
displaySplitFollowingMaster(available_verse_1)
// set goto button text
val reference = activeSplit0.book.reference(available_chapter_1)
bGoto.text = reference.replace(' ', '\u00a0')
if (fullScreen) {
fullscreenReferenceToast?.cancel()
val toast = Toast.makeText(this, reference, Toast.LENGTH_SHORT).apply {
setGravity(Gravity.CENTER_HORIZONTAL or Gravity.TOP, 0, 0)
}
toast.show()
fullscreenReferenceToast = toast
}
if (dictionaryMode) {
finishDictionaryMode()
}
return Ari.encode(0, available_chapter_1, available_verse_1)
}
private fun loadChapterToVersesController(
cr: ContentResolver,
versesController: VersesController,
dataSetter: (VersesDataModel) -> Unit,
version: Version,
versionId: String,
book: Book,
chapter_1: Int,
current_chapter_1: Int,
uncheckAllVerses: Boolean,
): Boolean {
val verses = version.loadChapterText(book, chapter_1) ?: return false
val pericope_aris = mutableListOf<Int>()
val pericope_blocks = mutableListOf<PericopeBlock>()
val nblock = version.loadPericope(book.bookId, chapter_1, pericope_aris, pericope_blocks)
val retainSelectedVerses = !uncheckAllVerses && chapter_1 == current_chapter_1
setDataWithRetainSelectedVerses(cr, versesController, dataSetter, retainSelectedVerses, Ari.encode(book.bookId, chapter_1, 0), pericope_aris, pericope_blocks, nblock, verses, version, versionId)
return true
}
// Moved from the old VersesView method
private fun setDataWithRetainSelectedVerses(
cr: ContentResolver,
versesController: VersesController,
dataSetter: (VersesDataModel) -> Unit,
retainSelectedVerses: Boolean,
ariBc: Int,
pericope_aris: List<Int>,
pericope_blocks: List<PericopeBlock>,
nblock: Int,
verses: SingleChapterVerses,
version: Version,
versionId: String,
) {
var selectedVerses_1: IntArrayList? = null
if (retainSelectedVerses) {
selectedVerses_1 = versesController.getCheckedVerses_1()
}
// # fill adapter with new data. make sure all checked states are reset
versesController.uncheckAllVerses(true)
val versesAttributes = VerseAttributeLoader.load(S.getDb(), cr, ariBc, verses)
val newData = VersesDataModel(ariBc, verses, nblock, pericope_aris, pericope_blocks, version, versionId, versesAttributes)
dataSetter(newData)
if (selectedVerses_1 != null) {
versesController.checkVerses(selectedVerses_1, true)
}
}
private fun displaySplitFollowingMaster(verse_1: Int) {
val activeSplit1 = activeSplit1
if (activeSplit1 != null) { // split1
val splitBook = activeSplit1.version.getBook(activeSplit0.book.bookId)
if (splitBook == null) {
lsSplit1.setEmptyMessage(getString(R.string.split_version_cant_display_verse, activeSplit0.book.reference(this.chapter_1), activeSplit1.version.shortName), S.applied().fontColor)
dataSplit1 = VersesDataModel.EMPTY
} else {
lsSplit1.setEmptyMessage(null, S.applied().fontColor)
this.uncheckVersesWhenActionModeDestroyed = false
try {
loadChapterToVersesController(contentResolver, lsSplit1, { dataSplit1 = it }, activeSplit1.version, activeSplit1.versionId, splitBook, this.chapter_1, this.chapter_1, true)
} finally {
this.uncheckVersesWhenActionModeDestroyed = true
}
lsSplit1.scrollToVerse(verse_1)
}
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return consumeKey(keyCode) || super.onKeyDown(keyCode, event)
}
override fun onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent): Boolean {
return consumeKey(keyCode) || super.onKeyMultiple(keyCode, repeatCount, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
val volumeButtonsForNavigation = Preferences.getString(R.string.pref_volumeButtonNavigation_key, R.string.pref_volumeButtonNavigation_default)
if (volumeButtonsForNavigation != "default") { // consume here
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) return true
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) return true
}
return super.onKeyUp(keyCode, event)
}
override fun getLeftDrawer(): LeftDrawer {
return leftDrawer
}
fun bLeft_click() {
Tracker.trackEvent("nav_left_click")
val currentBook = activeSplit0.book
if (chapter_1 == 1) {
// we are in the beginning of the book, so go to prev book
var tryBookId = currentBook.bookId - 1
while (tryBookId >= 0) {
val newBook = activeSplit0.version.getBook(tryBookId)
if (newBook != null) {
activeSplit0 = activeSplit0.copy(book = newBook)
val newChapter_1 = newBook.chapter_count // to the last chapter
display(newChapter_1, 1)
break
}
tryBookId--
}
// whileelse: now is already Genesis 1. No need to do anything
} else {
val newChapter = chapter_1 - 1
display(newChapter, 1)
}
}
fun bRight_click() {
Tracker.trackEvent("nav_right_click")
val currentBook = activeSplit0.book
if (chapter_1 >= currentBook.chapter_count) {
val maxBookId = activeSplit0.version.maxBookIdPlusOne
var tryBookId = currentBook.bookId + 1
while (tryBookId < maxBookId) {
val newBook = activeSplit0.version.getBook(tryBookId)
if (newBook != null) {
activeSplit0 = activeSplit0.copy(book = newBook)
display(1, 1)
break
}
tryBookId++
}
// whileelse: now is already Revelation (or the last book) at the last chapter. No need to do anything
} else {
val newChapter = chapter_1 + 1
display(newChapter, 1)
}
}
private fun bVersion_click() {
Tracker.trackEvent("nav_version_click")
openVersionsDialog()
}
override fun onSearchRequested(): Boolean {
menuSearch_click()
return true
}
inner class AttributeListener : VersesController.AttributeListener() {
fun openBookmarkDialog(_id: Long) {
val dialog = TypeBookmarkDialog.EditExisting(this@IsiActivity, _id)
dialog.setListener { reloadBothAttributeMaps() }
dialog.show()
}
override fun onBookmarkAttributeClick(version: Version, versionId: String, ari: Int) {
val markers = S.getDb().listMarkersForAriKind(ari, Marker.Kind.bookmark)
if (markers.size == 1) {
openBookmarkDialog(markers[0]._id)
} else {
MaterialDialog.Builder(this@IsiActivity)
.title(R.string.edit_bookmark)
.showWithAdapter(MultipleMarkerSelectAdapter(version, versionId, markers, Marker.Kind.bookmark))
}
}
fun openNoteDialog(_id: Long) {
startActivityForResult(NoteActivity.createEditExistingIntent(_id), RequestCodes.FromActivity.EditNote1)
}
override fun onNoteAttributeClick(version: Version, versionId: String, ari: Int) {
val markers = S.getDb().listMarkersForAriKind(ari, Marker.Kind.note)
if (markers.size == 1) {
openNoteDialog(markers[0]._id)
} else {
MaterialDialog.Builder(this@IsiActivity)
.title(R.string.edit_note)
.showWithAdapter(MultipleMarkerSelectAdapter(version, versionId, markers, Marker.Kind.note))
}
}
inner class MarkerHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val lDate: TextView = itemView.findViewById(R.id.lDate)
val lCaption: TextView = itemView.findViewById(R.id.lCaption)
val lSnippet: TextView = itemView.findViewById(R.id.lSnippet)
val panelLabels: FlowLayout = itemView.findViewById(R.id.panelLabels)
}
inner class MultipleMarkerSelectAdapter(
val version: Version,
versionId: String,
private val markers: List<Marker>,
val kind: Marker.Kind,
) : MaterialDialogAdapterHelper.Adapter() {
val textSizeMult = S.getDb().getPerVersionSettings(versionId).fontSizeMultiplier
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return MarkerHolder(layoutInflater.inflate(R.layout.item_marker, parent, false))
}
override fun onBindViewHolder(_holder_: RecyclerView.ViewHolder, position: Int) {
val holder = _holder_ as MarkerHolder
run {
val marker = markers[position]
run {
val addTime = marker.createTime
val modifyTime = marker.modifyTime
if (addTime == modifyTime) {
holder.lDate.text = Sqlitil.toLocaleDateMedium(addTime)
} else {
holder.lDate.text = getString(R.string.create_edited_modified_time, Sqlitil.toLocaleDateMedium(addTime), Sqlitil.toLocaleDateMedium(modifyTime))
}
Appearances.applyMarkerDateTextAppearance(holder.lDate, textSizeMult)
}
val ari = marker.ari
val reference = version.reference(ari)
val caption = marker.caption
if (kind == Marker.Kind.bookmark) {
holder.lCaption.text = caption
Appearances.applyMarkerTitleTextAppearance(holder.lCaption, textSizeMult)
holder.lSnippet.visibility = View.GONE
val labels = S.getDb().listLabelsByMarker(marker)
if (labels.size != 0) {
holder.panelLabels.visibility = View.VISIBLE
holder.panelLabels.removeAllViews()
for (label in labels) {
holder.panelLabels.addView(MarkerListActivity.getLabelView(layoutInflater, holder.panelLabels, label))
}
} else {
holder.panelLabels.visibility = View.GONE
}
} else if (kind == Marker.Kind.note) {
holder.lCaption.text = reference
Appearances.applyMarkerTitleTextAppearance(holder.lCaption, textSizeMult)
holder.lSnippet.text = caption
Appearances.applyTextAppearance(holder.lSnippet, textSizeMult)
}
holder.itemView.setBackgroundColor(S.applied().backgroundColor)
}
holder.itemView.setOnClickListener {
dismissDialog()
val which = holder.bindingAdapterPosition
val marker = markers[which]
if (kind == Marker.Kind.bookmark) {
openBookmarkDialog(marker._id)
} else if (kind == Marker.Kind.note) {
openNoteDialog(marker._id)
}
}
}
override fun getItemCount(): Int {
return markers.size
}
}
override fun onProgressMarkAttributeClick(version: Version, versionId: String, preset_id: Int) {
S.getDb().getProgressMarkByPresetId(preset_id)?.let { progressMark ->
ProgressMarkRenameDialog.show(this@IsiActivity, progressMark, object : ProgressMarkRenameDialog.Listener {
override fun onOked() {
lsSplit0.uncheckAllVerses(true)
}
override fun onDeleted() {
lsSplit0.uncheckAllVerses(true)
}
})
}
}
override fun onHasMapsAttributeClick(version: Version, versionId: String, ari: Int) {
val locale = version.locale
try {
val intent = Intent("palki.maps.action.SHOW_MAPS_DIALOG")
intent.putExtra("ari", ari)
if (locale != null) {
intent.putExtra("locale", locale)
}
startActivity(intent)
} catch (e: ActivityNotFoundException) {
MaterialDialog.Builder(this@IsiActivity)
.content(R.string.maps_could_not_open)
.positiveText(R.string.ok)
.show()
}
}
}
inner class VerseInlineLinkSpanFactory(private val sourceSupplier: () -> VersesController) : VerseInlineLinkSpan.Factory {
override fun create(type: VerseInlineLinkSpan.Type, arif: Int) = object : VerseInlineLinkSpan(type, arif) {
override fun onClick(type: Type, arif: Int) {
val source = sourceSupplier()
val activeSplit1 = activeSplit1
if (type == Type.xref) {
val dialog = XrefDialog.newInstance(arif)
val verseSelectedListener = { arif_source: Int, ari_target: Int ->
dialog.dismiss()
val ari_source = arif_source ushr 8
updateBackForwardListCurrentEntry(ari_source)
jumpToAri(ari_target, updateBackForwardListCurrentEntryWithSource = false)
}
if (source === lsSplit0 || activeSplit1 == null) { // use activeVersion
dialog.init(activeSplit0.version, activeSplit0.versionId, verseSelectedListener)
} else if (source === lsSplit1) { // use activeSplitVersion
dialog.init(activeSplit1.version, activeSplit1.versionId, verseSelectedListener)
}
val fm = supportFragmentManager
dialog.show(fm, "XrefDialog")
} else if (type == Type.footnote) {
val fe = when {
source === lsSplit0 -> activeSplit0.version.getFootnoteEntry(arif)
source === lsSplit1 -> activeSplit1?.version?.getFootnoteEntry(arif)
else -> null
}
if (fe != null) {
val footnoteText = SpannableStringBuilder()
VerseRenderer.appendSuperscriptNumber(footnoteText, arif and 0xff)
footnoteText.append(" ")
var footnoteDialog: MaterialDialog? = null
val rendered = FormattedTextRenderer.render(
fe.content,
mustHaveFormattedHeader = false,
appendToThis = footnoteText,
tagListener = object : FormattedTextRenderer.TagListener {
override fun onTag(tag: String, buffer: Spannable, start: Int, end: Int) {
when {
tag.startsWith("t") -> { // target verse
val encodedTarget = tag.substring(1)
buffer.setSpan(object : ClickableSpan() {
override fun onClick(widget: View) {
val ranges = TargetDecoder.decode(encodedTarget)
val versesDialog = VersesDialog.newInstance(ranges)
versesDialog.listener = object : VersesDialog.VersesDialogListener() {
override fun onVerseSelected(ari: Int) {
footnoteDialog?.dismiss()
versesDialog.dismiss()
jumpToAri(ari)
}
}
versesDialog.show(supportFragmentManager, "verses_dialog_from_footnote")
}
}, start, end, 0)
}
else -> {
MaterialDialog.Builder(this@IsiActivity)
.content(String.format(Locale.US, "Error: footnote at arif 0x%08x contains unsupported tag %s", arif, tag))
.positiveText(R.string.ok)
.show()
}
}
}
},
)
// Detect URLs
val matcher = PatternsCompat.WEB_URL.matcher(rendered)
while (matcher.find()) {
val url = matcher.group()
val span = object : ClickableSpan() {
override fun onClick(widget: View) {
val uri = if (url.startsWith("http:") || url.startsWith("https:")) {
Uri.parse(url)
} else {
Uri.parse("http://$url")
}
try {
startActivity(Intent(Intent.ACTION_VIEW, uri))
} catch (ignored: Exception) {
}
}
}
rendered.setSpan(span, matcher.start(), matcher.end(), 0)
}
val ari = arif ushr 8
val title = when {
source === lsSplit0 -> activeSplit0.version.reference(ari)
source === lsSplit1 -> activeSplit1?.version?.reference(ari)
else -> null
}.orEmpty()
footnoteDialog = MaterialDialog.Builder(this@IsiActivity)
.title(title)
.content(rendered)
.positiveText(R.string.ok)
.show()
} else {
MaterialDialog.Builder(this@IsiActivity)
.content(String.format(Locale.US, "Error: footnote arif 0x%08x couldn't be loaded", arif))
.positiveText(R.string.ok)
.show()
}
} else {
MaterialDialog.Builder(this@IsiActivity)
.content("Error: Unknown inline link type: $type")
.positiveText(R.string.ok)
.show()
}
}
}
}
enum class RibkaEligibility {
None,
Main,
Split,
}
/**
* Check whether we are using a version eligible for ribka.
*/
fun checkRibkaEligibility(): RibkaEligibility {
val validPresetName = "in-ayt"
val activeMVersion = activeSplit0.mv
val activePresetName = if (activeMVersion is MVersionDb) activeMVersion.preset_name else null
if (validPresetName == activePresetName) {
return RibkaEligibility.Main
}
val splitPresetName = (activeSplit1?.mv as? MVersionDb)?.preset_name
return if (validPresetName == splitPresetName) RibkaEligibility.Split else RibkaEligibility.None
}
fun reloadBothAttributeMaps() {
val newDataSplit0 = reloadAttributeMapsToVerseDataModel(dataSplit0)
dataSplit0 = newDataSplit0
if (activeSplit1 != null) {
val newDataSplit1 = reloadAttributeMapsToVerseDataModel(dataSplit1)
dataSplit1 = newDataSplit1
}
}
private fun reloadAttributeMapsToVerseDataModel(
data: VersesDataModel,
): VersesDataModel {
val versesAttributes = VerseAttributeLoader.load(
S.getDb(),
contentResolver,
data.ari_bc_,
data.verses_
)
return data.copy(versesAttributes = versesAttributes)
}
/**
* @param aris aris where the verses are to be checked for dictionary words.
*/
private fun startDictionaryMode(aris: Set<Int>) {
if (!OtherAppIntegration.hasIntegratedDictionaryApp()) {
OtherAppIntegration.askToInstallDictionary(this)
return
}
dictionaryMode = true
uiSplit0 = uiSplit0.copy(dictionaryModeAris = aris)
uiSplit1 = uiSplit1.copy(dictionaryModeAris = aris)
}
private fun finishDictionaryMode() {
dictionaryMode = false
uiSplit0 = uiSplit0.copy(dictionaryModeAris = emptySet())
uiSplit1 = uiSplit1.copy(dictionaryModeAris = emptySet())
}
override fun bMarkers_click() {
startActivity(MarkersActivity.createIntent())
}
override fun bDisplay_click() {
Tracker.trackEvent("left_drawer_display_click")
setShowTextAppearancePanel(textAppearancePanel == null)
}
override fun cFullScreen_checkedChange(isChecked: Boolean) {
Tracker.trackEvent("left_drawer_full_screen_click")
setFullScreen(isChecked)
}
override fun cNightMode_checkedChange(isChecked: Boolean) {
Tracker.trackEvent("left_drawer_night_mode_click")
setNightMode(isChecked)
}
override fun cFollowSystemTheme_checkedChange(isChecked: Boolean, cNightMode: SwitchCompat) {
Tracker.trackEvent("left_drawer_follow_system_theme_click")
cNightMode.isEnabled = !isChecked
setFollowSystemTheme(isChecked, cNightMode)
}
override fun cSplitVersion_checkedChange(cSplitVersion: SwitchCompat, isChecked: Boolean) {
Tracker.trackEvent("left_drawer_split_click")
if (isChecked) {
cSplitVersion.isChecked = false // do it later, at the version chooser dialog
openSplitVersionsDialog()
} else {
disableSplitVersion()
}
}
override fun bProgressMarkList_click() {
Tracker.trackEvent("left_drawer_progress_mark_list_click")
if (S.getDb().countAllProgressMarks() > 0) {
val dialog = ProgressMarkListDialog()
dialog.progressMarkSelectedListener = { preset_id ->
gotoProgressMark(preset_id)
}
dialog.show(supportFragmentManager, "dialog_progress_mark_list")
leftDrawer.closeDrawer()
} else {
MaterialDialog.Builder(this)
.content(R.string.pm_activate_tutorial)
.positiveText(R.string.ok)
.show()
}
}
override fun bProgress_click(preset_id: Int) {
gotoProgressMark(preset_id)
}
override fun bCurrentReadingClose_click() {
Tracker.trackEvent("left_drawer_current_reading_close_click")
CurrentReading.clear()
}
override fun bCurrentReadingReference_click() {
Tracker.trackEvent("left_drawer_current_reading_verse_reference_click")
val aris = CurrentReading.get() ?: return
val ari_start = aris[0]
jumpToAri(ari_start)
leftDrawer.closeDrawer()
}
private fun gotoProgressMark(preset_id: Int) {
val progressMark = S.getDb().getProgressMarkByPresetId(preset_id) ?: return
val ari = progressMark.ari
if (ari != 0) {
Tracker.trackEvent("left_drawer_progress_mark_pin_click_succeed")
jumpToAri(ari)
} else {
Tracker.trackEvent("left_drawer_progress_mark_pin_click_failed")
MaterialDialog.Builder(this)
.content(R.string.pm_activate_tutorial)
.positiveText(R.string.ok)
.show()
}
}
companion object {
const val ACTION_ATTRIBUTE_MAP_CHANGED = "yuku.alkitab.action.ATTRIBUTE_MAP_CHANGED"
const val ACTION_ACTIVE_VERSION_CHANGED = "yuku.alkitab.base.IsiActivity.action.ACTIVE_VERSION_CHANGED"
const val ACTION_NIGHT_MODE_CHANGED = "yuku.alkitab.base.IsiActivity.action.NIGHT_MODE_CHANGED"
const val ACTION_NEEDS_RESTART = "yuku.alkitab.base.IsiActivity.action.NEEDS_RESTART"
@JvmStatic
fun createIntent(): Intent {
return Intent(App.context, IsiActivity::class.java)
}
@JvmStatic
fun createIntent(ari: Int) = Intent(App.context, IsiActivity::class.java).apply {
action = "yuku.alkitab.action.VIEW"
putExtra("ari", ari)
}
}
}
| apache-2.0 | abbd303fa9e327adf489fd33e06f1c53 | 38.683221 | 392 | 0.57767 | 4.81773 | false | false | false | false |
isuPatches/WiseFy | wisefy/src/main/java/com/isupatches/wisefy/connection/WiseFyConnectionLegacy.kt | 1 | 7186 | /*
* Copyright 2019 Patches Klinefelter
*
* 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.isupatches.wisefy.connection
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import com.isupatches.wisefy.constants.MOBILE
import com.isupatches.wisefy.constants.NetworkType
import com.isupatches.wisefy.constants.WIFI
import com.isupatches.wisefy.logging.WiseFyLogger
/**
* A class used internally to query and determine different parts of the connection state for a
* device when WiseFy is set to use the legacy connectivity class or is on a pre-SDK23 device.
*
* @see [ConnectivityManager]
* @see [WifiManager]
* @see [AbstractWiseFyConnection]
*
* Updates
* - 01/07/2020: Added WiseFyLogger
*
* @author Patches
* @since 3.0
*/
@Suppress("deprecation")
internal class WiseFyConnectionLegacy private constructor(
private val connectivityManager: ConnectivityManager,
wifiManager: WifiManager,
private val logger: WiseFyLogger?
) : AbstractWiseFyConnection(wifiManager, logger) {
internal companion object {
private val TAG = WiseFyConnectionLegacy::class.java.simpleName
/**
* Used internally to create an instance of a legacy WiseFyConnection.
*
* @param connectivityManager The instance of ConnectivityManager to use
* @param wifiManager The instance of WifiManager to use
*
* @return WiseFyConnectionLegacy
*
* @see [WiseFyConnection]
*
* Updates
* - 01/04/2020: Formatting update
* - 01/07/2020: Added WiseFyLogger
*
* @author Patches
* @since 4.0
*/
fun create(
connectivityManager: ConnectivityManager,
wifiManager: WifiManager,
logger: WiseFyLogger? = null
): WiseFyConnection {
return WiseFyConnectionLegacy(connectivityManager, wifiManager, logger)
}
}
/**
* Used internally for any initialization of [WiseFyConnectionLegacy] class.
*
* @author Patches
* @since 4.0
*/
override fun init() {
// No-op
}
/**
* Used internally for any tear down of [WiseFyConnectionLegacy] class.
*
* @author Patches
* @since 4.0
*/
override fun destroy() {
// No-op
}
/**
* Used internally to check if a network is connected to a mobile network (f.e. non-Wifi)
*
* @return boolean - True if the device is using a mobile network, false otherwise
*
* @see [ConnectivityManager.getActiveNetworkInfo]
* @see [isNetworkConnectedAndMatchesType]
* @see [MOBILE]
*
* @author Patches
* @since 4.0
*/
override fun isDeviceConnectedToMobileNetwork(): Boolean {
return isNetworkConnectedAndMatchesType(connectivityManager.activeNetworkInfo, MOBILE)
}
/**
* Used internally to check if a network is connected to a wifi network (f.e. not using
* mobile data)
*
* @return boolean - True if the device is using a wifi network, false otherwise
*
* @see [ConnectivityManager.getActiveNetworkInfo]
* @see [isNetworkConnectedAndMatchesType]
* @see [WIFI]
*
* Updates
* - 01/04/2020: Formatting update
*
* @author Patches
* @since 4.0
*/
override fun isDeviceConnectedToWifiNetwork(): Boolean {
return isNetworkConnectedAndMatchesType(connectivityManager.activeNetworkInfo, WIFI)
}
/**
* Used internally to check if a network is in a roaming state.
*
* @return boolean - True if the device is roaming, false otherwise
*
* @see [ConnectivityManager.getActiveNetworkInfo]
* @see [NetworkInfo.isRoaming]
*
* @author Patches
* @since 4.0
*/
override fun isDeviceRoaming(): Boolean {
val networkInfo = connectivityManager.activeNetworkInfo
return networkInfo != null && networkInfo.isRoaming
}
/**
* Used internally to check if a network is connected.
*
* @return boolean - True if the network is both available and connected
*
* @see [NetworkInfo]
* @see [isConnectedAndAvailable]
*
* Updates
* - 05/12/2019: Switched to using [isConnectedAndAvailable]
*
* @author Patches
* @since 3.0
*/
override fun isNetworkConnected(): Boolean {
val networkInfo = connectivityManager.activeNetworkInfo
logger?.d(TAG, "networkInfo: %s", networkInfo ?: "")
return networkInfo?.isConnectedAndAvailable() ?: false
}
/**
* Used internally to check to see if a given network matches a specified type (i.error. Mobile or Wifi)
*
* *NOTE* Case insensitive
*
* @param networkInfo The network to check
* @param type The type of network (f.e. Mobile or Wifi)
*
* @return boolean - True if the network matches the given type
*
* @see [NetworkInfo]
* @see [NetworkType]
*
* Updates
* - 05/12/2019: Made networkInfo expectation non-null
* - 01/04/2020: Formatting update
*
* @author Patches
* @since 3.0
*/
private fun doesNetworkMatchType(networkInfo: NetworkInfo, @NetworkType type: String): Boolean {
return type.equals(networkInfo.typeName, ignoreCase = true)
}
/**
* Used internally to check if a given network matches a given type and is connected.
*
* @param networkInfo The network to check
* @param type The type of network (f.e. Mobile or Wifi)
*
* @return boolean - True if the network is both connected and matches the given type of network
*
* @see [doesNetworkMatchType]
* @see [isConnectedAndAvailable]
* @see [NetworkInfo]
*
* Updates
* - 05/12/2019: Switched to using [isConnectedAndAvailable] over [isNetworkConnected]
* - 01/04/2020: Formatting update
*
* @author Patches
* @since 3.0
*/
private fun isNetworkConnectedAndMatchesType(networkInfo: NetworkInfo?, @NetworkType type: String): Boolean {
return networkInfo?.let { doesNetworkMatchType(it, type) && it.isConnectedAndAvailable() } ?: false
}
/**
* Used within legacy class to determine if a given network is in a connected state.
*
* @return boolean - Whether the given NetworkInfo is both connected and available.
*
* @see [NetworkInfo.isConnected]
* @see [NetworkInfo.isAvailable]
*
* @author Patches
* @since 4.0
*/
private fun NetworkInfo.isConnectedAndAvailable() = isConnected && isAvailable
}
| apache-2.0 | 841cb434e294939c9972492680d25910 | 30.656388 | 113 | 0.654189 | 4.516656 | false | false | false | false |
Jire/Abendigo | src/main/kotlin/org/abendigo/csgo/EntityType.kt | 2 | 7052 | package org.abendigo.csgo
import org.jire.arrowhead.get
enum class EntityType(val id: Int, val weapon: Boolean = false, val grenade: Boolean = false) {
NULL(-1),
NextBotCombatCharacter(0),
CAK47(1, weapon = true),
CBaseAnimating(2),
CBaseAnimatingOverlay(3),
CBaseAttributableItem(4),
CBaseButton(5),
CBaseCombatCharacter(6),
CBaseCombatWeapon(7),
CBaseCSGrenade(8, grenade = true),
CBaseCSGrenadeProjectile(9, grenade = true),
CBaseDoor(10),
CBaseEntity(11),
CBaseFlex(12),
CBaseGrenade(13),
CBaseParticleEntity(14),
CBasePlayer(15),
CBasePropDoor(16),
CBaseTeamObjectiveResource(17),
CBaseTempEntity(18),
CBaseToggle(19),
CBaseTrigger(20),
CBaseViewModel(21),
CBaseVPhysicsTrigger(22),
CBaseWeaponWorldModel(23),
CBeam(24),
CBeamSpotlight(25),
CBoneFollower(26),
CBreakableProp(27),
CBreakableSurface(28),
CC4(29),
CCascadeLight(30),
CChicken(31),
CColorCorrection(32),
CColorCorrectionVolume(33),
CCSGameRulesProxy(34),
CCSPlayer(35),
CCSPlayerResource(36),
CCSRagdoll(37),
CCSTeam(38),
CDEagle(39, weapon = true),
CDecoyGrenade(40, grenade = true),
CDecoyProjectile(41, grenade = true),
CDynamicLight(42),
CDynamicProp(43),
CEconEntity(44),
CEmbers(45),
CEntityDissolve(46),
CEntityFlame(47),
CEntityFreezing(48),
CEntityParticleTrail(49),
CEnvAmbientLight(50),
CEnvDetailController(51),
CEnvDOFController(52),
CEnvParticleScript(53),
CEnvProjectedTexture(54),
CEnvQuadraticBeam(55),
CEnvScreenEffect(56),
CEnvScreenOverlay(57),
CEnvTonemapController(58),
CEnvWind(59),
CFEPlayerDecal(60),
CFireCrackerBlast(61),
CFireSmoke(62),
CFireTrail(63),
CFish(64),
CFlashbang(65, grenade = true),
CFogController(66),
CFootstepControl(67),
CFunc_Dust(68),
CFunc_LOD(69),
CFuncAreaPortalWindow(70),
CFuncBrush(71),
CFuncConveyor(72),
CFuncLadder(73),
CFuncMonitor(74),
CFuncMoveLinear(75),
CFuncOccluder(76),
CFuncReflectiveGlass(77),
CFuncRotating(78),
CFuncSmokeVolume(79),
CFuncTrackTrain(80),
CGameRulesProxy(81),
CHandleTest(82),
CHEGrenade(83, grenade = true),
CHostage(84),
CHostageCarriableProp(85),
CIncendiaryGrenade(86, grenade = true),
CInferno(87),
CInfoLadderDismount(88),
CInfoOverlayAccessor(89),
CItem_Healthshot(90),
CKnife(91),
CKnifeGG(92),
CLightGlow(93),
CMaterialModifyControl(94),
CMolotovGrenade(95, grenade = true),
CMolotovProjectile(96, grenade = true),
CMovieDisplay(97),
CParticleFire(98),
CParticlePerformanceMonitor(99),
CParticleSystem(100),
CPhysBox(101),
CPhysBoxMultiplayer(102),
CPhysicsProp(103),
CPhysicsPropMultiplayer(104),
CPhysMagnet(105),
CPlantedC4(106),
CPlasma(107),
CPlayerResource(108),
CPointCamera(109),
CPointCommentaryNode(110),
CPoseController(111),
CPostProcessController(112),
CPrecipitation(113),
CPrecipitationBlocker(114),
CPredictedViewModel(115),
CProp_Hallucination(116),
CPropDoorRotating(117),
CPropJeep(118),
CPropVehicleDriveable(119),
CRagdollManager(120),
CRagdollProp(121),
CRagdollPropAttached(122),
CRopeKeyframe(123),
CSCAR17(124, weapon = true),
CSceneEntity(125),
CSensorGrenade(126),
CSensorGrenadeProjectile(127),
CShadowControl(128),
CSlideshowDisplay(129),
CSmokeGrenade(130, grenade = true),
CSmokeGrenadeProjectile(131, grenade = true),
CSmokeStack(132),
CSpatialEntity(133),
CSpotlightEnd(134),
CSprite(135),
CSpriteOriented(136),
CSpriteTrail(137),
CStatueProp(138),
CSteamJet(139),
CSun(140),
CSunlightShadowControl(141),
CTeam(142),
CTeamplayRoundBasedRulesProxy(143),
CTEArmorRicochet(144),
CTEBaseBeam(145),
CTEBeamEntPoint(146),
CTEBeamEnts(147),
CTEBeamFollow(148),
CTEBeamLaser(149),
CTEBeamPoints(150),
CTEBeamRing(151),
CTEBeamRingPoint(152),
CTEBeamSpline(153),
CTEBloodSprite(154),
CTEBloodStream(155),
CTEBreakModel(156),
CTEBSPDecal(157),
CTEBubbles(158),
CTEBubbleTrail(159),
CTEClientProjectile(160),
CTEDecal(161),
CTEDust(162),
CTEDynamicLight(163),
CTEEffectDispatch(164),
CTEEnergySplash(165),
CTEExplosion(166),
CTEFireBullets(167),
CTEFizz(168),
CTEFootprintDecal(169),
CTEFoundryHelpers(170),
CTEGaussExplosion(171),
CTEGlowSprite(172),
CTEImpact(173),
CTEKillPlayerAttachments(174),
CTELargeFunnel(175),
CTEMetalSparks(176),
CTEMuzzleFlash(177),
CTEParticleSystem(178),
CTEPhysicsProp(179),
CTEPlantBomb(180),
CTEPlayerAnimEvent(181),
CTEPlayerDecal(182),
CTEProjectedDecal(183),
CTERadioIcon(184),
CTEShatterSurface(185),
CTEShowLine(186),
CTesla(187),
CTESmoke(188),
CTESparks(189),
CTESprite(190),
CTESpriteSpray(191),
CTest_ProxyToggle_Networkable(192),
CTestTraceline(193),
CTEWorldDecal(194),
CTriggerPlayerMovement(195),
CTriggerSoundOperator(196),
CVGuiScreen(197),
CVoteController(198),
CWaterBullet(199),
CWaterLODControl(200),
CWeaponAug(201, weapon = true),
CWeaponAWP(202, weapon = true),
CWeaponBaseItem(203),
CWeaponBizon(204, weapon = true),
CWeaponCSBase(205),
CWeaponCSBaseGun(206),
CWeaponCycler(207),
CWeaponElite(208, weapon = true),
CWeaponFamas(209, weapon = true),
CWeaponFiveSeven(210, weapon = true),
CWeaponG3SG1(211, weapon = true),
CWeaponGalil(212, weapon = true),
CWeaponGalilAR(213, weapon = true),
CWeaponGlock(214, weapon = true),
CWeaponHKP2000(215, weapon = true),
CWeaponM249(216, weapon = true),
CWeaponM3(217, weapon = true),
CWeaponM4A1(218, weapon = true),
CWeaponMAC10(219, weapon = true),
CWeaponMag7(220, weapon = true),
CWeaponMP5Navy(221, weapon = true),
CWeaponMP7(222, weapon = true),
CWeaponMP9(223, weapon = true),
CWeaponNegev(224, weapon = true),
CWeaponNOVA(225, weapon = true),
CWeaponP228(226, weapon = true),
CWeaponP250(227, weapon = true),
CWeaponP90(228, weapon = true),
CWeaponSawedoff(229, weapon = true),
CWeaponSCAR20(230, weapon = true),
CWeaponScout(231, weapon = true),
CWeaponSG550(232, weapon = true),
CWeaponSG552(233, weapon = true),
CWeaponSG556(234, weapon = true),
CWeaponSSG08(235, weapon = true),
CWeaponTaser(236),
CWeaponTec9(237, weapon = true),
CWeaponTMP(238, weapon = true),
CWeaponUMP45(239, weapon = true),
CWeaponUSP(240, weapon = true),
CWeaponXM1014(241, weapon = true),
CWorld(242),
DustTrail(243),
MovieExplosion(244),
ParticleSmokeGrenade(245, grenade = true),
RocketTrail(246),
SmokeTrail(247),
SporeExplosion(248),
SporeTrail(249);
companion object {
private val cachedValues = values()
fun byID(id: Int) = cachedValues.firstOrNull { it.id == id }
fun byEntityAddress(address: Int): EntityType? {
if (address <= 0) return null
val vtRead = csgo.read(address + 0x8, 4) ?: return null
val vt = vtRead.getInt(0)
if (vt <= 0) return null
val fnRead = csgo.read(vt + 2 * 0x4, 4) ?: return null
val fn = fnRead.getInt(0)
if (fn <= 0) return null
val clsRead = csgo.read(fn + 0x1, 4) ?: return null
val cls = clsRead.getInt(0)
if (cls <= 0) return null
// val clsn: Int = csgo[cls + 8]
val clsIDRead = csgo.read(cls + 20, 4) ?: return null
val clsID = clsIDRead.getInt(0)
if (clsID < 0 || clsID > SporeTrail.id) return null
return byID(clsID)
}
}
} | gpl-3.0 | a537769ae52acc83bd68ec74cc1b8a05 | 23.15411 | 95 | 0.737096 | 2.513186 | false | false | false | false |
pokk/KotlinKnifer | kotlinshaver/src/main/java/com/devrapid/kotlinshaver/Coroutine.kt | 1 | 2514 | @file:Suppress("NOTHING_TO_INLINE")
package com.devrapid.kotlinshaver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
// --------------------- launch
inline fun gLaunch(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
noinline block: suspend CoroutineScope.() -> Unit,
) = GlobalScope.launch(context, start, block)
inline fun ui(noinline block: suspend CoroutineScope.() -> Unit) =
CoroutineScope(Main.immediate).launch(block = block)
inline fun uiLate(noinline block: suspend CoroutineScope.() -> Unit) =
CoroutineScope(Main).launch(block = block)
inline fun bkg(noinline block: suspend CoroutineScope.() -> Unit) =
CoroutineScope(Default).launch(block = block)
inline fun io(noinline block: suspend CoroutineScope.() -> Unit) =
CoroutineScope(IO).launch(block = block)
// ---------------------- async
inline fun <T> gAsync(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
noinline block: suspend CoroutineScope.() -> T,
) = GlobalScope.async(context, start, block)
inline fun <T> uiAsync(noinline block: suspend CoroutineScope.() -> T) =
CoroutineScope(Main.immediate).async(block = block)
inline fun <T> uiLateAsync(noinline block: suspend CoroutineScope.() -> T) =
CoroutineScope(Main).async(block = block)
inline fun <T> bkgAsync(noinline block: suspend CoroutineScope.() -> T) =
CoroutineScope(Default).async(block = block)
inline fun <T> ioAsync(noinline block: suspend CoroutineScope.() -> T) =
CoroutineScope(IO).async(block = block)
// ----------------------- with context
suspend inline fun <T> uiSwitch(noinline block: suspend CoroutineScope.() -> T) =
withContext(Main.immediate, block)
suspend inline fun <T> uiLateSwitch(noinline block: suspend CoroutineScope.() -> T) =
withContext(Main, block)
suspend inline fun <T> bkgSwitch(noinline block: suspend CoroutineScope.() -> T) =
withContext(Default, block)
suspend inline fun <T> ioSwitch(noinline block: suspend CoroutineScope.() -> T) =
withContext(IO, block)
| apache-2.0 | 5b5a92e4cf2335feb9e62c30b43999e5 | 35.434783 | 85 | 0.736277 | 4.372174 | false | false | false | false |
UnknownJoe796/ponderize | app/src/main/java/com/ivieleague/ponderize/vc/DatabaseVC.kt | 1 | 1951 | package com.ivieleague.ponderize.vc
import android.view.Gravity
import android.view.View
import android.widget.TextView
import com.ivieleague.ponderize.Database
import com.ivieleague.ponderize.model.Verse
import com.ivieleague.ponderize.styleHeader
import com.ivieleague.ponderize.styleItem
import com.lightningkite.kotlincomponents.adapter.LightningAdapter
import com.lightningkite.kotlincomponents.linearLayout
import com.lightningkite.kotlincomponents.observable.bind
import com.lightningkite.kotlincomponents.selectableItemBackgroundResource
import com.lightningkite.kotlincomponents.vertical
import com.lightningkite.kotlincomponents.viewcontroller.StandardViewController
import com.lightningkite.kotlincomponents.viewcontroller.containers.VCStack
import com.lightningkite.kotlincomponents.viewcontroller.implementations.VCActivity
import org.jetbrains.anko.*
import java.util.*
/**
* Created by josep on 10/4/2015.
*/
class DatabaseVC(val stack: VCStack, val database: Database, val onResult: (ArrayList<Verse>) -> Unit) : StandardViewController(){
override fun makeView(activity: VCActivity): View {
return linearLayout(activity) {
gravity = Gravity.CENTER
orientation = vertical
textView("Scriptures") {
styleHeader()
}.lparams(wrapContent, wrapContent)
listView {
adapter = LightningAdapter(database.volumes) { itemObs ->
TextView(context).apply {
styleItem()
backgroundResource = selectableItemBackgroundResource
bind(itemObs) {
text = it.title
}
onClick {
stack.push(VolumeVC(stack, itemObs.get(), onResult))
}
}
}
}.lparams(matchParent, 0, 1f)
}
}
} | mit | 4d0028604bc311b63963c6008553a6c6 | 38.04 | 130 | 0.664787 | 5.330601 | false | false | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/ui/mapcreate/components/AreaView.kt | 1 | 2763 | package com.peterlaurence.trekme.ui.mapcreate.components
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.TypedValue
import android.view.View
import com.peterlaurence.mapview.ReferentialData
import com.peterlaurence.mapview.ReferentialOwner
import com.peterlaurence.trekme.R
/**
* A custom view that draws a square between two [AreaMarker] and represents an area.
*
* @author peterLaurence on 12/05/18
*/
class AreaView(context: Context) : View(context), ReferentialOwner {
private val strokeWidth: Float
private val paintBackground: Paint = Paint()
private val paintStroke: Paint = Paint()
private var mBackgroundColor: Int = Color.BLUE
private var mStrokeColor: Int = Color.BLUE
private var x1: Float = 0f
private var y1: Float = 0f
private var x2: Float = 0f
private var y2: Float = 0f
override var referentialData = ReferentialData(false, 0f, 1f, 0.0, 0.0)
set(value) {
field = value
invalidate()
}
init {
setWillNotDraw(false)
val a = context.obtainStyledAttributes(
R.style.AreaViewStyle, R.styleable.AreaView)
mBackgroundColor = a.getColor(
R.styleable.AreaView_backgroundColor,
this.mBackgroundColor)
mStrokeColor = a.getColor(
R.styleable.AreaView_strokeColor,
this.mStrokeColor)
a.recycle()
paintBackground.style = Paint.Style.FILL
paintBackground.color = mBackgroundColor
paintBackground.isAntiAlias = true
val metrics = resources.displayMetrics
strokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_STROKE_WIDTH_DP.toFloat(), metrics)
paintStroke.style = Paint.Style.STROKE
paintStroke.color = mStrokeColor
paintStroke.strokeWidth = strokeWidth
paintStroke.strokeJoin = Paint.Join.ROUND
paintStroke.strokeCap = Paint.Cap.ROUND
}
fun updateArea(x1: Float, y1: Float, x2: Float, y2: Float) {
this.x1 = x1
this.y1 = y1
this.x2 = x2
this.y2 = y2
invalidate()
}
override fun onDraw(canvas: Canvas) {
val scale = referentialData.scale
canvas.scale(scale, scale)
paintStroke.strokeWidth = strokeWidth / scale
canvas.drawLine(x1, y1, x2, y1, paintStroke)
canvas.drawLine(x1, y1, x1, y2, paintStroke)
canvas.drawLine(x2, y2, x2, y1, paintStroke)
canvas.drawLine(x2, y2, x1, y2, paintStroke)
canvas.drawRect(x1, y1, x2, y2, paintBackground)
super.onDraw(canvas)
}
}
private const val DEFAULT_STROKE_WIDTH_DP = 1 | gpl-3.0 | 91b5f323c756c90ca7528a3e4fc88bf6 | 31.139535 | 120 | 0.667391 | 4.004348 | false | false | false | false |
android/xAnd11 | core/src/main/java/com/monksanctum/xand11/core/comm/Event.kt | 1 | 14124 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.monksanctum.xand11.comm
import org.monksanctum.xand11.core.ObjectPool
import org.monksanctum.xand11.core.Rect
import org.monksanctum.xand11.core.Utils
import org.monksanctum.xand11.core.post
enum class Event(val code: Byte) {
ERROR(0),
REPLY(1),
KEY_PRESS(2),
KEY_RELEASE(3),
BUTTON_PRESS(4),
BUTTON_RELEASE(5),
MOTION_NOTIFY(6),
ENTER_NOTIFY(7),
LEAVE_NOTIFY(8),
FOCUS_IN(9),
FOCUS_OUT(10),
KEYMAP_NOTIFY(11),
EXPOSE(12),
GRAPHICS_EXPOSE(13),
NO_EXPOSE(14),
VISIBILITY_NOTIFY(15),
CREATE_NOTIFY(16),
DESTROY_NOTIFY(17),
UNMAP_NOTIFY(18),
MAP_NOTIFY(19),
MAP_REQUEST(20),
REPARENT_NOTIFY(21),
CONFIGURE_NOTIFY(22),
CONFIGURE_REQUEST(23),
GRAVITY_NOTIFY(24),
RESIZE_REQUEST(25),
CIRCULATE_NOTIFY(26),
CILCULATE_REQUEST(27),
PROPERTY_NOTIFY(28),
SELECTION_CLEAR(29),
SELECTION_REQUEST(30),
SELECTION_NOTIFY(31),
COLORMAP_NOTIFY(32),
CLIENT_MESSAGE(33),
MAPPING_NOTIFY(34);
companion object {
private val sNames = arrayOfNulls<String>(256)
// TODO: Probobly should be per client or something...?
private val sEvent = 1
private val sEventPool: ObjectPool<EventInfo, String> = object : ObjectPool<EventInfo, String>() {
override fun create(vararg arg: String): EventInfo {
return EventInfo()
}
}
fun sendPropertyChange(client: Client, window: Int, atom: Int, deleted: Boolean) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(window)
writer.writeCard32(atom)
writer.writeCard32(client.timestamp)
writer.writeByte((if (deleted) 1 else 0).toByte())
writer.writePadding(15)
client.clientListener.sendPacket(MAP_NOTIFY, writer)
}
fun sendMapNotify(client: Client, window: Int, event: Int,
overrideRedirect: Boolean) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(event)
writer.writeCard32(window)
writer.writeByte((if (overrideRedirect) 1 else 0).toByte())
writer.writePadding(19)
client.clientListener.sendPacket(MAP_NOTIFY, writer)
}
fun sendUnmapNotify(client: Client, window: Int, event: Int,
fromConfigure: Boolean) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(event)
writer.writeCard32(window)
writer.writeByte((if (fromConfigure) 1 else 0).toByte())
writer.writePadding(19)
client.clientListener.sendPacket(UNMAP_NOTIFY, writer)
}
fun sendSelectionRequest(client: Client, timestamp: Int, owner: Int, requestor: Int,
selection: Int, target: Int, property: Int) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(timestamp)
writer.writeCard32(owner)
writer.writeCard32(requestor)
writer.writeCard32(selection)
writer.writeCard32(target)
writer.writeCard32(property)
writer.writePadding(4)
client.clientListener.sendPacket(SELECTION_REQUEST, writer)
}
fun sendSelectionNotify(client: Client, timestamp: Int, requestor: Int,
selection: Int, target: Int, property: Int) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(timestamp)
writer.writeCard32(requestor)
writer.writeCard32(selection)
writer.writeCard32(target)
writer.writeCard32(property)
writer.writePadding(8)
client.clientListener.sendPacket(SELECTION_NOTIFY, writer)
}
fun sendSelectionClear(client: Client, timestamp: Int, owner: Int, selection: Int) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(timestamp)
writer.writeCard32(owner)
writer.writeCard32(selection)
writer.writePadding(16)
client.clientListener.sendPacket(SELECTION_CLEAR, writer)
}
fun sendExpose(client: Client, window: Int, bounds: Rect) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(window)
writer.writeCard16(bounds.left)
writer.writeCard16(bounds.top)
writer.writeCard16(bounds.width())
writer.writeCard16(bounds.height())
writer.writeCard16(0) // What?
writer.writePadding(14)
Utils.sBgHandler.post { client.clientListener.sendPacket(EXPOSE, writer) }
}
fun sendConfigureWindow(client: Client, event: Int, window: Int, sibling: Int,
bounds: Rect, borderWidth: Int, overrideDirect: Boolean) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(event)
writer.writeCard32(window)
writer.writeCard32(sibling)
writer.writeCard16(bounds.left)
writer.writeCard16(bounds.top)
writer.writeCard16(bounds.width())
writer.writeCard16(bounds.height())
writer.writeCard16(borderWidth)
writer.writeByte((if (overrideDirect) 1 else 0).toByte())
writer.writePadding(5)
client.clientListener.sendPacket(CONFIGURE_NOTIFY, writer)
}
fun sendKeyDown(client: Client, id: Int, x: Int, y: Int, keyCode: Int, state: Int) {
val writer = PacketWriter(client.clientListener.writer)
writer.minorOpCode = keyCode.toByte()
writer.writeCard32(client.timestamp)
writer.writeCard32(3)
writer.writeCard32(id)
writer.writeCard32(0) // Child
writer.writeCard16(x) // Root-x
writer.writeCard16(y) // Root-y
writer.writeCard16(x)
writer.writeCard16(y)
writer.writeCard16(state) // Keybutton state
writer.writeByte(1.toByte()) // Same screen.
writer.writePadding(1)
client.clientListener.sendPacket(KEY_PRESS, writer)
}
fun sendKeyUp(client: Client, id: Int, x: Int, y: Int, keyCode: Int, state: Int) {
val writer = PacketWriter(client.clientListener.writer)
writer.minorOpCode = keyCode.toByte()
writer.writeCard32(client.timestamp)
writer.writeCard32(3)
writer.writeCard32(id)
writer.writeCard32(0) // Child
writer.writeCard16(0) // Root-x
writer.writeCard16(0) // Root-y
writer.writeCard16(x)
writer.writeCard16(y)
writer.writeCard16(state) // Keybutton state
writer.writeByte(1.toByte())
writer.writePadding(1)
client.clientListener.sendPacket(KEY_RELEASE, writer)
}
fun sendEnter(client: Client, id: Int, x: Int, y: Int) {
val writer = PacketWriter(client.clientListener.writer)
writer.minorOpCode = 1.toByte()
writer.writeCard32(client.timestamp)
writer.writeCard32(id)
writer.writeCard32(id)
writer.writeCard32(0)
writer.writeCard16(0) // Root-x
writer.writeCard16(0) // Root-y
writer.writeCard16(x)
writer.writeCard16(y)
writer.writeCard16(0) // Keybutton state
writer.writeByte(0.toByte()) // Normal, not grab
writer.writeByte(3.toByte()) // Same screen, focus
client.clientListener.sendPacket(ENTER_NOTIFY, writer)
}
fun sendLeave(client: Client, id: Int, x: Int, y: Int) {
val writer = PacketWriter(client.clientListener.writer)
writer.minorOpCode = 1.toByte()
writer.writeCard32(client.timestamp)
writer.writeCard32(id)
writer.writeCard32(id)
writer.writeCard32(0)
writer.writeCard16(0) // Root-x
writer.writeCard16(0) // Root-y
writer.writeCard16(x)
writer.writeCard16(y)
writer.writeCard16(0) // Keybutton state
writer.writeByte(0.toByte()) // Normal, not grab
writer.writeByte(3.toByte()) // Same screen, focus
client.clientListener.sendPacket(LEAVE_NOTIFY, writer)
}
fun sendDestroy(client: Client, id: Int, arg: Int) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(id)
writer.writeCard32(arg)
writer.writePadding(20)
client.clientListener.sendPacket(DESTROY_NOTIFY, writer)
}
fun sendCreate(client: Client, id: Int, child: Int, x: Int, y: Int, width: Int,
height: Int, borderWidth: Int, overrideRedirect: Boolean) {
val writer = PacketWriter(client.clientListener.writer)
writer.writeCard32(id)
writer.writeCard32(child)
writer.writeCard16(x)
writer.writeCard16(y)
writer.writeCard16(width)
writer.writeCard16(height)
writer.writeCard16(borderWidth)
writer.writeByte((if (overrideRedirect) 1 else 0).toByte())
writer.writePadding(9)
client.clientListener.sendPacket(CREATE_NOTIFY, writer)
}
fun populateNames() {
enumValues<Event>().forEach {
sNames[it.code.toInt()] = it.name
}
}
fun getName(what: Int): String? {
return if (sNames[what] == null) {
"Unknown($what)"
} else sNames[what]
}
fun obtainInfo(type: Event, id: Int, arg: Int): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.arg = arg
return e
}
fun obtainInfo(type: Event, id: Int, arg: Int, flag: Boolean): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.arg = arg
e.flag = flag
return e
}
fun obtainInfo(type: Event, id: Int, arg: Int, arg2: Int, arg3: Int, arg4: Int,
arg5: Int, arg6: Int, flag: Boolean): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.arg = arg
e.arg2 = arg2
e.arg3 = arg3
e.arg4 = arg4
e.arg5 = arg5
e.arg6 = arg6
e.flag = flag
return e
}
fun obtainInfo(type: Event, id: Int, arg: Rect, flag: Boolean): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.rect = arg
e.flag = flag
return e
}
fun obtainInfo(type: Event, id: Int, arg1: Int, arg2: Int, arg3: Int, rect: Rect,
flag: Boolean): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.arg = arg1
e.arg2 = arg2
e.arg3 = arg3
e.rect = rect
e.flag = flag
return e
}
fun obtainInfo(type: Event, id: Int, arg1: Int, arg2: Int, arg3: Int, arg4: Int,
arg5: Int): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.arg = arg1
e.arg2 = arg2
e.arg3 = arg3
e.arg4 = arg4
e.arg5 = arg5
return e
}
fun obtainInfo(type: Event, id: Int, arg1: Int, arg2: Int): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.arg = arg1
e.arg2 = arg2
return e
}
fun obtainInfo(type: Event, id: Int, arg1: Int, arg2: Int, arg3: Int): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.arg = arg1
e.arg2 = arg2
e.arg3 = arg3
return e
}
fun obtainInfo(type: Event, id: Int, arg1: Int, arg2: Int, arg3: Int, arg4: Int): EventInfo {
val e = sEventPool.obtain()
e.type = type
e.id = id
e.arg = arg1
e.arg2 = arg2
e.arg3 = arg3
e.arg4 = arg4
return e
}
}
class EventInfo : ObjectPool.Recycleable() {
var type: Event = Event.ERROR
var id: Int = 0
var arg: Int = 0
var arg2: Int = 0
var arg3: Int = 0
var arg5: Int = 0
var arg4: Int = 0
var arg6: Int = 0
var flag: Boolean = false
var rect: Rect? = null
}
}
| apache-2.0 | 38bdca6c776d748df949de0ebf305811 | 33.047146 | 106 | 0.548287 | 4.140721 | false | false | false | false |
AndroidX/androidx | core/core-ktx/src/androidTest/java/androidx/core/view/MenuTest.kt | 3 | 4770 | /*
* 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 androidx.core.view
import android.view.Menu.NONE
import android.view.MenuItem
import android.widget.Toolbar
import androidx.test.core.app.ApplicationProvider
import androidx.test.filters.SdkSuppress
import androidx.test.filters.SmallTest
import androidx.testutils.assertThrows
import androidx.testutils.fail
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
@SdkSuppress(minSdkVersion = 21)
@SmallTest
class MenuTest {
private val menu =
Toolbar(ApplicationProvider.getApplicationContext() as android.content.Context).menu
@Test fun get() {
val item = menu.add("")
assertSame(item, menu[0])
}
@Test fun contains() {
val item1 = menu.add("")
assertTrue(item1 in menu)
val item2 = menu.add("")
assertTrue(item2 in menu)
}
@Test fun minusAssign() {
val item1 = menu.add(NONE, 1, NONE, "")
val item2 = menu.add(NONE, 2, NONE, "")
assertEquals(2, menu.size)
menu -= item2
assertEquals(1, menu.size)
assertSame(item1, menu.getItem(0))
menu -= item1
assertEquals(0, menu.size)
}
@Test fun size() {
assertEquals(0, menu.size)
menu.add("")
assertEquals(1, menu.size)
menu.add(NONE, 123, NONE, "")
assertEquals(2, menu.size)
menu.removeItem(123)
assertEquals(1, menu.size)
}
@Test fun isEmpty() {
assertTrue(menu.isEmpty())
menu.add("")
assertFalse(menu.isEmpty())
}
@Test fun isNotEmpty() {
assertFalse(menu.isNotEmpty())
menu.add("")
assertTrue(menu.isNotEmpty())
}
@Test fun forEach() {
menu.forEach {
fail("Empty menu should not invoke lambda")
}
val item1 = menu.add("")
val item2 = menu.add("")
val items = mutableListOf<MenuItem>()
menu.forEach {
items += it
}
assertThat(items).containsExactly(item1, item2)
}
@Test fun forEachIndexed() {
menu.forEachIndexed { _, _ ->
fail("Empty menu should not invoke lambda")
}
val item1 = menu.add("")
val item2 = menu.add("")
val items = mutableListOf<MenuItem>()
menu.forEachIndexed { index, item ->
assertEquals(index, items.size)
items += item
}
assertThat(items).containsExactly(item1, item2)
}
@Test fun iterator() {
val item1 = menu.add("")
val item2 = menu.add("")
val iterator = menu.iterator()
assertTrue(iterator.hasNext())
assertSame(item1, iterator.next())
assertTrue(iterator.hasNext())
assertSame(item2, iterator.next())
assertFalse(iterator.hasNext())
assertThrows<IndexOutOfBoundsException> {
iterator.next()
}
}
@Test fun iteratorRemoving() {
val item1 = menu.add(NONE, 9, NONE, "")
val item2 = menu.add(NONE, 13, NONE, "")
val iterator = menu.iterator()
assertSame(item1, iterator.next())
iterator.remove()
assertFalse(item1 in menu)
assertEquals(1, menu.size())
assertSame(item2, iterator.next())
iterator.remove()
assertFalse(item2 in menu)
assertEquals(0, menu.size())
}
@Test fun children() {
val items = listOf(
menu.add(NONE, 1, NONE, ""),
menu.add(NONE, 2, NONE, ""),
menu.add(NONE, 3, NONE, "")
)
menu.children.forEachIndexed { index, child ->
assertSame(items[index], child)
}
}
@Test fun removeItemAt() {
val item1 = menu.add(NONE, 9, NONE, "")
val item2 = menu.add(NONE, 13, NONE, "")
menu.removeItemAt(0)
assertFalse(item1 in menu)
assertEquals(1, menu.size())
menu.removeItemAt(0)
assertFalse(item2 in menu)
assertEquals(0, menu.size())
}
}
| apache-2.0 | 2a878428d477d89a5c64d2326b379e40 | 25.648045 | 92 | 0.602516 | 4.187884 | false | true | false | false |
AndroidX/androidx | room/room-runtime/src/main/java/androidx/room/util/DBUtil.kt | 3 | 7538 | /*
* 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.
*/
@file:JvmName("DBUtil")
@file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
package androidx.room.util
import android.database.AbstractWindowedCursor
import android.database.Cursor
import android.database.sqlite.SQLiteConstraintException
import android.os.Build
import android.os.CancellationSignal
import androidx.annotation.RestrictTo
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteCompat
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteQuery
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.nio.ByteBuffer
/**
* Performs the SQLiteQuery on the given database.
*
* This util method encapsulates copying the cursor if the `maybeCopy` parameter is
* `true` and either the api level is below a certain threshold or the full result of the
* query does not fit in a single window.
*
* @param db The database to perform the query on.
* @param sqLiteQuery The query to perform.
* @param maybeCopy True if the result cursor should maybe be copied, false otherwise.
* @return Result of the query.
*
*/
@Deprecated(
"This is only used in the generated code and shouldn't be called directly."
)
fun query(db: RoomDatabase, sqLiteQuery: SupportSQLiteQuery, maybeCopy: Boolean): Cursor {
return query(db, sqLiteQuery, maybeCopy, null)
}
/**
* Performs the SQLiteQuery on the given database.
*
* This util method encapsulates copying the cursor if the `maybeCopy` parameter is
* `true` and either the api level is below a certain threshold or the full result of the
* query does not fit in a single window.
*
* @param db The database to perform the query on.
* @param sqLiteQuery The query to perform.
* @param maybeCopy True if the result cursor should maybe be copied, false otherwise.
* @param signal The cancellation signal to be attached to the query.
* @return Result of the query.
*/
fun query(
db: RoomDatabase,
sqLiteQuery: SupportSQLiteQuery,
maybeCopy: Boolean,
signal: CancellationSignal?
): Cursor {
val cursor = db.query(sqLiteQuery, signal)
if (maybeCopy && cursor is AbstractWindowedCursor) {
val rowsInCursor = cursor.count // Should fill the window.
val rowsInWindow = if (cursor.hasWindow()) {
cursor.window.numRows
} else {
rowsInCursor
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M || rowsInWindow < rowsInCursor) {
return copyAndClose(cursor)
}
}
return cursor
}
/**
* Drops all FTS content sync triggers created by Room.
*
* FTS content sync triggers created by Room are those that are found in the sqlite_master table
* who's names start with 'room_fts_content_sync_'.
*
* @param db The database.
*/
fun dropFtsSyncTriggers(db: SupportSQLiteDatabase) {
val existingTriggers = buildList {
db.query("SELECT name FROM sqlite_master WHERE type = 'trigger'").useCursor { cursor ->
while (cursor.moveToNext()) {
add(cursor.getString(0))
}
}
}
existingTriggers.forEach { triggerName ->
if (triggerName.startsWith("room_fts_content_sync_")) {
db.execSQL("DROP TRIGGER IF EXISTS $triggerName")
}
}
}
/**
* Checks for foreign key violations by executing a PRAGMA foreign_key_check.
*/
fun foreignKeyCheck(
db: SupportSQLiteDatabase,
tableName: String
) {
db.query("PRAGMA foreign_key_check(`$tableName`)").useCursor { cursor ->
if (cursor.count > 0) {
val errorMsg = processForeignKeyCheckFailure(cursor)
throw SQLiteConstraintException(errorMsg)
}
}
}
/**
* Reads the user version number out of the database header from the given file.
*
* @param databaseFile the database file.
* @return the database version
* @throws IOException if something goes wrong reading the file, such as bad database header or
* missing permissions.
*
* @see [User Version
* Number](https://www.sqlite.org/fileformat.html.user_version_number).
*/
@Throws(IOException::class)
fun readVersion(databaseFile: File): Int {
FileInputStream(databaseFile).channel.use { input ->
val buffer = ByteBuffer.allocate(4)
input.tryLock(60, 4, true)
input.position(60)
val read = input.read(buffer)
if (read != 4) {
throw IOException("Bad database header, unable to read 4 bytes at offset 60")
}
buffer.rewind()
return buffer.int // ByteBuffer is big-endian by default
}
}
/**
* CancellationSignal is only available from API 16 on. This function will create a new
* instance of the Cancellation signal only if the current API > 16.
*
* @return A new instance of CancellationSignal or null.
*/
fun createCancellationSignal(): CancellationSignal? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
SupportSQLiteCompat.Api16Impl.createCancellationSignal()
} else {
null
}
}
/**
* Converts the [Cursor] returned in case of a foreign key violation into a detailed
* error message for debugging.
*
* The foreign_key_check pragma returns one row output for each foreign key violation.
*
* The cursor received has four columns for each row output. The first column is the name of
* the child table. The second column is the rowId of the row that contains the foreign key
* violation (or NULL if the child table is a WITHOUT ROWID table). The third column is the
* name of the parent table. The fourth column is the index of the specific foreign key
* constraint that failed.
*
* @param cursor Cursor containing information regarding the FK violation
* @return Error message generated containing debugging information
*/
private fun processForeignKeyCheckFailure(cursor: Cursor): String {
return buildString {
val rowCount = cursor.count
val fkParentTables = mutableMapOf<String, String>()
while (cursor.moveToNext()) {
if (cursor.isFirst) {
append("Foreign key violation(s) detected in '")
append(cursor.getString(0)).append("'.\n")
}
val constraintIndex = cursor.getString(3)
if (!fkParentTables.containsKey(constraintIndex)) {
fkParentTables[constraintIndex] = cursor.getString(2)
}
}
append("Number of different violations discovered: ")
append(fkParentTables.keys.size).append("\n")
append("Number of rows in violation: ")
append(rowCount).append("\n")
append("Violation(s) detected in the following constraint(s):\n")
for ((key, value) in fkParentTables) {
append("\tParent Table = ")
append(value)
append(", Foreign Key Constraint Index = ")
append(key).append("\n")
}
}
} | apache-2.0 | 26b5121e0448faca31c3b2fa1e0bd8c6 | 34.394366 | 96 | 0.689838 | 4.292711 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/foundation/src/main/kotlin/com/teamwizardry/librarianlib/foundation/block/BaseButtonBlock.kt | 1 | 2726 | package com.teamwizardry.librarianlib.foundation.block
import com.teamwizardry.librarianlib.core.util.loc
import net.minecraft.block.AbstractButtonBlock
import net.minecraft.block.BlockState
import net.minecraft.block.StairsBlock
import net.minecraft.state.properties.Half
import net.minecraft.state.properties.StairsShape
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraft.world.server.ServerWorld
import net.minecraftforge.client.model.generators.BlockStateProvider
import net.minecraftforge.client.model.generators.ConfiguredModel
import java.util.*
public abstract class BaseButtonBlock(
override val properties: FoundationBlockProperties,
protected val textureName: String
) : AbstractButtonBlock(false, properties.vanillaProperties), IFoundationBlock {
public abstract val pressDuration: Int
override fun generateBlockState(gen: BlockStateProvider) {
val texture = gen.modLoc("block/$textureName")
val unpressedModel = gen.models()
.withExistingParent(registryName!!.path, loc("block/button"))
.texture("texture", texture)
val pressedModel = gen.models()
.withExistingParent(registryName!!.path + "_down", loc("block/button_pressed"))
.texture("texture", texture)
gen.horizontalFaceBlock(this, { state -> if(state.get(POWERED)) pressedModel else unpressedModel }, 180)
gen.itemModels().singleTexture("block/${registryName!!.path}_inventory", loc("block/button_inventory"), texture)
}
override fun inventoryModelName(): String {
return "block/${registryName!!.path}_inventory"
}
override fun powerBlock(state: BlockState, world: World, pos: BlockPos) {
setPressed(state, world, pos, true, playSound = false)
}
override fun tick(state: BlockState, world: ServerWorld, pos: BlockPos, rand: Random?) {
setPressed(state, world, pos, false, playSound = true)
}
protected fun setPressed(state: BlockState, world: World, pos: BlockPos, pressed: Boolean, playSound: Boolean) {
if (pressed != state.get(POWERED)) {
world.setBlockState(pos, state.with(POWERED, pressed), 3)
this.updateNeighbors(state, world, pos)
if (pressed) {
world.pendingBlockTicks.scheduleTick(BlockPos(pos), this, pressDuration)
}
if(playSound) {
playSound(null, world, pos, pressed)
}
}
}
private fun updateNeighbors(state: BlockState, world: World, pos: BlockPos) {
world.notifyNeighborsOfStateChange(pos, this)
world.notifyNeighborsOfStateChange(pos.offset(getFacing(state).opposite), this)
}
} | lgpl-3.0 | 490618f227e23c973a4f953855317111 | 40.953846 | 120 | 0.706163 | 4.347687 | false | false | false | false |
nrizzio/Signal-Android | qr/lib/src/main/java/org/signal/qr/QrProcessor.kt | 1 | 2295 | package org.signal.qr
import androidx.annotation.RequiresApi
import androidx.camera.core.ImageProxy
import com.google.zxing.BinaryBitmap
import com.google.zxing.ChecksumException
import com.google.zxing.DecodeHintType
import com.google.zxing.FormatException
import com.google.zxing.LuminanceSource
import com.google.zxing.NotFoundException
import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.Result
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import org.signal.core.util.logging.Log
/**
* Wraps [QRCodeReader] for use from API19 or API21+.
*/
class QrProcessor {
private val reader = QRCodeReader()
private var previousHeight = 0
private var previousWidth = 0
@RequiresApi(21)
fun getScannedData(proxy: ImageProxy): String? {
return getScannedData(ImageProxyLuminanceSource(proxy))
}
fun getScannedData(
data: ByteArray,
width: Int,
height: Int
): String? {
return getScannedData(PlanarYUVLuminanceSource(data, width, height, 0, 0, width, height, false))
}
private fun getScannedData(source: LuminanceSource): String? {
try {
if (source.width != previousWidth || source.height != previousHeight) {
Log.i(TAG, "Processing ${source.width} x ${source.height} image")
previousWidth = source.width
previousHeight = source.height
}
listener?.invoke(source)
val bitmap = BinaryBitmap(HybridBinarizer(source))
val result: Result? = reader.decode(bitmap, mapOf(DecodeHintType.TRY_HARDER to true, DecodeHintType.CHARACTER_SET to "ISO-8859-1"))
if (result != null) {
return result.text
}
} catch (e: NullPointerException) {
Log.w(TAG, "Random null", e)
} catch (e: ChecksumException) {
Log.w(TAG, "QR code read and decoded, but checksum failed", e)
} catch (e: FormatException) {
Log.w(TAG, "Thrown when a barcode was successfully detected, but some aspect of the content did not conform to the barcodes format rules.", e)
} catch (e: NotFoundException) {
// Thanks ZXing...
}
return null
}
companion object {
private val TAG = Log.tag(QrProcessor::class.java)
/** For debugging only */
var listener: ((LuminanceSource) -> Unit)? = null
}
}
| gpl-3.0 | c90c0ea4ae9c1b7fb67337da5b9f7713 | 30.438356 | 148 | 0.709804 | 3.844221 | false | false | false | false |
DUBattleCode/TournamentFramework | src/main/java/org/DUCodeWars/framework/player/net/NetHandler.kt | 2 | 2616 | package org.DUCodeWars.framework.player.net
import com.google.gson.JsonObject
import org.DUCodeWars.framework.player.AbstractPlayer
import org.DUCodeWars.framework.server.net.Serialisation
import org.DUCodeWars.framework.server.net.packets.PacketSer
import org.DUCodeWars.framework.server.net.packets.Response
import org.DUCodeWars.framework.server.net.packets.notifications.NotificationResponse
import org.DUCodeWars.framework.server.net.packets.notifications.packets.*
import org.DUCodeWars.framework.server.net.packets.packets.NamePS
import org.DUCodeWars.framework.server.net.packets.packets.NameResponse
abstract class NetHandler<out P : AbstractPlayer>(host: String, port: Int, val player: P) {
private val client = Client(host, port)
private var run = true
private val packets: MutableMap<String, (JsonObject) -> Response> = mutableMapOf()
fun registerPacket(action: String, function: (JsonObject) -> Response, serialiser: PacketSer<*, *>) {
packets.put(action, function)
Serialisation.addSerialiser(serialiser)
}
abstract fun registerPackets()
fun start() {
registerPacket("name", { json -> name(json) }, NamePS())
registerPacket("alive", { json -> alive(json) }, AlivePS())
registerPacket("id", { json -> id(json) }, IdPS())
registerPacket("disqualify", { json -> disqualify(json) }, DisqualifyPS())
registerPackets()
while (true) {
val read = client.readJSON()
val response = getResponse(read)
client.writeJSON(Serialisation.serResponse(response))
}
}
private fun getResponse(json: JsonObject): Response {
val action = json["action"].asString
val response = packets[action]!!(json)
return response
}
private fun alive(@Suppress("UNUSED_PARAMETER") request: JsonObject): NotificationResponse {
return NotificationResponse(request)
}
private fun disqualify(request: JsonObject): NotificationResponse {
val disqualifyRequest = Serialisation.deserRequest<DisqualifyRequest>(request)
player.playerDisqualified(disqualifyRequest.disqualifiedId, disqualifyRequest.reason)
return NotificationResponse(request)
}
private fun id(request: JsonObject): NotificationResponse {
val idRequest = Serialisation.deserRequest<IdRequest>(request)
player.id = idRequest.id
return NotificationResponse(request)
}
private fun name(@Suppress("UNUSED_PARAMETER") request: JsonObject): NameResponse {
return NameResponse(player.name, player.creator)
}
} | mit | 4bdd997afca767e581463023a4201c2e | 39.890625 | 105 | 0.715596 | 4.494845 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/util/Taggable.kt | 1 | 1925 | package org.andstatus.app.util
import org.andstatus.app.util.Taggable.Companion.noNameTag
import kotlin.reflect.KClass
private fun klassToStringTag(clazz: KClass<*>) = clazz.simpleName ?: noNameTag
/**
* We may override classTag method, providing e.g. "static final String TAG"
* instead of directly calling getClass().getSimpleName() each time its needed,
* because of its performance issue, see https://bugs.openjdk.java.net/browse/JDK-8187123
* @author [email protected]
*/
interface Taggable {
/** We override this method in order to solve Java's problem of getSimpleName() performance */
val classTag: String get() = klassToStringTag(this::class)
companion object {
const val MAX_TAG_LENGTH = 23
const val noNameTag: String = "NoName"
/** Truncated to [.MAX_TAG_LENGTH] */
fun anyToTruncatedTag(anyTag: Any?): String {
val tag: String = anyToTag(anyTag)
return if (tag.length > MAX_TAG_LENGTH) tag.substring(0, MAX_TAG_LENGTH) else tag
}
fun anyToTag(anyTag: Any?): String {
val tag: String = when (anyTag) {
null -> "(null)"
is Identifiable -> anyTag.instanceTag
is Taggable -> anyTag.classTag
is String -> anyTag
is Enum<*> -> anyTag.toString()
is KClass<*> -> klassToStringTag(anyTag)
is Class<*> -> anyTag.simpleName
else -> klassToStringTag(anyTag::class)
}
return if (tag.trim { it <= ' ' }.isEmpty()) {
"(empty)"
} else tag
}
}
}
/** To be used as a delegate implementing [Taggable]
* See [Delegation](https://kotlinlang.org/docs/delegation.html) */
class TaggedInstance(tag: String) : Taggable {
constructor(clazz: KClass<*>) : this(klassToStringTag(clazz))
override val classTag: String = tag
}
| apache-2.0 | db8651e1dd63e9bb38b93654c2902a0e | 35.320755 | 99 | 0.616104 | 4.095745 | false | false | false | false |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/extensions/SnackbarExtensions.kt | 1 | 2271 | /*
* Copyright (c) 2019 52inc.
*
* 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.ftinc.kit.extensions
import android.app.Activity
import androidx.annotation.IdRes
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar
import androidx.fragment.app.Fragment
import android.view.View
internal fun Activity.find(@IdRes resId: Int) = this.findViewById<View>(resId)
fun Activity.snackbar(message: String, duration: Int = Snackbar.LENGTH_SHORT) = snackbar(find(android.R.id.content), message, duration)
fun Activity.snackbar(@StringRes message: Int, duration: Int = Snackbar.LENGTH_SHORT) = snackbar(find(android.R.id.content), message, duration)
fun Activity.snackbar(view: View, message: String, duration: Int = Snackbar.LENGTH_SHORT) = Snackbar.make(view, message, duration).show()
fun Activity.snackbar(view: View, @StringRes message: Int, duration: Int = Snackbar.LENGTH_SHORT) = Snackbar.make(view, message, duration).show()
fun Fragment.snackbar(message: String, duration: Int = Snackbar.LENGTH_SHORT) = view?.let { snackbar(it, message, duration) }
fun Fragment.snackbar(@StringRes message: Int, duration: Int = Snackbar.LENGTH_SHORT) = view?.let { snackbar(it, message, duration) }
fun Fragment.snackbar(view: View, message: String) = snackbar(view, message, Snackbar.LENGTH_SHORT)
fun Fragment.snackbar(view: View, @StringRes message: Int) = snackbar(view, message, Snackbar.LENGTH_SHORT)
fun Fragment.snackbar(view: View, message: String, duration: Int) = com.google.android.material.snackbar.Snackbar.make(view, message, duration).show()
fun Fragment.snackbar(view: View, @StringRes message: Int, duration: Int) = com.google.android.material.snackbar.Snackbar.make(view, message, duration).show()
| apache-2.0 | f407ef2fdccd60f74b25048e010f0036 | 55.775 | 158 | 0.767063 | 3.836149 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/errorreporter/AnonymousFeedback.kt | 1 | 12511 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.errorreporter
import com.demonwav.mcdev.update.PluginUtil
import com.demonwav.mcdev.util.HttpConnectionFactory
import com.demonwav.mcdev.util.fromJson
import com.google.gson.Gson
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.util.text.StringUtil
import java.net.HttpURLConnection
import java.nio.ByteBuffer
import java.nio.charset.CodingErrorAction
import org.apache.commons.httpclient.HttpStatus
import org.apache.commons.io.IOUtils
import org.apache.http.HttpHeaders
import org.apache.http.entity.ContentType
object AnonymousFeedback {
data class FeedbackData(val url: String, val token: Int, val isDuplicate: Boolean)
private const val authedUrl = "https://www.denwav.dev/errorReport"
private const val baseUrl = "https://api.github.com/repos/minecraft-dev/mcdev-error-report/issues"
fun sendFeedback(
factory: HttpConnectionFactory,
envDetails: LinkedHashMap<String, String?>,
attachments: List<Attachment>
): FeedbackData {
val duplicateId = findDuplicateIssue(envDetails, factory)
if (duplicateId != null) {
// This is a duplicate
val issueContent = convertToGitHubIssueFormat(envDetails, attachments)
val commentUrl = sendCommentOnDuplicateIssue(duplicateId, factory, issueContent)
return FeedbackData(commentUrl, duplicateId, true)
}
val (htmlUrl, token) = sendFeedback(factory, convertToGitHubIssueFormat(envDetails, attachments))
return FeedbackData(htmlUrl, token, false)
}
private fun convertToGitHubIssueFormat(
envDetails: LinkedHashMap<String, String?>,
attachments: List<Attachment>
): ByteArray {
val result = LinkedHashMap<String, String>(5)
result["title"] = "[auto-generated] Exception in plugin"
result["body"] = generateGitHubIssueBody(envDetails, attachments)
return Gson().toJson(result).toByteArray()
}
private fun generateGitHubIssueBody(body: LinkedHashMap<String, String?>, attachments: List<Attachment>): String {
val errorDescription = body.remove("error.description") ?: ""
var errorMessage = body.remove("error.message")
if (errorMessage.isNullOrBlank()) {
errorMessage = "no error"
}
val rawStackTrace = body.remove("error.raw_stacktrace")?.takeIf { it.isNotBlank() } ?: "no stacktrace"
val stackTrace = body.remove("error.stacktrace")?.takeIf { it.isNotBlank() } ?: "no stacktrace"
val sb = StringBuilder()
if (errorDescription.isNotEmpty()) {
sb.append(errorDescription).append("\n\n")
}
sb.append("<table><tr><td><table>\n")
for ((i, entry) in body.entries.withIndex()) {
if (i == 6) {
sb.append("</table></td><td><table>\n")
}
val (key, value) = entry
sb.append("<tr><td><b>")
.append(key)
.append("</b></td><td><code>")
.append(value)
.append("</code></td></tr>\n")
}
sb.append("</table></td></tr></table>\n")
sb.append("\n<pre><code>").append(stackTrace).append("</code></pre>\n")
sb.append("\n<details><summary>Original stack trace</summary>\n\n```\n")
.append(rawStackTrace)
.append("\n```\n</details>\n")
sb.append("\n```\n").append(errorMessage).append("\n```\n")
if (attachments.isNotEmpty()) {
for (attachment in attachments) {
sb.append("\n---\n\n```\n").append(attachment.name).append("\n```\n")
sb.append("```\n")
try {
// No clue what the data format of the attachment is
// but if we try to decode it as UTF-8 and it succeeds, chances are likely that's what it is
val charBuf = Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(attachment.bytes))
val text = charBuf.toString()
if (text != attachment.displayText) {
sb.append(attachment.displayText).append("\n```\n")
sb.append("```\n")
}
sb.append(text)
} catch (e: Exception) {
// Guess it's not text...
sb.append(attachment.displayText).append("\n```\n")
sb.append("```\n")
sb.append(attachment.encodedBytes)
}
sb.append("\n```\n")
}
}
return sb.toString()
}
private fun sendFeedback(factory: HttpConnectionFactory, payload: ByteArray): Pair<String, Int> {
val connection = getConnection(factory, authedUrl)
connection.connect()
val json = executeCall(connection, payload)
return json["html_url"] as String to (json["number"] as Double).toInt()
}
private fun connect(factory: HttpConnectionFactory, url: String): HttpURLConnection {
val connection = factory.openHttpConnection(url)
connection.connectTimeout = 5000
connection.readTimeout = 5000
return connection
}
private const val openIssueUrl = "$baseUrl?state=open&creator=minecraft-dev-autoreporter&per_page=100"
private const val closedIssueUrl = "$baseUrl?state=closed&creator=minecraft-dev-autoreporter&per_page=100"
private const val packagePrefix = "\tat com.demonwav.mcdev"
private fun findDuplicateIssue(envDetails: LinkedHashMap<String, String?>, factory: HttpConnectionFactory): Int? {
val numberRegex = Regex("\\d+")
val newLineRegex = Regex("[\r\n]+")
val stack = envDetails["error.raw_stacktrace"]?.replace(numberRegex, "") ?: return null
val ourMcdevParts = stack.lineSequence()
.filter { line -> line.startsWith(packagePrefix) }
.map { it.trim() }
.toList()
if (ourMcdevParts.isEmpty()) {
return null
}
val predicate = fun(map: Map<*, *>): Boolean {
val body = (map["body"] as? String ?: return false)
.replace(numberRegex, "")
.replace(newLineRegex, "\n")
// We can't comment on locked issues
if (map["locked"] as Boolean) {
return false
}
val first = body.indexOf("\n```\n", startIndex = 0) + 5
val second = body.indexOf("\n```\n", startIndex = first)
if (first == 4 || second == -1) {
return false
}
val stackText = body.substring(first, second)
val theirMcdevParts = stackText.lineSequence()
.filter { line -> line.startsWith(packagePrefix) }
.map { it.trim() }
.toList()
return ourMcdevParts == theirMcdevParts
}
// Look first for an open issue, then for a closed issue if one isn't found
val block = getAllIssues(openIssueUrl, factory)?.firstOrNull(predicate)
?: getAllIssues(closedIssueUrl, factory, limit = 300)?.firstOrNull(predicate)
?: return null
return (block["number"] as Double).toInt()
}
private fun getMcdevStackElementLines(stack: String, numberRegex: Regex, linkRegex: Regex): List<String> {
return stack.lineSequence()
.mapNotNull { line -> linkRegex.matchEntire(line)?.groups?.get("content")?.value }
.map { line -> StringUtil.unescapeXmlEntities(line) }
.map { line -> line.replace(numberRegex, "") }
.toList()
}
private fun getAllIssues(url: String, factory: HttpConnectionFactory, limit: Int = -1): List<Map<*, *>>? {
var useAuthed = false
var next: String? = url
val list = mutableListOf<Map<*, *>>()
while (next != null) {
val connection: HttpURLConnection = connect(factory, next)
try {
connection.requestMethod = "GET"
connection.setRequestProperty("User-Agent", userAgent)
connection.connect()
if (connection.responseCode == HttpStatus.SC_FORBIDDEN && !useAuthed) {
useAuthed = true
next = replaceWithAuth(next)
continue
}
if (connection.responseCode != HttpStatus.SC_OK) {
return null
}
val charset = connection.getHeaderField(HttpHeaders.CONTENT_TYPE)?.let {
ContentType.parse(it).charset
} ?: Charsets.UTF_8
val data = connection.inputStream.reader(charset).readText()
val response = Gson().fromJson<List<Map<*, *>>>(data)
list.addAll(response)
if (limit > 0 && list.size >= limit) {
return list
}
val link = connection.getHeaderField("Link")
next = getNextLink(link, useAuthed)
} finally {
connection.disconnect()
}
}
return list
}
private fun getNextLink(linkHeader: String?, useAuthed: Boolean): String? {
if (linkHeader == null) {
return null
}
val links = linkHeader.split(",")
for (link in links) {
if (!link.contains("rel=\"next\"")) {
continue
}
val parts = link.split(";")
if (parts.isEmpty()) {
continue
}
val nextUrl = parts[0].trim().removePrefix("<").removeSuffix(">")
if (!useAuthed) {
return nextUrl
}
return replaceWithAuth(nextUrl)
}
return null
}
private fun replaceWithAuth(url: String): String? {
// non-authed-API requests are rate limited at 60 / hour / IP
// authed requests have a rate limit of 5000 / hour / account
// We don't want to use the authed URL by default since all users would use the same rate limit
// but it's a good fallback when the non-authed API stops working.
val index = url.indexOf('?')
if (index == -1) {
return null
}
return authedUrl + url.substring(index)
}
private fun sendCommentOnDuplicateIssue(id: Int, factory: HttpConnectionFactory, payload: ByteArray): String {
val commentUrl = "$authedUrl/$id/comments"
val connection = getConnection(factory, commentUrl)
val json = executeCall(connection, payload)
return json["html_url"] as String
}
private fun executeCall(connection: HttpURLConnection, payload: ByteArray): Map<*, *> {
connection.outputStream.use {
it.write(payload)
}
val responseCode = connection.responseCode
if (responseCode != HttpStatus.SC_CREATED) {
throw RuntimeException("Expected HTTP_CREATED (201), obtained $responseCode instead.")
}
val contentEncoding = connection.contentEncoding ?: "UTF-8"
val body = connection.inputStream.use {
IOUtils.toString(it, contentEncoding)
}
connection.disconnect()
return Gson().fromJson(body)
}
private fun getConnection(factory: HttpConnectionFactory, url: String): HttpURLConnection {
val connection = connect(factory, url)
connection.doOutput = true
connection.requestMethod = "POST"
connection.setRequestProperty("User-Agent", userAgent)
connection.setRequestProperty("Content-Type", "application/json")
return connection
}
private val userAgent by lazy {
var agent = "Minecraft Development IntelliJ IDEA plugin"
val pluginDescription = PluginManagerCore.getPlugin(PluginUtil.PLUGIN_ID)
if (pluginDescription != null) {
val name = pluginDescription.name
val version = pluginDescription.version
agent = "$name ($version)"
}
agent
}
}
| mit | 47f524337cfc34eba0e0becad3528382 | 35.68915 | 118 | 0.583886 | 4.666542 | false | false | false | false |
mwolfson/android-historian | app/src/main/java/com/designdemo/uaha/view/product/ProductActivity.kt | 1 | 6496 | package com.designdemo.uaha.view.product
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.designdemo.uaha.util.UiUtil
import com.designdemo.uaha.view.demo.BottomNavActivity
import com.designdemo.uaha.view.demo.MotionLayoutActivity
import com.designdemo.uaha.view.product.device.DeviceFragment
import com.designdemo.uaha.view.product.fav.FavFragment
import com.designdemo.uaha.view.product.os.OsFragment
import com.designdemo.uaha.view.user.UserActivity
import com.google.android.material.navigation.NavigationView
import com.support.android.designlibdemo.R
import kotlinx.android.synthetic.main.activity_detail.bottom_appbar
import kotlinx.android.synthetic.main.activity_main.drawer_layout
import kotlinx.android.synthetic.main.activity_main.nav_view
import kotlinx.android.synthetic.main.activity_main.product_tabs
import kotlinx.android.synthetic.main.activity_main.product_viewpager
class ProductActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.Base_Theme_DesignDemo)
setContentView(R.layout.activity_main)
val bottomAppBar = bottom_appbar
setSupportActionBar(bottomAppBar)
bottomAppBar.replaceMenu(R.menu.main_actions)
val ab = supportActionBar
ab?.setHomeAsUpIndicator(R.drawable.vct_menu)
ab?.setDisplayHomeAsUpEnabled(true)
val navigationView = nav_view
if (navigationView != null) {
setupDrawerContent(navigationView)
val headerView = navigationView.getHeaderView(0)
if (headerView != null) {
val versionText = headerView.findViewById<TextView>(R.id.header_versioninfo)
versionText.text = UiUtil.versionInfo(this)
val appTitleText = headerView.findViewById<TextView>(R.id.header_apptitle)
appTitleText.setOnClickListener {
val playStore = Intent(Intent.ACTION_VIEW, Uri.parse(
"https://play.google.com/store/apps/details?id=com.ableandroid.historian"))
startActivity(playStore)
}
}
}
setupViewPager(product_viewpager)
product_viewpager?.currentItem = intent.getIntExtra(EXTRA_FRAG_TYPE, OS_FRAG)
product_tabs?.setupWithViewPager(product_viewpager)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main_actions, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
drawer_layout.openDrawer(GravityCompat.START)
return true
}
R.id.menu_help -> {
val bottomNavIntent = Intent(applicationContext, BottomNavActivity::class.java)
startActivity(bottomNavIntent)
}
}
return super.onOptionsItemSelected(item)
}
private fun setupViewPager(viewPager: ViewPager) {
val adapter = Adapter(supportFragmentManager)
val osFrag = OsFragment()
val deviceFrag = DeviceFragment()
val favFrag = FavFragment()
adapter.addFragment(osFrag, getString(R.string.os_version))
adapter.addFragment(deviceFrag, getString(R.string.devices))
adapter.addFragment(favFrag, getString(R.string.favorites))
viewPager.adapter = adapter
}
private fun setupDrawerContent(navigationView: NavigationView) {
navigationView.setNavigationItemSelectedListener { menuItem ->
val retVal: Boolean
menuItem.isChecked = true
when (menuItem.itemId) {
R.id.nav_userinfo -> {
startActivity(Intent(applicationContext, UserActivity::class.java))
retVal = true
}
R.id.nav_link1 -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.android.com/")))
retVal = true
}
R.id.nav_link2 -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://material.io/")))
retVal = true
}
R.id.nav_bottom_nav -> {
startActivity(Intent(applicationContext, BottomNavActivity::class.java))
retVal = true
}
R.id.nav_motionlayout -> {
startActivity(Intent(applicationContext, MotionLayoutActivity::class.java))
retVal = true
}
R.id.nav_homepage -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("http://www.ableandroid.com/")))
retVal = true
}
R.id.nav_playlink -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/apps/testing/com.ableandroid.historian")))
retVal = true
}
R.id.nav_githublink -> {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/mwolfson/android-historian")))
retVal = true
}
else -> retVal = false
}
retVal
}
}
internal class Adapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
private val fragments = ArrayList<Fragment>()
private val fragmentTitles = ArrayList<String>()
fun addFragment(fragment: Fragment, title: String) {
fragments.add(fragment)
fragmentTitles.add(title)
}
override fun getItem(position: Int) = fragments[position]
override fun getCount() = fragments.size
override fun getPageTitle(position: Int) = fragmentTitles[position]
}
companion object {
const val OS_FRAG = 0
const val DEVICE_FRAG = 1
const val FAV_FRAG = 2
const val EXTRA_FRAG_TYPE = "extraFragType"
}
}
| apache-2.0 | 717a714a6667ec41db5f81241040e2ad | 37.43787 | 138 | 0.634083 | 4.79056 | false | false | false | false |
GavinThePacMan/daysuntil | app/src/main/kotlin/com/gpacini/daysuntil/ui/views/ProgressButton.kt | 2 | 2052 | package com.gpacini.daysuntil.ui.views
import android.content.Context
import android.graphics.PorterDuff
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ProgressBar
import butterknife.bindView
import com.gpacini.daysuntil.R
/**
* Created by gavinpacini on 01/05/2016.
*
* TODO: Add description
*/
class ProgressButton(context: Context, attrs: AttributeSet) : FrameLayout(context, attrs) {
private val btnSave: Button by bindView(R.id.btn)
private val proSave: ProgressBar by bindView(R.id.pro)
private var listener: OnClickListener? = null
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.ProgressButton, 0, 0)
val text = a.getString(R.styleable.ProgressButton_text)
val textColors = a.getColorStateList(R.styleable.ProgressButton_textColor)
val enabled = a.getBoolean(R.styleable.ProgressButton_enabled, true)
a.recycle()
val inflater = LayoutInflater.from(context)
inflater.inflate(R.layout.custom_progressbutton, this)
btnSave.text = text
btnSave.setTextColor(textColors)
btnSave.isEnabled = enabled
proSave.indeterminateDrawable.setColorFilter(textColors.defaultColor, PorterDuff.Mode.SRC_IN);
}
override fun setEnabled(enabled: Boolean) {
btnSave.isEnabled = enabled
}
override fun isEnabled(): Boolean {
return btnSave.isEnabled
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_UP) {
if (btnSave.isEnabled) {
proSave.visibility = View.VISIBLE
btnSave.visibility = View.INVISIBLE
listener?.onClick(this)
}
}
return super.dispatchTouchEvent(event)
}
override fun setOnClickListener(listener: OnClickListener) {
this.listener = listener
}
} | apache-2.0 | 978c80a6c3ee3df4b7e82d62eb45aa8c | 30.106061 | 102 | 0.702729 | 4.451193 | false | false | false | false |
REDNBLACK/advent-of-code2016 | src/main/kotlin/day12/Advent12.kt | 1 | 4846 | package day12
import day12.Operation.Type.*
import parseInput
import splitToLines
/**
--- Day 12: Leonardo's Monorail ---
You finally reach the top floor of this building: a garden with a slanted glass ceiling. Looks like there are no more stars to be had.
While sitting on a nearby bench amidst some tiger lilies, you manage to decrypt some of the files you extracted from the servers downstairs.
According to these documents, Easter Bunny HQ isn't just this building - it's a collection of buildings in the nearby area. They're all connected by a local monorail, and there's another building not far from here! Unfortunately, being night, the monorail is currently not operating.
You remotely connect to the monorail control systems and discover that the boot sequence expects a password. The password-checking logic (your puzzle input) is easy to extract, but the code it uses is strange: it's assembunny code designed for the new computer you just assembled. You'll have to execute the code and get the password.
The assembunny code you've extracted operates on four registers (a, b, c, and d) that start at 0 and can hold any integer. However, it seems to make use of only a few instructions:
cpy x y copies x (either an integer or the value of a register) into register y.
inc x increases the value of register x by one.
dec x decreases the value of register x by one.
jnz x y jumps to an instruction y away (positive means forward; negative means backward), but only if x is not zero.
The jnz instruction moves relative to itself: an offset of -1 would continue at the previous instruction, while an offset of 2 would skip over the next instruction.
For example:
cpy 41 a
inc a
inc a
dec a
jnz a 2
dec a
The above code would set register a to 41, increase its value by 2, decrease its value by 1, and then skip the last dec a (because a is not zero, so the jnz a 2 skips it), leaving register a at 42. When you move past the last instruction, the program halts.
After executing the assembunny code in your puzzle input, what value is left in register a?
--- Part Two ---
As you head down the fire escape to the monorail, you notice it didn't start; register c needs to be initialized to the position of the ignition key.
If you instead initialize register c to be 1, what value is now left in register a?
*/
fun main(args: Array<String>) {
val test = """cpy 41 a
|inc a
|inc a
|dec a
|jnz a 2
|dec a""".trimMargin()
val input = parseInput("day12-input.txt")
println(executeOperations(test, mapOf("a" to 0)) == mapOf("a" to 42))
println(executeOperations(input, mapOf("a" to 0, "b" to 0, "c" to 0, "d" to 0)))
println(executeOperations(input, mapOf("a" to 0, "b" to 0, "c" to 1, "d" to 0)))
}
data class Operation(val type: Operation.Type, val args: List<String>) {
enum class Type { CPY, INC, DEC, JNZ, TGL }
}
fun executeOperations(input: String, initial: Map<String, Int>): Map<String, Int> {
val operations = parseOperations(input)
val registers = initial.values.toIntArray()
var index = 0
fun safeIndex(data: String) = when (data[0]) {
'a' -> 0
'b' -> 1
'c' -> 2
'd' -> 3
else -> null
}
fun safeValue(data: String) = when (data[0]) {
'a' -> registers[0]
'b' -> registers[1]
'c' -> registers[2]
'd' -> registers[3]
else -> data.toInt()
}
while (index < operations.size) {
val (type, arg) = operations[index]
when (type) {
CPY -> safeIndex(arg[1])?.let { registers[it] = safeValue(arg[0]) }
INC -> safeIndex(arg[0])?.let { registers[it] += 1 }
DEC -> safeIndex(arg[0])?.let { registers[it] -= 1 }
JNZ -> if (safeValue(arg[0]) != 0) index += safeValue(arg[1]) - 1
TGL -> {
val changeIndex = index + safeValue(arg[0])
if (changeIndex < operations.size) {
val changeOperation = operations[changeIndex]
val newType = when (changeOperation.type) {
CPY -> JNZ
JNZ -> CPY
TGL -> INC
INC -> DEC
DEC -> INC
}
operations[changeIndex] = changeOperation.copy(type = newType)
}
}
}
index++
}
return initial.keys.toTypedArray().zip(registers.toTypedArray()).toMap()
}
private fun parseOperations(input: String) = input.splitToLines()
.map {
val args = it.split(" ")
val type = Operation.Type.valueOf(args[0].toUpperCase())
Operation(type, args.drop(1).take(2))
}
.toMutableList()
| mit | 52a25ec73f34058829176853e22c4db1 | 38.398374 | 334 | 0.626083 | 3.933442 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/onboarding/OnboardingNavigator.kt | 1 | 1795 | package de.tum.`in`.tumcampusapp.component.ui.onboarding
import android.content.Intent
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.transaction
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.ui.onboarding.di.OnboardingScope
import de.tum.`in`.tumcampusapp.utils.Const
import de.tum.`in`.tumcampusapp.utils.Utils
import javax.inject.Inject
@OnboardingScope
class OnboardingNavigator @Inject constructor(
private val activity: OnboardingActivity
) {
private var didFinishFlow = false
private val fragmentManager: FragmentManager
get() = activity.supportFragmentManager
fun openNext() {
val destination = when (val current = fragmentManager.findFragmentById(R.id.contentFrame)) {
is OnboardingStartFragment -> CheckTokenFragment.newInstance()
is CheckTokenFragment -> OnboardingExtrasFragment.newInstance()
else -> throw IllegalStateException("Invalid fragment ${current?.javaClass?.simpleName}")
}
fragmentManager.transaction {
replace(R.id.contentFrame, destination)
addToBackStack(null)
}
}
fun finish() {
didFinishFlow = true
val intent = Intent(activity, StartupActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
activity.startActivity(intent)
activity.finishAndRemoveTask()
}
fun onClose() {
if (!didFinishFlow) {
// The user opened the onboarding screen and maybe filled out some information, but did
// not finish it completely.
Utils.setSetting(activity, Const.LRZ_ID, "")
Utils.setSetting(activity, Const.ACCESS_TOKEN, "")
}
}
}
| gpl-3.0 | ea8d322eab8f2918dd31fd6ea8c51c28 | 34.196078 | 101 | 0.695822 | 4.748677 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/models/tasks/Task.kt | 1 | 12230 | package com.habitrpg.wearos.habitica.models.tasks
import android.os.Parcel
import android.os.Parcelable
import android.text.Spanned
import com.habitrpg.android.habitica.R
import com.habitrpg.shared.habitica.models.tasks.Attribute
import com.habitrpg.shared.habitica.models.tasks.BaseTask
import com.habitrpg.shared.habitica.models.tasks.Frequency
import com.habitrpg.shared.habitica.models.tasks.TaskType
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import org.json.JSONArray
import org.json.JSONException
import java.util.Date
@JsonClass(generateAdapter = true)
open class Task constructor(): Parcelable, BaseTask {
@Json(name="_id")
var id: String? = null
var userId: String = ""
var priority: Float = 0.0f
var text: String = ""
var notes: String? = null
override var type: TaskType?
get() = TaskType.from(typeValue)
set(value) { typeValue = value?.value }
internal var typeValue: String? = null
var challengeID: String? = null
var challengeBroken: String? = null
var attribute: Attribute?
get() = Attribute.from(attributeValue)
set(value) { attributeValue = value?.value }
var attributeValue: String? = Attribute.STRENGTH.value
var value: Double? = 0.0
var dateCreated: Date? = null
var position: Int = 0
// Habits
var up: Boolean? = false
var down: Boolean? = false
override var counterUp: Int? = 0
override var counterDown: Int? = 0
// todos/dailies
override var completed: Boolean = false
var checklist: List<ChecklistItem>? = listOf()
var reminders: List<RemindersItem>? = listOf()
// dailies
var frequency: Frequency? = null
var everyX: Int? = 0
override var streak: Int? = 0
var startDate: Date? = null
var repeat: Days? = null
// todos
@Json(name="date")
var dueDate: Date? = null
// used for buyable items
var specialTag: String? = ""
@Json(ignore = true)
var parsedText: Spanned? = null
@Json(ignore = true)
var parsedNotes: Spanned? = null
override var isDue: Boolean? = null
var nextDue: List<Date>? = null
// Needed for offline creating/updating
var isSaving: Boolean = false
var hasErrored: Boolean = false
var isCreating: Boolean = false
var yesterDaily: Boolean = true
internal var daysOfMonthString: String? = null
internal var weeksOfMonthString: String? = null
@Json(ignore = true)
private var daysOfMonth: List<Int>? = null
@Json(ignore = true)
private var weeksOfMonth: List<Int>? = null
val completedChecklistCount: Int
get() = checklist?.count { it.completed } ?: 0
val extraLightTaskColor: Int
get() {
val value = value ?: 0.0
return when {
value < -20 -> return R.color.watch_maroon_200
value < -10 -> return R.color.watch_red_200
value < -1 -> return R.color.watch_orange_200
value < 1 -> return R.color.watch_yellow_200
value < 5 -> return R.color.watch_green_200
value < 10 -> return R.color.watch_teal_200
else -> R.color.watch_blue_200
}
}
val lightTaskColor: Int
get() {
val value = value ?: 0.0
return when {
value < -20 -> return R.color.watch_maroon_100
value < -10 -> return R.color.watch_red_100
value < -1 -> return R.color.watch_orange_100
value < 1 -> return R.color.watch_yellow_100
value < 5 -> return R.color.watch_green_100
value < 10 -> return R.color.watch_teal_100
else -> R.color.watch_blue_100
}
}
val mediumTaskColor: Int
get() {
val value = value ?: 0.0
return when {
value < -20 -> return R.color.watch_maroon_10
value < -10 -> return R.color.watch_red_10
value < -1 -> return R.color.watch_orange_10
value < 1 -> return R.color.watch_yellow_10
value < 5 -> return R.color.watch_green_10
value < 10 -> return R.color.watch_teal_10
else -> R.color.watch_blue_10
}
}
override fun equals(other: Any?): Boolean {
if (other == null) {
return false
}
return if (Task::class.java.isAssignableFrom(other.javaClass)) {
val otherTask = other as? Task
this.id == otherTask?.id
} else {
super.equals(other)
}
}
fun isBeingEdited(task: Task): Boolean {
when {
text != task.text -> return true
notes != task.notes -> return true
reminders != task.reminders -> return true
checklist != task.checklist -> return true
priority != task.priority -> return true
attribute != task.attribute && attribute != null -> return true
}
when (type) {
TaskType.HABIT -> {
return when {
up != task.up -> true
down != task.down -> true
frequency != task.frequency -> true
counterUp != task.counterUp -> true
counterDown != task.counterDown -> true
else -> false
}
}
TaskType.DAILY -> {
return when {
startDate != task.startDate -> true
everyX != task.everyX -> true
frequency != task.frequency -> true
repeat != task.repeat -> true
streak != task.streak -> true
else -> false
}
}
TaskType.TODO -> {
return dueDate != task.dueDate
}
TaskType.REWARD -> {
return value != task.value
}
else -> {
return false
}
}
}
override fun hashCode(): Int {
return id?.hashCode() ?: 0
}
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(this.userId)
dest.writeValue(this.priority)
dest.writeString(this.text)
dest.writeString(this.notes)
dest.writeString(this.attribute?.value)
dest.writeString(this.type?.value)
this.value?.let { dest.writeDouble(it) }
dest.writeLong(this.dateCreated?.time ?: -1)
dest.writeInt(this.position)
dest.writeValue(this.up)
dest.writeValue(this.down)
dest.writeByte(if (this.completed) 1.toByte() else 0.toByte())
dest.writeList(this.checklist as? List<*>)
dest.writeList(this.reminders as? List<*>)
dest.writeString(this.frequency?.value)
dest.writeValue(this.everyX)
dest.writeString(this.daysOfMonthString)
dest.writeString(this.weeksOfMonthString)
dest.writeValue(this.streak)
dest.writeLong(this.startDate?.time ?: -1)
dest.writeParcelable(this.repeat, flags)
dest.writeLong(this.dueDate?.time ?: -1)
dest.writeString(this.specialTag)
dest.writeString(this.id)
dest.writeInt(this.counterUp ?: 0)
dest.writeInt(this.counterDown ?: 0)
}
protected constructor(`in`: Parcel): this() {
this.userId = `in`.readString() ?: ""
this.priority = `in`.readValue(Float::class.java.classLoader) as? Float ?: 0f
this.text = `in`.readString() ?: ""
this.notes = `in`.readString()
this.attribute = Attribute.from(`in`.readString() ?: "")
this.type = TaskType.from(`in`.readString() ?: "")
this.value = `in`.readDouble()
val tmpDateCreated = `in`.readLong()
this.dateCreated = if (tmpDateCreated == -1L) null else Date(tmpDateCreated)
this.position = `in`.readInt()
this.up = `in`.readValue(Boolean::class.java.classLoader) as? Boolean ?: false
this.down = `in`.readValue(Boolean::class.java.classLoader) as? Boolean ?: false
this.completed = `in`.readByte().toInt() != 0
this.checklist = listOf()
`in`.readList(this.checklist as List<ChecklistItem>, ChecklistItem::class.java.classLoader)
this.reminders = listOf()
`in`.readList(this.reminders as List<RemindersItem>, RemindersItem::class.java.classLoader)
this.frequency = Frequency.from(`in`.readString() ?: "")
this.everyX = `in`.readValue(Int::class.java.classLoader) as? Int ?: 1
this.daysOfMonthString = `in`.readString()
this.weeksOfMonthString = `in`.readString()
this.streak = `in`.readValue(Int::class.java.classLoader) as? Int ?: 0
val tmpStartDate = `in`.readLong()
this.startDate = if (tmpStartDate == -1L) null else Date(tmpStartDate)
this.repeat = `in`.readParcelable(Days::class.java.classLoader)
val tmpDuedate = `in`.readLong()
this.dueDate = if (tmpDuedate == -1L) null else Date(tmpDuedate)
this.specialTag = `in`.readString()
this.id = `in`.readString()
this.counterUp = `in`.readInt()
this.counterDown = `in`.readInt()
}
fun setWeeksOfMonth(weeksOfMonth: List<Int>?) {
this.weeksOfMonth = weeksOfMonth
if ((weeksOfMonth?.size ?: 0) > 0) {
this.weeksOfMonthString = this.weeksOfMonth?.toString()
} else {
weeksOfMonthString = "[]"
}
}
fun getWeeksOfMonth(): List<Int>? {
if (weeksOfMonth == null) {
val weeksOfMonth = mutableListOf<Int>()
if (weeksOfMonthString != null) {
try {
val obj = JSONArray(weeksOfMonthString)
var i = 0
while (i < obj.length()) {
weeksOfMonth.add(obj.getInt(i))
i += 1
}
} catch (e: JSONException) {
}
}
this.weeksOfMonth = weeksOfMonth.toList()
}
return weeksOfMonth
}
fun setDaysOfMonth(daysOfMonth: List<Int>?) {
this.daysOfMonth = daysOfMonth
if ((daysOfMonth?.size ?: 0) > 0) {
this.daysOfMonthString = this.daysOfMonth?.toString()
} else {
daysOfMonthString = "[]"
}
}
fun getDaysOfMonth(): List<Int>? {
if (daysOfMonth == null) {
val daysOfMonth = mutableListOf<Int>()
if (daysOfMonthString != null) {
try {
val obj = JSONArray(daysOfMonthString)
var i = 0
while (i < obj.length()) {
daysOfMonth.add(obj.getInt(i))
i += 1
}
} catch (e: JSONException) {
}
}
this.daysOfMonth = daysOfMonth
}
return daysOfMonth
}
companion object CREATOR : Parcelable.Creator<Task> {
override fun createFromParcel(source: Parcel): Task = Task(source)
override fun newArray(size: Int): Array<Task?> = arrayOfNulls(size)
const val FILTER_ALL = "all"
const val FILTER_WEAK = "weak"
const val FILTER_STRONG = "strong"
const val FILTER_ACTIVE = "active"
const val FILTER_GRAY = "gray"
const val FILTER_DATED = "dated"
const val FILTER_COMPLETED = "completed"
@JvmField
val CREATOR: Parcelable.Creator<Task> = object : Parcelable.Creator<Task> {
override fun createFromParcel(source: Parcel): Task = Task(source)
override fun newArray(size: Int): Array<Task?> = arrayOfNulls(size)
}
}
}
| gpl-3.0 | ed8ce12d9bb44708f5020d8e79270e71 | 35.060606 | 99 | 0.546934 | 4.427951 | false | false | false | false |
Zeyad-37/GenericUseCase | usecases/src/main/java/com/zeyad/usecases/Config.kt | 2 | 802 | package com.zeyad.usecases
import android.annotation.SuppressLint
import android.content.Context
import com.google.gson.Gson
import com.zeyad.usecases.network.ApiConnection
import com.zeyad.usecases.stores.CloudStore
import io.reactivex.Scheduler
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit
@SuppressLint("StaticFieldLeak")
object Config {
val gson: Gson = Gson()
var baseURL: String = ""
var cacheTimeUnit: TimeUnit = TimeUnit.SECONDS
var backgroundThread: Scheduler = Schedulers.io()
var apiConnection: ApiConnection? = null
var cloudStore: CloudStore? = null
var withCache: Boolean = false
var withSQLite: Boolean = false
var useApiWithCache: Boolean = false
var cacheDuration: Long = 0
lateinit var context: Context
} | apache-2.0 | 07e6db009b2de634d7a8dc02d4b24691 | 31.12 | 53 | 0.769327 | 4.311828 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/codegen/coroutines/controlFlow_tryCatch4.kt | 1 | 1089 | import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resume(value: Any?) {}
override fun resumeWithException(exception: Throwable) { throw exception }
}
suspend fun s1(): Int = suspendCoroutineOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
suspend fun s2(): Int = suspendCoroutineOrReturn { x ->
println("s2")
x.resumeWithException(Error())
COROUTINE_SUSPENDED
}
fun f1(): Int {
println("f1")
return 117
}
fun f2(): Int {
println("f2")
return 1
}
fun f3(x: Int, y: Int): Int {
println("f3")
return x + y
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
fun main(args: Array<String>) {
var result = 0
builder {
val x = try {
s2()
} catch (t: Throwable) {
f2()
}
result = x
}
println(result)
} | apache-2.0 | e12ddd7d508f10fc7489bfb33d924dc4 | 19.185185 | 115 | 0.627181 | 3.903226 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsReaderController.kt | 1 | 8367 | package eu.kanade.tachiyomi.ui.setting
import android.os.Build
import android.support.v7.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.SharedData.map
import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys
class SettingsReaderController : SettingsController() {
override fun setupPreferenceScreen(screen: PreferenceScreen) = with(screen) {
titleRes = R.string.pref_category_reader
intListPreference {
key = Keys.defaultViewer
titleRes = R.string.pref_viewer_type
entriesRes = arrayOf(R.string.left_to_right_viewer, R.string.right_to_left_viewer,
R.string.vertical_viewer, R.string.webtoon_viewer)
entryValues = arrayOf("1", "2", "3", "4")
defaultValue = "1"
summary = "%s"
}
intListPreference {
key = Keys.imageScaleType
titleRes = R.string.pref_image_scale_type
entriesRes = arrayOf(R.string.scale_type_fit_screen, R.string.scale_type_stretch,
R.string.scale_type_fit_width, R.string.scale_type_fit_height,
R.string.scale_type_original_size, R.string.scale_type_smart_fit)
entryValues = arrayOf("1", "2", "3", "4", "5", "6")
defaultValue = "1"
summary = "%s"
}
intListPreference {
key = Keys.zoomStart
titleRes = R.string.pref_zoom_start
entriesRes = arrayOf(R.string.zoom_start_automatic, R.string.zoom_start_left,
R.string.zoom_start_right, R.string.zoom_start_center)
entryValues = arrayOf("1", "2", "3", "4")
defaultValue = "1"
summary = "%s"
}
intListPreference {
key = Keys.rotation
titleRes = R.string.pref_rotation_type
entriesRes = arrayOf(R.string.rotation_free, R.string.rotation_lock,
R.string.rotation_force_portrait, R.string.rotation_force_landscape)
entryValues = arrayOf("1", "2", "3", "4")
defaultValue = "1"
summary = "%s"
}
intListPreference {
key = Keys.readerTheme
titleRes = R.string.pref_reader_theme
entriesRes = arrayOf(R.string.white_background, R.string.black_background)
entryValues = arrayOf("0", "1")
defaultValue = "0"
summary = "%s"
}
intListPreference {
key = Keys.doubleTapAnimationSpeed
titleRes = R.string.pref_double_tap_anim_speed
entries = arrayOf(context.getString(R.string.double_tap_anim_speed_0), context.getString(R.string.double_tap_anim_speed_fast), context.getString(R.string.double_tap_anim_speed_normal))
entryValues = arrayOf("1", "250", "500") // using a value of 0 breaks the image viewer, so min is 1
defaultValue = "500"
summary = "%s"
}
switchPreference {
key = Keys.skipRead
titleRes = R.string.pref_skip_read_chapters
defaultValue = false
}
switchPreference {
key = Keys.fullscreen
titleRes = R.string.pref_fullscreen
defaultValue = true
}
switchPreference {
key = Keys.keepScreenOn
titleRes = R.string.pref_keep_screen_on
defaultValue = true
}
switchPreference {
key = Keys.showPageNumber
titleRes = R.string.pref_show_page_number
defaultValue = true
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
switchPreference {
key = Keys.trueColor
titleRes = R.string.pref_true_color
defaultValue = false
}
}
// EXH -->
intListPreference {
key = Keys.eh_readerThreads
title = "Download threads"
entries = arrayOf("1", "2", "3", "4", "5")
entryValues = entries
defaultValue = "2"
summary = "Higher values can speed up image downloading significantly, but can also trigger bans. Recommended value is 2 or 3. Current value is: %s"
}
switchPreference {
key = Keys.eh_aggressivePageLoading
title = "Aggressively load pages"
summary = "Slowly download the entire gallery while reading instead of just loading the pages you are viewing."
defaultValue = false
}
switchPreference {
key = Keys.eh_readerInstantRetry
title = "Skip queue on retry"
summary = "Normally, pressing the retry button on a failed download will wait until the downloader has finished downloading the last page before beginning to re-download the failed page. Enabling this will force the downloader to begin re-downloading the failed page as soon as you press the retry button."
defaultValue = true
}
listPreference {
key = Keys.eh_cacheSize
title = "Reader cache size"
entryValues = arrayOf(
"50",
"75",
"100",
"150",
"250",
"500",
"750",
"1000",
"1500",
"2000",
"2500",
"3000",
"3500",
"4000",
"4500",
"5000"
)
entries = arrayOf(
"50 MB",
"75 MB",
"100 MB",
"150 MB",
"250 MB",
"500 MB",
"750 MB",
"1 GB",
"1.5 GB",
"2 GB",
"2.5 GB",
"3 GB",
"3.5 GB",
"4 GB",
"4.5 GB",
"5 GB"
)
defaultValue = "75"
summary = "The amount of images to save on device while reading. Higher values will result in a smoother reading experience, at the cost of higher disk space usage"
}
switchPreference {
key = Keys.eh_preserveReadingPosition
title = "Preserve reading position on read manga"
defaultValue = false
}
switchPreference {
key = Keys.eh_showTransitionPages
title = "Show transition pages between chapters"
defaultValue = true
}
// EXH <--
preferenceCategory {
titleRes = R.string.pager_viewer
switchPreference {
key = Keys.enableTransitions
titleRes = R.string.pref_page_transitions
defaultValue = true
}
switchPreference {
key = Keys.cropBorders
titleRes = R.string.pref_crop_borders
defaultValue = false
}
}
preferenceCategory {
titleRes = R.string.webtoon_viewer
switchPreference {
key = Keys.cropBordersWebtoon
titleRes = R.string.pref_crop_borders
defaultValue = false
}
}
preferenceCategory {
titleRes = R.string.pref_reader_navigation
switchPreference {
key = Keys.readWithTapping
titleRes = R.string.pref_read_with_tapping
defaultValue = true
}
switchPreference {
key = Keys.readWithLongTap
titleRes = R.string.pref_read_with_long_tap
defaultValue = true
}
switchPreference {
key = Keys.readWithVolumeKeys
titleRes = R.string.pref_read_with_volume_keys
defaultValue = false
}
switchPreference {
key = Keys.readWithVolumeKeysInverted
titleRes = R.string.pref_read_with_volume_keys_inverted
defaultValue = false
}.apply { dependency = Keys.readWithVolumeKeys }
}
}
}
| apache-2.0 | 48ba46422d4d7efb922d1a464966519f | 37.557604 | 318 | 0.518107 | 4.910211 | false | false | false | false |
Bios-Marcel/ServerBrowser | src/main/kotlin/com/msc/serverbrowser/gui/views/ServerView.kt | 1 | 11679 | package com.msc.serverbrowser.gui.views
import com.msc.serverbrowser.Client
import com.msc.serverbrowser.data.entites.Player
import com.msc.serverbrowser.data.entites.SampServer
import com.msc.serverbrowser.gui.components.SampServerTable
import javafx.collections.FXCollections
import javafx.geometry.Orientation
import javafx.scene.control.*
import javafx.scene.control.cell.PropertyValueFactory
import javafx.scene.layout.*
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
class ServerView(client: Client) {
/**
* Root-container of this view.
*/
val rootPane: VBox
val addressTextField: TextField
val connectButton: Button
val addToFavouritesButton: Button
val tableTypeToggleGroup: ToggleGroup
val favouriteButton: RadioButton
val historyButton: RadioButton
val allButton: RadioButton
val serverTable: SampServerTable
val lastJoinTableColumn: TableColumn<SampServer, Long>
val playersTableColumn: TableColumn<SampServer, String>
val playerTable: TableView<Player>
val regexCheckBox: CheckBox
val nameFilterTextField: TextField
val gamemodeFilterTextField: TextField
val languageFilterTextField: TextField
val versionFilterComboBox: ComboBox<String>
val serverAddressTextField: TextField
val serverPingLabel: Label
val serverLagcompLabel: Label
val serverPasswordLabel: Label
val serverMapLabel: Label
val serverWebsiteLink: Hyperlink
init {
/**
* Addressfield and Buttons at the top
*/
addressTextField = TextField()
addressTextField.promptText = Client.getString("promptEnterValidAddress")
connectButton = Button(Client.getString("connect"))
addToFavouritesButton = Button(Client.getString("addToFavourites"))
val addressFieldContainer = HBox(5.0, addressTextField, connectButton, addToFavouritesButton)
HBox.setHgrow(addressTextField, Priority.ALWAYS)
/**
* Buttons for switching the table between favourites-, all- and historymode
*/
favouriteButton = RadioButton(Client.getString("favourites"))
allButton = RadioButton(Client.getString("all"))
historyButton = RadioButton(Client.getString("history"))
favouriteButton.isSelected = true
tableTypeToggleGroup = ToggleGroup()
tableTypeToggleGroup.toggles.addAll(favouriteButton, allButton, historyButton)
val tableTypeButtonContainer = HBox(5.0, favouriteButton, allButton, historyButton)
HBox.setHgrow(favouriteButton, Priority.ALWAYS)
HBox.setHgrow(allButton, Priority.ALWAYS)
HBox.setHgrow(historyButton, Priority.ALWAYS)
val tableButtonTypeWidthBinding = tableTypeButtonContainer.widthProperty().divide(0.33)
favouriteButton.prefWidthProperty().bind(tableButtonTypeWidthBinding)
allButton.prefWidthProperty().bind(tableButtonTypeWidthBinding)
historyButton.prefWidthProperty().bind(tableButtonTypeWidthBinding)
favouriteButton.styleClass.add("server-type-switch-button")
allButton.styleClass.add("server-type-switch-button")
historyButton.styleClass.add("server-type-switch-button")
/**
* Servertable
*/
serverTable = SampServerTable(client)
serverTable.maxHeight = Double.MAX_VALUE
val passwordedTableColumn = TableColumn<SampServer, Boolean>("\uf023")
passwordedTableColumn.prefWidth = 35.0
passwordedTableColumn.minWidth = 35.0
passwordedTableColumn.maxWidth = 35.0
passwordedTableColumn.style = "-fx-font-family: FontAwesome"
val hostnameTableColumn = TableColumn<SampServer, String>(Client.getString("hostnameTableHeader"))
playersTableColumn = TableColumn(Client.getString("playersTableHeader"))
val gamemodeTableColumn = TableColumn<SampServer, String>(Client.getString("gamemodeTableHeader"))
val languageTableColumn = TableColumn<SampServer, String>(Client.getString("languageTableHeader"))
val versionTableColum = TableColumn<SampServer, String>(Client.getString("versionTableHeader"))
lastJoinTableColumn = TableColumn(Client.getString("lastVisit"))
passwordedTableColumn.cellValueFactory = PropertyValueFactory<SampServer, Boolean>("passworded")
passwordedTableColumn.setCellFactory {
object : TableCell<SampServer, Boolean>() {
init {
style = "-fx-font-family: FontAwesome; -fx-alignment:center"
}
override fun updateItem(item: Boolean?, empty: Boolean) {
text = if (empty.not() && item != null && item) {
"\uf023"
} else {
""
}
}
}
}
hostnameTableColumn.cellValueFactory = PropertyValueFactory<SampServer, String>("hostname")
playersTableColumn.cellValueFactory = PropertyValueFactory<SampServer, String>("playersAndMaxPlayers")
gamemodeTableColumn.cellValueFactory = PropertyValueFactory<SampServer, String>("mode")
languageTableColumn.cellValueFactory = PropertyValueFactory<SampServer, String>("language")
versionTableColum.cellValueFactory = PropertyValueFactory<SampServer, String>("version")
lastJoinTableColumn.cellValueFactory = PropertyValueFactory<SampServer, Long>("lastJoin")
lastJoinTableColumn.setCellFactory {
object : TableCell<SampServer, Long>() {
override fun updateItem(item: Long?, empty: Boolean) {
if (empty.not() && item != null) {
val date = LocalDateTime.ofInstant(Instant.ofEpochMilli(item), ZoneId.systemDefault())
val dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm a")
text = dateFormat.format(date)
}
}
}
}
serverTable.columns.addAll(passwordedTableColumn, hostnameTableColumn, playersTableColumn, gamemodeTableColumn, languageTableColumn, versionTableColum, lastJoinTableColumn)
serverTable.columnResizePolicy = TableView.CONSTRAINED_RESIZE_POLICY
/**
* Playertable
*/
playerTable = TableView()
val playerNameTableColumn = TableColumn<Player, String>(Client.getString("playerTableHeader"))
val playerScoreTableColumn = TableColumn<Player, Int>(Client.getString("scoreTableHeader"))
playerNameTableColumn.cellValueFactory = PropertyValueFactory<Player, String>("playerName")
playerScoreTableColumn.cellValueFactory = PropertyValueFactory<Player, Int>("playerScore")
val playerScoreTableColumnWidth = 85.0
playerScoreTableColumn.maxWidth = playerScoreTableColumnWidth
playerScoreTableColumn.minWidth = playerScoreTableColumnWidth
playerTable.prefHeight = 200.0
playerTable.columns.addAll(playerNameTableColumn, playerScoreTableColumn)
playerTable.columnResizePolicy = TableView.CONSTRAINED_RESIZE_POLICY
/**
* Filterarea
*/
regexCheckBox = CheckBox()
nameFilterTextField = TextField()
gamemodeFilterTextField = TextField()
languageFilterTextField = TextField()
versionFilterComboBox = ComboBox()
versionFilterComboBox.items = FXCollections.observableArrayList("", "0.3a", "0.3c", "0.3d", "0.3e", "0.3x", "0.3z", "0.3.7", "0.3.8", "0.3.DL")
val filterPanelContent = GridPane()
with(filterPanelContent) {
vgap = 5.0
hgap = 5.0
val constraintsColumnTitle = ColumnConstraints()
constraintsColumnTitle.hgrow = Priority.NEVER
constraintsColumnTitle.minWidth = Region.USE_PREF_SIZE
val constraintsColumnValue = ColumnConstraints()
constraintsColumnValue.hgrow = Priority.ALWAYS
columnConstraints.addAll(constraintsColumnTitle, constraintsColumnValue)
rowConstraints.add(RowConstraints())
rowConstraints.add(RowConstraints())
for (i in 0 until 4) {
val rowConstraint = RowConstraints()
rowConstraint.vgrow = Priority.ALWAYS
rowConstraints.add(rowConstraint)
}
add(Label(Client.getString("useRegex")), 0, 0)
add(regexCheckBox, 1, 0)
add(Separator(Orientation.HORIZONTAL), 0, 1, 2, 1)
add(Label(Client.getString("hostnameTableHeader")), 0, 2)
add(nameFilterTextField, 1, 2)
add(Label(Client.getString("gamemodeTableHeader")), 0, 3)
add(gamemodeFilterTextField, 1, 3)
add(Label(Client.getString("languageTableHeader")), 0, 4)
add(languageFilterTextField, 1, 4)
add(Label(Client.getString("versionTableHeader")), 0, 5)
add(versionFilterComboBox, 1, 5)
versionFilterComboBox.maxWidth = Double.MAX_VALUE
}
val filterPanel = TitledPane(Client.getString("filterSettings"), filterPanelContent)
filterPanel.isCollapsible = false
filterPanel.maxHeight = Double.MAX_VALUE
/**
* Serverinfo area
*/
serverAddressTextField = TextField()
serverAddressTextField.styleClass.add("copyableLabel")
serverAddressTextField.isEditable = false
serverPingLabel = Label()
serverLagcompLabel = Label()
serverPasswordLabel = Label()
serverMapLabel = Label()
serverWebsiteLink = Hyperlink()
serverWebsiteLink.isUnderline = true
val serverInfoPanelContent = GridPane()
with(serverInfoPanelContent) {
vgap = 5.0
hgap = 10.0
val constraintsColumnTitle = ColumnConstraints()
constraintsColumnTitle.hgrow = Priority.NEVER
constraintsColumnTitle.minWidth = Region.USE_PREF_SIZE
val constraintsColumnValue = ColumnConstraints()
constraintsColumnValue.hgrow = Priority.NEVER
columnConstraints.addAll(constraintsColumnTitle, constraintsColumnValue)
for (i in 0 until 6) {
val rowConstraint = RowConstraints()
rowConstraint.vgrow = Priority.ALWAYS
rowConstraints.add(rowConstraint)
}
add(Label(Client.getString("address")), 0, 0)
add(serverAddressTextField, 1, 0)
add(Label(Client.getString("ping")), 0, 1)
add(serverPingLabel, 1, 1)
add(Label(Client.getString("lagcomp")), 0, 2)
add(serverLagcompLabel, 1, 2)
add(Label(Client.getString("password")), 0, 3)
add(serverPasswordLabel, 1, 3)
add(Label(Client.getString("map")), 0, 4)
add(serverMapLabel, 1, 4)
add(Label(Client.getString("website")), 0, 5)
add(serverWebsiteLink, 1, 5)
}
val serverInfoPanel = TitledPane(Client.getString("serverInfo"), serverInfoPanelContent)
serverInfoPanel.isCollapsible = false
serverInfoPanel.maxHeight = Double.MAX_VALUE
/**
* Bottom area
*/
val bottomHBox = HBox(5.0, playerTable, filterPanel, serverInfoPanel)
HBox.setHgrow(filterPanel, Priority.ALWAYS)
/**
* Root
*/
rootPane = VBox(5.0, addressFieldContainer, tableTypeButtonContainer, serverTable, bottomHBox)
VBox.setVgrow(serverTable, Priority.ALWAYS)
}
} | mpl-2.0 | c5fadaf2af45eb518bced41adfb2f2dd | 38.459459 | 180 | 0.666324 | 4.874374 | false | false | false | false |
CarlosEsco/tachiyomi | buildSrc/src/main/kotlin/Commands.kt | 1 | 915 | import org.gradle.api.Project
import java.io.ByteArrayOutputStream
import java.text.SimpleDateFormat
import java.util.TimeZone
import java.util.Date
// Git is needed in your system PATH for these commands to work.
// If it's not installed, you can return a random value as a workaround
fun Project.getCommitCount(): String {
return runCommand("git rev-list --count HEAD")
// return "1"
}
fun Project.getGitSha(): String {
return runCommand("git rev-parse --short HEAD")
// return "1"
}
fun Project.getBuildTime(): String {
val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'")
df.timeZone = TimeZone.getTimeZone("UTC")
return df.format(Date())
}
fun Project.runCommand(command: String): String {
val byteOut = ByteArrayOutputStream()
project.exec {
commandLine = command.split(" ")
standardOutput = byteOut
}
return String(byteOut.toByteArray()).trim()
} | apache-2.0 | 49d3c714a8be53085f11e62016e94f16 | 27.625 | 71 | 0.702732 | 3.961039 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/pojo/NotificationResponse.kt | 1 | 780 | package io.github.feelfreelinux.wykopmobilny.models.pojo
import com.squareup.moshi.Json
data class NotificationResponse(
@Json(name = "author")
val author : String?,
@Json(name = "author_avatar")
val authorAvatar : String,
@Json(name = "author_avatar_med")
val authorAvatarMed : String,
@Json(name = "author_avatar_lo")
val authorAvatarLo : String,
@Json(name = "author_group")
val authorGroup : Int,
@Json(name = "author_sex")
val authorSex : String,
@Json(name = "date")
val date : String,
@Json(name = "body")
val body : String,
@Json(name = "url")
val url : String,
@Json(name = "new")
val new : Boolean
) | mit | 7e8b81a44c601ea1ece0802e1cb24c7f | 21.314286 | 56 | 0.557692 | 3.9 | false | false | false | false |
square/wire | wire-library/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt | 1 | 4642 | /*
* Copyright 2020 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
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.google.gson.TypeAdapter
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.squareup.wire.internal.JsonFormatter
import com.squareup.wire.internal.JsonIntegration
import java.lang.reflect.Type
internal object GsonJsonIntegration : JsonIntegration<Gson, TypeAdapter<Any?>>() {
override fun frameworkAdapter(
framework: Gson,
type: Type
): TypeAdapter<Any?> = framework.getAdapter(TypeToken.get(type)).nullSafe() as TypeAdapter<Any?>
override fun listAdapter(elementAdapter: TypeAdapter<Any?>): TypeAdapter<Any?> =
ListJsonAdapter(elementAdapter).nullSafe() as TypeAdapter<Any?>
override fun mapAdapter(
framework: Gson,
keyFormatter: JsonFormatter<*>,
valueAdapter: TypeAdapter<Any?>
): TypeAdapter<Any?> = MapJsonAdapter(keyFormatter, valueAdapter).nullSafe() as TypeAdapter<Any?>
fun <T> TypeAdapter<T>.serializeNulls(): TypeAdapter<T> {
val delegate = this
return object : TypeAdapter<T>() {
override fun write(writer: JsonWriter, value: T) {
val oldSerializeNulls = writer.serializeNulls
writer.serializeNulls = true
try {
delegate.write(writer, value)
} finally {
writer.serializeNulls = oldSerializeNulls
}
}
override fun read(reader: JsonReader): T {
return delegate.read(reader)
}
}
}
override fun structAdapter(framework: Gson): TypeAdapter<Any?> =
framework.getAdapter(Object::class.java).serializeNulls().nullSafe() as TypeAdapter<Any?>
override fun formatterAdapter(jsonFormatter: JsonFormatter<*>): TypeAdapter<Any?> =
FormatterJsonAdapter(jsonFormatter).nullSafe() as TypeAdapter<Any?>
private class FormatterJsonAdapter<T : Any>(
private val formatter: JsonFormatter<T>
) : TypeAdapter<T>() {
override fun write(writer: JsonWriter, value: T) {
val stringOrNumber = formatter.toStringOrNumber(value)
if (stringOrNumber is Number) {
writer.value(stringOrNumber)
} else {
writer.value(stringOrNumber as String)
}
}
override fun read(reader: JsonReader): T? {
val string = reader.nextString()
try {
return formatter.fromString(string)
} catch (_: RuntimeException) {
throw JsonSyntaxException("decode failed: $string at path ${reader.path}")
}
}
}
/** Adapt a list of values by delegating to an adapter for a single value. */
private class ListJsonAdapter<T>(
private val single: TypeAdapter<T>
) : TypeAdapter<List<T?>>() {
override fun read(reader: JsonReader): List<T?> {
val result = mutableListOf<T?>()
reader.beginArray()
while (reader.hasNext()) {
result.add(single.read(reader))
}
reader.endArray()
return result
}
override fun write(writer: JsonWriter, value: List<T?>?) {
writer.beginArray()
for (v in value!!) {
single.write(writer, v)
}
writer.endArray()
}
}
/** Adapt a list of values by delegating to an adapter for a single value. */
private class MapJsonAdapter<K : Any, V>(
private val keyFormatter: JsonFormatter<K>,
private val valueAdapter: TypeAdapter<V>
) : TypeAdapter<Map<K, V>>() {
override fun read(reader: JsonReader): Map<K, V> {
val result = mutableMapOf<K, V>()
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
val key = keyFormatter.fromString(name) as K
val value = valueAdapter.read(reader)!!
result[key] = value
}
reader.endObject()
return result
}
override fun write(writer: JsonWriter, value: Map<K, V>?) {
writer.beginObject()
for ((k, v) in value!!) {
writer.name(keyFormatter.toStringOrNumber(k).toString())
valueAdapter.write(writer, v)
}
writer.endObject()
}
}
}
| apache-2.0 | 6b765888371cab73a7d047a3a69dc986 | 31.921986 | 99 | 0.675355 | 4.270469 | false | false | false | false |
pyamsoft/pydroid | ui/src/main/java/com/pyamsoft/pydroid/ui/internal/app/AppHeader.kt | 1 | 5395 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.ui.internal.app
import androidx.annotation.DrawableRes
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.shape.ZeroCornerSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import coil.ImageLoader
import coil.compose.AsyncImage
import com.pyamsoft.pydroid.theme.keylines
import com.pyamsoft.pydroid.ui.defaults.DialogDefaults
import com.pyamsoft.pydroid.ui.defaults.ImageDefaults
import com.pyamsoft.pydroid.ui.internal.test.createNewTestImageLoader
@Composable
private fun AppHeader(
modifier: Modifier = Modifier,
@DrawableRes icon: Int,
name: String,
imageLoader: ImageLoader,
) {
val elevation = LocalDialogElevation.current
val color = LocalDialogColor.current
Box(
modifier = modifier,
contentAlignment = Alignment.BottomCenter,
) {
// Behind the content
// Space half the height and draw the header behind it
Surface(
modifier = Modifier.fillMaxWidth().height(ImageDefaults.LargeSize / 2),
elevation = elevation,
color = color,
shape =
MaterialTheme.shapes.medium.copy(
bottomStart = ZeroCornerSize,
bottomEnd = ZeroCornerSize,
),
content = {},
)
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center,
) {
AsyncImage(
modifier = Modifier.size(ImageDefaults.LargeSize),
model = icon,
imageLoader = imageLoader,
contentDescription = "$name Icon",
)
}
}
}
private fun noLocalProvidedFor(name: String): Nothing {
error("CompositionLocal $name not present")
}
/** Dialog elevation */
private val LocalDialogElevation =
compositionLocalOf<Dp> { noLocalProvidedFor("LocalDialogElevation") }
/** Dialog color */
private val LocalDialogColor = compositionLocalOf<Color> { noLocalProvidedFor("LocalDialogColor") }
@Composable
internal fun AppHeaderDialog(
modifier: Modifier = Modifier,
@DrawableRes icon: Int,
name: String,
imageLoader: ImageLoader,
color: Color = MaterialTheme.colors.surface,
content: LazyListScope.() -> Unit,
) {
CompositionLocalProvider(
LocalDialogElevation provides DialogDefaults.Elevation,
LocalDialogColor provides color,
) {
LazyColumn(
modifier = modifier,
) {
val scope = this
item {
AppHeader(
modifier = Modifier.fillMaxWidth(),
icon = icon,
name = name,
imageLoader = imageLoader,
)
}
scope.content()
// Footer for dialogs
item {
val elevation = LocalDialogElevation.current
val c = LocalDialogColor.current
Surface(
modifier = Modifier.fillMaxWidth().height(MaterialTheme.keylines.baseline),
elevation = elevation,
color = c,
shape =
MaterialTheme.shapes.medium.copy(
topStart = ZeroCornerSize,
topEnd = ZeroCornerSize,
),
content = {},
)
}
}
}
}
/** Wraps a LazyListScope.item in a Surface so it appears in the Dialog correctly */
internal inline fun LazyListScope.dialogItem(
modifier: Modifier = Modifier,
crossinline content: @Composable () -> Unit
) {
val self = this
self.item {
val elevation = LocalDialogElevation.current
val color = LocalDialogColor.current
Surface(
modifier = modifier,
elevation = elevation,
color = color,
shape = RectangleShape,
) {
content()
}
}
}
@Preview
@Composable
private fun PreviewAppHeader() {
AppHeader(
icon = 0,
name = "TEST",
imageLoader = createNewTestImageLoader(),
)
}
@Preview
@Composable
private fun PreviewAppHeaderDialog() {
AppHeaderDialog(
icon = 0,
name = "TEST",
imageLoader = createNewTestImageLoader(),
) {
item {
Text(
text = "Just a Test",
)
}
}
}
| apache-2.0 | 9e6a93ab94794c46fe5d1d9fe1ce6c67 | 26.953368 | 99 | 0.682669 | 4.5954 | false | false | false | false |
JetBrains/ideavim | src/test/java/org/jetbrains/plugins/ideavim/ex/LongerScriptTest.kt | 1 | 57539 | /*
* 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 org.jetbrains.plugins.ideavim.ex
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.vimscript.parser.VimscriptParser
import com.maddyhome.idea.vim.vimscript.parser.errors.IdeavimErrorListener
import org.jetbrains.plugins.ideavim.VimTestCase
import kotlin.system.measureTimeMillis
// todo time limit
class LongerScriptTest : VimTestCase() {
// it's always broken somehow
fun `test token helper function`() {
configureByText("\n")
val function = """
fun! F(pattern)
let result = []
let prefix = ''
let suffix = ''
let index = 0
let inSuffix = 0
while index < len(a:pattern)
let char = a:pattern[index]
if char !=? '[' && !inSuffix
let prefix .= char
elseif char ==? '[' || char ==? ']'
let inSuffix = 1
else
let suffix .= char
endif
let index += 1
endwhile
let result += [prefix]
let index = 0
while index < len(suffix)
let prefix .= suffix[index]
let result += [prefix]
let index += 1
endwhile
let resultString = ''
let index = 0
while index < len(result) - 1
let resultString .= "'" . result[index] . "' | "
let index += 1
endwhile
let resultString .= "'" . result[index] . "';"
return resultString
endfunction
""".trimIndent()
val parsingTime = measureTimeMillis { VimscriptParser.parse(function) }
println(parsingTime)
injector.vimscriptExecutor.execute(function)
typeText(commandToKeys("echo F('s[ubstitute]')"))
assertExOutput("'s' | 'su' | 'sub' | 'subs' | 'subst' | 'substi' | 'substit' | 'substitu' | 'substitut' | 'substitute';\n")
}
fun `test matchit vim parsing time`() {
val script = """
" matchit.vim: (global plugin) Extended "%" matching
" autload script of matchit plugin, see ../plugin/matchit.vim
" Last Change: Mar 01, 2020
let s:last_mps = ""
let s:last_words = ":"
let s:patBR = ""
let s:save_cpo = &cpo
set cpo&vim
" Auto-complete mappings: (not yet "ready for prime time")
" TODO Read :help write-plugin for the "right" way to let the user
" specify a key binding.
" let g:match_auto = '<C-]>'
" let g:match_autoCR = '<C-CR>'
" if exists("g:match_auto")
" execute "inoremap " . g:match_auto . ' x<Esc>"=<SID>Autocomplete()<CR>Pls'
" endif
" if exists("g:match_autoCR")
" execute "inoremap " . g:match_autoCR . ' <CR><C-R>=<SID>Autocomplete()<CR>'
" endif
" if exists("g:match_gthhoh")
" execute "inoremap " . g:match_gthhoh . ' <C-O>:call <SID>Gthhoh()<CR>'
" endif " gthhoh = "Get the heck out of here!"
let s:notslash = '\\\@1<!\%(\\\\\)*'
function s:RestoreOptions()
" In s:CleanUp(), :execute "set" restore_options .
let restore_options = ""
if get(b:, 'match_ignorecase', &ic) != &ic
let restore_options .= (&ic ? " " : " no") . "ignorecase"
let &ignorecase = b:match_ignorecase
endif
if &ve != ''
let restore_options = " ve=" . &ve . restore_options
set ve=
endif
return restore_options
endfunction
function matchit#Match_wrapper(word, forward, mode) range
let restore_options = s:RestoreOptions()
" If this function was called from Visual mode, make sure that the cursor
" is at the correct end of the Visual range:
if a:mode == "v"
execute "normal! gv\<Esc>"
elseif a:mode == "o" && mode(1) !~# '[vV]'
exe "norm! v"
elseif a:mode == "n" && mode(1) =~# 'ni'
exe "norm! v"
endif
" In s:CleanUp(), we may need to check whether the cursor moved forward.
let startpos = [line("."), col(".")]
" Use default behavior if called with a count.
if v:count
exe "normal! " . v:count . "%"
return s:CleanUp(restore_options, a:mode, startpos)
end
" First step: if not already done, set the script variables
" s:do_BR flag for whether there are backrefs
" s:pat parsed version of b:match_words
" s:all regexp based on s:pat and the default groups
if !exists("b:match_words") || b:match_words == ""
let match_words = ""
elseif b:match_words =~ ":"
let match_words = b:match_words
else
" Allow b:match_words = "GetVimMatchWords()" .
execute "let match_words =" b:match_words
endif
" Thanks to Preben "Peppe" Guldberg and Bram Moolenaar for this suggestion!
if (match_words != s:last_words) || (&mps != s:last_mps)
\ || exists("b:match_debug")
let s:last_mps = &mps
" quote the special chars in 'matchpairs', replace [,:] with \| and then
" append the builtin pairs (/*, */, #if, #ifdef, #ifndef, #else, #elif,
" #endif)
let default = escape(&mps, '[${'$'}^.*~\\/?]') . (strlen(&mps) ? "," : "") .
\ '\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\>:#\s*endif\>'
" s:all = pattern with all the keywords
let match_words = match_words . (strlen(match_words) ? "," : "") . default
let s:last_words = match_words
if match_words !~ s:notslash . '\\\d'
let s:do_BR = 0
let s:pat = match_words
else
let s:do_BR = 1
let s:pat = s:ParseWords(match_words)
endif
let s:all = substitute(s:pat, s:notslash . '\zs[,:]\+', '\\|', 'g')
" Just in case there are too many '\(...)' groups inside the pattern, make
" sure to use \%(...) groups, so that error E872 can be avoided
let s:all = substitute(s:all, '\\(', '\\%(', 'g')
let s:all = '\%(' . s:all . '\)'
if exists("b:match_debug")
let b:match_pat = s:pat
endif
" Reconstruct the version with unresolved backrefs.
let s:patBR = substitute(match_words.',',
\ s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
let s:patBR = substitute(s:patBR, s:notslash.'\zs:\{2,}', ':', 'g')
endif
" Second step: set the following local variables:
" matchline = line on which the cursor started
" curcol = number of characters before match
" prefix = regexp for start of line to start of match
" suffix = regexp for end of match to end of line
" Require match to end on or after the cursor and prefer it to
" start on or before the cursor.
let matchline = getline(startpos[0])
if a:word != ''
" word given
if a:word !~ s:all
echohl WarningMsg|echo 'Missing rule for word:"'.a:word.'"'|echohl NONE
return s:CleanUp(restore_options, a:mode, startpos)
endif
let matchline = a:word
let curcol = 0
let prefix = '^\%('
let suffix = '\)${'$'}'
" Now the case when "word" is not given
else " Find the match that ends on or after the cursor and set curcol.
let regexp = s:Wholematch(matchline, s:all, startpos[1]-1)
let curcol = match(matchline, regexp)
" If there is no match, give up.
if curcol == -1
return s:CleanUp(restore_options, a:mode, startpos)
endif
let endcol = matchend(matchline, regexp)
let suf = strlen(matchline) - endcol
let prefix = (curcol ? '^.*\%' . (curcol + 1) . 'c\%(' : '^\%(')
let suffix = (suf ? '\)\%' . (endcol + 1) . 'c.*${'$'}' : '\)${'$'}')
endif
if exists("b:match_debug")
let b:match_match = matchstr(matchline, regexp)
let b:match_col = curcol+1
endif
" Third step: Find the group and single word that match, and the original
" (backref) versions of these. Then, resolve the backrefs.
" Set the following local variable:
" group = colon-separated list of patterns, one of which matches
" = ini:mid:fin or ini:fin
"
" Now, set group and groupBR to the matching group: 'if:endif' or
" 'while:endwhile' or whatever. A bit of a kluge: s:Choose() returns
" group . "," . groupBR, and we pick it apart.
let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, s:patBR)
let i = matchend(group, s:notslash . ",")
let groupBR = strpart(group, i)
let group = strpart(group, 0, i-1)
" Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
if s:do_BR " Do the hard part: resolve those backrefs!
let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
endif
if exists("b:match_debug")
let b:match_wholeBR = groupBR
let i = matchend(groupBR, s:notslash . ":")
let b:match_iniBR = strpart(groupBR, 0, i-1)
endif
" Fourth step: Set the arguments for searchpair().
let i = matchend(group, s:notslash . ":")
let j = matchend(group, '.*' . s:notslash . ":")
let ini = strpart(group, 0, i-1)
let mid = substitute(strpart(group, i,j-i-1), s:notslash.'\zs:', '\\|', 'g')
let fin = strpart(group, j)
"Un-escape the remaining , and : characters.
let ini = substitute(ini, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
let mid = substitute(mid, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
let fin = substitute(fin, s:notslash . '\zs\\\(:\|,\)', '\1', 'g')
" searchpair() requires that these patterns avoid \(\) groups.
let ini = substitute(ini, s:notslash . '\zs\\(', '\\%(', 'g')
let mid = substitute(mid, s:notslash . '\zs\\(', '\\%(', 'g')
let fin = substitute(fin, s:notslash . '\zs\\(', '\\%(', 'g')
" Set mid. This is optimized for readability, not micro-efficiency!
if a:forward && matchline =~ prefix . fin . suffix
\ || !a:forward && matchline =~ prefix . ini . suffix
let mid = ""
endif
" Set flag. This is optimized for readability, not micro-efficiency!
if a:forward && matchline =~ prefix . fin . suffix
\ || !a:forward && matchline !~ prefix . ini . suffix
let flag = "bW"
else
let flag = "W"
endif
" Set skip.
if exists("b:match_skip")
let skip = b:match_skip
elseif exists("b:match_comment") " backwards compatibility and testing!
let skip = "r:" . b:match_comment
else
let skip = 's:comment\|string'
endif
let skip = s:ParseSkip(skip)
if exists("b:match_debug")
let b:match_ini = ini
let b:match_tail = (strlen(mid) ? mid.'\|' : '') . fin
endif
" Fifth step: actually start moving the cursor and call searchpair().
" Later, :execute restore_cursor to get to the original screen.
let view = winsaveview()
call cursor(0, curcol + 1)
if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
let skip = "0"
else
execute "if " . skip . "| let skip = '0' | endif"
endif
let sp_return = searchpair(ini, mid, fin, flag, skip)
if &selection isnot# 'inclusive' && a:mode == 'v'
" move cursor one pos to the right, because selection is not inclusive
" add virtualedit=onemore, to make it work even when the match ends the " line
if !(col('.') < col('${'$'}')-1)
set ve=onemore
endif
norm! l
endif
let final_position = "call cursor(" . line(".") . "," . col(".") . ")"
" Restore cursor position and original screen.
call winrestview(view)
normal! m'
if sp_return > 0
execute final_position
endif
return s:CleanUp(restore_options, a:mode, startpos, mid.'\|'.fin)
endfun
" Restore options and do some special handling for Operator-pending mode.
" The optional argument is the tail of the matching group.
fun! s:CleanUp(options, mode, startpos, ...)
if strlen(a:options)
execute "set" a:options
endif
" Open folds, if appropriate.
if a:mode != "o"
if &foldopen =~ "percent"
normal! zv
endif
" In Operator-pending mode, we want to include the whole match
" (for example, d%).
" This is only a problem if we end up moving in the forward direction.
elseif (a:startpos[0] < line(".")) ||
\ (a:startpos[0] == line(".") && a:startpos[1] < col("."))
if a:0
" Check whether the match is a single character. If not, move to the
" end of the match.
let matchline = getline(".")
let currcol = col(".")
let regexp = s:Wholematch(matchline, a:1, currcol-1)
let endcol = matchend(matchline, regexp)
if endcol > currcol " This is NOT off by one!
call cursor(0, endcol)
endif
endif " a:0
endif " a:mode != "o" && etc.
return 0
endfun
" Example (simplified HTML patterns): if
" a:groupBR = '<\(\k\+\)>:</\1>'
" a:prefix = '^.\{3}\('
" a:group = '<\(\k\+\)>:</\(\k\+\)>'
" a:suffix = '\).\{2}${'$'}'
" a:matchline = "123<tag>12" or "123</tag>12"
" then extract "tag" from a:matchline and return "<tag>:</tag>" .
fun! s:InsertRefs(groupBR, prefix, group, suffix, matchline)
if a:matchline !~ a:prefix .
\ substitute(a:group, s:notslash . '\zs:', '\\|', 'g') . a:suffix
return a:group
endif
let i = matchend(a:groupBR, s:notslash . ':')
let ini = strpart(a:groupBR, 0, i-1)
let tailBR = strpart(a:groupBR, i)
let word = s:Choose(a:group, a:matchline, ":", "", a:prefix, a:suffix,
\ a:groupBR)
let i = matchend(word, s:notslash . ":")
let wordBR = strpart(word, i)
let word = strpart(word, 0, i-1)
" Now, a:matchline =~ a:prefix . word . a:suffix
if wordBR != ini
let table = s:Resolve(ini, wordBR, "table")
else
let table = ""
let d = 0
while d < 10
if tailBR =~ s:notslash . '\\' . d
let table = table . d
else
let table = table . "-"
endif
let d = d + 1
endwhile
endif
let d = 9
while d
if table[d] != "-"
let backref = substitute(a:matchline, a:prefix.word.a:suffix,
\ '\'.table[d], "")
" Are there any other characters that should be escaped?
let backref = escape(backref, '*,:')
execute s:Ref(ini, d, "start", "len")
let ini = strpart(ini, 0, start) . backref . strpart(ini, start+len)
let tailBR = substitute(tailBR, s:notslash . '\zs\\' . d,
\ escape(backref, '\\&'), 'g')
endif
let d = d-1
endwhile
if exists("b:match_debug")
if s:do_BR
let b:match_table = table
let b:match_word = word
else
let b:match_table = ""
let b:match_word = ""
endif
endif
return ini . ":" . tailBR
endfun
" Input a comma-separated list of groups with backrefs, such as
" a:groups = '\(foo\):end\1,\(bar\):end\1'
" and return a comma-separated list of groups with backrefs replaced:
" return '\(foo\):end\(foo\),\(bar\):end\(bar\)'
fun! s:ParseWords(groups)
let groups = substitute(a:groups.",", s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
let groups = substitute(groups, s:notslash . '\zs:\{2,}', ':', 'g')
let parsed = ""
while groups =~ '[^,:]'
let i = matchend(groups, s:notslash . ':')
let j = matchend(groups, s:notslash . ',')
let ini = strpart(groups, 0, i-1)
let tail = strpart(groups, i, j-i-1) . ":"
let groups = strpart(groups, j)
let parsed = parsed . ini
let i = matchend(tail, s:notslash . ':')
while i != -1
" In 'if:else:endif', ini='if' and word='else' and then word='endif'.
let word = strpart(tail, 0, i-1)
let tail = strpart(tail, i)
let i = matchend(tail, s:notslash . ':')
let parsed = parsed . ":" . s:Resolve(ini, word, "word")
endwhile " Now, tail has been used up.
let parsed = parsed . ","
endwhile " groups =~ '[^,:]'
let parsed = substitute(parsed, ',${'$'}', '', '')
return parsed
endfun
" TODO I think this can be simplified and/or made more efficient.
" TODO What should I do if a:start is out of range?
" Return a regexp that matches all of a:string, such that
" matchstr(a:string, regexp) represents the match for a:pat that starts
" as close to a:start as possible, before being preferred to after, and
" ends after a:start .
" Usage:
" let regexp = s:Wholematch(getline("."), 'foo\|bar', col(".")-1)
" let i = match(getline("."), regexp)
" let j = matchend(getline("."), regexp)
" let match = matchstr(getline("."), regexp)
fun! s:Wholematch(string, pat, start)
let group = '\%(' . a:pat . '\)'
let prefix = (a:start ? '\(^.*\%<' . (a:start + 2) . 'c\)\zs' : '^')
let len = strlen(a:string)
let suffix = (a:start+1 < len ? '\(\%>'.(a:start+1).'c.*${'$'}\)\@=' : '${'$'}')
if a:string !~ prefix . group . suffix
let prefix = ''
endif
return prefix . group . suffix
endfun
" No extra arguments: s:Ref(string, d) will
" find the d'th occurrence of '\(' and return it, along with everything up
" to and including the matching '\)'.
" One argument: s:Ref(string, d, "start") returns the index of the start
" of the d'th '\(' and any other argument returns the length of the group.
" Two arguments: s:Ref(string, d, "foo", "bar") returns a string to be
" executed, having the effect of
" :let foo = s:Ref(string, d, "start")
" :let bar = s:Ref(string, d, "len")
fun! s:Ref(string, d, ...)
let len = strlen(a:string)
if a:d == 0
let start = 0
else
let cnt = a:d
let match = a:string
while cnt
let cnt = cnt - 1
let index = matchend(match, s:notslash . '\\(')
if index == -1
return ""
endif
let match = strpart(match, index)
endwhile
let start = len - strlen(match)
if a:0 == 1 && a:1 == "start"
return start - 2
endif
let cnt = 1
while cnt
let index = matchend(match, s:notslash . '\\(\|\\)') - 1
if index == -2
return ""
endif
" Increment if an open, decrement if a ')':
let cnt = cnt + (match[index]=="(" ? 1 : -1) " ')'
let match = strpart(match, index+1)
endwhile
let start = start - 2
let len = len - start - strlen(match)
endif
if a:0 == 1
return len
elseif a:0 == 2
return "let " . a:1 . "=" . start . "| let " . a:2 . "=" . len
else
return strpart(a:string, start, len)
endif
endfun
" Count the number of disjoint copies of pattern in string.
" If the pattern is a literal string and contains no '0' or '1' characters
" then s:Count(string, pattern, '0', '1') should be faster than
" s:Count(string, pattern).
fun! s:Count(string, pattern, ...)
let pat = escape(a:pattern, '\\')
if a:0 > 1
let foo = substitute(a:string, '[^'.a:pattern.']', "a:1", "g")
let foo = substitute(a:string, pat, a:2, "g")
let foo = substitute(foo, '[^' . a:2 . ']', "", "g")
return strlen(foo)
endif
let result = 0
let foo = a:string
let index = matchend(foo, pat)
while index != -1
let result = result + 1
let foo = strpart(foo, index)
let index = matchend(foo, pat)
endwhile
return result
endfun
" s:Resolve('\(a\)\(b\)', '\(c\)\2\1\1\2') should return table.word, where
" word = '\(c\)\(b\)\(a\)\3\2' and table = '-32-------'. That is, the first
" '\1' in target is replaced by '\(a\)' in word, table[1] = 3, and this
" indicates that all other instances of '\1' in target are to be replaced
" by '\3'. The hard part is dealing with nesting...
" Note that ":" is an illegal character for source and target,
" unless it is preceded by "\".
fun! s:Resolve(source, target, output)
let word = a:target
let i = matchend(word, s:notslash . '\\\d') - 1
let table = "----------"
while i != -2 " There are back references to be replaced.
let d = word[i]
let backref = s:Ref(a:source, d)
" The idea is to replace '\d' with backref. Before we do this,
" replace any \(\) groups in backref with :1, :2, ... if they
" correspond to the first, second, ... group already inserted
" into backref. Later, replace :1 with \1 and so on. The group
" number w+b within backref corresponds to the group number
" s within a:source.
" w = number of '\(' in word before the current one
let w = s:Count(
\ substitute(strpart(word, 0, i-1), '\\\\', '', 'g'), '\(', '1')
let b = 1 " number of the current '\(' in backref
let s = d " number of the current '\(' in a:source
while b <= s:Count(substitute(backref, '\\\\', '', 'g'), '\(', '1')
\ && s < 10
if table[s] == "-"
if w + b < 10
" let table[s] = w + b
let table = strpart(table, 0, s) . (w+b) . strpart(table, s+1)
endif
let b = b + 1
let s = s + 1
else
execute s:Ref(backref, b, "start", "len")
let ref = strpart(backref, start, len)
let backref = strpart(backref, 0, start) . ":". table[s]
\ . strpart(backref, start+len)
let s = s + s:Count(substitute(ref, '\\\\', '', 'g'), '\(', '1')
endif
endwhile
let word = strpart(word, 0, i-1) . backref . strpart(word, i+1)
let i = matchend(word, s:notslash . '\\\d') - 1
endwhile
let word = substitute(word, s:notslash . '\zs:', '\\', 'g')
if a:output == "table"
return table
elseif a:output == "word"
return word
else
return table . word
endif
endfun
" Assume a:comma = ",". Then the format for a:patterns and a:1 is
" a:patterns = "<pat1>,<pat2>,..."
" a:1 = "<alt1>,<alt2>,..."
" If <patn> is the first pattern that matches a:string then return <patn>
" if no optional arguments are given; return <patn>,<altn> if a:1 is given.
fun! s:Choose(patterns, string, comma, branch, prefix, suffix, ...)
let tail = (a:patterns =~ a:comma."${'$'}" ? a:patterns : a:patterns . a:comma)
let i = matchend(tail, s:notslash . a:comma)
if a:0
let alttail = (a:1 =~ a:comma."${'$'}" ? a:1 : a:1 . a:comma)
let j = matchend(alttail, s:notslash . a:comma)
endif
let current = strpart(tail, 0, i-1)
if a:branch == ""
let currpat = current
else
let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g')
endif
while a:string !~ a:prefix . currpat . a:suffix
let tail = strpart(tail, i)
let i = matchend(tail, s:notslash . a:comma)
if i == -1
return -1
endif
let current = strpart(tail, 0, i-1)
if a:branch == ""
let currpat = current
else
let currpat = substitute(current, s:notslash . a:branch, '\\|', 'g')
endif
if a:0
let alttail = strpart(alttail, j)
let j = matchend(alttail, s:notslash . a:comma)
endif
endwhile
if a:0
let current = current . a:comma . strpart(alttail, 0, j-1)
endif
return current
endfun
fun! matchit#Match_debug()
let b:match_debug = 1 " Save debugging information.
" pat = all of b:match_words with backrefs parsed
amenu &Matchit.&pat :echo b:match_pat<CR>
" match = bit of text that is recognized as a match
amenu &Matchit.&match :echo b:match_match<CR>
" curcol = cursor column of the start of the matching text
amenu &Matchit.&curcol :echo b:match_col<CR>
" wholeBR = matching group, original version
amenu &Matchit.wh&oleBR :echo b:match_wholeBR<CR>
" iniBR = 'if' piece, original version
amenu &Matchit.ini&BR :echo b:match_iniBR<CR>
" ini = 'if' piece, with all backrefs resolved from match
amenu &Matchit.&ini :echo b:match_ini<CR>
" tail = 'else\|endif' piece, with all backrefs resolved from match
amenu &Matchit.&tail :echo b:match_tail<CR>
" fin = 'endif' piece, with all backrefs resolved from match
amenu &Matchit.&word :echo b:match_word<CR>
" '\'.d in ini refers to the same thing as '\'.table[d] in word.
amenu &Matchit.t&able :echo '0:' . b:match_table . ':9'<CR>
endfun
" Jump to the nearest unmatched "(" or "if" or "<tag>" if a:spflag == "bW"
" or the nearest unmatched "</tag>" or "endif" or ")" if a:spflag == "W".
" Return a "mark" for the original position, so that
" let m = MultiMatch("bW", "n") ... call winrestview(m)
" will return to the original position. If there is a problem, do not
" move the cursor and return {}, unless a count is given, in which case
" go up or down as many levels as possible and again return {}.
" TODO This relies on the same patterns as % matching. It might be a good
" idea to give it its own matching patterns.
fun! matchit#MultiMatch(spflag, mode)
let restore_options = s:RestoreOptions()
let startpos = [line("."), col(".")]
" save v:count1 variable, might be reset from the restore_cursor command
let level = v:count1
if a:mode == "o" && mode(1) !~# '[vV]'
exe "norm! v"
endif
" First step: if not already done, set the script variables
" s:do_BR flag for whether there are backrefs
" s:pat parsed version of b:match_words
" s:all regexp based on s:pat and the default groups
" This part is copied and slightly modified from matchit#Match_wrapper().
if !exists("b:match_words") || b:match_words == ""
let match_words = ""
" Allow b:match_words = "GetVimMatchWords()" .
elseif b:match_words =~ ":"
let match_words = b:match_words
else
execute "let match_words =" b:match_words
endif
if (match_words != s:last_words) || (&mps != s:last_mps) ||
\ exists("b:match_debug")
let default = escape(&mps, '[${'$'}^.*~\\/?]') . (strlen(&mps) ? "," : "") .
\ '\/\*:\*\/,#\s*if\%(n\=def\)\=:#\s*else\>:#\s*elif\>:#\s*endif\>'
let s:last_mps = &mps
let match_words = match_words . (strlen(match_words) ? "," : "") . default
let s:last_words = match_words
if match_words !~ s:notslash . '\\\d'
let s:do_BR = 0
let s:pat = match_words
else
let s:do_BR = 1
let s:pat = s:ParseWords(match_words)
endif
let s:all = '\%(' . substitute(s:pat, '[,:]\+', '\\|', 'g') . '\)'
if exists("b:match_debug")
let b:match_pat = s:pat
endif
" Reconstruct the version with unresolved backrefs.
let s:patBR = substitute(match_words.',',
\ s:notslash.'\zs[,:]*,[,:]*', ',', 'g')
let s:patBR = substitute(s:patBR, s:notslash.'\zs:\{2,}', ':', 'g')
endif
" Second step: figure out the patterns for searchpair()
" and save the screen, cursor position, and 'ignorecase'.
" - TODO: A lot of this is copied from matchit#Match_wrapper().
" - maybe even more functionality should be split off
" - into separate functions!
let openlist = split(s:pat . ',', s:notslash . '\zs:.\{-}' . s:notslash . ',')
let midclolist = split(',' . s:pat, s:notslash . '\zs,.\{-}' . s:notslash . ':')
call map(midclolist, {-> split(v:val, s:notslash . ':')})
let closelist = []
let middlelist = []
call map(midclolist, {i,v -> [extend(closelist, v[-1 : -1]),
\ extend(middlelist, v[0 : -2])]})
call map(openlist, {i,v -> v =~# s:notslash . '\\|' ? '\%(' . v . '\)' : v})
call map(middlelist, {i,v -> v =~# s:notslash . '\\|' ? '\%(' . v . '\)' : v})
call map(closelist, {i,v -> v =~# s:notslash . '\\|' ? '\%(' . v . '\)' : v})
let open = join(openlist, ',')
let middle = join(middlelist, ',')
let close = join(closelist, ',')
if exists("b:match_skip")
let skip = b:match_skip
elseif exists("b:match_comment") " backwards compatibility and testing!
let skip = "r:" . b:match_comment
else
let skip = 's:comment\|string'
endif
let skip = s:ParseSkip(skip)
let view = winsaveview()
" Third step: call searchpair().
" Replace '\('--but not '\\('--with '\%(' and ',' with '\|'.
let openpat = substitute(open, '\%(' . s:notslash . '\)\@<=\\(', '\\%(', 'g')
let openpat = substitute(openpat, ',', '\\|', 'g')
let closepat = substitute(close, '\%(' . s:notslash . '\)\@<=\\(', '\\%(', 'g')
let closepat = substitute(closepat, ',', '\\|', 'g')
let middlepat = substitute(middle, '\%(' . s:notslash . '\)\@<=\\(', '\\%(', 'g')
let middlepat = substitute(middlepat, ',', '\\|', 'g')
if skip =~ 'synID' && !(has("syntax") && exists("g:syntax_on"))
let skip = '0'
else
try
execute "if " . skip . "| let skip = '0' | endif"
catch /^Vim\%((\a\+)\)\=:E363/
" We won't find anything, so skip searching, should keep Vim responsive.
return {}
endtry
endif
mark '
while level
if searchpair(openpat, middlepat, closepat, a:spflag, skip) < 1
call s:CleanUp(restore_options, a:mode, startpos)
return {}
endif
let level = level - 1
endwhile
" Restore options and return a string to restore the original position.
call s:CleanUp(restore_options, a:mode, startpos)
return view
endfun
" Search backwards for "if" or "while" or "<tag>" or ...
" and return "endif" or "endwhile" or "</tag>" or ... .
" For now, this uses b:match_words and the same script variables
" as matchit#Match_wrapper() . Later, it may get its own patterns,
" either from a buffer variable or passed as arguments.
" fun! s:Autocomplete()
" echo "autocomplete not yet implemented :-("
" if !exists("b:match_words") || b:match_words == ""
" return ""
" end
" let startpos = matchit#MultiMatch("bW")
"
" if startpos == ""
" return ""
" endif
" " - TODO: figure out whether 'if' or '<tag>' matched, and construct
" " - the appropriate closing.
" let matchline = getline(".")
" let curcol = col(".") - 1
" " - TODO: Change the s:all argument if there is a new set of match pats.
" let regexp = s:Wholematch(matchline, s:all, curcol)
" let suf = strlen(matchline) - matchend(matchline, regexp)
" let prefix = (curcol ? '^.\{' . curcol . '}\%(' : '^\%(')
" let suffix = (suf ? '\).\{' . suf . '}${'$'}' : '\)${'$'}')
" " Reconstruct the version with unresolved backrefs.
" let patBR = substitute(b:match_words.',', '[,:]*,[,:]*', ',', 'g')
" let patBR = substitute(patBR, ':\{2,}', ':', "g")
" " Now, set group and groupBR to the matching group: 'if:endif' or
" " 'while:endwhile' or whatever.
" let group = s:Choose(s:pat, matchline, ",", ":", prefix, suffix, patBR)
" let i = matchend(group, s:notslash . ",")
" let groupBR = strpart(group, i)
" let group = strpart(group, 0, i-1)
" " Now, matchline =~ prefix . substitute(group,':','\|','g') . suffix
" if s:do_BR
" let group = s:InsertRefs(groupBR, prefix, group, suffix, matchline)
" endif
" " let g:group = group
"
" " - TODO: Construct the closing from group.
" let fake = "end" . expand("<cword>")
" execute startpos
" return fake
" endfun
" Close all open structures. "Get the heck out of here!"
" fun! s:Gthhoh()
" let close = s:Autocomplete()
" while strlen(close)
" put=close
" let close = s:Autocomplete()
" endwhile
" endfun
" Parse special strings as typical skip arguments for searchpair():
" s:foo becomes (current syntax item) =~ foo
" S:foo becomes (current syntax item) !~ foo
" r:foo becomes (line before cursor) =~ foo
" R:foo becomes (line before cursor) !~ foo
fun! s:ParseSkip(str)
let skip = a:str
if skip[1] == ":"
if skip[0] == "s"
let skip = "synIDattr(synID(line('.'),col('.'),1),'name') =~? '" .
\ strpart(skip,2) . "'"
elseif skip[0] == "S"
let skip = "synIDattr(synID(line('.'),col('.'),1),'name') !~? '" .
\ strpart(skip,2) . "'"
elseif skip[0] == "r"
let skip = "strpart(getline('.'),0,col('.'))=~'" . strpart(skip,2). "'"
elseif skip[0] == "R"
let skip = "strpart(getline('.'),0,col('.'))!~'" . strpart(skip,2). "'"
endif
endif
return skip
endfun
let &cpo = s:save_cpo
unlet s:save_cpo
" vim:sts=2:sw=2:et:
""".trimIndent()
val parsingTime = measureTimeMillis { VimscriptParser.parse(script) }
assertEmpty(IdeavimErrorListener.testLogger)
println(parsingTime)
}
fun `test abolish vim parsing time`() {
val script = """
" abolish.vim - Language friendly searches, substitutions, and abbreviations
" Maintainer: Tim Pope <http://tpo.pe/>
" Version: 1.1
" GetLatestVimScripts: 1545 1 :AutoInstall: abolish.vim
" Initialization {{{1
if exists("g:loaded_abolish") || &cp || v:version < 700
finish
endif
let g:loaded_abolish = 1
if !exists("g:abolish_save_file")
if isdirectory(expand("~/.vim"))
let g:abolish_save_file = expand("~/.vim/after/plugin/abolish.vim")
elseif isdirectory(expand("~/vimfiles")) || has("win32")
let g:abolish_save_file = expand("~/vimfiles/after/plugin/abolish.vim")
else
let g:abolish_save_file = expand("~/.vim/after/plugin/abolish.vim")
endif
endif
" }}}1
" Utility functions {{{1
function! s:function(name)
return function(substitute(a:name,'^s:',matchstr(expand('<sfile>'), '<SNR>\d\+_'),''))
endfunction
function! s:send(self,func,...)
if type(a:func) == type('') || type(a:func) == type(0)
let l:Func = get(a:self,a:func,'')
else
let l:Func = a:func
endif
let s = type(a:self) == type({}) ? a:self : {}
if type(Func) == type(function('tr'))
return call(Func,a:000,s)
elseif type(Func) == type({}) && has_key(Func,'apply')
return call(Func.apply,a:000,Func)
elseif type(Func) == type({}) && has_key(Func,'call')
return call(Func.call,a:000,s)
elseif type(Func) == type('') && Func == '' && has_key(s,'function missing')
return call('s:send',[s,'function missing',a:func] + a:000)
else
return Func
endif
endfunction
let s:object = {}
function! s:object.clone(...)
let sub = deepcopy(self)
return a:0 ? extend(sub,a:1) : sub
endfunction
if !exists("g:Abolish")
let Abolish = {}
endif
call extend(Abolish, s:object, 'force')
call extend(Abolish, {'Coercions': {}}, 'keep')
function! s:throw(msg)
let v:errmsg = a:msg
throw "Abolish: ".a:msg
endfunction
function! s:words()
let words = []
let lnum = line('w0')
while lnum <= line('w${'$'}')
let line = getline(lnum)
let col = 0
while match(line,'\<\k\k\+\>',col) != -1
let words += [matchstr(line,'\<\k\k\+\>',col)]
let col = matchend(line,'\<\k\k\+\>',col)
endwhile
let lnum += 1
endwhile
return words
endfunction
function! s:extractopts(list,opts)
let i = 0
while i < len(a:list)
if a:list[i] =~ '^-[^=]' && has_key(a:opts,matchstr(a:list[i],'-\zs[^=]*'))
let key = matchstr(a:list[i],'-\zs[^=]*')
let value = matchstr(a:list[i],'=\zs.*')
if type(get(a:opts,key)) == type([])
let a:opts[key] += [value]
elseif type(get(a:opts,key)) == type(0)
let a:opts[key] = 1
else
let a:opts[key] = value
endif
else
let i += 1
continue
endif
call remove(a:list,i)
endwhile
return a:opts
endfunction
" }}}1
" Dictionary creation {{{1
function! s:mixedcase(word)
return substitute(s:camelcase(a:word),'^.','\u&','')
endfunction
function! s:camelcase(word)
let word = substitute(a:word, '-', '_', 'g')
if word !~# '_' && word =~# '\l'
return substitute(word,'^.','\l&','')
else
return substitute(word,'\C\(_\)\=\(.\)','\=submatch(1)==""?tolower(submatch(2)) : toupper(submatch(2))','g')
endif
endfunction
function! s:snakecase(word)
let word = substitute(a:word,'::','/','g')
let word = substitute(word,'\(\u\+\)\(\u\l\)','\1_\2','g')
let word = substitute(word,'\(\l\|\d\)\(\u\)','\1_\2','g')
let word = substitute(word,'[.-]','_','g')
let word = tolower(word)
return word
endfunction
function! s:uppercase(word)
return toupper(s:snakecase(a:word))
endfunction
function! s:dashcase(word)
return substitute(s:snakecase(a:word),'_','-','g')
endfunction
function! s:spacecase(word)
return substitute(s:snakecase(a:word),'_',' ','g')
endfunction
function! s:dotcase(word)
return substitute(s:snakecase(a:word),'_','.','g')
endfunction
function! s:titlecase(word)
return substitute(s:spacecase(a:word), '\(\<\w\)','\=toupper(submatch(1))','g')
endfunction
call extend(Abolish, {
\ 'camelcase': s:function('s:camelcase'),
\ 'mixedcase': s:function('s:mixedcase'),
\ 'snakecase': s:function('s:snakecase'),
\ 'uppercase': s:function('s:uppercase'),
\ 'dashcase': s:function('s:dashcase'),
\ 'dotcase': s:function('s:dotcase'),
\ 'spacecase': s:function('s:spacecase'),
\ 'titlecase': s:function('s:titlecase')
\ }, 'keep')
function! s:create_dictionary(lhs,rhs,opts)
let dictionary = {}
let i = 0
let expanded = s:expand_braces({a:lhs : a:rhs})
for [lhs,rhs] in items(expanded)
if get(a:opts,'case',1)
let dictionary[s:mixedcase(lhs)] = s:mixedcase(rhs)
let dictionary[tolower(lhs)] = tolower(rhs)
let dictionary[toupper(lhs)] = toupper(rhs)
endif
let dictionary[lhs] = rhs
endfor
let i += 1
return dictionary
endfunction
function! s:expand_braces(dict)
let new_dict = {}
for [key,val] in items(a:dict)
if key =~ '{.*}'
let redo = 1
let [all,kbefore,kmiddle,kafter;crap] = matchlist(key,'\(.\{-\}\){\(.\{-\}\)}\(.*\)')
let [all,vbefore,vmiddle,vafter;crap] = matchlist(val,'\(.\{-\}\){\(.\{-\}\)}\(.*\)') + ["","","",""]
if all == ""
let [vbefore,vmiddle,vafter] = [val, ",", ""]
endif
let targets = split(kmiddle,',',1)
let replacements = split(vmiddle,',',1)
if replacements == [""]
let replacements = targets
endif
for i in range(0,len(targets)-1)
let new_dict[kbefore.targets[i].kafter] = vbefore.replacements[i%len(replacements)].vafter
endfor
else
let new_dict[key] = val
endif
endfor
if exists("redo")
return s:expand_braces(new_dict)
else
return new_dict
endif
endfunction
" }}}1
" Abolish Dispatcher {{{1
function! s:SubComplete(A,L,P)
if a:A =~ '^[/?]\k\+${'$'}'
let char = strpart(a:A,0,1)
return join(map(s:words(),'char . v:val'),"\n")
elseif a:A =~# '^\k\+${'$'}'
return join(s:words(),"\n")
endif
endfunction
function! s:Complete(A,L,P)
" Vim bug: :Abolish -<Tab> calls this function with a:A equal to 0
if a:A =~# '^[^/?-]' && type(a:A) != type(0)
return join(s:words(),"\n")
elseif a:L =~# '^\w\+\s\+\%(-\w*\)\=${'$'}'
return "-search\n-substitute\n-delete\n-buffer\n-cmdline\n"
elseif a:L =~# ' -\%(search\|substitute\)\>'
return "-flags="
else
return "-buffer\n-cmdline"
endif
endfunction
let s:commands = {}
let s:commands.abstract = s:object.clone()
function! s:commands.abstract.dispatch(bang,line1,line2,count,args)
return self.clone().go(a:bang,a:line1,a:line2,a:count,a:args)
endfunction
function! s:commands.abstract.go(bang,line1,line2,count,args)
let self.bang = a:bang
let self.line1 = a:line1
let self.line2 = a:line2
let self.count = a:count
return self.process(a:bang,a:line1,a:line2,a:count,a:args)
endfunction
function! s:dispatcher(bang,line1,line2,count,args)
let i = 0
let args = copy(a:args)
let command = s:commands.abbrev
while i < len(args)
if args[i] =~# '^-\w\+${'$'}' && has_key(s:commands,matchstr(args[i],'-\zs.*'))
let command = s:commands[matchstr(args[i],'-\zs.*')]
call remove(args,i)
break
endif
let i += 1
endwhile
try
return command.dispatch(a:bang,a:line1,a:line2,a:count,args)
catch /^Abolish: /
echohl ErrorMsg
echo v:errmsg
echohl NONE
return ""
endtry
endfunction
" }}}1
" Subvert Dispatcher {{{1
function! s:subvert_dispatcher(bang,line1,line2,count,args)
try
return s:parse_subvert(a:bang,a:line1,a:line2,a:count,a:args)
catch /^Subvert: /
echohl ErrorMsg
echo v:errmsg
echohl NONE
return ""
endtry
endfunction
function! s:parse_subvert(bang,line1,line2,count,args)
if a:args =~ '^\%(\w\|${'$'}\)'
let args = (a:bang ? "!" : "").a:args
else
let args = a:args
endif
let separator = '\v((\\)@<!(\\\\)*\\)@<!' . matchstr(args,'^.')
let split = split(args,separator,1)[1:]
if a:count || split == [""]
return s:parse_substitute(a:bang,a:line1,a:line2,a:count,split)
elseif len(split) == 1
return s:find_command(separator,"",split[0])
elseif len(split) == 2 && split[1] =~# '^[A-Za-z]*n[A-Za-z]*${'$'}'
return s:parse_substitute(a:bang,a:line1,a:line2,a:count,[split[0],"",split[1]])
elseif len(split) == 2 && split[1] =~# '^[A-Za-z]*\%([+-]\d\+\)\=${'$'}'
return s:find_command(separator,split[1],split[0])
elseif len(split) >= 2 && split[1] =~# '^[A-Za-z]* '
let flags = matchstr(split[1],'^[A-Za-z]*')
let rest = matchstr(join(split[1:],separator),' \zs.*')
return s:grep_command(rest,a:bang,flags,split[0])
elseif len(split) >= 2 && separator == ' '
return s:grep_command(join(split[1:],' '),a:bang,"",split[0])
else
return s:parse_substitute(a:bang,a:line1,a:line2,a:count,split)
endif
endfunction
function! s:normalize_options(flags)
if type(a:flags) == type({})
let opts = a:flags
let flags = get(a:flags,"flags","")
else
let opts = {}
let flags = a:flags
endif
if flags =~# 'w'
let opts.boundaries = 2
elseif flags =~# 'v'
let opts.boundaries = 1
elseif !has_key(opts,'boundaries')
let opts.boundaries = 0
endif
let opts.case = (flags !~# 'I' ? get(opts,'case',1) : 0)
let opts.flags = substitute(flags,'\C[avIiw]','','g')
return opts
endfunction
" }}}1
" Searching {{{1
function! s:subesc(pattern)
return substitute(a:pattern,'[][\\/.*+?~%()&]','\\&','g')
endfunction
function! s:sort(a,b)
if a:a ==? a:b
return a:a == a:b ? 0 : a:a > a:b ? 1 : -1
elseif strlen(a:a) == strlen(a:b)
return a:a >? a:b ? 1 : -1
else
return strlen(a:a) < strlen(a:b) ? 1 : -1
endif
endfunction
function! s:pattern(dict,boundaries)
if a:boundaries == 2
let a = '<'
let b = '>'
elseif a:boundaries
let a = '%(<|_@<=|[[:lower:]]@<=[[:upper:]]@=)'
let b = '%(>|_@=|[[:lower:]]@<=[[:upper:]]@=)'
else
let a = ''
let b = ''
endif
return '\v\C'.a.'%('.join(map(sort(keys(a:dict),function('s:sort')),'s:subesc(v:val)'),'|').')'.b
endfunction
function! s:egrep_pattern(dict,boundaries)
if a:boundaries == 2
let a = '\<'
let b = '\>'
elseif a:boundaries
let a = '(\<\|_)'
let b = '(\>\|_\|[[:upper:]][[:lower:]])'
else
let a = ''
let b = ''
endif
return a.'('.join(map(sort(keys(a:dict),function('s:sort')),'s:subesc(v:val)'),'\|').')'.b
endfunction
function! s:c()
call histdel('search',-1)
return ""
endfunction
function! s:find_command(cmd,flags,word)
let opts = s:normalize_options(a:flags)
let dict = s:create_dictionary(a:word,"",opts)
" This is tricky. If we use :/pattern, the search drops us at the
" beginning of the line, and we can't use position flags (e.g., /foo/e).
" If we use :norm /pattern, we leave ourselves vulnerable to "press enter"
" prompts (even with :silent).
let cmd = (a:cmd =~ '[?!]' ? '?' : '/')
let @/ = s:pattern(dict,opts.boundaries)
if opts.flags == "" || !search(@/,'n')
return "norm! ".cmd."\<CR>"
elseif opts.flags =~ ';[/?]\@!'
call s:throw("E386: Expected '?' or '/' after ';'")
else
return "exe 'norm! ".cmd.cmd.opts.flags."\<CR>'|call histdel('search',-1)"
return ""
endif
endfunction
function! s:grep_command(args,bang,flags,word)
let opts = s:normalize_options(a:flags)
let dict = s:create_dictionary(a:word,"",opts)
if &grepprg == "internal"
let lhs = "'".s:pattern(dict,opts.boundaries)."'"
elseif &grepprg =~# '^rg\|^ag'
let lhs = "'".s:egrep_pattern(dict,opts.boundaries)."'"
else
let lhs = "-E '".s:egrep_pattern(dict,opts.boundaries)."'"
endif
return "grep".(a:bang ? "!" : "")." ".lhs." ".a:args
endfunction
let s:commands.search = s:commands.abstract.clone()
let s:commands.search.options = {"word": 0, "variable": 0, "flags": ""}
function! s:commands.search.process(bang,line1,line2,count,args)
call s:extractopts(a:args,self.options)
if self.options.word
let self.options.flags .= "w"
elseif self.options.variable
let self.options.flags .= "v"
endif
let opts = s:normalize_options(self.options)
if len(a:args) > 1
return s:grep_command(join(a:args[1:]," "),a:bang,opts,a:args[0])
elseif len(a:args) == 1
return s:find_command(a:bang ? "!" : " ",opts,a:args[0])
else
call s:throw("E471: Argument required")
endif
endfunction
" }}}1
" Substitution {{{1
function! Abolished()
return get(g:abolish_last_dict,submatch(0),submatch(0))
endfunction
function! s:substitute_command(cmd,bad,good,flags)
let opts = s:normalize_options(a:flags)
let dict = s:create_dictionary(a:bad,a:good,opts)
let lhs = s:pattern(dict,opts.boundaries)
let g:abolish_last_dict = dict
return a:cmd.'/'.lhs.'/\=Abolished()'."/".opts.flags
endfunction
function! s:parse_substitute(bang,line1,line2,count,args)
if get(a:args,0,'') =~ '^[/?'']'
let separator = matchstr(a:args[0],'^.')
let args = split(join(a:args,' '),separator,1)
call remove(args,0)
else
let args = a:args
endif
if len(args) < 2
call s:throw("E471: Argument required")
elseif len(args) > 3
call s:throw("E488: Trailing characters")
endif
let [bad,good,flags] = (args + [""])[0:2]
if a:count == 0
let cmd = "substitute"
else
let cmd = a:line1.",".a:line2."substitute"
endif
return s:substitute_command(cmd,bad,good,flags)
endfunction
let s:commands.substitute = s:commands.abstract.clone()
let s:commands.substitute.options = {"word": 0, "variable": 0, "flags": "g"}
function! s:commands.substitute.process(bang,line1,line2,count,args)
call s:extractopts(a:args,self.options)
if self.options.word
let self.options.flags .= "w"
elseif self.options.variable
let self.options.flags .= "v"
endif
let opts = s:normalize_options(self.options)
if len(a:args) <= 1
call s:throw("E471: Argument required")
else
let good = join(a:args[1:],"")
let cmd = a:bang ? "." : "%"
return s:substitute_command(cmd,a:args[0],good,self.options)
endif
endfunction
" }}}1
" Abbreviations {{{1
function! s:badgood(args)
let words = filter(copy(a:args),'v:val !~ "^-"')
call filter(a:args,'v:val =~ "^-"')
if empty(words)
call s:throw("E471: Argument required")
elseif !empty(a:args)
call s:throw("Unknown argument: ".a:args[0])
endif
let [bad; words] = words
return [bad, join(words," ")]
endfunction
function! s:abbreviate_from_dict(cmd,dict)
for [lhs,rhs] in items(a:dict)
exe a:cmd lhs rhs
endfor
endfunction
let s:commands.abbrev = s:commands.abstract.clone()
let s:commands.abbrev.options = {"buffer":0,"cmdline":0,"delete":0}
function! s:commands.abbrev.process(bang,line1,line2,count,args)
let args = copy(a:args)
call s:extractopts(a:args,self.options)
if self.options.delete
let cmd = "unabbrev"
let good = ""
else
let cmd = "noreabbrev"
endif
if !self.options.cmdline
let cmd = "i" . cmd
endif
if self.options.delete
let cmd = "silent! ".cmd
endif
if self.options.buffer
let cmd = cmd . " <buffer>"
endif
let [bad, good] = s:badgood(a:args)
if substitute(bad, '[{},]', '', 'g') !~# '^\k*${'$'}'
call s:throw("E474: Invalid argument (not a keyword: ".string(bad).")")
endif
if !self.options.delete && good == ""
call s:throw("E471: Argument required".a:args[0])
endif
let dict = s:create_dictionary(bad,good,self.options)
call s:abbreviate_from_dict(cmd,dict)
if a:bang
let i = 0
let str = "Abolish ".join(args," ")
let file = g:abolish_save_file
if !isdirectory(fnamemodify(file,':h'))
call mkdir(fnamemodify(file,':h'),'p')
endif
if filereadable(file)
let old = readfile(file)
else
let old = ["\" Exit if :Abolish isn't available.","if !exists(':Abolish')"," finish","endif",""]
endif
call writefile(old + [str],file)
endif
return ""
endfunction
let s:commands.delete = s:commands.abbrev.clone()
let s:commands.delete.options.delete = 1
" }}}1
" Maps {{{1
function! s:unknown_coercion(letter,word)
return a:word
endfunction
call extend(Abolish.Coercions, {
\ 'c': Abolish.camelcase,
\ 'm': Abolish.mixedcase,
\ 's': Abolish.snakecase,
\ '_': Abolish.snakecase,
\ 'u': Abolish.uppercase,
\ 'U': Abolish.uppercase,
\ '-': Abolish.dashcase,
\ 'k': Abolish.dashcase,
\ '.': Abolish.dotcase,
\ ' ': Abolish.spacecase,
\ 't': Abolish.titlecase,
\ "function missing": s:function("s:unknown_coercion")
\}, "keep")
function! s:coerce(type) abort
if a:type !~# '^\%(line\|char\|block\)'
let s:transformation = a:type
let &opfunc = matchstr(expand('<sfile>'), '<SNR>\w*')
return 'g@'
endif
let selection = &selection
let clipboard = &clipboard
try
set selection=inclusive clipboard-=unnamed clipboard-=unnamedplus
let regbody = getreg('"')
let regtype = getregtype('"')
let c = v:count1
let begin = getcurpos()
while c > 0
let c -= 1
if a:type ==# 'line'
let move = "'[V']"
elseif a:type ==# 'block'
let move = "`[\<C-V>`]"
else
let move = "`[v`]"
endif
silent exe 'normal!' move.'y'
let word = @@
let @@ = s:send(g:Abolish.Coercions,s:transformation,word)
if word !=# @@
let changed = 1
exe 'normal!' move.'p'
endif
endwhile
call setreg('"',regbody,regtype)
call setpos("'[",begin)
call setpos(".",begin)
finally
let &selection = selection
let &clipboard = clipboard
endtry
endfunction
nnoremap <expr> <Plug>(abolish-coerce) <SID>coerce(nr2char(getchar()))
vnoremap <expr> <Plug>(abolish-coerce) <SID>coerce(nr2char(getchar()))
nnoremap <expr> <plug>(abolish-coerce-word) <SID>coerce(nr2char(getchar())).'iw'
" }}}1
if !exists("g:abolish_no_mappings") || ! g:abolish_no_mappings
nmap cr <Plug>(abolish-coerce-word)
endif
command! -nargs=+ -bang -bar -range=0 -complete=custom,s:Complete Abolish
\ :exec s:dispatcher(<bang>0,<line1>,<line2>,<count>,[<f-args>])
command! -nargs=1 -bang -bar -range=0 -complete=custom,s:SubComplete Subvert
\ :exec s:subvert_dispatcher(<bang>0,<line1>,<line2>,<count>,<q-args>)
if exists(':S') != 2
command -nargs=1 -bang -bar -range=0 -complete=custom,s:SubComplete S
\ :exec s:subvert_dispatcher(<bang>0,<line1>,<line2>,<count>,<q-args>)
endif
" vim:set ft=vim sw=2 sts=2:
""".trimIndent()
val parsingTime = measureTimeMillis { VimscriptParser.parse(script) }
assertEmpty(IdeavimErrorListener.testLogger)
println(parsingTime)
}
}
| mit | 415b194407899603b0c6ab64ff5f66f2 | 37.720727 | 127 | 0.516206 | 3.470595 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/change/shift/ShiftLeft.kt | 1 | 2703 | /*
* 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.change.shift
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.command.Argument
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.DuplicableOperatorAction
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.handler.ChangeEditorActionHandler
import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler
import com.maddyhome.idea.vim.helper.enumSetOf
import java.util.*
class ShiftLeftLinesAction : ChangeEditorActionHandler.ForEachCaret() {
override val type: Command.Type = Command.Type.INSERT
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_SAVE_STROKE)
override fun execute(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Boolean {
injector.changeGroup.indentLines(editor, caret, context, operatorArguments.count1, -1, operatorArguments)
return true
}
}
class ShiftLeftMotionAction : ChangeEditorActionHandler.ForEachCaret(), DuplicableOperatorAction {
override val type: Command.Type = Command.Type.CHANGE
override val argumentType: Argument.Type = Argument.Type.MOTION
override val duplicateWith: Char = '<'
override fun execute(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
argument: Argument?,
operatorArguments: OperatorArguments,
): Boolean {
argument ?: return false
injector.changeGroup.indentMotion(editor, caret, context, argument, -1, operatorArguments)
return true
}
}
class ShiftLeftVisualAction : VisualOperatorActionHandler.ForEachCaret() {
override val type: Command.Type = Command.Type.CHANGE
override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_EXIT_VISUAL)
override fun executeAction(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
cmd: Command,
range: VimSelection,
operatorArguments: OperatorArguments,
): Boolean {
injector.changeGroup.indentRange(
editor,
caret,
context,
range.toVimTextRange(false),
cmd.count,
-1,
operatorArguments
)
return true
}
}
| mit | 6c130e914b03b70def9ee119076d760b | 29.033333 | 109 | 0.762116 | 4.352657 | false | false | false | false |
DroidSmith/TirePressureGuide | tireguide/src/main/java/com/droidsmith/tireguide/TireGuideActivity.kt | 1 | 19187 | package com.droidsmith.tireguide
import android.icu.text.NumberFormat
import android.os.Bundle
import android.text.InputType
import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.ArrayAdapter
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import com.droidsmith.tireguide.calcengine.Calculator
import com.droidsmith.tireguide.data.RiderType
import com.droidsmith.tireguide.data.TireWidth
import com.droidsmith.tireguide.databinding.ActivityTireGuideBinding
import com.droidsmith.tireguide.databinding.ContentTireGuideBinding
import com.droidsmith.tireguide.extensions.*
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import java.util.*
class TireGuideActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
// This property is only valid between onCreateView and onDestroyView
private lateinit var binding: ActivityTireGuideBinding
private lateinit var contentTireGuide: ContentTireGuideBinding
private lateinit var tirePressureDataBase: TirePressureDataBase
private var totalWeight: Double = 0.0
private var frontLoadWeight: Double = 0.0
private var frontLoadPercent: Double = 0.0
private var rearLoadWeight: Double = 0.0
private var rearLoadPercent: Double = 0.0
private var bodyWeight: Double = 0.0
private var bikeWeight: Double = 0.0
private var itemSelectedFromProfile = false
private var initialLoad = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityTireGuideBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
setSupportActionBar(binding.appBarTireGuide.toolbar)
tirePressureDataBase = TirePressureDataBase(this)
val toggle = ActionBarDrawerToggle(
this,
binding.drawerLayout,
binding.appBarTireGuide.toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
binding.drawerLayout.addDrawerListener(toggle)
toggle.syncState()
binding.navigationView.setNavigationItemSelectedListener(this)
binding.appBarTireGuide.fab.setOnClickListener { button ->
view.hideKeyboard()
onAddProfile(button)
}
contentTireGuide = binding.appBarTireGuide.contentTireGuide
contentTireGuide.profileEdit.setOnEditorActionListener { _, actionId, event ->
var handled = false
if (wasReturnPressed(actionId, event)) {
contentTireGuide.bodyWeightEdit.requestFocus()
handled = true
}
handled
}
contentTireGuide.bodyWeightEdit.setOnEditorActionListener { _, actionId, event ->
var handled = false
if (wasReturnPressed(actionId, event)) {
contentTireGuide.bikeWeightEdit.requestFocus()
handled = true
}
handled
}
contentTireGuide.bikeWeightEdit.setOnEditorActionListener { _, actionId, event ->
var handled = false
if (wasReturnPressed(actionId, event)) {
view.hideKeyboard()
contentTireGuide.frontWidthSpinner.showDropDown()
handled = true
}
handled
}
val tireWidths: Array<String> = TireWidth.getWidthsAsStrings()
val frontWidthAdapter = ArrayAdapter(requireActivity(), R.layout.dropdown_menu_popup_item, tireWidths)
contentTireGuide.frontWidthSpinner.apply {
setAdapter(frontWidthAdapter)
inputType = InputType.TYPE_NULL
setText(TireWidth.TWENTY_FIVE.displayName, false)
addOnTextChangedBehavior {
if (!itemSelectedFromProfile && !initialLoad) {
view.hideKeyboard()
contentTireGuide.rearWidthSpinner.showDropDown()
}
}
}
val rearWidthAdapter = ArrayAdapter(requireActivity(), R.layout.dropdown_menu_popup_item, tireWidths)
contentTireGuide.rearWidthSpinner.apply {
setAdapter(rearWidthAdapter)
inputType = InputType.TYPE_NULL
setText(TireWidth.TWENTY_FIVE.displayName, false)
addOnTextChangedBehavior {
if (!itemSelectedFromProfile && !initialLoad) {
hideKeyboard()
contentTireGuide.riderTypeSpinner.showDropDown()
}
}
}
val riderTypes: Array<String> = RiderType.getRiderTypesAsStrings(requireActivity())
val riderTypeAdapter = ArrayAdapter(requireActivity(), R.layout.dropdown_menu_popup_item, riderTypes)
contentTireGuide.riderTypeSpinner.apply {
setAdapter(riderTypeAdapter)
inputType = InputType.TYPE_NULL
setText(getString(RiderType.CASUAL.displayName), false)
addOnTextChangedBehavior { riderDisplayType ->
if (!itemSelectedFromProfile && !initialLoad) {
when (RiderType.getTypeFromDisplayName(requireActivity(), riderDisplayType)) {
RiderType.RACER -> {
contentTireGuide.frontLoadEdit.setText(RACER_FRONT)
contentTireGuide.frontLoadUnitsSpinner.setSelection(0, true)
contentTireGuide.rearLoadEdit.setText(RACER_REAR)
contentTireGuide.rearLoadUnitsSpinner.setSelection(0, true)
}
RiderType.SPORT -> {
contentTireGuide.frontLoadEdit.setText(SPORT_FRONT)
contentTireGuide.frontLoadUnitsSpinner.setSelection(0, true)
contentTireGuide.rearLoadEdit.setText(SPORT_REAR)
contentTireGuide.rearLoadUnitsSpinner.setSelection(0, true)
}
else -> {
contentTireGuide.frontLoadEdit.setText(CASUAL_FRONT)
contentTireGuide.frontLoadUnitsSpinner.setSelection(0, true)
contentTireGuide.rearLoadEdit.setText(CASUAL_REAR)
contentTireGuide.rearLoadUnitsSpinner.setSelection(0, true)
}
}
contentTireGuide.frontLoadEdit.requestFocus()
contentTireGuide.frontLoadEdit.showKeyboard()
}
}
}
contentTireGuide.frontLoadEdit.setText(CASUAL_FRONT)
contentTireGuide.frontLoadEdit.setOnEditorActionListener { _, actionId, event ->
var handled = false
if (wasReturnPressed(actionId, event)) {
contentTireGuide.rearLoadEdit.requestFocus()
handled = true
}
handled
}
val frontLoadAdapter = ArrayAdapter.createFromResource(
this,
R.array.load_array,
R.layout.spinner_item
)
frontLoadAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item)
contentTireGuide.frontLoadUnitsSpinner.adapter = frontLoadAdapter
contentTireGuide.frontLoadUnitsSpinner.setSelection(0, true)
contentTireGuide.rearLoadEdit.setText(CASUAL_REAR)
contentTireGuide.rearLoadEdit.setOnEditorActionListener { _, actionId, event ->
var handled = false
if (wasReturnPressed(actionId, event)) {
view.hideKeyboard()
onCalculateTirePressure()
handled = true
}
handled
}
val rearLoadAdapter = ArrayAdapter.createFromResource(
this,
R.array.load_array,
R.layout.spinner_item
)
rearLoadAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item)
contentTireGuide.rearLoadUnitsSpinner.adapter = rearLoadAdapter
contentTireGuide.rearLoadUnitsSpinner.setSelection(0, true)
contentTireGuide.calculateButton.setOnClickListener { button ->
button.hideKeyboard()
onCalculateTirePressure()
}
contentTireGuide.profileEdit.requestFocus()
getProfile()
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
if (frontLoadPercent > 0) {
contentTireGuide.frontLoadEdit.setText(fmt(frontLoadPercent))
}
if (rearLoadPercent > 0) {
contentTireGuide.rearLoadEdit.setText(fmt(rearLoadPercent))
}
initialLoad = false
}
private fun fmt(d: Double): String = NumberFormat.getNumberInstance(Locale.US).format(d)
override fun onBackPressed() {
if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
binding.drawerLayout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.tire_guide, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
return if (id == R.id.action_settings) true
else super.onOptionsItemSelected(item)
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
totalWeight = savedInstanceState.getDouble(BUNDLE_TOTAL_WEIGHT)
frontLoadWeight = savedInstanceState.getDouble(BUNDLE_FRONT_LOAD_WEIGHT)
frontLoadPercent = savedInstanceState.getDouble(BUNDLE_FRONT_LOAD_PERCENT)
rearLoadWeight = savedInstanceState.getDouble(BUNDLE_REAR_LOAD_WEIGHT)
rearLoadPercent = savedInstanceState.getDouble(BUNDLE_REAR_LOAD_PERCENT)
bodyWeight = savedInstanceState.getDouble(BUNDLE_BODY_WEIGHT)
bikeWeight = savedInstanceState.getDouble(BUNDLE_BIKE_WEIGHT)
itemSelectedFromProfile = savedInstanceState.getBoolean(BUNDLE_ITEM_SELECTED_FROM_PROFILE)
val tireWidths: Array<String> = TireWidth.getWidthsAsStrings()
val frontWidthAdapter = ArrayAdapter(requireActivity(), R.layout.dropdown_menu_popup_item, tireWidths)
contentTireGuide.frontWidthSpinner.setAdapter(frontWidthAdapter)
val rearWidthAdapter = ArrayAdapter(requireActivity(), R.layout.dropdown_menu_popup_item, tireWidths)
contentTireGuide.rearWidthSpinner.setAdapter(rearWidthAdapter)
val riderTypes: Array<String> = RiderType.getRiderTypesAsStrings(requireActivity())
val riderTypeAdapter = ArrayAdapter(requireActivity(), R.layout.dropdown_menu_popup_item, riderTypes)
contentTireGuide.riderTypeSpinner.setAdapter(riderTypeAdapter)
initialLoad = true
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putDouble(BUNDLE_TOTAL_WEIGHT, totalWeight)
outState.putDouble(BUNDLE_FRONT_LOAD_WEIGHT, frontLoadWeight)
outState.putDouble(BUNDLE_FRONT_LOAD_PERCENT, frontLoadPercent)
outState.putDouble(BUNDLE_REAR_LOAD_WEIGHT, rearLoadWeight)
outState.putDouble(BUNDLE_REAR_LOAD_PERCENT, rearLoadPercent)
outState.putDouble(BUNDLE_BODY_WEIGHT, bodyWeight)
outState.putDouble(BUNDLE_BIKE_WEIGHT, bikeWeight)
outState.putBoolean(BUNDLE_ITEM_SELECTED_FROM_PROFILE, itemSelectedFromProfile)
tirePressureDataBase.close()
}
/**
* Retrieves the profile from the database and displays the values.
*/
private fun getProfile() {
val profile = tirePressureDataBase.profiles
profile.moveToFirst()
while (!profile.isAfterLast) {
itemSelectedFromProfile = true
contentTireGuide.profileEdit.setText(profile.getString(Profiles.PROFILE_NAME))
bodyWeight = profile.getDouble(Profiles.BODY_WEIGHT)
contentTireGuide.bodyWeightEdit.setText(fmt(bodyWeight))
bikeWeight = profile.getDouble(Profiles.BIKE_WEIGHT)
contentTireGuide.bikeWeightEdit.setText(fmt(bikeWeight))
val frontTireWidth = TireWidth.getWidthFromDisplayName(profile.getString(Profiles.FRONT_TIRE_WIDTH))
contentTireGuide.frontWidthSpinner.setText(frontTireWidth?.displayName, false)
val rearTireWidth = TireWidth.getWidthFromDisplayName(profile.getString(Profiles.REAR_TIRE_WIDTH))
contentTireGuide.rearWidthSpinner.setText(rearTireWidth?.displayName, false)
val riderType = RiderType.getTypeFromServiceName(profile.getString(Profiles.RIDER_TYPE))
contentTireGuide.riderTypeSpinner.setText(riderType?.displayName?.let { getString(it) }, false)
frontLoadPercent = profile.getDouble(Profiles.FRONT_LOAD_PERCENT)
rearLoadPercent = profile.getDouble(Profiles.REAR_LOAD_PERCENT)
profile.moveToNext()
}
itemSelectedFromProfile = false
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.navigationRecents -> {
//Todo pull the latest profile, I think
}
R.id.navigationAdd -> {
val group = this.findViewById<ViewGroup>(android.R.id.content)
if (group != null) {
val viewGroup = group.getChildAt(0) as ViewGroup
onAddProfile(viewGroup)
}
}
R.id.navigationManage -> {
// TODO I'm going to remember what this is some day
}
R.id.navigationHelp -> {
openExternalUrl(TIRE_INFLATION_PDF)
}
}
val drawer = findViewById<DrawerLayout>(R.id.drawerLayout)
drawer?.closeDrawer(GravityCompat.START)
return true
}
private fun onAddProfile(view: View) {
val profileNameText = if (contentTireGuide.profileEdit.text.isNullOrEmpty()) {
DEFAULT
} else {
contentTireGuide.profileEdit.text.toString()
}
val selectedRiderType =
RiderType.getTypeFromDisplayName(requireActivity(), contentTireGuide.riderTypeSpinner.text.toString())
val frontTireWidth = TireWidth.getWidthFromDisplayName(contentTireGuide.frontWidthSpinner.text.toString())
val rearTireWidth = TireWidth.getWidthFromDisplayName(contentTireGuide.rearWidthSpinner.text.toString())
view.hideKeyboard()
onCalculateTirePressure()
val profile = tirePressureDataBase.addProfile(
profileNameText,
selectedRiderType?.serviceName.orEmpty(),
bodyWeight,
bikeWeight,
frontTireWidth?.displayName.orEmpty(),
rearTireWidth?.displayName.orEmpty(),
frontLoadPercent,
rearLoadPercent
)
if (profile.toFloat() == 0f) {
Snackbar.make(view, R.string.updated_existing_profile, Snackbar.LENGTH_SHORT).show()
} else {
Snackbar.make(
view,
getString(R.string.created_new_profile, profile),
Snackbar.LENGTH_SHORT
).show()
}
}
private fun onCalculateTirePressure() {
bodyWeight = if (contentTireGuide.bodyWeightEdit.text.isNullOrEmpty()) {
0.0
} else {
contentTireGuide.bodyWeightEdit.text.toString().toDouble()
}
bikeWeight = if (contentTireGuide.bikeWeightEdit.text.isNullOrEmpty()) {
0.0
} else {
contentTireGuide.bikeWeightEdit.text.toString().toDouble()
}
val frontLoadText = if (contentTireGuide.frontLoadEdit.text.isNullOrEmpty()) {
"0.0"
} else {
contentTireGuide.frontLoadEdit.text.toString()
}
val rearLoadText = if (contentTireGuide.rearLoadEdit.text.isNullOrEmpty()) {
"0.0"
} else {
contentTireGuide.rearLoadEdit.text.toString()
}
totalWeight = bodyWeight + bikeWeight
val frontLoadItem = contentTireGuide.frontLoadUnitsSpinner.selectedItem.toString()
if ("%" == frontLoadItem) {
frontLoadPercent = frontLoadText.toDouble()
frontLoadWeight = totalWeight * frontLoadPercent / 100
} else {
frontLoadPercent = frontLoadText.toDouble() * 100 / totalWeight
frontLoadWeight = frontLoadText.toDouble()
}
val rearLoadItem = contentTireGuide.rearLoadUnitsSpinner.selectedItem.toString()
if ("%" == rearLoadItem) {
rearLoadPercent = rearLoadText.toDouble()
rearLoadWeight = totalWeight * rearLoadPercent / 100
} else {
rearLoadPercent = rearLoadText.toDouble() * 100 / totalWeight
rearLoadWeight = rearLoadText.toDouble()
}
val frontTireCalculator = Calculator()
contentTireGuide.frontTirePressure.text = fmt(
frontTireCalculator.psi(
frontLoadWeight,
contentTireGuide.frontWidthSpinner.text.toString()
)
)
val rearTireCalculator = Calculator()
contentTireGuide.rearTirePressure.text = fmt(
rearTireCalculator.psi(
rearLoadWeight,
contentTireGuide.rearWidthSpinner.text.toString()
)
)
}
private fun wasReturnPressed(actionId: Int, event: KeyEvent?): Boolean {
val action = actionId and EditorInfo.IME_MASK_ACTION
return event?.keyCode == KeyEvent.FLAG_EDITOR_ACTION ||
action == EditorInfo.IME_ACTION_DONE ||
action == EditorInfo.IME_ACTION_NEXT ||
action == EditorInfo.IME_ACTION_GO ||
event?.keyCode == KeyEvent.KEYCODE_ENTER
}
companion object {
private const val BUNDLE_TOTAL_WEIGHT = "BUNDLE_TOTAL_WEIGHT"
private const val BUNDLE_FRONT_LOAD_WEIGHT = "BUNDLE_FRONT_LOAD_WEIGHT"
private const val BUNDLE_FRONT_LOAD_PERCENT = "BUNDLE_FRONT_LOAD_PERCENT"
private const val BUNDLE_REAR_LOAD_WEIGHT = "BUNDLE_REAR_LOAD_WEIGHT"
private const val BUNDLE_REAR_LOAD_PERCENT = "BUNDLE_REAR_LOAD_PERCENT"
private const val BUNDLE_BODY_WEIGHT = "BUNDLE_BODY_WEIGHT"
private const val BUNDLE_BIKE_WEIGHT = "BUNDLE_BIKE_WEIGHT"
private const val BUNDLE_ITEM_SELECTED_FROM_PROFILE = "BUNDLE_IS_SELECTED_FROM_PROFILE"
}
}
| apache-2.0 | db8236dc1cba714aa765db55084ff276 | 41.828125 | 114 | 0.650753 | 4.717728 | false | false | false | false |
npryce/robots | webui/src/main/kotlin/robots/ui/config/ActionsConfiguration.kt | 1 | 2504 | package robots.ui.config
import kotlinx.html.js.onChangeFunction
import kotlinx.html.js.onClickFunction
import kotlinx.html.title
import org.w3c.dom.events.InputEvent
import react.RBuilder
import react.dom.button
import react.dom.div
import react.dom.input
import react.dom.table
import react.dom.tbody
import react.dom.td
import react.dom.tr
import robots.Action
import robots.ui.ActionCardStyle
import robots.ui.ActionCardSuit
import robots.ui.Speech
import robots.ui.handler
import robots.ui.newValue
fun RBuilder.actionsConfiguration(actions: ActionCardSuit, speech: Speech, updateActions: (ActionCardSuit) -> Unit) {
configPanel("actions") {
table(configItemsClass) {
tbody {
actions.forEachIndexed { i, card ->
tr {
actionCardEditor(
card = card,
speech = speech,
update = { updateActions(actions.replace(i, it)) },
delete = { updateActions(actions.remove(it)) }
)
}
}
}
}
div {
button {
attrs.title = "Add new action"
attrs.onClickFunction = { ev ->
updateActions(actions.add(ActionCardStyle("?", Action("Change this"))))
ev.stopPropagation()
}
+"+"
}
}
}
}
private fun RBuilder.actionCardEditor(
card: ActionCardStyle,
speech: Speech,
update: (ActionCardStyle) -> Unit,
delete: (ActionCardStyle) -> Unit
) {
td {
input {
attrs.width = "2"
attrs.onChangeFunction = handler<InputEvent> {
update(card.copy(face = it.newValue))
}
attrs.value = card.face
}
}
td {
input {
attrs.value = card.explanation
attrs.disabled = speech.isSpeaking
attrs.onChangeFunction = handler<InputEvent> {
update(card.copy(value = Action(it.newValue)))
}
}
}
td {
button {
attrs.disabled = speech.isSpeaking
attrs.onClickFunction = { speech.speak(card.explanation) }
+"▶︎"
}
}
td {
button {
attrs.disabled = speech.isSpeaking
attrs.onClickFunction = { delete(card) }
+"-"
}
}
}
| gpl-3.0 | 6f0f1e468d5765347d0236d8b7ffc4f9 | 26.777778 | 117 | 0.5296 | 4.612546 | false | false | false | false |
ingokegel/intellij-community | platform/platform-tests/testSrc/com/intellij/openapi/application/impl/CancellableReadActionWithJobTest.kt | 4 | 2419 | // 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.application.impl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class CancellableReadActionWithJobTest : CancellableReadActionTests() {
@Test
fun context() {
currentJobTest { currentJob ->
val application = ApplicationManager.getApplication()
assertNull(ProgressManager.getGlobalProgressIndicator())
application.assertReadAccessNotAllowed()
val result = computeCancellable {
val readJob = requireNotNull(Cancellation.currentJob())
assertJobIsChildOf(job = readJob, parent = currentJob)
assertNull(ProgressManager.getGlobalProgressIndicator())
application.assertReadAccessAllowed()
42
}
assertEquals(42, result)
assertNull(ProgressManager.getGlobalProgressIndicator())
application.assertReadAccessNotAllowed()
}
}
@Test
fun cancellation() {
val job = Job()
withCurrentJob(job) {
assertThrows<CancellationException> {
computeCancellable {
testNoExceptions()
job.cancel()
testExceptions()
}
}
}
}
@Test
fun rethrow() {
currentJobTest {
testComputeCancellableRethrow()
}
}
@Test
fun `throws when a write is pending`() {
currentJobTest {
testThrowsIfPendingWrite()
}
}
@Test
fun `throws when a write is running`() {
currentJobTest {
testThrowsIfRunningWrite()
}
}
@Test
fun `does not throw when a write is requested during almost finished computation`() {
currentJobTest {
testDoesntThrowWhenAlmostFinished()
}
}
@Test
fun `throws when a write is requested during computation`() {
currentJobTest {
testThrowsOnWrite()
}
}
@Test
fun `throws inside non-cancellable read action when a write is requested during computation`() {
currentJobTest {
runReadAction {
testThrowsOnWrite()
}
}
}
}
| apache-2.0 | b3cfe2f2500a2bc5ddae11c6c7543277 | 24.463158 | 120 | 0.700289 | 4.838 | false | true | false | false |
micolous/metrodroid | src/iOSMain/kotlin/au/id/micolous/metrodroid/util/StationTableReader.kt | 1 | 8661 | /*
* StationTableReader.kt
* Reader for Metrodroid Station Table (MdST) files.
*
* Copyright 2018 Michael Farrell <[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 au.id.micolous.metrodroid.util
import au.id.micolous.metrodroid.multi.Log
import au.id.micolous.metrodroid.transit.TransitName
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.util.StationTableReaderImpl.InvalidHeaderException
import platform.Foundation.NSBundle
import au.id.micolous.metrodroid.proto.stations.*
import kotlinx.cinterop.usePinned
import kotlinx.cinterop.addressOf
actual internal fun StationTableReaderGetSTR(name: String): StationTableReader? =
StationTableReaderRegistry.fetch(name)
private const val TAG = "StationTableReaderIOS"
class StationTableReaderWrapper (val name: String) {
val wrapped: StationTableReaderImpl? by lazy {
try {
val ret = StationTableReaderImpl(name)
Log.d(TAG, "Opened DB $name")
ret
} catch (e: Exception) {
Log.w(TAG, "DB $name doesn't exist: $e")
null
}
}
}
object StationTableReaderRegistry {
private val allList: List<String> get() {
val res = NSBundle.mainBundle.pathsForResourcesOfType("mdst", inDirectory = "mdst").toList().filterIsInstance<String>().map { it.substringAfterLast("/").substringBefore(".mdst") }
Log.d(TAG, "mdsts = $res")
return res
}
private val registry: Map<String, StationTableReaderWrapper> = allList.map { it to StationTableReaderWrapper(it) }.toMap()
fun fetch(name: String) = registry[name]?.wrapped
fun path(name: String) = NSBundle.mainBundle.pathForResource(name, ofType = "mdst", inDirectory = "mdst")
}
operator fun GPBUInt32UInt32Dictionary.get(key: UInt): UInt? {
val buffer = uintArrayOf(0.toUInt())
var found = false
buffer.usePinned { pin ->
found = this.getUInt32(pin.addressOf(0), forKey = key)
}
if (found)
return buffer[0]
return null
}
fun GPBUInt32Array.toList(): List<UInt> = List(this.count.toInt()) { this.valueAtIndex(it.toULong()) }
private const val MAX_VARINT = 10
fun <T : GPBMessage> parseDelimited(file: ConcurrentFileReader, off: Long, dest: T): Pair<T?, Int> {
val headBuf = file.read(off, MAX_VARINT)
val headCi = GPBCodedInputStream.streamWithData(headBuf.toNSData())
val payloadLen = headCi.readInt64().toInt()
val headLen = headCi.position().toInt()
val payloadBuf = file.read(off, payloadLen + headLen)
val payloadCi = GPBCodedInputStream.streamWithData(payloadBuf.toNSData())
try {
payloadCi.readMessage(dest, null)
} catch (e: Exception) {
Log.e(TAG, "error reading mesaage: $e")
return Pair(null, headLen + payloadLen)
}
return Pair(dest, headLen + payloadLen)
}
/**
* Metrodroid Station Table (MdST) file reader.
*
* For more information about the file format, see extras/mdst/README.md in the Metrodroid source
* repository.
*/
class StationTableReaderImpl
/**
* Initialises a "connection" to a Metrodroid Station Table kept in the `assets/` directory.
* @param dbName MdST filename
* @throws InvalidHeaderException If the file is not a MdST file.
*/
internal constructor(dbName: String) : StationTableReader {
private val mStationDb: StationDb
private val mStationIndex: StationIndex? by lazy {
try {
parseDelimited(mTable, mStationsStart + mStationsLength, StationIndex()).first
} catch (e: Exception) {
Log.e(TAG, "error reading index", e)
null
}
}
private val mTable: ConcurrentFileReader
private val mStationsLength: Long
private val mStationsStart: Long
override val notice: String?
get() = mStationDb.licenseNotice.ifEmpty { null }
class InvalidHeaderException (msg: String): Exception(msg)
init {
val path = StationTableReaderRegistry.path(dbName) ?: throw InvalidHeaderException("Resource not found")
mTable = ConcurrentFileReader.openFile(path) ?: throw InvalidHeaderException("Open failed")
val header = mTable.read(0, 12)
if (header.size != 12)
throw InvalidHeaderException("Failed reading header")
val imm = header.toImmutable()
// Read the Magic, and validate it.
if (imm.sliceOffLen(0, 4) != MAGIC) {
throw InvalidHeaderException("Header mismatch")
}
// Check the version
if (imm.byteArrayToInt(4, 4) != VERSION) {
throw InvalidHeaderException("Version")
}
mStationsLength = imm.byteArrayToLong(8, 4)
// Read out the header
val (stationDb, len) = parseDelimited(mTable, 12, StationDb())
mStationDb = stationDb ?: throw InvalidHeaderException("stationDb is nutll")
mStationsStart = 12 + len.toLong()
}
/**
* Gets a Station object, according to the MdST buf definition.
* @param id Stop ID
* @return Station object, or null if it could not be found.
*/
private fun getStationById(id: Int): Station? {
val offset: Int
try {
offset = mStationIndex?.stationMap?.get(id.toUInt())?.toInt() ?: return null
} catch (e: IllegalArgumentException) {
Log.d(TAG, "Unknown station $id")
return null
}
return parseDelimited(mTable, mStationsStart + offset.toLong(), Station()).first
}
override fun getOperatorDefaultMode(oper: Int): Trip.Mode? {
val po = mStationDb.operators.objectForKey(oper.toUInt()) as? Operator ?: return null
return convertTransportType(po.defaultTransport)
}
override fun getOperatorName(oper: Int): TransitName? {
val po = mStationDb.operators.objectForKey(oper.toUInt()) as? Operator ?: return null
return makeTransitName(po.name ?: return null)
}
override fun getLineName(id: Int): TransitName? {
val pl = mStationDb.lines.objectForKey(id.toUInt()) as? Line ?: return null
return makeTransitName(pl.name)
}
override fun getLineMode(id: Int): Trip.Mode? {
val pl = mStationDb.lines.objectForKey(id.toUInt()) as? Line ?: return null
return convertTransportType(pl.transport)
}
/**
* Gets a Metrodroid-native Station object for a given stop ID.
* @param id Stop ID.
* @return Station object, or null if it could not be found.
*/
override fun getStationById(id: Int, humanReadableID: String): ProtoStation? {
val ps = getStationById(id) ?: return null
return ProtoStation(name = makeTransitName(ps.name), latitude = ps.latitude, longitude = ps.longitude,
lineIdList = ps.lineIdArray.toList().map { it.toInt() }, operatorId = ps.operatorId.toInt())
}
@Suppress("RemoveExplicitTypeArguments")
private fun makeTransitName(name: Names) =
TransitName(englishFull = name.english,
englishShort = name.englishShort,
localFull = name.local,
localShort = name.localShort,
localLanguagesList = mStationDb.localLanguagesArray.toList().filterIsInstance<String>(),
ttsHintLanguage = mStationDb.ttsHintLanguage)
companion object {
private val MAGIC = ImmutableByteArray.of(0x4d, 0x64, 0x53, 0x54)
private const val VERSION = 1
private fun squash(input: String): String = input.substringAfter("TransportType").replace("_", "", ignoreCase = true).toLowerCase()
private fun convertTransportType(input : TransportType): Trip.Mode? {
if (input == TransportType_Unknown)
return null
val name = TransportType_EnumDescriptor().enumNameForValue(input)
if (name == null) {
Log.w(TAG, "Unknown transport type $input")
return null
}
return Trip.Mode.values().find { squash (it.name) == squash (name) }
}
}
}
| gpl-3.0 | 97334c608bd198a664898fc13a711d64 | 37.154185 | 187 | 0.665281 | 4.083451 | false | false | false | false |
anitaa1990/DeviceInfo-Sample | deviceinfo/src/main/java/com/an/deviceinfo/permission/PermissionManager.kt | 1 | 10936 | package com.an.deviceinfo.permission
import android.app.Activity
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v7.app.AlertDialog
import android.util.Log
class PermissionManager : DialogInterface.OnClickListener {
private val MY_PERMISSIONS = 1012
private val PERMISSIONS_TAG = "Permissions"
private val DEFAULT_DENY_DIALOG_TITLE = "Permission Required"
private val DEFAULT_DENY_DIALOG_POS_BTN = "GO TO SETTINGS"
private val DEFAULT_DENY_DIALOG_NEG_BTN = "CANCEL"
private var activity: Activity? = null
private var fragment: Fragment? = null
private var permissionUtils: PermissionUtils? = null
private var permissionCallback: PermissionCallback? = null
private var permission: String? = null
private var showDenyDialog = true
private var showRationale = true
private var denyDialogText: String? = null
private var denyDialogTitle = DEFAULT_DENY_DIALOG_TITLE
private var denyPosBtnTxt = DEFAULT_DENY_DIALOG_POS_BTN
private var denyNegBtnTxt = DEFAULT_DENY_DIALOG_NEG_BTN
private var showNegBtn = true
private var isCancellable = true
private var alertDialog: AlertDialog? = null
constructor(fragment: Fragment) {
this.fragment = fragment
this.activity = fragment.activity
permissionUtils = PermissionUtils(activity!!)
}
constructor(activity: Activity) {
this.activity = activity
permissionUtils = PermissionUtils(activity)
}
/**
* This is the method to be called to display permission dialog
* pass the permission string along with this method
*/
fun showPermissionDialog(permission: String): PermissionManager {
this.permission = permission
return this
}
/**
* This should be called in case you want to display
* a custom dialog explaining why you require this
* permission.
* This will be called once the user has denied the
* permission and checked the "never show again" button
*/
fun withDenyDialogEnabled(showDenyDialog: Boolean): PermissionManager {
this.showDenyDialog = showDenyDialog
return this
}
/**
* This should be called in case you want to display
* android dialog to users if they have not checked the
* "never show again" button
* This will be called once the user has denied the
* permission the first time
*/
fun withRationaleEnabled(showRationale: Boolean): PermissionManager {
this.showRationale = showRationale
return this
}
/**
* This will display the description text explaining to the users
* why we need this permission
*/
fun withDenyDialogMsg(denyDialogText: String): PermissionManager {
this.denyDialogText = denyDialogText
return this
}
/**
* This is an option parameter to display the title for the
* custom dialog. By default, it will be "Permission required"
*/
fun withDenyDialogTitle(denyDialogTitle: String): PermissionManager {
this.denyDialogTitle = denyDialogTitle
return this
}
/**
* This is an option parameter to display the positive button text
* for the custom dialog. By default, it will be "GO TO SETTINGS"
* This will redirect the users to the settings screen once clicked
*/
fun withDenyDialogPosBtnText(denyPosBtnTxt: String): PermissionManager {
this.denyPosBtnTxt = denyPosBtnTxt
return this
}
/**
* This is an option parameter to display the negative button text
* for the custom dialog. By default, it will be "Cancel"
*/
fun withDenyDialogNegBtnText(denyNegBtnTxt: String): PermissionManager {
this.denyNegBtnTxt = denyNegBtnTxt
return this
}
/**
* This is an option parameter to show/hide the negative dialog
* button. This is to make sure that the user has no choice but
* to grant the permission. By default this flag will be false.
*/
fun withDenyDialogNegBtn(showNegBtn: Boolean): PermissionManager {
this.showNegBtn = showNegBtn
return this
}
/**
* This is an option parameter to provide users with an option
* to cancel the permission dialog. If this is false the user
* has no choice but to grant the permission.
* By default this flag will be true.
*/
fun isDialogCancellable(isCancellable: Boolean): PermissionManager {
this.isCancellable = isCancellable
return this
}
/**
* This is an option parameter to receive a callback for the
* permission
*/
fun withCallback(permissionCallback: PermissionCallback): PermissionManager {
this.permissionCallback = permissionCallback
return this
}
/**
* Build method will be invoked only when the permission string is valid
* and if the showDenyDialog flag is enabled, you need to pass a dialog text
* in order to build the permissions dialog
*/
@Synchronized
fun build() {
if (permission == null) {
throw RuntimeException("You need to set a permission before calling Build method!")
}
if (permissionCallback == null) {
throw RuntimeException("You need to set a permissionCallback before calling Build method!")
}
if (showDenyDialog && denyDialogText == null) {
throw RuntimeException("You need to set a deny Dialog description message before calling Build method!")
}
/**
* Check if permission is already granted.
* If so, do not ask again
*/
if (permissionUtils!!.isPermissionGranted(permission!!)) {
Log.d(PERMISSIONS_TAG, String.format("%s permission already granted!", permission))
return
}
//
// /**
// * User has denied permission and has checked the never
// * show again button.
// * Custom deny dialog is displayed
// * */
// if(showDenyDialog && !activity.shouldShowRequestPermissionRationale(permission) && showRationale) {
// displayDenyDialog();
// return;
// }
askPermissionDialog()
}
@Synchronized private fun askPermissionDialog() {
if (hasStarted) return
hasStarted = true
/**
* onPermissionResult will only be called inside a fragment
* if the permission is asked in this way.
* We need to call fragment.requestPermissions when asking
* permission in a fragment
*/
if (fragment != null) {
fragment!!.requestPermissions(arrayOf<String>(permission!!), MY_PERMISSIONS)
return
}
/**
* If permission is not called inside a fragment and called only
* in the activity, then the below code is executed
*/
ActivityCompat.requestPermissions(activity!!, arrayOf<String>(permission!!), MY_PERMISSIONS)
}
@Synchronized
fun handleResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (permissions.size == 0) return
val permission = permissions[0]
when (requestCode) {
MY_PERMISSIONS -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/**
* Permission is granted
*/
hasStarted = false
if (permissionCallback != null) permissionCallback!!.onPermissionGranted(permissions, grantResults)
} else if (activity!!.shouldShowRequestPermissionRationale(permission) && showRationale) {
hasStarted = false
/**
* Show permission dialog again but only if "deny show again" button is not checked by user
* and if the user has specifically allowed to display the permission
*/
askPermissionDialog()
} else if (showDenyDialog) {
/**
* Show custom permission dialog explaining to the user why the app requires the permission
* This should only be displayed if the app developer has specified it
* It will be displayed by default and it will open the settings page by default
*/
displayDenyDialog()
} else {
/**
* User has denied the permission even after explanation.
* Denied callback is invoked
*/
if (permissionCallback != null) permissionCallback!!.onPermissionDismissed(permission)
}
}
}
@Synchronized private fun displayDenyDialog() {
val alertDialogBuilder = AlertDialog.Builder(activity!!)
/**
* dialog Title
*/
.setTitle(denyDialogTitle)
/**
* dialog description
* * */
.setMessage(denyDialogText)
/**
* dialog should be cancellable
* * */
.setCancelable(isCancellable)
/**
* dialog Postive Button text
* * */
.setPositiveButton(denyPosBtnTxt, this)
/**
* dialog Negative Button button
* By default this will be displayed to the user
* * */
if (showNegBtn) {
alertDialogBuilder.setNegativeButton(denyNegBtnTxt, this)
}
/**
* create alert dialog
* * */
alertDialog = alertDialogBuilder.show()
}
override fun onClick(dialog: DialogInterface, which: Int) {
hasStarted = false
if (alertDialog != null && alertDialog!!.isShowing)
alertDialog!!.dismiss()
if (which == DialogInterface.BUTTON_POSITIVE) {
permissionCallback!!.onPositiveButtonClicked(dialog, which)
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
permissionCallback!!.onNegativeButtonClicked(dialog, which)
}
}
/**
* Custom callback interface users can invoke to receive status
* about the permissions.
* This is an optional parameter
*/
interface PermissionCallback {
fun onPermissionGranted(permissions: Array<String>, grantResults: IntArray)
fun onPermissionDismissed(permission: String)
fun onPositiveButtonClicked(dialog: DialogInterface, which: Int)
fun onNegativeButtonClicked(dialog: DialogInterface, which: Int)
}
companion object {
private var hasStarted = false
}
} | apache-2.0 | 3c019f39f68a533ae69755f79abdd389 | 33.501577 | 117 | 0.622714 | 5.265286 | false | false | false | false |
bdelville/easingdaterange | library/src/main/java/eu/hithredin/easingdate/MaterialRangeSlider.kt | 1 | 17118 | package eu.hithredin.easingdate
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.util.TypedValue
import android.view.MotionEvent
import android.view.View
import android.view.animation.AccelerateInterpolator
import java.util.*
interface RangeSliderListener {
fun onUpperChanged(newValue: Int)
fun onLowerChanged(newValue: Int)
fun onEndAction(lower: Int, upper: Int)
}
/**
* Slider following Material Design with two movable targets that allow user to select a range of integers.
*
* Convertion from https://github.com/twotoasters/MaterialRangeSlider
*/
class MaterialRangeSlider : View {
private var deviceHelper: DeviceDateRange
private val DEFAULT_TOUCH_TARGET_SIZE = 50
private val DEFAULT_UNPRESSED_RADIUS = 15
private val DEFAULT_PRESSED_RADIUS = 40
private val DEFAULT_INSIDE_RANGE_STROKE_WIDTH = 8
private val DEFAULT_OUTSIDE_RANGE_STROKE_WIDTH = 4
private val HORIZONTAL_PADDING = (DEFAULT_PRESSED_RADIUS / 2) + DEFAULT_OUTSIDE_RANGE_STROKE_WIDTH
val DEFAULT_MAX: Int = 1000
private var unpressedRadius: Float = 0.toFloat()
private var pressedRadius: Float = 0.toFloat()
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var lineStartX: Int = 0
private var lineEndX: Int = 0
private var lineLength: Int = 0
private var minTargetRadius = 0f
private var maxTargetRadius = 0f
private var minPosition = 0
private var maxPosition = 0
private var midY = 0
//List of event IDs touching targets
private val isTouchingMinTarget = HashSet<Int>()
private val isTouchingMaxTarget = HashSet<Int>()
var min: Int = 0
set(min) {
field = min
range = max - min
}
var max: Int = DEFAULT_MAX
set(max) {
field = max
range = max - min
}
var range: Int = 0; private set
private var convertFactor: Float = 0.toFloat()
var rangeSliderListener: RangeSliderListener? = null
private var targetColor: Int = 0
private var insideRangeColor: Int = 0
private var outsideRangeColor: Int = 0
private var colorControlNormal: Int = 0
private var colorControlHighlight: Int = 0
private var insideRangeLineStrokeWidth: Float = 0.toFloat()
private var outsideRangeLineStrokeWidth: Float = 0.toFloat()
private var minAnimator: ObjectAnimator
private var maxAnimator: ObjectAnimator
internal var lastTouchedMin: Boolean = false
constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
deviceHelper = DeviceDateRange(context)
getDefaultColors()
getDefaultMeasurements()
//get attributes passed in XML
val styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.MaterialRangeSlider, 0, 0)
targetColor = styledAttrs.getColor(R.styleable.MaterialRangeSlider_insideRangeLineColor, colorControlNormal)
insideRangeColor = styledAttrs.getColor(R.styleable.MaterialRangeSlider_insideRangeLineColor, colorControlNormal)
outsideRangeColor = styledAttrs.getColor(R.styleable.MaterialRangeSlider_outsideRangeLineColor, colorControlHighlight)
min = styledAttrs.getInt(R.styleable.MaterialRangeSlider_min, min)
max = styledAttrs.getInt(R.styleable.MaterialRangeSlider_max, max)
unpressedRadius = styledAttrs.getDimension(R.styleable.MaterialRangeSlider_unpressedTargetRadius, DEFAULT_UNPRESSED_RADIUS.toFloat())
pressedRadius = styledAttrs.getDimension(R.styleable.MaterialRangeSlider_pressedTargetRadius, DEFAULT_PRESSED_RADIUS.toFloat())
insideRangeLineStrokeWidth = styledAttrs.getDimension(R.styleable.MaterialRangeSlider_insideRangeLineStrokeWidth, DEFAULT_INSIDE_RANGE_STROKE_WIDTH.toFloat())
outsideRangeLineStrokeWidth = styledAttrs.getDimension(R.styleable.MaterialRangeSlider_outsideRangeLineStrokeWidth, DEFAULT_OUTSIDE_RANGE_STROKE_WIDTH.toFloat())
styledAttrs.recycle()
minTargetRadius = unpressedRadius
maxTargetRadius = unpressedRadius
range = max - min
minAnimator = getMinTargetAnimator(true)
maxAnimator = getMaxTargetAnimator(true)
}
/**
* Get default colors from theme. Compatible with 5.0+ themes and AppCompat themes.
* Will attempt to get 5.0 colors, if not avail fallback to AppCompat, and if not avail use
* black and gray.
* These will be used if colors are not set in xml.
*/
private fun getDefaultColors() {
val typedValue = TypedValue()
val materialStyledAttrs = context.obtainStyledAttributes(typedValue.data, intArrayOf(android.R.attr.colorControlNormal, android.R.attr.colorControlHighlight))
val appcompatMaterialStyledAttrs = context.obtainStyledAttributes(typedValue.data, intArrayOf(android.support.v7.appcompat.R.attr.colorControlNormal, android.support.v7.appcompat.R.attr.colorControlHighlight))
colorControlNormal = materialStyledAttrs.getColor(0, appcompatMaterialStyledAttrs.getColor(0, android.R.color.holo_blue_dark))
colorControlHighlight = materialStyledAttrs.getColor(1, appcompatMaterialStyledAttrs.getColor(1, android.R.color.black))
targetColor = colorControlNormal
insideRangeColor = colorControlHighlight
materialStyledAttrs.recycle()
appcompatMaterialStyledAttrs.recycle()
}
/**
* Get default measurements to use for radius and stroke width.
* These are used if measurements are not set in xml.
*/
private fun getDefaultMeasurements() {
pressedRadius = Math.round(deviceHelper.dipToPixels(DEFAULT_PRESSED_RADIUS.toFloat()).toFloat()).toFloat()
unpressedRadius = Math.round(deviceHelper.dipToPixels(DEFAULT_UNPRESSED_RADIUS.toFloat()).toFloat()).toFloat()
insideRangeLineStrokeWidth = Math.round(deviceHelper.dipToPixels(DEFAULT_INSIDE_RANGE_STROKE_WIDTH.toFloat()).toFloat()).toFloat()
outsideRangeLineStrokeWidth = Math.round(deviceHelper.dipToPixels(DEFAULT_OUTSIDE_RANGE_STROKE_WIDTH.toFloat()).toFloat()).toFloat()
}
private fun getMinTargetAnimator(touching: Boolean): ObjectAnimator {
val anim = ObjectAnimator.ofFloat(this, "minTargetRadius", minTargetRadius, if (touching) pressedRadius else unpressedRadius)
anim.addUpdateListener { invalidate() }
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
anim.removeAllListeners()
super.onAnimationEnd(animation)
}
})
anim.interpolator = AccelerateInterpolator()
return anim
}
private fun getMaxTargetAnimator(touching: Boolean): ObjectAnimator {
val anim = ObjectAnimator.ofFloat(this, "maxTargetRadius", maxTargetRadius, if (touching) pressedRadius else unpressedRadius)
anim.addUpdateListener { invalidate() }
anim.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
anim.removeAllListeners()
}
})
anim.interpolator = AccelerateInterpolator()
return anim
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val widthMode = View.MeasureSpec.getMode(widthMeasureSpec)
val widthSize = View.MeasureSpec.getSize(widthMeasureSpec)
val heightMode = View.MeasureSpec.getMode(heightMeasureSpec)
val heightSize = View.MeasureSpec.getSize(heightMeasureSpec)
val desiredHeight = 96
var width = widthSize
var height = desiredHeight
if (widthMode == View.MeasureSpec.EXACTLY) {
width = widthSize
} else if (widthMode == View.MeasureSpec.AT_MOST) {
width = Math.min(width, widthSize)
}
if (heightMode == View.MeasureSpec.EXACTLY) {
height = heightSize
} else if (heightMode == View.MeasureSpec.AT_MOST) {
height = desiredHeight
}
lineLength = width - HORIZONTAL_PADDING * 2
midY = height / 2
lineStartX = HORIZONTAL_PADDING
lineEndX = lineLength + HORIZONTAL_PADDING
calculateConvertFactor()
selectedMin = min
selectedMax = max
setMeasuredDimension(width, height)
}
override fun onDraw(canvas: Canvas) {
drawEntireRangeLine(canvas)
drawSelectedRangeLine(canvas)
drawSelectedTargets(canvas)
}
private fun drawEntireRangeLine(canvas: Canvas) {
paint.color = outsideRangeColor
paint.strokeWidth = outsideRangeLineStrokeWidth
canvas.drawLine(lineStartX.toFloat(), midY.toFloat(), lineEndX.toFloat(), midY.toFloat(), paint)
}
private fun drawSelectedRangeLine(canvas: Canvas) {
paint.strokeWidth = insideRangeLineStrokeWidth
paint.color = insideRangeColor
canvas.drawLine(minPosition.toFloat(), midY.toFloat(), maxPosition.toFloat(), midY.toFloat(), paint)
}
private fun drawSelectedTargets(canvas: Canvas) {
paint.color = targetColor
canvas.drawCircle(minPosition.toFloat(), midY.toFloat(), minTargetRadius, paint)
canvas.drawCircle(maxPosition.toFloat(), midY.toFloat(), maxTargetRadius, paint)
}
//user has touched outside the target, lets jump to that position
private fun jumpToPosition(index: Int, event: MotionEvent) {
if (event.getX(index) > maxPosition && event.getX(index) <= lineEndX) {
maxPosition = event.getX(index).toInt()
invalidate()
callMaxChangedCallbacks()
} else if (event.getX(index) < minPosition && event.getX(index) >= lineStartX) {
minPosition = event.getX(index).toInt()
invalidate()
callMinChangedCallbacks()
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
if (!isEnabled)
return false
val actionIndex = event.actionIndex
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> if (lastTouchedMin) {
if (!checkTouchingMinTarget(actionIndex, event) && !checkTouchingMaxTarget(actionIndex, event)) {
jumpToPosition(actionIndex, event)
}
} else if (!checkTouchingMaxTarget(actionIndex, event) && !checkTouchingMinTarget(actionIndex, event)) {
jumpToPosition(actionIndex, event)
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
isTouchingMinTarget.remove(event.getPointerId(actionIndex))
isTouchingMaxTarget.remove(event.getPointerId(actionIndex))
if (isTouchingMinTarget.isEmpty()) {
minAnimator.cancel()
minAnimator = getMinTargetAnimator(false)
minAnimator.start()
}
if (isTouchingMaxTarget.isEmpty()) {
maxAnimator.cancel()
maxAnimator = getMaxTargetAnimator(false)
maxAnimator.start()
}
rangeSliderListener?.onEndAction(selectedMin, selectedMax)
}
MotionEvent.ACTION_MOVE -> {
for (i in 0..event.pointerCount - 1) {
if (isTouchingMinTarget.contains(event.getPointerId(i))) {
var touchX = event.getX(i).toInt()
touchX = clamp(touchX, lineStartX, lineEndX)
if (touchX >= maxPosition) {
maxPosition = touchX
callMaxChangedCallbacks()
}
minPosition = touchX
callMinChangedCallbacks()
}
if (isTouchingMaxTarget.contains(event.getPointerId(i))) {
var touchX = event.getX(i).toInt()
touchX = clamp(touchX, lineStartX, lineEndX)
if (touchX <= minPosition) {
minPosition = touchX
callMinChangedCallbacks()
}
maxPosition = touchX
callMaxChangedCallbacks()
}
}
invalidate()
}
MotionEvent.ACTION_POINTER_DOWN -> for (i in 0..event.pointerCount - 1) {
if (lastTouchedMin) {
if (!checkTouchingMinTarget(i, event) && !checkTouchingMaxTarget(i, event)) {
jumpToPosition(i, event)
}
} else if (!checkTouchingMaxTarget(i, event) && !checkTouchingMinTarget(i, event)) {
jumpToPosition(i, event)
}
}
MotionEvent.ACTION_CANCEL -> {
isTouchingMinTarget.clear()
isTouchingMaxTarget.clear()
}
}
return true
}
/**
* Checks if given index is touching the min target. If touching start animation.
*/
private fun checkTouchingMinTarget(index: Int, event: MotionEvent): Boolean {
if (isTouchingMinTarget(index, event)) {
lastTouchedMin = true
isTouchingMinTarget.add(event.getPointerId(index))
if (!minAnimator.isRunning) {
minAnimator = getMinTargetAnimator(true)
minAnimator.start()
}
return true
}
return false
}
/**
* Checks if given index is touching the max target. If touching starts animation.
*/
private fun checkTouchingMaxTarget(index: Int, event: MotionEvent): Boolean {
if (isTouchingMaxTarget(index, event)) {
lastTouchedMin = false
isTouchingMaxTarget.add(event.getPointerId(index))
if (!maxAnimator.isRunning) {
maxAnimator = getMaxTargetAnimator(true)
maxAnimator.start()
}
return true
}
return false
}
private fun callMinChangedCallbacks() {
rangeSliderListener?.onLowerChanged(selectedMin)
}
private fun callMaxChangedCallbacks() {
rangeSliderListener?.onUpperChanged(selectedMax)
}
private fun isTouchingMinTarget(pointerIndex: Int, event: MotionEvent): Boolean {
return event.getX(pointerIndex) > minPosition - DEFAULT_TOUCH_TARGET_SIZE
&& event.getX(pointerIndex) < minPosition + DEFAULT_TOUCH_TARGET_SIZE
&& event.getY(pointerIndex) > midY - DEFAULT_TOUCH_TARGET_SIZE
&& event.getY(pointerIndex) < midY + DEFAULT_TOUCH_TARGET_SIZE
}
private fun isTouchingMaxTarget(pointerIndex: Int, event: MotionEvent): Boolean {
return event.getX(pointerIndex) > maxPosition - DEFAULT_TOUCH_TARGET_SIZE
&& event.getX(pointerIndex) < maxPosition + DEFAULT_TOUCH_TARGET_SIZE
&& event.getY(pointerIndex) > midY - DEFAULT_TOUCH_TARGET_SIZE
&& event.getY(pointerIndex) < midY + DEFAULT_TOUCH_TARGET_SIZE
}
private fun calculateConvertFactor() {
convertFactor = range.toFloat() / lineLength
}
var selectedMin: Int
get() = Math.round((minPosition - lineStartX) * convertFactor + min)
private set(selectedMin) {
minPosition = Math.round((selectedMin - min) / convertFactor + lineStartX)
callMinChangedCallbacks()
}
var selectedMax: Int
get() = Math.round((maxPosition - lineStartX) * convertFactor + min)
private set(selectedMax) {
maxPosition = Math.round((selectedMax - min) / convertFactor + lineStartX)
callMaxChangedCallbacks()
}
/**
* Resets selected values to MIN and MAX.
*/
fun reset() {
minPosition = lineStartX
maxPosition = lineEndX
rangeSliderListener?.onLowerChanged(selectedMin)
rangeSliderListener?.onUpperChanged(selectedMax)
invalidate()
}
/**
* Keeps Number value inside min/max bounds by returning min or max if outside of
* bounds. Otherwise will return the value without altering.
*/
private fun <T : Number> clamp(value: T, min: T, max: T): T {
if (value.toDouble() > max.toDouble()) {
return max
} else if (value.toDouble() < min.toDouble()) {
return min
}
return value
}
fun setMinTargetRadius(minTargetRadius: Float) {
this.minTargetRadius = minTargetRadius
}
fun setMaxTargetRadius(maxTargetRadius: Float) {
this.maxTargetRadius = maxTargetRadius
}
} | apache-2.0 | 5d189072e1883d5ba9f5ed3c0f2afc2d | 39.566351 | 217 | 0.647739 | 4.784237 | false | false | false | false |
airbnb/lottie-android | sample/src/main/kotlin/com/airbnb/lottie/samples/QRScanActivity.kt | 1 | 1926 | package com.airbnb.lottie.samples
import android.content.Context
import android.content.Intent
import android.graphics.PointF
import android.os.Bundle
import android.os.Vibrator
import androidx.appcompat.app.AppCompatActivity
import com.airbnb.lottie.samples.databinding.QrscanActivityBinding
import com.airbnb.lottie.samples.model.CompositionArgs
import com.airbnb.lottie.samples.utils.vibrateCompat
import com.airbnb.lottie.samples.utils.viewBinding
import com.dlazaro66.qrcodereaderview.QRCodeReaderView
class QRScanActivity : AppCompatActivity(), QRCodeReaderView.OnQRCodeReadListener {
private val binding: QrscanActivityBinding by viewBinding()
@Suppress("DEPRECATION")
private val vibrator by lazy { getSystemService(Context.VIBRATOR_SERVICE) as Vibrator }
// Sometimes the qr code is read twice in rapid succession. This prevents it from being read
// multiple times.
private var hasReadQrCode = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.qrView.setQRDecodingEnabled(true)
binding.qrView.setAutofocusInterval(2000L)
binding.qrView.setBackCamera()
binding.qrView.setOnQRCodeReadListener(this)
binding.qrView.setOnClickListener { binding.qrView.forceAutoFocus() }
}
override fun onResume() {
super.onResume()
binding.qrView.startCamera()
hasReadQrCode = false
}
override fun onPause() {
super.onPause()
binding.qrView.stopCamera()
}
override fun onQRCodeRead(url: String, pointFS: Array<PointF>) {
if (hasReadQrCode) return
hasReadQrCode = true
vibrator.vibrateCompat(100)
finish()
startActivity(PlayerActivity.intent(this, CompositionArgs(url = url)))
}
companion object {
fun intent(context: Context) = Intent(context, QRScanActivity::class.java)
}
} | apache-2.0 | 004e85e8197047155e4671c320b84439 | 33.410714 | 96 | 0.738318 | 4.407323 | false | false | false | false |
armcha/Ribble | app/src/main/kotlin/io/armcha/ribble/presentation/utils/extensions/ViewEx.kt | 1 | 1728 | package io.armcha.ribble.presentation.utils.extensions
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.graphics.PorterDuff
import android.support.annotation.Px
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
/**
* Created by Chatikyan on 14.09.2017.
*/
fun TextView.leftIcon(drawableId: Int) {
setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(context, drawableId), null, null, null)
}
@SuppressLint("NewApi")
fun TextView.iconTint(colorId: Int) {
MorAbove {
compoundDrawableTintList = ColorStateList.valueOf(ContextCompat.getColor(context, colorId))
}
}
var View.scale: Float
get() = Math.min(scaleX, scaleY)
set(value) {
scaleY = value
scaleX = value
}
fun View.addTopMargin(@Px marginInPx: Int) {
(layoutParams as ViewGroup.MarginLayoutParams).topMargin = marginInPx
}
fun View.addBottomMargin(@Px marginInPx: Int) {
(layoutParams as ViewGroup.MarginLayoutParams).bottomMargin = marginInPx
}
fun View.show() {
visibility = View.VISIBLE
}
fun View.hide() {
visibility = View.GONE
}
fun View.invisible() {
visibility = View.INVISIBLE
}
fun View.onClick(function: () -> Unit) {
setOnClickListener {
function()
}
}
infix fun ViewGroup.inflate(layoutResId: Int): View =
LayoutInflater.from(context).inflate(layoutResId, this, false)
fun ImageView.tint(colorId: Int) {
setColorFilter(context.takeColor(colorId), PorterDuff.Mode.SRC_IN)
}
operator fun ViewGroup.get(index: Int): View = getChildAt(index) | apache-2.0 | 61d0d73604823c4a6028594b5dd2fc71 | 24.057971 | 109 | 0.744213 | 4.009281 | false | false | false | false |
android/project-replicator | generator/src/main/kotlin/com/android/gradle/replicator/generator/writer/DslWriter.kt | 1 | 3116 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.android.gradle.replicator.generator.writer
import com.android.gradle.replicator.model.PluginType
import java.io.File
abstract class DslWriter(
private val newDsl: Boolean
) {
companion object {
private const val INDENT: String = " "
}
private var file: File? = null
private var indent: Int = 0
protected val buffer = StringBuffer(50)
fun newBuildFile(folder: File) {
flush()
indent = 0
file = File(folder, "build.$extension")
}
fun newSettingsFile(folder: File) {
flush()
indent = 0
file = File(folder, "settings.$extension")
}
abstract fun pluginInBlock(plugin: PluginType, version: String? = null, apply: Boolean = true)
fun block(name: String, action: DslWriter.() -> Unit) {
writeIndent()
buffer.append("$name {\n")
indent++
action(this)
indent--
writeIndent()
buffer.append("}\n")
}
abstract fun asString(value: String): String
fun assign(propertyName: String, value: Any) {
writeIndent()
buffer.append("$propertyName = ${value}\n")
}
abstract fun compileSdk(level: Int)
abstract fun compileSdkPreview(level: String)
fun call(methodName: String, vararg values: Any) {
writeIndent()
doMethodCall(methodName = methodName, withBlock = false, values = *values)
buffer.append("\n")
}
fun callWithBlock(methodName: String, vararg values: Any, action: DslWriter.() -> Unit) {
writeIndent()
doMethodCall(methodName = methodName, withBlock = true, values = *values)
buffer.append(" {\n")
indent++
action(this)
indent--
writeIndent()
buffer.append("}\n")
}
fun gradlePluginPortal() {
writeIndent()
buffer.append("gradlePluginPortal()\n")
}
fun google() {
writeIndent()
buffer.append("google()\n")
}
fun jcenter() {
writeIndent()
buffer.append("jcenter()\n")
}
abstract fun url(uri: String)
fun flush() {
file?.let {
it.appendText(buffer.toString())
buffer.setLength(0)
}
}
protected abstract val extension: String
protected abstract fun doMethodCall(methodName: String, withBlock: Boolean, vararg values: Any)
protected fun writeIndent() {
for (i in 1..indent) {
buffer.append(INDENT)
}
}
} | apache-2.0 | 57b508162885b454010f8daf32c7388c | 24.975 | 99 | 0.620347 | 4.268493 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/markerblocks/InlineStructureHoldingMarkerBlock.kt | 1 | 1266 | package org.intellij.markdown.parser.markerblocks
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import java.util.*
abstract class InlineStructureHoldingMarkerBlock(
constraints: MarkdownConstraints,
protected val productionHolder: ProductionHolder)
: MarkerBlockImpl(constraints, productionHolder.mark()) {
override fun acceptAction(action: MarkerBlock.ClosingAction): Boolean {
if (action != MarkerBlock.ClosingAction.NOTHING) {
if (action == MarkerBlock.ClosingAction.DONE
|| action == MarkerBlock.ClosingAction.DEFAULT
&& getDefaultAction() == MarkerBlock.ClosingAction.DONE) {
for (range in getRangesContainingInlineStructure()) {
productionHolder.addProduction(
Collections.singletonList(SequentialParser.Node(range, MarkdownElementTypes.ATX_1)))
}
}
}
return super.acceptAction(action)
}
abstract fun getRangesContainingInlineStructure(): Collection<IntRange>
}
| apache-2.0 | b2af6a00a2d08d47795c181f444a034a | 39.83871 | 112 | 0.706951 | 5.728507 | false | false | false | false |
ilya-g/intellij-markdown | src/org/intellij/markdown/parser/MarkerProcessor.kt | 1 | 7802 | package org.intellij.markdown.parser
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider
import org.intellij.markdown.parser.markerblocks.impl.ParagraphMarkerBlock
import java.util.*
public abstract class MarkerProcessor<T : MarkerProcessor.StateInfo>(private val productionHolder: ProductionHolder,
protected val startConstraints: MarkdownConstraints) {
protected val NO_BLOCKS: List<MarkerBlock> = emptyList()
protected val markersStack: MutableList<MarkerBlock> = ArrayList()
protected var topBlockConstraints: MarkdownConstraints = startConstraints
protected abstract val stateInfo: T
protected abstract fun getMarkerBlockProviders(): List<MarkerBlockProvider<T>>
protected abstract fun updateStateInfo(pos: LookaheadText.Position)
protected abstract fun populateConstraintsTokens(pos: LookaheadText.Position,
constraints: MarkdownConstraints,
productionHolder: ProductionHolder)
private var nextInterestingPosForExistingMarkers: Int = -1
private val interruptsParagraph: (LookaheadText.Position, MarkdownConstraints) -> Boolean = { position, constraints ->
var result = false
for (provider in getMarkerBlockProviders()) {
if (provider.interruptsParagraph(position, constraints)) {
result = true
break
}
}
result
}
public open fun createNewMarkerBlocks(pos: LookaheadText.Position,
productionHolder: ProductionHolder): List<MarkerBlock> {
assert(MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints))
for (provider in getMarkerBlockProviders()) {
val list = provider.createMarkerBlocks(pos, productionHolder, stateInfo)
if (list.isNotEmpty()) {
return list
}
}
if (//!Character.isWhitespace(pos.char) &&
//stateInfo.paragraphBlock == null &&
pos.offsetInCurrentLine >= stateInfo.nextConstraints.getCharsEaten(pos.currentLine)
&& pos.charsToNonWhitespace() != null) {
return listOf(ParagraphMarkerBlock(stateInfo.currentConstraints, productionHolder.mark(), interruptsParagraph))
}
return emptyList()
}
public fun processPosition(pos: LookaheadText.Position): LookaheadText.Position? {
updateStateInfo(pos)
var shouldRecalcNextPos = false
if (pos.offset >= nextInterestingPosForExistingMarkers) {
processMarkers(pos)
shouldRecalcNextPos = true
}
if (MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints)
&& markersStack.lastOrNull()?.allowsSubBlocks() != false) {
val newMarkerBlocks = createNewMarkerBlocks(pos, productionHolder)
for (newMarkerBlock in newMarkerBlocks) {
addNewMarkerBlock(newMarkerBlock)
shouldRecalcNextPos = true
}
}
if (shouldRecalcNextPos) {
nextInterestingPosForExistingMarkers = calculateNextPosForExistingMarkers(pos)
}
if (pos.offsetInCurrentLine == -1
|| MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.currentConstraints)) {
val delta = stateInfo.nextConstraints.getCharsEaten(pos.currentLine) - pos.offsetInCurrentLine
if (delta > 0) {
if (pos.offsetInCurrentLine != -1 && stateInfo.nextConstraints.getIndent() <= topBlockConstraints.getIndent()) {
populateConstraintsTokens(pos, stateInfo.nextConstraints, productionHolder)
}
return pos.nextPosition(delta)
}
}
return pos.nextPosition(nextInterestingPosForExistingMarkers - pos.offset)
}
private fun calculateNextPosForExistingMarkers(pos: LookaheadText.Position): Int {
val result = markersStack.lastOrNull()?.getNextInterestingOffset(pos) ?: pos.nextLineOrEofOffset
return if (result == -1)
Integer.MAX_VALUE
else
result
}
public fun addNewMarkerBlock(newMarkerBlock: MarkerBlock) {
markersStack.add(newMarkerBlock)
relaxTopConstraints()
}
public fun flushMarkers() {
closeChildren(-1, MarkerBlock.ClosingAction.DEFAULT)
}
/**
* @return true if some markerBlock has canceled the event, false otherwise
*/
private fun processMarkers(pos: LookaheadText.Position): Boolean {
var index = markersStack.size
while (index > 0) {
index--
if (index >= markersStack.size) {
continue
}
val markerBlock = markersStack.get(index)
val processingResult = markerBlock.processToken(pos, stateInfo.currentConstraints)
if (processingResult == MarkerBlock.ProcessingResult.PASS) {
continue
}
applyProcessingResult(index, markerBlock, processingResult)
if (processingResult.eventAction == MarkerBlock.EventAction.CANCEL) {
return true
}
}
return false
}
private fun applyProcessingResult(index: Int, markerBlock: MarkerBlock, processingResult: MarkerBlock.ProcessingResult) {
closeChildren(index, processingResult.childrenAction)
// process self
if (markerBlock.acceptAction(processingResult.selfAction)) {
markersStack.removeAt(index)
relaxTopConstraints()
}
}
private fun closeChildren(index: Int, childrenAction: MarkerBlock.ClosingAction) {
if (childrenAction != MarkerBlock.ClosingAction.NOTHING) {
var latterIndex = markersStack.size - 1
while (latterIndex > index) {
val result = markersStack.get(latterIndex).acceptAction(childrenAction)
assert(result) { "If closing action is not NOTHING, marker should be gone" }
markersStack.removeAt(latterIndex)
--latterIndex
}
relaxTopConstraints()
}
}
private fun relaxTopConstraints() {
topBlockConstraints = if (markersStack.isEmpty())
startConstraints
else
markersStack.last().getBlockConstraints()
}
public open class StateInfo(public val currentConstraints: MarkdownConstraints,
public val nextConstraints: MarkdownConstraints,
private val markersStack: List<MarkerBlock>) {
public val paragraphBlock: ParagraphMarkerBlock?
get() = markersStack.firstOrNull { block -> block is ParagraphMarkerBlock } as ParagraphMarkerBlock?
public val lastBlock: MarkerBlock?
get() = markersStack.lastOrNull()
override fun equals(other: Any?): Boolean {
val otherStateInfo = other as? StateInfo ?: return false
return currentConstraints == otherStateInfo.currentConstraints &&
nextConstraints == otherStateInfo.nextConstraints &&
markersStack == otherStateInfo.markersStack
}
override fun hashCode(): Int {
var result = currentConstraints.hashCode()
result = result * 37 + nextConstraints.hashCode()
result = result * 37 + markersStack.hashCode()
return result
}
}
}
| apache-2.0 | d4bac236a3acb416856c8e53f9fced06 | 38.40404 | 128 | 0.638298 | 5.629149 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/secretsmanager/src/main/kotlin/com/kotlin/secrets/GetSecretValue.kt | 1 | 1778 | // snippet-sourcedescription:[GetSecretValue.kt demonstrates how to get the value of a secret from AWS Secrets Manager.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-keyword:[AWS Secrets Manager]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.secrets
// snippet-start:[secretsmanager.kotlin.get_secret.import]
import aws.sdk.kotlin.services.secretsmanager.SecretsManagerClient
import aws.sdk.kotlin.services.secretsmanager.model.GetSecretValueRequest
import kotlin.system.exitProcess
// snippet-end:[secretsmanager.kotlin.get_secret.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<secretName> <secretValue>
Where:
secretName - The name of the secret (for example, tutorials/MyFirstSecret).
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val secretName = args[0]
getValue(secretName)
}
// snippet-start:[secretsmanager.kotlin.get_secret.main]
suspend fun getValue(secretName: String?) {
val valueRequest = GetSecretValueRequest {
secretId = secretName
}
SecretsManagerClient { region = "us-east-1" }.use { secretsClient ->
val response = secretsClient.getSecretValue(valueRequest)
val secret = response.secretString
println("The secret value is $secret")
}
}
// snippet-end:[secretsmanager.kotlin.get_secret.main]
| apache-2.0 | d0810f2ef718be34fde90367952f7791 | 29.192982 | 120 | 0.699663 | 3.924945 | false | false | false | false |
gituser9/InvoiceManagement | app/src/main/java/com/user/invoicemanagement/other/Constant.kt | 1 | 543 | package com.user.invoicemanagement.other
import java.text.DecimalFormat
import java.text.NumberFormat
object Constant {
const val emailForReportsKey = "emailForReports"
const val settingsName = "userInfo"
val priceFormat = NumberFormat.getCurrencyInstance()
val whiteSpaceRegex: Regex = "\\s".toRegex()
init {
val decimalFormatSymbols = (priceFormat as DecimalFormat).decimalFormatSymbols
decimalFormatSymbols.currencySymbol = ""
priceFormat.decimalFormatSymbols = decimalFormatSymbols
}
} | mit | 3b9db26ebf8f0c3cfb72caaf63cb6c90 | 26.2 | 86 | 0.747698 | 5.376238 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/translations/inspections/MissingFormatInspection.kt | 1 | 1898 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.inspections
import com.demonwav.mcdev.translations.identification.TranslationInstance
import com.demonwav.mcdev.translations.identification.TranslationInstance.Companion.FormattingError
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.PsiReferenceExpression
class MissingFormatInspection : TranslationInspection() {
override fun getStaticDescription() = "Detects missing format arguments for translations"
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitReferenceExpression(expression: PsiReferenceExpression) {
visit(expression)
}
override fun visitLiteralExpression(expression: PsiLiteralExpression) {
visit(expression, ChangeTranslationQuickFix("Use a different translation"))
}
private fun visit(expression: PsiExpression, vararg quickFixes: LocalQuickFix) {
val result = TranslationInstance.find(expression)
if (result != null && result.formattingError == FormattingError.MISSING) {
holder.registerProblem(
expression,
"There are missing formatting arguments to satisfy '${result.text}'",
ProblemHighlightType.GENERIC_ERROR,
*quickFixes
)
}
}
}
}
| mit | 80c9e4f9b0a06cc34cd1968cdd42181b | 36.96 | 99 | 0.724974 | 5.615385 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/codeVision/ui/renderers/painters/CodeVisionScaledIconPainter.kt | 2 | 1194 | package com.intellij.codeInsight.codeVision.ui.renderers.painters
import com.intellij.openapi.editor.Editor
import com.intellij.util.IconUtil
import java.awt.AlphaComposite
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Point
import javax.swing.Icon
import kotlin.math.roundToInt
class CodeVisionScaledIconPainter(val yShiftIconMultiplier: Double = 0.865, val scaleMultiplier: Double = 0.8) : ICodeVisionPainter {
fun paint(editor: Editor, g: Graphics, icon: Icon, point: Point, scaleFactor: Float) {
val scaledIcon = IconUtil.scale(icon, editor.component, scaleFactor)
val g2d = g as Graphics2D
val composite = g2d.composite
g2d.composite = AlphaComposite.SrcOver
scaledIcon.paintIcon(editor.component, g, point.x, point.y - (yShiftIconMultiplier * scaledIcon.iconHeight).toInt())
g2d.composite = composite
}
fun scaleFactor(iconValue: Int, neededValue: Int): Float = (neededValue * scaleMultiplier).toFloat() / iconValue
fun width(icon: Icon, scaleFactor: Float): Int = (icon.iconWidth * scaleFactor).toDouble().roundToInt()
fun height(icon: Icon, scaleFactor: Float): Int = (icon.iconHeight * scaleFactor).toDouble().roundToInt()
} | apache-2.0 | 434ca896fe29617eef8f4abe3cd4bafd | 43.259259 | 133 | 0.768844 | 3.864078 | false | false | false | false |
google/intellij-community | json/src/com/intellij/jsonpath/ui/JsonPathEvaluateView.kt | 1 | 15629 | // 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.jsonpath.ui
import com.intellij.codeInsight.actions.ReformatCodeProcessor
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.find.FindBundle
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.json.JsonBundle
import com.intellij.json.JsonFileType
import com.intellij.json.psi.JsonFile
import com.intellij.jsonpath.JsonPathFileType
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_EXPRESSION_KEY
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_HISTORY
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_RESULT_KEY
import com.intellij.jsonpath.ui.JsonPathEvaluateManager.Companion.JSON_PATH_EVALUATE_SOURCE_KEY
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionButtonLook
import com.intellij.openapi.actionSystem.ex.ComboBoxAction
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.EditorKind
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.SimpleToolWindowPanel
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.PopupChooserBuilder
import com.intellij.openapi.util.NlsActions
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.EditorTextField
import com.intellij.ui.JBColor
import com.intellij.ui.components.*
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.popup.PopupState
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.jayway.jsonpath.Configuration
import com.jayway.jsonpath.Option
import com.jayway.jsonpath.spi.json.JacksonJsonProvider
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider
import java.awt.BorderLayout
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.event.KeyEvent
import java.util.*
import java.util.function.Supplier
import javax.swing.*
import kotlin.collections.ArrayDeque
internal abstract class JsonPathEvaluateView(protected val project: Project) : SimpleToolWindowPanel(true, true), Disposable {
companion object {
init {
Configuration.setDefaults(object : Configuration.Defaults {
private val jsonProvider = JacksonJsonProvider()
private val mappingProvider = JacksonMappingProvider()
override fun jsonProvider() = jsonProvider
override fun mappingProvider() = mappingProvider
override fun options() = EnumSet.noneOf(Option::class.java)
})
}
}
protected val searchTextField: EditorTextField = object : EditorTextField(project, JsonPathFileType.INSTANCE) {
override fun processKeyBinding(ks: KeyStroke?, e: KeyEvent?, condition: Int, pressed: Boolean): Boolean {
if (e?.keyCode == KeyEvent.VK_ENTER && pressed) {
evaluate()
return true
}
return super.processKeyBinding(ks, e, condition, pressed)
}
override fun createEditor(): EditorEx {
val editor = super.createEditor()
editor.setBorder(JBUI.Borders.empty())
editor.component.border = JBUI.Borders.empty(4, 0, 3, 6)
editor.component.isOpaque = false
editor.backgroundColor = UIUtil.getTextFieldBackground()
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.document)
if (psiFile != null) {
psiFile.putUserData(JSON_PATH_EVALUATE_EXPRESSION_KEY, true)
psiFile.putUserData(JSON_PATH_EVALUATE_SOURCE_KEY, Supplier(::getJsonFile))
}
return editor
}
}
protected val searchWrapper: JPanel = object : NonOpaquePanel(BorderLayout()) {
override fun updateUI() {
super.updateUI()
this.background = UIUtil.getTextFieldBackground()
}
}
val searchComponent: JComponent
get() = searchTextField
protected val resultWrapper: JBPanelWithEmptyText = JBPanelWithEmptyText(BorderLayout())
private val resultLabel = JBLabel(JsonBundle.message("jsonpath.evaluate.result"))
private val resultEditor: Editor = initJsonEditor("result.json", true, EditorKind.PREVIEW)
private val errorOutputArea: JBTextArea = JBTextArea()
private val errorOutputContainer: JScrollPane = JBScrollPane(errorOutputArea)
private val evalOptions: MutableSet<Option> = mutableSetOf()
init {
resultEditor.putUserData(JSON_PATH_EVALUATE_RESULT_KEY, true)
resultEditor.setBorder(JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0))
resultLabel.border = JBUI.Borders.empty(3, 6)
resultWrapper.emptyText.text = JsonBundle.message("jsonpath.evaluate.no.result")
errorOutputContainer.border = JBUI.Borders.customLine(JBColor.border(), 1, 0, 0, 0)
val historyButton = SearchHistoryButton(ShowHistoryAction(), false)
val historyButtonWrapper = NonOpaquePanel(BorderLayout())
historyButtonWrapper.border = JBUI.Borders.empty(3, 6, 3, 6)
historyButtonWrapper.add(historyButton, BorderLayout.NORTH)
searchTextField.setFontInheritedFromLAF(false) // use font as in regular editor
searchWrapper.add(historyButtonWrapper, BorderLayout.WEST)
searchWrapper.add(searchTextField, BorderLayout.CENTER)
searchWrapper.border = JBUI.Borders.customLine(JBColor.border(), 0, 0, 1, 0)
searchWrapper.isOpaque = true
errorOutputArea.isEditable = false
errorOutputArea.wrapStyleWord = true
errorOutputArea.lineWrap = true
errorOutputArea.border = JBUI.Borders.empty(10)
setExpression("$..*")
}
protected fun initToolbar() {
val actionGroup = DefaultActionGroup()
fillToolbarOptions(actionGroup)
val toolbar = ActionManager.getInstance().createActionToolbar("JsonPathEvaluateToolbar", actionGroup, true)
toolbar.targetComponent = this
setToolbar(toolbar.component)
}
protected abstract fun getJsonFile(): JsonFile?
protected fun resetExpressionHighlighting() {
val jsonPathFile = PsiDocumentManager.getInstance(project).getPsiFile(searchTextField.document)
if (jsonPathFile != null) {
// reset inspections in expression
DaemonCodeAnalyzer.getInstance(project).restart(jsonPathFile)
}
}
private fun fillToolbarOptions(group: DefaultActionGroup) {
val outputComboBox = object : ComboBoxAction() {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun createPopupActionGroup(button: JComponent?): DefaultActionGroup {
val outputItems = DefaultActionGroup()
outputItems.add(OutputOptionAction(false, JsonBundle.message("jsonpath.evaluate.output.values")))
outputItems.add(OutputOptionAction(true, JsonBundle.message("jsonpath.evaluate.output.paths")))
return outputItems
}
override fun update(e: AnActionEvent) {
val presentation = e.presentation
if (e.project == null) return
presentation.text = if (evalOptions.contains(Option.AS_PATH_LIST)) {
JsonBundle.message("jsonpath.evaluate.output.paths")
}
else {
JsonBundle.message("jsonpath.evaluate.output.values")
}
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
val panel = JPanel(GridBagLayout())
panel.add(JLabel(JsonBundle.message("jsonpath.evaluate.output.option")),
GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, JBUI.insetsLeft(5), 0, 0))
panel.add(super.createCustomComponent(presentation, place),
GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, JBInsets.emptyInsets(), 0, 0))
return panel
}
}
group.add(outputComboBox)
group.add(DefaultActionGroup(JsonBundle.message("jsonpath.evaluate.options"), true).apply {
templatePresentation.icon = AllIcons.General.Settings
add(OptionToggleAction(Option.SUPPRESS_EXCEPTIONS, JsonBundle.message("jsonpath.evaluate.suppress.exceptions")))
add(OptionToggleAction(Option.ALWAYS_RETURN_LIST, JsonBundle.message("jsonpath.evaluate.return.list")))
add(OptionToggleAction(Option.DEFAULT_PATH_LEAF_TO_NULL, JsonBundle.message("jsonpath.evaluate.nullize.missing.leaf")))
add(OptionToggleAction(Option.REQUIRE_PROPERTIES, JsonBundle.message("jsonpath.evaluate.require.all.properties")))
})
}
protected fun initJsonEditor(fileName: String, isViewer: Boolean, kind: EditorKind): Editor {
val sourceVirtualFile = LightVirtualFile(fileName, JsonFileType.INSTANCE, "") // require strict JSON with quotes
val sourceFile = PsiManager.getInstance(project).findFile(sourceVirtualFile)!!
val document = PsiDocumentManager.getInstance(project).getDocument(sourceFile)!!
val editor = EditorFactory.getInstance().createEditor(document, project, sourceVirtualFile, isViewer, kind)
editor.settings.isLineNumbersShown = false
return editor
}
fun setExpression(jsonPathExpr: String) {
searchTextField.text = jsonPathExpr
}
private fun setResult(result: String) {
WriteAction.run<Throwable> {
resultEditor.document.setText(result)
PsiDocumentManager.getInstance(project).commitDocument(resultEditor.document)
val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(resultEditor.document)!!
ReformatCodeProcessor(psiFile, false).run()
}
if (!resultWrapper.components.contains(resultEditor.component)) {
resultWrapper.removeAll()
resultWrapper.add(resultLabel, BorderLayout.NORTH)
resultWrapper.add(resultEditor.component, BorderLayout.CENTER)
resultWrapper.revalidate()
resultWrapper.repaint()
}
resultEditor.caretModel.moveToOffset(0)
}
private fun setError(error: String) {
errorOutputArea.text = error
if (!resultWrapper.components.contains(errorOutputArea)) {
resultWrapper.removeAll()
resultWrapper.add(resultLabel, BorderLayout.NORTH)
resultWrapper.add(errorOutputContainer, BorderLayout.CENTER)
resultWrapper.revalidate()
resultWrapper.repaint()
}
}
private fun evaluate() {
val evaluator = JsonPathEvaluator(getJsonFile(), searchTextField.text, evalOptions)
val result = evaluator.evaluate()
when (result) {
is IncorrectExpression -> setError(result.message)
is IncorrectDocument -> setError(result.message)
is ResultNotFound -> setError(result.message)
is ResultString -> setResult(result.value)
else -> {}
}
if (result != null && result !is IncorrectExpression) {
addJSONPathToHistory(searchTextField.text.trim())
}
}
override fun dispose() {
EditorFactory.getInstance().releaseEditor(resultEditor)
}
private inner class OutputOptionAction(private val enablePaths: Boolean, @NlsActions.ActionText message: String)
: DumbAwareAction(message) {
override fun actionPerformed(e: AnActionEvent) {
if (enablePaths) {
evalOptions.add(Option.AS_PATH_LIST)
}
else {
evalOptions.remove(Option.AS_PATH_LIST)
}
evaluate()
}
}
private inner class OptionToggleAction(private val option: Option, @NlsActions.ActionText message: String) : ToggleAction(message) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun isSelected(e: AnActionEvent): Boolean {
return evalOptions.contains(option)
}
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (state) {
evalOptions.add(option)
}
else {
evalOptions.remove(option)
}
evaluate()
}
}
private class SearchHistoryButton constructor(action: AnAction, focusable: Boolean) :
ActionButton(action, action.templatePresentation.clone(), ActionPlaces.UNKNOWN, ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE) {
override fun getDataContext(): DataContext {
return DataManager.getInstance().getDataContext(this)
}
override fun getPopState(): Int {
return if (isSelected) SELECTED else super.getPopState()
}
override fun getIcon(): Icon {
if (isEnabled && isSelected) {
val selectedIcon = myPresentation.selectedIcon
if (selectedIcon != null) return selectedIcon
}
return super.getIcon()
}
init {
setLook(ActionButtonLook.INPLACE_LOOK)
isFocusable = focusable
updateIcon()
}
}
private fun getExpressionHistory(): List<String> {
return PropertiesComponent.getInstance().getValue(JSON_PATH_EVALUATE_HISTORY)?.split('\n') ?: emptyList()
}
private fun setExpressionHistory(history: Collection<String>) {
PropertiesComponent.getInstance().setValue(JSON_PATH_EVALUATE_HISTORY, history.joinToString("\n"))
}
private fun addJSONPathToHistory(path: String) {
if (path.isBlank()) return
val history = ArrayDeque(getExpressionHistory())
if (!history.contains(path)) {
history.addFirst(path)
if (history.size > 10) {
history.removeLast()
}
setExpressionHistory(history)
}
else {
if (history.firstOrNull() == path) {
return
}
history.remove(path)
history.addFirst(path)
setExpressionHistory(history)
}
}
private inner class ShowHistoryAction : DumbAwareAction(FindBundle.message("find.search.history"), null,
AllIcons.Actions.SearchWithHistory) {
private val popupState: PopupState<JBPopup?> = PopupState.forPopup()
override fun actionPerformed(e: AnActionEvent) {
if (popupState.isRecentlyHidden) return
val historyList = JBList(getExpressionHistory())
showCompletionPopup(searchWrapper, historyList, searchTextField, popupState)
}
init {
registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts("ShowSearchHistory"), searchTextField)
}
private fun showCompletionPopup(toolbarComponent: JComponent?,
list: JList<String>,
textField: EditorTextField,
popupState: PopupState<JBPopup?>) {
val builder: PopupChooserBuilder<*> = JBPopupFactory.getInstance().createListPopupBuilder(list)
val popup = builder
.setMovable(false)
.setResizable(false)
.setRequestFocus(true)
.setItemChoosenCallback(Runnable {
val selectedValue = list.selectedValue
if (selectedValue != null) {
textField.text = selectedValue
IdeFocusManager.getGlobalInstance().requestFocus(textField, false)
}
})
.createPopup()
popupState.prepareToShow(popup)
if (toolbarComponent != null) {
popup.showUnderneathOf(toolbarComponent)
}
else {
popup.showUnderneathOf(textField)
}
}
}
} | apache-2.0 | 799d9dbe658746d382f98dc936164802 | 36.936893 | 139 | 0.730437 | 4.829728 | false | false | false | false |
google/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/impl/ResizeHandlebarUpdater.kt | 5 | 3455 | package org.jetbrains.plugins.notebooks.visualization.outputs.impl
import com.intellij.ide.IdeEventQueue
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.ui.IdeBorderFactory
import org.jetbrains.plugins.notebooks.visualization.notebookAppearance
import org.jetbrains.plugins.notebooks.visualization.outputs.impl.ResizeHandlebarUpdater.Companion.ensureInstalled
import java.awt.*
import java.awt.event.MouseEvent
import java.lang.ref.WeakReference
import javax.swing.border.Border
/**
* A global event listener that draws a resizing handlebar below hovered cell outputs. Since cell outputs may contain non-Swing
* components (like JCef), the usual MouseListener from Swing can't be used.
*
* Call [ensureInstalled] to initialize it.
*/
@Service
class ResizeHandlebarUpdater private constructor() : IdeEventQueue.EventDispatcher, Disposable {
companion object {
@JvmStatic
fun ensureInstalled() {
ApplicationManager.getApplication().assertIsDispatchThread()
service<ResizeHandlebarUpdater>()
}
private val borderInsets = Insets(0, 0, 10, 0)
@JvmField
internal val invisibleResizeBorder = IdeBorderFactory.createEmptyBorder(borderInsets)
}
private val visibleResizeBorder = VisibleResizeBorder(this)
private var currentCollapsingComponent = WeakReference<CollapsingComponent?>(null)
init {
IdeEventQueue.getInstance().addDispatcher(this, this)
}
override fun dispatch(e: AWTEvent): Boolean {
when (e.id) {
MouseEvent.MOUSE_MOVED, MouseEvent.MOUSE_WHEEL, MouseEvent.MOUSE_DRAGGED -> Unit
else -> return false
}
if (e !is MouseEvent) return false
setCurrentCollapsingComponent(getCollapsingComponentDepthFirst(e.component, e.x, e.y)?.takeIf { it.resizable })
return false
}
override fun dispose(): Unit = Unit
private fun getCollapsingComponentDepthFirst(component: Component, x: Int, y: Int): CollapsingComponent? =
when {
component !is Container || !component.isVisible || !component.contains(x, y) -> null
component is CollapsingComponent -> component
else ->
component.components.firstNotNullOfOrNull { child ->
val loc = child.location
getCollapsingComponentDepthFirst(child, x - loc.x, y - loc.y)
}
}
private fun setCurrentCollapsingComponent(new: CollapsingComponent?) {
val old = currentCollapsingComponent.get()
if (old != new) {
old?.border = invisibleResizeBorder
new?.border = visibleResizeBorder
currentCollapsingComponent = WeakReference(new)
}
}
private class VisibleResizeBorder(private val owner: ResizeHandlebarUpdater) : Border {
override fun paintBorder(c: Component, g: Graphics, x: Int, y: Int, width: Int, height: Int) {
g as Graphics2D
g.color =
owner.currentCollapsingComponent.get()?.editor?.run { notebookAppearance.getCodeCellBackground(colorsScheme) }
?: return
g.stroke = BasicStroke(1.0f)
val insets = getBorderInsets(c)
assert(insets.top + insets.left + insets.right == 0)
val yDraw = y + height - insets.bottom / 2
g.drawLine(x, yDraw, x + width, yDraw)
}
override fun getBorderInsets(c: Component): Insets = borderInsets
override fun isBorderOpaque(): Boolean = false
}
}
| apache-2.0 | f2a146b0ab0d5a41f635da7a96897e99 | 33.55 | 127 | 0.734877 | 4.487013 | false | false | false | false |
apollographql/apollo-android | apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/exception/Exceptions.kt | 1 | 4986 | // This is in the `exception` package and not `api.exception` to keep some compatibility with 2.x
package com.apollographql.apollo3.exception
import com.apollographql.apollo3.api.http.HttpHeader
import okio.BufferedSource
/**
* The base class for all exceptions
*
* This inherits from [RuntimeException]. Java callers will have to explicitly catch all [ApolloException]s.
*/
open class ApolloException(message: String? = null, cause: Throwable? = null) : RuntimeException(message, cause)
/**
* A network error happened: socket closed, DNS issue, TLS problem, etc...
*
* @param message a message indicating what the error was.
* @param platformCause the underlying cause. Might be null. When not null, it can be cast to:
* - a [Throwable] on JVM platforms.
* - a [NSError] on Darwin platforms.
* to get more details about what went wrong.
*/
class ApolloNetworkException(
message: String? = null,
val platformCause: Any? = null,
) : ApolloException(message = message, cause = platformCause as? Throwable)
/**
* A WebSocket connection could not be established: e.g., expired token
*/
class ApolloWebSocketClosedException(
val code: Int,
val reason: String? = null,
cause: Throwable? = null,
) : ApolloException(message = "WebSocket Closed code='$code' reason='$reason'", cause = cause)
/**
* The response was received but the response code was not 200
*
* @param statusCode: the HTTP status code
* @param headers: the HTTP headers
* @param body: the HTTP error body. By default, [body] is always null. You can opt-in [exposeHttpErrorBody] in [HttpNetworkTransport]
* if you need it. If you're doing this, you **must** call [BufferedSource.close] on [body] to avoid sockets and other resources leaking.
*/
class ApolloHttpException(
val statusCode: Int,
val headers: List<HttpHeader>,
val body: BufferedSource?,
message: String,
cause: Throwable? = null,
) : ApolloException(message = message, cause = cause)
/**
* Thrown when the data being parsed is not encoded as valid JSON.
*/
class JsonEncodingException(message: String) : ApolloException(message)
/**
* Thrown when the data in a JSON document doesn't match the data expected by the caller.
*
* For example, suppose the application expects a boolean but the JSON document contains a string. When the call to
* [JsonReader.nextBoolean] is made, a `JsonDataException` is thrown.
*
* Exceptions of this type should be fixed by either changing the application code to accept the unexpected JSON, or by changing the JSON
* to conform to the application's expectations.
*
* This exception may also be triggered if a document's nesting exceeds 31 levels. This depth is sufficient for all practical applications,
* but shallow enough to avoid uglier failures like [StackOverflowError].
*/
class JsonDataException(message: String) : ApolloException(message)
/**
* The response could not be parsed either because of another issue than [JsonDataException] or [JsonEncodingException]
*/
class ApolloParseException(message: String? = null, cause: Throwable? = null) : ApolloException(message = message, cause = cause)
/**
* An object/field was missing in the cache
* If [fieldName] is null, it means a reference to an object could not be resolved
*/
class CacheMissException(val key: String, val fieldName: String? = null) : ApolloException(message = message(key, fieldName)) {
private companion object {
private fun message(key: String?, fieldName: String?): String {
return if (fieldName == null) {
"Object '$key' not found"
} else {
"Object '$key' has no field named '$fieldName'"
}
}
}
}
/**
* A HTTP cache miss happened
*/
class HttpCacheMissException(message: String, cause: Exception? = null) : ApolloException(message = message, cause = cause)
/**
* Multiple exceptions happened, for an exemple with a [CacheFirst] fetch policy
*/
class ApolloCompositeException(first: Throwable?, second: Throwable?) : ApolloException(message = "multiple exceptions happened", second) {
val first = (first as? ApolloException) ?: throw RuntimeException("unexpected first exception", first)
val second = (second as? ApolloException) ?: throw RuntimeException("unexpected second exception", second)
}
class AutoPersistedQueriesNotSupported : ApolloException(message = "The server does not support auto persisted queries")
class MissingValueException : ApolloException(message = "The optional doesn't have a value")
/**
* Something went wrong but it's not sure exactly what
*/
@Deprecated("This is only used in the JVM runtime and is scheduled for removal")
class ApolloGenericException(message: String? = null, cause: Throwable? = null) : ApolloException(message = message, cause = cause)
@Deprecated("This is only used in the JVM runtime and is scheduled for removal")
class ApolloCanceledException(message: String? = null, cause: Throwable? = null) : ApolloException(message = message, cause = cause)
| mit | f8bf8a6cfe88d9a2ef4a5f26b5d8a02f | 40.55 | 139 | 0.737465 | 4.254266 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/external/ScionBrowser.kt | 1 | 1623 | package org.jetbrains.haskell.external
import java.io.OutputStreamWriter
import java.io.InputStream
import java.io.InputStreamReader
import java.io.Writer
import java.io.Reader
import java.util.zip.Inflater
/**
* Created by atsky on 5/23/14.
*/
class ScionBrowser
fun main(args : Array<String>) {
val path = "/home/atsky/.cabal/bin/scion-browser"
val processBuilder: ProcessBuilder = ProcessBuilder(path)
val process = processBuilder.start()
val streamWriter = OutputStreamWriter(process.outputStream!!)
val input: InputStream = process.inputStream!!
val error = InputStreamReader(process.errorStream!!)
System.out.println(run("{ \"command\" : \"load-local-db\", \"filepath\" : \"local.db\", \"rebuild\" : true }\n", streamWriter, input, error))
val result = run("{ \"command\" : \"get-declarations\", \"module\" : \"Data.Maybe\", \"db\" : \"_all\" }\n", streamWriter, input, error)
System.out.println(result)
}
fun run(toRun : String, streamWriter : Writer, input: InputStream, error : Reader) : String {
streamWriter.write(toRun)
streamWriter.flush()
while (input.available() == 0) {
if (error.ready()) {
val ch = error.read()
if (ch != -1) {
System.out.print(ch.toChar())
}
}
}
System.out.println()
val len = input.available()
val buff = ByteArray(len)
input.read(buff)
val inflater = Inflater()
inflater.setInput(buff)
val outCompressed = ByteArray(1024 * 1024)
val size = inflater.inflate(outCompressed)
return String(outCompressed, 0, size)
} | apache-2.0 | e1f867f7b51f72c5d97e3be2de3ed720 | 26.066667 | 145 | 0.648799 | 3.882775 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepic/droid/core/ShareHelperImpl.kt | 1 | 4177 | package org.stepic.droid.core
import android.content.Context
import android.content.Intent
import android.net.Uri
import org.stepic.droid.R
import org.stepic.droid.configuration.EndpointResolver
import org.stepic.droid.di.AppSingleton
import org.stepic.droid.model.CertificateListItem
import org.stepic.droid.util.StringUtil
import org.stepic.droid.util.resolvers.text.TextResolver
import org.stepik.android.model.*
import org.stepik.android.model.Unit
import org.stepik.android.model.user.User
import javax.inject.Inject
@AppSingleton
class ShareHelperImpl
@Inject
constructor(
private val endpointResolver: EndpointResolver,
private val context: Context,
private val textResolver: TextResolver
) : ShareHelper {
private val textPlainType = "text/plain"
override fun getIntentForCourseSharing(course: Course): Intent {
val stringBuilder = StringBuilder()
with(stringBuilder) {
if (course.title != null) {
append(course.title)
append("\r\n")
append("\r\n")
}
if (course.summary?.isNotEmpty() == true) {
append(textResolver.fromHtml(course.summary).toString())
append("\r\n")
append("\r\n")
}
}
val uriForSharing = Uri.parse(StringUtil.getUriForCourse(endpointResolver.getBaseUrl(), course.slug)).toString()
val textForSharing = textResolver.fromHtml(stringBuilder.toString()).toString() + "\r\n\r\n" + uriForSharing
return getShareIntentBase(textForSharing)
}
override fun getIntentForShareCertificate(certificateListItem: CertificateListItem.Data): Intent =
getShareIntentBase(certificateListItem.certificate.url ?: " ")
override fun getIntentForStepSharing(step: Step, lesson: Lesson, unit: Unit?): Intent {
val textForSharing = Uri.parse(StringUtil.getUriForStep(endpointResolver.getBaseUrl(), lesson, unit, step)).toString()
return getShareIntentBase(textForSharing)
}
override fun getIntentForSectionSharing(section: Section): Intent {
val textForSharing = Uri.parse(StringUtil.getAbsoluteUriForSection(endpointResolver, section)).toString()
return getShareIntentBase(textForSharing)
}
override fun getIntentForUserSharing(user: User): Intent {
val stringBuilder = StringBuilder()
with(stringBuilder) {
if (!user.fullName.isNullOrBlank()) {
append(user.fullName)
append("\r\n")
append("\r\n")
}
val uriForSharing = Uri.parse(StringUtil.getUriForProfile(endpointResolver.getBaseUrl(), user.id)).toString()
append(uriForSharing)
}
val textForSharing = stringBuilder.toString()
return getShareIntentBase(textForSharing)
}
override fun getIntentForCourseResultSharing(course: Course, message: String): Intent {
val stringBuilder = StringBuilder()
with(stringBuilder) {
append(message)
append("\r\n")
append("\r\n")
val uriForSharing = Uri.parse(StringUtil.getUriForCourse(endpointResolver.getBaseUrl(), course.slug)).toString()
append(uriForSharing)
}
val textForSharing = stringBuilder.toString()
return getShareIntentBase(textForSharing)
}
override fun getIntentForCourseResultCertificateSharing(certificate: Certificate, message: String): Intent {
val stringBuilder = StringBuilder()
with(stringBuilder) {
append(message)
append("\r\n")
append("\r\n")
append(certificate.url ?: "")
}
val textForSharing = stringBuilder.toString()
return getShareIntentBase(textForSharing)
}
private fun getShareIntentBase(textForSharing: String): Intent {
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.putExtra(Intent.EXTRA_TEXT, textForSharing)
shareIntent.type = textPlainType
return Intent.createChooser(shareIntent, context.getString(R.string.share_title))
}
}
| apache-2.0 | 4c6fafc01f9da36eb0b860cc38eac393 | 36.294643 | 126 | 0.672732 | 4.682735 | false | false | false | false |
customerly/Customerly-Android-SDK | customerly-android-sdk/src/main/java/io/customerly/activity/chat/ClyChatActivity.kt | 1 | 33506 | package io.customerly.activity.chat
/*
* Copyright (C) 2017 Customerly
*
* 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.
*/
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import io.customerly.Customerly
import io.customerly.R
import io.customerly.activity.CLYINPUT_EXTRA_MUST_SHOW_BACK
import io.customerly.activity.ClyIInputActivity
import io.customerly.alert.showClyAlertMessage
import io.customerly.api.*
import io.customerly.entity.ClyAdminFull
import io.customerly.entity.chat.*
import io.customerly.entity.iamLead
import io.customerly.entity.ping.ClyNextOfficeHours
import io.customerly.sxdependencies.*
import io.customerly.sxdependencies.annotations.SXColorInt
import io.customerly.sxdependencies.annotations.SXStringRes
import io.customerly.sxdependencies.annotations.SXUiThread
import io.customerly.utils.download.imagehandler.ClyImageRequest
import io.customerly.utils.download.startFileDownload
import io.customerly.utils.getContrastBW
import io.customerly.utils.ggkext.*
import io.customerly.utils.network.ClySntpClient
import io.customerly.utils.ui.RvProgressiveScrollListener
import kotlinx.android.synthetic.main.io_customerly__activity_chat.*
import java.lang.ref.WeakReference
import java.util.*
import kotlin.math.min
/**
* Created by Gianni on 03/09/16.
* Project: Customerly Android SDK
*/
private const val EXTRA_CONVERSATION_ID = "EXTRA_CONVERSATION_ID"
private const val EXTRA_MESSAGE_CONTENT = "EXTRA_MESSAGE_CONTENT"
private const val EXTRA_MESSAGE_ATTACHMENTS = "EXTRA_MESSAGE_ATTACHMENTS"
private const val MESSAGES_PER_PAGE = 20
internal const val TYPING_NO_ONE = 0L
private const val PERMISSION_REQUEST__WRITE_EXTERNAL_STORAGE = 4321
internal fun Activity.startClyChatActivity(conversationId: Long, messageContent:String? = null, attachments: ArrayList<ClyAttachment>? = null, mustShowBack: Boolean = true, requestCode: Int = -1) {
val intent = Intent(this, ClyChatActivity::class.java)
if (conversationId != CONVERSATIONID_UNKNOWN_FOR_MESSAGE) {
intent.putExtra(EXTRA_CONVERSATION_ID, conversationId)
}
if (messageContent != null) {
intent.putExtra(EXTRA_MESSAGE_CONTENT, messageContent)
}
if (attachments != null && attachments.isNotEmpty()) {
intent.putParcelableArrayListExtra(EXTRA_MESSAGE_ATTACHMENTS, attachments)
}
if (requestCode == -1) {
if (this is ClyChatActivity) {
//If i am starting a IAct_Chat Activity from a IAct_Chat activity i'll show the back button only if it is visible in the current IAct_Chat activity.
//Then i finish the current activity to avoid long stack of IAct_Chat activities
this.startActivity(intent.putExtra(CLYINPUT_EXTRA_MUST_SHOW_BACK, this.mustShowBack))
this.finish()
} else {
this.startActivity(intent.putExtra(CLYINPUT_EXTRA_MUST_SHOW_BACK, mustShowBack))
}
} else {
this.startActivityForResult(intent.putExtra(CLYINPUT_EXTRA_MUST_SHOW_BACK, mustShowBack), requestCode)
}
}
internal class ClyChatActivity : ClyIInputActivity() {
private var conversationId: Long = CONVERSATIONID_UNKNOWN_FOR_MESSAGE
internal var typingAccountId = TYPING_NO_ONE
internal var typingAccountName: String? = null
internal var chatList = ArrayList<ClyMessage>(0)
internal var conversationFullAdmin: ClyAdminFull? = null
private var conversationFullAdminFromMessagesAccountId: Long? = null
private val onBottomReachedListener = object : Function1<RvProgressiveScrollListener,Unit> {
private val wActivity : WeakReference<ClyChatActivity> = [email protected]()
override fun invoke(scrollListener: RvProgressiveScrollListener) {
this.wActivity.get()?.let { activity ->
Customerly.checkConfigured {
activity.conversationId.takeIf { it != CONVERSATIONID_UNKNOWN_FOR_MESSAGE }?.also { conversationId ->
ClyApiRequest(
context = this.wActivity.get(),
endpoint = ENDPOINT_MESSAGE_RETRIEVE,
requireToken = true,
trials = 2,
onPreExecute = { this.wActivity.get()?.io_customerly__progress_view?.visibility = View.VISIBLE },
jsonObjectConverter = { it.parseMessagesList() },
callback = { response ->
when (response) {
is ClyApiResponse.Success -> {
this.wActivity.get()?.let { activity ->
response.result.sortByDescending { it.id }
val newChatList = ArrayList(activity.chatList)
val previousSize = newChatList.size
val scrollToLastUnread = response.result
.asSequence()
.filterNot { newChatList.contains(it) }//Avoid duplicates
.mapIndexedNotNull { index, clyMessage ->
newChatList.add(clyMessage)//Add new not duplicate message to list
if (clyMessage.isNotSeen) {//If not seen map it to his index, discard it otherwise
index
} else {
null
}
}
.min() ?: -1
val addedMessagesCount = newChatList.size - previousSize
activity.io_customerly__progress_view.visibility = View.GONE
if (addedMessagesCount > 0) {
activity.chatList = newChatList
(activity.io_customerly__recycler_view.layoutManager as? SXLinearLayoutManager)?.let { llm ->
if (llm.findFirstCompletelyVisibleItemPosition() == 0) {
llm.scrollToPosition(0)
} else if (previousSize == 0 && scrollToLastUnread != -1) {
llm.scrollToPosition(scrollToLastUnread)
}
}
(activity.io_customerly__recycler_view.adapter as? ClyChatAdapter)?.let { adapter ->
if (previousSize != 0) {
adapter.notifyItemChanged(adapter.listIndex2position(previousSize - 1))
}
adapter.notifyItemRangeInserted(adapter.listIndex2position(previousSize), adapter.listIndex2position(addedMessagesCount))
}
activity.updateAccountInfos()
}
response.result.firstOrNull()?.takeIf { it.isNotSeen }?.let { activity.sendSeen(messageId = it.id) }
if (previousSize == 0) {
activity.io_customerly__recycler_view.layoutManager?.scrollToPosition(0)
}
}
if (response.result.size >= MESSAGES_PER_PAGE) {
scrollListener.onFinishedUpdating()
}
}
is ClyApiResponse.Failure -> {
this.wActivity.get()?.let {
it.io_customerly__progress_view?.visibility = View.GONE
Toast.makeText(it.applicationContext, R.string.io_customerly__connection_error, Toast.LENGTH_SHORT).show()
}
}
}
})
.p(key = "conversation_id", value = conversationId)
.p(key = "per_page", value = MESSAGES_PER_PAGE)
.p(key = "messages_before_id", value = activity.chatList.mapNotNull { msg -> if(msg.id > 0) msg.id else null }.min() ?: Long.MAX_VALUE)
.p(key = "lead_hash", value = Customerly.currentUser.leadHash)
.start()
}
}
}
}
}
private var progressiveScrollListener: RvProgressiveScrollListener? = null
private var permissionRequestPendingFileName: String? = null
private var permissionRequestPendingPath: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (this.onCreateLayout(R.layout.io_customerly__activity_chat)) {
this.io_customerly__actionlayout.setBackgroundColor(Customerly.lastPing.widgetColor)
this.io_customerly__progress_view.indeterminateDrawable.setColorFilterMultiply(color = Customerly.lastPing.widgetColor)
this.io_customerly__recycler_view.also { recyclerView ->
recyclerView.layoutManager = SXLinearLayoutManager(this.applicationContext).also { llm ->
llm.reverseLayout = true
RvProgressiveScrollListener(llm = llm, onBottomReached = this.onBottomReachedListener).also {
this.progressiveScrollListener = it
recyclerView.addOnScrollListener(it)
}
}
recyclerView.itemAnimator = SXDefaultItemAnimator()
recyclerView.setHasFixedSize(true)
recyclerView.adapter = ClyChatAdapter(chatActivity = this)
}
val conversationId: Long = this.intent.getLongExtra(EXTRA_CONVERSATION_ID, CONVERSATIONID_UNKNOWN_FOR_MESSAGE)
if(conversationId != CONVERSATIONID_UNKNOWN_FOR_MESSAGE) {
this.onConversationId(conversationId = conversationId)
this.updateAccountInfos(fallbackUserOnLastActive = false)
} else {
this.io_customerly__progress_view.visibility = View.GONE
val messageContent:String? = this.intent.getStringExtra(EXTRA_MESSAGE_CONTENT)
if(messageContent != null) {
this.onSendMessage(
content = messageContent,
attachments = this.intent.getParcelableArrayListExtra<ClyAttachment>(EXTRA_MESSAGE_ATTACHMENTS)?.toTypedArray()
?: emptyArray())
}
this.updateAccountInfos(fallbackUserOnLastActive = false)
}
}
}
private fun onConversationId(conversationId: Long) {
this.conversationId = conversationId
this.inputLayout?.visibility = View.VISIBLE
val weakRv = this.io_customerly__recycler_view.weak()
Customerly.clySocket.typingListener = { pConversationId, accountId, accountName, pTyping ->
if((pTyping && typingAccountId != accountId)
||
(!pTyping && typingAccountId != TYPING_NO_ONE)) {
if (conversationId == pConversationId) {
weakRv.get()?.post {
when(pTyping) {
true -> when(this.typingAccountId) {
TYPING_NO_ONE -> {
this.typingAccountId = accountId
this.typingAccountName = accountName
weakRv.get()?.also { recyclerView ->
recyclerView.adapter?.notifyItemInserted(0)
(recyclerView.layoutManager as? SXLinearLayoutManager)?.takeIf {
it.findFirstCompletelyVisibleItemPosition() == 0
}?.scrollToPosition(0)
}
}
else -> {
this.typingAccountId = accountId
this.typingAccountName = accountName
weakRv.get()?.adapter?.notifyItemChanged(0)
}
}
false -> {
this.typingAccountId = TYPING_NO_ONE
this.typingAccountName = null
weakRv.get()?.adapter?.notifyItemRemoved(0)
}
}
}
}
}
}
this.inputInput?.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 (s.isEmpty()) {
Customerly.clySocket.sendStopTyping(conversationId = conversationId)
} else {
Customerly.clySocket.sendStartTyping(conversationId = conversationId, previewText = s.toString())
}
}
})
val weakActivity = this.weak()
this.io_customerly__recycler_view.postDelayed( {
weakActivity.reference { activity ->
if (activity.chatList.count { it.writer.isAccount } == 0) {
var botMessageContent: String? = null
val nextOfficeHours: ClyNextOfficeHours? = Customerly.lastPing.nextOfficeHours
if(nextOfficeHours?.isOfficeOpen() == false) {
botMessageContent = nextOfficeHours.getBotMessage(context = activity)
}
@SXStringRes val replyTimeStringResId: Int? = Customerly.lastPing.replyTime?.stringResId
if(botMessageContent == null && replyTimeStringResId != null && replyTimeStringResId > 0) {
botMessageContent = activity.getString(replyTimeStringResId)
}
if(botMessageContent != null) {
activity.addMessageAt0(message = ClyMessage.Bot.Text(
messageId = activity.chatList.optAt(0)?.id
?: -System.currentTimeMillis(),
conversationId = conversationId,
content = botMessageContent))
}
}
}
}, 3000)
this.io_customerly__recycler_view.postDelayed( {
weakActivity.reference { activity ->
if(Customerly.currentUser.email == null) {
activity.addMessageAt0(message = ClyMessage.Bot.Text(
messageId = activity.chatList.optAt(0)?.id
?: -System.currentTimeMillis(),
conversationId = conversationId,
content = activity.getString(R.string.io_customerly__give_us_a_way_to_reach_you)))
activity.io_customerly__recycler_view.postDelayed( {
weakActivity.get()?.addMessageAt0(message = ClyMessage.Bot.Form.AskEmail(conversationId = conversationId, messageId = 1))
}, 1000)
} else if (activity.chatList.count { it.writer.isAccount } == 0) {
activity.tryLoadForm()
}
null
}
}, 4000)
}
override fun onResume() {
super.onResume()
this.progressiveScrollListener?.let { this.onBottomReachedListener(it) }
}
override fun onDestroy() {
Customerly.clySocket.typingListener = null
this.conversationId.takeIf { it != CONVERSATIONID_UNKNOWN_FOR_MESSAGE }?.apply { Customerly.clySocket.sendStopTyping(conversationId = this) }
super.onDestroy()
}
override fun onReconnection() {
this.progressiveScrollListener?.let { this.onBottomReachedListener(it) }
}
override fun onLogoutUser() {
this.finish()
}
internal fun startAttachmentDownload(filename: String, fullPath: String) {
if (SXContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
startFileDownload(context = this, filename = filename, fullPath = fullPath)
} else {
this.permissionRequestPendingFileName = filename
this.permissionRequestPendingPath = fullPath
if (SXActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
SXAlertDialogBuilder(this)
.setTitle(R.string.io_customerly__permission_request)
.setMessage(R.string.io_customerly__permission_request_explanation_write)
.setPositiveButton(android.R.string.ok) { _, _ -> SXActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_REQUEST__WRITE_EXTERNAL_STORAGE) }
.show()
} else {
SXActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_REQUEST__WRITE_EXTERNAL_STORAGE)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSION_REQUEST__WRITE_EXTERNAL_STORAGE -> {
for (i in 0 until min(grantResults.size, permissions.size)) {
if (permissions[i] == Manifest.permission.WRITE_EXTERNAL_STORAGE && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
val pendingFileName = this.permissionRequestPendingFileName
val pendingPath = this.permissionRequestPendingPath
if(pendingFileName?.isNotEmpty() == true && pendingPath?.isNotEmpty() == true) {
this.startAttachmentDownload(filename = pendingFileName, fullPath = pendingPath)
this.permissionRequestPendingFileName = null
this.permissionRequestPendingPath = null
}
return
}
}
Toast.makeText(this.applicationContext, R.string.io_customerly__permission_denied_write, Toast.LENGTH_LONG).show()
}
else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
private fun sendSeen(messageId: Long) {
val wContext = this.weak()
ClySntpClient.getNtpTimeAsync(context = this) { time ->
val utc = (time ?: System.currentTimeMillis()).msAsSeconds
Customerly.clySocket.sendSeen(messageId = messageId, seenTimestamp = utc)
ClyApiRequest<Any>(
context = wContext.get(),
endpoint = ENDPOINT_MESSAGE_SEEN,
requireToken = true,
jsonObjectConverter = { it })
.p(key = "conversation_message_id", value = messageId)
.p(key = "seen_date", value = utc)
.start()
}
}
internal fun startSendMessageRequest(message: ClyMessage) {
val weakAct = this.weak()
ClyApiRequest(
context = this,
endpoint = ENDPOINT_MESSAGE_SEND,
requireToken = true,
trials = 2,
jsonObjectConverter = { response ->
Customerly.clySocket.sendMessage(timestamp = response.optLong("timestamp", -1L))
Customerly.currentUser.leadHash = response.optString("lead_hash").takeIf { it != "" }
response.optJSONObject("message")?.parseMessage()
},
callback = { response ->
weakAct.get()?.also { activity ->
val chatList = activity.chatList
when (response) {
is ClyApiResponse.Success -> {
chatList.indexOf(message).takeIf { it != -1 }?.also {
chatList[it] = response.result
activity.notifyItemChangedInList(message = response.result)
if(activity.conversationId == CONVERSATIONID_UNKNOWN_FOR_MESSAGE) {
activity.onConversationId(conversationId = response.result.conversationId)
}
}
}
is ClyApiResponse.Failure -> {
message.setStateFailed()
activity.notifyItemChangedInList(message = message)
Toast.makeText(activity.applicationContext, R.string.io_customerly__connection_error, Toast.LENGTH_SHORT).show()
}
}
activity.updateAccountInfos(true)
}
}).apply {
if(message.conversationId != CONVERSATIONID_UNKNOWN_FOR_MESSAGE) {
this.p(key = "conversation_id", value = message.conversationId)
}
}
.p(key = "message", value = message.content)
.p(key = "attachments", value = message.attachments.toJSON(context = this))
.p(key = "lead_hash", value = Customerly.currentUser.leadHash)
.start()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
this.finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
@SXUiThread
override fun onSendMessage(content: String, attachments: Array<ClyAttachment>) {
val userId = Customerly.jwtToken?.userID
val conversationId = this.conversationId
when {
userId != null -> ClyMessage.Human.UserLocal(userId = userId, conversationId = conversationId, content = content, attachments = attachments).also { message ->
this.addMessageAt0(message = message)
this.startSendMessageRequest(message = message)
}
Customerly.lastPing.allowAnonymousChat -> {
val pendingMessage = ClyMessage.Human.UserLocal(conversationId = conversationId, content = content, attachments = attachments)
this.addMessageAt0(message = pendingMessage)
val weakActivity = this.weak()
ClyApiRequest(
context = this.applicationContext,
endpoint = ENDPOINT_PING,
jsonObjectConverter = { Unit },
callback = { response ->
Customerly.jwtToken?.userID?.apply { pendingMessage.writer.id = this }
weakActivity.reference { clyChatActivity ->
when (response) {
is ClyApiResponse.Success -> {
pendingMessage.setStateSending()
clyChatActivity.notifyItemChangedInList(message = pendingMessage)
clyChatActivity.startSendMessageRequest(message = pendingMessage)
}
is ClyApiResponse.Failure -> {
pendingMessage.setStateFailed()
clyChatActivity.notifyItemChangedInList(message = pendingMessage)
}
}
}
})
.p(key = "force_lead", value = true)
.start()
}
else -> {
this.inputLayout?.visibility = View.GONE
ClyMessage.Human.UserLocal(conversationId = conversationId, content = content, attachments = attachments).also { pendingMessage ->
this.addMessageAt0(message = pendingMessage)
this.addMessageAt0(message = ClyMessage.Bot.Form.AskEmail(conversationId = pendingMessage.conversationId, messageId = 1, pendingMessage = pendingMessage))
}
}
}
}
internal fun tryLoadForm() {
if(Customerly.iamLead()
&& this.chatList.asSequence().none {
when (it) {
is ClyMessage.Bot.Form.Profiling -> !it.form.answerConfirmed
is ClyMessage.Bot.Form.AskEmail -> Customerly.currentUser.email == null
else -> false
}
}) {
Customerly.lastPing.nextFormDetails?.also { form ->
this.conversationId.takeIf { it != CONVERSATIONID_UNKNOWN_FOR_MESSAGE }?.also { conversationId ->
this.addMessageAt0(message = ClyMessage.Bot.Form.Profiling(
messageId = this.chatList.optAt(0)?.id ?: -System.currentTimeMillis(),
conversationId = conversationId,
form = form))
}
}
}
}
private fun addMessageAt0(message: ClyMessage) {
this.chatList.add(0, message)
this.io_customerly__recycler_view?.let {
(it.adapter as? ClyChatAdapter)?.apply {
this.notifyItemInserted(this.listIndex2position(listIndex = 0))
}
(it.layoutManager as? SXLinearLayoutManager)?.takeIf { llm -> llm.findFirstCompletelyVisibleItemPosition() == 0 }?.scrollToPosition(0)
}
}
@SXUiThread
override fun onNewSocketMessages(messages: ArrayList<ClyMessage>) {
messages
.asSequence()
.lastOrNull { it.conversationId != this.conversationId}
?.let { otherConversationMessage ->
try {
this.showClyAlertMessage(message = otherConversationMessage)
} catch (exception : WindowManager.BadTokenException) { }
}
val newChatList = ArrayList(this.chatList)
messages
.asSequence()
.filter { it.conversationId == this.conversationId && !newChatList.contains(it) }
.forEach { newChatList.add(it) }
newChatList.sortByDescending { it.id }//Sorting by conversation_message_id DESC
this.chatList = newChatList
this.io_customerly__recycler_view?.let {
val wRv = it.weak()
it.post {
wRv.get()?.let { rv ->
rv.adapter?.notifyDataSetChanged()
(rv.layoutManager as? SXLinearLayoutManager)?.takeIf { llm -> llm.findFirstCompletelyVisibleItemPosition() == 0 }?.scrollToPosition(0)
}
}
}
this.updateAccountInfos()
newChatList.firstOrNull()?.takeIf { it.isNotSeen }?.also { this.sendSeen(messageId = it.id) }
}
private fun updateAccountInfos(fallbackUserOnLastActive: Boolean = true) {
val lastAccountId = this.chatList.firstOrNull { it.writer.isAccount }?.writer?.id
if(this.conversationFullAdmin == null || this.conversationFullAdminFromMessagesAccountId != lastAccountId) {
Customerly.getAccountDetails { adminsFullDetails ->
val fullAdmin = when {
lastAccountId != null -> adminsFullDetails?.firstOrNull { it.accountId == lastAccountId }
fallbackUserOnLastActive -> adminsFullDetails?.maxBy { it.lastActive }
else -> null
}
@SXColorInt val titleTextColorInt = Customerly.lastPing.widgetColor.getContrastBW()
if(fullAdmin != null) {
this.conversationFullAdmin = fullAdmin
this.conversationFullAdminFromMessagesAccountId = lastAccountId
fullAdmin.jobTitle?.also { jobTitle ->
this.io_customerly__job.apply {
this.text = jobTitle
this.setTextColor(titleTextColorInt)
this.visibility = View.VISIBLE
}
}
this.io_customerly__title.setOnClickListener {
(it.activity as? ClyChatActivity)?.also { chatActivity ->
chatActivity.io_customerly__recycler_view?.layoutManager?.also { llm ->
this.progressiveScrollListener?.skipNextBottom()
llm.scrollToPosition(llm.itemCount - 1)
}
}
}
this.io_customerly__icon.visibility = View.VISIBLE
ClyImageRequest(context = this, url = fullAdmin.getImageUrl(sizePx = 48.dp2px))
.fitCenter()
.transformCircle()
.resize(width = 48.dp2px)
.placeholder(placeholder = R.drawable.io_customerly__ic_default_admin)
.into(imageView = this.io_customerly__icon)
.start()
this.io_customerly__name.apply {
this.text = fullAdmin.name
this.setTextColor(titleTextColorInt)
}
this.io_customerly__recycler_view.apply {
(this.adapter as? ClyChatAdapter)?.also { adapter ->
val llm = this.layoutManager as? SXLinearLayoutManager
this.post {
val scrollTo0 = llm?.findFirstCompletelyVisibleItemPosition() == 0
adapter.notifyAccountCardChanged()
if (scrollTo0) {
llm?.scrollToPosition(0)
}
}
}
}
} else {
this.io_customerly__icon.visibility = View.GONE
this.io_customerly__name.apply {
this.setText(R.string.io_customerly__activity_title_chat)
this.setTextColor(titleTextColorInt)
}
}
}
}
}
fun notifyItemChangedInList(message: ClyMessage) {
this.chatList.indexOf(message).takeIf { it != -1 }?.also { listIndex ->
(this.io_customerly__recycler_view.adapter as? ClyChatAdapter)?.also { adapter ->
adapter.notifyItemChanged(adapter.listIndex2position(listIndex))
}
}
}
}
| apache-2.0 | 6427377c0580bc4d661b8c552ebe189b | 50.786708 | 214 | 0.526085 | 5.708979 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.