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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JuliusKunze/kotlin-native
|
samples/objc/src/main/kotlin/Window.kt
|
1
|
1903
|
import kotlinx.cinterop.*
import platform.AppKit.*
import platform.Foundation.*
import platform.objc.*
import platform.osx.*
fun main(args: Array<String>) {
autoreleasepool {
runApp()
}
}
private fun runApp() {
val app = NSApplication.sharedApplication()
app.delegate = MyAppDelegate()
app.setActivationPolicy(NSApplicationActivationPolicy.NSApplicationActivationPolicyRegular)
app.activateIgnoringOtherApps(true)
app.run()
}
private class MyAppDelegate() : NSObject(), NSApplicationDelegateProtocol {
private val window: NSWindow
init {
val mainDisplayRect = NSScreen.mainScreen()!!.frame
val windowRect = mainDisplayRect.useContents {
NSMakeRect(
origin.x + size.width * 0.25,
origin.y + size.height * 0.25,
size.width * 0.5,
size.height * 0.5
)
}
val windowStyle = NSWindowStyleMaskTitled or NSWindowStyleMaskMiniaturizable or
NSWindowStyleMaskClosable or NSWindowStyleMaskResizable
window = NSWindow(windowRect, windowStyle, NSBackingStoreBuffered, false).apply {
title = "Окошко Konan"
opaque = true
hasShadow = true
preferredBackingLocation = NSWindowBackingLocationVideoMemory
hidesOnDeactivate = false
backgroundColor = NSColor.whiteColor()
releasedWhenClosed = false
delegate = object : NSObject(), NSWindowDelegateProtocol {
override fun windowShouldClose(sender: NSWindow): Boolean {
NSApplication.sharedApplication().stop(this)
return true
}
}
}
}
override fun applicationWillFinishLaunching(notification: NSNotification) {
window.makeKeyAndOrderFront(this)
}
}
|
apache-2.0
|
b4f03a4ef79af0635a624f11effbd324
| 29.596774 | 95 | 0.628361 | 4.778338 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/coroutines/inlineSuspendFunction.kt
|
2
|
1200
|
// IGNORE_BACKEND: NATIVE
// WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
// WITH_REFLECT
// CHECK_NOT_CALLED: suspendInline_61zpoe$
// CHECK_NOT_CALLED: suspendInline_6r51u9$
// CHECK_NOT_CALLED: suspendInline
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
class Controller {
fun withValue(v: String, x: Continuation<String>) {
x.resume(v)
}
suspend inline fun suspendInline(v: String): String = suspendCoroutineOrReturn { x ->
withValue(v, x)
COROUTINE_SUSPENDED
}
suspend inline fun suspendInline(crossinline b: () -> String): String = suspendInline(b())
suspend inline fun <reified T : Any> suspendInline(): String = suspendInline({ T::class.simpleName!! })
}
fun builder(c: suspend Controller.() -> Unit) {
c.startCoroutine(Controller(), EmptyContinuation)
}
class OK
fun box(): String {
var result = ""
builder {
result = suspendInline("56")
if (result != "56") throw RuntimeException("fail 1")
result = suspendInline { "57" }
if (result != "57") throw RuntimeException("fail 2")
result = suspendInline<OK>()
}
return result
}
|
apache-2.0
|
ff91d81e8ef81c20e8b07f6d1307e3c6
| 24.531915 | 107 | 0.661667 | 3.97351 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/platformTypes/primitives/equals.kt
|
2
|
140
|
fun box(): String {
val l = ArrayList<Int>()
l.add(1)
val x = l[0] == 2
if (x != false) return "Fail: $x}"
return "OK"
}
|
apache-2.0
|
75a1a69e2c2a53db98f1e3a7e136aab3
| 19.142857 | 38 | 0.478571 | 2.745098 | false | false | false | false |
exponent/exponent
|
packages/expo-font/android/src/main/java/expo/modules/font/FontLoaderModule.kt
|
2
|
2694
|
// Copyright 2015-present 650 Industries. All rights reserved.
package expo.modules.font
import android.content.Context
import android.graphics.Typeface
import android.net.Uri
import expo.modules.core.ExportedModule
import expo.modules.core.ModuleRegistry
import expo.modules.core.ModuleRegistryDelegate
import expo.modules.core.interfaces.ExpoMethod
import expo.modules.core.Promise
import expo.modules.interfaces.font.FontManagerInterface
import expo.modules.interfaces.constants.ConstantsInterface
import java.io.File
import java.lang.Exception
private const val ASSET_SCHEME = "asset://"
private const val EXPORTED_NAME = "ExpoFontLoader"
class FontLoaderModule(context: Context) : ExportedModule(context) {
private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate()
private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>()
override fun onCreate(moduleRegistry: ModuleRegistry) {
moduleRegistryDelegate.onCreate(moduleRegistry)
}
override fun getName(): String {
return EXPORTED_NAME
}
@ExpoMethod
fun loadAsync(fontFamilyName: String, localUri: String, promise: Promise) {
try {
// TODO: remove Expo references
// https://github.com/expo/expo/pull/4652#discussion_r296630843
val prefix = if (isScoped) {
"ExpoFont-"
} else {
""
}
// TODO(nikki): make sure path is in experience's scope
val typeface: Typeface = if (localUri.startsWith(ASSET_SCHEME)) {
Typeface.createFromAsset(
context.assets, // Also remove the leading slash.
localUri.substring(ASSET_SCHEME.length + 1)
)
} else {
Typeface.createFromFile(File(Uri.parse(localUri).path))
}
val fontManager: FontManagerInterface? by moduleRegistry()
if (fontManager == null) {
promise.reject("E_NO_FONT_MANAGER", "There is no FontManager in module registry. Are you sure all the dependencies of expo-font are installed and linked?")
return
}
fontManager!!.setTypeface(prefix + fontFamilyName, Typeface.NORMAL, typeface)
promise.resolve(null)
} catch (e: Exception) {
promise.reject("E_UNEXPECTED", "Font.loadAsync unexpected exception: " + e.message, e)
}
}
// If there's no constants module, or app ownership isn't "expo", we're not in Expo Client.
private val isScoped: Boolean
get() {
val constantsModule: ConstantsInterface? by moduleRegistry()
// If there's no constants module, or app ownership isn't "expo", we're not in Expo Client.
return constantsModule != null && "expo" == constantsModule!!.appOwnership
}
}
|
bsd-3-clause
|
ab137f78f47891e16ffacd18fa30cc93
| 33.538462 | 163 | 0.717149 | 4.345161 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/testFramework/util.kt
|
1
|
9923
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.testFramework
import org.jetbrains.kotlin.idea.perf.profilers.*
import org.jetbrains.kotlin.idea.perf.util.*
import org.jetbrains.kotlin.idea.perf.util.pathToResource
import org.jetbrains.kotlin.idea.perf.util.plainname
import org.jetbrains.kotlin.util.PerformanceCounter
import java.lang.ref.WeakReference
import java.util.HashMap
import kotlin.system.measureNanoTime
import kotlin.system.measureTimeMillis
import kotlin.test.assertEquals
typealias StatInfos = Map<String, Any>?
// much stricter version of com.intellij.util.PathUtil.suggestFileName(java.lang.String)
// returns OS-neutral file name, which remains the same when generated on different OSes
fun suggestOsNeutralFileName(name: String) = name.asSequence().map { ch ->
if (ch < 32.toChar() || ch in "<>:\"|?*.\\/;" || ch.isWhitespace()) '_' else ch
}.joinToString(separator = "")
fun <SV, TV> perfTest(
stats: Stats,
testName: String,
warmUpIterations: Int = 5,
iterations: Int = 20,
fastIterations: Boolean = false,
setUp: (TestData<SV, TV>) -> Unit = { },
test: (TestData<SV, TV>) -> Unit,
tearDown: (TestData<SV, TV>) -> Unit = { },
stabilityWatermark: Int? = 20
) {
val setUpWrapper = stats.profilerConfig.wrapSetUp(setUp)
val testWrapper = stats.profilerConfig.wrapTest(test)
val tearDownWrapper = stats.profilerConfig.wrapTearDown(tearDown)
val warmPhaseData = PhaseData(
stats = stats,
iterations = warmUpIterations,
testName = testName,
fastIterations = fastIterations,
setUp = setUpWrapper,
test = testWrapper,
tearDown = tearDownWrapper,
stabilityWatermark = stabilityWatermark
)
val mainPhaseData = PhaseData(
stats = stats,
iterations = iterations,
testName = testName,
fastIterations = fastIterations,
setUp = setUpWrapper,
test = testWrapper,
tearDown = tearDownWrapper,
stabilityWatermark = stabilityWatermark
)
val block = {
val metricChildren = mutableListOf<Metric>()
try {
warmUpPhase(warmPhaseData, metricChildren)
val statInfoArray = mainPhase(mainPhaseData, metricChildren)
if (!mainPhaseData.fastIterations) assertEquals(iterations, statInfoArray.size)
if (testName != Stats.WARM_UP) {
// do not estimate stability for warm-up
if (!testName.contains(Stats.WARM_UP)) {
val stabilityPercentage = stats.stabilityPercentage(statInfoArray)
logMessage { "$testName stability is $stabilityPercentage %" }
val stabilityName = "${stats.name}: $testName stability"
val stable = stabilityWatermark?.let { stabilityPercentage <= it } ?: true
val error = if (stable) {
null
} else {
"$testName stability is $stabilityPercentage %, above accepted level of $stabilityWatermark %"
}
TeamCity.test(stabilityName, errorDetails = error, includeStats = false) {
metricChildren.add(Metric("stability", metricValue = stabilityPercentage.toLong()))
}
}
stats.processTimings(testName, statInfoArray, metricChildren)
} else {
stats.convertStatInfoIntoMetrics(
testName,
printOnlyErrors = true,
statInfoArray = statInfoArray,
metricChildren = metricChildren
)
}
} catch (e: Throwable) {
stats.processTimings(testName, emptyArray(), metricChildren)
}
}
if (testName != Stats.WARM_UP) {
TeamCity.suite(testName, block)
} else {
block()
}
stats.flush()
}
data class PhaseData<SV, TV>(
val stats: Stats,
val iterations: Int,
val testName: String,
val setUp: (TestData<SV, TV>) -> Unit,
val test: (TestData<SV, TV>) -> Unit,
val tearDown: (TestData<SV, TV>) -> Unit,
val stabilityWatermark: Int?,
val fastIterations: Boolean = false
)
data class TestData<SV, TV>(var setUpValue: SV?, var value: TV?) {
fun reset() {
setUpValue = null
value = null
}
}
private val emptyFun:(TestData<*, *>) -> Unit = {}
private fun <SV, TV> ProfilerConfig.wrapSetUp(setup: (TestData<SV, TV>) -> Unit): (TestData<SV, TV>) -> Unit =
if (!dryRun) setup else emptyFun
private fun <SV, TV> ProfilerConfig.wrapTest(test: (TestData<SV, TV>) -> Unit): (TestData<SV, TV>) -> Unit =
if (!dryRun) test else emptyFun
private fun <SV, TV> ProfilerConfig.wrapTearDown(tearDown: (TestData<SV, TV>) -> Unit): (TestData<SV, TV>) -> Unit =
if (!dryRun) tearDown else emptyFun
private fun <SV, TV> warmUpPhase(phaseData: PhaseData<SV, TV>, metricChildren: MutableList<Metric>) {
val warmUpStatInfosArray = phase(phaseData, Stats.WARM_UP, true)
if (phaseData.testName != Stats.WARM_UP) {
phaseData.stats.printWarmUpTimings(phaseData.testName, warmUpStatInfosArray, metricChildren)
} else {
phaseData.stats.convertStatInfoIntoMetrics(
phaseData.testName,
printOnlyErrors = true,
statInfoArray = warmUpStatInfosArray,
warmUp = true,
metricChildren = metricChildren
) { attempt -> "warm-up #$attempt" }
}
warmUpStatInfosArray.filterNotNull().map { it[Stats.ERROR_KEY] as? Throwable }.firstOrNull()?.let { throw it }
}
private fun <SV, TV> mainPhase(phaseData: PhaseData<SV, TV>, metricChildren: MutableList<Metric>): Array<StatInfos> {
val statInfosArray = phase(phaseData, "")
statInfosArray.filterNotNull().map { it[Stats.ERROR_KEY] as? Throwable }.firstOrNull()?.let {
phaseData.stats.convertStatInfoIntoMetrics(
phaseData.testName,
printOnlyErrors = true,
statInfoArray = statInfosArray,
metricChildren = metricChildren
)
throw it
}
return statInfosArray
}
private fun <SV, TV> phase(phaseData: PhaseData<SV, TV>, phaseName: String, warmup: Boolean = false): Array<StatInfos> {
val statInfosArray = Array<StatInfos>(phaseData.iterations) { null }
val testData = TestData<SV, TV>(null, null)
val stats = phaseData.stats
try {
val phaseProfiler =
createPhaseProfiler(stats.name, phaseData.testName, phaseName, stats.profilerConfig.copy(warmup = warmup))
for (attempt in 0 until phaseData.iterations) {
testData.reset()
triggerGC(attempt)
val setUpMillis = measureTimeMillis {
phaseData.setUp(testData)
}
val attemptName = "${phaseData.testName} #$attempt"
//logMessage { "$attemptName setup took $setUpMillis ms" }
val valueMap = HashMap<String, Any>(2 * PerformanceCounter.numberOfCounters + 1)
statInfosArray[attempt] = valueMap
try {
phaseProfiler.start()
valueMap[Stats.TEST_KEY] = measureNanoTime {
phaseData.test(testData)
}
PerformanceCounter.report { name, counter, nanos ->
valueMap["counter \"$name\": count"] = counter.toLong()
valueMap["counter \"$name\": time"] = nanos.nsToMs
}
} catch (t: Throwable) {
logMessage(t) { "error at $attemptName" }
valueMap[Stats.ERROR_KEY] = t
break
} finally {
phaseProfiler.stop()
try {
val tearDownMillis = measureTimeMillis {
phaseData.tearDown(testData)
}
//logMessage { "$attemptName tearDown took $tearDownMillis ms" }
} catch (t: Throwable) {
logMessage(t) { "error at tearDown of $attemptName" }
valueMap[Stats.ERROR_KEY] = t
break
} finally {
PerformanceCounter.resetAllCounters()
}
}
if (phaseData.fastIterations && attempt > 0) {
val subArray = statInfosArray.take(attempt + 1).toTypedArray()
val stabilityPercentage = stats.stabilityPercentage(subArray)
val stable = phaseData.stabilityWatermark?.let { stabilityPercentage <= it } == true
if (stable) {
return subArray
}
}
}
} catch (t: Throwable) {
logMessage(t) { "error at ${phaseData.testName}" }
TeamCity.testFailed(stats.name, error = t)
}
return statInfosArray
}
private fun createPhaseProfiler(
statsName: String,
testName: String,
phaseName: String,
profilerConfig: ProfilerConfig
): PhaseProfiler {
profilerConfig.name = "$testName${if (phaseName.isEmpty()) "" else "-$phaseName"}"
profilerConfig.path = pathToResource("profile/${plainname(statsName)}").path
val profilerHandler = if (profilerConfig.enabled && !profilerConfig.warmup)
ProfilerHandler.getInstance(profilerConfig)
else
DummyProfilerHandler
return if (profilerHandler != DummyProfilerHandler) {
ActualPhaseProfiler(profilerHandler)
} else {
DummyPhaseProfiler
}
}
private fun triggerGC(attempt: Int) {
if (attempt > 0) {
val ref = WeakReference(IntArray(32 * 1024))
while (ref.get() != null) {
System.gc()
Thread.sleep(1)
}
}
}
|
apache-2.0
|
ff8987b32e432a43b67770159c40a051
| 36.164794 | 158 | 0.605664 | 4.490045 | false | true | false | false |
jotomo/AndroidAPS
|
danar/src/main/java/info/nightscout/androidaps/danaRv2/comm/MsgHistoryEvents_v2.kt
|
1
|
10055
|
package info.nightscout.androidaps.danaRv2.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.danar.R
import info.nightscout.androidaps.danar.comm.MessageBase
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.db.ExtendedBolus
import info.nightscout.androidaps.db.Source
import info.nightscout.androidaps.db.TemporaryBasal
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.utils.DateUtil
import java.util.*
class MsgHistoryEvents_v2 constructor(
private val injector: HasAndroidInjector,
var from: Long = 0
) : MessageBase(injector) {
init {
SetCommand(0xE003)
if (from > DateUtil.now()) {
aapsLogger.error("Asked to load from the future")
from = 0
}
if (from == 0L) {
AddParamByte(0.toByte())
AddParamByte(1.toByte())
AddParamByte(1.toByte())
AddParamByte(0.toByte())
AddParamByte(0.toByte())
} else {
val gfrom = GregorianCalendar()
gfrom.timeInMillis = from
AddParamDate(gfrom)
}
danaRv2Plugin.eventsLoadingDone = false
aapsLogger.debug(LTag.PUMPBTCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
val recordCode = intFromBuff(bytes, 0, 1).toByte()
// Last record
if (recordCode == 0xFF.toByte()) {
danaRv2Plugin.eventsLoadingDone = true
return
}
danaRv2Plugin.eventsLoadingDone = false
val datetime = dateTimeSecFromBuff(bytes, 1) // 6 bytes
val param1 = intFromBuff(bytes, 7, 2)
val param2 = intFromBuff(bytes, 9, 2)
val temporaryBasal = TemporaryBasal(injector)
.date(datetime)
.source(Source.PUMP)
.pumpId(datetime)
val extendedBolus = ExtendedBolus(injector)
.date(datetime)
.source(Source.PUMP)
.pumpId(datetime)
val status: String
when (recordCode.toInt()) {
info.nightscout.androidaps.dana.DanaPump.TEMPSTART -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT TEMPSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min")
temporaryBasal.percentRate = param1
temporaryBasal.durationInMinutes = param2
activePlugin.activeTreatments.addToHistoryTempBasal(temporaryBasal)
status = "TEMPSTART " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.TEMPSTOP -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT TEMPSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime))
activePlugin.activeTreatments.addToHistoryTempBasal(temporaryBasal)
status = "TEMPSTOP " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.EXTENDEDSTART -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT EXTENDEDSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min")
extendedBolus.insulin = param1 / 100.0
extendedBolus.durationInMinutes = param2
activePlugin.activeTreatments.addToHistoryExtendedBolus(extendedBolus)
status = "EXTENDEDSTART " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.EXTENDEDSTOP -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT EXTENDEDSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min")
activePlugin.activeTreatments.addToHistoryExtendedBolus(extendedBolus)
status = "EXTENDEDSTOP " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.BOLUS -> {
val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(datetime, param1 / 100.0)
?: DetailedBolusInfo()
detailedBolusInfo.date = datetime
detailedBolusInfo.source = Source.PUMP
detailedBolusInfo.pumpId = datetime
detailedBolusInfo.insulin = param1 / 100.0
val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false)
aapsLogger.debug(LTag.PUMPBTCOMM, (if (newRecord) "**NEW** " else "") + "EVENT BOLUS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min")
status = "BOLUS " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.DUALBOLUS -> {
val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(datetime, param1 / 100.0)
?: DetailedBolusInfo()
detailedBolusInfo.date = datetime
detailedBolusInfo.source = Source.PUMP
detailedBolusInfo.pumpId = datetime
detailedBolusInfo.insulin = param1 / 100.0
val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false)
aapsLogger.debug(LTag.PUMPBTCOMM, (if (newRecord) "**NEW** " else "") + "EVENT DUALBOLUS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min")
status = "DUALBOLUS " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.DUALEXTENDEDSTART -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT DUALEXTENDEDSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min")
extendedBolus.insulin = param1 / 100.0
extendedBolus.durationInMinutes = param2
activePlugin.activeTreatments.addToHistoryExtendedBolus(extendedBolus)
status = "DUALEXTENDEDSTART " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.DUALEXTENDEDSTOP -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min")
activePlugin.activeTreatments.addToHistoryExtendedBolus(extendedBolus)
status = "DUALEXTENDEDSTOP " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.SUSPENDON -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT SUSPENDON (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")")
status = "SUSPENDON " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.SUSPENDOFF -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT SUSPENDOFF (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")")
status = "SUSPENDOFF " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.REFILL -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT REFILL (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U")
status = "REFILL " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.PRIME -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT PRIME (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U")
status = "PRIME " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.PROFILECHANGE -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT PROFILECHANGE (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + param2 / 100.0 + "U/h")
status = "PROFILECHANGE " + dateUtil.timeString(datetime)
}
info.nightscout.androidaps.dana.DanaPump.CARBS -> {
val emptyCarbsInfo = DetailedBolusInfo()
emptyCarbsInfo.carbs = param1.toDouble()
emptyCarbsInfo.date = datetime
emptyCarbsInfo.source = Source.PUMP
emptyCarbsInfo.pumpId = datetime
val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(emptyCarbsInfo, false)
aapsLogger.debug(LTag.PUMPBTCOMM, (if (newRecord) "**NEW** " else "") + "EVENT CARBS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g")
status = "CARBS " + dateUtil.timeString(datetime)
}
else -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "Event: " + recordCode + " " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Param1: " + param1 + " Param2: " + param2)
status = "UNKNOWN " + dateUtil.timeString(datetime)
}
}
if (datetime > danaRv2Plugin.lastEventTimeLoaded) danaRv2Plugin.lastEventTimeLoaded = datetime
rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.processinghistory) + ": " + status))
}
}
|
agpl-3.0
|
c223c62ab8fc78a8456f9b558cc4bea0
| 57.127168 | 255 | 0.603779 | 4.589229 | false | false | false | false |
fabmax/kool
|
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/uidemo/UiDemo.kt
|
1
|
5085
|
package de.fabmax.kool.demo.uidemo
import de.fabmax.kool.AssetManager
import de.fabmax.kool.KoolContext
import de.fabmax.kool.demo.DemoLoader
import de.fabmax.kool.demo.DemoScene
import de.fabmax.kool.demo.Settings
import de.fabmax.kool.demo.UiSizes
import de.fabmax.kool.math.MutableVec2f
import de.fabmax.kool.modules.ui2.*
import de.fabmax.kool.pipeline.Texture2d
import de.fabmax.kool.scene.Scene
import de.fabmax.kool.util.Color
import de.fabmax.kool.util.MsdfFont
class UiDemo : DemoScene("UI Demo") {
val selectedColors = mutableStateOf(Colors.darkColors())
val selectedUiSize = mutableStateOf(Sizes.medium)
val demoWindows = mutableListOf<DemoWindow>()
private val windowSpawnLocation = MutableVec2f(320f, 64f)
private val dockingHost = DockingHost()
var exampleImage: Texture2d? = null
override suspend fun AssetManager.loadResources(ctx: KoolContext) {
exampleImage = loadAndPrepareTexture("${DemoLoader.materialPath}/uv_checker_map.jpg")
}
override fun Scene.setupMainScene(ctx: KoolContext) {
setupUiScene(true)
+dockingHost.apply {
onUpdate += {
// set a left margin for the demo menu band
dockingSurface.rootContainer.dockMarginStart.set(UiSizes.baseSize)
}
}
// Spawn a few windows, docked right, left and in center
//
// Specifying the docking path is a bit cumbersome right now:
// Docking nodes are organized as a bin-tree, only leaf nodes can contain docked windows.
// The docking path specifies the path in the tree where to dock the given window, starting at the root node.
// The numbers define the split weights in case tree nodes have to be spawned to complete the path.
// If the internal tree structure conflicts with the given path, the window is docked in the next best slot.
//
// The LauncherWindow is docked at Start (left) position below the root node. Splitting it with an absolute
// width of 250 dp, remaining screen space remain will be empty.
// Then, the ThemeEditorWindow is spawned on the right side of the empty side (path: root -> end/right -> end/right),
// taking 30 % of the empty space.
spawnWindow(LauncherWindow(this@UiDemo), listOf(DockingHost.DockPosition.Start to Dp(250f)))
spawnWindow(ThemeEditorWindow(this@UiDemo), listOf(DockingHost.DockPosition.End to Grow.Std, DockingHost.DockPosition.End to Grow(0.3f)))
// TextStyleWindow is spawned as a floating window
spawnWindow(TextStyleWindow(this@UiDemo))
//spawnWindow(TextAreaWindow(this@UiDemo))
// add a sidebar for the demo menu
+Panel {
surface.colors = selectedColors.use()
surface.sizes = Settings.uiSize.use().sizes
val fgColor: Color
val bgColor: Color
if (colors.isLight) {
fgColor = colors.primary
bgColor = colors.secondaryVariant.mix(Color.BLACK, 0.3f)
} else {
fgColor = colors.secondary
bgColor = colors.backgroundVariant
}
modifier
.width(UiSizes.baseSize)
.height(Grow.Std)
.backgroundColor(bgColor)
.layout(CellLayout)
.onClick { demoLoader?.menu?.isExpanded = true }
Text("UI Demo") {
val font = MsdfFont(sizePts = sizes.largeText.sizePts * 1.25f, weight = MsdfFont.WEIGHT_BOLD)
modifier
.textColor(fgColor)
.textRotation(270f)
.font(font)
.margin(top = UiSizes.baseSize)
.align(AlignmentX.Center, AlignmentY.Top)
}
}
}
fun spawnWindow(window: DemoWindow, dockPath: List<Pair<DockingHost.DockPosition, Dimension>>? = null) {
demoWindows += window
dockingHost.apply {
+window.windowSurface
if (dockPath != null) {
dockWindow(window.windowScope, dockPath)
} else {
window.windowScope.windowState.setWindowLocation(Dp(windowSpawnLocation.x), Dp(windowSpawnLocation.y))
windowSpawnLocation.x += 32f
windowSpawnLocation.y += 32f
if (windowSpawnLocation.y > 480f) {
windowSpawnLocation.y -= 416
windowSpawnLocation.x -= 384
if (windowSpawnLocation.x > 480f) {
windowSpawnLocation.x = 320f
}
}
}
}
window.windowSurface.bringToTop()
}
fun closeWindow(window: DemoWindow, ctx: KoolContext) {
dockingHost.undockWindow(window.windowScope)
dockingHost -= window.windowSurface
demoWindows -= window
window.windowSurface.dispose(ctx)
}
interface DemoWindow {
val windowSurface: UiSurface
val windowScope: WindowScope
}
}
|
apache-2.0
|
bc0b987ce2de91ffe46d98cd261ca34f
| 37.824427 | 145 | 0.623599 | 4.406412 | false | false | false | false |
dpisarenko/econsim-tr01
|
src/main/java/cc/altruix/econsimtr01/ch03/AgriculturalSimParametersProvider.kt
|
1
|
3660
|
/*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 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.
*
* econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01.ch03
import cc.altruix.econsimtr01.PlResource
import java.io.File
import java.util.*
/**
* Created by pisarenko on 14.05.2016.
*/
open class AgriculturalSimParametersProvider(file: File) :
PropertiesFileSimParametersProvider(file) {
companion object {
val RESOURCE_AREA_WITH_SEEDS = PlResource(
id = "R1",
name = "Area with seeds",
unit = "Square meters"
)
val RESOURCE_AREA_WITH_CROP = PlResource(
id = "R2",
name = "Area with crop",
unit = "Square meters"
)
val RESOURCE_EMPTY_AREA = PlResource(
id = "R3",
name = "Area with neither seeds, nor crop in it",
unit = "Square meters"
)
val RESOURCE_SEEDS = PlResource(
id = "R4",
name = "Seeds",
unit = "Kilograms"
)
}
override fun createValidators():
MutableMap<String, List<IPropertiesFileValueValidator>> {
val validators = HashMap<String, List<IPropertiesFileValueValidator>>()
validators["SimulationName"] = listOf(
ExistenceValidator,
NonBlankStringValidator
)
listOf(
"SizeOfField",
"NumberOfWorkers",
"Process1QuantityOfSeeds",
"Process1EffortInSquareMeters",
"Process2YieldPerSquareMeter",
"Process3EffortPerSquareMeter",
"LaborPerBusinessDay",
"InitialSeedQuantity"
).forEach { param ->
validators[param] = listOf(
ExistenceValidator,
NonBlankStringValidator,
NonZeroPositiveDoubleValueValidator
)
}
listOf(
"Process1Start",
"Process1End",
"Process2End",
"Process3End"
).forEach { param ->
validators[param] = listOf(
ExistenceValidator,
NonBlankStringValidator,
DayOfMonthValidator
)
}
return validators
}
override fun initAndValidate() {
super.initAndValidate()
if (validity.valid) {
agents.add(Farmers(this))
agents.add(Field(this))
val shack = Shack()
agents.add(shack)
agents.forEach { it.init() }
shack.put(AgriculturalSimParametersProvider.RESOURCE_SEEDS.id,
data["InitialSeedQuantity"].toString().toDouble())
}
}
}
|
gpl-3.0
|
df3095d8c41a0b4205bcaf130d5d2736
| 31.105263 | 79 | 0.570492 | 4.621212 | false | false | false | false |
siosio/intellij-community
|
platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/ModifiableModuleModelBridgeImpl.kt
|
1
|
12384
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.module
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleWithNameAlreadyExists
import com.intellij.openapi.module.impl.getModuleNameByFilePath
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.projectModel.ProjectModelBundle
import com.intellij.util.PathUtil
import com.intellij.util.containers.BidirectionalMap
import com.intellij.util.io.systemIndependentPath
import com.intellij.workspaceModel.ide.*
import com.intellij.workspaceModel.ide.impl.JpsEntitySourceFactory
import com.intellij.workspaceModel.ide.impl.legacyBridge.LegacyBridgeModifiableBase
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.mutableModuleMap
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableModuleModelBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import java.io.IOException
import java.nio.file.Path
internal class ModifiableModuleModelBridgeImpl(
private val project: Project,
private val moduleManager: ModuleManagerBridgeImpl,
diff: WorkspaceEntityStorageBuilder,
cacheStorageResult: Boolean = true
) : LegacyBridgeModifiableBase(diff, cacheStorageResult), ModifiableModuleModelBridge {
override fun getProject(): Project = project
private val myModulesToAdd = BidirectionalMap<String, ModuleBridge>()
private val myModulesToDispose = HashMap<String, ModuleBridge>()
private val myUncommittedModulesToDispose = ArrayList<ModuleBridge>()
private val currentModulesSet = moduleManager.modules.toMutableSet()
private val myNewNameToModule = BidirectionalMap<String, ModuleBridge>()
private val virtualFileManager: VirtualFileUrlManager = VirtualFileUrlManager.getInstance(project)
private var moduleGroupsAreModified = false
// TODO Add cache?
override fun getModules(): Array<Module> {
return currentModulesSet.toTypedArray()
}
override fun newModule(filePath: String, moduleTypeId: String): Module = newModule(filePath, moduleTypeId, null)
override fun newNonPersistentModule(moduleName: String, moduleTypeId: String): Module {
val moduleEntity = diff.addModuleEntity(
name = moduleName,
dependencies = listOf(ModuleDependencyItem.ModuleSourceDependency),
source = NonPersistentEntitySource
)
val module = moduleManager.createModule(moduleEntity.persistentId(), moduleName, null, entityStorageOnDiff, diff)
diff.mutableModuleMap.addMapping(moduleEntity, module)
myModulesToAdd[moduleName] = module
currentModulesSet.add(module)
module.init(null)
module.setModuleType(moduleTypeId)
return module
}
override fun newModule(filePath: String, moduleTypeId: String, options: MutableMap<String, String>?): Module {
// TODO Handle filePath, add correct iml source with a path
// TODO Must be in sync with module loading. It is not now
val canonicalPath = FileUtil.toSystemIndependentName(resolveShortWindowsName(filePath))
val existingModule = getModuleByFilePath(canonicalPath)
if (existingModule != null) {
return existingModule
}
val moduleName = getModuleNameByFilePath(canonicalPath)
if (findModuleByName(moduleName) != null) {
throw ModuleWithNameAlreadyExists("Module already exists: $moduleName", moduleName)
}
removeUnloadedModule(moduleName)
val entitySource = JpsEntitySourceFactory.createEntitySourceForModule(project, virtualFileManager.fromPath(PathUtil.getParentPath(canonicalPath)), null)
val moduleEntity = diff.addModuleEntity(
name = moduleName,
dependencies = listOf(ModuleDependencyItem.ModuleSourceDependency),
type = moduleTypeId,
source = entitySource
)
return createModuleInstance(moduleEntity, true)
}
private fun resolveShortWindowsName(filePath: String): String {
return try {
FileUtil.resolveShortWindowsName(filePath)
}
catch (ignored: IOException) {
filePath
}
}
private fun createModuleInstance(moduleEntity: ModuleEntity, isNew: Boolean): ModuleBridge {
val moduleInstance = moduleManager.createModuleInstance(moduleEntity, entityStorageOnDiff, diff = diff, isNew = isNew, null)
diff.mutableModuleMap.addMapping(moduleEntity, moduleInstance)
myModulesToAdd[moduleEntity.name] = moduleInstance
currentModulesSet.add(moduleInstance)
return moduleInstance
}
private fun getModuleByFilePath(filePath: String): ModuleBridge? {
for (module in modules) {
val sameFilePath = when (SystemInfo.isFileSystemCaseSensitive) {
true -> module.moduleFilePath == filePath
false -> module.moduleFilePath.equals(filePath, ignoreCase = true)
}
if (sameFilePath) {
return module as ModuleBridge
}
}
return null
}
private fun removeUnloadedModule(moduleName: String) {
// If module name equals to already unloaded module, the previous should be removed from store
val unloadedModuleDescription = moduleManager.getUnloadedModuleDescription(moduleName)
if (unloadedModuleDescription != null) {
val moduleEntity = entityStorageOnDiff.current.resolve(ModuleId(unloadedModuleDescription.name))
if (moduleEntity != null) {
diff.removeEntity(moduleEntity)
}
else {
LOG.error("Could not find module to remove by id: ${unloadedModuleDescription.name}")
}
}
}
override fun loadModule(file: Path) = loadModule(file.systemIndependentPath)
override fun loadModule(filePath: String): Module {
val moduleName = getModuleNameByFilePath(filePath)
if (findModuleByName(moduleName) != null) {
error("Module name '$moduleName' already exists. Trying to load module: $filePath")
}
removeUnloadedModule(moduleName)
val moduleEntity = moduleManager.loadModuleToBuilder(moduleName, filePath, diff)
return createModuleInstance(moduleEntity, false)
}
override fun disposeModule(module: Module) {
if (module.project.isDisposed()) {
//if the project is being disposed now, removing module won't work because WorkspaceModelImpl won't fire events and the module won't be disposed
//it looks like this may happen in tests only so it's ok to skip removal of the module since the project will be disposed anyway
return
}
module as ModuleBridge
if (findModuleByName(module.name) == null) {
LOG.error("Module '${module.name}' is not found. Probably it's already disposed.")
return
}
if (myModulesToAdd.containsValue(module)) {
myModulesToAdd.removeValue(module)
myUncommittedModulesToDispose.add(module)
}
currentModulesSet.remove(module)
myNewNameToModule.removeValue(module)
myModulesToDispose[module.name] = module
val moduleEntity = diff.findModuleEntity(module)
if (moduleEntity == null) {
LOG.error("Could not find module entity to remove by $module")
return
}
moduleEntity.dependencies
.asSequence()
.filterIsInstance<ModuleDependencyItem.Exportable.LibraryDependency>()
.filter { (it.library.tableId as? LibraryTableId.ModuleLibraryTableId)?.moduleId == module.moduleEntityId }
.mapNotNull { it.library.resolve(diff) }
.forEach {
diff.removeEntity(it)
}
diff.removeEntity(moduleEntity)
}
override fun findModuleByName(name: String): Module? {
val addedModule = myModulesToAdd[name]
if (addedModule != null) return addedModule
if (myModulesToDispose.containsKey(name)) return null
val newNameModule = myNewNameToModule[name]
if (newNameModule != null) return null
return moduleManager.findModuleByName(name)
}
override fun dispose() {
assertModelIsLive()
ApplicationManager.getApplication().assertWriteAccessAllowed()
for (moduleToAdd in myModulesToAdd.values) {
Disposer.dispose(moduleToAdd)
}
for (module in myUncommittedModulesToDispose) {
Disposer.dispose(module)
}
myModulesToAdd.clear()
myModulesToDispose.clear()
myNewNameToModule.clear()
}
override fun isChanged(): Boolean =
myModulesToAdd.isNotEmpty() ||
myModulesToDispose.isNotEmpty() ||
myNewNameToModule.isNotEmpty() ||
moduleGroupsAreModified
override fun commit() {
val diff = collectChanges()
WorkspaceModel.getInstance(project).updateProjectModel {
it.addDiff(diff)
}
}
override fun prepareForCommit() {
ApplicationManager.getApplication().assertWriteAccessAllowed()
myUncommittedModulesToDispose.forEach { module -> Disposer.dispose(module) }
}
override fun collectChanges(): WorkspaceEntityStorageBuilder {
prepareForCommit()
return diff
}
override fun renameModule(module: Module, newName: String) {
module as ModuleBridge
val oldModule = findModuleByName(newName)
val uncommittedOldName = myNewNameToModule.getKeysByValue(module)
myNewNameToModule.removeValue(module)
myNewNameToModule.remove(newName)
removeUnloadedModule(newName)
val oldName = uncommittedOldName ?: module.name
if (oldName != newName) { // if renaming to itself, forget it altogether
val moduleToAdd = myModulesToAdd.remove(oldName)
if (moduleToAdd != null) {
moduleToAdd.rename(newName, true)
myModulesToAdd[newName] = moduleToAdd
}
else {
myNewNameToModule[newName] = module
}
val entity = entityStorageOnDiff.current.findModuleEntity(module) ?: error("Unable to find module entity for $module")
diff.modifyEntity(ModifiableModuleEntity::class.java, entity) {
name = newName
}
}
if (oldModule != null) {
throw ModuleWithNameAlreadyExists(ProjectModelBundle.message("module.already.exists.error", newName), newName)
}
}
override fun getModuleToBeRenamed(newName: String): Module? = myNewNameToModule[newName]
override fun getNewName(module: Module): String? = myNewNameToModule.getKeysByValue(module as ModuleBridge)?.single()
override fun getActualName(module: Module): String = getNewName(module) ?: module.name
override fun getModuleGroupPath(module: Module): Array<String>? =
ModuleManagerBridgeImpl.getModuleGroupPath(module, entityStorageOnDiff)
override fun hasModuleGroups(): Boolean = ModuleManagerBridgeImpl.hasModuleGroups(entityStorageOnDiff)
override fun setModuleGroupPath(module: Module, groupPath: Array<out String>?) {
val storage = entityStorageOnDiff.current
val moduleEntity = storage.findModuleEntity(module as ModuleBridge) ?: error("Could not resolve module entity for $module")
val moduleGroupEntity = moduleEntity.groupPath
val groupPathList = groupPath?.toList()
// TODO How to deduplicate with ModuleCustomImlDataEntity ?
if (moduleGroupEntity?.path != groupPathList) {
when {
moduleGroupEntity == null && groupPathList != null -> diff.addModuleGroupPathEntity(
module = moduleEntity,
path = groupPathList,
source = moduleEntity.entitySource
)
moduleGroupEntity == null && groupPathList == null -> Unit
moduleGroupEntity != null && groupPathList == null -> diff.removeEntity(moduleGroupEntity)
moduleGroupEntity != null && groupPathList != null -> diff.modifyEntity(ModifiableModuleGroupPathEntity::class.java,
moduleGroupEntity) {
path = groupPathList
}
else -> error("Should not be reached")
}
moduleGroupsAreModified = true
}
}
companion object {
private val LOG = logger<ModifiableModuleModelBridgeImpl>()
}
}
|
apache-2.0
|
3c8d0bcd09fdf00bb2c1203549db7c09
| 37.340557 | 156 | 0.745317 | 5.223113 | false | false | false | false |
HenningLanghorst/fancy-kotlin-stuff
|
src/main/kotlin/de/henninglanghorst/kotlinstuff/ui/DefaultFieldDefinitions.kt
|
1
|
3550
|
package de.henninglanghorst.kotlinstuff.ui
import de.henninglanghorst.kotlinstuff.ui.dsl.datePicker
import de.henninglanghorst.kotlinstuff.ui.dsl.fieldDefinition
import de.henninglanghorst.kotlinstuff.ui.dsl.listener
import de.henninglanghorst.kotlinstuff.ui.dsl.textField
import javafx.scene.control.Control
import javafx.scene.control.Label
import javafx.scene.control.TextField
import javafx.scene.control.TextFormatter
import java.math.BigDecimal
import java.math.BigInteger
import java.time.LocalDate
import kotlin.reflect.full.createType
object DefaultFieldDefinitions : FieldDefinitions {
private val nullableString = String::class.createType(nullable = true)
private val nonNullString = String::class.createType(nullable = false)
private val nullableLocalDate = LocalDate::class.createType(nullable = true)
private val nullableInt = Int::class.createType(nullable = true)
private val nullableBigInteger = BigInteger::class.createType(nullable = true)
private val nullableBigDecimal = BigDecimal::class.createType(nullable = true)
private val nullableLong = Long::class.createType(nullable = true)
private val fieldDefinitions = listOf(
fieldDefinition(nullableInt) {
textField {
verifyConversion { it.toInt() }
listener { _, _, newValue -> value = newValue.toInt().takeIf { newValue.isNotEmpty() } }
}
},
fieldDefinition(nullableLong) {
textField {
verifyConversion { it.toLong() }
listener { _, _, newValue -> value = newValue.toLong().takeIf { newValue.isNotEmpty() } }
}
},
fieldDefinition(nullableString) {
textField {
listener { _, _, newValue -> value = newValue.takeIf { it.isNotEmpty() } }
}
},
fieldDefinition(nonNullString) {
textField {
listener { _, _, newValue -> value = newValue }
}
},
fieldDefinition(nullableBigInteger) {
textField {
verifyConversion { it.toBigInteger() }
listener { _, _, newValue -> value = newValue.toBigInteger().takeIf { newValue.isNotEmpty() } }
}
},
fieldDefinition(nullableBigDecimal) {
textField {
textField {
verifyConversion { it.toBigInteger() }
listener { _, _, newValue -> value = newValue.toBigDecimal().takeIf { newValue.isNotEmpty() } }
}
}
},
fieldDefinition(nullableLocalDate) {
datePicker {
listener { _, _, newValue -> value = newValue }
}
}
)
private fun TextField.verifyConversion(tryToConvert: (String) -> Unit) {
textFormatter = TextFormatter<String> {
try {
tryToConvert(it.controlNewText)
it
} catch (e: NumberFormatException) {
null
}
}
}
override fun createControl(constructorParameter: ConstructorParameter): Control {
return fieldDefinitions.firstOrNull { it.type == constructorParameter.parameter.type }
?.createControl(constructorParameter)
?: Label("Unsupported type: ${constructorParameter.parameter.type}")
}
}
|
apache-2.0
|
9141da409e8297bbc2fc822c457a5e0f
| 38.898876 | 119 | 0.587042 | 5.314371 | false | false | false | false |
BijoySingh/Quick-Note-Android
|
base/src/main/java/com/maubis/scarlet/base/note/actions/TextToSpeechBottomSheet.kt
|
1
|
2852
|
package com.maubis.scarlet.base.note.actions
import android.app.Dialog
import android.speech.tts.TextToSpeech
import android.widget.ImageView
import android.widget.TextView
import com.maubis.markdown.Markdown
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme
import com.maubis.scarlet.base.database.room.note.Note
import com.maubis.scarlet.base.note.getFullText
import com.maubis.scarlet.base.support.ui.ThemeColorType
import com.maubis.scarlet.base.support.ui.ThemedActivity
import com.maubis.scarlet.base.support.ui.ThemedBottomSheetFragment
import com.maubis.scarlet.base.support.utils.removeMarkdownHeaders
fun Note.getTextToSpeechText(): String {
val builder = StringBuilder()
builder.append(Markdown.render(removeMarkdownHeaders(getFullText())), true)
return builder.toString().trim { it <= ' ' }
}
class TextToSpeechBottomSheet : ThemedBottomSheetFragment() {
var note: Note? = null
var textToSpeech: TextToSpeech? = null
override fun setupView(dialog: Dialog?) {
super.setupView(dialog)
if (dialog == null || note == null) {
return
}
val nonNullNote = note!!
val title = dialog.findViewById<TextView>(R.id.options_title)
title.setTextColor(sAppTheme.get(ThemeColorType.SECONDARY_TEXT))
val speakPlayPause = dialog.findViewById<ImageView>(R.id.speak_play_pause)
speakPlayPause.setColorFilter(sAppTheme.get(ThemeColorType.TOOLBAR_ICON))
speakPlayPause.setOnClickListener {
val tts = textToSpeech
if (tts === null) {
return@setOnClickListener
}
when {
tts.isSpeaking -> {
tts.stop()
speakPlayPause.setImageResource(R.drawable.ic_action_play_sound)
}
else -> {
speak(nonNullNote)
speakPlayPause.setImageResource(R.drawable.ic_action_stop)
}
}
}
textToSpeech = TextToSpeech(themedContext(), TextToSpeech.OnInitListener {
speak(nonNullNote)
speakPlayPause.setImageResource(R.drawable.ic_action_stop)
})
makeBackgroundTransparent(dialog, R.id.root_layout)
}
private fun speak(note: Note) {
textToSpeech?.speak(note.getTextToSpeechText(), TextToSpeech.QUEUE_FLUSH, null, "NOTE")
}
override fun getBackgroundView(): Int = R.id.container_layout
override fun getBackgroundCardViewIds(): Array<Int> = arrayOf(R.id.speak_note_card)
override fun getLayout(): Int = R.layout.bottom_sheet_speak_note
override fun onPause() {
super.onPause()
textToSpeech?.stop()
}
override fun onDestroy() {
super.onDestroy()
textToSpeech?.shutdown()
}
companion object {
fun openSheet(activity: ThemedActivity, note: Note) {
val sheet = TextToSpeechBottomSheet()
sheet.note = note
sheet.show(activity.supportFragmentManager, sheet.tag)
}
}
}
|
gpl-3.0
|
974e3e16061005409a7457b66988ffa2
| 30.01087 | 91 | 0.722651 | 4.133333 | false | false | false | false |
jwren/intellij-community
|
platform/feedback/src/com/intellij/feedback/common/OpenApplicationFeedbackResolver.kt
|
1
|
2773
|
// 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.feedback.common
import com.intellij.feedback.common.bundle.CommonFeedbackBundle
import com.intellij.feedback.common.notification.RequestFeedbackNotification
import com.intellij.feedback.kotlinRejecters.bundle.KotlinRejectersFeedbackBundle
import com.intellij.feedback.kotlinRejecters.dialog.KotlinRejectersFeedbackDialog
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.feedback.kotlinRejecters.state.KotlinRejectersInfoService
import com.intellij.notification.NotificationAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDate
import kotlinx.datetime.TimeZone
import kotlinx.datetime.todayAt
class OpenApplicationFeedbackShower : AppLifecycleListener {
companion object {
val LAST_DATE_COLLECT_FEEDBACK = LocalDate(2022, 5, 31)
const val MAX_NUMBER_NOTIFICATION_SHOWED = 3
fun showNotification(project: Project?, forTest: Boolean) {
val notification = RequestFeedbackNotification(
KotlinRejectersFeedbackBundle.message("notification.kotlin.feedback.request.feedback.title"),
KotlinRejectersFeedbackBundle.message("notification.kotlin.feedback.request.feedback.content")
)
notification.addAction(
NotificationAction.createSimpleExpiring(CommonFeedbackBundle.message("notification.request.feedback.action.respond.text")) {
val dialog = KotlinRejectersFeedbackDialog(project, forTest)
dialog.show()
}
)
notification.notify(project)
notification.addAction(
NotificationAction.createSimpleExpiring(CommonFeedbackBundle.message("notification.request.feedback.action.dont.show.text")) {
if (!forTest) {
IdleFeedbackTypeResolver.isFeedbackNotificationDisabled = true
}
}
)
}
}
override fun appStarted() {
//Try to show only one possible feedback form - Kotlin Rejecters form
val kotlinRejectersInfoState = KotlinRejectersInfoService.getInstance().state
if (!kotlinRejectersInfoState.feedbackSent && kotlinRejectersInfoState.showNotificationAfterRestart &&
LAST_DATE_COLLECT_FEEDBACK >= Clock.System.todayAt(TimeZone.currentSystemDefault()) &&
!IdleFeedbackTypeResolver.isFeedbackNotificationDisabled &&
kotlinRejectersInfoState.numberNotificationShowed <= MAX_NUMBER_NOTIFICATION_SHOWED) {
val project = ProjectManagerEx.getInstance().openProjects.firstOrNull()
kotlinRejectersInfoState.numberNotificationShowed += 1
showNotification(project, false)
}
}
}
|
apache-2.0
|
a2caf5bea148de98fe8803653956781a
| 46.827586 | 136 | 0.775334 | 5.051002 | false | true | false | false |
SimpleMobileTools/Simple-Gallery
|
app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/IncludedFoldersActivity.kt
|
1
|
2087
|
package com.simplemobiletools.gallery.pro.activities
import android.os.Bundle
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.getProperTextColor
import com.simplemobiletools.commons.helpers.NavigationIcon
import com.simplemobiletools.commons.interfaces.RefreshRecyclerViewListener
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.adapters.ManageFoldersAdapter
import com.simplemobiletools.gallery.pro.extensions.config
import kotlinx.android.synthetic.main.activity_manage_folders.*
class IncludedFoldersActivity : SimpleActivity(), RefreshRecyclerViewListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_manage_folders)
updateFolders()
setupOptionsMenu()
manage_folders_toolbar.title = getString(R.string.include_folders)
}
override fun onResume() {
super.onResume()
setupToolbar(manage_folders_toolbar, NavigationIcon.Arrow)
}
private fun updateFolders() {
val folders = ArrayList<String>()
config.includedFolders.mapTo(folders) { it }
manage_folders_placeholder.apply {
text = getString(R.string.included_activity_placeholder)
beVisibleIf(folders.isEmpty())
setTextColor(getProperTextColor())
}
val adapter = ManageFoldersAdapter(this, folders, false, this, manage_folders_list) {}
manage_folders_list.adapter = adapter
}
private fun setupOptionsMenu() {
manage_folders_toolbar.setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.add_folder -> addFolder()
else -> return@setOnMenuItemClickListener false
}
return@setOnMenuItemClickListener true
}
}
override fun refreshItems() {
updateFolders()
}
private fun addFolder() {
showAddIncludedFolderDialog {
updateFolders()
}
}
}
|
gpl-3.0
|
b1531289f135e40b1226a1f6921e0b19
| 34.372881 | 94 | 0.703881 | 5.102689 | false | false | false | false |
androidx/androidx
|
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/viewinterop/NestedScrollInteropConnectionTest.kt
|
3
|
13859
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.viewinterop
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.ModifierLocalNestedScroll
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.modifier.modifierLocalProvider
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.R
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.test.swipeDown
import androidx.compose.ui.test.swipeUp
import androidx.compose.ui.test.swipeWithVelocity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.swipeUp
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import kotlin.math.abs
import org.hamcrest.Matchers.not
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
class NestedScrollInteropConnectionTest {
@get:Rule
val rule = createAndroidComposeRule<ComponentActivity>()
private val deltaCollectorNestedScrollConnection = InspectableNestedScrollConnection()
private val nestedScrollParentView by lazy {
rule.activity.findViewById<TestNestedScrollParentView>(R.id.main_layout)
}
private val items = (1..300).map { it.toString() }
private val topItemTag = items.first()
private val appBarExpandedSize = 240.dp
private val appBarCollapsedSize = 54.dp
private val appBarScrollDelta = appBarExpandedSize - appBarCollapsedSize
private val completelyCollapsedScroll = 600.dp
@Before
fun setUp() {
deltaCollectorNestedScrollConnection.reset()
}
@Test
fun swipeComposeScrollable_insideNestedScrollingParentView_shouldScrollViewToo() {
// arrange
createViewComposeActivity { TestListWithNestedScroll(items) }
// act: scroll compose side
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeUp()
}
// assert: compose list is scrolled
rule.onNodeWithTag(topItemTag).assertDoesNotExist()
// assert: toolbar is collapsed
onView(withId(R.id.fab)).check(matches(not(isDisplayed())))
}
@Test
fun swipeComposeScrollable_insideNestedScrollingParentView_shouldPropagateConsumedDelta() {
// arrange
createViewComposeActivity {
TestListWithNestedScroll(
items,
Modifier.nestedScroll(deltaCollectorNestedScrollConnection)
)
}
// act: small scroll, everything will be consumed by view side
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeWithVelocity(
start = center,
end = Offset(center.x, center.y + 100),
endVelocity = 0f
)
}
// assert: check delta on view side
rule.runOnIdle {
assertThat(
abs(
nestedScrollParentView.offeredToParentOffset.y -
deltaCollectorNestedScrollConnection.offeredFromChild.y
)
).isAtMost(ScrollRoundingErrorTolerance)
assertThat(deltaCollectorNestedScrollConnection.consumedDownChain)
.isEqualTo(Offset.Zero)
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Test
fun swipeNoOpComposeScrollable_insideNestedScrollingParentView_shouldNotScrollView() {
// arrange
createViewComposeActivity {
TestListWithNestedScroll(
items, Modifier.modifierLocalProvider(ModifierLocalNestedScroll) { null })
}
// act: scroll compose side
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeUp()
}
// assert: compose list is scrolled
rule.onNodeWithTag(topItemTag).assertDoesNotExist()
// assert: toolbar not collapsed
onView(withId(R.id.fab)).check(matches(isDisplayed()))
}
@Test
fun swipeTurnOffNestedInterop_insideNestedScrollingParentView_shouldNotScrollView() {
// arrange
createViewComposeActivity(enableInterop = false) { TestListWithNestedScroll(items) }
// act: scroll compose side
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeUp()
}
// assert: compose list is scrolled
rule.onNodeWithTag(topItemTag).assertDoesNotExist()
// assert: toolbar not collapsed
onView(withId(R.id.fab)).check(matches(isDisplayed()))
}
@Test
fun swipeComposeUpAndDown_insideNestedScrollingParentView_shouldPutViewToStartingPosition() {
// arrange
createViewComposeActivity { TestListWithNestedScroll(items) }
// act: scroll compose side
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeUp()
swipeDown()
}
// assert: compose list is scrolled
rule.onNodeWithTag(topItemTag).assertIsDisplayed()
// assert: toolbar is collapsed
onView(withId(R.id.fab)).check(matches(isDisplayed()))
}
@Test
fun swipeComposeScrollable_byAppBarSize_shouldCollapseToolbar() {
// arrange
createViewComposeActivity { TestListWithNestedScroll(items) }
// act: scroll compose side by the height of the toolbar
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeWithVelocity(
start = center,
end = Offset(center.x, center.y - appBarExpandedSize.roundToPx()),
endVelocity = 0f
)
}
// assert: compose list is scrolled just enough to collapse toolbar
rule.onNodeWithTag(topItemTag).assertIsDisplayed()
// assert: toolbar is collapsed
onView(withId(R.id.fab)).check(matches(not(isDisplayed())))
}
@Test
fun swipeNestedScrollingParentView_hasComposeScrollable_shouldNotScrollElement() {
// arrange
createViewComposeActivity { TestListWithNestedScroll(items) }
// act
onView(withId(R.id.app_bar)).perform(click(), swipeUp())
// assert: toolbar is collapsed
onView(withId(R.id.fab)).check(matches(not(isDisplayed())))
// assert: compose list is not scrolled
rule.onNodeWithTag(topItemTag).assertIsDisplayed()
}
@Test
fun swipeComposeScrollable_insideNestedScrollingParentView_shouldPropagateCorrectPreDelta() {
// arrange
createViewComposeActivity {
TestListWithNestedScroll(
items,
Modifier.nestedScroll(deltaCollectorNestedScrollConnection)
)
}
// act: split scroll, some will be consumed by view and the rest by compose
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeWithVelocity(
start = center,
end = Offset(center.x, center.y - completelyCollapsedScroll.roundToPx()),
endVelocity = 0f
)
}
// assert: check that compose presented the correct delta values to view
rule.runOnIdle {
val appBarScrollDeltaPixels = appBarScrollDelta.value * rule.density.density * -1
val offeredToParent = nestedScrollParentView.offeredToParentOffset.y
val availableToParent = deltaCollectorNestedScrollConnection.offeredFromChild.y +
appBarScrollDeltaPixels
assertThat(offeredToParent - availableToParent).isAtMost(ScrollRoundingErrorTolerance)
}
}
@Test
fun swipingComposeScrollable_insideNestedScrollingParentView_shouldPropagateCorrectPostDelta() {
// arrange
createViewComposeActivity {
TestListWithNestedScroll(
items,
Modifier.nestedScroll(deltaCollectorNestedScrollConnection)
)
}
// act: split scroll, some will be consumed by view rest by compose
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeWithVelocity(
start = center,
end = Offset(center.x, center.y - completelyCollapsedScroll.roundToPx()),
endVelocity = 0f
)
}
// assert: check that whatever that is unconsumed by view was consumed by children
val unconsumedInView = nestedScrollParentView.unconsumedOffset.round().y
val consumedByChildren = deltaCollectorNestedScrollConnection.consumedDownChain.round().y
rule.runOnIdle {
assertThat(abs(unconsumedInView - consumedByChildren))
.isAtMost(ScrollRoundingErrorTolerance)
}
}
@Test
fun swipeComposeScrollable_insideNestedScrollParentView_shouldPropagateCorrectPreVelocity() {
// arrange
createViewComposeActivity {
TestListWithNestedScroll(
items,
Modifier.nestedScroll(deltaCollectorNestedScrollConnection)
)
}
// act: split scroll, some will be consumed by view rest by compose
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeUp(
startY = center.y,
endY = center.y - completelyCollapsedScroll.roundToPx(),
durationMillis = 200
)
}
// assert: check that whatever that is unconsumed by view was consumed by children
val velocityOfferedInView = abs(nestedScrollParentView.velocityOfferedToParentOffset.y)
val velocityAvailableInCompose =
abs(deltaCollectorNestedScrollConnection.velocityOfferedFromChild.y)
rule.runOnIdle {
assertThat(velocityOfferedInView - velocityAvailableInCompose).isEqualTo(
VelocityRoundingErrorTolerance
)
}
}
@Test
fun swipeComposeScrollable_insideNestedScrollParentView_shouldPropagateCorrectPostVelocity() {
// arrange
createViewComposeActivity {
TestListWithNestedScroll(
items,
Modifier.nestedScroll(deltaCollectorNestedScrollConnection)
)
}
// act: split scroll, some will be consumed by view rest by compose
rule.onNodeWithTag(MainListTestTag).performTouchInput {
swipeUp(
startY = center.y,
endY = center.y - completelyCollapsedScroll.roundToPx(),
durationMillis = 200
)
}
// assert: check that whatever that is unconsumed by view was consumed by children
val velocityUnconsumedOffset = abs(nestedScrollParentView.velocityUnconsumedOffset.y)
val velocityConsumedByChildren =
abs(deltaCollectorNestedScrollConnection.velocityConsumedDownChain.y)
rule.runOnIdle {
assertThat(abs(velocityUnconsumedOffset - velocityConsumedByChildren)).isAtMost(
VelocityRoundingErrorTolerance
)
}
}
@OptIn(ExperimentalComposeUiApi::class)
private fun createViewComposeActivity(
enableInterop: Boolean = true,
content: @Composable () -> Unit
) {
rule
.activityRule
.scenario
.createActivityWithComposeContent(
layout = R.layout.test_nested_scroll_coordinator_layout,
enableInterop = enableInterop,
content = content
)
}
}
private const val ScrollRoundingErrorTolerance = 10
private const val VelocityRoundingErrorTolerance = 0
private const val MainListTestTag = "MainListTestTag"
@Composable
private fun TestListWithNestedScroll(items: List<String>, modifier: Modifier = Modifier) {
Box(modifier) {
LazyColumn(Modifier.testTag(MainListTestTag)) {
items(items) { TestItem(it) }
}
}
}
@Composable
private fun TestItem(item: String) {
Box(
modifier = Modifier
.padding(16.dp)
.height(56.dp)
.fillMaxWidth()
.testTag(item), contentAlignment = Alignment.Center
) {
BasicText(item)
}
}
|
apache-2.0
|
1f87cb5d107cdef70e2149f888f1ad41
| 35.567282 | 100 | 0.679342 | 5.225867 | false | true | false | false |
androidx/androidx
|
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/HorizontalPageIndicator.kt
|
3
|
16515
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.compose.material
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.wear.compose.foundation.CurvedDirection
import androidx.wear.compose.foundation.CurvedLayout
import androidx.wear.compose.foundation.curvedComposable
import androidx.wear.compose.material.PageIndicatorDefaults.MaxNumberOfIndicators
import java.lang.Integer.min
import kotlin.math.abs
/**
* A horizontal indicator for a Pager, representing
* the currently active page and total pages drawn using a [Shape]. It shows up to 6 pages
* on the screen and doesn't represent the exact page index if there are more than 6 pages.
* Instead of showing the exact position, [HorizontalPageIndicator] shows a half-size indicator
* on the left or on the right if there are more pages.
*
* Here's how different positions 0..10 might be visually represented:
* "X" is selected item, "O" and "o" full and half size items respectively.
*
* O X O O O o - 2nd position out of 10. There are no more items on the left but more on the right
* o O O O X o - might be 6, 7 or 8 out of 10, as there are more possible items
* on the left and on the right
* o O O O X O - is 9 out of 10, as there're no more items on the right
*
* [HorizontalPageIndicator] may be linear or curved, depending on [indicatorStyle]. By default
* it depends on the screen shape of the device - for circular screens it will be curved,
* whilst for square screens it will be linear.
*
* This component also allows customising the [indicatorShape], which defines how the
* indicator is visually represented.
*
* @sample androidx.wear.compose.material.samples.HorizontalPageIndicatorSample
*
* @param pageIndicatorState The state object of a [HorizontalPageIndicator] to be used to
* observe the Pager's state.
* @param modifier Modifier to be applied to the [HorizontalPageIndicator]
* @param indicatorStyle The style of [HorizontalPageIndicator] - may be linear or curved.
* By default determined by the screen shape.
* @param selectedColor The color of the selected [HorizontalPageIndicator] item
* @param unselectedColor The color of unselected [HorizontalPageIndicator] items.
* Defaults to [selectedColor] with 30% alpha
* @param indicatorSize The size of each [HorizontalPageIndicator] item in [Dp]
* @param spacing The spacing between indicator items in [Dp]
* @param indicatorShape The shape of each [HorizontalPageIndicator] item.
* Defaults to [CircleShape]
**/
@Composable
public fun HorizontalPageIndicator(
pageIndicatorState: PageIndicatorState,
modifier: Modifier = Modifier,
indicatorStyle: PageIndicatorStyle = PageIndicatorDefaults.style(),
selectedColor: Color = MaterialTheme.colors.onBackground,
unselectedColor: Color = selectedColor.copy(alpha = 0.3f),
indicatorSize: Dp = 6.dp,
spacing: Dp = 4.dp,
indicatorShape: Shape = CircleShape
) {
// We want to bring offset to 0..1 range.
// However, it can come in any range. It might be for example selectedPage = 1, with offset 2.5
// We can't work with these offsets, thus should normalize them so that offset will be
// in 0..1 range. For example selectedPage = 3, offset = -1.5 -> could transform it
// to selectedPage = 1, offset = 0.5
// Other example: selectedPage = 1, offset = 2.5 -> selectedPage = 3, offset = 0.5
val normalizedSelectedPage: Int =
(pageIndicatorState.selectedPage + pageIndicatorState.pageOffset).toInt()
val normalizedOffset =
pageIndicatorState.selectedPage + pageIndicatorState.pageOffset - normalizedSelectedPage
val horizontalPadding = spacing / 2
val spacerDefaultSize = (indicatorSize + spacing).value
val pagesOnScreen = min(MaxNumberOfIndicators, pageIndicatorState.pageCount)
val pagesState = remember(pageIndicatorState.pageCount) {
PagesState(
totalPages = pageIndicatorState.pageCount,
pagesOnScreen = pagesOnScreen
)
}
pagesState.recalculateState(normalizedSelectedPage, normalizedOffset)
val indicatorFactory: @Composable (Int) -> Unit = { page ->
// An external box with a fixed indicatorSize - let us remain the same size for
// an indicator even if it's shrinked for smooth animations
Box(
modifier = Modifier
.padding(horizontal = horizontalPadding)
.size(indicatorSize)
) {
Box(
modifier = Modifier
.fillMaxSize()
.align(Alignment.Center)
.scale(pagesState.sizeRatio(page))
.clip(indicatorShape)
.alpha(pagesState.alpha(page))
// Interpolation between unselected and selected colors depending
// on selectedPageRatio
.background(
lerp(
unselectedColor, selectedColor,
pagesState.calculateSelectedRatio(page, normalizedOffset)
)
)
)
}
}
val spacerLeft = @Composable {
Spacer(
Modifier.width((pagesState.leftSpacerSizeRatio * spacerDefaultSize).dp)
.height(indicatorSize)
)
}
val spacerRight = @Composable {
Spacer(
Modifier.width((pagesState.rightSpacerSizeRatio * spacerDefaultSize).dp)
.height(indicatorSize)
)
}
when (indicatorStyle) {
PageIndicatorStyle.Linear -> {
LinearPageIndicator(
modifier = modifier,
pagesOnScreen = pagesOnScreen,
indicatorFactory = indicatorFactory,
spacerLeft = spacerLeft,
spacerRight = spacerRight
)
}
PageIndicatorStyle.Curved -> {
CurvedPageIndicator(
modifier = modifier,
pagesOnScreen = pagesOnScreen,
indicatorFactory = indicatorFactory,
spacerLeft = spacerLeft,
spacerRight = spacerRight
)
}
}
}
/**
* The style of [HorizontalPageIndicator]. May be Curved or Linear
*/
@kotlin.jvm.JvmInline
public value class PageIndicatorStyle internal constructor(internal val value: Int) {
companion object {
/**
* Curved style of [HorizontalPageIndicator]
*/
public val Curved = PageIndicatorStyle(0)
/**
* Linear style of [HorizontalPageIndicator]
*/
public val Linear = PageIndicatorStyle(1)
}
}
/**
* Contains the default values used by [HorizontalPageIndicator]
*/
public object PageIndicatorDefaults {
/**
* Default style of [HorizontalPageIndicator]. Depending on shape of device, it returns either Curved
* or Linear style.
*/
@Composable
public fun style(): PageIndicatorStyle =
if (isRoundDevice()) PageIndicatorStyle.Curved
else PageIndicatorStyle.Linear
internal val MaxNumberOfIndicators = 6
}
/**
* An interface for connection between Pager and [HorizontalPageIndicator].
*/
public interface PageIndicatorState {
/**
* The current offset from the start of [selectedPage], as a ratio of the page width.
*
* Changes when a scroll (drag, swipe or fling) between pages happens in Pager.
*/
public val pageOffset: Float
/**
* The currently selected page index
*/
public val selectedPage: Int
/**
* Total number of pages
*/
public val pageCount: Int
}
@Composable
private fun LinearPageIndicator(
modifier: Modifier,
pagesOnScreen: Int,
indicatorFactory: @Composable (Int) -> Unit,
spacerLeft: @Composable () -> Unit,
spacerRight: @Composable () -> Unit
) {
Row(
modifier = modifier.fillMaxSize(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.Bottom
) {
// drawing 1 extra spacer for transition
spacerLeft()
for (page in 0..pagesOnScreen) {
indicatorFactory(page)
}
spacerRight()
}
}
@Composable
private fun CurvedPageIndicator(
modifier: Modifier,
pagesOnScreen: Int,
indicatorFactory: @Composable (Int) -> Unit,
spacerLeft: @Composable () -> Unit,
spacerRight: @Composable () -> Unit
) {
CurvedLayout(
modifier = modifier,
// 90 degrees equals to 6 o'clock position, at the bottom of the screen
anchor = 90f,
// Since Swipe to dismiss is always LtR, we want to follow the same direction when
// navigating amongst pages, so the first page is always on the left.
angularDirection = CurvedDirection.Angular.CounterClockwise
) {
// drawing 1 extra spacer for transition
curvedComposable {
spacerLeft()
}
for (page in 0..pagesOnScreen) {
curvedComposable {
indicatorFactory(page)
}
}
curvedComposable {
spacerRight()
}
}
}
/**
* Represents an internal state of pageIndicator
*/
internal class PagesState(
val totalPages: Int,
val pagesOnScreen: Int
) {
// Sizes and alphas of first and last indicators on the screen. Used to show that there're more
// pages on the left or on the right, and also for smooth transitions
private var firstAlpha = 1f
private var lastAlpha = 0f
private var firstSize = 1f
private var secondSize = 1f
private var lastSize = 1f
private var lastButOneSize = 1f
private var smoothProgress = 0f
// An offset in pages, basically meaning how many pages are hidden to the left.
private var hiddenPagesToTheLeft = 0
// A default size of spacers - invisible items to the left and to the right of
// visible indicators, used for smooth transitions
// Current visible position on the screen.
private var visibleDotIndex = 0
// A size of a left spacer used for smooth transitions
val leftSpacerSizeRatio
get() = 1 - smoothProgress
// A size of a right spacer used for smooth transitions
val rightSpacerSizeRatio
get() = smoothProgress
/**
* Depending on the page index, return an alpha for this indicator
*
* @param page Page index
* @return An alpha of page index- in range 0..1
*/
fun alpha(page: Int): Float =
when (page) {
0 -> firstAlpha
pagesOnScreen -> lastAlpha
else -> 1f
}
/**
* Depending on the page index, return a size ratio for this indicator
*
* @param page Page index
* @return An size ratio for page index - in range 0..1
*/
fun sizeRatio(page: Int): Float =
when (page) {
0 -> firstSize
1 -> secondSize
pagesOnScreen - 1 -> lastButOneSize
pagesOnScreen -> lastSize
else -> 1f
}
/**
* Returns a value in the range 0..1 where 0 is unselected state, and 1 is selected.
* Used to show a smooth transition between page indicator items.
*/
fun calculateSelectedRatio(targetPage: Int, offset: Float): Float =
(1 - abs(visibleDotIndex + offset - targetPage)).coerceAtLeast(0f)
// Main function responsible for recalculation of all parameters regarding
// to the [selectedPage] and [offset]
fun recalculateState(selectedPage: Int, offset: Float) {
val pageWithOffset = selectedPage + offset
// Calculating offsetInPages relating to the [selectedPage].
// For example, for [selectedPage] = 4 we will see this picture :
// O O O O X o. [offsetInPages] will be 0.
// But when [selectedPage] will be incremented to 5, it will be seen as
// o O O O X o, with [offsetInPages] = 1
if (selectedPage > hiddenPagesToTheLeft + pagesOnScreen - 2) {
// Set an offset as a difference between current page and pages on the screen,
// except if this is not the last page - then offsetInPages is not changed
hiddenPagesToTheLeft = (selectedPage - (pagesOnScreen - 2))
.coerceAtMost(totalPages - pagesOnScreen)
} else if (pageWithOffset <= hiddenPagesToTheLeft) {
hiddenPagesToTheLeft = (selectedPage - 1).coerceAtLeast(0)
}
// Condition for scrolling to the right. A smooth scroll to the right is only triggered
// when we have more than 2 pages to the right, and currently we're on the right edge.
// For example -> o O O O X o -> a small "o" shows that there're more pages to the right
val scrolledToTheRight = pageWithOffset > hiddenPagesToTheLeft + pagesOnScreen - 2 &&
pageWithOffset < totalPages - 2
// Condition for scrolling to the left. A smooth scroll to the left is only triggered
// when we have more than 2 pages to the left, and currently we're on the left edge.
// For example -> o X O O O o -> a small "o" shows that there're more pages to the left
val scrolledToTheLeft = pageWithOffset > 1 && pageWithOffset < hiddenPagesToTheLeft + 1
smoothProgress = if (scrolledToTheLeft || scrolledToTheRight) offset else 0f
// Calculating exact parameters for border indicators like [firstAlpha], [lastSize], etc.
firstAlpha = 1 - smoothProgress
lastAlpha = smoothProgress
secondSize = 1 - 0.5f * smoothProgress
// Depending on offsetInPages we'll either show a shrinked first indicator, or full-size
firstSize = if (hiddenPagesToTheLeft == 0 ||
hiddenPagesToTheLeft == 1 && scrolledToTheLeft
) {
1 - smoothProgress
} else {
0.5f * (1 - smoothProgress)
}
// Depending on offsetInPages and other parameters, we'll either show a shrinked
// last indicator, or full-size
lastSize =
if (hiddenPagesToTheLeft == totalPages - pagesOnScreen - 1 && scrolledToTheRight ||
hiddenPagesToTheLeft == totalPages - pagesOnScreen && scrolledToTheLeft
) {
smoothProgress
} else {
0.5f * smoothProgress
}
lastButOneSize = if (scrolledToTheRight || scrolledToTheLeft) {
0.5f * (1 + smoothProgress)
} else if (hiddenPagesToTheLeft < totalPages - pagesOnScreen) 0.5f else 1f
// A visibleDot represents a currently selected page on the screen
// As we scroll to the left, we add an invisible indicator to the left, shifting all other
// indicators to the right. The shift is only possible when a visibleDot = 1,
// thus we have to leave it at 1 as we always add a positive offset
visibleDotIndex = if (scrolledToTheLeft) 1
else selectedPage - hiddenPagesToTheLeft
}
}
|
apache-2.0
|
06a169b77110a96f4445525fd158ef63
| 37.143187 | 105 | 0.6637 | 4.637742 | false | false | false | false |
androidx/androidx
|
compose/ui/ui-graphics/src/androidAndroidTest/kotlin/androidx/compose/ui/graphics/AndroidCanvasTest.kt
|
3
|
22118
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.ColorMatrixColorFilter
import android.graphics.LightingColorFilter
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.compose.testutils.captureToImage
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import org.junit.Assert.assertTrue
@MediumTest
@RunWith(AndroidJUnit4::class)
class AndroidCanvasTest {
@Suppress("DEPRECATION")
@get:Rule
val activityTestRule = androidx.test.rule.ActivityTestRule<TestActivity>(
TestActivity::class.java
)
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.O)
@Test
fun testEnableDisableZ() {
val activity = activityTestRule.activity
activity.hasFocusLatch.await(5, TimeUnit.SECONDS)
val drawLatch = CountDownLatch(1)
var groupView: ViewGroup? = null
activityTestRule.runOnUiThread {
val group = EnableDisableZViewGroup(drawLatch, activity)
groupView = group
group.setBackgroundColor(android.graphics.Color.WHITE)
group.layoutParams = ViewGroup.LayoutParams(12, 12)
val child = View(activity)
val childLayoutParams = FrameLayout.LayoutParams(10, 10)
childLayoutParams.gravity = Gravity.TOP or Gravity.LEFT
child.layoutParams = childLayoutParams
child.elevation = 4f
child.setBackgroundColor(android.graphics.Color.WHITE)
group.addView(child)
activity.setContentView(group)
}
assertTrue(drawLatch.await(1, TimeUnit.SECONDS))
// Not sure why this test is flaky, so this is just going to make sure that
// the drawn content can get onto the screen before we capture the bitmap.
activityTestRule.runOnUiThread { }
val bitmap = groupView!!.captureToImage().asAndroidBitmap()
assertEquals(android.graphics.Color.WHITE, bitmap.getPixel(0, 0))
assertEquals(android.graphics.Color.WHITE, bitmap.getPixel(9, 9))
assertNotEquals(android.graphics.Color.WHITE, bitmap.getPixel(10, 10))
}
@Test
fun testScaleWithDefaultPivot() {
val bg = androidx.compose.ui.graphics.Color.Red
val fg = androidx.compose.ui.graphics.Color.Blue
val width = 200
val height = 200
val imageBitmap = ImageBitmap(width, height)
val canvas = Canvas(imageBitmap)
val paint = Paint().apply { this.color = bg }
val rect = Rect(Offset.Zero, Size(width.toFloat(), height.toFloat()))
with(canvas) {
drawRect(rect, paint)
withSave {
scale(0.5f, 0.5f)
paint.color = fg
drawRect(rect, paint)
}
}
val pixelMap = imageBitmap.toPixelMap()
assertEquals(fg, pixelMap[0, 0])
assertEquals(fg, pixelMap[99, 0])
assertEquals(fg, pixelMap[0, 99])
assertEquals(fg, pixelMap[99, 99])
assertEquals(bg, pixelMap[0, 100])
assertEquals(bg, pixelMap[100, 0])
assertEquals(bg, pixelMap[100, 100])
assertEquals(bg, pixelMap[100, 99])
assertEquals(bg, pixelMap[99, 100])
}
@Test
fun testScaleWithCenterPivot() {
val bg = androidx.compose.ui.graphics.Color.Red
val fg = androidx.compose.ui.graphics.Color.Blue
val width = 200
val height = 200
val imageBitmap = ImageBitmap(width, height)
val canvas = Canvas(imageBitmap)
val paint = Paint().apply { this.color = bg }
val rect = Rect(Offset(0.0f, 0.0f), Size(width.toFloat(), height.toFloat()))
with(canvas) {
drawRect(rect, paint)
withSave {
scale(0.5f, 0.5f, width / 2.0f, height / 2.0f)
paint.color = fg
drawRect(rect, paint)
}
}
val pixelMap = imageBitmap.toPixelMap()
val left = width / 2 - 50
val top = height / 2 - 50
val right = width / 2 + 50 - 1
val bottom = height / 2 + 50 - 1
assertEquals(fg, pixelMap[left, top])
assertEquals(fg, pixelMap[right, top])
assertEquals(fg, pixelMap[left, bottom])
assertEquals(fg, pixelMap[right, bottom])
assertEquals(bg, pixelMap[left - 1, top - 1])
assertEquals(bg, pixelMap[left - 1, top])
assertEquals(bg, pixelMap[left, top - 1])
assertEquals(bg, pixelMap[right + 1, top - 1])
assertEquals(bg, pixelMap[right + 1, top])
assertEquals(bg, pixelMap[right, top - 1])
assertEquals(bg, pixelMap[left - 1, bottom + 1])
assertEquals(bg, pixelMap[left - 1, bottom])
assertEquals(bg, pixelMap[left, bottom + 1])
assertEquals(bg, pixelMap[right + 1, bottom + 1])
assertEquals(bg, pixelMap[right + 1, bottom])
assertEquals(bg, pixelMap[right, bottom + 1])
}
@Test
fun testScaleWithBottomRightPivot() {
val bg = androidx.compose.ui.graphics.Color.Red
val fg = androidx.compose.ui.graphics.Color.Blue
val width = 200
val height = 200
val imageBitmap = ImageBitmap(width, height)
val canvas = Canvas(imageBitmap)
val paint = Paint().apply { this.color = bg }
val rect = Rect(Offset(0.0f, 0.0f), Size(width.toFloat(), height.toFloat()))
with(canvas) {
drawRect(rect, paint)
withSave {
scale(0.5f, 0.5f, width.toFloat(), height.toFloat())
paint.color = fg
drawRect(rect, paint)
}
}
val pixelMap = imageBitmap.toPixelMap()
val left = width - 100
val top = height - 100
val right = width - 1
val bottom = height - 1
assertEquals(fg, pixelMap[left, top])
assertEquals(fg, pixelMap[right, top])
assertEquals(fg, pixelMap[left, bottom])
assertEquals(fg, pixelMap[left, right])
assertEquals(bg, pixelMap[left, top - 1])
assertEquals(bg, pixelMap[left - 1, top])
assertEquals(bg, pixelMap[left - 1, top - 1])
assertEquals(bg, pixelMap[right, top - 1])
assertEquals(bg, pixelMap[left - 1, bottom])
}
@Test
fun testRotationCenterPivot() {
val bg = androidx.compose.ui.graphics.Color.Red
val fg = androidx.compose.ui.graphics.Color.Blue
val width = 200
val height = 200
val imageBitmap = ImageBitmap(width, height)
val canvas = Canvas(imageBitmap)
val paint = Paint().apply { this.color = bg }
val rect = Rect(Offset(0.0f, 0.0f), Size(width.toFloat(), height.toFloat()))
with(canvas) {
drawRect(rect, paint)
withSave {
rotate(180.0f, 100.0f, 100.0f)
paint.color = fg
drawRect(
Rect(100.0f, 100.0f, 200.0f, 200.0f),
paint
)
}
}
val pixelMap = imageBitmap.toPixelMap()
assertEquals(fg, pixelMap[0, 0])
assertEquals(fg, pixelMap[99, 0])
assertEquals(fg, pixelMap[0, 99])
assertEquals(fg, pixelMap[99, 99])
assertEquals(bg, pixelMap[0, 100])
assertEquals(bg, pixelMap[100, 0])
assertEquals(bg, pixelMap[100, 100])
assertEquals(bg, pixelMap[100, 99])
assertEquals(bg, pixelMap[99, 100])
}
@Test
fun testRotationDefaultPivot() {
val bg = androidx.compose.ui.graphics.Color.Red
val fg = androidx.compose.ui.graphics.Color.Blue
val width = 200
val height = 200
val imageBitmap = ImageBitmap(width, height)
val canvas = Canvas(imageBitmap)
val paint = Paint().apply { this.color = bg }
val rect = Rect(Offset(0.0f, 0.0f), Size(width.toFloat(), height.toFloat()))
with(canvas) {
drawRect(rect, paint)
withSave {
rotate(-45.0f)
paint.color = fg
drawRect(
Rect(0.0f, 0.0f, 100.0f, 100.0f),
paint
)
}
}
val pixelMap = imageBitmap.toPixelMap()
assertEquals(fg, pixelMap[2, 0])
assertEquals(fg, pixelMap[50, 49])
assertEquals(fg, pixelMap[70, 0])
assertEquals(fg, pixelMap[70, 68])
assertEquals(bg, pixelMap[50, 51])
assertEquals(bg, pixelMap[75, 76])
}
@Test
fun testCornerPathEffect() {
val width = 80
val height = 80
val radius = 20f
val imageBitmap = ImageBitmap(width, height)
imageBitmap.asAndroidBitmap().eraseColor(android.graphics.Color.WHITE)
val canvas = Canvas(imageBitmap)
canvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
Paint().apply {
color = Color.Blue
pathEffect = PathEffect.cornerPathEffect(radius)
}
)
val androidBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
androidBitmap.eraseColor(android.graphics.Color.WHITE)
val androidCanvas = android.graphics.Canvas(androidBitmap)
androidCanvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
frameworkPaint().apply {
isAntiAlias = true
color = android.graphics.Color.BLUE
pathEffect = android.graphics.CornerPathEffect(radius)
}
)
val composePixels = imageBitmap.toPixelMap()
for (i in 0 until width) {
for (j in 0 until height) {
assertEquals(
"invalid color at i: " + i + ", " + j,
composePixels[i, j],
Color(androidBitmap.getPixel(i, j)),
)
}
}
}
@Test
fun testDashPathEffect() {
val width = 80
val height = 80
val imageBitmap = ImageBitmap(width, height)
imageBitmap.asAndroidBitmap().eraseColor(android.graphics.Color.WHITE)
val canvas = Canvas(imageBitmap)
canvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
Paint().apply {
color = Color.Blue
pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 5f), 8f)
}
)
val androidBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
androidBitmap.eraseColor(android.graphics.Color.WHITE)
val androidCanvas = android.graphics.Canvas(androidBitmap)
androidCanvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
frameworkPaint().apply {
isAntiAlias = true
color = android.graphics.Color.BLUE
pathEffect = android.graphics.DashPathEffect(floatArrayOf(10f, 5f), 8f)
}
)
val composePixels = imageBitmap.toPixelMap()
for (i in 0 until 80) {
for (j in 0 until 80) {
assertEquals(
"invalid color at i: " + i + ", " + j,
composePixels[i, j].toArgb(),
androidBitmap.getPixel(i, j)
)
}
}
}
@Test
fun testChainPathEffect() {
val width = 80
val height = 80
val imageBitmap = ImageBitmap(width, height)
imageBitmap.asAndroidBitmap().eraseColor(android.graphics.Color.WHITE)
val canvas = Canvas(imageBitmap)
canvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
Paint().apply {
color = Color.Blue
pathEffect =
PathEffect.chainPathEffect(
PathEffect.dashPathEffect(floatArrayOf(10f, 5f), 8f),
PathEffect.cornerPathEffect(20f)
)
}
)
val androidBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
androidBitmap.eraseColor(android.graphics.Color.WHITE)
val androidCanvas = android.graphics.Canvas(androidBitmap)
androidCanvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
frameworkPaint().apply {
isAntiAlias = true
color = android.graphics.Color.BLUE
pathEffect =
android.graphics.ComposePathEffect(
android.graphics.DashPathEffect(floatArrayOf(10f, 5f), 8f),
android.graphics.CornerPathEffect(20f)
)
}
)
val composePixels = imageBitmap.toPixelMap()
for (i in 0 until 80) {
for (j in 0 until 80) {
assertEquals(
"invalid color at i: " + i + ", " + j,
composePixels[i, j].toArgb(),
androidBitmap.getPixel(i, j)
)
}
}
}
@Test
fun testPathDashPathEffect() {
val width = 80
val height = 80
val imageBitmap = ImageBitmap(width, height)
imageBitmap.asAndroidBitmap().eraseColor(android.graphics.Color.WHITE)
val canvas = Canvas(imageBitmap)
canvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
Paint().apply {
color = Color.Blue
pathEffect =
PathEffect.stampedPathEffect(
Path().apply {
lineTo(0f, 5f)
lineTo(5f, 5f)
close()
},
5f,
2f,
StampedPathEffectStyle.Rotate
)
}
)
val androidBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
androidBitmap.eraseColor(android.graphics.Color.WHITE)
val androidCanvas = android.graphics.Canvas(androidBitmap)
androidCanvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
frameworkPaint().apply {
isAntiAlias = true
color = android.graphics.Color.BLUE
pathEffect =
android.graphics.PathDashPathEffect(
android.graphics.Path().apply {
lineTo(0f, 5f)
lineTo(5f, 5f)
close()
},
5f,
2f,
android.graphics.PathDashPathEffect.Style.ROTATE
)
}
)
val composePixels = imageBitmap.toPixelMap()
for (i in 0 until 80) {
for (j in 0 until 80) {
assertEquals(
"invalid color at i: " + i + ", " + j,
composePixels[i, j].toArgb(),
androidBitmap.getPixel(i, j)
)
}
}
}
@Test
fun testColorFilterTint() {
val width = 80
val height = 80
val imageBitmap = ImageBitmap(width, height)
imageBitmap.asAndroidBitmap().eraseColor(android.graphics.Color.WHITE)
val canvas = Canvas(imageBitmap)
canvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
Paint().apply {
color = Color.Blue
colorFilter = ColorFilter.tint(Color.Magenta, BlendMode.SrcIn)
}
)
val androidBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
androidBitmap.eraseColor(android.graphics.Color.WHITE)
val androidCanvas = android.graphics.Canvas(androidBitmap)
androidCanvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
frameworkPaint().apply {
isAntiAlias = true
color = android.graphics.Color.BLUE
colorFilter = PorterDuffColorFilter(Color.Magenta.toArgb(), PorterDuff.Mode.SRC_IN)
}
)
val composePixels = imageBitmap.toPixelMap()
for (i in 0 until 80) {
for (j in 0 until 80) {
assertEquals(
"invalid color at i: " + i + ", " + j,
composePixels[i, j].toArgb(),
androidBitmap.getPixel(i, j)
)
}
}
}
@Test
fun testColorFilterLighting() {
val width = 80
val height = 80
val imageBitmap = ImageBitmap(width, height)
imageBitmap.asAndroidBitmap().eraseColor(android.graphics.Color.WHITE)
val canvas = Canvas(imageBitmap)
canvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
Paint().apply {
color = Color.Blue
colorFilter = ColorFilter.lighting(Color.Red, Color.Blue)
}
)
val androidBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
androidBitmap.eraseColor(android.graphics.Color.WHITE)
val androidCanvas = android.graphics.Canvas(androidBitmap)
androidCanvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
frameworkPaint().apply {
isAntiAlias = true
color = android.graphics.Color.BLUE
colorFilter = LightingColorFilter(Color.Red.toArgb(), Color.Blue.toArgb())
}
)
val composePixels = imageBitmap.toPixelMap()
for (i in 0 until 80) {
for (j in 0 until 80) {
assertEquals(
"invalid color at i: " + i + ", " + j,
composePixels[i, j].toArgb(),
androidBitmap.getPixel(i, j)
)
}
}
}
@Test
fun testColorFilterColorMatrix() {
val width = 80
val height = 80
val imageBitmap = ImageBitmap(width, height)
imageBitmap.asAndroidBitmap().eraseColor(android.graphics.Color.WHITE)
val canvas = Canvas(imageBitmap)
val colorMatrix = ColorMatrix().apply { setToSaturation(0f) }
canvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
Paint().apply {
color = Color.Blue
colorFilter = ColorFilter.colorMatrix(colorMatrix)
}
)
val androidBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
androidBitmap.eraseColor(android.graphics.Color.WHITE)
val androidCanvas = android.graphics.Canvas(androidBitmap)
androidCanvas.drawRect(
0f,
0f,
width.toFloat(),
height.toFloat(),
frameworkPaint().apply {
isAntiAlias = true
color = android.graphics.Color.BLUE
colorFilter = ColorMatrixColorFilter(colorMatrix.values)
}
)
val composePixels = imageBitmap.toPixelMap()
for (i in 0 until 80) {
for (j in 0 until 80) {
assertEquals(
"invalid color at i: " + i + ", " + j,
composePixels[i, j].toArgb(),
androidBitmap.getPixel(i, j)
)
}
}
}
fun frameworkPaint(): android.graphics.Paint =
android.graphics.Paint(
android.graphics.Paint.ANTI_ALIAS_FLAG or
android.graphics.Paint.DITHER_FLAG or
android.graphics.Paint.FILTER_BITMAP_FLAG
)
class EnableDisableZViewGroup @JvmOverloads constructor(
val drawLatch: CountDownLatch,
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
override fun dispatchDraw(canvas: Canvas) {
val androidCanvas = Canvas(canvas)
androidCanvas.enableZ()
for (i in 0 until childCount) {
drawChild(androidCanvas.nativeCanvas, getChildAt(i), drawingTime)
}
androidCanvas.disableZ()
drawLatch.countDown()
}
}
}
|
apache-2.0
|
0703a7b14a0daf5c0cf2c4a0bb159d33
| 33.453271 | 99 | 0.553938 | 4.631072 | false | true | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/ProjectFrameHelper.kt
|
1
|
16043
|
// 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.wm.impl
import com.intellij.ide.RecentProjectsManagerBase
import com.intellij.notification.ActionCenter
import com.intellij.notification.NotificationsManager
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.MnemonicHelper
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.impl.MouseGestureManager
import com.intellij.openapi.application.*
import com.intellij.openapi.application.impl.LaterInvocator
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx
import com.intellij.openapi.options.advanced.AdvancedSettings
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy
import com.intellij.openapi.wm.ex.IdeFrameEx
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.IdeFrameImpl.FrameHelper
import com.intellij.openapi.wm.impl.status.IdeStatusBarImpl
import com.intellij.openapi.wm.impl.status.widget.StatusBarWidgetsActionGroup
import com.intellij.openapi.wm.impl.status.widget.StatusBarWidgetsManager
import com.intellij.ui.*
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.util.io.SuperUserStatus.isSuperUser
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.accessibility.AccessibleContextAccessor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.ApiStatus
import java.awt.Image
import java.awt.Rectangle
import java.awt.Window
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.nio.file.Path
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.atomic.AtomicBoolean
import javax.accessibility.AccessibleContext
import javax.swing.*
open class ProjectFrameHelper(
private var frame: IdeFrameImpl?,
@field:Volatile @field:Suppress("unused") private var selfie: Image?
) : IdeFrameEx, AccessibleContextAccessor, DataProvider, Disposable {
private val isUpdatingTitle = AtomicBoolean()
private var title: String? = null
private var fileTitle: String? = null
private var currentFile: Path? = null
private var project: Project? = null
@get:ApiStatus.Internal
var rootPane: IdeRootPane? = null
private set
private var balloonLayout: BalloonLayout? = null
private var frameDecorator: IdeFrameDecorator? = null
// frame can be activated before project is assigned to it,
// so we remember the activation time and report it against the assigned project later
private var activationTimestamp: Long? = null
init {
setupCloseAction()
preInit()
@Suppress("LeakingThis")
Disposer.register(ApplicationManager.getApplication(), this)
}
companion object {
private val LOG = logger<ProjectFrameHelper>()
@JvmStatic
fun getFrameHelper(window: Window?): ProjectFrameHelper? {
if (window == null) {
return null
}
val projectFrame = if (window is IdeFrameImpl) {
window
}
else {
SwingUtilities.getAncestorOfClass(IdeFrameImpl::class.java, window) as? IdeFrameImpl ?: return null
}
return projectFrame.frameHelper?.helper as? ProjectFrameHelper
}
val superUserSuffix: String?
get() = if (!isSuperUser) null else if (SystemInfoRt.isWindows) "Administrator" else "ROOT"
fun appendTitlePart(sb: StringBuilder, s: String?) {
appendTitlePart(sb, s, " \u2013 ")
}
private fun appendTitlePart(builder: StringBuilder, s: String?, separator: String) {
if (!s.isNullOrBlank()) {
if (builder.isNotEmpty()) {
builder.append(separator)
}
builder.append(s)
}
}
private fun isTemporaryDisposed(frame: RootPaneContainer?): Boolean {
return ClientProperty.isTrue(frame?.rootPane, ScreenUtil.DISPOSE_TEMPORARY)
}
}
private fun preInit() {
val rootPane = createIdeRootPane()
this.rootPane = rootPane
frame!!.rootPane = rootPane
// NB!: the root pane must be set before decorator,
// which holds its own client properties in a root pane
frameDecorator = IdeFrameDecorator.decorate(frame!!, this)
frame!!.setFrameHelper(object : FrameHelper {
override fun getData(dataId: String) = [email protected](dataId)
override fun getAccessibleName(): @NlsSafe String {
val builder = StringBuilder()
project?.let {
builder.append(it.name)
builder.append(" - ")
}
builder.append(ApplicationNamesInfo.getInstance().fullProductName)
return builder.toString()
}
override fun dispose() {
if (isTemporaryDisposed(frame)) {
frame!!.doDispose()
}
else {
Disposer.dispose(this@ProjectFrameHelper)
}
}
override fun getProject() = [email protected]
override fun getHelper() = this@ProjectFrameHelper
}, frameDecorator)
balloonLayout = if (ActionCenter.isEnabled()) {
ActionCenterBalloonLayout(rootPane, JBUI.insets(8))
}
else {
BalloonLayoutImpl(rootPane, JBUI.insets(8))
}
frame!!.background = JBColor.PanelBackground
rootPane.prepareToolbar()
}
protected open fun createIdeRootPane(): IdeRootPane = IdeRootPane(frame = frame!!, frameHelper = this, parentDisposable = this)
fun releaseFrame() {
rootPane!!.removeToolbar()
WindowManagerEx.getInstanceEx().releaseFrame(this)
}
private val isInitialized = AtomicBoolean()
// purpose of delayed init - to show project frame as early as possible (and start loading of project too) and use it as project loading "splash"
// show frame -> start project loading (performed in a pooled thread) -> do UI tasks while project loading
fun init(installPainters: Boolean = true) {
if (!isInitialized.compareAndSet(false, true)) {
return
}
if (installPainters) {
installPainters()
}
rootPane!!.createAndConfigureStatusBar(this, this)
val frame = frame!!
MnemonicHelper.init(frame)
frame.focusTraversalPolicy = IdeFocusTraversalPolicy()
// to show window thumbnail under Macs
// http://lists.apple.com/archives/java-dev/2009/Dec/msg00240.html
if (SystemInfoRt.isMac) {
frame.iconImage = null
}
else if (SystemInfoRt.isLinux) {
frame.addComponentListener(object : ComponentAdapter() {
override fun componentShown(e: ComponentEvent) {
frame.removeComponentListener(this)
IdeMenuBar.installAppMenuIfNeeded(frame)
}
})
// in production (not from sources) makes sense only on Linux
AppUIUtil.updateWindowIcon(frame)
}
MouseGestureManager.getInstance().add(this)
ApplicationManager.getApplication().invokeLater(
{ (NotificationsManager.getNotificationsManager() as NotificationsManagerImpl).dispatchEarlyNotifications() },
ModalityState.NON_MODAL,
{ this.frame == null }
)
}
fun installPainters() {
(rootPane!!.glassPane as IdeGlassPaneImpl).installPainters()
}
override fun getComponent(): JComponent? = frame?.rootPane
private fun setupCloseAction() {
frame!!.defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE
val helper = createCloseProjectWindowHelper()
frame!!.addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent) {
if (isTemporaryDisposed(frame!!) || LaterInvocator.isInModalContext(frame!!, project)) {
return
}
val app = ApplicationManager.getApplication()
if (app != null && !app.isDisposed) {
helper.windowClosing(project)
}
}
})
}
protected open fun createCloseProjectWindowHelper(): CloseProjectWindowHelper = CloseProjectWindowHelper()
override fun getStatusBar(): IdeStatusBarImpl? = rootPane?.statusBar
override fun setFrameTitle(text: String) {
frame!!.title = text
}
fun frameReleased() {
project?.let {
project = null
// already disposed
rootPane?.deinstallNorthComponents(it)
}
fileTitle = null
currentFile = null
title = null
frame?.title = ""
}
override fun setFileTitle(fileTitle: String?, file: Path?) {
this.fileTitle = fileTitle
currentFile = file
updateTitle()
}
override fun getNorthExtension(key: String): JComponent? = project?.let { rootPane?.findNorthUiComponentByKey(key = key) }
protected open val titleInfoProviders: List<TitleInfoProvider>
get() = TitleInfoProvider.EP.extensionList
suspend fun updateTitle(title: String) {
withContext(Dispatchers.EDT + ModalityState.any().asContextElement()) {
[email protected] = title
updateTitle()
}
}
fun updateTitle() {
if (!isUpdatingTitle.compareAndSet(false, true)) {
return
}
try {
if (AdvancedSettings.getBoolean("ide.show.fileType.icon.in.titleBar")) {
// this property requires java.io.File
frame!!.rootPane.putClientProperty("Window.documentFile", currentFile?.toFile())
}
val builder = StringBuilder()
appendTitlePart(builder, title)
appendTitlePart(builder, fileTitle)
val titleInfoProviders = titleInfoProviders
if (!titleInfoProviders.isEmpty()) {
val project = project!!
for (extension in titleInfoProviders) {
if (extension.isActive(project)) {
val it = extension.getValue(project)
if (!it.isEmpty()) {
appendTitlePart(builder = builder, s = it, separator = " ")
}
}
}
}
if (builder.isNotEmpty()) {
frame!!.title = builder.toString()
}
}
finally {
isUpdatingTitle.set(false)
}
}
fun updateView() {
val rootPane = rootPane!!
rootPane.updateToolbar()
rootPane.updateMainMenuActions()
rootPane.updateNorthComponents()
}
override fun getCurrentAccessibleContext(): AccessibleContext = frame!!.accessibleContext
override fun getData(dataId: String): Any? {
val project = project
return when {
CommonDataKeys.PROJECT.`is`(dataId) -> if (project != null && project.isInitialized) project else null
IdeFrame.KEY.`is`(dataId) -> this
PlatformDataKeys.LAST_ACTIVE_TOOL_WINDOWS.`is`(dataId) -> {
if (project == null || !project.isInitialized) return null
val manager = project.serviceIfCreated<ToolWindowManager>() as? ToolWindowManagerImpl ?: return null
manager.getLastActiveToolWindows().toList().toTypedArray()
}
PlatformDataKeys.LAST_ACTIVE_FILE_EDITOR.`is`(dataId) -> {
if (project == null || !project.isInitialized) return null
FileEditorManagerEx.getInstanceEx(project).currentWindow?.getSelectedComposite(true)?.selectedEditor
}
else -> null
}
}
override fun getProject() = project
@RequiresEdt
fun setProject(project: Project) {
if (this.project === project) {
return
}
this.project = project
val rootPane = rootPane!!
rootPane.setProject(project)
rootPane.installNorthComponents(project)
rootPane.statusBar?.let {
project.messageBus.connect().subscribe(StatusBar.Info.TOPIC, it)
}
installDefaultProjectStatusBarWidgets(project)
if (selfie != null) {
StartupManager.getInstance(project).runAfterOpened { selfie = null }
}
frameDecorator?.setProject()
activationTimestamp?.let {
RecentProjectsManagerBase.getInstanceEx().setActivationTimestamp(project, it)
}
}
protected open fun installDefaultProjectStatusBarWidgets(project: Project) {
project.service<StatusBarWidgetsManager>().installPendingWidgets()
val statusBar = statusBar!!
PopupHandler.installPopupMenu(statusBar, StatusBarWidgetsActionGroup.GROUP_ID, ActionPlaces.STATUS_BAR_PLACE)
val rootPane = rootPane!!
val navBar = rootPane.navBarStatusWidgetComponent
if (navBar != null) {
statusBar.setCentralWidget(object : StatusBarWidget {
override fun dispose() {
}
override fun ID(): String = IdeStatusBarImpl.NAVBAR_WIDGET_KEY
override fun install(statusBar: StatusBar) {
}
}, navBar)
}
}
fun appClosing() {
frameDecorator?.appClosing()
}
override fun dispose() {
MouseGestureManager.getInstance().remove(this)
balloonLayout?.let {
balloonLayout = null
(it as BalloonLayoutImpl).dispose()
}
// clear both our and swing hard refs
rootPane?.let { rootPane ->
if (ApplicationManager.getApplication().isUnitTestMode) {
rootPane.removeNotify()
}
frame!!.rootPane = JRootPane()
this.rootPane = null
}
frame?.let {
it.doDispose()
it.setFrameHelper(null, null)
frame = null
}
frameDecorator = null
}
val frameOrNull: IdeFrameImpl?
get() = frame
fun getFrame(): IdeFrameImpl? {
val frame = frame
if (frame == null) {
@Suppress("DEPRECATION")
if (Disposer.isDisposed(this)) {
LOG.error("${javaClass.simpleName} is already disposed")
}
else {
LOG.error("Frame is null, but ${javaClass.simpleName} is not disposed yet")
}
}
return frame
}
fun requireNotNullFrame(): IdeFrameImpl {
frame?.let {
return it
}
@Suppress("DEPRECATION")
if (Disposer.isDisposed(this)) {
throw AssertionError("${javaClass.simpleName} is already disposed")
}
else {
throw AssertionError("Frame is null, but ${javaClass.simpleName} is not disposed yet")
}
}
override fun suggestChildFrameBounds(): Rectangle {
val b = frame!!.bounds
b.x += 100
b.width -= 200
b.y += 100
b.height -= 200
return b
}
override fun getBalloonLayout(): BalloonLayout? = balloonLayout
override fun isInFullScreen(): Boolean = frameDecorator?.isInFullScreen ?: false
override fun toggleFullScreen(state: Boolean): CompletableFuture<*> {
val frameDecorator = frameDecorator
if (frameDecorator == null || temporaryFixForIdea156004(state)) {
return CompletableFuture.completedFuture(null)
}
else {
return frameDecorator.toggleFullScreen(state)
}
}
private fun temporaryFixForIdea156004(state: Boolean): Boolean {
if (SystemInfoRt.isMac) {
try {
val modalBlockerField = Window::class.java.getDeclaredField("modalBlocker")
modalBlockerField.isAccessible = true
val modalBlocker = modalBlockerField.get(frame) as? Window
if (modalBlocker != null) {
ApplicationManager.getApplication().invokeLater({ toggleFullScreen(state) }, ModalityState.NON_MODAL)
return true
}
}
catch (e: NoSuchFieldException) {
LOG.error(e)
}
catch (e: IllegalAccessException) {
LOG.error(e)
}
}
return false
}
override fun notifyProjectActivation() {
val currentTimeMillis = System.currentTimeMillis()
activationTimestamp = currentTimeMillis
project?.let {
RecentProjectsManagerBase.getInstanceEx().setActivationTimestamp(it, currentTimeMillis)
}
}
fun isTabbedWindow() = frameDecorator?.isTabbedWindow ?: false
}
|
apache-2.0
|
41eda2ee209c567b77aecb1e6437ca34
| 31.543611 | 147 | 0.701801 | 4.719918 | false | false | false | false |
siosio/intellij-community
|
platform/built-in-server/src/org/jetbrains/io/fastCgi/FastCgiService.kt
|
1
|
7076
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.io.fastCgi
import com.intellij.concurrency.ConcurrentCollectionFactory
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.util.Consumer
import com.intellij.util.io.addChannelListener
import com.intellij.util.io.handler
import io.netty.bootstrap.Bootstrap
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.handler.codec.http.*
import org.jetbrains.builtInWebServer.PathInfo
import org.jetbrains.builtInWebServer.SingleConnectionNetService
import org.jetbrains.builtInWebServer.liveReload.WebServerPageConnectionService
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.errorIfNotMessage
import org.jetbrains.io.*
import java.util.concurrent.atomic.AtomicInteger
internal val LOG = logger<FastCgiService>()
// todo send FCGI_ABORT_REQUEST if client channel disconnected
abstract class FastCgiService(project: Project) : SingleConnectionNetService(project) {
private val requestIdCounter = AtomicInteger()
private val requests = ConcurrentCollectionFactory.createConcurrentIntObjectMap<ClientInfo>()
override fun configureBootstrap(bootstrap: Bootstrap, errorOutputConsumer: Consumer<String>) {
bootstrap.handler {
it.pipeline().addLast("fastCgiDecoder", FastCgiDecoder(errorOutputConsumer, this@FastCgiService))
it.pipeline().addLast("exceptionHandler", ChannelExceptionHandler.getInstance())
}
}
override fun addCloseListener(it: Channel) {
super.addCloseListener(it)
it.closeFuture().addChannelListener {
requestIdCounter.set(0)
if (!requests.isEmpty) {
val waitingClients = requests.elements().toList()
requests.clear()
for (client in waitingClients) {
sendBadGateway(client.channel, client.extraHeaders)
}
}
}
}
fun send(fastCgiRequest: FastCgiRequest, content: ByteBuf) {
val notEmptyContent: ByteBuf?
if (content.isReadable) {
content.retain()
notEmptyContent = content
notEmptyContent.touch()
}
else {
notEmptyContent = null
}
try {
val promise: Promise<*>
val handler = processHandler.resultIfFullFilled
if (handler == null) {
promise = processHandler.get()
}
else {
val channel = processChannel.get()
if (channel == null || !channel.isOpen) {
// channel disconnected for some reason
promise = connectAgain()
}
else {
fastCgiRequest.writeToServerChannel(notEmptyContent, channel)
return
}
}
promise
.onSuccess { fastCgiRequest.writeToServerChannel(notEmptyContent, processChannel.get()!!) }
.onError {
LOG.errorIfNotMessage(it)
handleError(fastCgiRequest, notEmptyContent)
}
}
catch (e: Throwable) {
LOG.error(e)
handleError(fastCgiRequest, notEmptyContent)
}
}
private fun handleError(fastCgiRequest: FastCgiRequest, content: ByteBuf?) {
try {
if (content != null && content.refCnt() != 0) {
content.release()
}
}
finally {
requests.remove(fastCgiRequest.requestId)?.let {
sendBadGateway(it.channel, it.extraHeaders)
}
}
}
fun allocateRequestId(channel: Channel, pathInfo: PathInfo, request: FullHttpRequest, extraHeaders: HttpHeaders): Int {
var requestId = requestIdCounter.getAndIncrement()
if (requestId >= java.lang.Short.MAX_VALUE) {
requestIdCounter.set(0)
requestId = requestIdCounter.getAndDecrement()
}
requests.put(requestId, ClientInfo(channel, pathInfo, request, extraHeaders))
return requestId
}
fun responseReceived(id: Int, buffer: ByteBuf?) {
val client = requests.remove(id)
if (client == null || !client.channel.isActive) {
buffer?.release()
return
}
val channel = client.channel
if (buffer == null) {
HttpResponseStatus.BAD_GATEWAY.send(channel)
return
}
val extraSuffix = WebServerPageConnectionService.instance.fileRequested(client.request, client.pathInfo::getOrResolveVirtualFile)
val bufferWithExtraSuffix =
if (extraSuffix == null) buffer
else {
Unpooled.wrappedBuffer(buffer, Unpooled.copiedBuffer(extraSuffix, Charsets.UTF_8))
}
val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, bufferWithExtraSuffix)
try {
parseHeaders(httpResponse, bufferWithExtraSuffix)
httpResponse.addServer()
if (!HttpUtil.isContentLengthSet(httpResponse)) {
HttpUtil.setContentLength(httpResponse, bufferWithExtraSuffix.readableBytes().toLong())
}
httpResponse.headers().add(client.extraHeaders)
}
catch (e: Throwable) {
bufferWithExtraSuffix.release()
try {
LOG.error(e)
}
finally {
HttpResponseStatus.INTERNAL_SERVER_ERROR.send(channel)
}
return
}
channel.writeAndFlush(httpResponse)
}
}
private fun sendBadGateway(channel: Channel, extraHeaders: HttpHeaders) {
try {
if (channel.isActive) {
HttpResponseStatus.BAD_GATEWAY.send(channel, extraHeaders = extraHeaders)
}
}
catch (e: Throwable) {
NettyUtil.log(e, LOG)
}
}
@Suppress("HardCodedStringLiteral")
private fun parseHeaders(response: HttpResponse, buffer: ByteBuf) {
val builder = StringBuilder()
while (buffer.isReadable) {
builder.setLength(0)
var key: String? = null
var valueExpected = true
while (true) {
val b = buffer.readByte().toInt()
if (b < 0 || b.toChar() == '\n') {
break
}
if (b.toChar() != '\r') {
if (valueExpected && b.toChar() == ':') {
valueExpected = false
key = builder.toString()
builder.setLength(0)
MessageDecoder.skipWhitespace(buffer)
}
else {
builder.append(b.toChar())
}
}
}
if (builder.isEmpty()) {
// end of headers
return
}
// skip standard headers
@Suppress("SpellCheckingInspection")
if (key.isNullOrEmpty() || key.startsWith("http", ignoreCase = true) || key.startsWith("X-Accel-", ignoreCase = true)) {
continue
}
val value = builder.toString()
if (key.equals("status", ignoreCase = true)) {
val index = value.indexOf(' ')
if (index == -1) {
LOG.warn("Cannot parse status: $value")
response.status = HttpResponseStatus.OK
}
else {
response.status = HttpResponseStatus.valueOf(Integer.parseInt(value.substring(0, index)))
}
}
else if (!(key.startsWith("http") || key.startsWith("HTTP"))) {
response.headers().add(key, value)
}
}
}
private class ClientInfo(val channel: Channel, val pathInfo: PathInfo, var request: FullHttpRequest, val extraHeaders: HttpHeaders)
|
apache-2.0
|
da46ae17047590710f5b3ff295ecf903
| 30.314159 | 140 | 0.676512 | 4.535897 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/KotlinFindUsagesSupport.kt
|
2
|
2528
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.findUsages
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
import org.jetbrains.kotlin.psi.*
interface KotlinFindUsagesSupport {
companion object {
fun getInstance(project: Project): KotlinFindUsagesSupport = project.getServiceSafe()
val KtParameter.isDataClassComponentFunction: Boolean
get() = getInstance(project).isDataClassComponentFunction(this)
fun KtElement.isCallReceiverRefersToCompanionObject(companionObject: KtObjectDeclaration): Boolean =
getInstance(project).isCallReceiverRefersToCompanionObject(this, companionObject)
fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement> =
getInstance(target.project).getTopMostOverriddenElementsToHighlight(target)
fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String? =
getInstance(declaration.project).tryRenderDeclarationCompactStyle(declaration)
fun PsiReference.isConstructorUsage(ktClassOrObject: KtClassOrObject): Boolean =
getInstance(ktClassOrObject.project).isConstructorUsage(this, ktClassOrObject)
fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?) : List<PsiElement> =
getInstance(declaration.project).getSuperMethods(declaration, ignore)
fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project): GlobalSearchScope =
getInstance(project).sourcesAndLibraries(delegate, project)
}
fun isCallReceiverRefersToCompanionObject(element: KtElement, companionObject: KtObjectDeclaration): Boolean
fun isDataClassComponentFunction(element: KtParameter): Boolean
fun getTopMostOverriddenElementsToHighlight(target: PsiElement): List<PsiElement>
fun tryRenderDeclarationCompactStyle(declaration: KtDeclaration): String?
fun isConstructorUsage(psiReference: PsiReference, ktClassOrObject: KtClassOrObject): Boolean
fun getSuperMethods(declaration: KtDeclaration, ignore: Collection<PsiElement>?) : List<PsiElement>
fun sourcesAndLibraries(delegate: GlobalSearchScope, project: Project): GlobalSearchScope
}
|
apache-2.0
|
37189d792c34b819ab315fdad60e91dc
| 47.634615 | 158 | 0.789953 | 5.390192 | false | false | false | false |
juzraai/ted-xml-model
|
src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/common/Values.kt
|
1
|
579
|
package hu.juzraai.ted.xml.model.tedexport.common
import org.simpleframework.xml.ElementList
import org.simpleframework.xml.ElementListUnion
import org.simpleframework.xml.Root
/**
* Model of VALUES element.
*
* @author Zsolt Jurányi
*/
@Root(name = "VALUES")
data class Values(
@field:ElementListUnion(
ElementList(entry = "VALUE", inline = true, type = Value::class, required = false),
ElementList(entry = "VALUE_RANGE", inline = true, type = ValueRange::class, required = false)
)
var values: List<ValueOrValueRange> = mutableListOf<ValueOrValueRange>()
)
|
apache-2.0
|
0b2f7f64a115b3f0fc97643833390e30
| 29.473684 | 97 | 0.740484 | 3.52439 | false | false | false | false |
softappeal/yass
|
kotlin/yass/main/ch/softappeal/yass/transport/socket/SocketTransport.kt
|
1
|
2204
|
package ch.softappeal.yass.transport.socket
import ch.softappeal.yass.*
import ch.softappeal.yass.remote.*
import ch.softappeal.yass.serialize.*
import ch.softappeal.yass.transport.*
import java.io.*
import java.net.*
import java.util.concurrent.*
private val socket_ = ThreadLocal<Socket>()
val socket: Socket get() = checkNotNull(socket_.get()) { "no active invocation" }
/** Buffering of output is needed to prevent long delays due to Nagle's algorithm. */
private fun createBuffer(): ByteArrayOutputStream = ByteArrayOutputStream(128)
private fun write(buffer: ByteArrayOutputStream, socket: Socket) {
val out = socket.getOutputStream()
buffer.writeTo(out)
out.flush()
}
/** [requestExecutor] is called once for each request. */
fun socketServer(setup: ServerSetup, requestExecutor: Executor) = object : SocketListener(requestExecutor) {
override fun accept(socket: Socket) = threadLocal(socket_, socket) {
val reader = reader(socket.getInputStream())
val transport = setup.resolve(reader)
transport.invocation(true, transport.read(reader)).invoke({ socket.close() }) { reply ->
val buffer = createBuffer()
transport.write(writer(buffer), reply)
write(buffer, socket)
}
}
}
fun socketClient(setup: ClientSetup, socketConnector: SocketConnector) = object : Client() {
override fun executeInContext(action: () -> Any?): Any? {
val socket = socketConnector()
try {
setForceImmediateSend(socket)
return threadLocal(socket_, socket) { action() }
} catch (e: Exception) {
close(socket, e)
throw e
}
}
/**
* If an exception is throw in this method, the socket would also be closed in [executeInContext].
* That's ok because [Socket.close] is idempotent.
*/
override fun invoke(invocation: ClientInvocation) = socket_.get().use { socket ->
invocation.invoke(true) { request ->
val buffer = createBuffer()
setup.write(writer(buffer), request)
write(buffer, socket)
invocation.settle(setup.read(reader(socket.getInputStream())))
}
}
}
|
bsd-3-clause
|
3ac08e04b01c6c350a32af67e92212b8
| 35.131148 | 108 | 0.661525 | 4.338583 | false | false | false | false |
bartwell/ExFilePicker
|
library/src/main/java/ru/bartwell/exfilepicker/data/config/ColorsConfig.kt
|
1
|
1203
|
package ru.bartwell.exfilepicker.data.config
import android.graphics.Color
data class ColorsConfig(
val toolbarBackground: Int,
val toolbarTitle: Int,
val background: Int,
val itemTitle: Int,
val itemSubtitle: Int,
val checkboxChecked: Int,
val checkboxUnchecked: Int,
val statusBar: Int,
val navigationBar: Int,
) {
companion object {
val DARK = ColorsConfig(
toolbarBackground = Color.BLACK,
toolbarTitle = Color.WHITE,
background = Color.BLACK,
itemTitle = Color.WHITE,
itemSubtitle = Color.WHITE,
checkboxChecked = Color.WHITE,
checkboxUnchecked = Color.DKGRAY,
statusBar = Color.BLACK,
navigationBar = Color.BLACK,
)
val LIGHT = ColorsConfig(
toolbarBackground = Color.GRAY,
toolbarTitle = Color.BLACK,
background = Color.WHITE,
itemTitle = Color.BLACK,
itemSubtitle = Color.DKGRAY,
checkboxChecked = Color.BLACK,
checkboxUnchecked = Color.GRAY,
statusBar = Color.GRAY,
navigationBar = Color.GRAY,
)
}
}
|
mit
|
a920ebab250007bf3ea68a87195d11f9
| 29.075 | 45 | 0.593516 | 4.930328 | false | true | false | false |
Szewek/Minecraft-Flux
|
src/main/java/szewek/mcflux/items/ItemSpecial.kt
|
1
|
1678
|
package szewek.mcflux.items
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.item.EnumAction
import net.minecraft.item.ItemStack
import net.minecraft.util.ActionResult
import net.minecraft.util.EnumActionResult
import net.minecraft.util.EnumHand
import net.minecraft.util.text.TextComponentTranslation
import net.minecraft.world.World
import net.minecraftforge.items.ItemHandlerHelper
import szewek.mcflux.special.SpecialEventHandler
class ItemSpecial : ItemMCFlux() {
override fun getItemUseAction(stack: ItemStack) = EnumAction.EAT
override fun getMaxItemUseDuration(stack: ItemStack) = 30
override fun onItemRightClick(w: World, p: EntityPlayer, h: EnumHand): ActionResult<ItemStack> {
p.activeHand = h
return ActionResult(EnumActionResult.SUCCESS, p.getHeldItem(h))
}
override fun onItemUseFinish(stk: ItemStack, w: World, elb: EntityLivingBase): ItemStack {
if (!w.isRemote && elb is EntityPlayerMP && stk.item === this && stk.hasTagCompound()) {
val mp = elb as EntityPlayerMP?
val nbt = stk.tagCompound!!
val se = SpecialEventHandler.getEvent(nbt.getInteger("seid")) ?: return stk
if (se.endTime <= System.currentTimeMillis() / 60000) {
mp!!.sendMessage(TextComponentTranslation("mcflux.special.ended"))
return ItemStack.EMPTY
}
val items = se.createItems()
for (item in items) {
if (item == ItemStack.EMPTY)
continue
ItemHandlerHelper.giveItemToPlayer(mp!!, item, -1)
}
stk.grow(-1)
mp!!.sendMessage(TextComponentTranslation("mcflux.special.desc", se.description))
}
return stk
}
}
|
mit
|
24e859d4f79e79e6d2ba13555e26845c
| 34.702128 | 97 | 0.765793 | 3.78781 | false | false | false | false |
virvar/magnetic-ball-2
|
MagneticBall2App/src/main/kotlin/ru/virvar/apps/magneticBall2App/Main.kt
|
1
|
435
|
package ru.virvar.apps.magneticBall2App
import ru.virvar.apps.magneticBallCore.Game
fun main(args: Array<String>) {
val configLoader = ConfigLoader("appProperties.cfg")
val gameConfig = configLoader.readProperties()
val game = Game(gameConfig.levelGenerator, gameConfig.blocksGenerator, gameConfig.turnHandler)
val gameFrame = GameFrame(game, gameConfig.drawer)
gameFrame.isVisible = true
gameFrame.start()
}
|
gpl-2.0
|
40bca59e71f4657fac348fc359691657
| 35.25 | 98 | 0.770115 | 3.849558 | false | true | false | false |
TradeMe/MapMe
|
mapme/src/test/java/nz/co/trademe/mapme/BaseAdapterTest.kt
|
1
|
3769
|
package nz.co.trademe.mapme
import android.annotation.SuppressLint
import android.content.Context
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import com.nhaarman.mockito_kotlin.spy
import nz.co.trademe.mapme.util.TestAdapter
import nz.co.trademe.mapme.util.TestAnnotation
import nz.co.trademe.mapme.util.TestAnnotationFactory
import nz.co.trademe.mapme.util.TestItem
import nz.co.trademe.mapme.util.TestItemDiffCallback
import nz.co.trademe.mapme.util.TestMap
import nz.co.trademe.mapme.util.addItems
import org.junit.Before
import org.mockito.Mock
import org.mockito.MockitoAnnotations
@SuppressLint("NewApi")
abstract class BaseAdapterTest {
@Mock
lateinit var context: Context
@Mock
lateinit var mapView: View
var items = arrayListOf<TestItem>()
lateinit var adapter: TestAdapter
var adapterObserver: RecyclerView.AdapterDataObserver = spy(TestDataObserver())
@Before
fun before() {
MockitoAnnotations.initMocks(this)
items.clear()
}
fun createAdapter(count: Int) {
items = addItems(items, count)
val factory = TestAnnotationFactory()
adapter = TestAdapter(items, context, factory)
resetVerification()
adapter.attach(mapView, TestMap())
adapter.notifyDataSetChanged()
adapter.await()
adapter.resetCounts()
}
/**
* Resets the adapter observer and adapter update/create verifications
*/
fun resetVerification() {
adapter.unregisterObserver(adapterObserver)
val observer = TestDataObserver()
adapterObserver = spy(observer)
adapter.registerObserver(adapterObserver)
adapter.resetCounts()
}
/**
* Waits for all asynchronous updates to complete
*/
fun TestAdapter.await() = phaser.arriveAndAwaitAdvance()
/**
* Convenience method to find the annotation with a matching position
*/
fun TestAdapter.annotationWithPosition(position: Int): TestAnnotation {
return annotations.find { it.position == position } as TestAnnotation
}
open fun dispatchDiff(old: List<TestItem>, new: List<TestItem>, detectMoves: Boolean = false) : TestAdapter {
val callback = TestItemDiffCallback(old, new)
val diffResult = DiffUtil.calculateDiff(callback, detectMoves)
items.clear()
items.addAll(new)
diffResult.dispatchUpdatesTo(adapter)
return adapter
}
/**
* A test observer used for verification
*/
open class TestDataObserver : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
println("onChanged")
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
super.onItemRangeRemoved(positionStart, itemCount)
println("onItemRangeRemoved positionStart: $positionStart, itemCount: $itemCount")
}
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
super.onItemRangeMoved(fromPosition, toPosition, itemCount)
println("onItemRangeMoved fromPosition: $fromPosition, toPosition: $toPosition, itemCount: $itemCount")
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
super.onItemRangeInserted(positionStart, itemCount)
println("onItemRangeInserted positionStart: $positionStart, itemCount: $itemCount")
}
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
super.onItemRangeChanged(positionStart, itemCount)
println("onItemRangeChanged positionStart: $positionStart, itemCount: $itemCount")
}
}
}
|
mit
|
e88de988e8ae26e1e61e0f425f0c160c
| 31.491379 | 115 | 0.700451 | 4.758838 | false | true | false | false |
davinkevin/Podcast-Server
|
backend/src/main/kotlin/com/github/davinkevin/podcastserver/find/finders/gulli/GulliFinder.kt
|
1
|
2242
|
package com.github.davinkevin.podcastserver.find.finders.gulli
import com.github.davinkevin.podcastserver.extension.java.util.orNull
import com.github.davinkevin.podcastserver.find.FindCoverInformation
import com.github.davinkevin.podcastserver.find.FindPodcastInformation
import com.github.davinkevin.podcastserver.find.finders.fetchCoverInformationOrOption
import com.github.davinkevin.podcastserver.find.finders.Finder
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.bodyToMono
import reactor.core.publisher.Mono
import reactor.kotlin.core.publisher.toMono
import reactor.kotlin.core.util.function.component1
import reactor.kotlin.core.util.function.component2
import java.net.URI
import java.util.*
import com.github.davinkevin.podcastserver.service.image.ImageService
class GulliFinder(
private val client: WebClient,
private val image: ImageService
): Finder {
override fun findInformation(url: String): Mono<FindPodcastInformation> {
val path = url.substringAfterLast("replay.gulli.fr")
return client
.get()
.uri(path)
.retrieve()
.bodyToMono<String>()
.map { Jsoup.parse(it, url) }
.flatMap { findCover(it).zipWith(it.toMono()) }
.map { (cover, d) -> FindPodcastInformation(
title = d.select("ol.breadcrumb li.active").first()!!.text(),
cover = cover.orNull(),
description = d.select(".container_full .description").text(),
url = URI(url),
type = "Gulli"
) }
}
private fun findCover(d: Document): Mono<Optional<FindCoverInformation>> {
val imgTag = d.select(".container_full .visuel img")
.firstOrNull() ?: return Optional.empty<FindCoverInformation>().toMono()
return image.fetchCoverInformationOrOption(URI(imgTag.attr("src")))
}
override fun compatibility(url: String): Int = when {
"replay.gulli.fr" in url -> 1
else -> Integer.MAX_VALUE
}
}
|
apache-2.0
|
9524d949aa3a4dab8a6af9995c314cb0
| 39.763636 | 88 | 0.669492 | 4.413386 | false | false | false | false |
mpv-android/mpv-android
|
app/src/main/java/is/xyz/mpv/config/ScalerDialogPreference.kt
|
1
|
2584
|
package `is`.xyz.mpv.config
import `is`.xyz.mpv.R
import android.content.Context
import android.preference.DialogPreference
import android.util.AttributeSet
import android.view.View
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.Spinner
class ScalerDialogPreference @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = android.R.attr.dialogPreferenceStyle,
defStyleRes: Int = 0
): DialogPreference(context, attrs, defStyleAttr, defStyleRes) {
private var entries: Array<String>
init {
isPersistent = false
dialogLayoutResource = R.layout.scaler_pref
// read list of scalers from specified resource
val styledAttrs = context.obtainStyledAttributes(attrs, R.styleable.ScalerPreferenceDialog)
val res = styledAttrs.getResourceId(R.styleable.ScalerPreferenceDialog_entries, -1)
entries = context.resources.getStringArray(res)
styledAttrs.recycle()
}
private lateinit var myView: View
override fun onBindDialogView(view: View) {
super.onBindDialogView(view)
myView = view
val s = myView.findViewById<Spinner>(R.id.scaler)
val e1 = myView.findViewById<EditText>(R.id.param1)
val e2 = myView.findViewById<EditText>(R.id.param2)
// populate Spinner and set selected item
s.adapter = ArrayAdapter(context, android.R.layout.simple_spinner_item, entries).apply {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
val va = sharedPreferences.getString(key, "")
val idx = entries.indexOf(va)
if (idx != -1)
s.setSelection(idx, false)
// populate EditText's
e1.setText(sharedPreferences.getString("${key}_param1", ""))
e2.setText(sharedPreferences.getString("${key}_param2", ""))
}
override fun onDialogClosed(positiveResult: Boolean) {
super.onDialogClosed(positiveResult)
// save values only if user presses OK
if (!positiveResult)
return
val s = myView.findViewById<Spinner>(R.id.scaler)
val e1 = myView.findViewById<EditText>(R.id.param1)
val e2 = myView.findViewById<EditText>(R.id.param2)
val e = editor // Will create(!) a new SharedPreferences.Editor instance
e.putString(key, s.selectedItem as String)
e.putString("${key}_param1", e1.text.toString())
e.putString("${key}_param2", e2.text.toString())
e.commit()
}
}
|
mit
|
4bc6dd5f849e10e840bc4770d0a6b4b6
| 34.39726 | 99 | 0.675697 | 4.350168 | false | false | false | false |
android/user-interface-samples
|
TextStyling/app/src/test/java/com/android/example/text/styling/parser/ParserTest.kt
|
2
|
5255
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.text.styling.parser
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Tests for [Parser]
*/
class ParserTest {
private val LINE_SEPARATOR = System.getProperty("line.separator")
@Test fun quoteBeginningOfText() {
val withQuote = "> This is a quote.$LINE_SEPARATOR"+"This is not"
val elements = Parser.parse(withQuote).elements
val expected = listOf(
Element(Element.Type.QUOTE, "This is a quote.$LINE_SEPARATOR"),
Element(Element.Type.TEXT, "This is not"))
assertEquals(expected, elements)
}
@Test fun quoteEndOfText() {
val withQuote = "This is not a quote.$LINE_SEPARATOR> This is a quote"
val elements = Parser.parse(withQuote).elements
val expected = listOf(
Element(Element.Type.TEXT, "This is not a quote.$LINE_SEPARATOR"),
Element(Element.Type.QUOTE, "This is a quote"))
assertEquals(expected, elements)
}
@Test fun simpleBulletPoints() {
val bulletPoints = "Bullet points:$LINE_SEPARATOR* One$LINE_SEPARATOR+ Two$LINE_SEPARATOR* Three"
val elements = Parser.parse(bulletPoints).elements
assertEquals(elements.size, 4)
assertEquals(elements[0].type, Element.Type.TEXT)
assertEquals(elements[0].text, "Bullet points:$LINE_SEPARATOR")
assertEquals(elements[1].type, Element.Type.BULLET_POINT)
assertEquals(elements[1].text, "One$LINE_SEPARATOR")
assertEquals(elements[2].type, Element.Type.BULLET_POINT)
assertEquals(elements[2].text, "Two$LINE_SEPARATOR")
assertEquals(elements[3].type, Element.Type.BULLET_POINT)
assertEquals(elements[3].text, "Three")
}
@Test fun simpleCode() {
val code = "Styling `Text` in `Kotlin`"
val elements = Parser.parse(code).elements
val expected = listOf(
Element(Element.Type.TEXT, "Styling "),
Element(Element.Type.CODE_BLOCK, "Text"),
Element(Element.Type.TEXT, " in "),
Element(Element.Type.CODE_BLOCK, "Kotlin"))
assertEquals(expected, elements)
}
@Test fun codeWithExtraTick() {
val code = "Styling `Text` in `Kotlin"
val elements = Parser.parse(code).elements
val expected = listOf(
Element(Element.Type.TEXT, "Styling "),
Element(Element.Type.CODE_BLOCK, "Text"),
Element(Element.Type.TEXT, " in "),
Element(Element.Type.TEXT, "`Kotlin"))
assertEquals(expected, elements)
}
@Test fun quoteBulletPointsCode() {
val text = "Complex:$LINE_SEPARATOR> Quote${LINE_SEPARATOR}With points:$LINE_SEPARATOR+ bullet `one`$LINE_SEPARATOR* bullet `two` is `long`"
val elements = Parser.parse(text).elements
assertEquals(elements.size, 5)
assertEquals(elements[0].type, Element.Type.TEXT)
assertEquals(elements[0].text, "Complex:$LINE_SEPARATOR")
assertEquals(elements[1].type, Element.Type.QUOTE)
assertEquals(elements[1].text, "Quote$LINE_SEPARATOR")
assertEquals(elements[2].type, Element.Type.TEXT)
assertEquals(elements[2].text, "With points:$LINE_SEPARATOR")
// first bullet point
assertEquals(elements[3].type, Element.Type.BULLET_POINT)
assertEquals(elements[3].text, "bullet `one`$LINE_SEPARATOR")
val subElements1 = elements[3].elements
assertEquals(subElements1.size, 3)
assertEquals(subElements1[0].type, Element.Type.TEXT)
assertEquals(subElements1[0].text, "bullet ")
assertEquals(subElements1[1].type, Element.Type.CODE_BLOCK)
assertEquals(subElements1[1].text, "one")
assertEquals(subElements1[2].type, Element.Type.TEXT)
assertEquals(subElements1[2].text, "$LINE_SEPARATOR")
// second bullet point
assertEquals(elements[4].type, Element.Type.BULLET_POINT)
assertEquals(elements[4].text, "bullet `two` is `long`")
val subElements2 = elements[4].elements
assertEquals(subElements2.size, 4)
assertEquals(subElements2[0].type, Element.Type.TEXT)
assertEquals(subElements2[0].text, "bullet ")
assertEquals(subElements2[1].type, Element.Type.CODE_BLOCK)
assertEquals(subElements2[1].text, "two")
assertEquals(subElements2[2].type, Element.Type.TEXT)
assertEquals(subElements2[2].text, " is ")
assertEquals(subElements2[3].type, Element.Type.CODE_BLOCK)
assertEquals(subElements2[3].text, "long")
}
}
|
apache-2.0
|
b4868a17ce580fb97dc0032bc2f2f13a
| 39.744186 | 149 | 0.656137 | 4.121569 | false | true | false | false |
ujpv/intellij-rust
|
src/main/kotlin/org/rust/ide/notifications/MissingToolchainNotificationProvider.kt
|
1
|
9672
|
package org.rust.ide.notifications
import com.intellij.ProjectTopics
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.NotificationType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileChooser.FileChooser
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import org.rust.cargo.project.settings.RustProjectSettingsService
import org.rust.cargo.project.settings.rustSettings
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.toolchain.RustToolchain
import org.rust.cargo.toolchain.Rustup
import org.rust.cargo.util.StandardLibraryRoots
import org.rust.cargo.util.cargoProjectRoot
import backcompat.runWriteAction
import org.rust.cargo.project.workspace.cargoProject
import org.rust.ide.utils.service
import org.rust.lang.core.psi.impl.isNotRustFile
import java.awt.Component
/**
* Warn user if rust toolchain or standard library is not properly configured.
*
* Try to fix this automatically (toolchain from PATH, standard library from the last project)
* and if not successful show the actual notification to the user.
*/
class MissingToolchainNotificationProvider(
private val project: Project,
private val notifications: EditorNotifications
) : EditorNotifications.Provider<EditorNotificationPanel>() {
init {
project.messageBus.connect(project).apply {
subscribe(RustProjectSettingsService.TOOLCHAIN_TOPIC,
object : RustProjectSettingsService.ToolchainListener {
override fun toolchainChanged(newToolchain: RustToolchain?) {
notifications.updateAllNotifications()
}
})
subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun beforeRootsChange(event: ModuleRootEvent?) {
// NOP
}
override fun rootsChanged(event: ModuleRootEvent?) {
notifications.updateAllNotifications()
}
})
}
}
override fun getKey(): Key<EditorNotificationPanel> = PROVIDER_KEY
override fun createNotificationPanel(file: VirtualFile, editor: FileEditor): EditorNotificationPanel? {
if (file.isNotRustFile || isNotificationDisabled()) return null
val toolchain = project.toolchain
if (toolchain == null || !toolchain.looksLikeValidToolchain()) {
return if (trySetupToolchainAutomatically())
null
else
createBadToolchainPanel()
}
val module = ModuleUtilCore.findModuleForFile(file, project) ?: return null
if (module.cargoProject?.hasStandardLibrary == false) {
val rustup = module.cargoProjectRoot?.let { toolchain.rustup(it.path) }
return if (trySetupLibraryAutomatically(module, rustup)) {
null
} else {
createLibraryAttachingPanel(module, rustup)
}
}
return null
}
private fun trySetupToolchainAutomatically(): Boolean {
if (alreadyTriedForThisProject(TOOLCHAIN_DISCOVERY_KEY)) return false
val toolchain = RustToolchain.suggest() ?: return false
ApplicationManager.getApplication().invokeLater {
if (project.isDisposed) return@invokeLater
val oldToolchain = project.rustSettings.toolchain
if (oldToolchain != null && oldToolchain.looksLikeValidToolchain()) {
return@invokeLater
}
runWriteAction {
project.rustSettings.toolchain = toolchain
}
project.showBalloon("Using Cargo at ${toolchain.presentableLocation}", NotificationType.INFORMATION)
notifications.updateAllNotifications()
}
return true
}
private fun createBadToolchainPanel(): EditorNotificationPanel =
EditorNotificationPanel().apply {
setText("No Rust toolchain configured")
createActionLabel("Setup toolchain") {
project.service<RustProjectSettingsService>().configureToolchain()
}
createActionLabel("Do not show again") {
disableNotification()
notifications.updateAllNotifications()
}
}
private fun trySetupLibraryAutomatically(module: Module, rustup: Rustup?): Boolean {
if (alreadyTriedForThisProject(LIBRARY_DISCOVERY_KEY)) return false
val stdlib = rustup?.getStdlibFromSysroot()
?:
PropertiesComponent.getInstance().getValue(LIBRARY_LOCATION_KEY)?.let { previousLocation ->
VirtualFileManager.getInstance().findFileByUrl(previousLocation)
}
?: return false
ApplicationManager.getApplication().invokeLater {
if (module.isDisposed) return@invokeLater
if (tryAttachStdlibToModule(module, stdlib)) {
project.showBalloon(
"Using rust standard library at ${stdlib.presentableUrl}",
NotificationType.INFORMATION
)
}
notifications.updateAllNotifications()
}
return true
}
private fun createLibraryAttachingPanel(module: Module, rustup: Rustup?): EditorNotificationPanel =
EditorNotificationPanel().apply {
setText("No standard library sources found, some code insight will not work")
if (rustup != null) {
createActionLabel("Download via rustup") {
object : Task.Backgroundable(module.project, "rustup component add rust-src") {
private lateinit var result: Rustup.DownloadResult
override fun run(indicator: ProgressIndicator) {
result = rustup.downloadStdlib()
}
override fun onSuccess() {
if (module.isDisposed) return
val result = result
when (result) {
is Rustup.DownloadResult.Ok -> tryAttachStdlibToModule(module, result.library)
is Rustup.DownloadResult.Err ->
project.showBalloon(
"Failed to download standard library: ${result.error}",
NotificationType.ERROR
)
}
notifications.updateAllNotifications()
}
}.queue()
}
} else {
createActionLabel("Attach") {
val stdlib = chooseStdlibLocation(this) ?: return@createActionLabel
if (!tryAttachStdlibToModule(module, stdlib)) {
project.showBalloon(
"Invalid Rust standard library source path: `${stdlib.presentableUrl}`",
NotificationType.ERROR
)
}
notifications.updateAllNotifications()
}
}
createActionLabel("Do not show again") {
disableNotification()
notifications.updateAllNotifications()
}
}
private fun chooseStdlibLocation(parent: Component): VirtualFile? {
val descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor()
return FileChooser.chooseFile(descriptor, parent, project, null)
}
private fun tryAttachStdlibToModule(module: Module, stdlib: VirtualFile): Boolean {
val roots = StandardLibraryRoots.fromFile(stdlib)
?: return false
runWriteAction { roots.attachTo(module) }
PropertiesComponent.getInstance().setValue(LIBRARY_LOCATION_KEY, stdlib.url)
return true
}
private fun disableNotification() {
PropertiesComponent.getInstance(project).setValue(NOTIFICATION_STATUS_KEY, true)
}
private fun isNotificationDisabled(): Boolean =
PropertiesComponent.getInstance(project).getBoolean(NOTIFICATION_STATUS_KEY)
private fun alreadyTriedForThisProject(key: String): Boolean {
val properties = PropertiesComponent.getInstance(project)
val result = properties.getBoolean(key)
properties.setValue(key, true)
return result
}
companion object {
private val NOTIFICATION_STATUS_KEY = "org.rust.hideToolchainNotifications"
private val TOOLCHAIN_DISCOVERY_KEY = "org.rust.alreadyTriedToolchainAutoDiscovery"
private val LIBRARY_DISCOVERY_KEY = "org.rust.alreadyTriedLibraryAutoDiscovery"
private val LIBRARY_LOCATION_KEY = "org.rust.previousLibraryLocation"
private val PROVIDER_KEY: Key<EditorNotificationPanel> = Key.create("Setup Rust toolchain")
}
}
|
mit
|
6a586a65c34a05700eab12570dfd9f17
| 39.3 | 112 | 0.639268 | 5.890378 | false | false | false | false |
ujpv/intellij-rust
|
src/test/kotlin/org/rust/lang/core/psi/RustLiteralOffsetsTest.kt
|
1
|
4142
|
package org.rust.lang.core.psi
import com.intellij.psi.tree.IElementType
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.rust.lang.core.psi.impl.RustNumericLiteralImpl
import org.rust.lang.core.psi.impl.RustRawStringLiteralImpl
import org.rust.lang.core.psi.impl.RustStringLiteralImpl
import org.rust.lang.core.psi.RustTokenElementTypes.BYTE_LITERAL as BCH
import org.rust.lang.core.psi.RustTokenElementTypes.CHAR_LITERAL as CHR
import org.rust.lang.core.psi.RustTokenElementTypes.FLOAT_LITERAL as FLT
import org.rust.lang.core.psi.RustTokenElementTypes.INTEGER_LITERAL as INT
import org.rust.lang.core.psi.RustTokenElementTypes.RAW_BYTE_STRING_LITERAL as BRW
import org.rust.lang.core.psi.RustTokenElementTypes.RAW_STRING_LITERAL as RAW
abstract class RustLiteralOffsetsTestCase(
private val type: IElementType,
private val text: String,
private val constructor: (IElementType, CharSequence) -> RustLiteral) {
protected fun doTest() {
val literal = constructor(type, text.replace("|", ""))
val expected = makeOffsets(text)
assertEquals(expected, literal.offsets)
}
private fun makeOffsets(text: String): RustLiteral.Offsets {
val parts = text.split('|')
assert(parts.size == 5)
val prefixEnd = parts[0].length
val openDelimEnd = prefixEnd + parts[1].length
val valueEnd = openDelimEnd + parts[2].length
val closeDelimEnd = valueEnd + parts[3].length
val suffixEnd = closeDelimEnd + parts[4].length
return RustLiteral.Offsets.fromEndOffsets(prefixEnd, openDelimEnd, valueEnd, closeDelimEnd, suffixEnd)
}
}
@RunWith(Parameterized::class)
class RustNumericLiteralOffsetsTest(
type: IElementType,
text: String
) : RustLiteralOffsetsTestCase(type, text, ::RustNumericLiteralImpl) {
@Test
fun test() = doTest()
companion object {
@Parameterized.Parameters(name = "{index}: {1}")
@JvmStatic fun data(): Collection<Array<Any>> = listOf(
arrayOf(INT, "||123||i32"),
arrayOf(INT, "||0||u"),
arrayOf(INT, "||0||"),
arrayOf(FLT, "||-12||f32"),
arrayOf(FLT, "||-12.124||f32"),
arrayOf(FLT, "||1.0e10||"),
arrayOf(FLT, "||1.0e||"),
arrayOf(FLT, "||1.0e||e"),
arrayOf(INT, "||0xABC||"),
arrayOf(INT, "||0xABC||i64"),
arrayOf(FLT, "||2.||"),
arrayOf(INT, "||0x||"),
arrayOf(INT, "||1_______||"),
arrayOf(INT, "||1_______||i32")
)
}
}
@RunWith(Parameterized::class)
class RustStringLiteralOffsetsTest(type: IElementType, text: String) :
RustLiteralOffsetsTestCase(type, text, ::RustStringLiteralImpl) {
@Test
fun test() = doTest()
companion object {
@Parameterized.Parameters(name = "{index}: {1}")
@JvmStatic fun data(): Collection<Array<Any>> = listOf(
arrayOf(CHR, "|'|a|'|suf"),
arrayOf(BCH, "b|'|a|'|"),
arrayOf(BCH, "b|'|a|'|suf"),
arrayOf(CHR, "|'|a||"),
arrayOf(CHR, "|'||'|"),
arrayOf(CHR, "|'|\\\\|'|"),
arrayOf(CHR, "|'|\\'||"),
arrayOf(CHR, "|'||'|a"),
arrayOf(CHR, "|'|\\\\|'|a"),
arrayOf(CHR, "|'|\\'a||"),
arrayOf(CHR, "|'|\\\\\\'a||")
)
}
}
@RunWith(Parameterized::class)
class RustRawStringLiteralOffsetsTest(type: IElementType, text: String) :
RustLiteralOffsetsTestCase(type, text, ::RustRawStringLiteralImpl) {
@Test
fun test() = doTest()
companion object {
@Parameterized.Parameters(name = "{index}: {1}")
@JvmStatic fun data(): Collection<Array<Any>> = listOf(
arrayOf(RAW, "r|\"|a|\"|suf"),
arrayOf(BRW, "br|\"|a|\"|suf"),
arrayOf(RAW, "r|\"|a|\"|"),
arrayOf(RAW, "r|###\"|aaa||"),
arrayOf(RAW, "r|###\"|aaa\"##||"),
arrayOf(RAW, "r|###\"||\"###|"),
arrayOf(RAW, "r|###\"|a\"##a|\"###|s")
)
}
}
|
mit
|
848f924a515aa7d25e8324ebceb2274d
| 35.654867 | 110 | 0.593433 | 3.878277 | false | true | false | false |
signed/intellij-community
|
platform/configuration-store-impl/testSrc/ModuleStoreTest.kt
|
1
|
6426
|
package com.intellij.configurationStore
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.impl.stores.BatchUpdateListener
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.impl.storage.ClasspathStorage
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.*
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.io.parentSystemIndependentPath
import com.intellij.util.io.readText
import com.intellij.util.io.systemIndependentPath
import gnu.trove.TObjectIntHashMap
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.nio.file.Path
import java.nio.file.Paths
@RunsInEdt
@RunsInActiveStoreMode
class ModuleStoreTest {
companion object {
@JvmField
@ClassRule val projectRule = ProjectRule()
val MODULE_DIR = "\$MODULE_DIR$"
private inline fun <T> Module.useAndDispose(task: Module.() -> T): T {
try {
return task()
}
finally {
ModuleManager.getInstance(projectRule.project).disposeModule(this)
}
}
private fun VirtualFile.loadModule(): Module {
val project = projectRule.project
return runWriteAction { ModuleManager.getInstance(project).loadModule(path) }
}
fun Path.createModule() = projectRule.createModule(this)
}
private val tempDirManager = TemporaryDirectory()
private val ruleChain = RuleChain(tempDirManager, EdtRule(), ActiveStoreRule(projectRule), DisposeModulesRule(projectRule))
@Rule fun getChain() = ruleChain
@Test fun `set option`() {
val moduleFile = runWriteAction {
VfsTestUtil.createFile(tempDirManager.newVirtualDirectory("module"), "test.iml", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"JAVA_MODULE\" foo=\"bar\" version=\"4\" />")
}
moduleFile.loadModule().useAndDispose {
assertThat(getOptionValue("foo")).isEqualTo("bar")
setOption("foo", "not bar")
saveStore()
}
moduleFile.loadModule().useAndDispose {
assertThat(getOptionValue("foo")).isEqualTo("not bar")
setOption("foo", "not bar")
// ensure that save the same data will not lead to any problems (like "Content equals, but it must be handled not on this level")
saveStore()
}
}
@Test fun `newModule should always create a new module from scratch`() {
val moduleFile = runWriteAction {
VfsTestUtil.createFile(tempDirManager.newVirtualDirectory("module"), "test.iml", "<module type=\"JAVA_MODULE\" foo=\"bar\" version=\"4\" />")
}
Paths.get(moduleFile.path).createModule().useAndDispose {
assertThat(getOptionValue("foo")).isNull()
}
}
@Test fun `must be empty if classpath storage`() {
// we must not use VFS here, file must not be created
val moduleFile = tempDirManager.newPath("module", refreshVfs = true).resolve("test.iml")
moduleFile.createModule().useAndDispose {
ModuleRootModificationUtil.addContentRoot(this, moduleFile.parentSystemIndependentPath)
saveStore()
assertThat(moduleFile).isRegularFile
assertThat(moduleFile.readText()).startsWith("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<module type=\"JAVA_MODULE\" version=\"4\">")
ClasspathStorage.setStorageType(ModuleRootManager.getInstance(this), "eclipse")
saveStore()
assertThat(moduleFile).hasContent("""<?xml version="1.0" encoding="UTF-8"?>
<module classpath="eclipse" classpath-dir="$MODULE_DIR" type="JAVA_MODULE" version="4" />""")
}
}
@Test fun `one batch update session if several modules changed`() {
val nameToCount = TObjectIntHashMap<String>()
val root = tempDirManager.newPath(refreshVfs = true)
fun Module.addContentRoot() {
val moduleName = name
var batchUpdateCount = 0
nameToCount.put(moduleName, batchUpdateCount)
messageBus.connect().subscribe(BatchUpdateListener.TOPIC, object : BatchUpdateListener {
override fun onBatchUpdateStarted() {
nameToCount.put(moduleName, ++batchUpdateCount)
}
})
//
ModuleRootModificationUtil.addContentRoot(this, root.resolve(moduleName).systemIndependentPath)
assertThat(contentRootUrls).hasSize(1)
saveStore()
}
fun Module.removeContentRoot() {
val modulePath = stateStore.stateStorageManager.expandMacros(StoragePathMacros.MODULE_FILE)
val moduleFile = Paths.get(modulePath)
assertThat(moduleFile).isRegularFile()
val virtualFile = LocalFileSystem.getInstance().findFileByPath(modulePath)!!
val newData = moduleFile.readText().replace("<content url=\"file://\$MODULE_DIR$/$name\" />\n", "").toByteArray()
runWriteAction {
virtualFile.setBinaryContent(newData)
}
}
fun Module.assertChangesApplied() {
assertThat(contentRootUrls).isEmpty()
}
val m1 = root.resolve("m1.iml").createModule()
val m2 = root.resolve("m2.iml").createModule()
var projectBatchUpdateCount = 0
projectRule.project.messageBus.connect(m1).subscribe(BatchUpdateListener.TOPIC, object : BatchUpdateListener {
override fun onBatchUpdateStarted() {
nameToCount.put("p", ++projectBatchUpdateCount)
}
})
m1.addContentRoot()
m2.addContentRoot()
m1.removeContentRoot()
m2.removeContentRoot()
(ProjectManager.getInstance() as StoreAwareProjectManager).flushChangedProjectFileAlarm()
m1.assertChangesApplied()
m2.assertChangesApplied()
assertThat(nameToCount.size()).isEqualTo(3)
assertThat(nameToCount.get("p")).isEqualTo(1)
assertThat(nameToCount.get("m1")).isEqualTo(1)
assertThat(nameToCount.get("m1")).isEqualTo(1)
}
}
val Module.contentRootUrls: Array<String>
get() = ModuleRootManager.getInstance(this).contentRootUrls
fun ProjectRule.createModule(path: Path): Module {
val p = project
return runWriteAction { ModuleManager.getInstance(p).newModule(path.systemIndependentPath, ModuleTypeId.JAVA_MODULE) }
}
|
apache-2.0
|
350896d7283a4472e3f3e9d4276a906a
| 35.310734 | 191 | 0.726113 | 4.636364 | false | true | false | false |
signed/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/diagnostic/logger.kt
|
1
|
1747
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.diagnostic
import com.intellij.openapi.progress.ProcessCanceledException
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.javaGetter
inline fun <reified T : Any> logger(): Logger = Logger.getInstance(T::class.java)
fun logger(category: String) = Logger.getInstance(category)
/**
* Get logger instance to be used in Kotlin package methods. Usage:
* ```
* private val LOG: Logger get() = logger(::LOG) // define at top level of the file containing the function
* ```
* In Kotlin 1.1 even simpler declaration will be possible:
* ```
* private val LOG: Logger = logger(::LOG)
* ```
* Notice explicit type declaration which can't be skipped in this case.
*/
fun logger(field: KProperty<Logger>) = Logger.getInstance(field.javaGetter!!.declaringClass)
inline fun Logger.debug(e: Exception? = null, lazyMessage: () -> String) {
if (isDebugEnabled) {
debug(lazyMessage(), e)
}
}
inline fun <T> Logger.catchAndLog(runnable: () -> T): T? {
try {
return runnable()
}
catch (e: ProcessCanceledException) {
return null
}
catch (e: Throwable) {
error(e)
return null
}
}
|
apache-2.0
|
97c0ef50b0a225555123c6be5fb6b535
| 30.214286 | 108 | 0.713795 | 3.934685 | false | false | false | false |
angcyo/RLibrary
|
uiview/src/main/java/com/angcyo/uiview/game/layer/BaseTouchLayer.kt
|
1
|
14649
|
package com.angcyo.uiview.game.layer
import android.graphics.Canvas
import android.graphics.PointF
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.view.MotionEvent
import com.angcyo.library.utils.L
import com.angcyo.uiview.game.spirit.BaseLayerBean
import com.angcyo.uiview.game.spirit.TouchSpiritBean
import com.angcyo.uiview.helper.BezierHelper
import com.angcyo.uiview.kotlin.nowTime
import com.angcyo.uiview.utils.ScreenUtil
import com.angcyo.uiview.utils.ThreadExecutor
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:接收Touch事件, 可以用来操作界面的Layer
* 创建人员:Robi
* 创建时间:2017/12/16 14:04
* 修改人员:Robi
* 修改时间:2017/12/16 14:04
* 修改备注:
* Version: 1.0.0
*/
abstract class BaseTouchLayer : BaseFrameLayer() {
val TAG = "BaseTouchLayer"
/**每次新增精灵的数量*/
var addSpiritNum = 5
/**需要绘制多少个贝塞尔曲线周期*/
var bezierPart = 0.25F
/**每次新增 时间间隔*/
var spiritAddInterval = 700L
set(value) {
drawIntervalThreadTime = value
field = value
}
/**最大数量 -1 表示无限循环*/
var maxSpiritNum = 100
/**点到的时候, 自动移出*/
var removeOnTouch = true
/*精灵列表*/
private val spiritList = frameList
/**精灵点击事件*/
var onClickSpiritListener: OnClickSpiritListener? = null
/**游戏开始渲染后的绘制回调*/
var onLayerDrawListener: OnLayerDrawListener? = null
/*已经添加了多少个*/
private var spiritAddNumEd = 0
/**点中了多少个Rain*/
var touchUpSpiritNum = 0
/**是否结束添加*/
protected var isSpiritAddEnd = false
/**是否需要检查Touch事件*/
protected var checkTouchEvent = true
/*开始绘制的时间, 游戏开始的时间*/
private var startDrawTime = 0L
/*在那个位置按下了*/
protected val touchPointF: PointF by lazy {
PointF()
}
override var pauseDrawFrame: Boolean = true
set(value) {
field = value
if (!field) {
//开始绘制
startDrawTime = System.currentTimeMillis()
} else {
startDrawTime = 0L
}
}
init {
//drawIntervalTime = spiritAddInterval
drawIntervalThreadTime = spiritAddInterval
pauseDrawFrame = true //暂停绘制
}
/**重置精灵状态参数*/
fun reset() {
spiritList.clear()
spiritAddNumEd = 0
touchUpSpiritNum = 0
isSpiritAddEnd = false
pauseDrawFrame = true //暂停绘制
onRenderStartTime = nowTime()
}
/**结束绘制*/
fun endSpirit() {
val showNum = spiritList.size
spiritList.clear()
isSpiritAddEnd = true
val addNum = spiritAddNumEd
val maxNum = maxSpiritNum
pauseDrawFrame = true //暂停绘制
L.e(TAG, "call: endSpirit -> showNum:$showNum addNum:$addNum maxNum:$maxNum touchUpNum:$touchUpSpiritNum")
//listener?.onRainEnd(addNum, showNum, maxNum, touchUpNum)
}
/**当屏幕上的Spirit滚动出屏之后, 再结束*/
fun delayEndSpirit() {
spiritAddNumEd = maxSpiritNum
}
override fun draw(canvas: Canvas, gameStartTime: Long /*最开始渲染的时间*/, lastRenderTime: Long, nowRenderTime: Long /*现在渲染的时候*/) {
if (!pauseDrawFrame) {
onLayerDrawListener?.onLayerDraw(startDrawTime, nowRenderTime)
}
if (isSpiritAddEnd) {
return
}
super.draw(canvas, gameStartTime, lastRenderTime, nowRenderTime)
//updateSpiritList()
}
override fun drawThread(gameStartTime: Long, lastRenderTimeThread: Long, nowRenderTime: Long) {
if (isSpiritAddEnd || pauseDrawFrame) {
return
}
super.drawThread(gameStartTime, lastRenderTimeThread, nowRenderTime)
updateSpiritList()
}
override fun onDraw(canvas: Canvas, gameStartTime: Long, lastRenderTime: Long, nowRenderTime: Long) {
super.onDraw(canvas, gameStartTime, lastRenderTime, nowRenderTime)
//checkAddNewSpirit()
onLayerDrawListener?.onLayerOnDraw(startDrawTime, nowRenderTime)
}
override fun onDrawThread(gameStartTime: Long, lastRenderTimeThread: Long, nowRenderTime: Long) {
if (isSpiritAddEnd || pauseDrawFrame) {
return
}
super.onDrawThread(gameStartTime, lastRenderTimeThread, nowRenderTime)
checkAddNewSpirit()
}
/**移除Spirit*/
fun removeSpirit(bean: TouchSpiritBean) {
synchronized(lock) {
spiritList.remove(bean)
}
}
override fun onTouchEvent(event: MotionEvent, point: PointF): Boolean {
touchPointF.set(point)
if (!checkTouchEvent) {
return super.onTouchEvent(event, point)
}
if (isSpiritAddEnd) {
return super.onTouchEvent(event, point)
}
if (!spiritList.isEmpty()) {
return checkTouchListener(point.x.toInt(), point.y.toInt())
}
return super.onTouchEvent(event, point)
}
protected fun checkTouchListener(x: Int, y: Int): Boolean {
var isIn = false
synchronized(lock) {
for (i in spiritList.size - 1 downTo 0) {
val spiritBean: TouchSpiritBean = spiritList[i] as TouchSpiritBean
//L.w("check", "${spiritBean.getRect()} $x $y ${spiritBean.isIn(x, y)}")
if (spiritBean.isIn(x, y)) {
touchUpSpiritNum++
onClickSpiritListener?.onClickSpirit(this, spiritBean, x, y)
isIn = true
if (removeOnTouch) {
removeSpirit(spiritBean)
}
break
}
}
}
return isIn
}
/**检查是否需要添加新的精灵*/
protected fun checkAddNewSpirit() {
if (maxSpiritNum == -1) {
//无限循环
if (spiritAddNumEd == maxSpiritNum) {
//需要结束了
if (spiritList.isEmpty()) {
//所有Rain, 移除了屏幕
ThreadExecutor.instance().onMain {
endSpirit()
}
}
} else {
addNewRainInner(addSpiritNum)
}
} else {
if (spiritAddNumEd >= maxSpiritNum) {
//所有Rain 添加完毕
if (spiritList.isEmpty()) {
//所有Rain, 移除了屏幕
ThreadExecutor.instance().onMain {
endSpirit()
}
}
} else if (spiritAddNumEd + addSpiritNum > maxSpiritNum) {
//达到最大
addNewRainInner(maxSpiritNum - spiritAddNumEd)
} else {
addNewRainInner(addSpiritNum)
}
}
}
/**更新精灵配置*/
protected fun updateSpiritList() {
val removeList = mutableListOf<TouchSpiritBean>()
synchronized(lock) {
for (index in 0 until spiritList.size) {
val bean: TouchSpiritBean = spiritList[index] as TouchSpiritBean
val onUpdateSpiritList = bean.onUpdateSpiritList()
if (onUpdateSpiritList) {
} else {
//L.i("call: updateSpiritList1 -> index:${bean.updateIndex} startY:${bean.startY} top:${bean.getTop()}")
bean.offset(0, (bean.stepY /*ScreenUtil.density*/).toInt())
if (bean.useBezier) {
if (bean.stepY < 0) {
//从下往上飘
val maxY = bean.startY / bezierPart /*分成5份, 循环5次曲线*/
if (maxY > 0) {
//计算Y轴, 在贝塞尔曲线上变化的0-1f的比例, 从而计算出x的坐标
val fl = Math.abs((bean.startY - bean.getSpiritDrawRect().centerY()) % (maxY + 1) / maxY.toFloat())
val evaluate = bean.bezierHelper!!.evaluate(fl)
val dx = (evaluate - bean.getSpiritDrawRect().centerX()).toInt()
if (dx < bean.getSpiritDrawRect().width()) {
//控制位移的幅度, 防止漂移现象
bean.offset(dx, 0)
//L.e("updateRainList ->evaluate:$evaluate fl:$fl dx:$dx $maxY")
}
}
} else {
//从上往下飘
val maxY = (gameRenderView.measuredHeight - bean.startY) / bezierPart /*分成5份, 循环5次曲线*/
if (maxY > 0) {
val fl = Math.abs((bean.getSpiritDrawRect().centerY() - bean.startY) % (maxY + 1) / maxY.toFloat())
val dx = (bean.bezierHelper!!.evaluate(fl) - bean.getSpiritDrawRect().centerX()).toInt()
if (dx < bean.getSpiritDrawRect().width()) {
//控制位移的幅度, 防止漂移现象
bean.offset(dx, 0)
}
//L.e("updateRainList -> fl:$fl dx:$dx ${bean.getRect()} $maxY")
}
}
}
}
bean.updateIndex++
if (isSpiritRemoveFromLayer(bean)) {
//移动到屏幕外了,需要移除
removeList.add(bean)
}
}
spiritList.removeAll(removeList)
}
}
/**是否移除了屏幕*/
open protected fun isSpiritRemoveFromLayer(spirit: TouchSpiritBean): Boolean {
if (spirit.stepY < 0) {
//往上移动
val bottom = spirit.getDrawBottom()
return bottom <= 0
}
//往下移动
val top = spirit.getDrawTop()
//L.w("call: updateSpiritList2 -> index:${bean.updateIndex} startY:${bean.startY} top:$top")
return top > gameRenderView.measuredHeight
}
//添加精灵
protected fun addNewRainInner(num: Int) {
//L.e(TAG, "call: addNewRainInner -> $num")
synchronized(lock) {
for (i in 0 until num) {
spiritList.add(onAddNewSpirit())
spiritAddNumEd++
}
}
}
fun getDrawable(id: Int): Drawable {
return ContextCompat.getDrawable(gameRenderView.context, id)!!
}
/**添加新的精灵*/
abstract fun onAddNewSpirit(): TouchSpiritBean
/**精灵的默认基础配置*/
protected fun initSpirit(spiritBean: TouchSpiritBean) {
val randomStepY = spiritBean.stepY + random.nextInt(5)
if (spiritBean.randomStep) {
spiritBean.stepY = randomStepY
}
val sw = if (gameRenderView.measuredWidth == 0) ScreenUtil.screenWidth else gameRenderView.measuredWidth
val drawable = spiritBean.drawableArray[0]
val intrinsicWidth = (drawable.intrinsicWidth * ScreenUtil.density()).toInt()
val intrinsicHeight = (drawable.intrinsicHeight * ScreenUtil.density()).toInt()
spiritBean.startX = getSpiritStartX(spiritBean, sw)
spiritBean.startY = getSpiritStartY(spiritBean)
spiritBean.bezierHelper = createBezierHelper(spiritBean, spiritBean.startX, spiritBean.startY, intrinsicWidth, intrinsicHeight)
var sx = spiritBean.startX
var sy = spiritBean.startY
if (spiritBean.useBezier) {
sx = spiritBean.bezierHelper!!.evaluate(0f).toInt()
//L.w("updateRainList getSpiritStartX:$getSpiritStartX $sx ${spiritBean.bezierHelper!!.evaluate(1f).toInt()}")
}
//L.e("call: initSpirit -> startX:$sx startY:$sy step:${spiritBean.stepY}")
//spiritBean.setRect(sx, sy, intrinsicWidth, intrinsicHeight)
initSpiritRect(spiritBean, sx, sy, intrinsicWidth, intrinsicHeight)
}
open protected fun initSpiritRect(spiritBean: TouchSpiritBean, sx: Int, sy: Int, width: Int, height: Int) {
spiritBean.setRect(sx, sy, width, height)
}
open protected fun createBezierHelper(spirit: TouchSpiritBean, randomX: Int, randomY: Int, intrinsicWidth: Int, intrinsicHeight: Int): BezierHelper {
val randomStepY = random.nextInt(7)
val x: Float = randomX.toFloat()
val left = randomStepY % 2 == 0 //优先向左飘
val cp1: Float = if (left) (x - intrinsicWidth) else (x + intrinsicWidth)
val cp2: Float = if (left) (x + intrinsicWidth) else (x - intrinsicWidth)
return BezierHelper(x, x, cp1, cp2)
}
/*随机产生x轴*/
open protected fun getSpiritStartX(spiritBean: TouchSpiritBean, sw: Int): Int {
val width = spiritBean.width() * spiritBean.scaleX
if (spiritBean.useBezier) {
return (random.nextFloat() * (sw - 2 * width) + width).toInt()
} else {
return (random.nextFloat() * (sw - width) + width / 4).toInt()
}
}
/*随机产生y轴*/
open protected fun getSpiritStartY(spiritBean: TouchSpiritBean): Int {
val height = spiritBean.height() * spiritBean.scaleY
return (-(random.nextFloat() * height / 2) - height).toInt()
}
override fun addFrameBean(frameBean: BaseLayerBean) {
//super.addFrameBean(frameBean)
}
}
interface OnClickSpiritListener {
fun onClickSpirit(baseTouchLayer: BaseTouchLayer, spiritBean: TouchSpiritBean, x: Int, y: Int)
}
interface OnLayerDrawListener {
fun onLayerDraw(startDrawTime: Long, nowDrawTime: Long)
fun onLayerOnDraw(startDrawTime: Long, nowDrawTime: Long)
}
|
apache-2.0
|
2ea8cf1e0315b042f85351f556d763ff
| 32.645729 | 153 | 0.547472 | 3.894633 | false | false | false | false |
shyiko/ktlint
|
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/ChainWrappingRule.kt
|
1
|
6610
|
package com.pinterest.ktlint.ruleset.standard
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType.ANDAND
import com.pinterest.ktlint.core.ast.ElementType.COMMA
import com.pinterest.ktlint.core.ast.ElementType.DIV
import com.pinterest.ktlint.core.ast.ElementType.DOT
import com.pinterest.ktlint.core.ast.ElementType.ELSE_KEYWORD
import com.pinterest.ktlint.core.ast.ElementType.ELVIS
import com.pinterest.ktlint.core.ast.ElementType.LBRACE
import com.pinterest.ktlint.core.ast.ElementType.LPAR
import com.pinterest.ktlint.core.ast.ElementType.MINUS
import com.pinterest.ktlint.core.ast.ElementType.MUL
import com.pinterest.ktlint.core.ast.ElementType.OROR
import com.pinterest.ktlint.core.ast.ElementType.PERC
import com.pinterest.ktlint.core.ast.ElementType.PLUS
import com.pinterest.ktlint.core.ast.ElementType.PREFIX_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.SAFE_ACCESS
import com.pinterest.ktlint.core.ast.ElementType.WHEN_CONDITION_WITH_EXPRESSION
import com.pinterest.ktlint.core.ast.ElementType.WHITE_SPACE
import com.pinterest.ktlint.core.ast.isPartOfComment
import com.pinterest.ktlint.core.ast.nextCodeLeaf
import com.pinterest.ktlint.core.ast.nextLeaf
import com.pinterest.ktlint.core.ast.prevCodeLeaf
import com.pinterest.ktlint.core.ast.prevLeaf
import com.pinterest.ktlint.core.ast.upsertWhitespaceAfterMe
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet
import org.jetbrains.kotlin.lexer.KtTokens
class ChainWrappingRule : Rule("chain-wrapping") {
private val sameLineTokens = TokenSet.create(MUL, DIV, PERC, ANDAND, OROR)
private val prefixTokens = TokenSet.create(PLUS, MINUS)
private val nextLineTokens = TokenSet.create(DOT, SAFE_ACCESS, ELVIS)
private val noSpaceAroundTokens = TokenSet.create(DOT, SAFE_ACCESS)
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
/*
org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement (DOT) | "."
org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl (WHITE_SPACE) | "\n "
org.jetbrains.kotlin.psi.KtCallExpression (CALL_EXPRESSION)
*/
val elementType = node.elementType
if (nextLineTokens.contains(elementType)) {
if (node.isPartOfComment()) {
return
}
val nextLeaf = node.nextCodeLeaf()?.prevLeaf()
if (nextLeaf?.elementType == WHITE_SPACE &&
nextLeaf.textContains('\n')
) {
emit(node.startOffset, "Line must not end with \"${node.text}\"", true)
if (autoCorrect) {
// rewriting
// <prevLeaf><node="."><nextLeaf="\n"> to
// <prevLeaf><delete space if any><nextLeaf="\n"><node="."><space if needed>
// (or)
// <prevLeaf><node="."><spaceBeforeComment><comment><nextLeaf="\n"> to
// <prevLeaf><delete space if any><spaceBeforeComment><comment><nextLeaf="\n"><node="."><space if needed>
val prevLeaf = node.prevLeaf()
if (prevLeaf is PsiWhiteSpace) {
prevLeaf.node.treeParent.removeChild(prevLeaf.node)
}
if (!noSpaceAroundTokens.contains(elementType)) {
(nextLeaf as LeafElement).upsertWhitespaceAfterMe(" ")
}
node.treeParent.removeChild(node)
(nextLeaf as LeafElement).rawInsertAfterMe(node as LeafElement)
}
}
} else if (sameLineTokens.contains(elementType) || prefixTokens.contains(elementType)) {
if (node.isPartOfComment()) {
return
}
val prevLeaf = node.prevLeaf()
if (
prevLeaf?.elementType == WHITE_SPACE &&
prevLeaf.textContains('\n') &&
// fn(*typedArray<...>()) case
(elementType != MUL || !prevLeaf.isPartOfSpread()) &&
// unary +/-
(!prefixTokens.contains(elementType) || !node.isInPrefixPosition()) &&
// LeafPsiElement->KtOperationReferenceExpression->KtPrefixExpression->KtWhenConditionWithExpression
!node.isPartOfWhenCondition()
) {
emit(node.startOffset, "Line must not begin with \"${node.text}\"", true)
if (autoCorrect) {
// rewriting
// <insertionPoint><prevLeaf="\n"><node="&&"><nextLeaf=" "> to
// <insertionPoint><prevLeaf=" "><node="&&"><nextLeaf="\n"><delete node="&&"><delete nextLeaf=" ">
// (or)
// <insertionPoint><spaceBeforeComment><comment><prevLeaf="\n"><node="&&"><nextLeaf=" "> to
// <insertionPoint><space if needed><node="&&"><spaceBeforeComment><comment><prevLeaf="\n"><delete node="&&"><delete nextLeaf=" ">
val nextLeaf = node.nextLeaf()
if (nextLeaf is PsiWhiteSpace) {
nextLeaf.node.treeParent.removeChild(nextLeaf.node)
}
val insertionPoint = prevLeaf.prevCodeLeaf() as LeafPsiElement
node.treeParent.removeChild(node)
insertionPoint.rawInsertAfterMe(node as LeafPsiElement)
if (!noSpaceAroundTokens.contains(elementType)) {
insertionPoint.upsertWhitespaceAfterMe(" ")
}
}
}
}
}
private fun ASTNode.isPartOfSpread() =
prevCodeLeaf()?.let { leaf ->
val type = leaf.elementType
type == LPAR ||
type == COMMA ||
type == LBRACE ||
type == ELSE_KEYWORD ||
KtTokens.OPERATIONS.contains(type)
} == true
private fun ASTNode.isInPrefixPosition() =
treeParent?.treeParent?.elementType == PREFIX_EXPRESSION
private fun ASTNode.isPartOfWhenCondition() =
treeParent?.treeParent?.treeParent?.elementType == WHEN_CONDITION_WITH_EXPRESSION
}
|
mit
|
eef278e057311056d573ab268638c33c
| 49.075758 | 150 | 0.620424 | 4.674682 | false | false | false | false |
roadmaptravel/Rome2RioAndroid
|
library/src/main/java/com/getroadmap/r2rlib/models/Icon.kt
|
1
|
1353
|
package com.getroadmap.r2rlib.models
import android.os.Parcel
import android.os.Parcelable
/**
* Created by jan on 08/07/16.
* "icon": implements Parcelable {
* "url": "/logos/trains/nl.png",
* "x": 0,
* "y": 0,
* "w": 27,
* "h": 23
* }
*/
open class Icon() : Parcelable {
private var url: String? = null
private var x: Int? = null
private var y: Int? = null
private var w: Int? = null
private var h: Int? = null
constructor(parcel: Parcel) : this() {
url = parcel.readString()
x = parcel.readValue(Int::class.java.classLoader) as? Int
y = parcel.readValue(Int::class.java.classLoader) as? Int
w = parcel.readValue(Int::class.java.classLoader) as? Int
h = parcel.readValue(Int::class.java.classLoader) as? Int
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(url)
parcel.writeValue(x)
parcel.writeValue(y)
parcel.writeValue(w)
parcel.writeValue(h)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Icon> {
override fun createFromParcel(parcel: Parcel): Icon {
return Icon(parcel)
}
override fun newArray(size: Int): Array<Icon?> {
return arrayOfNulls(size)
}
}
}
|
apache-2.0
|
7108147f45acc18d2b684ec04ed1d5cf
| 24.074074 | 65 | 0.605322 | 3.696721 | false | false | false | false |
ruuvi/Android_RuuvitagScanner
|
app/src/main/java/com/ruuvi/station/network/domain/RuuviNetworkInteractor.kt
|
1
|
7798
|
package com.ruuvi.station.network.domain
import com.ruuvi.station.database.tables.RuuviTagEntity
import com.ruuvi.station.network.data.NetworkTokenInfo
import com.ruuvi.station.network.data.request.*
import com.ruuvi.station.network.data.response.*
import kotlinx.coroutines.*
import timber.log.Timber
import java.util.*
class RuuviNetworkInteractor (
private val tokenRepository: NetworkTokenRepository,
private val networkRepository: RuuviNetworkRepository
) {
val signedIn: Boolean
get() = getToken() != null
fun getEmail() = getToken()?.email
private fun getToken() = tokenRepository.getTokenInfo()
private var userInfo: UserInfoResponse? = null
val mainScope = CoroutineScope(Dispatchers.Main)
val ioScope = CoroutineScope(Dispatchers.IO)
init {
getUserInfo {}
}
fun registerUser(user: UserRegisterRequest, onResult: (UserRegisterResponse?) -> Unit) {
networkRepository.registerUser(user) {
onResult(it)
}
}
fun verifyUser(token: String, onResult: (UserVerifyResponse?) -> Unit) {
networkRepository.verifyUser(token) { response ->
response?.let {
if (response.error.isNullOrEmpty() && response.data != null) {
tokenRepository.saveTokenInfo(
NetworkTokenInfo(response.data.email, response.data.accessToken))
}
}
onResult(response)
}
}
fun getUserInfo(onResult: (UserInfoResponse?) -> Unit) {
ioScope.launch {
val result = getUserInfo()
withContext(Dispatchers.Main) {
onResult(result)
}
}
}
suspend fun getUserInfo(): UserInfoResponse? {
val token = getToken()
if (token != null) {
val benchUpdate1 = Date()
userInfo = networkRepository.getUserInfo(token.token)
val benchUpdate2 = Date()
Timber.d("benchmark-getUserInfo-finish ${benchUpdate2.time - benchUpdate1.time} ms")
return userInfo
} else {
return null
}
}
fun getSensorNetworkStatus(mac: String): SensorDataResponse? {
return userInfo?.data?.sensors?.firstOrNull {it.sensor == mac}
}
fun claimSensor(tag: RuuviTagEntity, onResult: (ClaimSensorResponse?) -> Unit) {
val token = getToken()?.token
token?.let {
val request = ClaimSensorRequest(tag.displayName, tag.id.toString())
networkRepository.claimSensor(request, token) { claimResponse ->
getUserInfo {
onResult(claimResponse)
}
}
}
}
fun unclaimSensor(tagId: String) {
val token = getToken()?.token
token?.let {
ioScope.launch {
networkRepository.unclaimSensor(UnclaimSensorRequest(tagId), token)
}
}
}
fun shareSensor(recipientEmail: String, tagId: String, handler: CoroutineExceptionHandler, onResult: (ShareSensorResponse?) -> Unit) {
val token = getToken()?.token
CoroutineScope(Dispatchers.IO).launch(handler) {
token?.let {
val request = ShareSensorRequest(recipientEmail, tagId)
val response = networkRepository.shareSensor(request, token)
withContext(Dispatchers.Main) {
onResult(response)
}
}
}
}
fun unshareSensor(recipientEmail: String, tagId: String, handler: CoroutineExceptionHandler, onResult: (ShareSensorResponse?) -> Unit) {
val token = getToken()?.token
CoroutineScope(Dispatchers.IO).launch(handler) {
token?.let {
val request = UnshareSensorRequest(recipientEmail, tagId)
val response = networkRepository.unshareSensor(request, token)
withContext(Dispatchers.Main) {
onResult(response)
}
}
}
}
fun unshareAll(tagId: String, handler: CoroutineExceptionHandler, onResult: (Boolean) -> Unit) {
val token = getToken()?.token
CoroutineScope(Dispatchers.IO).launch(handler) {
token?.let {
val sharedInfo = networkRepository.getSharedSensors(it)
if (sharedInfo?.data?.sensors?.isEmpty() == false) {
val emails = sharedInfo.data.sensors.filter { it.sensor == tagId }.map { it.sharedTo }
if (emails.isEmpty() == false) {
for (email in emails) {
val request = UnshareSensorRequest(email, tagId)
networkRepository.unshareSensor(request, token)
}
onResult(true)
}
}
}
}
}
fun getShаredInfo(tagId: String, handler: CoroutineExceptionHandler, onResult: (List<SharedSensorDataResponse>?) -> Unit) {
val token = getToken()?.token
CoroutineScope(Dispatchers.IO).launch(handler) {
token?.let {
val response = networkRepository.getSharedSensors(it)
Timber.d("getShаredInfo ${response.toString()}")
if (response?.data != null) {
val result = response.data.sensors.filter { it.sensor == tagId }
withContext(Dispatchers.Main) {
onResult(result)
}
}
}
}
}
fun getSensorData(request: GetSensorDataRequest, onResult: (GetSensorDataResponse?) -> Unit) {
val token = getToken()?.token
mainScope.launch {
token?.let {
val result = networkRepository.getSensorData(token, request )
onResult(result)
}
}
}
fun updateSensor(tagId: String, newName: String, handler: CoroutineExceptionHandler, onResult: (UpdateSensorResponse?) -> Unit) {
val token = getToken()?.token
CoroutineScope(Dispatchers.IO).launch(handler) {
token?.let {
val request = UpdateSensorRequest(tagId, newName)
val response = networkRepository.updateSensor(request, token)
withContext(Dispatchers.Main) {
onResult(response)
}
}
}
}
fun uploadImage(tagId: String, filename: String, handler: CoroutineExceptionHandler, onResult: (UploadImageResponse?) -> Unit) {
val token = getToken()?.token
CoroutineScope(Dispatchers.IO).launch(handler) {
token?.let {
val request = UploadImageRequest(tagId, "image/jpeg")
val response = networkRepository.uploadImage(filename, request, token)
withContext(Dispatchers.Main) {
onResult(response)
}
}
}
}
fun resetImage(tagId: String, handler: CoroutineExceptionHandler, onResult: (UploadImageResponse?) -> Unit) {
val token = getToken()?.token
CoroutineScope(Dispatchers.IO).launch(handler) {
token?.let {
val request = UploadImageRequest.getResetImageRequest(tagId)
val response = networkRepository.resetImage(request, token)
withContext(Dispatchers.Main) {
onResult(response)
}
}
}
}
suspend fun getSensorData(request: GetSensorDataRequest):GetSensorDataResponse? = withContext(Dispatchers.IO) {
val token = getToken()?.token
token?.let {
return@withContext networkRepository.getSensorData(token, request)
}
}
}
|
mit
|
d4ef058739d1787210b74347949644a4
| 35.773585 | 140 | 0.578245 | 5.042691 | false | false | false | false |
Bombe/Sone
|
src/main/kotlin/net/pterodactylus/sone/web/pages/EditProfilePage.kt
|
1
|
3867
|
package net.pterodactylus.sone.web.pages
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.data.Profile.*
import net.pterodactylus.sone.main.*
import net.pterodactylus.sone.text.*
import net.pterodactylus.sone.utils.*
import net.pterodactylus.sone.web.*
import net.pterodactylus.sone.web.page.*
import net.pterodactylus.util.template.*
import javax.inject.*
/**
* This page lets the user edit her profile.
*/
@MenuName("EditProfile")
@TemplatePath("/templates/editProfile.html")
@ToadletPath("editProfile.html")
class EditProfilePage @Inject constructor(webInterface: WebInterface, loaders: Loaders, templateRenderer: TemplateRenderer) :
LoggedInPage("Page.EditProfile.Title", webInterface, loaders, templateRenderer) {
override fun handleRequest(soneRequest: SoneRequest, currentSone: Sone, templateContext: TemplateContext) {
currentSone.profile.let { profile ->
templateContext["firstName"] = profile.firstName
templateContext["middleName"] = profile.middleName
templateContext["lastName"] = profile.lastName
templateContext["birthDay"] = profile.birthDay
templateContext["birthMonth"] = profile.birthMonth
templateContext["birthYear"] = profile.birthYear
templateContext["avatarId"] = profile.avatar
templateContext["fields"] = profile.fields
if (soneRequest.isPOST) {
if (soneRequest.httpRequest.getPartAsStringFailsafe("save-profile", 4) == "true") {
profile.firstName = soneRequest.httpRequest.getPartAsStringFailsafe("first-name", 256).trim()
profile.middleName = soneRequest.httpRequest.getPartAsStringFailsafe("middle-name", 256).trim()
profile.lastName = soneRequest.httpRequest.getPartAsStringFailsafe("last-name", 256).trim()
profile.birthDay = soneRequest.httpRequest.getPartAsStringFailsafe("birth-day", 256).trim().toIntOrNull()
profile.birthMonth = soneRequest.httpRequest.getPartAsStringFailsafe("birth-month", 256).trim().toIntOrNull()
profile.birthYear = soneRequest.httpRequest.getPartAsStringFailsafe("birth-year", 256).trim().toIntOrNull()
profile.setAvatar(soneRequest.core.getImage(soneRequest.httpRequest.getPartAsStringFailsafe("avatarId", 256).trim(), false))
profile.fields.forEach { field ->
field.value = TextFilter.filter(soneRequest.httpRequest.getHeader("Host"), soneRequest.httpRequest.getPartAsStringFailsafe("field-${field.id}", 400).trim())
}
currentSone.profile = profile
soneRequest.core.touchConfiguration()
redirectTo("editProfile.html")
} else if (soneRequest.httpRequest.getPartAsStringFailsafe("add-field", 4) == "true") {
val fieldName = soneRequest.httpRequest.getPartAsStringFailsafe("field-name", 100)
try {
profile.addField(fieldName)
currentSone.profile = profile
soneRequest.core.touchConfiguration()
redirectTo("editProfile.html#profile-fields")
} catch (e: DuplicateField) {
templateContext["fieldName"] = fieldName
templateContext["duplicateFieldName"] = true
}
} else profile.fields.forEach { field ->
if (soneRequest.httpRequest.getPartAsStringFailsafe("delete-field-${field.id}", 4) == "true") {
redirectTo("deleteProfileField.html?field=${field.id}")
} else if (soneRequest.httpRequest.getPartAsStringFailsafe("edit-field-${field.id}", 4) == "true") {
redirectTo("editProfileField.html?field=${field.id}")
} else if (soneRequest.httpRequest.getPartAsStringFailsafe("move-down-field-${field.id}", 4) == "true") {
profile.moveFieldDown(field)
currentSone.profile = profile
redirectTo("editProfile.html#profile-fields")
} else if (soneRequest.httpRequest.getPartAsStringFailsafe("move-up-field-${field.id}", 4) == "true") {
profile.moveFieldUp(field)
currentSone.profile = profile
redirectTo("editProfile.html#profile-fields")
}
}
}
}
}
}
|
gpl-3.0
|
b54473ffe58f13f2bcbc637f8f299a2e
| 49.220779 | 162 | 0.740626 | 4.028125 | false | false | false | false |
FurhatRobotics/example-skills
|
demo-skill/src/main/kotlin/furhatos/app/demo/flow/autoBehavior/lookingAround.kt
|
1
|
776
|
package furhatos.app.demo.flow.autoBehavior
import furhatos.app.demo.LOOKAROUND_INTERVAL
import furhatos.app.demo.util.getRandomNearbyLocation
import furhatos.flow.kotlin.State
import furhatos.flow.kotlin.furhat
import furhatos.flow.kotlin.state
import furhatos.flow.kotlin.users
import furhatos.records.Location
fun lookingAround(startingLocation: Location = Location(0.0, 0.0, 1.5)) : State = state {
onEntry {
furhat.attend(startingLocation)
}
onTime(repeat = LOOKAROUND_INTERVAL, instant = true) {
val userAttendActions = users.list.map {
{ furhat.attend(it) }
}.toTypedArray()
random(
*userAttendActions,
{ furhat.attend(startingLocation.getRandomNearbyLocation(0.1)) }
)
}
}
|
mit
|
6076d85cd756d6b3aafad64048a360e8
| 28.884615 | 89 | 0.70232 | 3.919192 | false | false | false | false |
google/horologist
|
audio-ui/src/androidTest/java/com/google/android/horologist/audio/ui/FakeVolumeRepository.kt
|
1
|
1393
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.horologist.audio.ui
import com.google.android.horologist.audio.VolumeRepository
import com.google.android.horologist.audio.VolumeState
import kotlinx.coroutines.flow.MutableStateFlow
class FakeVolumeRepository constructor(initial: VolumeState) : VolumeRepository {
override val volumeState: MutableStateFlow<VolumeState> = MutableStateFlow(initial)
override fun increaseVolume() {
val current = volumeState.value
volumeState.value = current.copy(current = (current.current + 1).coerceAtMost(current.max))
}
override fun decreaseVolume() {
val current = volumeState.value
volumeState.value = current.copy(current = (current.current - 1).coerceAtLeast(0))
}
override fun close() {
}
}
|
apache-2.0
|
484495cc02308c236399359d7aa34a66
| 35.657895 | 99 | 0.743001 | 4.339564 | false | false | false | false |
yshrsmz/monotweety
|
app/src/main/java/net/yslibrary/monotweety/appdata/user/remote/UserRemoteRepositoryImpl.kt
|
1
|
1480
|
package net.yslibrary.monotweety.appdata.user.remote
import com.twitter.sdk.android.core.Callback
import com.twitter.sdk.android.core.Result
import com.twitter.sdk.android.core.TwitterException
import com.twitter.sdk.android.core.services.AccountService
import io.reactivex.Single
import net.yslibrary.monotweety.appdata.user.User
import net.yslibrary.monotweety.di.UserScope
import javax.inject.Inject
import com.twitter.sdk.android.core.models.User as TwitterUser
@UserScope
class UserRemoteRepositoryImpl @Inject constructor(
private val accountService: AccountService
) : UserRemoteRepository {
override fun get(): Single<User> {
return Single.create<TwitterUser> { emitter ->
val call = accountService.verifyCredentials(false, true, false)
call.enqueue(object : Callback<TwitterUser>() {
override fun failure(exception: TwitterException) {
emitter.onError(exception)
}
override fun success(result: Result<TwitterUser>) {
emitter.onSuccess(result.data)
}
})
emitter.setCancellable { call.cancel() }
}.map { user ->
User(
id = user.id,
name = user.name,
screenName = user.screenName,
profileImageUrl = user.profileImageUrlHttps,
_updatedAt = -1 // updated in UserRepository
)
}
}
}
|
apache-2.0
|
dc445ace769cc6a085d185242f501135
| 36 | 75 | 0.642568 | 4.74359 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android
|
example/src/main/java/org/wordpress/android/fluxc/example/ui/customer/search/WooCustomersSearchBuilderFragment.kt
|
2
|
2237
|
package org.wordpress.android.fluxc.example.ui.customer.search
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import kotlinx.android.synthetic.main.fragment_woo_customers_search_builder.*
import org.wordpress.android.fluxc.example.R.layout
import org.wordpress.android.fluxc.example.replaceFragment
import org.wordpress.android.util.ToastUtils
class WooCustomersSearchBuilderFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(layout.fragment_woo_customers_search_builder, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btnCustomerSearch.setOnClickListener {
replaceFragment(
WooCustomersSearchFragment.newInstance(
siteId = requireArguments().getInt(KEY_SELECTED_SITE_ID),
searchParams = buildParams()
)
)
}
}
private fun buildParams() = WooCustomersSearchFragment.SearchParams(
searchQuery = etCustomerSearch.text?.toString(),
includeIds = etCustomerInclude.text.toIds(),
excludeIds = etCustomerExclude.text.toIds(),
email = etCustomerEmail.text?.toString(),
role = etCustomerRole.text?.toString()
)
@Suppress("SwallowedException", "TooGenericExceptionCaught")
private fun Editable?.toIds(): List<Long> {
return try {
if (this.isNullOrEmpty()) return emptyList()
this.toString().split(",\\s*").map { it.toLong() }
} catch (e: Exception) {
ToastUtils.showToast(requireContext(), "Wrongly formatted ids")
emptyList()
}
}
companion object {
fun newInstance(siteId: Int) = WooCustomersSearchBuilderFragment().apply {
arguments = Bundle().apply { putInt(KEY_SELECTED_SITE_ID, siteId) }
}
}
}
private const val KEY_SELECTED_SITE_ID = "selected_site_id"
|
gpl-2.0
|
2fe73e5f94e1e78d9396311f4ed4d015
| 38.245614 | 116 | 0.670988 | 4.821121 | false | false | false | false |
mmartin101/GhibliAPIAndroid
|
app/src/main/java/com/mmartin/ghibliapi/network/moshi/GhibliUrlWithIdAdapter.kt
|
1
|
791
|
package com.mmartin.ghibliapi.network.moshi
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
/**
* Created by mmartin on 2/3/18.
*/
class GhibliUrlWithIdAdapter {
@ToJson
fun toJson(@UrlsWithId list: List<String>): List<String> {
return list
}
@FromJson
@UrlsWithId
fun fromJson(urlsWithId: List<String>?): List<String> {
val idList = mutableListOf<String>()
urlsWithId?.forEach {
val lastForwardSlashIndex = it.lastIndexOf('/')
if (lastForwardSlashIndex == -1 || lastForwardSlashIndex == it.length - 1) {
return emptyList()
} else {
idList.add(it.slice(lastForwardSlashIndex + 1 until it.length))
}
}
return idList
}
}
|
mit
|
751e5beefd45b080c4516f6aff9f43b4
| 26.310345 | 88 | 0.608091 | 4.035714 | false | false | false | false |
kibotu/RecyclerViewPresenter
|
app/src/main/kotlin/net/kibotu/android/recyclerviewpresenter/app/screens/kotlin/LabelPresenter.kt
|
1
|
1018
|
package net.kibotu.android.recyclerviewpresenter.app.screens.kotlin
import androidx.recyclerview.widget.RecyclerView
import net.kibotu.android.recyclerviewpresenter.Presenter
import net.kibotu.android.recyclerviewpresenter.PresenterViewModel
import net.kibotu.android.recyclerviewpresenter.app.R
import net.kibotu.android.recyclerviewpresenter.app.databinding.LabelPresenterItemBinding
import net.kibotu.logger.Logger
/**
* Created by [Jan Rabe](https://kibotu.net).
*/
class LabelPresenter : Presenter<String, LabelPresenterItemBinding>(
layout = R.layout.label_presenter_item,
viewBindingAccessor = LabelPresenterItemBinding::bind
) {
override fun bindViewHolder(
viewBinding: LabelPresenterItemBinding,
viewHolder: RecyclerView.ViewHolder,
item: PresenterViewModel<String>,
payloads: MutableList<Any>?
) = with(viewBinding) {
Logger.v( "bindViewHolder ${viewHolder.adapterPosition} $item payload=$payloads" )
label.text = "${item.model}"
}
}
|
apache-2.0
|
5568238f4d615e38d92f0082b23a3af3
| 35.392857 | 90 | 0.768173 | 4.504425 | false | false | false | false |
Commit451/LabCoat
|
app/src/main/java/com/commit451/gitlab/model/api/RepositoryFile.kt
|
2
|
736
|
package com.commit451.gitlab.model.api
import android.os.Parcelable
import com.squareup.moshi.Json
import kotlinx.android.parcel.Parcelize
@Parcelize
data class RepositoryFile(
@Json(name = "file_name")
var fileName: String? = null,
@Json(name = "file_path")
var filePath: String? = null,
@Json(name = "size")
var size: Long = 0,
@Json(name = "encoding")
var encoding: String? = null,
@Json(name = "content")
var content: String,
@Json(name = "ref")
var ref: String? = null,
@Json(name = "blob_id")
var blobId: String? = null,
@Json(name = "commit_id")
var commitId: String? = null,
@Json(name = "last_commit_id")
var lastCommitId: String? = null
) : Parcelable
|
apache-2.0
|
792974771f00fdabfb867cb28ffaf0d5
| 26.259259 | 39 | 0.637228 | 3.315315 | false | false | false | false |
charlag/Promind
|
app/src/main/java/com/charlag/promind/ui/component/new_hint/NewHintFragment.kt
|
1
|
6378
|
package com.charlag.promind.ui.component.new_hint
import android.app.DatePickerDialog
import android.app.Dialog
import android.app.TimePickerDialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v4.app.Fragment
import android.support.v7.widget.Toolbar
import android.text.format.DateFormat
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.*
import com.charlag.promind.R
import com.charlag.promind.util.Empty
import com.charlag.promind.util.appComponent
import com.charlag.promind.util.rx.addTo
import com.charlag.promind.util.rx.rxClicks
import com.charlag.promind.util.rx.rxItemCeleted
import com.charlag.promind.util.rx.rxText
import com.charlag.promind.util.view.findView
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
import java.util.*
import javax.inject.Inject
/**
* Created by charlag on 18/06/2017.
*/
class NewHintFragment : Fragment(), NewHintContract.View {
@Inject @JvmField var presenter: NewHintContract.Presenter? = null
private lateinit var toolbar: Toolbar
private lateinit var titleField: EditText
private lateinit var appPicker: Spinner
private lateinit var timeFromButton: Button
private lateinit var timeToButton: Button
private lateinit var dateButton: Button
private val fromTimePickedSubject: PublishSubject<NewHintContract.Time> =
PublishSubject.create()
private val toTimePickedSubject: PublishSubject<NewHintContract.Time> = PublishSubject.create()
private val disposable = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_new_hint, container, false)
toolbar = view.findView(R.id.toolbar)
titleField = view.findView(R.id.et_title)
appPicker = view.findView(R.id.picker_app)
timeFromButton = view.findView(R.id.btn_time_from)
timeToButton = view.findView(R.id.btn_time_to)
dateButton = view.findView(R.id.btn_date)
toolbar.inflateMenu(R.menu.new_hint)
toolbar.setNavigationIcon(R.drawable.ic_close_black_24dp)
toolbar.setNavigationOnClickListener { activity.onBackPressed() }
return view
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (presenter == null) {
DaggerNewHintComponent.builder()
.appComponent(context.appComponent)
.newHintPresenterModule(NewHintPresenterModule())
.build()
.inject(this)
}
val presenter = presenter!!
presenter.attachView(this)
val appsAdapter = ArrayAdapter<String>(context, android.R.layout.simple_list_item_1)
appPicker.adapter = appsAdapter
presenter.appsList
.observeOn(AndroidSchedulers.mainThread())
.subscribe { apps ->
appsAdapter.addAll(apps.map(AppViewModel::name))
}
.addTo(disposable)
presenter.showFromTimePicker.subscribe {
TimePickerFragment(fromTimePickedSubject).show(childFragmentManager, "timePicker")
}
.addTo(disposable)
presenter.showToTimePicker.subscribe {
TimePickerFragment(toTimePickedSubject).show(fragmentManager, "timePicker")
}
.addTo(disposable)
presenter.showDatePicker.subscribe {
DatePickerFragment(datePicked).show(fragmentManager, "datePicker")
}
.addTo(disposable)
}
override val titleText: Observable<String>
get() = titleField.rxText.map(CharSequence::toString)
override val appSelected: Observable<Int>
get() = appPicker.rxItemCeleted
override val fromTimePicked: Observable<NewHintContract.Time> = fromTimePickedSubject
override val toTimePicked: Observable<NewHintContract.Time> = toTimePickedSubject
override val addPressed: PublishSubject<Empty> = PublishSubject.create()
override val fromTimePressed: Observable<Empty>
get() = timeFromButton.rxClicks.map(Empty.map)
override val toTimePressed: Observable<Empty>
get() = timeToButton.rxClicks.map(Empty.map)
override val datePressed: Observable<Empty>
get() = dateButton.rxClicks.map(Empty.map)
override val datePicked: PublishSubject<Date> = PublishSubject.create()
override fun onDestroy() {
super.onDestroy()
disposable.dispose()
presenter?.detachView()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
addPressed.onNext(Empty)
return true
}
}
class TimePickerFragment(private val observer: Observer<NewHintContract.Time>) :
android.support.v4.app.DialogFragment(), TimePickerDialog.OnTimeSetListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val cal = Calendar.getInstance()
val hour = cal.get(Calendar.HOUR_OF_DAY)
val minute = cal.get(Calendar.MINUTE)
return TimePickerDialog(activity, this, hour, minute, DateFormat.is24HourFormat(activity))
}
override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
observer.onNext(NewHintContract.Time(hourOfDay, minute))
}
}
class DatePickerFragment(private val observer: Observer<Date>) :
DialogFragment(), DatePickerDialog.OnDateSetListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val cal = Calendar.getInstance()
return DatePickerDialog(activity, this, cal[Calendar.YEAR], cal[Calendar.MONTH],
cal[Calendar.DAY_OF_MONTH])
}
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
val date = Calendar.getInstance().run {
set(Calendar.YEAR, year)
set(Calendar.MONTH, month)
set(Calendar.DAY_OF_MONTH, dayOfMonth)
time
}
observer.onNext(date)
}
}
|
mit
|
99a35dbae9f84e3e03c1ed99153d886c
| 36.964286 | 99 | 0.70022 | 4.591793 | false | false | false | false |
vsch/idea-multimarkdown
|
src/main/java/com/vladsch/md/nav/util/MdIndentConverter.kt
|
1
|
9602
|
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.util
import com.intellij.openapi.util.TextRange
import com.vladsch.flexmark.util.sequence.BasedSequence
import com.vladsch.plugin.util.toBased
import java.util.*
class MdIndentConverter {
// verbatim content node
private val content: BasedSequence
// offset in parent of the containing verbatim element
private val startOffsetInParent: Int
// range within document of original lines without indent removal
private val originalLines: ArrayList<TextRange>
// range within document of lines adjusted for editing of fragment
private val convertedLines: ArrayList<TextRange>
/**
* create indent converter from original and unprefixed/unsuffixed lines
*/
constructor(contentChars: CharSequence, startOffsetInParent: Int, prefixedLines: List<BasedSequence>, unprefixedLines: List<BasedSequence>?, unsuffixedLines: List<BasedSequence>?) {
this.content = contentChars.toBased()
assert(content.builder.addAll(prefixedLines).toSequence() == content) {
"Content not equal to lines\n" +
"content: '${content.toVisibleWhitespaceString()}'\n" +
" lines: '${content.builder.addAll(prefixedLines).toSequence().toVisibleWhitespaceString()}'"
}
this.startOffsetInParent = startOffsetInParent
val iMax = prefixedLines.size
this.originalLines = ArrayList(iMax)
this.convertedLines = ArrayList(iMax)
var originalOffset = 0
for (i in 0 until iMax) {
val prefixedLine = prefixedLines[i]
val prefixedLineLength = prefixedLine.length
assert(prefixedLine == content.subSequence(originalOffset, originalOffset + prefixedLineLength)) { "[$i]: originalOffset: $originalOffset, line: `${prefixedLine.toVisibleWhitespaceString()}` content.subSequence `${content.subSequence(originalOffset, originalOffset + prefixedLineLength).toVisibleWhitespaceString()}`" }
originalLines.add(TextRange(originalOffset, originalOffset + prefixedLineLength))
var unprefixedLineLength = prefixedLineLength
if (unprefixedLines != null && unprefixedLines.size > i) {
val unprefixedLine = unprefixedLines[i]
unprefixedLineLength = unprefixedLine.length
if (prefixedLine.endsWith('\n') && !unprefixedLine.endsWith('\n')) {
// add implicit EOL
unprefixedLineLength++
}
}
val prefixDiff = prefixedLineLength - unprefixedLineLength
if (unsuffixedLines != null && unsuffixedLines.size > i) {
val unsuffixedLine = unsuffixedLines[i]
unprefixedLineLength = unsuffixedLine.length
} else {
if (prefixedLine.endsWith('\n'))
unprefixedLineLength--
}
val endIndex = originalOffset + prefixDiff + unprefixedLineLength
assert(endIndex <= originalOffset + prefixedLine.length) { "endIndex: $endIndex > originalOffset: $originalOffset + prefixedLine.length: ${prefixedLine.length}" }
assert(endIndex <= content.length) { "endIndex: $endIndex > content.length: ${content.length}" }
convertedLines.add(TextRange(originalOffset + prefixDiff, endIndex))
// original lines length
originalOffset += prefixedLineLength
}
}
fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean {
var lineCount = 0
val startOffset = rangeInsideHost.startOffset - startOffsetInParent
val endOffset = rangeInsideHost.endOffset - startOffsetInParent
// find the starting line
while (lineCount < convertedLines.size && startOffset > convertedLines[lineCount].endOffset) {
lineCount++
}
while (lineCount < convertedLines.size) {
if (convertedLines[lineCount].startOffset >= endOffset) break
// add the text
if (convertedLines[lineCount].endOffset <= endOffset) {
// characters were stripped so we must copy to end of this line then add \n
outChars.append(content.subSequence(convertedLines[lineCount].startOffset, convertedLines[lineCount].endOffset))
outChars.append('\n')
} else {
outChars.append(content.subSequence(convertedLines[lineCount].startOffset, endOffset))
}
if (convertedLines[lineCount].endOffset >= endOffset) {
break
}
lineCount++
}
return true
}
@Suppress("UNUSED_PARAMETER")
fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int {
var lineCount = 0
var decodedOffset = 0
val endOfContent = startOffsetInParent + originalLines[originalLines.size - 1].endOffset
// find the starting line
while (lineCount < convertedLines.size) {
val length = convertedLines[lineCount].length
if (offsetInDecoded <= decodedOffset + length) {
return startOffsetInParent + convertedLines[lineCount].startOffset + offsetInDecoded - decodedOffset // return offset into the converted content
}
decodedOffset = endOfContent.coerceAtMost(decodedOffset + length + 1) // add 1 for implicit EOL
lineCount++
}
if (decodedOffset + 1 >= offsetInDecoded) {
// return end of content
return endOfContent
}
return -1
}
companion object {
val FULL_INDENT = " "
// NOTE: for fenced prefixed blocks the leading and trailing prefixes are removed when passed to IntelliLang but
// here we have to include them because the whole verbatim content will be replaced.
fun encode(newContent: String, firstIndentPrefix: String, indentPrefix: String, isFenced: Boolean, endLineSuffix: String?, excludeSuffixAfter: String?): String {
var lastPos = 0
var pos: Int
val firstIndent = normalizeIndent(firstIndentPrefix, isFenced)
val restIndent = normalizeIndent(indentPrefix, isFenced)
val outChars = StringBuilder(newContent.length + (indentPrefix.length + 20))
var prefix = firstIndent
val suffix = endLineSuffix ?: ""
var subSequence: CharSequence
while (true) {
pos = if (lastPos < newContent.length) newContent.indexOf('\n', lastPos) else -1
if (pos < 0) {
if (lastPos < newContent.length) {
outChars.append(prefix)
subSequence = newContent.subSequence(lastPos, newContent.length)
if (!suffix.isEmpty()) subSequence = trimEnd(subSequence, suffix)
if (subSequence.length > 0) {
outChars.append(subSequence)
if (excludeSuffixAfter == null || excludeSuffixAfter.indexOf(subSequence[subSequence.length - 1]) < 0) {
outChars.append(suffix)
}
}
outChars.append('\n')
}
break
} else {
outChars.append(prefix)
prefix = restIndent
subSequence = newContent.subSequence(lastPos, pos)
if (!suffix.isEmpty()) subSequence = trimEnd(subSequence, suffix)
if (subSequence.length > 0) {
outChars.append(subSequence)
if (!suffix.isEmpty() && (excludeSuffixAfter == null || excludeSuffixAfter.indexOf(subSequence[subSequence.length - 1]) < 0)) {
outChars.append(suffix)
}
}
outChars.append('\n')
lastPos = pos + 1
}
}
//if (isFenced) outChars.append(indent)
return outChars.toString()
}
private fun trimEnd(sequence: CharSequence, stripEndLine: String): CharSequence {
val iMax = sequence.length
var lastEnd = iMax
var i = iMax
while (i-- > 0) {
val c = sequence[i]
if (lastEnd - i - 1 < stripEndLine.length && c == stripEndLine[lastEnd - i - 1]) {
// skip strip end line
continue
}
if (c != ' ' && c != '\t') {
return sequence.subSequence(0, i + 1)
}
lastEnd = i
}
return sequence.subSequence(0, 0)
}
internal fun normalizeIndent(indentPrefix: String, isFenced: Boolean): String {
var normalized = ""
val iMax = indentPrefix.length
for (i in 0 .. iMax - 1) {
val c = indentPrefix[i]
if (c == '\t') {
val count = 4 - i % 4
normalized += FULL_INDENT.substring(0, count)
} else {
normalized += c
}
}
return if (isFenced) normalized else normalized + FULL_INDENT
}
}
}
|
apache-2.0
|
b12790ed49e9ded9e61c67a412e36c66
| 40.930131 | 331 | 0.584566 | 5.179072 | false | false | false | false |
quarkusio/quarkus
|
integration-tests/hibernate-reactive-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/reactive/kotlin/TestEndpoint.kt
|
1
|
75555
|
@file:Suppress("ReactiveStreamsUnusedPublisher")
package io.quarkus.it.panache.reactive.kotlin
import io.quarkus.hibernate.reactive.panache.Panache
import io.quarkus.hibernate.reactive.panache.common.runtime.ReactiveTransactional
import io.quarkus.hibernate.reactive.panache.kotlin.PanacheEntityBase
import io.quarkus.hibernate.reactive.panache.kotlin.PanacheQuery
import io.quarkus.panache.common.Page
import io.quarkus.panache.common.Page.ofSize
import io.quarkus.panache.common.Parameters.with
import io.quarkus.panache.common.Sort
import io.quarkus.panache.common.exception.PanacheQueryException
import io.smallrye.mutiny.Uni
import org.hibernate.engine.spi.SelfDirtinessTracker
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import java.util.function.Supplier
import java.util.stream.Stream
import javax.inject.Inject
import javax.persistence.LockModeType
import javax.persistence.NoResultException
import javax.persistence.NonUniqueResultException
import javax.ws.rs.GET
import javax.ws.rs.Path
@Path("test")
class TestEndpoint {
@Inject
lateinit var bug5274EntityRepository: Bug5274EntityRepository
@Inject
lateinit var bug5885EntityRepository: Bug5885EntityRepository
@Inject
lateinit var personDao: PersonRepository
@Inject
lateinit var dogDao: DogDao
@Inject
lateinit var addressDao: AddressDao
@Inject
lateinit var namedQueryRepository: NamedQueryRepository
@Inject
lateinit var namedQueryWith2QueriesRepository: NamedQueryWith2QueriesRepository
@GET
@Path("ignored-properties")
fun ignoredProperties(): Person {
Person::class.java.getMethod("\$\$_hibernate_read_id")
Person::class.java.getMethod("\$\$_hibernate_read_name")
Assertions.assertThrows(NoSuchMethodException::class.java) {
Person::class.java.getMethod("\$\$_hibernate_read_persistent")
}
// no need to persist it, we can fake it
val person = Person()
person.id = 666L
person.name = "Eddie"
person.status = Status.DECEASED
return person
}
@GET
@Path("5274")
fun testBug5274(): Uni<String> {
return bug5274EntityRepository.count()
.map { "OK" }
}
@GET
@Path("5885")
fun testBug5885(): Uni<String> {
return bug5885EntityRepository.findById(1L)
.map { "OK" }
}
@GET
@Path("7721")
fun testBug7721(): Uni<String> {
val entity = Bug7721Entity()
return Panache.withTransaction {
entity.persist<Bug7721Entity>()
.flatMap { entity.delete() }
.map { "OK" }
}
}
@GET
@Path("8254")
@ReactiveTransactional
fun testBug8254(): Uni<String> {
val owner = CatOwner("8254")
return owner.persist<CatOwner>()
.flatMap { Cat(owner).persist<Cat>() }
.flatMap { Cat(owner).persist<Cat>() }
.flatMap { Cat(owner).persist<Cat>() }
// This used to fail with an invalid query "SELECT COUNT(*) SELECT DISTINCT cat.owner FROM Cat cat WHERE cat.owner = ?1"
// Should now result in a valid query "SELECT COUNT(DISTINCT cat.owner) FROM Cat cat WHERE cat.owner = ?1"
.flatMap {
CatOwner.find("SELECT DISTINCT cat.owner FROM Cat cat WHERE cat.owner = ?1", owner).count()
}.flatMap { count ->
assertEquals(1L, count)
CatOwner.find("SELECT cat.owner FROM Cat cat WHERE cat.owner = ?1", owner).count()
}.flatMap { count ->
assertEquals(3L, count)
Cat.find("SELECT cat FROM Cat cat WHERE cat.owner = ?1", owner).count()
}.flatMap { count ->
assertEquals(3L, count)
Cat.find("FROM Cat WHERE owner = ?1", owner).count()
}.flatMap { count ->
assertEquals(3L, count)
Cat.find("owner", owner).count()
}.flatMap { count ->
assertEquals(3L, count)
CatOwner.find("name = ?1", "8254").count()
}.map { count ->
assertEquals(1L, count)
"OK"
}
}
@GET
@Path("9025")
@ReactiveTransactional
fun testBug9025(): Uni<String> {
val apple = Fruit("apple", "red")
val orange = Fruit("orange", "orange")
val banana = Fruit("banana", "yellow")
return Fruit.persist(apple, orange, banana)
.flatMap {
val query = Fruit.find("select name, color from Fruit").page(ofSize(1))
query.list()
.flatMap { query.pageCount() }
.map { "OK" }
}
}
@GET
@Path("9036")
@ReactiveTransactional
fun testBug9036(): Uni<String> {
return Person.deleteAll()
.flatMap { Person().persist<Person>() }
.flatMap {
val deadPerson = Person()
deadPerson.name = "Stef"
deadPerson.status = Status.DECEASED
deadPerson.persist<PanacheEntityBase>()
}.flatMap {
val livePerson = Person()
livePerson.name = "Stef"
livePerson.status = Status.LIVING
livePerson.persist<PanacheEntityBase>()
}.flatMap { Person.count() }
.flatMap { count ->
assertEquals(3, count)
Person.listAll()
}.flatMap { list ->
assertEquals(3, list.size)
Person.find("status", Status.LIVING).firstResult()
}.flatMap { livePerson ->
// should be filtered
val query = Person.findAll(Sort.by("id"))
.filter("Person.isAlive")
.filter("Person.hasName", with("name", "Stef"))
query.count()
.flatMap { count ->
assertEquals(1, count)
query.list()
}.flatMap { list ->
assertEquals(1, list.size)
assertEquals(livePerson, list[0])
query.stream().collect().asList()
}.flatMap { list ->
assertEquals(1, list.size)
query.firstResult()
}.flatMap { result ->
assertEquals(livePerson, result)
query.singleResult()
}.flatMap { result ->
assertEquals(livePerson, result)
Person.count()
}.flatMap { count ->
assertEquals(3, count)
Person.listAll()
}.flatMap { list ->
assertEquals(3, list.size)
Person.deleteAll()
}.map { "OK" }
}
}
@GET
@Path("composite")
@ReactiveTransactional
fun testCompositeKey(): Uni<String> {
val obj = ObjectWithCompositeId()
obj.part1 = "part1"
obj.part2 = "part2"
obj.description = "description"
return obj.persist<ObjectWithCompositeId>()
.flatMap {
val key = ObjectWithCompositeId.ObjectKey("part1", "part2")
ObjectWithCompositeId.findById(key)
.flatMap { result ->
Assertions.assertNotNull(result)
ObjectWithCompositeId.deleteById(key)
}.flatMap { deleted ->
assertTrue(deleted)
ObjectWithCompositeId.deleteById(key)
}.flatMap { deleted ->
assertFalse(deleted)
val embeddedKey = ObjectWithEmbeddableId.ObjectKey("part1", "part2")
val embeddable = ObjectWithEmbeddableId()
embeddable.key = embeddedKey
embeddable.description = "description"
embeddable.persist<ObjectWithEmbeddableId>()
.flatMap { ObjectWithEmbeddableId.findById(embeddedKey) }
.flatMap { embeddableResult ->
Assertions.assertNotNull(embeddableResult)
ObjectWithEmbeddableId.deleteById(embeddedKey)
}.flatMap { deleted2 ->
assertTrue(deleted2)
ObjectWithEmbeddableId.deleteById(
ObjectWithEmbeddableId.ObjectKey(
"notexist1",
"notexist2"
)
)
}.map { deleted2 ->
assertFalse(deleted2)
"OK"
}
}
}
}
@GET
@Path("model")
@ReactiveTransactional
fun testModel(): Uni<String> {
return Person.findAll().list()
.flatMap { persons ->
assertEquals(0, persons.size)
Person.listAll()
}.flatMap { persons ->
assertEquals(0, persons.size)
Person.findAll().stream().collect().asList()
}.flatMap { personStream ->
assertEquals(0, personStream.size)
Person.streamAll().collect().asList()
}.flatMap { personStream ->
assertEquals(0, personStream.size)
assertThrows(NoResultException::class.java) {
Person.findAll().singleResult()
}
}.flatMap { result ->
Assertions.assertNull(result)
makeSavedPerson()
}.flatMap { person ->
Assertions.assertNotNull(person.id)
person.id as Long
Person.count()
.flatMap { count ->
assertEquals(1, count)
Person.count("name = ?1", "stef")
}.flatMap { count ->
assertEquals(1, count)
Person.count("name = :name", with("name", "stef").map())
}.flatMap { count ->
assertEquals(1, count)
Person.count("name = :name", with("name", "stef"))
}.flatMap { count ->
assertEquals(1, count)
Person.count("name", "stef")
}.flatMap { count ->
assertEquals(1, count)
Dog.count()
}.flatMap { count ->
assertEquals(1, count)
// FIXME: fetch
assertEquals(1, person.dogs.size)
Person.findAll().list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.listAll()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.findAll().stream().collect().asList()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.streamAll().collect().asList()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.findAll().firstResult()
}.flatMap { personResult ->
assertEquals(person, personResult)
Person.findAll().singleResult()
}.flatMap { personResult ->
assertEquals(person, personResult)
Person.find("name = ?1", "stef").list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("FROM Person2 WHERE name = ?1", "stef").list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("name = ?1", "stef")
.withLock(LockModeType.PESSIMISTIC_READ).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.list("name = ?1", "stef")
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("name = :name", with("name", "stef").map()).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("name = :name", with("name", "stef")).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.list("name = :name", with("name", "stef").map())
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("name = :name", with("name", "stef").map()).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.list("name = :name", with("name", "stef"))
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("name", "stef").list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("name = ?1", "stef").stream().collect().asList()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.stream("name = ?1", "stef").collect().asList()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.stream("name = :name", with("name", "stef").map()).collect().asList()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.stream("name = :name", with("name", "stef")).collect().asList()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("name", "stef").stream().collect().asList()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.find("name", "stef").firstResult()
}.flatMap { personResult ->
assertEquals(person, personResult)
Person.find("name", "stef").singleResult()
}.flatMap { personResult ->
assertEquals(person, personResult)
Person.find("name", "stef").singleResult()
}.flatMap { personResult ->
assertEquals(person, personResult)
Person.list("#Person.getByName", with("name", "stef"))
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
assertThrows(PanacheQueryException::class.java) {
Person.find("#Person.namedQueryNotFound").list()
}
}.flatMap {
assertThrows(IllegalArgumentException::class.java) {
Person.list(
"#Person.getByName",
Sort.by("name"),
with("name", "stef")
)
}
}
.flatMap { NamedQueryEntity.list("#NamedQueryMappedSuperClass.getAll") }
.flatMap { NamedQueryEntity.list("#NamedQueryEntity.getAll") }
.flatMap { NamedQueryWith2QueriesEntity.list("#NamedQueryWith2QueriesEntity.getAll1") }
.flatMap { NamedQueryWith2QueriesEntity.list("#NamedQueryWith2QueriesEntity.getAll2") }
.flatMap { Person.find("").list() }
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
Person.findById(person.id!!)
}.flatMap { byId ->
assertEquals(person, byId)
assertEquals("Person<" + person.id + ">", byId.toString())
Person.findById(person.id!!, LockModeType.PESSIMISTIC_READ)
}.flatMap { byId ->
assertEquals(person, byId)
assertEquals("Person<" + person.id + ">", byId.toString())
person.delete()
}.flatMap { Person.count() }
.flatMap { count ->
assertEquals(0, count)
makeSavedPerson()
}
}.flatMap { person ->
Person.count()
.flatMap { count ->
assertEquals(1, count)
Person.delete("name = ?1", "emmanuel")
}.flatMap { count ->
assertEquals(0, count)
Dog.delete("owner = ?1", person)
}.flatMap { count ->
assertEquals(1, count)
Person.delete("name", "stef")
}.flatMap { count ->
assertEquals(1, count)
makeSavedPerson()
}
}.flatMap { person ->
Dog.delete("owner = :owner", with("owner", person).map())
.flatMap { count ->
assertEquals(1, count)
Person.delete("name", "stef")
}.flatMap { count ->
assertEquals(1, count)
makeSavedPerson()
}
}.flatMap { person ->
Dog.delete("owner = :owner", with("owner", person))
.flatMap { count ->
assertEquals(1, count)
Person.delete("name", "stef")
}.flatMap { count ->
assertEquals(1, count)
makeSavedPerson()
}
}.flatMap { person ->
Dog.delete("FROM Dog WHERE owner = :owner", with("owner", person))
.flatMap { count ->
assertEquals(1, count)
Person.delete("FROM Person2 WHERE name = ?1", "stef")
}.flatMap { count ->
assertEquals(1, count)
makeSavedPerson()
}
}.flatMap { person ->
Dog.delete("DELETE FROM Dog WHERE owner = :owner", with("owner", person))
.flatMap { count ->
assertEquals(1, count)
Person.delete("DELETE FROM Person2 WHERE name = ?1", "stef")
}.map { count ->
assertEquals(1, count)
null
}
}.flatMap { Person.deleteAll() }
.flatMap { count ->
assertEquals(0, count)
makeSavedPerson()
}.flatMap {
Dog.deleteAll()
.flatMap { count ->
assertEquals(1, count)
Person.deleteAll()
}.map { count ->
assertEquals(1, count)
null
}
}
.flatMap { testPersist(PersistTest.Variadic) }
.flatMap { testPersist(PersistTest.Iterable) }
.flatMap { testPersist(PersistTest.Stream) }
.flatMap { Person.deleteAll() }
.flatMap { count ->
assertEquals(6, count)
testSorting()
} // paging
.flatMap { makeSavedPerson("0") }
.flatMap { makeSavedPerson("1") }
.flatMap { makeSavedPerson("2") }
.flatMap { makeSavedPerson("3") }
.flatMap { makeSavedPerson("4") }
.flatMap { makeSavedPerson("5") }
.flatMap { makeSavedPerson("6") }
.flatMap { testPaging(Person.findAll()) }
.flatMap { testPaging(Person.find("ORDER BY name")) } // range
.flatMap { testRange(Person.findAll()) }
.flatMap { testRange(Person.find("ORDER BY name")) }
.flatMap {
assertThrows(NonUniqueResultException::class.java) {
Person.findAll().singleResult()
}
}
.flatMap { Person.findAll().firstResult() }
.flatMap { person ->
Assertions.assertNotNull(person)
Person.deleteAll()
}.flatMap { count ->
assertEquals(7, count)
testUpdate()
}.flatMap {
Person.deleteById(666L) // not existing
}.flatMap { deleted ->
assertFalse(deleted)
// persistAndFlush
val person1 = Person()
person1.name = "testFLush1"
person1.uniqueName = "unique"
person1.persist<Person>()
}.flatMap { Person.deleteAll() }
.map { "OK" }
}
@GET
@Path("model1")
@ReactiveTransactional
@Suppress("CAST_NEVER_SUCCEEDS")
fun testModel1(): Uni<String> {
return Person.count()
.flatMap { count ->
assertEquals(0, count)
makeSavedPerson("")
}.flatMap { person ->
val trackingPerson = person as SelfDirtinessTracker
var dirtyAttributes = trackingPerson.`$$_hibernate_getDirtyAttributes`()
assertEquals(0, dirtyAttributes.size)
person.name = "1"
dirtyAttributes = trackingPerson.`$$_hibernate_getDirtyAttributes`()
assertEquals(1, dirtyAttributes.size)
Person.count()
}.map { count ->
assertEquals(1, count)
"OK"
}
}
@GET
@Path("model2")
@ReactiveTransactional
fun testModel2(): Uni<String> {
return Person.count()
.flatMap { count ->
assertEquals(1, count)
Person.findAll().firstResult()
}.map { person ->
assertEquals("1", person?.name)
person?.name = "2"
"OK"
}
}
@GET
@Path("projection1")
@ReactiveTransactional
fun testProjection(): Uni<String> {
return Person.count()
.flatMap { count ->
assertEquals(1, count)
Person.findAll().project(PersonName::class.java)
.firstResult()
}.flatMap { person ->
assertEquals("2", person?.name)
Person.find("name", "2").project(PersonName::class.java)
.firstResult()
}.flatMap { person ->
assertEquals("2", person?.name)
Person.find("name = ?1", "2").project(PersonName::class.java)
.firstResult()
}.flatMap { person ->
assertEquals("2", person?.name)
Person.find(
"name = :name",
with("name", "2")
)
.project(PersonName::class.java)
.firstResult()
}.flatMap { person ->
assertEquals("2", person?.name)
val query: PanacheQuery<PersonName> =
Person.findAll()
.project(
PersonName::class.java
)
.page(0, 2)
query.list()
.flatMap { results ->
assertEquals(1, results.size)
query.nextPage()
query.list()
}.flatMap { results ->
assertEquals(0, results.size)
Person.findAll()
.project(PersonName::class.java)
.count()
}.map { count ->
assertEquals(1, count)
"OK"
}
}
}
@GET
@Path("projection2")
@ReactiveTransactional
fun testProjection2(): Uni<String> {
val ownerName = "Julie"
val catName = "Bubulle"
val catWeight = 8.5
val catOwner = CatOwner(ownerName)
return catOwner.persist<CatOwner>()
.flatMap {
Cat(catName, catOwner, catWeight)
.persist<Cat>()
}.flatMap {
Cat.find("name", catName)
.project(CatDto::class.java)
.firstResult()
}.flatMap { cat ->
assertEquals(catName, cat?.name)
assertEquals(ownerName, cat?.ownerName)
Cat.find(
"select c.name, c.owner.name as ownerName from Cat c where c.name = :name",
with("name", catName)
)
.project(CatProjectionBean::class.java)
.singleResult()
}.flatMap { catView ->
assertEquals(catName, catView.name)
assertEquals(ownerName, catView.ownerName)
Assertions.assertNull(catView.weight)
Cat.find("select 'fake_cat', 'fake_owner', 12.5 from Cat c")
.project(CatProjectionBean::class.java)
.firstResult()
}.map { catView ->
assertEquals("fake_cat", catView?.name)
assertEquals("fake_owner", catView?.ownerName)
assertEquals(12.5, catView?.weight)
// The spaces at the beginning are intentional
Cat.find(
" SELECT c.name, cast(null as string), SUM(c.weight) from Cat c where name = :name group by name ",
with("name", catName)
)
.project(CatProjectionBean::class.java)
}.flatMap { projectionQuery: PanacheQuery<CatProjectionBean> ->
projectionQuery
.firstResult()
.map { catView: CatProjectionBean? ->
assertEquals(catName, catView?.name)
Assertions.assertNull(catView?.ownerName)
assertEquals(catWeight, catView?.weight)
}
projectionQuery.count()
}.map { count ->
assertEquals(1L, count)
// The spaces at the beginning are intentional
Cat.find(
" SELECT disTINct c.name, cast(null as string), SUM(c.weight) from Cat c where " +
"name = :name group by name ",
with("name", catName)
)
.project(CatProjectionBean::class.java)
}.flatMap { projectionQuery ->
projectionQuery
.firstResult()
.map { catView ->
assertEquals(catName, catView?.name)
Assertions.assertNull(catView?.ownerName)
assertEquals(catWeight, catView?.weight)
}
projectionQuery.count()
}.map { count ->
assertEquals(1L, count)
val exception = Assertions.assertThrows(PanacheQueryException::class.java) {
Cat.find("select new FakeClass('fake_cat', 'fake_owner', 12.5) from Cat c")
.project(CatProjectionBean::class.java)
}
assertTrue(exception.message!!.startsWith("Unable to perform a projection on a 'select new' query"))
"OK"
}
}
@GET
@Path("model3")
@ReactiveTransactional
fun testModel3(): Uni<String> {
return Person.count()
.flatMap { count ->
assertEquals(1, count)
Person.findAll().firstResult()
}.flatMap { person ->
assertEquals("2", person?.name)
Dog.deleteAll()
}.flatMap { Person.deleteAll() }
.flatMap { Address.deleteAll() }
.flatMap { Person.count() }
.map { count ->
assertEquals(0, count)
"OK"
}
}
@GET
@Path("model-dao")
@ReactiveTransactional
fun testModelDao(): Uni<String> {
return personDao.findAll().list()
.flatMap { persons ->
assertEquals(0, persons.size)
personDao.listAll()
}.flatMap { persons ->
assertEquals(0, persons.size)
personDao.findAll().stream().collect().asList()
}.flatMap { personStream ->
assertEquals(0, personStream.size)
personDao.streamAll().collect().asList()
}.flatMap { personStream ->
assertEquals(0, personStream.size)
assertThrows(NoResultException::class.java) {
personDao.findAll().singleResult()
}
}.flatMap {
personDao.findAll().firstResult()
}.flatMap { result ->
Assertions.assertNull(result)
makeSavedPersonDao()
}
.flatMap { person ->
Assertions.assertNotNull(person.id)
personDao.count()
.flatMap { count ->
assertEquals(1, count)
personDao.count("name = ?1", "stef")
}
.flatMap { count ->
assertEquals(1, count)
personDao.count("name = :name", with("name", "stef").map())
}
.flatMap { count ->
assertEquals(1, count)
personDao.count("name = :name", with("name", "stef"))
}
.flatMap { count ->
assertEquals(1, count)
personDao.count("name", "stef")
}
.flatMap { count ->
assertEquals(1, count)
dogDao.count()
}
.flatMap { count ->
assertEquals(1, count)
// FIXME: fetch
assertEquals(1, person.dogs.size)
personDao.findAll().list()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.listAll()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.findAll().stream()
.collect().asList()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.streamAll().collect().asList()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.findAll().firstResult()
}.flatMap { personResult ->
assertEquals(person, personResult)
personDao.findAll().singleResult()
}
.flatMap { personResult ->
assertEquals(person, personResult)
personDao.find("name = ?1", "stef").list()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.find("name = ?1", "stef")
.withLock(LockModeType.PESSIMISTIC_READ)
.list()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.list("name = ?1", "stef")
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.find("name = :name", with("name", "stef").map())
.list()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.find("name = :name", with("name", "stef"))
.list()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.list("name = :name", with("name", "stef").map())
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.find("name = :name", with("name", "stef").map())
.list()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.list("name = :name", with("name", "stef"))
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.find("name", "stef").list()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.find("name = ?1", "stef").stream()
.collect().asList()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.stream("name = ?1", "stef").collect().asList()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.stream("name = :name", with("name", "stef").map())
.collect().asList()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.stream("name = :name", with("name", "stef"))
.collect().asList()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.find("name", "stef").stream()
.collect().asList()
}
.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.find("name", "stef").firstResult()
}.flatMap { personResult ->
assertEquals(person, personResult)
personDao.find("name", "stef").singleResult()
}.flatMap { personResult ->
assertEquals(person, personResult)
personDao.find("name", "stef").singleResult()
}
.flatMap { personResult ->
assertEquals(person, personResult)
personDao.list("#Person.getByName", with("name", "stef"))
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
assertThrows(PanacheQueryException::class.java) {
personDao.find("#Person.namedQueryNotFound").list()
}
}.flatMap {
assertThrows(IllegalArgumentException::class.java) {
personDao.list("#Person.getByName", Sort.by("name"), with("name", "stef"))
}
}.flatMap {
namedQueryRepository.list("#NamedQueryMappedSuperClass.getAll")
}.flatMap {
namedQueryRepository.list("#NamedQueryEntity.getAll")
}.flatMap {
namedQueryWith2QueriesRepository.list("#NamedQueryWith2QueriesEntity.getAll1")
}.flatMap {
namedQueryWith2QueriesRepository.list("#NamedQueryWith2QueriesEntity.getAll2")
}.flatMap {
personDao.find("").list()
}.flatMap { persons ->
assertEquals(1, persons.size)
assertEquals(person, persons[0])
personDao.findById(person.id!!)
}.flatMap { byId ->
assertEquals(person, byId)
assertEquals("Person<${person.id}>", byId.toString())
personDao.findById(person.id!!, LockModeType.PESSIMISTIC_READ)
}.flatMap { byId ->
assertEquals(person, byId)
assertEquals("Person<${person.id}>", byId.toString())
person.delete()
}.flatMap { personDao.count() }
.flatMap { count ->
assertEquals(0, count)
makeSavedPersonDao()
}.flatMap {
Person.count("#Person.countAll")
.flatMap { count ->
assertEquals(1, count)
Person.count("#Person.countByName", with("name", "stef").map())
}.flatMap { count ->
assertEquals(1, count)
Person.count("#Person.countByName", with("name", "stef"))
}.flatMap { count ->
assertEquals(1, count)
Person.count("#Person.countByName.ordinal", "stef")
}.flatMap { count ->
assertEquals(1, count)
Uni.createFrom().voidItem()
}
}.flatMap {
Person.update("#Person.updateAllNames", with("name", "stef2").map())
.flatMap { count ->
assertEquals(1, count)
Person.find("#Person.getByName", with("name", "stef2")).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
Person.update("#Person.updateAllNames", with("name", "stef3"))
}.flatMap { count ->
assertEquals(1, count)
Person.find("#Person.getByName", with("name", "stef3")).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
Person.update(
"#Person.updateNameById",
with("name", "stef2")
.and("id", persons[0].id).map()
)
}.flatMap { count ->
assertEquals(1, count)
Person.find("#Person.getByName", with("name", "stef2")).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
Person.update(
"#Person.updateNameById",
with("name", "stef3")
.and("id", persons[0].id)
)
}.flatMap { count ->
assertEquals(1, count)
Person.find("#Person.getByName", with("name", "stef3")).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
Person.update("#Person.updateNameById.ordinal", "stef", persons[0].id!!)
}.flatMap { count ->
assertEquals(1, count)
Person.find("#Person.getByName", with("name", "stef")).list()
}.flatMap { persons ->
assertEquals(1, persons.size)
Uni.createFrom().voidItem()
}
}.flatMap {
Dog.deleteAll()
.flatMap {
Person.delete("#Person.deleteAll")
}.flatMap { count ->
assertEquals(1, count)
Person.find("").list()
}.flatMap { persons ->
assertEquals(0, persons.size)
Uni.createFrom().voidItem()
}
}.flatMap {
makeSavedPerson().flatMap { personToDelete ->
Dog.deleteAll()
.flatMap {
Person.find("").list()
}.flatMap { persons ->
assertEquals(1, persons.size)
Person.delete("#Person.deleteById", with("id", personToDelete.id).map())
}.flatMap { count ->
assertEquals(1, count)
Person.find("").list()
}.flatMap { persons ->
assertEquals(0, persons.size)
Uni.createFrom().voidItem()
}
}
}.flatMap {
makeSavedPerson().flatMap { personToDelete ->
Dog.deleteAll()
.flatMap {
Person.find("").list()
}.flatMap { persons ->
assertEquals(1, persons.size)
Person.delete("#Person.deleteById", with("id", personToDelete.id))
}.flatMap { count ->
assertEquals(1, count)
Person.find("").list()
}.flatMap { persons ->
assertEquals(0, persons.size)
Uni.createFrom().voidItem()
}
}
}.flatMap {
makeSavedPerson().flatMap { personToDelete ->
Dog.deleteAll()
.flatMap {
Person.find("").list()
}.flatMap { persons ->
assertEquals(1, persons.size)
Person.delete("#Person.deleteById.ordinal", personToDelete.id!!)
}.flatMap { count ->
assertEquals(1, count)
Person.find("").list()
}.flatMap { persons ->
assertEquals(0, persons.size)
makeSavedPersonDao()
}
}
}
}.flatMap { person ->
personDao.count()
.flatMap { count ->
assertEquals(1, count)
personDao.delete("name = ?1", "emmanuel")
}.flatMap { count ->
assertEquals(0, count)
dogDao.delete("owner = ?1", person)
}.flatMap { count ->
assertEquals(1, count)
personDao.delete("name", "stef")
}.flatMap { count ->
assertEquals(1, count)
makeSavedPersonDao()
}
}.flatMap { person ->
dogDao.delete("owner = :owner", with("owner", person).map())
.flatMap { count ->
assertEquals(1, count)
personDao.delete("name", "stef")
}.flatMap { count ->
assertEquals(1, count)
makeSavedPersonDao()
}
}.flatMap { person ->
dogDao.delete("owner = :owner", with("owner", person))
.flatMap { count ->
assertEquals(1, count)
personDao.delete("name", "stef")
}.flatMap { count ->
assertEquals(1, count)
makeSavedPersonDao()
}
}.flatMap { person ->
dogDao.delete("FROM Dog WHERE owner = :owner", with("owner", person))
.flatMap { count ->
assertEquals(1, count)
personDao.delete("FROM Person2 WHERE name = ?1", "stef")
}.flatMap { count ->
assertEquals(1, count)
makeSavedPersonDao()
}
}.flatMap { person ->
dogDao.delete("DELETE FROM Dog WHERE owner = :owner", with("owner", person))
.flatMap { count ->
assertEquals(1, count)
personDao.delete("DELETE FROM Person2 WHERE name = ?1", "stef")
}.map { count ->
assertEquals(1, count)
null
}
}.flatMap { v -> personDao.deleteAll() }
.flatMap { count ->
assertEquals(0, count)
makeSavedPersonDao()
}.flatMap { person ->
dogDao.deleteAll()
.flatMap { count ->
assertEquals(1, count)
personDao.deleteAll()
}.map { count ->
assertEquals(1, count)
null
}
}
.flatMap { testPersistDao(PersistTest.Iterable) }
.flatMap { v -> testPersistDao(PersistTest.Stream) }
.flatMap { v -> testPersistDao(PersistTest.Variadic) }
.flatMap { personDao.deleteAll() }
.flatMap { count ->
assertEquals(6, count)
testSorting()
}.flatMap {
makeSavedPersonDao("0")
}.flatMap {
makeSavedPersonDao("1")
}.flatMap {
makeSavedPersonDao("2")
}.flatMap {
makeSavedPersonDao("3")
}.flatMap {
makeSavedPersonDao("4")
}.flatMap {
makeSavedPersonDao("5")
}.flatMap {
makeSavedPersonDao("6")
}.flatMap {
testPaging(personDao.findAll())
}.flatMap { v -> testPaging(personDao.find("ORDER BY name")) } // range
.flatMap { testRange(personDao.findAll()) }
.flatMap { testRange(personDao.find("ORDER BY name")) }
.flatMap {
assertThrows(NonUniqueResultException::class.java) {
personDao.findAll().singleResult()
}
}.flatMap {
personDao.findAll().firstResult()
}.flatMap { person ->
Assertions.assertNotNull(person)
personDao.deleteAll()
}.flatMap { count ->
assertEquals(7, count)
testUpdateDao()
}.flatMap {
// delete by id
val toRemove = Person()
toRemove.name = "testDeleteById"
toRemove.uniqueName = "testDeleteByIdUnique"
toRemove.persist<Person>()
.flatMap {
personDao.deleteById(toRemove.id!!)
}
}.flatMap { deleted ->
assertTrue(deleted)
personDao.deleteById(666L) // not existing
}.flatMap { deleted ->
assertFalse(deleted)
// persistAndFlush
val person1 = Person()
person1.name = "testFLush1"
person1.uniqueName = "unique"
personDao.persistAndFlush(person1)
}.flatMap {
personDao.deleteAll()
}.map {
"OK"
}
}
@GET
@Path("testSortByNullPrecedence")
@ReactiveTransactional
fun testSortByNullPrecedence(): Uni<String> {
return Person.deleteAll()
.flatMap {
val stefPerson = Person()
stefPerson.name = "Stef"
stefPerson.uniqueName = "stef"
val josePerson = Person()
josePerson.name = null
josePerson.uniqueName = "jose"
Person.persist(stefPerson, josePerson)
}
.flatMap {
Person.findAll(Sort.by("name", Sort.NullPrecedence.NULLS_FIRST)).list()
}.flatMap { list ->
assertEquals("jose", list[0].uniqueName)
Person.findAll(Sort.by("name", Sort.NullPrecedence.NULLS_LAST)).list()
}.flatMap { list ->
assertEquals("jose", list[list.size - 1].uniqueName)
Person.deleteAll()
}.map { "OK" }
}
private fun makeSavedPerson(): Uni<Person> {
val uni: Uni<Person> = makeSavedPerson("")
return uni.flatMap { person ->
val dog = Dog("octave", "dalmatian")
dog.owner = person
person.dogs.add(dog)
dog.persist<Dog>()
.map { person }
}
}
private fun makeSavedPerson(suffix: String = ""): Uni<Person> {
val address = Address()
address.street = "stef street"
val person = Person()
person.name = "stef$suffix"
person.status = Status.LIVING
person.address = address
return person.address!!.persist<Address>()
.flatMap { person.persist() }
}
private fun assertThrows(exceptionClass: Class<out Throwable>, f: Supplier<Uni<*>>): Uni<Void> {
val uni = try {
f.get()
} catch (t: Throwable) {
Uni.createFrom().failure<Any>(t)
}
return uni
.onItemOrFailure()
.invoke { r: Any?, t: Throwable? -> System.err.println("Got back val: $r and exception $t") }
.onItem().invoke { _ -> Assertions.fail("Did not throw " + exceptionClass.name) }
.onFailure(exceptionClass)
.recoverWithItem { null }
.map { null }
}
private fun testPersist(persistsTest: PersistTest): Uni<Void> {
val person1 = Person()
person1.name = "stef1"
val person2 = Person()
person2.name = "stef2"
assertFalse(person1.isPersistent())
assertFalse(person2.isPersistent())
return when (persistsTest) {
PersistTest.Iterable -> Person.persist(listOf(person1, person2))
PersistTest.Stream -> Person.persist(Stream.of(person1, person2))
PersistTest.Variadic -> Person.persist(person1, person2)
}.map {
assertTrue(person1.isPersistent())
assertTrue(person2.isPersistent())
null
}
}
private fun testSorting(): Uni<Unit> {
val person1 = Person()
person1.name = "stef"
person1.status = Status.LIVING
val person2 = Person()
person2.name = "stef"
person2.status = Status.DECEASED
val person3 = Person()
person3.name = "emmanuel"
person3.status = Status.LIVING
return person1.persist<Person>()
.flatMap { person2.persist<Person>() }
.flatMap { person3.persist<Person>() }
.flatMap {
val sort1 = Sort.by("name", "status")
val order1 = listOf(person3, person2, person1)
val sort2 = Sort.descending("name", "status")
val order2 = listOf(person1, person2)
Person.findAll(sort1).list()
.flatMap { list ->
assertEquals(order1, list)
Person.listAll(sort1)
}.flatMap { list ->
assertEquals(order1, list)
Person.streamAll(sort1).collect().asList()
}.flatMap { list ->
assertEquals(order1, list)
Person.find("name", sort2, "stef").list()
}.flatMap { list ->
assertEquals(order2, list)
Person.list("name", sort2, "stef")
}.flatMap { list ->
assertEquals(order2, list)
Person.stream("name", sort2, "stef").collect().asList()
}.flatMap { list ->
assertEquals(order2, list)
Person.find("name = :name", sort2, with("name", "stef").map())
.list()
}.flatMap { list ->
assertEquals(order2, list)
Person.list("name = :name", sort2, with("name", "stef").map())
}.flatMap { list ->
assertEquals(order2, list)
Person.stream("name = :name", sort2, with("name", "stef").map())
.collect().asList()
}.flatMap { list ->
assertEquals(order2, list)
Person.find("name = :name", sort2, with("name", "stef")).list()
}.flatMap { list ->
assertEquals(order2, list)
Person.list("name = :name", sort2, with("name", "stef"))
}.flatMap { list ->
assertEquals(order2, list)
Person.stream("name = :name", sort2, with("name", "stef"))
.collect().asList()
}
}.flatMap { Person.deleteAll() }
.map { count ->
assertEquals(3, count)
}
}
private fun testPaging(query: PanacheQuery<Person>): Uni<Void> {
// No paging allowed until a page is set up
Assertions.assertThrows(UnsupportedOperationException::class.java) { query.firstPage() }
Assertions.assertThrows(UnsupportedOperationException::class.java) { query.previousPage() }
Assertions.assertThrows(UnsupportedOperationException::class.java) { query.nextPage() }
Assertions.assertThrows(UnsupportedOperationException::class.java) { query.lastPage() }
Assertions.assertThrows(UnsupportedOperationException::class.java) { query.hasNextPage() }
Assertions.assertThrows(UnsupportedOperationException::class.java) { query.hasPreviousPage() }
Assertions.assertThrows(UnsupportedOperationException::class.java) { query.page() }
Assertions.assertThrows(UnsupportedOperationException::class.java) { query.pageCount() }
return query.page(0, 3).list()
.flatMap { persons: List<Person> ->
assertEquals(3, persons.size)
assertEquals("stef0", persons[0].name)
assertEquals("stef1", persons[1].name)
assertEquals("stef2", persons[2].name)
query.page(1, 3).list()
}
.flatMap { persons: List<Person> ->
assertEquals(3, persons.size)
assertEquals("stef3", persons[0].name)
assertEquals("stef4", persons[1].name)
assertEquals("stef5", persons[2].name)
query.page(2, 3).list()
}
.flatMap { persons: List<Person> ->
assertEquals(1, persons.size)
assertEquals("stef6", persons[0].name)
query.page(2, 4).list()
}
.flatMap { persons: List<Person> ->
assertEquals(0, persons.size)
query.page(Page(3)).list()
}
.flatMap { persons: List<Person> ->
assertEquals(3, persons.size)
assertEquals("stef0", persons[0].name)
assertEquals("stef1", persons[1].name)
assertEquals("stef2", persons[2].name)
query.page(Page(1, 3)).list()
}
.flatMap { persons: List<Person> ->
assertEquals(3, persons.size)
assertEquals("stef3", persons[0].name)
assertEquals("stef4", persons[1].name)
assertEquals("stef5", persons[2].name)
query.page(Page(2, 3)).list()
}
.flatMap { persons: List<Person> ->
assertEquals(1, persons.size)
assertEquals("stef6", persons[0].name)
query.page(Page(3, 3)).list()
}
.flatMap { persons: List<Person> ->
assertEquals(0, persons.size)
query.page(Page(3)).list()
}
.flatMap { persons: List<Person> ->
assertEquals(3, persons.size)
assertEquals("stef0", persons[0].name)
assertEquals("stef1", persons[1].name)
assertEquals("stef2", persons[2].name)
query.hasNextPage()
}
.flatMap { hasNextPage: Boolean ->
assertTrue(hasNextPage)
assertFalse(query.hasPreviousPage())
query.nextPage().list()
}
.flatMap { persons: List<Person> ->
assertEquals(1, query.page().index)
assertEquals(3, query.page().size)
assertEquals(3, persons.size)
assertEquals("stef3", persons[0].name)
assertEquals("stef4", persons[1].name)
assertEquals("stef5", persons[2].name)
query.hasNextPage()
}
.flatMap { hasNextPage: Boolean ->
assertTrue(hasNextPage)
assertTrue(query.hasPreviousPage())
query.nextPage().list()
}
.flatMap { persons: List<Person> ->
assertEquals(1, persons.size)
assertEquals("stef6", persons[0].name)
query.hasNextPage()
}
.flatMap { hasNextPage: Boolean ->
assertFalse(hasNextPage)
assertTrue(query.hasPreviousPage())
query.nextPage().list()
}
.flatMap { persons: List<Person> ->
assertEquals(0, persons.size)
query.count()
}.flatMap { count ->
assertEquals(7, count)
query.pageCount()
}
.flatMap { count ->
assertEquals(3, count)
query.page(0, 3)
.range(0, 1)
.list()
}
.map { persons: List<Person> ->
assertEquals(2, persons.size)
assertEquals("stef0", persons[0].name)
assertEquals("stef1", persons[1].name)
null
}
}
private fun testRange(query: PanacheQuery<Person>): Uni<Void> {
return query.range(0, 2).list()
.flatMap { persons: List<Person> ->
assertEquals(3, persons.size)
assertEquals("stef0", persons[0].name)
assertEquals("stef1", persons[1].name)
assertEquals("stef2", persons[2].name)
query.range(3, 5).list()
}
.flatMap { persons: List<Person> ->
assertEquals(3, persons.size)
assertEquals("stef3", persons[0].name)
assertEquals("stef4", persons[1].name)
assertEquals("stef5", persons[2].name)
query.range(6, 8).list()
}
.flatMap { persons: List<Person> ->
assertEquals(1, persons.size)
assertEquals("stef6", persons[0].name)
query.range(8, 12).list()
}
.flatMap { persons: List<Person> ->
assertEquals(0, persons.size)
// mix range with page
Assertions.assertThrows(UnsupportedOperationException::class.java) {
query.range(0, 2)
.nextPage()
}
Assertions.assertThrows(UnsupportedOperationException::class.java) {
query.range(0, 2)
.previousPage()
}
Assertions.assertThrows(UnsupportedOperationException::class.java) {
query.range(0, 2).pageCount()
}
// Assertions.assertThrows(UnsupportedOperationException.class, () -> query.range(0, 2).lastPage());
Assertions.assertThrows(UnsupportedOperationException::class.java) {
query.range(0, 2).firstPage()
}
Assertions.assertThrows(UnsupportedOperationException::class.java) {
query.range(0, 2).hasPreviousPage()
}
Assertions.assertThrows(UnsupportedOperationException::class.java) {
query.range(0, 2).hasNextPage()
}
Assertions.assertThrows(UnsupportedOperationException::class.java) {
query.range(0, 2).page()
}
query.range(0, 2)
.page(0, 3)
.list()
}
.map { persons: List<Person> ->
assertEquals(3, persons.size)
assertEquals("stef0", persons[0].name)
assertEquals("stef1", persons[1].name)
assertEquals("stef2", persons[2].name)
null
}
}
private fun testUpdate(): Uni<Void> {
return makeSavedPerson("p1")
.flatMap {
makeSavedPerson("p2")
}.flatMap {
Person.update("update from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1")
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
Person.update(
"update from Person2 p set p.name = 'stefNEW' where p.name = :pName",
with("pName", "stefp2")
.map()
)
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
Person.deleteAll()
}.flatMap { count ->
assertEquals(2L, count)
makeSavedPerson("p1")
}.flatMap {
makeSavedPerson("p2")
}.flatMap {
Person.update("from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1")
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
Person.update(
"from Person2 p set p.name = 'stefNEW' where p.name = :pName",
with("pName", "stefp2").map()
)
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
Person.deleteAll()
}.flatMap { count ->
assertEquals(2, count)
makeSavedPerson("p1")
}.flatMap {
makeSavedPerson("p2")
}.flatMap {
Person.update("set name = 'stefNEW' where name = ?1", "stefp1")
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
Person.update(
"set name = 'stefNEW' where name = :pName",
with("pName", "stefp2").map()
)
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
Person.deleteAll()
}.flatMap { count ->
assertEquals(2, count)
makeSavedPerson("p1")
}.flatMap {
makeSavedPerson("p2")
}.flatMap {
Person.update("name = 'stefNEW' where name = ?1", "stefp1")
}.flatMap { updateByIndexParameter: Any ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
Person.update("name = 'stefNEW' where name = :pName", with("pName", "stefp2").map())
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
Person.deleteAll()
}.flatMap { count ->
assertEquals(2, count)
makeSavedPerson("p1")
}.flatMap { makeSavedPerson("p2") }
.flatMap {
Person.update("name = 'stefNEW' where name = ?1", "stefp1")
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
Person.update("name = 'stefNEW' where name = :pName", with("pName", "stefp2"))
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
Person.deleteAll()
}.flatMap {
assertThrows(PanacheQueryException::class.java) {
Person.update(" ")
}
}
}
private fun makeSavedPersonDao(): Uni<Person> {
val uni: Uni<Person> = makeSavedPersonDao("")
return uni.flatMap { person: Person ->
val dog = Dog("octave", "dalmatian")
dog.owner = person
person.dogs.add(dog)
dog.persist<Dog>()
.map { person }
}
}
private fun makeSavedPersonDao(suffix: String): Uni<Person> {
val person = Person()
person.name = "stef$suffix"
person.status = Status.LIVING
person.address = Address("stef street")
return addressDao.persist(person.address!!)
.flatMap { personDao.persist(person) }
}
private fun testPersistDao(persistTest: PersistTest): Uni<Void> {
val person1 = Person()
person1.name = "stef1"
val person2 = Person()
person2.name = "stef2"
assertFalse(personDao.isPersistent(person1))
assertFalse(personDao.isPersistent(person2))
val persist = when (persistTest) {
PersistTest.Iterable -> personDao.persist(listOf(person1, person2))
PersistTest.Stream -> personDao.persist(Stream.of(person1, person2))
PersistTest.Variadic -> personDao.persist(person1, person2)
}
return persist.map {
assertTrue(personDao.isPersistent(person1))
assertTrue(personDao.isPersistent(person2))
null
}
}
private fun testUpdateDao(): Uni<Void> {
return makeSavedPersonDao("p1")
.flatMap {
makeSavedPersonDao("p2")
}.flatMap {
personDao.update(
"update from Person2 p set p.name = 'stefNEW' where p.name = ?1",
"stefp1"
)
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
personDao.update(
"update from Person2 p set p.name = 'stefNEW' where p.name = :pName",
with("pName", "stefp2").map()
)
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
personDao.deleteAll()
}.flatMap { count ->
assertEquals(2, count)
makeSavedPersonDao("p1")
}.flatMap {
makeSavedPersonDao("p2")
}.flatMap {
personDao.update("from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1")
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
personDao.update(
"from Person2 p set p.name = 'stefNEW' where p.name = :pName",
with("pName", "stefp2").map()
)
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
personDao.deleteAll()
}.flatMap { count ->
assertEquals(2, count)
makeSavedPersonDao("p1")
}.flatMap {
makeSavedPersonDao("p2")
}.flatMap {
personDao.update("set name = 'stefNEW' where name = ?1", "stefp1")
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
personDao.update(
"set name = 'stefNEW' where name = :pName",
with("pName", "stefp2").map()
)
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
personDao.deleteAll()
}.flatMap { count ->
assertEquals(2, count)
makeSavedPersonDao("p1")
}.flatMap {
makeSavedPersonDao("p2")
}.flatMap {
personDao.update("name = 'stefNEW' where name = ?1", "stefp1")
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
personDao.update(
"name = 'stefNEW' where name = :pName",
with("pName", "stefp2").map()
)
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
personDao.deleteAll()
}.flatMap { count ->
assertEquals(2, count)
makeSavedPersonDao("p1")
}.flatMap {
makeSavedPersonDao("p2")
}.flatMap {
personDao.update("name = 'stefNEW' where name = ?1", "stefp1")
}.flatMap { updateByIndexParameter ->
assertEquals(1, updateByIndexParameter, "More than one Person updated")
personDao.update(
"name = 'stefNEW' where name = :pName",
with("pName", "stefp2")
)
}.flatMap { updateByNamedParameter ->
assertEquals(1, updateByNamedParameter, "More than one Person updated")
personDao.deleteAll()
}.flatMap { count ->
assertEquals(2, count)
assertThrows(PanacheQueryException::class.java) { personDao.update(" ") }
}
}
enum class PersistTest {
Iterable, Variadic, Stream
}
}
|
apache-2.0
|
0b64e51d84c4b4bcac42b6b2d05660b7
| 43.391892 | 135 | 0.453061 | 5.342597 | false | false | false | false |
tobyt42/tube-status
|
src/main/java/uk/terhoeven/news/tube/api/Line.kt
|
1
|
1785
|
package uk.terhoeven.news.tube.api
import com.google.common.base.MoreObjects
import java.util.*
import java.util.stream.Collectors
class Line(val id: String, val name: String) {
override fun toString(): String {
return MoreObjects.toStringHelper(this)
.add("id", id)
.add("name", name)
.toString()
}
companion object {
var BAKERLOO = Line("bakerloo", "Bakerloo")
var CENTRAL = Line("central", "Central")
var CIRCLE = Line("circle", "Circle")
var DISTRICT = Line("district", "District")
var DLR = Line("dlr", "DLR")
var JUBILEE = Line("jubilee", "Jubilee")
var HAMMERSMITH_CITY = Line("hammersmith-city", "Hammersmith and City")
var METROPOLITAN = Line("metropolitan", "Metropolitan")
var NORTHERN = Line("northern", "Northern")
var OVERGROUND = Line("london-overground", "London Overground")
var PICCADILLY = Line("piccadilly", "Piccadilly")
var TFL_RAIL = Line("tfl-rail", "TfL Rail")
var TRAM = Line("tram", "Tram")
var VICTORIA = Line("victoria", "Victoria")
var WATERLOO_CITY = Line("waterloo-city", "Waterloo and City")
var LINES: Collection<Line> = Arrays.asList(BAKERLOO, CENTRAL, CIRCLE, DISTRICT, DLR, JUBILEE, HAMMERSMITH_CITY, METROPOLITAN, NORTHERN, OVERGROUND, PICCADILLY, TFL_RAIL, TRAM, VICTORIA, WATERLOO_CITY)
var LINE_IDS: Collection<String> = LINES.stream().map { it.id }.collect(Collectors.toList())
fun parse(lineId: String): Line {
val match = LINES.stream().filter { line -> line.id == lineId }.findAny()
return if (match.isPresent) {
match.get()
} else Line(lineId, lineId)
}
}
}
|
mit
|
3dd036dc84c978935315447140820f12
| 41.5 | 209 | 0.610084 | 3.342697 | false | false | false | false |
JimSeker/ui
|
Communication/FragComNavVModelDemo_kt/app/src/main/java/edu/cs4730/fragcomnavvmodeldemo_kt/DataViewModel.kt
|
1
|
697
|
package edu.cs4730.fragcomnavvmodeldemo_kt
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.LiveData
class DataViewModel(application: Application) : AndroidViewModel(application) {
@JvmField
var num_one = 0
@JvmField
var num_two = 0
private val item: MutableLiveData<String> = MutableLiveData()
val data: LiveData<String>
get() = item
fun getItem(): String? {
return item.value
}
fun setItem(n: String) {
Log.d("VM", "data is $n")
item.value = n
}
init {
item.value = "default value"
}
}
|
apache-2.0
|
b44014a2cef542acfccc9115ca4de131
| 22.266667 | 79 | 0.674319 | 4.076023 | false | false | false | false |
JimSeker/ui
|
Basic/FormExample_kt/app/src/main/java/edu/cs4730/formexample_kt/MainActivity.kt
|
1
|
2867
|
package edu.cs4730.formexample_kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.*
class MainActivity : AppCompatActivity(), RadioGroup.OnCheckedChangeListener, TextWatcher,
View.OnClickListener {
//variables for the widgets
lateinit var myRadioGroup: RadioGroup
lateinit var et: EditText
lateinit var btnalert: Button
lateinit var label: TextView
//variable for the log
var TAG = "ForExample"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//EditText view setup and listener
et = findViewById(R.id.ETname)
et.addTextChangedListener(this)
//the top label in the xml doc.
label = findViewById(R.id.Label01)
//setup the radio group with a listener.
myRadioGroup = findViewById(R.id.SndGroup)
myRadioGroup.setOnCheckedChangeListener(this)
//setup the button with a listener as well.
btnalert = findViewById(R.id.Button01)
btnalert.setOnClickListener(this)
}
/* Radio group listener for OnCheckedChangeListener */
override fun onCheckedChanged(group: RadioGroup, CheckedId: Int) {
if (group === myRadioGroup) { //if not myRadioGroup, we are in trouble!
if (CheckedId == R.id.RB01) {
// information radio button clicked
Log.d(TAG, "RB01 was pushed.")
} else if (CheckedId == R.id.RB02) {
// Confirmation radio button clicked
Log.d(TAG, "RB02 was pushed.")
} else if (CheckedId == R.id.RB03) {
// Warning radio button clicked
Toast.makeText(this, "Warning!", Toast.LENGTH_LONG).show()
}
}
}
/* EditView listeners */
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
if (et.length() > 10) {
Toast.makeText(this, "Long Word!", Toast.LENGTH_SHORT).show()
Log.d(TAG, "Long Word!")
}
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
//left blank
}
override fun afterTextChanged(s: Editable) {
//left blank
}
/* button listener */
override fun onClick(v: View) {
if (v === btnalert) {
if (et.text.toString().compareTo("") != 0) Toast.makeText(
this,
"The edittext has " + et.text.toString(),
Toast.LENGTH_SHORT
).show() else Toast.makeText(this, "The button was pressed", Toast.LENGTH_SHORT).show()
Log.d(TAG, "The button was pressed.")
}
}
}
|
apache-2.0
|
6acc75a2dbcac3d31f8611d39d89e8b2
| 32.348837 | 99 | 0.61737 | 4.363775 | false | false | false | false |
Jonatino/Droid-Explorer
|
src/main/kotlin/com/droid/explorer/DroidExplorer.kt
|
1
|
4673
|
/*
* Copyright 2016 Jonathan Beaudoin
*
* 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.droid.explorer
import com.droid.explorer.command.adb.impl.DeviceSerial
import com.droid.explorer.command.adb.impl.DeviceState
import com.droid.explorer.command.adb.impl.Root
import com.droid.explorer.command.adb.impl.Start
import com.droid.explorer.filesystem.FileSystem
import com.droid.explorer.filesystem.entry.Entry
import com.droid.explorer.gui.Css
import com.droid.explorer.gui.Icons
import com.droid.explorer.gui.TextIconCell
import com.droid.explorer.util.action
import javafx.animation.Animation
import javafx.animation.KeyFrame
import javafx.animation.Timeline
import javafx.event.EventHandler
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.control.cell.PropertyValueFactory
import javafx.scene.input.MouseEvent
import javafx.scene.layout.AnchorPane
import javafx.stage.Stage
import javafx.util.Duration
import org.controlsfx.control.BreadCrumbBar
import tornadofx.App
import tornadofx.FX
import tornadofx.FX.Companion.stylesheets
import tornadofx.View
import tornadofx.find
import java.util.*
import kotlin.concurrent.thread
import kotlin.properties.Delegates.notNull
/**
* Created by Jonathan on 4/23/2016.
*/
class AppClass : App() {
override val primaryView = DroidExplorer::class
override fun start(stage: Stage) {
FX.setPrimaryStage(stage = stage)
FX.setApplication(application = this)
try {
val view = find(primaryView)
droidExplorer = view
stage.apply {
scene = Scene(view.root)
scene.stylesheets.addAll(FX.stylesheets)
titleProperty().bind(view.titleProperty)
show()
}
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}
var droidExplorer by notNull<DroidExplorer>()
class DroidExplorer : View() {
override val root: AnchorPane by fxml()
private val type: TableColumn<Entry, String> by fxid()
private val name: TableColumn<Entry, String> by fxid()
private val status: Label by fxid()
val fileTable: TableView<Entry> by fxid()
val date: TableColumn<Entry, String> by fxid()
val permissions: TableColumn<Entry, String> by fxid()
val filePath: BreadCrumbBar<Entry> by fxid()
val back: Button by fxid()
val forward: Button by fxid()
val refresh: Button by fxid()
val home: Button by fxid()
init {
Start().run()
Root().run()
title = "Droid Explorer"
primaryStage.minHeight = 300.0
primaryStage.minWidth = 575.0
name.cellValueFactory = PropertyValueFactory("name")
date.cellValueFactory = PropertyValueFactory("date")
permissions.cellValueFactory = PropertyValueFactory("permissions")
type.cellValueFactory = PropertyValueFactory("type")
fileTable.placeholder = Label("This folder is empty.")
stylesheets.add(Css.MAIN)
primaryStage.icons.add(Icons.FAVICON.image)
back.graphic = Icons.BACK
forward.graphic = Icons.FORWARD
refresh.graphic = Icons.REFRESH
home.graphic = Icons.HOME
refresh.action = FileSystem::refresh
home.action = FileSystem.root::navigate
back.action = FileSystem::back
forward.action = FileSystem::forward
name.setCellFactory { TextIconCell() }
fileTable.onMouseClicked = EventHandler<MouseEvent> { mouseEvent ->
if (mouseEvent.clickCount % 2 == 0) {
val file = fileTable.selectionModel.selectedItem
file?.navigate()
}
}
fileTable.selectionModel.selectionMode = SelectionMode.MULTIPLE
filePath.setOnCrumbAction { it.selectedCrumb.value!!.navigate() }
thread {
val timeline = Timeline(KeyFrame(Duration.ZERO, EventHandler {
DeviceState().run {
if (it == "unknown") {
connected = false
} else if (!connected && it == "device") {
DeviceSerial().run {
connected = true
}
}
}
}), KeyFrame(Duration.millis(250.0)))
timeline.cycleCount = Animation.INDEFINITE
timeline.play()
}
}
var connected: Boolean = false
set(value) {
field = value
if (!connected) fileTable.items.clear()
status.text = if (connected) "Connected" else "Disconnected"
FileSystem.refresh()
}
}
|
apache-2.0
|
a28ff8004c4b8cdca37cc603df5496ae
| 27.150602 | 78 | 0.72523 | 3.768548 | false | false | false | false |
Aptoide/aptoide-client-v8
|
app/src/main/java/cm/aptoide/pt/download/view/DownloadViewActionPresenter.kt
|
1
|
13854
|
package cm.aptoide.pt.download.view
import cm.aptoide.analytics.AnalyticsManager
import cm.aptoide.pt.aab.DynamicSplit
import cm.aptoide.pt.aab.DynamicSplitsManager
import cm.aptoide.pt.actions.PermissionManager
import cm.aptoide.pt.actions.PermissionService
import cm.aptoide.pt.ads.MoPubAdsManager
import cm.aptoide.pt.ads.WalletAdsOfferManager.OfferResponseStatus
import cm.aptoide.pt.app.migration.AppcMigrationManager
import cm.aptoide.pt.crashreports.CrashReport
import cm.aptoide.pt.database.room.RoomDownload
import cm.aptoide.pt.download.*
import cm.aptoide.pt.install.InstallAnalytics
import cm.aptoide.pt.install.InstallManager
import cm.aptoide.pt.notification.NotificationAnalytics
import cm.aptoide.pt.presenter.ActionPresenter
import cm.aptoide.pt.presenter.View
import hu.akarnokd.rxjava.interop.RxJavaInterop
import rx.Completable
import rx.Observable
import rx.Scheduler
/**
* This presenter is only responsible for handling download actions.
* This means that whoever uses this is responsible for updating the download status correctly.
*
* This is useful in RecyclerView scenarios, where it does not make sense to tie each download view
* to a new presenter and where updating a view means actually updating a list of downloads.
*
* To update a view based on a Download object, consider observing [DownloadStatusModel] using
* [DownloadStatusManager] and rendering [Download] to views using [DownloadViewStatusHelper]
*/
open class DownloadViewActionPresenter(private val installManager: InstallManager,
private val moPubAdsManager: MoPubAdsManager,
private val permissionManager: PermissionManager,
private val appcMigrationManager: AppcMigrationManager,
private val downloadDialogProvider: DownloadDialogProvider,
private val downloadNavigator: DownloadNavigator,
private val permissionService: PermissionService,
private val ioScheduler: Scheduler,
private val viewScheduler: Scheduler,
private val downloadFactory: DownloadFactory,
private val downloadAnalytics: DownloadAnalytics,
private val installAnalytics: InstallAnalytics,
private val notificationAnalytics: NotificationAnalytics,
private val crashReport: CrashReport,
private val dynamicSplitsManager: DynamicSplitsManager) :
ActionPresenter<DownloadClick>() {
private lateinit var analyticsContext: DownloadAnalytics.AppContext
private var isInApkfyContext = false
private var editorsChoicePosition: String? = null
fun setContextParams(context: DownloadAnalytics.AppContext, isApkfy: Boolean,
editorsChoicePosition: String?) {
this.analyticsContext = context
this.isInApkfyContext = isApkfy
this.editorsChoicePosition = editorsChoicePosition
}
override fun present() {
if (!this::analyticsContext.isInitialized) {
throw java.lang.IllegalStateException("setContextParams must be called!")
}
lifecycleView.lifecycleEvent
.filter { lifecycleEvent -> lifecycleEvent == View.LifecycleEvent.CREATE }
.flatMap {
eventObservable
.skipWhile { event -> event.action == DownloadEvent.GENERIC_ERROR || event.action == DownloadEvent.OUT_OF_SPACE_ERROR }
.flatMapCompletable { event ->
when (event.action) {
DownloadEvent.INSTALL -> installApp(event)
DownloadEvent.RESUME -> resumeDownload(event)
DownloadEvent.PAUSE -> pauseDownload(event)
DownloadEvent.CANCEL -> cancelDownload(event)
DownloadEvent.GENERIC_ERROR -> downloadDialogProvider.showGenericError()
DownloadEvent.OUT_OF_SPACE_ERROR -> handleOutOfSpaceError(event)
}
}
.retry()
}
.compose(lifecycleView.bindUntilEvent(View.LifecycleEvent.DESTROY))
.subscribe({}, { err -> crashReport.log(err) })
}
private fun handleOutOfSpaceError(downloadClick: DownloadClick): Completable {
return downloadNavigator.openOutOfSpaceDialog(downloadClick.download.size,
downloadClick.download.packageName)
.andThen(downloadNavigator.outOfSpaceDialogResult()
.filter { result -> result.clearedSuccessfully }).first().toCompletable()
.andThen(resumeDownload(downloadClick))
.doOnError { t: Throwable? ->
t?.printStackTrace()
}
}
private fun installApp(downloadClick: DownloadClick): Completable {
when (downloadClick.download.downloadModel?.action) {
DownloadStatusModel.Action.MIGRATE,
DownloadStatusModel.Action.UPDATE,
DownloadStatusModel.Action.INSTALL -> {
return moPubAdsManager.adsVisibilityStatus
.flatMapCompletable { status -> downloadApp(downloadClick.download, status) }
}
DownloadStatusModel.Action.DOWNGRADE -> {
return moPubAdsManager.adsVisibilityStatus
.flatMapCompletable { status -> downgradeApp(downloadClick.download, status) }
}
DownloadStatusModel.Action.OPEN -> {
return downloadNavigator.openApp(downloadClick.download.packageName)
}
else -> {
return Completable.complete()
}
}
}
private fun downgradeApp(download: Download,
status: OfferResponseStatus): Completable {
return downloadDialogProvider.showDowngradeDialog()
.filter { downgrade -> downgrade }
.doOnNext { downloadDialogProvider.showDowngradingSnackBar() }
.flatMapCompletable { downloadApp(download, status) }
.toCompletable()
}
private fun downloadApp(download: Download,
status: OfferResponseStatus): Completable {
return Observable.defer {
if (installManager.showWarning()) {
return@defer downloadDialogProvider.showRootInstallWarningPopup()
.doOnNext { answer -> installManager.rootInstallAllowed(answer) }
.map { download }
}
return@defer Observable.just(download)
}
.observeOn(viewScheduler)
.flatMap {
permissionManager.requestDownloadAccessWithWifiBypass(permissionService,
download.size)
.flatMap { permissionManager.requestExternalStoragePermission(permissionService) }
.flatMapSingle {
RxJavaInterop.toV1Single(dynamicSplitsManager.getAppSplitsByMd5(download.md5))
}
.observeOn(ioScheduler)
.flatMapCompletable {
createDownload(download, status, it.dynamicSplitsList)
.doOnNext { roomDownload ->
setupDownloadEvents(roomDownload, download.appId,
download.downloadModel!!.action, status, download.storeName,
download.malware.rank.name)
if (DownloadStatusModel.Action.MIGRATE == download.downloadModel.action) {
installAnalytics.uninstallStarted(download.packageName,
AnalyticsManager.Action.INSTALL,
analyticsContext)
appcMigrationManager.addMigrationCandidate(download.packageName)
}
}
.flatMapCompletable { download -> installManager.install(download) }
.toCompletable()
}
}
.toCompletable()
}
private fun createDownload(download: Download,
offerResponseStatus: OfferResponseStatus,
dynamicSplitsList: List<DynamicSplit>): Observable<RoomDownload> {
return Observable.just(
downloadFactory.create(
parseDownloadAction(download.downloadModel!!.action),
download.appName, download.packageName, download.md5, download.icon,
download.versionName, download.versionCode, download.path,
download.pathAlt,
download.obb, download.hasAdvertising || download.hasBilling,
download.size,
download.splits, download.requiredSplits,
download.malware.rank.toString(), download.storeName, download.oemId,
dynamicSplitsList))
.doOnError { throwable ->
if (throwable is InvalidAppException) {
downloadAnalytics.sendAppNotValidError(download.packageName,
download.versionCode,
mapDownloadAction(download.downloadModel.action), offerResponseStatus,
download.downloadModel.action == DownloadStatusModel.Action.MIGRATE,
download.splits.isNotEmpty(),
download.hasAdvertising || download.hasBilling, download.malware
.rank
.toString(), download.storeName, isInApkfyContext, throwable)
}
}
}
private fun resumeDownload(downloadClick: DownloadClick): Completable {
return installManager.getDownload(downloadClick.download.md5)
.flatMap { download ->
moPubAdsManager.adsVisibilityStatus
.doOnSuccess { status ->
val dl = downloadClick.download
setupDownloadEvents(download, dl.appId, dl.downloadModel!!.action, status,
dl.storeName, dl.malware.rank.name)
}.map { download }
}
.doOnError { throwable -> throwable.printStackTrace() }
.flatMapCompletable { download -> installManager.install(download) }
}
private fun pauseDownload(downloadClick: DownloadClick): Completable {
return Completable.fromAction {
downloadAnalytics.downloadInteractEvent(downloadClick.download.packageName, "pause")
}.andThen(installManager.pauseInstall(downloadClick.download.md5))
}
private fun cancelDownload(downloadClick: DownloadClick): Completable {
return Completable.fromAction {
downloadAnalytics.downloadInteractEvent(downloadClick.download.packageName, "cancel")
}.andThen(installManager.cancelInstall(downloadClick.download.md5,
downloadClick.download.packageName, downloadClick.download.versionCode))
}
fun setupDownloadEvents(download: RoomDownload,
appId: Long,
downloadAction: DownloadStatusModel.Action,
offerResponseStatus: OfferResponseStatus?,
storeName: String?, malwareRank: String) {
val campaignId = notificationAnalytics.getCampaignId(download.packageName, appId)
val abTestGroup = notificationAnalytics.getAbTestingGroup(download.packageName, appId)
installAnalytics.installStarted(download.packageName, download.versionCode,
AnalyticsManager.Action.INSTALL, analyticsContext,
getOrigin(download.action), campaignId, abTestGroup,
downloadAction == DownloadStatusModel.Action.MIGRATE,
download.hasAppc(), download.hasSplits(), offerResponseStatus.toString(), malwareRank,
storeName, isInApkfyContext)
if (DownloadStatusModel.Action.MIGRATE == downloadAction) {
downloadAnalytics.migrationClicked(download.md5, download.versionCode, download.packageName,
malwareRank, editorsChoicePosition, InstallType.UPDATE_TO_APPC,
AnalyticsManager.Action.INSTALL, offerResponseStatus, download.hasAppc(),
download.hasSplits(), storeName,
isInApkfyContext)
downloadAnalytics.downloadStartEvent(download, campaignId, abTestGroup,
analyticsContext, AnalyticsManager.Action.INSTALL, true, isInApkfyContext)
} else {
downloadAnalytics.installClicked(download.md5, download.versionCode, download.packageName,
malwareRank, editorsChoicePosition, mapDownloadAction(downloadAction),
AnalyticsManager.Action.INSTALL, offerResponseStatus, download.hasAppc(),
download.hasSplits(), storeName, isInApkfyContext)
downloadAnalytics.downloadStartEvent(download, campaignId, abTestGroup,
analyticsContext, AnalyticsManager.Action.INSTALL, false, isInApkfyContext)
}
}
private fun mapDownloadAction(downloadAction: DownloadStatusModel.Action): InstallType {
return when (downloadAction) {
DownloadStatusModel.Action.DOWNGRADE -> InstallType.DOWNGRADE
DownloadStatusModel.Action.INSTALL -> InstallType.INSTALL
DownloadStatusModel.Action.UPDATE -> InstallType.UPDATE
DownloadStatusModel.Action.MIGRATE, DownloadStatusModel.Action.OPEN -> throw IllegalStateException(
"Mapping an invalid download action " + downloadAction.name)
}
}
private fun getOrigin(action: Int): Origin? {
return when (action) {
RoomDownload.ACTION_INSTALL -> Origin.INSTALL
RoomDownload.ACTION_UPDATE -> Origin.UPDATE
RoomDownload.ACTION_DOWNGRADE -> Origin.DOWNGRADE
else -> Origin.INSTALL
}
}
fun parseDownloadAction(action: DownloadStatusModel.Action): Int {
val downloadAction: Int
downloadAction = when (action) {
DownloadStatusModel.Action.INSTALL -> RoomDownload.ACTION_INSTALL
DownloadStatusModel.Action.UPDATE -> RoomDownload.ACTION_UPDATE
DownloadStatusModel.Action.DOWNGRADE -> RoomDownload.ACTION_DOWNGRADE
DownloadStatusModel.Action.MIGRATE -> RoomDownload.ACTION_DOWNGRADE
else -> throw IllegalArgumentException("Invalid action $action")
}
return downloadAction
}
}
|
gpl-3.0
|
29899ed92c2951c65bdcf14019f2c061
| 47.275261 | 133 | 0.674029 | 5.31008 | false | false | false | false |
ebraminio/DroidPersianCalendar
|
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/calendar/CalendarFragment.kt
|
1
|
21712
|
package com.byagowi.persiancalendar.ui.calendar
import android.Manifest
import android.animation.LayoutTransition
import android.content.ContentUris
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.CalendarContract
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.*
import android.widget.ArrayAdapter
import android.widget.FrameLayout
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.SearchView.SearchAutoComplete
import androidx.core.app.ActivityCompat
import androidx.core.content.edit
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.byagowi.persiancalendar.CALENDAR_EVENT_ADD_MODIFY_REQUEST_CODE
import com.byagowi.persiancalendar.LAST_CHOSEN_TAB_KEY
import com.byagowi.persiancalendar.PREF_HOLIDAY_TYPES
import com.byagowi.persiancalendar.R
import com.byagowi.persiancalendar.databinding.EventsTabContentBinding
import com.byagowi.persiancalendar.databinding.FragmentCalendarBinding
import com.byagowi.persiancalendar.databinding.OwghatTabContentBinding
import com.byagowi.persiancalendar.entities.CalendarEvent
import com.byagowi.persiancalendar.entities.DeviceCalendarEvent
import com.byagowi.persiancalendar.ui.MainActivity
import com.byagowi.persiancalendar.ui.calendar.dialogs.MonthOverviewDialog
import com.byagowi.persiancalendar.ui.calendar.dialogs.SelectDayDialog
import com.byagowi.persiancalendar.ui.calendar.dialogs.ShiftWorkDialog
import com.byagowi.persiancalendar.ui.calendar.times.TimeItemAdapter
import com.byagowi.persiancalendar.ui.shared.CalendarsView
import com.byagowi.persiancalendar.utils.*
import com.cepmuvakkit.times.posAlgo.SunMoonPosition
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.tabs.TabLayoutMediator
import io.github.persiancalendar.calendar.CivilDate
import io.github.persiancalendar.praytimes.Coordinate
import io.github.persiancalendar.praytimes.PrayTimesCalculator
import java.util.*
private const val CALENDARS_TAB = 0
private const val EVENTS_TAB = 1
private const val OWGHAT_TAB = 2
class CalendarFragment : Fragment() {
private var coordinate: Coordinate? = null
private lateinit var mainBinding: FragmentCalendarBinding
private lateinit var calendarsView: CalendarsView
private var owghatBinding: OwghatTabContentBinding? = null
private lateinit var eventsBinding: EventsTabContentBinding
private var searchView: SearchView? = null
private var todayButton: MenuItem? = null
abstract class TabsAdapter : RecyclerView.Adapter<TabsAdapter.ViewHolder>() {
inner class ViewHolder(private val frame: FrameLayout) : RecyclerView.ViewHolder(frame) {
fun bind(view: View) = frame.run {
removeAllViews()
addView(view)
}
}
}
lateinit var mainActivity: MainActivity
val initialDate = getTodayOfCalendar(mainCalendar)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View = FragmentCalendarBinding.inflate(inflater, container, false).apply {
mainBinding = this
mainActivity = activity as MainActivity
val tabs = listOf(
// First tab
R.string.calendar to CalendarsView(mainActivity).apply {
calendarsView = this
},
// Second tab
R.string.events to EventsTabContentBinding.inflate(inflater, container, false).apply {
eventsBinding = this
// Apply some animation, don't do the same for others tabs, it is problematic
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
eventsContent.layoutTransition =
LayoutTransition().apply { enableTransitionType(LayoutTransition.CHANGING) }
}
}.root
) + (getCoordinate(mainActivity)?.run {
coordinate = this
listOf(
// Optional third tab
R.string.owghat to OwghatTabContentBinding.inflate(
inflater, container, false
).apply {
owghatBinding = this
root.setOnClickListener { onOwghatClick() }
cityName.run {
setOnClickListener { onOwghatClick() }
// Easter egg to test AthanActivity
setOnLongClickListener {
startAthan(context, "FAJR")
true
}
val cityName = getCityName(context, false)
if (cityName.isNotEmpty()) text = cityName
}
timesRecyclerView.run {
layoutManager = FlexboxLayoutManager(context).apply {
flexWrap = FlexWrap.WRAP
justifyContent = JustifyContent.CENTER
}
adapter = TimeItemAdapter()
}
}.root
)
} ?: emptyList())
calendarPager.onDayClicked = fun(jdn: Long) { bringDate(jdn, monthChange = false) }
calendarPager.onDayLongClicked = fun(jdn: Long) { addEventOnCalendar(jdn) }
calendarPager.onMonthSelected = fun() {
val date = calendarPager.selectedMonth
mainActivity.setTitleAndSubtitle(getMonthName(date), formatNumber(date.year))
todayButton?.isVisible =
date.year != initialDate.year || date.month != initialDate.month
}
viewPager.adapter = object : TabsAdapter() {
override fun getItemCount(): Int = tabs.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) =
holder.bind(tabs[position].second)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder(
FrameLayout(mainActivity).apply {
layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
)
}
)
}
TabLayoutMediator(tabLayout, viewPager) { tab, i -> tab.setText(tabs[i].first) }.attach()
viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
if (position == OWGHAT_TAB) owghatBinding?.sunView?.startAnimate()
else owghatBinding?.sunView?.clear()
mainActivity.appPrefs.edit { putInt(LAST_CHOSEN_TAB_KEY, position) }
}
})
var lastTab = mainActivity.appPrefs.getInt(LAST_CHOSEN_TAB_KEY, CALENDARS_TAB)
if (lastTab >= tabs.size) lastTab = CALENDARS_TAB
viewPager.setCurrentItem(lastTab, false)
}.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
bringDate(getTodayJdn(), monthChange = false, highlight = false)
setHasOptionsMenu(true)
getTodayOfCalendar(mainCalendar).also {
mainActivity.setTitleAndSubtitle(
getMonthName(it),
formatNumber(it.year)
)
}
}
private fun addEventOnCalendar(jdn: Long) {
val civil = CivilDate(jdn)
val time = Calendar.getInstance()
time.set(civil.year, civil.month - 1, civil.dayOfMonth)
if (ActivityCompat.checkSelfPermission(
mainActivity, Manifest.permission.READ_CALENDAR
) != PackageManager.PERMISSION_GRANTED
) askForCalendarPermission(activity) else {
try {
startActivityForResult(
Intent(Intent.ACTION_INSERT)
.setData(CalendarContract.Events.CONTENT_URI)
.putExtra(
CalendarContract.Events.DESCRIPTION, dayTitleSummary(
getDateFromJdnOfCalendar(mainCalendar, jdn)
)
)
.putExtra(
CalendarContract.EXTRA_EVENT_BEGIN_TIME,
time.timeInMillis
)
.putExtra(
CalendarContract.EXTRA_EVENT_END_TIME,
time.timeInMillis
)
.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true),
CALENDAR_EVENT_ADD_MODIFY_REQUEST_CODE
)
} catch (e: Exception) {
e.printStackTrace()
Snackbar.make(
mainBinding.root,
R.string.device_calendar_does_not_support,
Snackbar.LENGTH_SHORT
).show()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == CALENDAR_EVENT_ADD_MODIFY_REQUEST_CODE) {
if (isShowDeviceCalendarEvents)
mainBinding.calendarPager.refresh(isEventsModified = true)
else {
if (ActivityCompat.checkSelfPermission(
mainActivity, Manifest.permission.READ_CALENDAR
) != PackageManager.PERMISSION_GRANTED
) askForCalendarPermission(activity) else {
toggleShowDeviceCalendarOnPreference(mainActivity, true)
mainActivity.restartActivity()
}
}
}
}
private fun getDeviceEventsTitle(dayEvents: List<CalendarEvent<*>>) = dayEvents
.filterIsInstance<DeviceCalendarEvent>()
.map { event ->
SpannableString(formatDeviceCalendarEventTitle(event)).apply {
setSpan(object : ClickableSpan() {
override fun onClick(textView: View) = try {
startActivityForResult(
Intent(Intent.ACTION_VIEW)
.setData(
ContentUris.withAppendedId(
CalendarContract.Events.CONTENT_URI, event.id.toLong()
)
),
CALENDAR_EVENT_ADD_MODIFY_REQUEST_CODE
)
} catch (e: Exception) { // Should be ActivityNotFoundException but we don't care really
e.printStackTrace()
Snackbar.make(
textView,
R.string.device_calendar_does_not_support,
Snackbar.LENGTH_SHORT
).show()
}
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
if (event.color.isNotEmpty()) {
try {
// should be turned to long then int otherwise gets stupid alpha
ds.color = event.color.toLong().toInt()
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}, 0, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}
.foldIndexed(SpannableStringBuilder()) { i, result, x ->
if (i != 0) result.append("\n")
result.append(x)
result
}
private var selectedJdn = getTodayJdn()
private fun bringDate(jdn: Long, highlight: Boolean = true, monthChange: Boolean = true) {
selectedJdn = jdn
mainBinding.calendarPager.setSelectedDay(jdn, highlight, monthChange)
val isToday = getTodayJdn() == jdn
// Show/Hide bring today menu button
todayButton?.isVisible = !isToday
// Update tabs
calendarsView.showCalendars(jdn, mainCalendar, getEnabledCalendarTypes())
showEvent(jdn, isToday)
setOwghat(jdn, isToday)
// a11y
if (isTalkBackEnabled && !isToday && monthChange) Snackbar.make(
mainBinding.root,
getA11yDaySummary(
mainActivity, jdn, false, emptyEventsStore(),
withZodiac = true, withOtherCalendars = true, withTitle = true
),
Snackbar.LENGTH_SHORT
).show()
}
private fun showEvent(jdn: Long, isToday: Boolean) {
eventsBinding.run {
shiftWorkTitle.text = getShiftWorkTitle(jdn, false)
val events = getEvents(
jdn,
readDayDeviceEvents(mainActivity, jdn)
)
val holidays = getEventsTitle(
events,
holiday = true,
compact = false,
showDeviceCalendarEvents = false,
insertRLM = false,
addIsHoliday = isHighTextContrastEnabled
)
val nonHolidays = getEventsTitle(
events,
holiday = false,
compact = false,
showDeviceCalendarEvents = false,
insertRLM = false,
addIsHoliday = false
)
val deviceEvents = getDeviceEventsTitle(events)
val contentDescription = StringBuilder()
eventMessage.visibility = View.GONE
noEvent.visibility = View.VISIBLE
if (holidays.isNotEmpty()) {
noEvent.visibility = View.GONE
holidayTitle.text = holidays
val holidayContent = getString(R.string.holiday_reason) + "\n" + holidays
holidayTitle.contentDescription = holidayContent
contentDescription.append(holidayContent)
holidayTitle.visibility = View.VISIBLE
} else {
holidayTitle.visibility = View.GONE
}
if (deviceEvents.isNotEmpty()) {
noEvent.visibility = View.GONE
deviceEventTitle.text = deviceEvents
contentDescription.append("\n")
contentDescription.append(getString(R.string.show_device_calendar_events))
contentDescription.append("\n")
contentDescription.append(deviceEvents)
deviceEventTitle.movementMethod = LinkMovementMethod.getInstance()
deviceEventTitle.visibility = View.VISIBLE
} else {
deviceEventTitle.visibility = View.GONE
}
if (nonHolidays.isNotEmpty()) {
noEvent.visibility = View.GONE
eventTitle.text = nonHolidays
contentDescription.append("\n")
contentDescription.append(getString(R.string.events))
contentDescription.append("\n")
contentDescription.append(nonHolidays)
eventTitle.visibility = View.VISIBLE
} else {
eventTitle.visibility = View.GONE
}
val messageToShow = SpannableStringBuilder()
val enabledTypes = mainActivity.appPrefs
.getStringSet(PREF_HOLIDAY_TYPES, null) ?: emptySet()
if (enabledTypes.isEmpty()) {
noEvent.visibility = View.GONE
if (messageToShow.isNotEmpty()) messageToShow.append("\n")
val title = getString(R.string.warn_if_events_not_set)
val ss = SpannableString(title)
val clickableSpan = object : ClickableSpan() {
override fun onClick(textView: View) {
mainActivity.navigateTo(R.id.settings)
}
}
ss.setSpan(clickableSpan, 0, title.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
messageToShow.append(ss)
contentDescription.append("\n")
contentDescription.append(title)
}
if (messageToShow.isNotEmpty()) {
eventMessage.text = messageToShow
eventMessage.movementMethod = LinkMovementMethod.getInstance()
eventMessage.visibility = View.VISIBLE
}
root.contentDescription = contentDescription
}
}
private fun setOwghat(jdn: Long, isToday: Boolean) {
if (coordinate == null) return
val prayTimes = PrayTimesCalculator.calculate(
calculationMethod, CivilDate(jdn).toCalendar().time, coordinate
)
(owghatBinding?.timesRecyclerView?.adapter as? TimeItemAdapter)?.prayTimes = prayTimes
owghatBinding?.sunView?.run {
setSunriseSunsetMoonPhase(prayTimes, try {
coordinate?.run {
SunMoonPosition(
getTodayJdn().toDouble(), latitude,
longitude, 0.0, 0.0
).moonPhase
} ?: 1.0
} catch (e: Exception) {
e.printStackTrace()
1.0
})
visibility = if (isToday) View.VISIBLE else View.GONE
if (isToday && mainBinding.viewPager.currentItem == OWGHAT_TAB) startAnimate()
}
}
private fun onOwghatClick() {
(owghatBinding?.timesRecyclerView?.adapter as? TimeItemAdapter)?.run {
isExpanded = !isExpanded
owghatBinding?.moreOwghat?.setImageResource(
if (isExpanded) R.drawable.ic_keyboard_arrow_up
else R.drawable.ic_keyboard_arrow_down
)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
menu.clear()
inflater.inflate(R.menu.calendar_menu_buttons, menu)
todayButton = menu.findItem(R.id.today_button).apply {
isVisible = false
setOnMenuItemClickListener {
bringDate(getTodayJdn(), highlight = false)
true
}
}
searchView = (menu.findItem(R.id.search).actionView as? SearchView?)?.apply {
setOnSearchClickListener {
// Remove search edit view below bar
findViewById<View?>(androidx.appcompat.R.id.search_plate)?.setBackgroundColor(
Color.TRANSPARENT
)
findViewById<SearchAutoComplete?>(androidx.appcompat.R.id.search_src_text)?.apply {
setHint(R.string.search_in_events)
setAdapter(
ArrayAdapter<CalendarEvent<*>>(
mainActivity, R.layout.suggestion, android.R.id.text1,
allEnabledEvents + getAllEnabledAppointments(context)
)
)
setOnItemClickListener { parent, _, position, _ ->
val date = (parent.getItemAtPosition(position) as CalendarEvent<*>).date
val type = getCalendarTypeFromDate(date)
val today = getTodayOfCalendar(type)
bringDate(
getDateOfCalendar(
type,
if (date.year == -1)
(today.year + if (date.month < today.month) 1 else 0)
else date.year,
date.month,
date.dayOfMonth
).toJdn()
)
onActionViewCollapsed()
}
}
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.go_to -> SelectDayDialog.newInstance(selectedJdn).apply {
onSuccess = fun(jdn: Long) { bringDate(jdn) }
}.show(
childFragmentManager,
SelectDayDialog::class.java.name
)
R.id.add_event -> addEventOnCalendar(selectedJdn)
R.id.shift_work -> ShiftWorkDialog.newInstance(selectedJdn).apply {
onSuccess = fun() {
updateStoredPreference(mainActivity)
mainActivity.restartActivity()
}
}.show(
childFragmentManager,
ShiftWorkDialog::class.java.name
)
R.id.month_overview -> MonthOverviewDialog
.newInstance(mainBinding.calendarPager.selectedMonth.toJdn())
.show(childFragmentManager, MonthOverviewDialog::class.java.name)
}
return true
}
fun closeSearch() = searchView?.run {
if (!isIconified) {
onActionViewCollapsed()
return true
} else false
} ?: false
}
|
gpl-3.0
|
d76b655269709972687e2d78f0b7fed6
| 40.045369 | 108 | 0.570007 | 5.429357 | false | false | false | false |
ccomeaux/boardgamegeek4android
|
app/src/main/java/com/boardgamegeek/ui/viewmodel/LoginViewModel.kt
|
1
|
1414
|
package com.boardgamegeek.ui.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.boardgamegeek.auth.BggCookieJar
import com.boardgamegeek.auth.NetworkAuthenticator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class LoginViewModel(application: Application) : AndroidViewModel(application) {
private var authenticationJob: Job? = null
private val _isAuthenticating = MutableLiveData<Boolean>()
val isAuthenticating: LiveData<Boolean>
get() = _isAuthenticating
private val _authenticationResult = MutableLiveData<BggCookieJar?>()
val authenticationResult: LiveData<BggCookieJar?>
get() = _authenticationResult
fun login(username: String?, password: String?) {
_isAuthenticating.value = true
authenticationJob = viewModelScope.launch(Dispatchers.IO) {
val bggCookieJar = NetworkAuthenticator.authenticate(
username.orEmpty(), password.orEmpty(), "Dialog", getApplication()
)
_authenticationResult.postValue(bggCookieJar)
_isAuthenticating.postValue(false)
}
}
fun cancel() {
authenticationJob?.cancel()
_isAuthenticating.value = false
}
}
|
gpl-3.0
|
90c33c06dd8ebea81ed9ef1d87469299
| 34.35 | 82 | 0.736917 | 5.237037 | false | false | false | false |
zoff99/ToxAndroidRefImpl
|
android-refimpl-app/app/src/main/java/com/zoffcc/applications/trifa/YuvToRgbConverter.kt
|
1
|
3271
|
package com.zoffcc.applications.trifa
import android.content.Context
import android.graphics.Bitmap
import android.graphics.ImageFormat
import android.media.Image
import android.renderscript.*
import java.nio.ByteBuffer
/**
* Helper class used to convert a [Image] object from
* [ImageFormat.YUV_420_888] format to an RGB [Bitmap] object, it has equivalent
* functionality to https://github
* .com/androidx/androidx/blob/androidx-main/camera/camera-core/src/main/java/androidx/camera/core/ImageYuvToRgbConverter.java
*
* NOTE: This has been tested in a limited number of devices and is not
* considered production-ready code. It was created for illustration purposes,
* since this is not an efficient camera pipeline due to the multiple copies
* required to convert each frame. For example, this
* implementation
* (https://stackoverflow.com/questions/52726002/camera2-captured-picture-conversion-from-yuv-420-888-to-nv21/52740776#52740776)
* might have better performance.
*/
class YuvToRgbConverter(context: Context) {
private val rs = RenderScript.create(context)
private val scriptYuvToRgb =
ScriptIntrinsicYuvToRGB.create(rs, Element.U8_4(rs))
// Do not add getters/setters functions to these private variables
// because yuvToRgb() assume they won't be modified elsewhere
private var yuvBits: ByteBuffer? = null
private var bytes: ByteArray = ByteArray(0)
private var inputAllocation: Allocation? = null
private var outputAllocation: Allocation? = null
@Synchronized
fun yuvToRgb(image: Image, output: Bitmap) {
val yuvBuffer = YuvByteBuffer(image, yuvBits)
yuvBits = yuvBuffer.buffer
if (needCreateAllocations(image, yuvBuffer)) {
val yuvType = Type.Builder(rs, Element.U8(rs))
.setX(image.width)
.setY(image.height)
.setYuvFormat(yuvBuffer.type)
inputAllocation = Allocation.createTyped(
rs,
yuvType.create(),
Allocation.USAGE_SCRIPT
)
bytes = ByteArray(yuvBuffer.buffer.capacity())
val rgbaType = Type.Builder(rs, Element.RGBA_8888(rs))
.setX(image.width)
.setY(image.height)
outputAllocation = Allocation.createTyped(
rs,
rgbaType.create(),
Allocation.USAGE_SCRIPT
)
}
yuvBuffer.buffer.get(bytes)
inputAllocation!!.copyFrom(bytes)
// Convert NV21 or YUV_420_888 format to RGB
inputAllocation!!.copyFrom(bytes)
scriptYuvToRgb.setInput(inputAllocation)
scriptYuvToRgb.forEach(outputAllocation)
outputAllocation!!.copyTo(output)
}
private fun needCreateAllocations(image: Image, yuvBuffer: YuvByteBuffer): Boolean {
return (inputAllocation == null || // the very 1st call
inputAllocation!!.type.x != image.width || // image size changed
inputAllocation!!.type.y != image.height ||
inputAllocation!!.type.yuv != yuvBuffer.type || // image format changed
bytes.size == yuvBuffer.buffer.capacity())
}
}
|
gpl-3.0
|
41644c3b57b62552cea3e16262e0bf81
| 40.417722 | 128 | 0.653928 | 4.396505 | false | false | false | false |
shkschneider/android_Skeleton
|
core/src/main/kotlin/me/shkschneider/skeleton/helper/ShortcutHelper.kt
|
1
|
2551
|
package me.shkschneider.skeleton.helper
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.graphics.drawable.Icon
import androidx.annotation.DrawableRes
import androidx.annotation.RequiresApi
import me.shkschneider.skeleton.helperx.Logger
import me.shkschneider.skeleton.helperx.SystemServices
// <https://developer.android.com/reference/android/content/pm/ShortcutManager.html>
@RequiresApi(AndroidHelper.API_25)
object ShortcutHelper {
private val maxRecommendedShortcuts by lazy {
SystemServices.shortcutManager()?.maxShortcutCountPerActivity ?: 4
}
open class Shortcut(
private var id: String,
@DrawableRes private var icon: Int,
private var label: String,
private var intent: Intent
) {
init {
if (intent.action.isNullOrEmpty()) {
intent.action = ApplicationHelper.packageName() + "\\." + this.id
}
}
fun shortcutInfo(): ShortcutInfo {
return ShortcutInfo.Builder(ContextHelper.applicationContext(), id)
.setIcon(Icon.createWithResource(ContextHelper.applicationContext(), icon))
.setShortLabel(label)
.setIntent(intent)
.build()
}
}
fun addDynamicShortcut(shortcut: Shortcut): Boolean {
SystemServices.shortcutManager()?.let { shortcutManager ->
val shortcutsInfo = shortcutManager.dynamicShortcuts
if (shortcutsInfo.size + 1 >= maxRecommendedShortcuts) {
Logger.warning("Lots of shortcuts")
}
return shortcutManager.isRateLimitingActive && shortcutManager.addDynamicShortcuts(listOf(shortcut.shortcutInfo()))
}
Logger.warning("ShortcutManager was NULL")
return false
}
fun setDynamicShortcuts(vararg shortcuts: Shortcut): Boolean {
if (shortcuts.size >= maxRecommendedShortcuts) {
Logger.warning("Lots of shortcuts")
}
val shortcutManager = SystemServices.shortcutManager() ?: return false
if (shortcutManager.isRateLimitingActive) {
return false
}
val shortcutInfos = shortcuts.map { it.shortcutInfo() }
return shortcutManager.setDynamicShortcuts(shortcutInfos)
}
fun removeDynamicShortcuts(): Boolean {
val shortcutManager = SystemServices.shortcutManager() ?: return false
shortcutManager.removeAllDynamicShortcuts()
return true
}
}
|
apache-2.0
|
7f2c39542f19ea221af4fc0d8c289798
| 34.430556 | 127 | 0.660917 | 5.303534 | false | false | false | false |
BasinMC/Basin
|
faucet/src/main/kotlin/org/basinmc/faucet/util/BitMask.kt
|
1
|
3346
|
/*
* Copyright 2019 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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.basinmc.faucet.util
import java.util.*
/**
* Represents an arbitrary bit mask which expresses the state of one or more predefined flags.
*
* @author [Johannes Donath](mailto:[email protected])
*/
abstract class BitMask<M : BitMask<M>> protected constructor(private val mask: Int) : Iterable<M> {
abstract val definition: Definition<M>
/**
* Retrieves the total amount of set flags within this mask.
*
* @return an amount of flags.
*/
val size = Integer.bitCount(this.mask)
/**
* Evaluates whether this mask contains the indicated flag.
*
* @param state an arbitrary flag.
* @return true if set, false otherwise.
*/
fun has(state: M) = if (this.javaClass != state.javaClass) { // TODO: Does this seem sensible?
false
} else {
this.mask and (state as BitMask<*>).mask == (state as BitMask<*>).mask
}
/**
* Sets one or more flags within this mask.
*
* @param state an arbitrary flag.
*/
fun set(state: M): M {
if (this.javaClass != state.javaClass) {
throw IllegalArgumentException(
"Expected state flag to be of type " + this.javaClass.name + " but got " + state.javaClass.name)
}
return this.definition.newInstance(this.mask xor (state as BitMask<*>).mask)
}
/**
* Un-Sets one or more flags within this mask.
*
* @param state an arbitrary flag.
*/
fun unset(state: M): M {
if (this.javaClass != state.javaClass) {
throw IllegalArgumentException(
"Expected state flag to be of type " + this.javaClass.name + " but got " + state.javaClass.name)
}
return this.definition.newInstance(this.mask and (state as BitMask<*>).mask.inv())
}
/**
* {@inheritDoc}
*/
override fun iterator(): Iterator<M> {
return this.definition.values
.filter(this::has)
.iterator()
}
interface Definition<M : BitMask<M>> {
/**
* Constructs a mutated bitmask instance for this particular type.
*
* @param mask an arbitrary bitmask.
* @return a mutated instance.
*/
fun newInstance(mask: Int): M
/**
* Retrieves a list of all permitted values within this mask type.
*
* @return a list of permitted values.
*/
val values: Collection<M>
}
/**
* {@inheritDoc}
*/
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is BitMask<*>) {
return false
}
val bitMask = other as BitMask<*>?
return this.mask == bitMask!!.mask
}
/**
* {@inheritDoc}
*/
override fun hashCode(): Int {
return Objects.hash(this.mask)
}
}
|
apache-2.0
|
e4fc1041f0f18817003a3abc3d25e2b2
| 25.768 | 106 | 0.646145 | 3.997611 | false | false | false | false |
zml2008/configurate
|
buildSrc/src/main/kotlin/org/spongepowered/configurate/build/ConfigurateDevPlugin.kt
|
1
|
3088
|
package org.spongepowered.configurate.build
import net.minecrell.gradle.licenser.LicenseExtension
import net.minecrell.gradle.licenser.Licenser
import org.gradle.api.JavaVersion
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaLibraryPlugin
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.tasks.bundling.AbstractArchiveTask
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.api.tasks.javadoc.Javadoc
import org.gradle.api.tasks.testing.Test
import org.gradle.external.javadoc.StandardJavadocDocletOptions
class ConfigurateDevPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
plugins.apply {
apply(Licenser::class.java)
apply(JavaLibraryPlugin::class.java)
apply(ConfiguratePublishingPlugin::class.java)
}
tasks.withType(JavaCompile::class.java) {
with(it.options) {
compilerArgs.addAll(listOf("-Xlint:all", "-Xlint:-path", "-Xlint:-serial", "-parameters"))
isDeprecation = true
encoding = "UTF-8"
}
}
tasks.withType(AbstractArchiveTask::class.java) {
it.isPreserveFileTimestamps = false
it.isReproducibleFileOrder = true
}
extensions.configure(JavaPluginExtension::class.java) {
it.withJavadocJar()
it.withSourcesJar()
it.sourceCompatibility = JavaVersion.VERSION_1_8
it.targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType(Javadoc::class.java) {
val opts = it.options
if (opts is StandardJavadocDocletOptions) {
opts.links(
"https://guava.dev/releases/25.1-jre/api/docs/"
)
opts.addBooleanOption("html5")
}
}
extensions.configure(LicenseExtension::class.java) {
with(it) {
header = rootProject.file("LICENSE_HEADER")
include("**/*.java")
include("**/*.kt")
newLine = false
}
}
repositories.addAll(listOf(repositories.mavenLocal(), repositories.mavenCentral(), repositories.jcenter()))
dependencies.apply {
add("testImplementation", "org.junit.jupiter:junit-jupiter-api:5.2.0")
add("testImplementation", "org.junit-pioneer:junit-pioneer:0.1.2")
add("testRuntimeOnly", "org.junit.jupiter:junit-jupiter-engine:5.2.0")
}
tasks.withType(Test::class.java) {
it.useJUnitPlatform()
}
extensions.configure(ConfiguratePublishingExtension::class.java) {
it.publish {
from(components.getByName("java"))
}
}
}
}
}
|
apache-2.0
|
7ccad91ff6ca4ce018d77a7205d750c9
| 36.658537 | 119 | 0.570272 | 4.787597 | false | true | false | false |
danrien/projectBlueWater
|
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/items/list/DemoableItemListAdapter.kt
|
1
|
3561
|
package com.lasthopesoftware.bluewater.client.browsing.items.list
import android.app.Activity
import android.os.Build
import android.view.View
import android.widget.ViewAnimator
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.client.browsing.items.access.ProvideItems
import com.lasthopesoftware.bluewater.client.browsing.items.list.menus.changes.handlers.IItemListMenuChangeHandler
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.IFileListParameterProvider
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.stringlist.FileStringListProvider
import com.lasthopesoftware.bluewater.client.browsing.items.menu.LongClickViewAnimatorListener
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItemAccess
import com.lasthopesoftware.bluewater.shared.android.messages.SendMessages
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise
import com.lasthopesoftware.bluewater.tutorials.ManageTutorials
import com.lasthopesoftware.bluewater.tutorials.TutorialManager
import tourguide.tourguide.Overlay
import tourguide.tourguide.Pointer
import tourguide.tourguide.ToolTip
import tourguide.tourguide.TourGuide
class DemoableItemListAdapter
(
private val activity: Activity,
sendMessages: SendMessages,
fileListParameterProvider: IFileListParameterProvider,
fileStringListProvider: FileStringListProvider,
itemListMenuEvents: IItemListMenuChangeHandler,
storedItemAccess: StoredItemAccess,
provideItems: ProvideItems,
libraryId: LibraryId,
private val manageTutorials: ManageTutorials
) : ItemListAdapter(
activity,
sendMessages,
fileListParameterProvider,
fileStringListProvider,
itemListMenuEvents,
storedItemAccess,
provideItems,
libraryId
) {
private var wasTutorialShown = false
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
super.onBindViewHolder(holder, position)
if (itemCount == 1 || position != 2)
bindTutorialView(holder.itemView)
}
private fun bindTutorialView(view: View) {
// use this flag to ensure the least amount of possible work is done for this tutorial
if (wasTutorialShown) return
wasTutorialShown = true
fun showTutorial() {
val displayColor =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) activity.resources.getColor(R.color.project_blue_light, null)
else activity.resources.getColor(R.color.project_blue_light)
val tourGuide = TourGuide.init(activity).with(TourGuide.Technique.CLICK)
.setPointer(Pointer().setColor(displayColor))
.setToolTip(
ToolTip()
.setTitle(activity.getString(R.string.title_long_click_menu))
.setDescription(activity.getString(R.string.tutorial_long_click_menu))
.setBackgroundColor(displayColor)
)
.setOverlay(Overlay())
.playOn(view)
view.setOnLongClickListener {
tourGuide.cleanUp()
if (view is ViewAnimator)
view.setOnLongClickListener(LongClickViewAnimatorListener(view))
false
}
}
if (DEBUGGING_TUTORIAL) {
showTutorial()
return
}
manageTutorials
.promiseWasTutorialShown(TutorialManager.KnownTutorials.longPressListTutorial)
.eventually(LoopedInPromise.response({ wasShown ->
if (!wasShown) {
showTutorial()
manageTutorials.promiseTutorialMarked(TutorialManager.KnownTutorials.longPressListTutorial)
}
}, activity))
}
companion object {
private const val DEBUGGING_TUTORIAL = false
}
}
|
lgpl-3.0
|
56589e20812371983b77d08057301a66
| 33.911765 | 117 | 0.808762 | 4.112009 | false | false | false | false |
tasks/tasks
|
app/src/main/java/org/tasks/ui/ChipListCache.kt
|
1
|
2164
|
package org.tasks.ui
import com.todoroo.astrid.api.CaldavFilter
import com.todoroo.astrid.api.Filter
import com.todoroo.astrid.api.GtasksFilter
import com.todoroo.astrid.api.TagFilter
import org.tasks.LocalBroadcastManager
import org.tasks.data.*
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ChipListCache @Inject internal constructor(
googleTaskListDao: GoogleTaskListDao,
caldavDao: CaldavDao,
tagDataDao: TagDataDao,
private val localBroadcastManager: LocalBroadcastManager) {
private val googleTaskLists: MutableMap<String?, GtasksFilter> = HashMap()
private val caldavCalendars: MutableMap<String?, CaldavFilter> = HashMap()
private val tagDatas: MutableMap<String?, TagFilter> = HashMap()
private fun updateGoogleTaskLists(updated: List<GoogleTaskList>) {
googleTaskLists.clear()
for (update in updated) {
googleTaskLists[update.remoteId] = GtasksFilter(update)
}
localBroadcastManager.broadcastRefresh()
}
private fun updateCaldavCalendars(updated: List<CaldavCalendar>) {
caldavCalendars.clear()
for (update in updated) {
caldavCalendars[update.uuid] = CaldavFilter(update)
}
localBroadcastManager.broadcastRefresh()
}
private fun updateTags(updated: List<TagData>) {
tagDatas.clear()
for (update in updated) {
tagDatas[update.remoteId] = TagFilter(update)
}
localBroadcastManager.broadcastRefresh()
}
fun getGoogleTaskList(googleTaskList: String?): Filter? = googleTaskLists[googleTaskList]
fun getCaldavList(caldav: String?): Filter? = caldavCalendars[caldav]
fun getTag(tag: String?): TagFilter? = tagDatas[tag]
init {
googleTaskListDao.subscribeToLists().observeForever { updated: List<GoogleTaskList> -> updateGoogleTaskLists(updated) }
caldavDao.subscribeToCalendars().observeForever { updated: List<CaldavCalendar> -> updateCaldavCalendars(updated) }
tagDataDao.subscribeToTags().observeForever { updated: List<TagData> -> updateTags(updated) }
}
}
|
gpl-3.0
|
efe469a8f8c3766a6617676f334442ce
| 36.327586 | 127 | 0.718577 | 4.452675 | false | false | false | false |
natanieljr/droidmate
|
project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/reporter/ApkViewsFileMF.kt
|
1
|
2622
|
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.reporter
import kotlinx.coroutines.CoroutineName
import org.droidmate.exploration.ExplorationContext
import org.droidmate.exploration.modelFeatures.misc.uniqueActionableWidgets
import org.droidmate.exploration.modelFeatures.misc.uniqueClickedWidgets
import java.nio.file.Files
import java.nio.file.Path
import kotlin.coroutines.CoroutineContext
class ApkViewsFileMF(reportDir: Path,
resourceDir: Path,
val fileName: String = "views.txt") : ApkReporterMF(reportDir, resourceDir) {
override val coroutineContext: CoroutineContext = CoroutineName("ApkViewsFileMF")
override suspend fun safeWriteApkReport(context: ExplorationContext<*, *, *>, apkReportDir: Path, resourceDir: Path) {
val reportData = getReportData(context)
val reportFile = apkReportDir.resolve(fileName)
Files.write(reportFile, reportData.toByteArray())
}
private fun getReportData(data: ExplorationContext<*,*,*>): String {
val sb = StringBuilder()
sb.append("Unique actionable widget\n")
.append(data.uniqueActionableWidgets.joinToString(separator = System.lineSeparator()) { it.uid.toString() })
.append("\n====================\n")
.append("Unique clicked widgets\n")
.append(data.uniqueClickedWidgets.joinToString(separator = System.lineSeparator()) { it.uid.toString() })
return sb.toString()
}
override fun reset() {
// Do nothing
// Nothing to reset here
}
}
|
gpl-3.0
|
64a72bcb42a04192ccc0512311bdc2a2
| 40.619048 | 124 | 0.712052 | 4.482051 | false | false | false | false |
arturbosch/detekt
|
detekt-report-html/src/main/kotlin/io/github/detekt/report/html/HtmlOutputReport.kt
|
1
|
6039
|
package io.github.detekt.report.html
import io.github.detekt.metrics.ComplexityReportGenerator
import io.github.detekt.psi.toUnifiedString
import io.gitlab.arturbosch.detekt.api.Detektion
import io.gitlab.arturbosch.detekt.api.Finding
import io.gitlab.arturbosch.detekt.api.OutputReport
import io.gitlab.arturbosch.detekt.api.ProjectMetric
import io.gitlab.arturbosch.detekt.api.TextLocation
import io.gitlab.arturbosch.detekt.api.internal.whichDetekt
import kotlinx.html.CommonAttributeGroupFacadeFlowInteractiveContent
import kotlinx.html.FlowContent
import kotlinx.html.FlowOrInteractiveContent
import kotlinx.html.HTMLTag
import kotlinx.html.HtmlTagMarker
import kotlinx.html.TagConsumer
import kotlinx.html.attributesMapOf
import kotlinx.html.details
import kotlinx.html.div
import kotlinx.html.h3
import kotlinx.html.id
import kotlinx.html.li
import kotlinx.html.span
import kotlinx.html.stream.createHTML
import kotlinx.html.ul
import kotlinx.html.visit
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Locale
private const val DEFAULT_TEMPLATE = "default-html-report-template.html"
private const val PLACEHOLDER_METRICS = "@@@metrics@@@"
private const val PLACEHOLDER_FINDINGS = "@@@findings@@@"
private const val PLACEHOLDER_COMPLEXITY_REPORT = "@@@complexity@@@"
private const val PLACEHOLDER_VERSION = "@@@version@@@"
private const val PLACEHOLDER_DATE = "@@@date@@@"
/**
* Contains rule violations and metrics formatted in a human friendly way, so that it can be inspected in a web browser.
* See: https://detekt.github.io/detekt/configurations.html#output-reports
*/
class HtmlOutputReport : OutputReport() {
override val ending = "html"
override val name = "HTML report"
override fun render(detektion: Detektion) =
javaClass.getResource("/$DEFAULT_TEMPLATE")
.openStream()
.bufferedReader()
.use { it.readText() }
.replace(PLACEHOLDER_VERSION, renderVersion())
.replace(PLACEHOLDER_DATE, renderDate())
.replace(PLACEHOLDER_METRICS, renderMetrics(detektion.metrics))
.replace(PLACEHOLDER_COMPLEXITY_REPORT, renderComplexity(getComplexityMetrics(detektion)))
.replace(PLACEHOLDER_FINDINGS, renderFindings(detektion.findings))
private fun renderVersion(): String = whichDetekt() ?: "unknown"
private fun renderDate(): String {
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val now = OffsetDateTime.now(ZoneOffset.UTC).format(formatter) + " UTC"
return now
}
private fun renderMetrics(metrics: Collection<ProjectMetric>) = createHTML().div {
ul {
metrics.forEach {
li { text("%,d ${it.type}".format(Locale.US, it.value)) }
}
}
}
private fun renderComplexity(complexityReport: List<String>) = createHTML().div {
ul {
complexityReport.forEach {
li { text(it.trim()) }
}
}
}
private fun renderFindings(findings: Map<String, List<Finding>>) = createHTML().div {
val total = findings.values
.asSequence()
.map { it.size }
.fold(0) { a, b -> a + b }
text("Total: %,d".format(Locale.US, total))
findings
.filter { it.value.isNotEmpty() }
.toList()
.sortedBy { (group, _) -> group }
.forEach { (group, groupFindings) ->
renderGroup(group, groupFindings)
}
}
private fun FlowContent.renderGroup(group: String, findings: List<Finding>) {
h3 { text("$group: %,d".format(Locale.US, findings.size)) }
findings
.groupBy { it.id }
.toList()
.sortedBy { (rule, _) -> rule }
.forEach { (rule, ruleFindings) ->
renderRule(rule, ruleFindings)
}
}
private fun FlowContent.renderRule(rule: String, findings: List<Finding>) {
details {
id = rule
open = true
summary("rule-container") {
span("rule") { text("$rule: %,d ".format(Locale.US, findings.size)) }
span("description") { text(findings.first().issue.description) }
}
ul {
findings
.sortedWith(compareBy({ it.file }, { it.location.source.line }, { it.location.source.column }))
.forEach {
li {
renderFinding(it)
}
}
}
}
}
private fun FlowContent.renderFinding(finding: Finding) {
val filePath = finding.location.filePath.relativePath ?: finding.location.filePath.absolutePath
span("location") {
text("${filePath.toUnifiedString()}:${finding.location.source.line}:${finding.location.source.column}")
}
if (finding.message.isNotEmpty()) {
span("message") { text(finding.message) }
}
val psiFile = finding.entity.ktElement?.containingFile
if (psiFile != null) {
val lineSequence = psiFile.text.splitToSequence('\n')
snippetCode(finding.id, lineSequence, finding.startPosition, finding.charPosition.length())
}
}
private fun getComplexityMetrics(detektion: Detektion): List<String> {
return ComplexityReportGenerator.create(detektion).generate().orEmpty()
}
}
@HtmlTagMarker
private fun FlowOrInteractiveContent.summary(
classes: String,
block: SUMMARY.() -> Unit = {}
): Unit = SUMMARY(attributesMapOf("class", classes), consumer).visit(block)
private class SUMMARY(
initialAttributes: Map<String, String>,
override val consumer: TagConsumer<*>
) : HTMLTag("summary", consumer, initialAttributes, null, false, false),
CommonAttributeGroupFacadeFlowInteractiveContent
private fun TextLocation.length(): Int = end - start
|
apache-2.0
|
da74221fefb73c043b27b36a095448d7
| 34.733728 | 120 | 0.643318 | 4.446981 | false | false | false | false |
michaelgallacher/intellij-community
|
python/python-terminal/src/com/jetbrains/python/sdk/PyVirtualEnvTerminalCustomizer.kt
|
3
|
2742
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.SystemInfo
import com.jetbrains.python.run.PyVirtualEnvReader
import com.jetbrains.python.run.findActivateScript
import org.jetbrains.plugins.terminal.LocalTerminalCustomizer
import java.io.File
/**
* @author traff
*/
class PyVirtualEnvTerminalCustomizer : LocalTerminalCustomizer() {
override fun customizeCommandAndEnvironment(project: Project,
command: Array<out String>,
envs: MutableMap<String, String>): Array<out String> {
val sdk: Sdk? = findSdk(project)
if (sdk != null && PythonSdkType.isVirtualEnv(sdk)) {
// in case of virtualenv sdk on unix we activate virtualenv
val path = sdk.homePath
if (path != null) {
val shellPath = command[0]
val shellName = File(shellPath).name
if (shellName == "bash" || shellName == "sh") {
//for bash and sh we pass activate script to jediterm shell integration (see jediterm-sh.in) to source it there
findActivateScript(path, shellPath)?.let { activate -> envs.put("JEDITERM_SOURCE", activate) }
}
else {
//for other shells we read envs from activate script by the default shell and pass them to the process
val reader = PyVirtualEnvReader(path)
reader.activate?.let { envs.putAll(reader.readShellEnv()) }
}
}
}
// for some reason virtualenv isn't activated in the rcfile for the login shell, so we make it non-login
return command.filter { arg -> arg != "--login" && arg != "-l"}.toTypedArray()
}
private fun findSdk(project: Project): Sdk? {
for (m in ModuleManager.getInstance(project).modules) {
val sdk: Sdk? = PythonSdkType.findPythonSdk(m)
if (sdk != null && !PythonSdkType.isRemote(sdk)) {
return sdk
}
}
return null
}
override fun getDefaultFolder(): String? {
return null
}
}
|
apache-2.0
|
107f3ed8e021b1348f684c3c74a4734a
| 32.439024 | 121 | 0.672867 | 4.31811 | false | false | false | false |
nickthecoder/paratask
|
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/MountTool.kt
|
1
|
8016
|
/*
ParaTask Copyright (C) 2017 Nick Robinson
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 uk.co.nickthecoder.paratask.tools.places
import javafx.application.Platform
import javafx.geometry.Side
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.input.TransferMode
import uk.co.nickthecoder.paratask.ParaTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.TaskParser
import uk.co.nickthecoder.paratask.ToolBarTool
import uk.co.nickthecoder.paratask.misc.FileOperations
import uk.co.nickthecoder.paratask.parameters.*
import uk.co.nickthecoder.paratask.project.MountPointButton
import uk.co.nickthecoder.paratask.project.ToolBarToolConnector
import uk.co.nickthecoder.paratask.project.ToolPane
import uk.co.nickthecoder.paratask.table.*
import uk.co.nickthecoder.paratask.table.filter.RowFilter
import uk.co.nickthecoder.paratask.table.filter.SingleRowFilter
import uk.co.nickthecoder.paratask.util.Resource
import uk.co.nickthecoder.paratask.util.process.BufferedSink
import uk.co.nickthecoder.paratask.util.process.Exec
import uk.co.nickthecoder.paratask.util.process.OSCommand
import java.io.File
import java.util.regex.Pattern
class MountTool : ListTableTool<MountTool.MountPoint>(), SingleRowFilter<MountTool.MountPoint>, ToolBarTool {
val toolBarSideP = ChoiceParameter<Side?>("toolbar", value = null, required = false)
.nullableEnumChoices(mixCase = true, nullLabel = "None")
override var toolBarSide by toolBarSideP
val labelOptionP = ChoiceParameter("buttonText", value = MountPointButton.LabelOption.DIRECTORY_NAME)
.enumChoices(mixCase = true)
val excludeFSTypesP = MultipleParameter("excludeFSTypes", value = listOf("tmpfs", "devtmpfs"), isBoxed = true) {
StringParameter("excludeFSType")
}
val excludeMountPointsP = MultipleParameter("excludeMountPoints", isBoxed = true) {
FileParameter("excludeMountPoint", mustExist = null, expectFile = null)
}
override val taskD = TaskDescription("mount", description = "Lists all mounted filesystems")
.addParameters(toolBarSideP, labelOptionP, excludeFSTypesP, excludeMountPointsP)
private val exampleRow = MountPoint(File(""), "", "", false, 0, 0, 0)
override val rowFilter = RowFilter(this, columns, exampleRow)
override var toolBarConnector: ToolBarToolConnector? = null
init {
labelOptionP.hidden = true
toolBarSideP.listen {
labelOptionP.hidden = toolBarSideP.value == null
}
columns.add(Column<MountPoint, ImageView>("icon", label = "", getter = { ImageView(it.icon) }))
columns.add(BooleanColumn<MountPoint>("mounted", label = "Mounted?", getter = { it.isMounted }))
columns.add(Column<MountPoint, String>("label", getter = { it.label }))
columns.add(Column<MountPoint, File>("path", getter = { it.file!! }))
columns.add(Column<MountPoint, String>("type", getter = { it.fsType }))
columns.add(SizeColumn<MountPoint>("size", getter = { it.size }))
columns.add(SizeColumn<MountPoint>("used", getter = { it.used }))
columns.add(SizeColumn<MountPoint>("available", getter = { it.available }))
}
override fun run() {
val mounted = Lister(false).list()
val mountedFiles = mounted.map { it.file }
val maybeMounted = Lister(true).list()
val tmpList = mutableListOf<MountPoint>()
tmpList.addAll(mounted)
tmpList.addAll(maybeMounted.filter { !mountedFiles.contains(it.file) })
list.clear()
list.addAll(tmpList.filter { accept(it) })
list.sortBy { it.fsType }
if (showingToolbar()) {
Platform.runLater {
updateToolbar(list.map { mountPoint -> MountPointButton(toolBarConnector!!.projectWindow, mountPoint, labelOptionP.value!!) })
}
}
}
fun accept(mountPoint: MountPoint): Boolean {
if (excludeFSTypesP.value.contains(mountPoint.fsType)) {
return false
}
if (excludeMountPointsP.value.contains(mountPoint.file)) {
return false
}
return true
}
override fun attached(toolPane: ToolPane) {
super.attached(toolPane)
if (toolBarConnector == null) {
toolBarConnector = ToolBarToolConnector(toolPane.halfTab.projectTab.projectTabs.projectWindow, this, false)
}
}
override fun createTableResults(): TableResults<MountPoint> {
val tableResults = super.createTableResults()
tableResults.dropHelper = object : TableDropFilesHelper<MountPoint>() {
override fun acceptDropOnNonRow() = emptyArray<TransferMode>()
override fun acceptDropOnRow(row: MountPoint) = if (row.isDirectory()) TransferMode.ANY else null
override fun droppedOnRow(row: MountPoint, content: List<File>, transferMode: TransferMode) {
if (row.isDirectory()) {
FileOperations.instance.fileOperation(content, row.file!!, transferMode)
}
}
override fun droppedOnNonRow(content: List<File>, transferMode: TransferMode) {}
}
return tableResults
}
class Lister(val useFstab: Boolean) {
val list = mutableListOf<MountPoint>()
val columnPositions = Array(7) { Pair(0, 0) }
fun list(): List<MountPoint> {
val command = OSCommand("findmnt", "--bytes", "-P", "--df", "--evaluate")
if (useFstab) {
command.addArgument("--fstab")
} else {
command.addArgument("--mtab")
}
val exec = Exec(command)
exec.outSink = BufferedSink { line ->
processLine(line)
}
exec.start().waitFor()
return list
}
val linePattern = Pattern.compile("""SOURCE="(.*)" FSTYPE="(.*)" SIZE="(.*)" USED="(.*)" AVAIL="(.*)" USE%="(.*)%" TARGET="(.*)"""")
fun processLine(line: String) {
val matcher = linePattern.matcher(line)
if (matcher.matches()) {
val target = matcher.group(7)
if (target.startsWith('/')) { // Exclude swap
list.add(MountPoint(
directory = File(target),
label = matcher.group(1),
fsType = matcher.group(2),
isMounted = !useFstab,
size = parseSize(matcher.group(3)),
used = parseSize(matcher.group(4)),
available = parseSize(matcher.group(5))))
}
}
}
fun parseSize(str: String): Long {
try {
return str.toLong()
} catch (e: Exception) {
}
return 0
}
}
class MountPoint(
val directory: File,
label: String,
val fsType: String,
val isMounted: Boolean,
val size: Long,
val used: Long,
val available: Long)
: Place(Resource(directory), label) {
val icon: Image? = ParaTask.imageResource("filetypes/${if (isMounted) "mounted" else "directory"}.png")
}
}
fun main(args: Array<String>) {
TaskParser(MountTool()).go(args)
}
|
gpl-3.0
|
ff1514c8748155229bfb631ab98162c6
| 35.940092 | 142 | 0.635479 | 4.354155 | false | false | false | false |
SeunAdelekan/Kanary
|
src/main/com/iyanuadelekan/kanary/handlers/AppHandler.kt
|
1
|
6274
|
package com.iyanuadelekan.kanary.handlers
import com.iyanuadelekan.kanary.app.KanaryApp
import com.iyanuadelekan.kanary.constants.HttpConstants
import com.iyanuadelekan.kanary.core.Route
import com.iyanuadelekan.kanary.helpers.http.response.send
import com.iyanuadelekan.kanary.helpers.http.response.withStatus
import com.iyanuadelekan.kanary.utils.RequestUtils
import org.eclipse.jetty.server.Request
import org.eclipse.jetty.server.handler.AbstractHandler
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* @author Iyanu Adelekan on 25/05/2017.
*/
/**
* @property app Instance of [KanaryApp]
*/
class AppHandler(val app: KanaryApp): AbstractHandler() {
private val supportedMethods = arrayOf(HttpConstants.GET.name, HttpConstants.POST.name,
HttpConstants.PUT.name, HttpConstants.DELETE.name, HttpConstants.PATCH.name, HttpConstants.OPTIONS.name)
/**
* Base handler for all incoming HTTP requests
* @param target Target resource
* @param baseRequest Mutable HTTP request instance
* @param request Immutable HTTP request instance
* @param response Instance used to handle server responses
*/
override fun handle(
target: String?,
baseRequest: Request?,
request: HttpServletRequest?,
response: HttpServletResponse?
) {
runMiddleware(baseRequest, request, response)
if (request != null) {
if(isMethodSupported(request.method)) {
val route: Route? = resolveTargetRoute(request.method, "$target")
if (route != null) {
val action = route.action
executeBeforeAction(route, request, response)
if(baseRequest != null && response != null) {
action.invoke(baseRequest, request, response)
}
executeAfterAction(route, request, response)
} else {
response?. withStatus(404)?. send("Method not found.")
}
} else {
response?.addHeader("Allow", "${HttpConstants.OPTIONS.name}, ${HttpConstants.GET.name}, " +
"${HttpConstants.POST.name}, ${HttpConstants.PUT.name}, ${HttpConstants.DELETE.name}, " +
HttpConstants.PATCH.name)
response?. withStatus(405)?. send("Method not allowed.")
}
}
}
/**
* Tests if a request method is supported
* @param method HTTP method to be tested
* @return true if supported and false otherwise
*/
private fun isMethodSupported(method: String): Boolean {
return supportedMethods.filter({ it == method }).isNotEmpty()
}
/**
* Method used for route resolution
* @param method HTTP method of the request
* @param target Target resource
* @return route required to handle HTTP request
*/
private fun resolveTargetRoute(method: String?, target: String?): Route? {
var route: Route? = null
var matchedRoutes: List<Route>
val formattedTarget: String? = RequestUtils().formatTarget(target)
app.routerList.forEach { router -> run {
when(method) {
HttpConstants.GET.name -> {
matchedRoutes = router.getRouteList.filter { it.path == formattedTarget }
if(matchedRoutes.isNotEmpty()) {
route = matchedRoutes[0]
}
}
HttpConstants.POST.name -> {
matchedRoutes = router.postRouteList.filter { it.path == formattedTarget }
if(matchedRoutes.isNotEmpty()) {
route = matchedRoutes[0]
}
}
HttpConstants.PUT.name -> {
matchedRoutes = router.putRouteList.filter { it.path == formattedTarget }
if(matchedRoutes.isNotEmpty()) {
route = matchedRoutes[0]
}
}
HttpConstants.DELETE.name -> {
matchedRoutes = router.deleteRouteList.filter { it.path == formattedTarget }
if(matchedRoutes.isNotEmpty()) {
route = matchedRoutes[0]
}
}
HttpConstants.PATCH.name -> {
matchedRoutes = router.patchRouteList.filter { it.path == formattedTarget }
if(matchedRoutes.isNotEmpty()) {
route = matchedRoutes[0]
}
}
HttpConstants.OPTIONS.name -> {
matchedRoutes = router.optionsRouteList.filter { it.path == formattedTarget }
if(matchedRoutes.isNotEmpty()) {
route = matchedRoutes[0]
}
}
}
} }
return route
}
/**
* Calls beforeAction life cycle callback of route's Associated controller
* @param route Instance of [Route]
* @param request Instance of [HttpServletRequest]
* @param response Instance of [HttpServletResponse]
*/
private fun executeBeforeAction(route: Route, request: HttpServletRequest, response: HttpServletResponse?) {
route.controller?.beforeAction(request, response)
}
/**
* Calls afterAction life cycle callback of route's Associated controller
* @param route Instance of [Route]
* @param request Instance of [HttpServletRequest]
* @param response Instance of [HttpServletResponse]
*/
private fun executeAfterAction(route: Route, request: HttpServletRequest, response: HttpServletResponse?) {
route.controller?.afterAction(request, response)
}
/**
* This executes all the middleware that have been queued
* @param request Instance of [HttpServletRequest]
* @param response Instance of [HttpServletResponse]
*/
private fun runMiddleware(baseReq: Request?, request: HttpServletRequest?, response: HttpServletResponse?) {
app.middlewareList.forEach { it.invoke(baseReq, request, response)}
}
}
|
apache-2.0
|
9b168d22698e85562fbaa9cc34c4eefa
| 38.465409 | 116 | 0.594836 | 5.104963 | false | false | false | false |
wiltonlazary/kotlin-native
|
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/ir/interop/cenum/CEnumCompanionGenerator.kt
|
1
|
5060
|
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.ir.interop.cenum
import org.jetbrains.kotlin.backend.konan.descriptors.getArgumentValueOrNull
import org.jetbrains.kotlin.backend.konan.ir.interop.DescriptorToIrTranslationMixin
import org.jetbrains.kotlin.backend.konan.ir.interop.irInstanceInitializer
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.ir.builders.irBlockBody
import org.jetbrains.kotlin.ir.builders.irReturn
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns
import org.jetbrains.kotlin.ir.expressions.IrBody
import org.jetbrains.kotlin.ir.expressions.impl.IrDelegatingConstructorCallImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrGetEnumValueImpl
import org.jetbrains.kotlin.ir.symbols.IrEnumEntrySymbol
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi2ir.generators.GeneratorContext
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
private val cEnumEntryAliasAnnonation = FqName("kotlinx.cinterop.internal.CEnumEntryAlias")
internal class CEnumCompanionGenerator(
context: GeneratorContext,
private val cEnumByValueFunctionGenerator: CEnumByValueFunctionGenerator
) : DescriptorToIrTranslationMixin {
override val irBuiltIns: IrBuiltIns = context.irBuiltIns
override val symbolTable: SymbolTable = context.symbolTable
override val typeTranslator: TypeTranslator = context.typeTranslator
// Depends on already generated `.values()` irFunction.
fun generate(enumClass: IrClass): IrClass =
createClass(enumClass.descriptor.companionObjectDescriptor!!) { companionIrClass ->
companionIrClass.superTypes += irBuiltIns.anyType
companionIrClass.addMember(createCompanionConstructor(companionIrClass.descriptor))
val valuesFunction = enumClass.functions.single { it.name.identifier == "values" }.symbol
val byValueIrFunction = cEnumByValueFunctionGenerator
.generateByValueFunction(companionIrClass, valuesFunction)
companionIrClass.addMember(byValueIrFunction)
findEntryAliases(companionIrClass.descriptor)
.map { declareEntryAliasProperty(it, enumClass) }
.forEach(companionIrClass::addMember)
}
private fun createCompanionConstructor(companionObjectDescriptor: ClassDescriptor): IrConstructor {
val anyPrimaryConstructor = companionObjectDescriptor.builtIns.any.unsubstitutedPrimaryConstructor!!
val superConstructorSymbol = symbolTable.referenceConstructor(anyPrimaryConstructor)
return createConstructor(companionObjectDescriptor.unsubstitutedPrimaryConstructor!!).also {
it.body = irBuilder(irBuiltIns, it.symbol, SYNTHETIC_OFFSET, SYNTHETIC_OFFSET).irBlockBody {
+IrDelegatingConstructorCallImpl(
startOffset, endOffset, context.irBuiltIns.unitType,
superConstructorSymbol
)
+irInstanceInitializer(symbolTable.referenceClass(companionObjectDescriptor))
}
}
}
/**
* Returns all properties in companion object that represent aliases to
* enum entries.
*/
private fun findEntryAliases(companionDescriptor: ClassDescriptor) =
companionDescriptor.defaultType.memberScope.getContributedDescriptors()
.filterIsInstance<PropertyDescriptor>()
.filter { it.annotations.hasAnnotation(cEnumEntryAliasAnnonation) }
private fun fundCorrespondingEnumEntrySymbol(aliasDescriptor: PropertyDescriptor, irClass: IrClass): IrEnumEntrySymbol {
val enumEntryName = aliasDescriptor.annotations
.findAnnotation(cEnumEntryAliasAnnonation)!!
.getArgumentValueOrNull<String>("entryName")
return irClass.declarations.filterIsInstance<IrEnumEntry>()
.single { it.name.identifier == enumEntryName }.symbol
}
private fun generateAliasGetterBody(getter: IrSimpleFunction, entrySymbol: IrEnumEntrySymbol): IrBody =
irBuilder(irBuiltIns, getter.symbol, SYNTHETIC_OFFSET, SYNTHETIC_OFFSET).irBlockBody {
+irReturn(
IrGetEnumValueImpl(startOffset, endOffset, entrySymbol.owner.parentAsClass.defaultType, entrySymbol)
)
}
private fun declareEntryAliasProperty(propertyDescriptor: PropertyDescriptor, enumClass: IrClass): IrProperty {
val entrySymbol = fundCorrespondingEnumEntrySymbol(propertyDescriptor, enumClass)
return createProperty(propertyDescriptor).also {
it.getter!!.body = generateAliasGetterBody(it.getter!!, entrySymbol)
}
}
}
|
apache-2.0
|
0d9683ff90f907a75c872deff010d7b0
| 52.840426 | 124 | 0.738933 | 5.331928 | false | false | false | false |
goodwinnk/intellij-community
|
java/java-impl/src/com/intellij/codeInsight/intention/impl/JavaElementActionsFactory.kt
|
2
|
5311
|
// 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.codeInsight.intention.impl
import com.intellij.codeInsight.daemon.impl.quickfix.ModifierFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.java.actions.*
import com.intellij.lang.jvm.*
import com.intellij.lang.jvm.actions.*
import com.intellij.lang.jvm.types.JvmType
import com.intellij.openapi.components.ServiceManager
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil
import java.util.*
class JavaElementActionsFactory(private val renderer: JavaElementRenderer) : JvmElementActionsFactory() {
override fun createChangeModifierActions(target: JvmModifiersOwner, request: MemberRequest.Modifier): List<IntentionAction> = with(
request) {
val declaration = target as PsiModifierListOwner
if (declaration.language != JavaLanguage.INSTANCE) return@with emptyList()
listOf(ModifierFix(declaration.modifierList, renderer.render(modifier), shouldPresent, false))
}
override fun createChangeModifierActions(target: JvmModifiersOwner, request: ChangeModifierRequest): List<IntentionAction> {
val declaration = target as PsiModifierListOwner
if (declaration.language != JavaLanguage.INSTANCE) return emptyList()
val fix = object : ModifierFix(declaration.modifierList, renderer.render(request.modifier), request.shouldBePresent(), false) {
override fun isAvailable(): Boolean = request.isValid && super.isAvailable()
}
return listOf(fix)
}
override fun createAddAnnotationActions(target: JvmModifiersOwner, request: AnnotationRequest): List<IntentionAction> {
val declaration = target as? PsiModifierListOwner ?: return emptyList()
if (declaration.language != JavaLanguage.INSTANCE) return emptyList()
return listOf(CreateAnnotationAction(declaration, request))
}
override fun createAddFieldActions(targetClass: JvmClass, request: CreateFieldRequest): List<IntentionAction> {
val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList()
val constantRequested = request.isConstant || javaClass.isInterface || request.modifiers.containsAll(constantModifiers)
val result = ArrayList<IntentionAction>()
if (constantRequested || request.fieldName.toUpperCase(Locale.ENGLISH) == request.fieldName) {
result += CreateConstantAction(javaClass, request)
}
if (!constantRequested) {
result += CreateFieldAction(javaClass, request)
}
if (canCreateEnumConstant(javaClass, request)) {
result += CreateEnumConstantAction(javaClass, request)
}
return result
}
override fun createAddMethodActions(targetClass: JvmClass, request: CreateMethodRequest): List<IntentionAction> {
val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList()
val requestedModifiers = request.modifiers
val staticMethodRequested = JvmModifier.STATIC in requestedModifiers
if (staticMethodRequested) {
// static method in interfaces are allowed starting with Java 8
if (javaClass.isInterface && !PsiUtil.isLanguageLevel8OrHigher(javaClass)) return emptyList()
// static methods in inner classes are disallowed JLS §8.1.3
if (javaClass.containingClass != null && !javaClass.hasModifierProperty(PsiModifier.STATIC)) return emptyList()
}
val result = ArrayList<IntentionAction>()
result += CreateMethodAction(javaClass, request, false)
if (!staticMethodRequested && javaClass.hasModifierProperty(PsiModifier.ABSTRACT) && !javaClass.isInterface) {
result += CreateMethodAction(javaClass, request, true)
}
if (!javaClass.isInterface) {
result += CreatePropertyAction(javaClass, request)
result += CreateGetterWithFieldAction(javaClass, request)
result += CreateSetterWithFieldAction(javaClass, request)
}
return result
}
override fun createAddConstructorActions(targetClass: JvmClass, request: CreateConstructorRequest): List<IntentionAction> {
val javaClass = targetClass.toJavaClassOrNull() ?: return emptyList()
return listOf(CreateConstructorAction(javaClass, request))
}
override fun createChangeParametersActions(target: JvmMethod, request: ChangeParametersRequest): List<IntentionAction> {
val psiMethod = target as? PsiMethod ?: return emptyList()
if (psiMethod.language != JavaLanguage.INSTANCE) return emptyList()
if (request.expectedParameters.any { it.expectedTypes.isEmpty() || it.semanticNames.isEmpty() }) return emptyList()
return listOf(ChangeMethodParameters(psiMethod, request))
}
}
class JavaElementRenderer {
companion object {
@JvmStatic
fun getInstance(): JavaElementRenderer {
return ServiceManager.getService(JavaElementRenderer::class.java)
}
}
fun render(visibilityModifiers: List<JvmModifier>): String =
visibilityModifiers.joinToString(" ") { render(it) }
fun render(jvmType: JvmType): String =
(jvmType as PsiType).canonicalText
fun render(jvmAnnotation: JvmAnnotation): String =
"@" + (jvmAnnotation as PsiAnnotation).qualifiedName!!
@PsiModifier.ModifierConstant
fun render(modifier: JvmModifier): String = modifier.toPsiModifier()
}
|
apache-2.0
|
1ded8ccbe89a332d2f7d747afa92b3dd
| 43.621849 | 140 | 0.763842 | 5.009434 | false | false | false | false |
deadpixelsociety/twodee
|
src/main/kotlin/com/thedeadpixelsociety/twodee/input/namespace.kt
|
1
|
566
|
package com.thedeadpixelsociety.twodee.input
import com.badlogic.gdx.Input
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.math.Vector3
private val v2 = Vector2()
private val v3 = Vector3()
/**
* Helper function to get the current mouse position in a 2D vector.
*/
fun <T : Input> T.mousePosition2() = v2.set(x.toFloat(), y.toFloat())
/**
* Helper function to get the current mouse position in a 3D vector.
* @param z The z value to use. Defaults to zero.
*/
fun <T : Input> T.mousePosition3(z: Float = 0f) = v3.set(x.toFloat(), y.toFloat(), z)
|
mit
|
0b4b779aacaea44c7ced2ed52aca787c
| 28.842105 | 85 | 0.713781 | 3.127072 | false | false | false | false |
nhaarman/AsyncAwait-Android
|
asyncawait-android/src/main/kotlin/com/nhaarman/async/Task.kt
|
1
|
3798
|
package com.nhaarman.async
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
/**
* A class that represents a cancelable task that can be awaited on.
* When the task completes normally, an instance of type [T] is passed
* as the result to the 'await' call.
*/
class Task<T>(
private val cancelable: Cancelable = CancelableImpl()
) : Cancelable by cancelable {
/** The Future that was created to start the coroutine. */
private var runningTask: Future<*>? = null
private @Volatile var onComplete: ((T) -> Unit)? = null
private @Volatile var onError: ((Throwable) -> Unit)? = null
private @Volatile var completedValue: CompletedValue<T>? = null
private @Volatile var erroredValue: Throwable? = null
/** The task that we're currently awaiting on. */
private var current: Cancelable? = null
internal fun awaitingOn(cancelable: Cancelable) {
if (current != null) error("Already waiting on $current.")
current = cancelable
}
internal fun awaitDone() {
current = null
}
private val latch = CountDownLatch(1)
internal fun whenComplete(onComplete: (T) -> Unit, onError: (Throwable) -> Unit) {
this.onComplete = onComplete
this.onError = onError
completedValue?.let { onComplete(it.value) }
erroredValue?.let { onError(it) }
}
internal fun startedWith(future: Future<*>) {
runningTask = future
}
internal fun complete(value: T) {
onComplete?.invoke(value)
completedValue = CompletedValue(value)
latch.countDown()
}
internal fun handleError(t: Throwable): Boolean {
val result = onError?.invoke(t) != null
erroredValue = t
latch.countDown()
return result
}
override fun cancel() {
cancelable.cancel()
current?.cancel()
current = null
runningTask?.cancel(true)
runningTask = null
onComplete = null
onError = null
}
/**
* Blocks the current thread until this task has completed
* either successfully or unsuccessfully.
*
* @throws IllegalStateException if the task was already canceled.
*/
fun wait(): T {
if (isCanceled()) throw IllegalStateException("Task is canceled.")
latch.await()
completedValue?.let { return it.value }
erroredValue?.let { throw it }
error("Neither completed nor errored value set.")
}
/**
* Blocks the current thread until this task has completed
* either successfully or unsuccessfully, or a timeout has passed.
*
* @param timeout the maximum time to wait
* @param unit the time unit of [timeout]
*
* @throws TimeoutException if the timeout has passed before the task was completed.
* @throws IllegalStateException if the task was already canceled.
*/
fun wait(timeout: Long, unit: TimeUnit): T {
if (isCanceled()) throw IllegalStateException("Task is canceled.")
latch.await(timeout, unit)
if (latch.count > 0) throw TimeoutException()
completedValue?.let { return it.value }
erroredValue?.let { throw it }
error("Neither completed nor errored value set.")
}
companion object {
/**
* Creates a [Task] that is completed with value [t].
*/
@JvmStatic
fun <T> completed(t: T) = Task<T>().apply { complete(t) }
/**
* Creates a [Task] that has errored with [t].
*/
@JvmStatic
fun <T> errored(t: Throwable) = Task<T>().apply { handleError(t) }
}
private class CompletedValue<T>(val value: T)
}
|
apache-2.0
|
555c4e54ceb2db316b54ab622325bb80
| 27.343284 | 88 | 0.628752 | 4.575904 | false | false | false | false |
Ztiany/Repository
|
Kotlin/Kotlin-coroutinelite/src/main/java/com/bennyhuo/coroutines/sample/Sample.kt
|
2
|
1913
|
package com.bennyhuo.coroutines.sample
import com.bennyhuo.coroutines.lite.delay
import com.bennyhuo.coroutines.lite.launch
import com.bennyhuo.coroutines.lite.runBlocking
import com.bennyhuo.coroutines.utils.log
/*
BlockingQueueDispatcher->dispatch->EventTask=Function0<kotlin.Unit> 471910020////startCoroutine
BlockingQueueDispatcher->dispatch->isCompleted = false
CommonPoolDispatcher-->block = Function0<kotlin.Unit> 1418481495
sample->join->com.bennyhuo.coroutines.lite.StandaloneCoroutine@87aac27//join 1
BlockingQueueDispatcher->dispatch->isCompleted = false
23:54:00:917 [CommonPool] -1
23:54:00:918 [CommonPool] -2
23:54:00:918 [CommonPool] -3
23:54:00:918 [CommonPool] -4
AbstractCoroutine com.bennyhuo.coroutines.lite.StandaloneCoroutine@87aac27 ->resume->value = kotlin.Unit//launch 执行完毕,使用runBlocking的Coroutine重新调度runBlocking
joinSuspend continuation = kotlin.coroutines.experimental.SafeContinuation@2a0b1bff
BlockingQueueDispatcher->dispatch->EventTask=Function0<kotlin.Unit> 120398637
BlockingQueueDispatcher->dispatch->get=Function0<kotlin.Unit> 120398637/执行拦截到的方法,执行完毕后( println("sample->end")段) BlockingCoroutine 状态为完成
AbstractCoroutine join ret=kotlin.Unit //join 1 end
sample->end
AbstractCoroutine com.bennyhuo.coroutines.lite.BlockingCoroutine@119d7047 ->resume->value = kotlin.Unit
*/
fun main(args: Array<String>) = runBlocking {
val join = launch {
log(-1)
/* val result = async {
log(1)
delay(100)
log(2)
loadForResult().also {
log(3)
}
}*/
log(-2)
// delay(200)
log(-3)
// log(result.await())
log(-4)
}
println("sample->join->$join")
join.join()
println("sample->end")
}
suspend fun loadForResult(): String {
delay(1000L)
return "HelloWorld"
}
|
apache-2.0
|
dd89a6f87eb3e63f66aa638ade9bb500
| 30.896552 | 156 | 0.718226 | 3.675944 | false | false | false | false |
icapps/niddler-ui
|
client-lib/src/main/kotlin/com/icapps/niddler/lib/device/Device.kt
|
1
|
3309
|
package com.icapps.niddler.lib.device
import com.google.gson.Gson
import com.icapps.niddler.lib.utils.createGsonListType
import com.icapps.niddler.lib.utils.debug
import com.icapps.niddler.lib.utils.logger
import java.io.IOException
import java.net.ConnectException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.URI
import java.util.Objects
/**
* @author nicolaverbeeck
*/
interface Device {
companion object {
const val REQUEST_QUERY = 0x01
const val ANNOUNCEMENT_PORT = 6394
}
fun getNiddlerSessions(): List<NiddlerSession>
fun prepareConnection(suggestedLocalPort: Int, remotePort: Int): PreparedDeviceConnection
}
interface PreparedDeviceConnection {
val uri: URI
}
data class NiddlerSession(val device: Device,
val packageName: String,
val port: Int,
val pid: Int,
val protocolVersion: Int) {
override fun equals(other: Any?): Boolean {
if (other !is NiddlerSession)
return false
return packageName == other.packageName
&& port == other.port
&& pid == other.pid
&& protocolVersion == other.protocolVersion
&& device == other.device
}
override fun hashCode(): Int {
return Objects.hash(packageName, port, pid, protocolVersion, device)
}
}
private data class NiddlerAnnouncementMessage(
val packageName: String,
val port: Int,
val pid: Int,
val protocol: Int
)
class DirectPreparedConnection(ip: String, port: Int) : PreparedDeviceConnection {
override val uri: URI
init {
val tempUri = URI.create("sis://$ip")
val usePort = if (tempUri.port == -1) port else tempUri.port
uri = URI.create("ws://${tempUri.host}:$usePort")
}
}
abstract class BaseDevice : Device {
private companion object {
private val log = logger<BaseDevice>()
private const val MAX_TIMEOUT = 300
private const val MAX_READ_TIMEOUT = 1000
}
private val gson = Gson()
protected fun readAnnouncement(connectPort: Int): List<NiddlerSession> {
Socket().use { socket ->
try {
socket.connect(InetSocketAddress(InetAddress.getLoopbackAddress(), connectPort), MAX_TIMEOUT)
socket.soTimeout = MAX_READ_TIMEOUT
} catch (e: ConnectException) {
return emptyList()
}
socket.getOutputStream().also { stream ->
stream.write(Device.REQUEST_QUERY)
stream.flush()
}
return try {
val line = socket.getInputStream().bufferedReader().readLine()
line?.let {
val fromJson = gson.fromJson<List<NiddlerAnnouncementMessage>>(line,
createGsonListType<NiddlerAnnouncementMessage>())
fromJson.map { NiddlerSession(this, it.packageName, it.port, it.pid, it.protocol) }
} ?: emptyList()
} catch (e: IOException) {
log.debug("Failed to read announcement line", e)
emptyList()
}
}
}
}
|
apache-2.0
|
408dd8abeed72ef819f0baffd405fe38
| 28.292035 | 109 | 0.600181 | 4.660563 | false | false | false | false |
dtarnawczyk/modernlrs
|
src/main/org/lrs/kmodernlrs/domain/Attachment.kt
|
1
|
414
|
package org.lrs.kmodernlrs.domain
import java.io.Serializable
data class Attachment(
var usageType: String? = "",
var display: Map<String, String> = mapOf(),
var description: Map<String, String> = mapOf(),
var contentType: String? = "",
var length: Int? = null,
var sha2: String? = "",
var fileUrl: String? = "") : Serializable {
companion object {
private val serialVersionUID:Long = 1
}
}
|
apache-2.0
|
385aebc99f21dccb354e5e0878909812
| 22.055556 | 49 | 0.669082 | 3.421488 | false | false | false | false |
openstreetview/android
|
app/src/main/java/com/telenav/osv/data/collector/obddata/OBDConstants.kt
|
1
|
3967
|
package com.telenav.osv.data.collector.obddata
/**
* Created by ovidiuc2 on 11/3/16.
*/
object OBDConstants {
/**
* ELM327 commands sent to the obd2
* the final 1 is because of this: it will wait till 1 answer comes in, and it will directly send it back
*/
/**
* command for speed
*/
const val CMD_SPEED = "010D1"
/**
* command for RPM - Revolutions Per Minute
*/
const val CMD_RPM = "010C1"
/**
* command for the fuel tank level input(represented as a percentage)
*/
const val CMD_FUEL_TANK_LEVEL_INPUT = "012F1"
/**
* command for the fuel type
*/
const val CMD_FUEL_TYPE = "01511"
/**
* command for consumption rate(measured in l/h)
*/
const val CMD_FUEL_CONSUMPTION_RATE = "015E1"
/**
* engine reference torque(measured in Nm)
*/
const val CMD_ENGINE_TORQUE = "01631"
/**
* vehicle identification number
*/
const val CMD_VIN = "0902"
/**
* Prefix of the response that comes from speed sensor
*/
const val PREFIX_RESPONSE_SPEED = "410D"
/**
* Prefix of the response that comes from rpm sensor
*/
const val PREFIX_RESPONSE_RPM = "410C"
/**
* Prefix of the response that comes from tank level sensor
*/
const val PREFIX_RESPONSE_TANK_LEVEL = "412F"
/**
* Prefix of the response that comes from fuel type sensor
*/
const val PREFIX_RESPONSE_FUEL_TYPE = "4151"
/**
* Prefix of the response that comes from fuel consumption sensor
*/
const val PREFIX_RESPONSE_FUEL_CONSUMPTION = "415E"
const val PREFIX_RESPONSE_0100 = "4100"
const val PREFIX_RESPONSE_0120 = "4120"
const val PREFIX_RESPONSE_0140 = "4140"
const val PREFIX_RESPONSE_0160 = "4160"
const val OPTIONAL_VIN_INFO = "014"
/**
* message returned by OBD when computation is not completed yet
*/
const val SEARCHING = "SEARCHING"
const val CAN_ERROR = "CAN ERROR"
const val STOPPED = "STOPPED"
/**
* Prefix of the response that comes from vehicle identification number requests
*/
const val PREFIX_RESPONSE_VIN = "0:4902"
/**
* Prefix of the response that comes from torque sensor
*/
const val PREFIX_RESPONSE_TORQUE_VALUE = "4163"
const val PREFIX_RESPONSE_MODE1_PID = "41"
const val PREFIX_RESPONSE_MODE9_PID = "49"
/**
* commands that retrieve sensor availability
*/
const val CMD_0100 = "0100"
const val CMD_0120 = "0120"
const val CMD_0140 = "0140"
const val CMD_0160 = "0160"
const val CMD_0180 = "0180"
const val CMD_0900 = "09001"
const val WIFI_DESTINATION_ADDRESS = "192.168.0.10"
const val DEST_PORT = 35000
const val RPM_INDEX = 11
const val SPEED_INDEX = 12
const val FUEL_TANK_LEVEL_INPUT_INDEX = 14
const val FUEL_TYPE_INDEX = 16
const val FUEL_CONSUMPTION_INDEX = 29
const val ENGINE_TORQUE_INDEX = 2
const val VIN_INDEX = 1
val FUEL_TYPES = arrayOf(
"Not available", //0
"Gasoline", //1
"Methanol", //2
"Ethanol", //3
"Diesel", //4
"LPG", //5
"CNG", //6
"Propane", //7
"Electric", //8
"Bifuel running Gasoline", //9
"Bifuel running Methanol", //10
"Bifuel running Ethanol", //11
"Bifuel running LPG", //12
"Bifuel running CNG", //13
"Bifuel running Propane", //14
"Bifuel running Electricity", //15
"Bifuel running electric and combustion engine", //16
"Hybrid gasoline", //17
"Hybrid Ethanol", //18
"Hybrid Diesel", //19
"Hybrid electric", //20
"Hybrid running electric and combustion engine", //21
"Hybrid Regenerative", //22
"Bifuel running diesel" //23
)
}
|
lgpl-3.0
|
1e50a5de17027c4934525e443555560d
| 27.546763 | 109 | 0.581548 | 3.622831 | false | false | false | false |
stripe/stripe-android
|
link/src/test/java/com/stripe/android/link/model/StripeIntentFixtures.kt
|
1
|
2544
|
package com.stripe.android.link.model
import com.stripe.android.model.parsers.PaymentIntentJsonParser
import com.stripe.android.model.parsers.SetupIntentJsonParser
import org.json.JSONObject
internal object StripeIntentFixtures {
private val PI_PARSER = PaymentIntentJsonParser()
private val SI_PARSER = SetupIntentJsonParser()
private val PI_SUCCEEDED_JSON = JSONObject(
"""
{
"id": "pi_1IRg6VCRMbs6F",
"object": "payment_intent",
"amount": 1099,
"canceled_at": null,
"cancellation_reason": null,
"capture_method": "automatic",
"client_secret": "pi_1IRg6VCRMbs6F_secret_7oH5g4v8GaCrHfsGYS6kiSnwF",
"confirmation_method": "automatic",
"created": 1614960135,
"currency": "usd",
"description": "Example PaymentIntent",
"last_payment_error": null,
"livemode": false,
"next_action": null,
"payment_method": "pm_1IJs3ZCRMbs",
"payment_method_types": ["card"],
"receipt_email": null,
"setup_future_usage": null,
"shipping": null,
"source": null,
"status": "succeeded"
}
""".trimIndent()
)
val PI_SUCCEEDED = requireNotNull(PI_PARSER.parse(PI_SUCCEEDED_JSON))
internal val SI_NEXT_ACTION_REDIRECT_JSON = JSONObject(
"""
{
"id": "seti_1EqTSZGMT9dGPIDGVzCUs6dV",
"object": "setup_intent",
"cancellation_reason": null,
"client_secret": "seti_1EqTSZGMT9dGPIDGVzCUs6dV_secret_FL9mS9ILygVyGEOSmVNqHT83rxkqy0Y",
"created": 1561677666,
"description": "a description",
"last_setup_error": null,
"livemode": false,
"next_action": {
"redirect_to_url": {
"return_url": "stripe://setup_intent_return",
"url": "https://hooks.stripe.com/redirect/authenticate/src_1EqTStGMT9dGPIDGJGPkqE6B?client_secret=src_client_secret_FL9m741mmxtHykDlRTC5aQ02"
},
"type": "redirect_to_url"
},
"payment_method": "pm_1EqTSoGMT9dGPIDG7dgafX1H",
"payment_method_types": [
"card"
],
"status": "requires_action",
"usage": "off_session"
}
""".trimIndent()
)
val SI_NEXT_ACTION_REDIRECT = requireNotNull(SI_PARSER.parse(SI_NEXT_ACTION_REDIRECT_JSON))
}
|
mit
|
c76d1f07f71ba8b32b88133a9e9d8912
| 36.411765 | 161 | 0.562893 | 3.741176 | false | false | false | false |
kkorolyov/Pancake
|
killstreek/src/main/kotlin/dev/kkorolyov/killstreek/Constants.kt
|
1
|
441
|
package dev.kkorolyov.killstreek
import dev.kkorolyov.pancake.platform.math.Vector3
import dev.kkorolyov.pancake.platform.math.Vectors
const val OBJECT_MASS = .1
const val PLAYER_MASS = 10.0
val MAX_SPEED: Vector3 = Vectors.create(50.0, 50.0, 50.0)
val OBJECT_DAMPING: Vector3 = Vectors.create(.9, .9, .9)
val PLAYER_DAMPING: Vector3 = Vectors.create(.5, .5, .5)
val BOX: Vector3 = Vectors.create(1.0, 1.0, 0.0)
val RADIUS = BOX.x / 2.0
|
bsd-3-clause
|
a175ae911c431247360c4bd9b7bec0fb
| 30.5 | 57 | 0.730159 | 2.423077 | false | false | false | false |
hannesa2/owncloud-android
|
owncloudApp/src/main/java/com/owncloud/android/presentation/ui/settings/fragments/SettingsLogsFragment.kt
|
2
|
3278
|
/**
* ownCloud Android client application
*
* @author Juan Carlos Garrote Gascón
*
* Copyright (C) 2021 ownCloud GmbH.
* <p>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.presentation.ui.settings.fragments
import android.content.Intent
import android.os.Bundle
import androidx.preference.CheckBoxPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.owncloud.android.R
import com.owncloud.android.presentation.ui.logging.LogsListActivity
import com.owncloud.android.presentation.viewmodels.settings.SettingsLogsViewModel
import org.koin.androidx.viewmodel.ext.android.viewModel
class SettingsLogsFragment : PreferenceFragmentCompat() {
// ViewModel
private val logsViewModel by viewModel<SettingsLogsViewModel>()
private var prefEnableLogging: SwitchPreferenceCompat? = null
private var prefHttpLogs: CheckBoxPreference? = null
private var prefLogsListActivity: Preference? = null
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings_logs, rootKey)
prefEnableLogging = findPreference(PREFERENCE_ENABLE_LOGGING)
prefHttpLogs = findPreference(PREFERENCE_LOG_HTTP)
prefLogsListActivity = findPreference(PREFERENCE_LOGS_LIST)
with(logsViewModel.isLoggingEnabled()) {
prefHttpLogs?.isEnabled = this
}
prefEnableLogging?.setOnPreferenceChangeListener { _: Preference?, newValue: Any ->
val value = newValue as Boolean
logsViewModel.setEnableLogging(value)
prefHttpLogs?.isEnabled = value
if (!value) {
// Disable http logs when global logs are disabled.
logsViewModel.shouldLogHttpRequests(value)
prefHttpLogs?.isChecked = false
}
true
}
prefHttpLogs?.setOnPreferenceChangeListener { _: Preference?, newValue: Any ->
logsViewModel.shouldLogHttpRequests(newValue as Boolean)
true
}
prefLogsListActivity?.let {
it.setOnPreferenceClickListener {
val intent = Intent(context, LogsListActivity::class.java)
startActivity(intent)
true
}
}
}
override fun onDestroy() {
logsViewModel.enqueueOldLogsCollectorWorker()
super.onDestroy()
}
companion object {
const val PREFERENCE_ENABLE_LOGGING = "enable_logging"
const val PREFERENCE_LOG_HTTP = "set_httpLogs"
const val PREFERENCE_LOGS_LIST = "logs_list"
}
}
|
gpl-2.0
|
4c4d7ae0db9f8568c8d7f3202a845a38
| 34.619565 | 91 | 0.702472 | 5.104361 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/ide/intentions/ConvertMethodCallToUFCSIntention.kt
|
2
|
4062
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.ide.inspections.import.AutoImportFix
import org.rust.ide.presentation.renderInsertionSafe
import org.rust.ide.utils.import.import
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.TraitImplSource
import org.rust.lang.core.resolve.ref.MethodResolveVariant
import org.rust.lang.core.types.inference
import org.rust.lang.core.types.ty.*
import org.rust.lang.core.types.type
class ConvertMethodCallToUFCSIntention : RsElementBaseIntentionAction<ConvertMethodCallToUFCSIntention.Context>() {
override fun getText() = "Convert to UFCS"
override fun getFamilyName() = text
override fun findApplicableContext(
project: Project,
editor: Editor,
element: PsiElement
): Context? {
val methodCall = element.parent as? RsMethodCall ?: return null
val function = methodCall.reference.resolve() as? RsFunction ?: return null
val methodVariants = methodCall.inference?.getResolvedMethod(methodCall).orEmpty()
if (methodVariants.isEmpty()) return null
return Context(methodCall, function, methodVariants)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val methodCall = ctx.methodCall
val function = ctx.function
val functionName = function.name ?: return
val factory = RsPsiFactory(project)
val selfType = getSelfType(function) ?: return
val receiver = methodCall.receiver
val prefix = getSelfArgumentPrefix(selfType, receiver)
val selfArgument = factory.createExpression("$prefix${receiver.text}")
val arguments = listOf(selfArgument) + methodCall.valueArgumentList.exprList
val ownerName = getOwnerName(ctx.methodVariants)
val ufcs = factory.createAssocFunctionCall(ownerName, functionName, arguments)
val parentDot = methodCall.parentDotExpr
val inserted = parentDot.replace(ufcs) as RsCallExpr
val path = (inserted.expr as? RsPathExpr)?.path ?: return
val importCtx = AutoImportFix.findApplicableContext(path)
importCtx?.candidates?.firstOrNull()?.import(inserted)
}
data class Context(
val methodCall: RsMethodCall,
val function: RsFunction,
val methodVariants: List<MethodResolveVariant>
)
}
private fun getOwnerName(methodVariants: List<MethodResolveVariant>): String {
val variant = methodVariants.minByOrNull {
if (it.source is TraitImplSource.ExplicitImpl) {
0
} else {
1
}
} ?: error("Method not resolved to any variant")
fun renderType(ty: Ty): String = ty.renderInsertionSafe(
includeTypeArguments = false,
includeLifetimeArguments = false
)
return when (val type = variant.selfTy) {
is TyAnon, is TyTraitObject -> (variant.source.value as? RsTraitItem)?.name ?: renderType(type)
else -> renderType(type)
}
}
private enum class SelfType {
Move,
Ref,
RefMut
}
private fun getSelfType(function: RsFunction): SelfType? {
val self = function.selfParameter ?: return null
val ref = self.isRef
return when {
!ref -> SelfType.Move
self.mutability == Mutability.MUTABLE -> SelfType.RefMut
else -> SelfType.Ref
}
}
private fun getSelfArgumentPrefix(selfType: SelfType, receiver: RsExpr): String {
val type = receiver.type
return when (selfType) {
SelfType.Move -> ""
SelfType.Ref -> {
if (type is TyReference) {
""
} else {
"&"
}
}
SelfType.RefMut -> {
if (type is TyReference) {
""
} else {
"&mut "
}
}
}
}
|
mit
|
23b6effea413a81de4cbb9b0464eeb7b
| 31.496 | 115 | 0.664697 | 4.483444 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/lang/core/parser/RustParserDefinition.kt
|
2
|
4905
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.parser
import com.intellij.lang.ASTNode
import com.intellij.lang.LanguageUtil
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import org.rust.ide.console.RsConsoleCodeFragmentContext
import org.rust.ide.console.RsConsoleView
import org.rust.lang.RsDebugInjectionListener
import org.rust.lang.core.lexer.RsLexer
import org.rust.lang.core.psi.*
import org.rust.lang.core.stubs.RsFileStub
import org.rust.lang.core.stubs.RsPathStub
import org.rust.lang.doc.psi.RsDocCommentElementType
import org.rust.lang.doc.psi.RsDocLinkDestination
import org.rust.lang.doc.psi.ext.isDocCommentLeafToken
class RustParserDefinition : ParserDefinition {
override fun createFile(viewProvider: FileViewProvider): PsiFile {
val default = { RsFile(viewProvider) }
val project = viewProvider.manager.project
val injectionHost = InjectedLanguageManager.getInstance(project).getInjectionHost(viewProvider)
if (injectionHost != null) {
// this class is contained in clion.jar, so it cannot be used inside `is` type check
if (injectionHost.javaClass.simpleName != "GDBExpressionPlaceholder") {
return default()
}
val injectionListener = project.messageBus.syncPublisher(RsDebugInjectionListener.INJECTION_TOPIC)
val contextResult = RsDebugInjectionListener.DebugContext()
injectionListener.evalDebugContext(injectionHost, contextResult)
val context = contextResult.element ?: return default()
val fragment = RsDebuggerExpressionCodeFragment(viewProvider, context)
injectionListener.didInject(injectionHost)
return fragment
} else if (viewProvider.virtualFile.name == RsConsoleView.VIRTUAL_FILE_NAME) {
val context = RsConsoleCodeFragmentContext.createContext(project, null)
return RsReplCodeFragment(viewProvider, context)
}
return default()
}
override fun spaceExistenceTypeBetweenTokens(left: ASTNode, right: ASTNode): ParserDefinition.SpaceRequirements {
val leftElementType = left.elementType
if (leftElementType == EOL_COMMENT) {
return ParserDefinition.SpaceRequirements.MUST_LINE_BREAK
}
val rightElementType = right.elementType
if (leftElementType.isDocCommentLeafToken) {
return when {
rightElementType.isDocCommentLeafToken -> ParserDefinition.SpaceRequirements.MAY
/** See [RsDocLinkDestination] */
right.treeParent?.elementType == RsPathStub.Type -> ParserDefinition.SpaceRequirements.MAY
else -> ParserDefinition.SpaceRequirements.MUST_LINE_BREAK
}
}
if (rightElementType.isDocCommentLeafToken && left.treeParent?.elementType == RsPathStub.Type) {
return ParserDefinition.SpaceRequirements.MAY
}
return LanguageUtil.canStickTokensTogetherByLexer(left, right, RsLexer())
}
override fun getFileNodeType(): IFileElementType = RsFileStub.Type
override fun getStringLiteralElements(): TokenSet = RS_ALL_STRING_LITERALS
override fun getWhitespaceTokens(): TokenSet =
TokenSet.create(TokenType.WHITE_SPACE)
override fun getCommentTokens() = RS_COMMENTS
override fun createElement(node: ASTNode?): PsiElement =
RsElementTypes.Factory.createElement(node)
override fun createLexer(project: Project?): Lexer = RsLexer()
override fun createParser(project: Project?): PsiParser = RustParser()
companion object {
@JvmField val BLOCK_COMMENT = RsTokenType("<BLOCK_COMMENT>")
@JvmField val EOL_COMMENT = RsTokenType("<EOL_COMMENT>")
@JvmField val INNER_BLOCK_DOC_COMMENT = RsDocCommentElementType("<INNER_BLOCK_DOC_COMMENT>")
@JvmField val OUTER_BLOCK_DOC_COMMENT = RsDocCommentElementType("<OUTER_BLOCK_DOC_COMMENT>")
@JvmField val INNER_EOL_DOC_COMMENT = RsDocCommentElementType("<INNER_EOL_DOC_COMMENT>")
@JvmField val OUTER_EOL_DOC_COMMENT = RsDocCommentElementType("<OUTER_EOL_DOC_COMMENT>")
/**
* Should be increased after any change of lexer rules
*/
const val LEXER_VERSION: Int = 4
/**
* Should be increased after any change of parser rules
*/
const val PARSER_VERSION: Int = LEXER_VERSION + 43
}
}
|
mit
|
86b42d56ca5857850750e29f0168e815
| 41.284483 | 117 | 0.717839 | 4.794721 | false | false | false | false |
Undin/intellij-rust
|
src/test/kotlin/org/rustSlowTests/lang/resolve/CargoProjectResolveTest.kt
|
2
|
37809
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rustSlowTests.lang.resolve
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.testFramework.fixtures.impl.TempDirTestFixtureImpl
import org.rust.*
import org.rust.cargo.RsWithToolchainTestBase
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.model.impl.testCargoProjects
import org.rust.lang.core.crate.impl.CrateGraphTestmarks
import org.rust.lang.core.psi.RsPath
import org.rust.lang.core.resolve.NameResolutionTestmarks
import org.rust.openapiext.pathAsPath
class CargoProjectResolveTest : RsWithToolchainTestBase() {
private val tempDirFixture = TempDirTestFixtureImpl()
override fun setUp() {
super.setUp()
tempDirFixture.setUp()
}
override fun tearDown() {
tempDirFixture.tearDown()
super.tearDown()
}
fun `test resolve external library which hides std crate`() = buildProject {
toml("Cargo.toml", """
[package]
name = "intellij-rust-test"
version = "0.1.0"
authors = []
[dependencies]
libc = "=0.2.30"
""")
dir("src") {
rust("main.rs", """
extern crate libc;
use libc::int8_t;
//^
""")
}
}.checkReferenceIsResolved<RsPath>("src/main.rs")
fun `test resolve external library which hides std crate in dependency`() {
val testProject = buildProject {
toml("Cargo.toml", """
[package]
name = "intellij-rust-test"
version = "0.1.0"
authors = []
[dependencies]
foo = { path = "./foo" }
""")
dir("src") {
rust("lib.rs", "")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
[dependencies]
libc = "=0.2.30"
""")
dir("src") {
rust("lib.rs", """
extern crate libc;
use libc::int8_t;
//^
""")
}
}
}
testProject.checkReferenceIsResolved<RsPath>("foo/src/lib.rs")
}
fun `test resolve local package`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
authors = []
[dependencies]
foo = { path = "./foo" }
""")
dir("src") {
rust("main.rs", """
extern crate foo;
mod bar;
fn main() {
foo::hello();
} //^
""")
rust("bar.rs", """
use foo::hello;
pub fn bar() {
hello();
} //^
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
""")
dir("src") {
rust("lib.rs", """
pub fn hello() {}
""")
}
}
}.run {
checkReferenceIsResolved<RsPath>("src/main.rs")
checkReferenceIsResolved<RsPath>("src/bar.rs")
}
fun `test resolve local package under symlink`() = fileTree {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
authors = []
[dependencies]
foo = { path = "./foo" }
""")
dir("src") {
rust("main.rs", """
extern crate foo;
mod bar;
fn main() {
foo::hello();
} //^
""")
rust("bar.rs", """
use foo::hello;
pub fn bar() {
hello();
} //^
""")
}
symlink("foo", "foo2")
dir("foo2") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
""")
dir("src") {
rust("lib.rs", """
pub fn hello() {}
""")
}
}
}.let { fileTree ->
// Symlinks doesn't work on Windows CI for some reason
if (SystemInfo.isWindows) return@let
val project = fileTree.create()
project.checkReferenceIsResolved<RsPath>("src/main.rs")
project.checkReferenceIsResolved<RsPath>("src/bar.rs")
}
fun `test module relations`() = buildProject {
toml("Cargo.toml", """
[package]
name = "mods"
version = "0.1.0"
authors = []
[dependencies]
""")
dir("src") {
rust("lib.rs", """
mod foo;
pub struct S;
""")
rust("foo.rs", """
use S;
//^
""")
}
}.checkReferenceIsResolved<RsPath>("src/foo.rs")
fun `test module relations when cargo project is under symlink`() = fileTree {
symlink("foo", "symlink_target")
dir("symlink_target") {
toml("Cargo.toml", """
[package]
name = "mods"
version = "0.1.0"
authors = []
[dependencies]
""")
dir("src") {
rust("lib.rs", """
mod foo;
pub struct S;
""")
rust("foo.rs", """
use S;
//^
""")
}
}
}.let { fileTree ->
// Symlinks doesn't work on Windows CI for some reason
if (SystemInfo.isWindows) return@let
val p = fileTree.create(project, cargoProjectDirectory)
project.testCargoProjects.attachCargoProject(cargoProjectDirectory.pathAsPath.resolve("foo/Cargo.toml"))
excludeDirectoryFromIndex("symlink_target")
p.checkReferenceIsResolved<RsPath>("foo/src/foo.rs")
}
fun `test module relations when parent of cargo project is under symlink`() = fileTree {
symlink("symlink_source", "symlink_target")
dir("symlink_target") {
dir("project") {
toml("Cargo.toml", """
[package]
name = "mods"
version = "0.1.0"
authors = []
[dependencies]
""")
dir("src") {
rust("lib.rs", """
mod foo;
pub struct S;
""")
rust("foo.rs", """
use S;
//^
""")
}
}
}
}.let { fileTree ->
// Symlinks doesn't work on Windows CI for some reason
if (SystemInfo.isWindows) return@let
val p = fileTree.create(project, cargoProjectDirectory)
project.testCargoProjects.attachCargoProject(cargoProjectDirectory.pathAsPath.resolve("symlink_source/project/Cargo.toml"))
excludeDirectoryFromIndex("symlink_target/project")
p.checkReferenceIsResolved<RsPath>("symlink_source/project/src/foo.rs")
}
fun `test kebab-case`() = buildProject {
toml("Cargo.toml", """
[package]
name = "kebab-case"
version = "0.1.0"
authors = []
[dependencies]
""")
dir("src") {
rust("main.rs", """
extern crate kebab_case;
fn main() {
kebab_case::foo();
} //^
""")
rust("lib.rs", "pub fn foo() { }")
}
}.checkReferenceIsResolved<RsPath>("src/main.rs")
fun `test case insensitive mods`() {
if (!SystemInfo.isWindows) return
buildProject {
toml("Cargo.toml", """
[package]
name = "mods"
version = "0.1.0"
authors = []
[dependencies]
""")
dir("src") {
rust("lib.rs", "mod foo; mod bar;")
rust("FOO.rs", "pub struct Spam;")
rust("BAR.rs", """
use foo::Spam;
//^
""")
}
}.checkReferenceIsResolved<RsPath>("src/BAR.rs")
}
// Test that we don't choke on winapi crate, which uses **A LOT** of
// glob imports and is just **ENORMOUS**
fun `test winapi torture (value)`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
authors = []
[dependencies]
winapi = "0.2"
""")
dir("src") {
rust("main.rs", """
extern crate winapi;
use winapi::*;
fn main() {
let _ = foo;
} //^
""")
}
}.checkReferenceIsResolved<RsPath>("src/main.rs", shouldNotResolve = true)
fun `test winapi torture (type)`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
authors = []
[dependencies]
winapi = "0.2"
""")
dir("src") {
rust("main.rs", """
extern crate winapi;
use winapi::*;
fn main() {
let a: Foo;
} //^
""")
}
}.checkReferenceIsResolved<RsPath>("src/main.rs", shouldNotResolve = true)
fun `test multiversion crate resolve`() = buildProject {
toml("Cargo.toml", """
[workspace]
members = ["hello"]
""")
dir("hello") {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
workspace = "../"
[dependencies]
rand = "=0.3.14"
bar = { version = "7.0.0", path = "../bar" }
""")
dir("src") {
rust("main.rs", """
extern crate rand;
extern crate bar;
fn main() {
let _ = rand::thread_rng();
//^
}
""")
}
}
dir("bar") {
toml("Cargo.toml", """
[package]
name = "bar"
version = "7.0.0"
[dependencies]
rand = { version = "54.0.0", path="../rand" }
""")
dir("src") {
rust("lib.rs", """
extern crate rand;
fn bar() {
let _ = rand::thread_rng();
//^
}
""")
}
}
dir("rand") {
toml("Cargo.toml", """
[package]
name = "rand"
version = "54.0.0"
""")
dir("src") {
rust("lib.rs", """
pub fn thread_rng() -> u32 { 42 }
""")
}
}
}.run {
checkReferenceIsResolved<RsPath>("hello/src/main.rs", toCrate = "rand 0.3.14")
checkReferenceIsResolved<RsPath>("bar/src/lib.rs", toCrate = "rand 54.0.0")
}
fun `test cargo rename`() = buildProject {
toml("Cargo.toml", """
[package]
name = "intellij-rust-test"
version = "0.1.0"
authors = []
edition = "2018"
[dependencies]
my_log = { package = "log", version = "=0.4.7" }
""")
dir("src") {
rust("main.rs", """
use my_log::Log;
//^
""")
}
}.checkReferenceIsResolved<RsPath>("src/main.rs", toCrate = "log 0.4.7")
fun `test cargo rename of local dependency`() = buildProject {
toml("Cargo.toml", """
[package]
name = "intellij-rust-test"
version = "0.1.0"
authors = []
edition = "2018"
[dependencies]
bar = { package = "foo", path = "./foo" }
""")
dir("src") {
rust("main.rs", """
use bar::foo;
//^
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
""")
dir("src") {
rust("lib.rs", """
pub fn foo() {}
""")
}
}
}.checkReferenceIsResolved<RsPath>("src/main.rs")
fun `test cargo rename of local dependency with custom lib target name`() = buildProject {
toml("Cargo.toml", """
[package]
name = "intellij-rust-test"
version = "0.1.0"
authors = []
edition = "2018"
[dependencies]
bar = { package = "foo", path = "./foo" }
""")
dir("src") {
rust("main.rs", """
use bar::foo;
//^
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
[lib]
name = "lib_foo"
""")
dir("src") {
rust("lib.rs", """
pub fn foo() {}
""")
}
}
}.checkReferenceIsResolved<RsPath>("src/main.rs")
fun `test custom target path`() {
val libraryDir = tempDirFixture.getFile(".")!!
val library = fileTree {
dir("cargo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
authors = []
[lib]
path = "../lib.rs"
""")
}
rust("lib.rs", """
mod qqq {
pub fn baz() {}
}
pub mod bar;
""")
rust("bar.rs", """
pub use super::qqq::baz;
""")
}.create(project, libraryDir)
val libraryPath = FileUtil.toSystemIndependentName(library.root.pathAsPath.resolve("cargo").toString())
.let { rustupFixture.toolchain?.toRemotePath(it) }
val testProject = buildProject {
toml("Cargo.toml", """
[package]
name = "intellij-rust-test"
version = "0.1.0"
authors = []
[dependencies]
foo = { path = "$libraryPath" }
""")
dir("src") {
rust("main.rs", """
extern crate foo;
use foo::bar::baz;
fn main() {
baz();
//^
}
""")
}
}
testProject.checkReferenceIsResolved<RsPath>("src/main.rs")
}
fun `test disabled cfg feature`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
[dependencies]
foo = { path = "./foo", features = [] }
""")
dir("src") {
rust("main.rs", """
extern crate foo;
fn main() {
let _ = foo::bar();
//^
}
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "1.0.0"
[features]
foobar = []
""")
dir("src") {
rust("lib.rs", """
#[cfg(feature="foobar")]
pub fn bar() -> u32 { 42 }
""")
}
}
}.run {
project.cargoProjects.singlePackage("foo").checkFeatureDisabled("foobar")
checkReferenceIsResolved<RsPath>("src/main.rs", shouldNotResolve = true)
}
fun `test enabled cfg feature`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
[dependencies]
foo = { path = "./foo", features = ["foobar"] }
""")
dir("src") {
rust("main.rs", """
extern crate foo;
fn main() {
let _ = foo::bar();
//^
}
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "1.0.0"
[features]
foobar = []
""")
dir("src") {
rust("lib.rs", """
#[cfg(feature="foobar")]
pub fn bar() -> u32 { 42 }
""")
}
}
}.run {
project.cargoProjects.singlePackage("foo").checkFeatureEnabled("foobar")
checkReferenceIsResolved<RsPath>("src/main.rs")
}
fun `test enabled cfg feature in renamed package`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
edition = "2018"
[dependencies]
foo = { path = "./foo", features = ["foo_feature"] }
""")
dir("src") {
rust("main.rs", """
fn main() {
let _ = foo::bar();
//^
}
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "1.0.0"
edition = "2018"
[features]
foo_feature = ["bar-renamed/bar_feature"]
[dependencies.bar-renamed]
package = "bar"
path = "../bar"
optional = true
""")
dir("src") {
rust("lib.rs", """
#[cfg(feature="bar-renamed")]
pub use bar_renamed::bar;
""")
}
}
dir("bar") {
toml("Cargo.toml", """
[package]
name = "bar"
version = "1.0.0"
[features]
bar_feature = []
""")
dir("src") {
rust("lib.rs", """
#[cfg(feature="bar_feature")]
pub fn bar() -> u32 { 42 }
""")
}
}
}.run {
project.cargoProjects.singlePackage("foo").checkFeatureEnabled("foo_feature")
project.cargoProjects.singlePackage("foo").checkFeatureEnabled("bar-renamed")
project.cargoProjects.singlePackage("bar").checkFeatureEnabled("bar_feature")
checkReferenceIsResolved<RsPath>("src/main.rs")
}
fun `test duplicate dependency with and without rename with different cargo features`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
edition = "2018"
[dependencies]
foo = { path = "./foo", features = ["bar-renamed"] }
""")
dir("src") {
rust("main.rs", """
fn main() {
let _ = foo::bar();
//^
}
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "1.0.0"
edition = "2018"
[dependencies.bar] # Disabled
path = "../bar"
features = ["bar_feature"]
optional = true
[dependencies.bar-renamed] # Enabled
package = "bar"
path = "../bar"
optional = true
""")
dir("src") {
rust("lib.rs", """
#[cfg(feature="bar-renamed")]
pub use bar_renamed::bar;
""")
}
}
dir("bar") {
toml("Cargo.toml", """
[package]
name = "bar"
version = "1.0.0"
[features]
bar_feature = [] # Disabled
""")
dir("src") {
rust("lib.rs", """
#[cfg(not(feature="bar_feature"))]
pub fn bar() -> u32 { 42 }
""")
}
}
}.run {
project.cargoProjects.singlePackage("foo").checkFeatureEnabled("bar-renamed")
project.cargoProjects.singlePackage("foo").checkFeatureDisabled("bar")
project.cargoProjects.singlePackage("bar").checkFeatureDisabled("bar_feature")
checkReferenceIsResolved<RsPath>("src/main.rs")
}
fun `test enabled cfg feature with changed target name`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
edition = "2018"
[dependencies]
foo = { path = "./foo", features = ["foo_feature"] }
""")
dir("src") {
rust("main.rs", """
fn main() {
let _ = foo::bar();
//^
}
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "1.0.0"
edition = "2018"
[features]
foo_feature = ["bar/bar_feature"]
[dependencies]
bar = { path = "../bar"}
""")
dir("src") {
rust("lib.rs", """
pub use bar_target::bar;
""")
}
}
dir("bar") {
toml("Cargo.toml", """
[package]
name = "bar"
version = "1.0.0"
[lib]
path = "src/lib.rs"
name = "bar_target"
[features]
bar_feature = []
""")
dir("src") {
rust("lib.rs", """
#[cfg(feature="bar_feature")]
pub fn bar() -> u32 { 42 }
""")
}
}
}.run {
project.cargoProjects.singlePackage("foo").checkFeatureEnabled("foo_feature")
project.cargoProjects.singlePackage("bar").checkFeatureEnabled("bar_feature")
checkReferenceIsResolved<RsPath>("src/main.rs")
}
fun `test 2 cargo projects with common dependency with different features`() = fileTree {
dir("project_1") {
toml("Cargo.toml", """
[package]
name = "project_1"
version = "0.1.0"
authors = []
[dependencies]
common_dep = { path = "../common_dep", features = ["foo"] }
""")
dir("src") {
rust("main.rs", """
extern crate common_dep;
fn main() {
common_dep::foo();
} //^
""")
}
}
dir("project_2") {
toml("Cargo.toml", """
[package]
name = "project_2"
version = "0.1.0"
authors = []
[dependencies]
common_dep = { path = "../common_dep", features = ["bar"] }
""")
dir("src") {
rust("main.rs", """
extern crate common_dep;
fn main() {
common_dep::bar();
} //^
""")
}
}
dir("common_dep") {
toml("Cargo.toml", """
[package]
name = "common_dep"
version = "0.1.0"
authors = []
[dependencies]
[features]
foo = []
bar = []
""")
dir("src") {
rust("lib.rs", """
#[cfg(feature = "foo")]
pub fn foo() {}
#[cfg(feature = "bar")]
pub fn bar() {}
""")
}
}
}.run {
val prj = create(project, cargoProjectDirectory)
project.testCargoProjects.attachCargoProjects(
cargoProjectDirectory.pathAsPath.resolve("project_1/Cargo.toml"),
cargoProjectDirectory.pathAsPath.resolve("project_2/Cargo.toml"),
)
prj.checkReferenceIsResolved<RsPath>("project_1/src/main.rs")
prj.checkReferenceIsResolved<RsPath>("project_2/src/main.rs")
}
@MinRustcVersion("1.60.0")
fun `test cargo features namespaced dependencies and weak dependency features`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
[features]
feature_foo = ["dep:foo"]
feature_baz = ["foo?/baz"]
[dependencies]
foo = { path = "./foo", optional = true }
""")
dir("src") {
rust("main.rs", """
fn main() {
foo::foo_fn();
} //^
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
[features]
baz = []
""")
dir("src") {
rust("lib.rs", """
#[cfg(feature = "baz")]
pub fn foo_fn() {}
""")
}
}
dir("bar") {
toml("Cargo.toml", """
[package]
name = "bar"
version = "0.1.0"
""")
dir("src") {
rust("lib.rs", "pub fn bar_fn() {}")
}
}
}.run {
val helloPkg = project.cargoProjects.singlePackage("hello")
assertEquals(setOf("feature_foo", "feature_baz"), helloPkg.featureState.keys)
helloPkg.checkFeatureEnabled("feature_foo")
helloPkg.checkFeatureEnabled("feature_baz")
project.cargoProjects.singlePackage("foo").checkFeatureEnabled("baz")
checkReferenceIsResolved<RsPath>("src/main.rs")
project.cargoProjects.disableCargoFeature("hello", "feature_foo")
project.cargoProjects.disableCargoFeature("hello", "feature_baz")
project.cargoProjects.singlePackage("foo").checkFeatureDisabled("baz")
checkReferenceIsResolved<RsPath>("src/main.rs", shouldNotResolve = true)
}
// TODO the test has been regressed after switching to Name Resolution 2.0
fun `test cyclic dev deps`() = expect<IllegalStateException> {
buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
build = "build.rs"
[dev-dependencies]
foo = { path = "./foo" }
""")
dir("tests") {
rust("main.rs", """
extern crate foo;
fn main() {
foo::bar();
} //^
""")
}
dir("src") {
rust("lib.rs", """
pub fn bar() {}
#[test]
fn test() {
extern crate foo;
foo::bar();
} //^
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "1.0.0"
[dependencies]
hello = { path = "../" }
""")
dir("src") {
rust("lib.rs", """
extern crate hello;
pub use hello::bar;
""")
}
}
}.run {
CrateGraphTestmarks.CyclicDevDependency.checkHit {
checkReferenceIsResolved<RsPath>("tests/main.rs")
checkReferenceIsResolved<RsPath>("src/lib.rs")
}
}
}
fun `test build-dependency is resolved in 'build rs' and not resolved in 'main rs'`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
build = "build.rs"
[build-dependencies]
foo = { path = "./foo" }
""")
rust("build.rs", """
extern crate foo;
fn main() {
foo::bar();
} //^
""")
dir("src") {
rust("main.rs", """
extern crate foo;
fn main() {
foo::bar();
} //^
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "1.0.0"
""")
dir("src") {
rust("lib.rs", """
pub fn bar() {}
""")
}
}
}.run {
checkReferenceIsResolved<RsPath>("build.rs")
checkReferenceIsResolved<RsPath>("src/main.rs", shouldNotResolve = true)
}
fun `test normal dependency is not resolved in 'build rs' and resolved in 'main rs'`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
build = "build.rs"
[dependencies]
foo = { path = "./foo" }
""")
rust("build.rs", """
extern crate foo;
fn main() {
foo::bar();
} //^
""")
dir("src") {
rust("main.rs", """
extern crate foo;
fn main() {
foo::bar();
} //^
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "1.0.0"
""")
dir("src") {
rust("lib.rs", """
pub fn bar() {}
""")
}
}
}.run {
checkReferenceIsResolved<RsPath>("build.rs", shouldNotResolve = true)
checkReferenceIsResolved<RsPath>("src/main.rs")
}
fun `test stdlib in 'build rs'`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
build = "build.rs"
""")
rust("build.rs", """
fn main() {
std::mem::size_of::<i32>();
} //^
""")
dir("src") {
rust("main.rs", "")
}
}.run {
checkReferenceIsResolved<RsPath>("build.rs")
}
fun `test change crate name`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
[lib]
name = "foo1"
""")
dir("src") {
rust("main.rs", """
fn main() {
foo2::func();
} //^
""")
rust("lib.rs", "pub fn func() {}")
}
}.run {
val projectManifest = cargoProjectDirectory.findFileByRelativePath("Cargo.toml")!!
checkReferenceIsResolved<RsPath>("src/main.rs", shouldNotResolve = true)
runWriteAction {
VfsUtil.saveText(projectManifest, VfsUtil.loadText(projectManifest).replace("foo1", "foo2"))
}
project.testCargoProjects.refreshAllProjectsSync()
checkReferenceIsResolved<RsPath>("src/main.rs")
}
fun `test change dependency name`() = buildProject {
toml("Cargo.toml", """
[package]
name = "hello"
version = "0.1.0"
[dependencies]
foo1 = { path = "./foo", package = "foo" }
""")
dir("src") {
rust("main.rs", """
fn main() {
foo2::func();
} //^
""")
}
dir("foo") {
toml("Cargo.toml", """
[package]
name = "foo"
version = "0.1.0"
""")
dir("src") {
rust("lib.rs", "pub fn func() {}")
}
}
}.run {
val projectManifest = cargoProjectDirectory.findFileByRelativePath("Cargo.toml")!!
checkReferenceIsResolved<RsPath>("src/main.rs", shouldNotResolve = true)
runWriteAction {
val textOld = """foo1 = { path = "./foo", package = "foo" }"""
val textNew = """foo2 = { path = "./foo", package = "foo" }"""
VfsUtil.saveText(projectManifest, VfsUtil.loadText(projectManifest).replace(textOld, textNew))
}
project.testCargoProjects.refreshAllProjectsSync()
checkReferenceIsResolved<RsPath>("src/main.rs")
}
// we test that there are no exceptions (and not resolve result)
fun `test remove crate from workspace`() = buildProject {
toml("Cargo.toml", """
[workspace]
members = [
"foo1",
"foo2"
]
""")
dir("foo1") {
toml("Cargo.toml", """
[package]
name = "foo1"
version = "0.1.0"
""")
dir("src") {
rust("lib.rs", "")
}
}
dir("foo2") {
toml("Cargo.toml", """
[package]
name = "foo2"
version = "0.1.0"
""")
dir("src") {
rust("main.rs", """
fn main() {
func();
} //^
fn func() {}
""")
}
}
}.run {
checkReferenceIsResolved<RsPath>("foo2/src/main.rs")
val projectManifest = cargoProjectDirectory.findFileByRelativePath("Cargo.toml")!!
runWriteAction {
VfsUtil.saveText(projectManifest, VfsUtil.loadText(projectManifest).replace(""""foo2"""", ""))
}
project.testCargoProjects.refreshAllProjectsSync()
checkReferenceIsResolved<RsPath>("foo2/src/main.rs")
}
@CheckTestmarkHit(NameResolutionTestmarks.UpdateDefMapsForAllCratesWhenFindingModData::class)
fun `test file outside of a package root`() = buildProject {
dir("cargo-package") {
toml("Cargo.toml", """
[package]
name = "cargo-package"
version = "0.1.0"
""")
dir("src") {
rust("lib.rs", """
fn func() {}
#[path = "../../outside/foo.rs"]
mod foo;
""")
}
}
dir("outside") {
rust("foo.rs", """
fn main() {
crate::func();
} //^
""")
}
}.run {
project.testCargoProjects.attachCargoProject(cargoProjectDirectory.pathAsPath.resolve("cargo-package/Cargo.toml"))
checkReferenceIsResolved<RsPath>("outside/foo.rs")
}
private fun excludeDirectoryFromIndex(path: String) {
runWriteAction {
ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring {
val module = ModuleUtilCore.findModuleForFile(cargoProjectDirectory, project)!!
ModuleRootModificationUtil.updateModel(module) { rootModel ->
rootModel.contentEntries.singleOrNull()!!
.addExcludeFolder(FileUtil.join(cargoProjectDirectory.url, path))
}
}
}
}
}
|
mit
|
da8753db171433ad5763513571a7e1c5
| 27.470633 | 131 | 0.394562 | 4.842341 | false | true | false | false |
charleskorn/batect
|
app/src/main/kotlin/batect/ui/interleaved/InterleavedContainerOutputSink.kt
|
1
|
1622
|
/*
Copyright 2017-2020 Charles Korn.
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 batect.ui.interleaved
import batect.config.Container
import batect.ui.text.Text
import batect.ui.text.TextRun
import okio.Buffer
import okio.Sink
import okio.Timeout
data class InterleavedContainerOutputSink(val container: Container, val output: InterleavedOutput, val prefix: TextRun = TextRun()) : Sink {
private val buffer = StringBuilder()
override fun write(source: Buffer, byteCount: Long) {
val text = source.readString(byteCount, Charsets.UTF_8)
buffer.append(text)
while (buffer.contains('\n')) {
val endOfLine = buffer.indexOf('\n')
val line = buffer.substring(0, endOfLine)
output.printForContainer(container, prefix + Text(line))
buffer.delete(0, endOfLine + 1)
}
}
override fun close() {
if (buffer.isNotEmpty()) {
output.printForContainer(container, prefix + Text(buffer.toString()))
}
}
override fun timeout(): Timeout = Timeout.NONE
override fun flush() {}
}
|
apache-2.0
|
0c59f1d2e1e4190e80f8c9136cfdf545
| 31.44 | 140 | 0.692355 | 4.407609 | false | false | false | false |
googlemaps/android-maps-compose
|
maps-compose/src/main/java/com/google/maps/android/compose/Circle.kt
|
1
|
3698
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.maps.android.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ComposeNode
import androidx.compose.runtime.currentComposer
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import com.google.android.gms.maps.model.Circle
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.PatternItem
import com.google.maps.android.ktx.addCircle
internal class CircleNode(
val circle: Circle,
var onCircleClick: (Circle) -> Unit
) : MapNode {
override fun onRemoved() {
circle.remove()
}
}
/**
* A composable for a circle on the map.
*
* @param center the [LatLng] to use for the center of this circle
* @param clickable boolean indicating if the circle is clickable or not
* @param fillColor the fill color of the circle
* @param radius the radius of the circle in meters.
* @param strokeColor the stroke color of the circle
* @param strokePattern a sequence of [PatternItem] to be repeated along the circle's outline (null
* represents a solid line)
* @param tag optional tag to be associated with the circle
* @param strokeWidth the width of the circle's outline in screen pixels
* @param visible the visibility of the circle
* @param zIndex the z-index of the circle
* @param onClick a lambda invoked when the circle is clicked
*/
@Composable
@GoogleMapComposable
public fun Circle(
center: LatLng,
clickable: Boolean = false,
fillColor: Color = Color.Transparent,
radius: Double = 0.0,
strokeColor: Color = Color.Black,
strokePattern: List<PatternItem>? = null,
strokeWidth: Float = 10f,
tag: Any? = null,
visible: Boolean = true,
zIndex: Float = 0f,
onClick: (Circle) -> Unit = {},
) {
val mapApplier = currentComposer.applier as? MapApplier
ComposeNode<CircleNode, MapApplier>(
factory = {
val circle = mapApplier?.map?.addCircle {
center(center)
clickable(clickable)
fillColor(fillColor.toArgb())
radius(radius)
strokeColor(strokeColor.toArgb())
strokePattern(strokePattern)
strokeWidth(strokeWidth)
visible(visible)
zIndex(zIndex)
} ?: error("Error adding circle")
circle.tag = tag
CircleNode(circle, onClick)
},
update = {
update(onClick) { this.onCircleClick = it }
set(center) { this.circle.center = it }
set(clickable) { this.circle.isClickable = it }
set(fillColor) { this.circle.fillColor = it.toArgb() }
set(radius) { this.circle.radius = it }
set(strokeColor) { this.circle.strokeColor = it.toArgb() }
set(strokePattern) { this.circle.strokePattern = it }
set(strokeWidth) { this.circle.strokeWidth = it }
set(tag) { this.circle.tag = it }
set(visible) { this.circle.isVisible = it }
set(zIndex) { this.circle.zIndex = it }
}
)
}
|
apache-2.0
|
4a4c9ac0bb04eef1a22c11672e51e162
| 36.363636 | 99 | 0.666036 | 4.216648 | false | false | false | false |
kiruto/debug-bottle
|
core/src/main/kotlin/com/exyui/android/debugbottle/core/consts.kt
|
1
|
831
|
package com.exyui.android.debugbottle.core
/**
* Created by yuriel on 8/22/16.
*/
const val DEFAULT_BLOCK_THRESHOLD = 500L
const val DEFAULT_TESTING_SEED = 1000
const val DEFAULT_TESTING_EVENT_COUNT = 50
const val DT_SETTING_STORE_FILE = "dt_settings"
const val BOTTLE_ENABLE = "BOTTLE_ENABLE"
const val BLOCK_THRESHOLD = "BLOCK_THRESHOLD"
const val STRICT_MODE = "STRICT_MODE"
const val NETWORK_SNIFF = "NETWORK_SNIFF"
const val LEAK_CANARY_ENABLE = "LEAK_CANARY_ENABLE"
const val BLOCK_CANARY_ENABLE = "BLOCK_CANARY_ENABLE"
const val TESTING_SEED = "TESTING_SEED"
const val TESTING_SEND_KEY_EVENT = "TESTING_SEND_KEY_EVENT"
const val TESTING_EVENT_COUNT = "TESTING_EVENT_COUNT"
const val TESTING_LOG_DEPTH = "TESTING_LOG_DEPTH"
const val MONKEY_BLACKLIST = "MONKEY_BLACKLIST"
const val NOTIFICATION_LOCK = "NOTIFICATION_LOCK"
|
apache-2.0
|
15f3096b465173bc8fe0a127cf1672e9
| 36.818182 | 59 | 0.765343 | 3.183908 | false | true | false | false |
kotlinx/kotlinx.html
|
src/commonMain/kotlin/generated/gen-tags-h.kt
|
1
|
6936
|
package kotlinx.html
import kotlinx.html.*
import kotlinx.html.impl.*
import kotlinx.html.attributes.*
/*******************************************************************************
DO NOT EDIT
This file was generated by module generate
*******************************************************************************/
@Suppress("unused")
open class H1(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("h1", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowHeadingPhrasingContent {
}
@Suppress("unused")
open class H2(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("h2", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowHeadingPhrasingContent {
}
@Suppress("unused")
open class H3(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("h3", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowHeadingPhrasingContent {
}
@Suppress("unused")
open class H4(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("h4", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowHeadingPhrasingContent {
}
@Suppress("unused")
open class H5(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("h5", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowHeadingPhrasingContent {
}
@Suppress("unused")
open class H6(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("h6", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowHeadingPhrasingContent {
}
@Suppress("unused")
open class HEAD(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("head", consumer, initialAttributes, null, false, false), HtmlHeadTag {
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override operator fun Entities.unaryPlus() : Unit {
@Suppress("DEPRECATION") entity(this)
}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override operator fun String.unaryPlus() : Unit {
@Suppress("DEPRECATION") text(this)
}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override fun text(s : String) : Unit {
super<HTMLTag>.text(s)
}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override fun text(n : Number) : Unit {
super<HTMLTag>.text(n)
}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override fun entity(e : Entities) : Unit {
super<HTMLTag>.entity(e)
}
}
@Suppress("unused")
open class HEADER(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("header", consumer, initialAttributes, null, false, false), HtmlBlockTag {
}
@Suppress("unused")
open class HGROUP(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("hgroup", consumer, initialAttributes, null, false, false), CommonAttributeGroupFacadeFlowHeadingContent {
}
/**
* Heading
*/
@HtmlTagMarker
inline fun HGROUP.h1(classes : String? = null, crossinline block : H1.() -> Unit = {}) : Unit = H1(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun HGROUP.h2(classes : String? = null, crossinline block : H2.() -> Unit = {}) : Unit = H2(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun HGROUP.h3(classes : String? = null, crossinline block : H3.() -> Unit = {}) : Unit = H3(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun HGROUP.h4(classes : String? = null, crossinline block : H4.() -> Unit = {}) : Unit = H4(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun HGROUP.h5(classes : String? = null, crossinline block : H5.() -> Unit = {}) : Unit = H5(attributesMapOf("class", classes), consumer).visit(block)
/**
* Heading
*/
@HtmlTagMarker
inline fun HGROUP.h6(classes : String? = null, crossinline block : H6.() -> Unit = {}) : Unit = H6(attributesMapOf("class", classes), consumer).visit(block)
val HGROUP.asFlowContent : FlowContent
get() = this
val HGROUP.asHeadingContent : HeadingContent
get() = this
@Suppress("unused")
open class HR(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>) : HTMLTag("hr", consumer, initialAttributes, null, false, true), HtmlBlockTag {
}
@Suppress("unused")
open class HTML(initialAttributes : Map<String, String>, override val consumer : TagConsumer<*>, namespace : String? = null) : HTMLTag("html", consumer, initialAttributes, namespace, false, false), CommonAttributeGroupFacade {
var manifest : String
get() = attributeStringString.get(this, "manifest")
set(newValue) {attributeStringString.set(this, "manifest", newValue)}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override operator fun Entities.unaryPlus() : Unit {
@Suppress("DEPRECATION") entity(this)
}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override operator fun String.unaryPlus() : Unit {
@Suppress("DEPRECATION") text(this)
}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override fun text(s : String) : Unit {
super<HTMLTag>.text(s)
}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override fun text(n : Number) : Unit {
super<HTMLTag>.text(n)
}
@Deprecated("This tag most likely doesn't support text content or requires unsafe content (try unsafe {}")
override fun entity(e : Entities) : Unit {
super<HTMLTag>.entity(e)
}
}
/**
* Document body
*/
@HtmlTagMarker
inline fun HTML.body(classes : String? = null, crossinline block : BODY.() -> Unit = {}) : Unit = BODY(attributesMapOf("class", classes), consumer).visit(block)
/**
* Document head
*/
@HtmlTagMarker
inline fun HTML.head(crossinline block : HEAD.() -> Unit = {}) : Unit = HEAD(emptyMap, consumer).visit(block)
@Deprecated("This tag doesn't support content or requires unsafe (try unsafe {})")
@Suppress("DEPRECATION")
/**
* Document head
*/
@HtmlTagMarker
fun HTML.head(content : String = "") : Unit = HEAD(emptyMap, consumer).visit({+content})
|
apache-2.0
|
6fee28c39bb7bfc61dac438cffd7dc0c
| 37.748603 | 226 | 0.692907 | 4.237019 | false | false | false | false |
androidx/androidx
|
room/room-runtime-lint/src/main/java/androidx/room/lint/CursorKotlinUseIssueDetector.kt
|
3
|
3234
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.lint
import com.android.tools.lint.checks.VersionChecks.Companion.isPrecededByVersionCheckExit
import com.android.tools.lint.checks.VersionChecks.Companion.isWithinVersionCheckConditional
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Incident
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.VersionChecks
import com.android.tools.lint.detector.api.minSdkLessThan
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UCallExpression
class CursorKotlinUseIssueDetector : Detector(), SourceCodeScanner {
companion object {
private const val DESCRIPTION = "Usage of `kotlin.io.use()` with Cursor requires API 16."
val ISSUE = Issue.create(
id = "CursorKotlinUse",
briefDescription = DESCRIPTION,
explanation = """
The use of `kotlin.io.use()` with `android.database.Cursor` is not safe when min
API level is less than 16 since Cursor does not implement Closeable.
""",
androidSpecific = true,
category = Category.CORRECTNESS,
severity = Severity.FATAL,
implementation = Implementation(
CursorKotlinUseIssueDetector::class.java, Scope.JAVA_FILE_SCOPE
)
)
}
override fun getApplicableMethodNames(): List<String> = listOf("use")
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
// Skip if `use` is not Kotlin's
if (!context.evaluator.isMemberInClass(method, "kotlin.io.CloseableKt")) {
return
}
// Skip if the receiver is not Android's Cursor
if (node.receiverType?.canonicalText != "android.database.Cursor") {
return
}
// If the call is within an SDK_INT check, then its OK
if (
VersionChecks.isWithinVersionCheckConditional(context, node, 16) ||
VersionChecks.isPrecededByVersionCheckExit(context, node, 16)
) {
return
}
context.report(
incident = Incident(ISSUE, DESCRIPTION, context.getLocation(node)),
constraint = minSdkLessThan(16)
)
}
}
|
apache-2.0
|
5aa2777c9465e7efa0fe3570628a8378
| 41.012987 | 98 | 0.698516 | 4.412005 | false | false | false | false |
andstatus/andstatus
|
app/src/main/kotlin/org/andstatus/app/widget/MySearchView.kt
|
1
|
8807
|
/*
* Copyright (c) 2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.widget
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.AttributeSet
import android.view.CollapsibleActionView
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.AutoCompleteTextView
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.Spinner
import android.widget.TextView.OnEditorActionListener
import org.andstatus.app.IntentExtra
import org.andstatus.app.R
import org.andstatus.app.SearchObjects
import org.andstatus.app.actor.ActorsScreenType
import org.andstatus.app.data.MatchedUri
import org.andstatus.app.origin.Origin
import org.andstatus.app.service.CommandData
import org.andstatus.app.service.MyServiceManager
import org.andstatus.app.timeline.LoadableListActivity
import org.andstatus.app.timeline.meta.Timeline
import org.andstatus.app.util.MyLog
import org.andstatus.app.view.SuggestionsAdapter
/**
* @author [email protected]
*/
class MySearchView(context: Context?, attrs: AttributeSet?) : LinearLayout(context, attrs), CollapsibleActionView {
private var parentActivity: LoadableListActivity<*>? = null
var timeline: Timeline? = if (isInEditMode) null else Timeline.EMPTY
var searchText: AutoCompleteTextView? = null
var searchObjects: Spinner? = null
var internetSearch: CheckBox? = null
var combined: CheckBox? = null
private var isInternetSearchEnabled = false
fun initialize(loadableListActivity: LoadableListActivity<*>) {
parentActivity = loadableListActivity
searchText = findViewById<View?>(R.id.search_text) as AutoCompleteTextView
if (searchText == null) {
MyLog.w(this, "searchView is null")
return
}
searchText?.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
// See https://stackoverflow.com/questions/3205339/android-how-to-make-keyboard-enter-button-say-search-and-handle-its-click
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
val query = v.text.toString()
if (query.isNotEmpty()) {
onQueryTextSubmit(query)
return@OnEditorActionListener true
}
}
false
})
searchObjects = findViewById<View?>(R.id.search_objects) as Spinner
if (searchObjects == null) {
MyLog.w(this, "searchObjects is null")
return
}
searchObjects?.setOnItemSelectedListener(object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
onSearchObjectsChange()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
})
val upButton = findViewById<View?>(R.id.up_button)
if (upButton == null) {
MyLog.w(this, "upButton is null")
return
}
upButton.setOnClickListener { onActionViewCollapsed() }
internetSearch = findViewById<View?>(R.id.internet_search) as CheckBox
if (internetSearch == null) {
MyLog.w(this, "internetSearch is null")
return
}
combined = findViewById(R.id.combined) as CheckBox
if (combined == null) {
MyLog.w(this, "combined is null")
return
}
combined?.setOnCheckedChangeListener({ buttonView, isChecked -> onSearchContextChanged() })
val submitButton = findViewById<View?>(R.id.submit_button)
if (submitButton == null) {
MyLog.w(this, "submitButton is null")
return
}
searchText?.let { st ->
submitButton.setOnClickListener { onQueryTextSubmit(st.getText().toString()) }
onActionViewCollapsed()
onSearchObjectsChange()
}
}
fun showSearchView(timeline: Timeline) {
this.timeline = timeline
if (isCombined() != timeline.isCombined) {
combined?.setChecked(timeline.isCombined)
}
onActionViewExpanded()
}
override fun onActionViewExpanded() {
onSearchObjectsChange()
visibility = VISIBLE
parentActivity?.hideActionBar(true)
}
override fun onActionViewCollapsed() {
visibility = GONE
parentActivity?.hideActionBar(false)
searchText?.setText("")
}
fun onQueryTextSubmit(query: String?) {
MyLog.d(this, "Submitting " + getSearchObjects() + " query '" + query + "'"
+ (if (isInternetSearch()) " Internet" else "")
+ if (isCombined()) " combined" else ""
)
if (isInternetSearch()) {
launchInternetSearch(query)
}
launchActivity(query)
onActionViewCollapsed()
searchText?.setAdapter(null)
SuggestionsAdapter.addSuggestion(getSearchObjects(), query)
}
private fun launchInternetSearch(query: String?) {
val myContext = parentActivity?.myContext ?: return
if (myContext.isEmpty) return
for (origin in myContext.origins.originsForInternetSearch(
getSearchObjects(), getOrigin(), isCombined())) {
MyServiceManager.sendManualForegroundCommand(
CommandData.newSearch(getSearchObjects(), myContext, origin, query))
}
}
private fun onSearchObjectsChange() {
parentActivity?.let { activity ->
searchText?.setAdapter(SuggestionsAdapter(activity, getSearchObjects()))
searchText?.setHint(if (getSearchObjects() == SearchObjects.NOTES) R.string.search_timeline_hint else R.string.search_userlist_hint)
onSearchContextChanged()
}
}
private fun launchActivity(query: String?) {
if (query.isNullOrEmpty()) {
return
}
val intent = Intent(Intent.ACTION_SEARCH, getUri(), context, getSearchObjects().getActivityClass())
intent.putExtra(IntentExtra.SEARCH_QUERY.key, query)
if (timeline?.hasSearchQuery() == true
&& getSearchObjects() == SearchObjects.NOTES &&
parentActivity?.myContext?.timelines?.getDefault() != timeline) {
// Send intent to existing activity
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
}
context.startActivity(intent)
}
private fun onSearchContextChanged() {
isInternetSearchEnabled = parentActivity?.myContext
?.origins?.isSearchSupported(
getSearchObjects(), getOrigin(), isCombined()) ?: false
internetSearch?.setEnabled(isInternetSearchEnabled)
if (!isInternetSearchEnabled && internetSearch?.isChecked() == true) {
internetSearch?.setChecked(false)
}
}
private fun getUri(): Uri? {
return when (getSearchObjects()) {
SearchObjects.NOTES -> timeline?.fromSearch(parentActivity?.myContext ?: return null, isInternetSearch())
?.fromIsCombined(parentActivity?.myContext ?: return null, isCombined())?.getUri()
SearchObjects.ACTORS -> MatchedUri.getActorsScreenUri(ActorsScreenType.ACTORS_AT_ORIGIN,
if (isCombined()) 0 else getOrigin().id, 0, "")
SearchObjects.GROUPS -> MatchedUri.getActorsScreenUri(ActorsScreenType.GROUPS_AT_ORIGIN,
if (isCombined()) 0 else getOrigin().id, 0, "")
}
}
fun getSearchObjects(): SearchObjects {
return SearchObjects.fromSpinner(searchObjects)
}
private fun getOrigin(): Origin {
return if (timeline?.getOrigin()?.isValid == true) timeline?.getOrigin() ?: Origin.EMPTY
else parentActivity?.myContext?.accounts?.currentAccount?.origin ?: Origin.EMPTY
}
private fun isInternetSearch(): Boolean {
return isInternetSearchEnabled && internetSearch?.isChecked() == true
}
private fun isCombined(): Boolean {
return combined?.isChecked() == true
}
}
|
apache-2.0
|
89424204913daa63ed9b256d4468ad7d
| 38.671171 | 144 | 0.656637 | 4.933894 | false | false | false | false |
EventFahrplan/EventFahrplan
|
app/src/main/java/nerd/tuxmobil/fahrplan/congress/dataconverters/SessionExtensions.kt
|
1
|
6902
|
@file:JvmName("SessionExtensions")
package nerd.tuxmobil.fahrplan.congress.dataconverters
import info.metadude.android.eventfahrplan.commons.temporal.Moment
import info.metadude.android.eventfahrplan.network.serialization.FahrplanParser
import nerd.tuxmobil.fahrplan.congress.models.DateInfo
import nerd.tuxmobil.fahrplan.congress.models.Session
import org.threeten.bp.ZoneOffset
import info.metadude.android.eventfahrplan.database.models.Highlight as HighlightDatabaseModel
import info.metadude.android.eventfahrplan.database.models.Session as SessionDatabaseModel
import info.metadude.android.eventfahrplan.network.models.Session as SessionNetworkModel
fun Session.shiftRoomIndexOnDays(dayIndices: Set<Int>): Session {
if (dayIndices.contains(day)) {
shiftRoomIndexBy(1)
}
return this
}
/**
* Returns a moment based on the start time of this session.
*/
fun Session.toStartsAtMoment(): Moment {
require(dateUTC > 0) { "Field 'dateUTC' is 0." }
return Moment.ofEpochMilli(dateUTC)
}
fun Session.toDateInfo(): DateInfo = DateInfo(day, Moment.parseDate(date))
fun Session.toHighlightDatabaseModel() = HighlightDatabaseModel(
sessionId = Integer.parseInt(sessionId),
isHighlight = highlight
)
fun Session.toSessionDatabaseModel() = SessionDatabaseModel(
sessionId = sessionId,
abstractt = abstractt,
date = date,
dateUTC = dateUTC,
dayIndex = day,
description = description,
duration = duration, // minutes
hasAlarm = hasAlarm,
language = lang,
links = links,
isHighlight = highlight,
recordingLicense = recordingLicense,
recordingOptOut = recordingOptOut,
relativeStartTime = relStartTime,
room = room,
roomIndex = roomIndex,
slug = slug,
speakers = createSpeakersString(speakers),
startTime = startTime, // minutes since day start
subtitle = subtitle,
timeZoneOffset = timeZoneOffset?.totalSeconds, // seconds
title = title,
track = track,
type = type,
url = url,
changedDay = changedDay,
changedDuration = changedDuration,
changedIsCanceled = changedIsCanceled,
changedIsNew = changedIsNew,
changedLanguage = changedLanguage,
changedRecordingOptOut = changedRecordingOptOut,
changedRoom = changedRoom,
changedSpeakers = changedSpeakers,
changedSubtitle = changedSubtitle,
changedTime = changedTime,
changedTitle = changedTitle,
changedTrack = changedTrack
)
fun SessionDatabaseModel.toSessionAppModel(): Session {
val session = Session(sessionId)
session.abstractt = abstractt
session.date = date
session.dateUTC = dateUTC
session.day = dayIndex
session.description = description
session.duration = duration // minutes
session.hasAlarm = hasAlarm
session.lang = language
session.links = links
session.highlight = isHighlight
session.recordingLicense = recordingLicense
session.recordingOptOut = recordingOptOut
session.relStartTime = relativeStartTime
session.room = room
session.roomIndex = roomIndex
session.slug = slug
session.speakers = createSpeakersList(speakers)
session.startTime = startTime // minutes since day start
session.subtitle = subtitle
session.timeZoneOffset = timeZoneOffset?.let { ZoneOffset.ofTotalSeconds(it) } // seconds
session.title = title
session.track = track
session.type = type
session.url = url
session.changedDay = changedDay
session.changedDuration = changedDuration
session.changedIsCanceled = changedIsCanceled
session.changedIsNew = changedIsNew
session.changedLanguage = changedLanguage
session.changedRecordingOptOut = changedRecordingOptOut
session.changedRoom = changedRoom
session.changedSpeakers = changedSpeakers
session.changedSubtitle = changedSubtitle
session.changedTime = changedTime
session.changedTitle = changedTitle
session.changedTrack = changedTrack
return session
}
fun SessionNetworkModel.toSessionAppModel(): Session {
val session = Session(sessionId)
session.abstractt = abstractt
session.date = date
session.dateUTC = dateUTC
session.day = dayIndex
session.description = description
session.duration = duration // minutes
session.hasAlarm = hasAlarm
session.lang = language
session.links = links
session.highlight = isHighlight
session.recordingLicense = recordingLicense
session.recordingOptOut = recordingOptOut
session.relStartTime = relativeStartTime
session.room = room
session.roomIndex = roomIndex
session.slug = slug
session.speakers = createSpeakersList(speakers)
session.startTime = startTime // minutes since day start
session.subtitle = subtitle
session.timeZoneOffset = timeZoneOffset?.let { ZoneOffset.ofTotalSeconds(it) } // seconds
session.title = title
session.track = track
session.type = type
session.url = url
session.changedDay = changedDayIndex
session.changedDuration = changedDuration
session.changedIsCanceled = changedIsCanceled
session.changedIsNew = changedIsNew
session.changedLanguage = changedLanguage
session.changedRecordingOptOut = changedRecordingOptOut
session.changedRoom = changedRoom
session.changedSpeakers = changedSpeakers
session.changedSubtitle = changedSubtitle
session.changedTime = changedStartTime
session.changedTitle = changedTitle
session.changedTrack = changedTrack
return session
}
fun Session.sanitize(): Session {
if (title == subtitle) {
subtitle = ""
}
if (abstractt == description) {
abstractt = ""
}
if (createSpeakersString(speakers) == subtitle) {
subtitle = ""
}
if (description.isEmpty()) {
description = abstractt
abstractt = ""
}
if (!lang.isNullOrEmpty()) {
lang = lang.lowercase()
}
if (("Sendezentrum-Bühne" == track || "Sendezentrum Bühne" == track || "xHain Berlin" == track) && !type.isNullOrEmpty()) {
track = type
}
if ("classics" == room && "Other" == type && track.isNullOrEmpty()) {
track = "Classics"
}
if ("rC3 Lounge" == room) {
track = "Music"
}
if (track.isNullOrEmpty() && !type.isNullOrEmpty()) {
track = type
}
return this
}
/**
* Delimiter which is used in [FahrplanParser] to construct the speakers string.
*/
private const val SPEAKERS_DELIMITER = ";"
private fun createSpeakersList(speakers: String): List<String> {
return if (speakers.isEmpty()) emptyList() else speakers.split(SPEAKERS_DELIMITER)
}
private fun createSpeakersString(speakers: List<String>): String {
return speakers.joinToString(SPEAKERS_DELIMITER)
}
|
apache-2.0
|
776095eccc8b80ff69a0be38d1b90d8b
| 32.173077 | 127 | 0.705362 | 4.700272 | false | false | false | false |
CruGlobal/android-gto-support
|
gto-support-androidx-lifecycle/src/main/kotlin/org/ccci/gto/android/common/androidx/lifecycle/SavedStateHandle+Delegates.kt
|
1
|
1247
|
package org.ccci.gto.android.common.androidx.lifecycle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun <T> SavedStateHandle.delegate(key: String? = null) = object : ReadWriteProperty<Any, T?> {
override fun getValue(thisRef: Any, property: KProperty<*>): T? = get(key ?: property.name)
override fun setValue(thisRef: Any, property: KProperty<*>, value: T?) = set(key ?: property.name, value)
}
fun <T : Any> SavedStateHandle.delegate(key: String? = null, ifNull: T) = object : ReadWriteProperty<Any, T> {
override fun getValue(thisRef: Any, property: KProperty<*>): T = get(key ?: property.name) ?: ifNull
override fun setValue(thisRef: Any, property: KProperty<*>, value: T) = set(key ?: property.name, value)
}
fun <T> SavedStateHandle.livedata(key: String? = null) = ReadOnlyProperty<Any, MutableLiveData<T>> { _, property ->
getLiveData(key ?: property.name)
}
fun <T> SavedStateHandle.livedata(key: String? = null, initialValue: T) =
ReadOnlyProperty<Any, MutableLiveData<T>> { _, property ->
getLiveData(key ?: property.name, initialValue)
}
|
mit
|
76870c148b60548b082187a7e66110fb
| 46.961538 | 115 | 0.726544 | 4.009646 | false | false | false | false |
felipebz/sonar-plsql
|
zpa-core/src/main/kotlin/org/sonar/plugins/plsqlopen/api/matchers/MethodMatcher.kt
|
1
|
5666
|
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.plsqlopen.api.matchers
import com.felipebz.flr.api.AstNode
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.squid.SemanticAstNode
import org.sonar.plugins.plsqlopen.api.symbols.PlSqlType
class MethodMatcher private constructor()
{
private var methodNameCriteria: NameCriteria? = null
private var packageNameCriteria: NameCriteria? = null
private var schemaNameCriteria: NameCriteria? = null
private var shouldCheckParameters = true
private var schemaIsOptional = false
var methodName: String = ""
private set
private val expectedArgumentTypes = ArrayList<PlSqlType>()
fun name(methodNameCriteria: String) =
name(NameCriteria.`is`(methodNameCriteria))
fun name(methodNameCriteria: NameCriteria) = apply {
check(this.methodNameCriteria == null)
this.methodNameCriteria = methodNameCriteria
}
fun packageName(packageNameCriteria: String) =
packageName(NameCriteria.`is`(packageNameCriteria))
fun packageName(packageNameCriteria: NameCriteria) = apply {
check(this.packageNameCriteria == null)
this.packageNameCriteria = packageNameCriteria
}
fun schema(schemaNameCriteria: String) =
schema(NameCriteria.`is`(schemaNameCriteria))
fun schema(schemaNameCriteria: NameCriteria) = apply {
check(this.schemaNameCriteria == null)
this.schemaNameCriteria = schemaNameCriteria
}
fun withNoParameterConstraint() = apply {
check(this.expectedArgumentTypes.isEmpty())
this.shouldCheckParameters = false
}
fun schemaIsOptional() = apply {
this.schemaIsOptional = true
}
fun addParameter() =
addParameter(PlSqlType.UNKNOWN)
fun addParameter(type: PlSqlType) = apply {
check(this.shouldCheckParameters)
expectedArgumentTypes.add(type)
}
fun addParameters(quantity: Int) = apply {
for (i in 0 until quantity) {
addParameter(PlSqlType.UNKNOWN)
}
}
fun addParameters(vararg types: PlSqlType) = apply {
check(this.shouldCheckParameters)
for (type in types) {
addParameter(type)
}
}
fun getArguments(node: AstNode): List<AstNode> {
val arguments = node.getFirstChildOrNull(PlSqlGrammar.ARGUMENTS)
return arguments?.getChildren(PlSqlGrammar.ARGUMENT) ?: ArrayList()
}
fun getArgumentsValues(node: AstNode) =
getArguments(node).map { it.lastChild }.toList()
fun matches(originalNode: AstNode): Boolean {
val node = normalize(originalNode)
val nodes = node.getChildren(PlSqlGrammar.VARIABLE_NAME, PlSqlGrammar.IDENTIFIER_NAME).toMutableList()
if (nodes.isEmpty()) {
return false
}
var matches = methodNameCriteria?.let { nameAcceptable(nodes.removeAt(nodes.lastIndex), it) } ?: true
packageNameCriteria?.let {
matches = matches and (nodes.isNotEmpty() && nameAcceptable(nodes.removeAt(nodes.lastIndex), it))
}
schemaNameCriteria?.let {
matches = matches and (schemaIsOptional && nodes.isEmpty() || nodes.isNotEmpty() && nameAcceptable(nodes.removeAt(nodes.lastIndex), it))
}
return matches && nodes.isEmpty() && argumentsAcceptable(originalNode)
}
private fun nameAcceptable(node: AstNode, criteria: NameCriteria): Boolean {
methodName = node.tokenOriginalValue
return criteria.matches(methodName)
}
private fun argumentsAcceptable(node: AstNode): Boolean {
val arguments = getArguments(node)
return !shouldCheckParameters || arguments.size == expectedArgumentTypes.size && argumentTypesAreCorrect(arguments)
}
private fun argumentTypesAreCorrect(arguments: List<AstNode>): Boolean {
var result = true
for ((i, type) in expectedArgumentTypes.withIndex()) {
val actualArgument = arguments[i].firstChild
result = result and (type === PlSqlType.UNKNOWN || type === semantic(actualArgument).plSqlType)
}
return result
}
private fun normalize(node: AstNode): AstNode {
if (node.type === PlSqlGrammar.METHOD_CALL || node.type === PlSqlGrammar.CALL_STATEMENT) {
var child = normalize(node.firstChild)
if (child.firstChild.type === PlSqlGrammar.HOST_AND_INDICATOR_VARIABLE) {
child = child.firstChild
}
return child
}
return node
}
companion object {
@JvmStatic
fun create(): MethodMatcher {
return MethodMatcher()
}
fun semantic(node: AstNode): SemanticAstNode {
return node as SemanticAstNode
}
}
}
|
lgpl-3.0
|
40a4023b6b3d71934980a1bb4af284b3
| 33.54878 | 148 | 0.678256 | 4.745394 | false | false | false | false |
fredyw/leetcode
|
src/main/kotlin/leetcode/Problem1797.kt
|
1
|
1066
|
package leetcode
import java.util.*
/**
* https://leetcode.com/problems/design-authentication-manager/
*/
class Problem1797 {
class AuthenticationManager(private val timeToLive: Int) {
private val tokenToExpirationTimeMap = mutableMapOf<String, Int>()
private val expirationTimeSet = TreeSet<Int>()
fun generate(tokenId: String, currentTime: Int) {
tokenToExpirationTimeMap[tokenId] = currentTime + timeToLive
expirationTimeSet += currentTime + timeToLive
}
fun renew(tokenId: String, currentTime: Int) {
val expirationTime = tokenToExpirationTimeMap[tokenId] ?: return
if (currentTime < expirationTime) {
tokenToExpirationTimeMap[tokenId] = currentTime + timeToLive
expirationTimeSet -= expirationTime
expirationTimeSet += currentTime + timeToLive
}
}
fun countUnexpiredTokens(currentTime: Int): Int {
return expirationTimeSet.tailSet(currentTime, false).size
}
}
}
|
mit
|
5036e8a557a8ee13d91f72b1f1218e32
| 33.387097 | 76 | 0.649156 | 4.86758 | false | false | false | false |
alorma/TimelineView
|
timeline/src/main/java/com/alorma/timeline/painter/point/CirclePointStylePainter.kt
|
1
|
1344
|
package com.alorma.timeline.painter.point
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
class CirclePointStylePainter : PointStylePainter() {
private val circleFillPaint: Paint by lazy {
Paint().apply {
flags = Paint.ANTI_ALIAS_FLAG
style = Paint.Style.FILL
}
}
private val circleStrokesPaint: Paint by lazy {
Paint().apply {
flags = Paint.ANTI_ALIAS_FLAG
strokeWidth = 8f
style = Paint.Style.STROKE
}
}
private var fillSize: Float = 0f
override fun initColors(strokeColor: Int, fillColor: Int) {
circleStrokesPaint.color = strokeColor
circleFillPaint.color = fillColor
}
override fun initSizes(strokeSize: Float, fillSize: Float) {
this.fillSize = fillSize
circleStrokesPaint.strokeWidth = strokeSize
}
override fun draw(canvas: Canvas, rect: Rect) {
canvas.drawCircle(
rect.centerX().toFloat(),
rect.centerY().toFloat(),
fillSize / 2,
circleFillPaint
)
canvas.drawCircle(
rect.centerX().toFloat(),
rect.centerY().toFloat(),
fillSize / 2,
circleStrokesPaint
)
}
}
|
apache-2.0
|
6ee40bd90c6ed2d5ceca357c029aad0b
| 25.9 | 64 | 0.584077 | 4.715789 | false | false | false | false |
westnordost/StreetComplete
|
app/src/main/java/de/westnordost/streetcomplete/util/ElementGeometryUtils.kt
|
1
|
2385
|
package de.westnordost.streetcomplete.util
import de.westnordost.osmapi.map.data.LatLon
import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.ktx.forEachLine
import kotlin.math.abs
fun ElementPolylinesGeometry.getOrientationAtCenterLineInDegrees(): Float {
val centerLine = polylines.first().centerLineOfPolyline()
return centerLine.first.initialBearingTo(centerLine.second).toFloat()
}
/** Returns whether any individual line segment in this ElementPolylinesGeometry is both within
* [maxDistance]m of any line segments of [others] and also
* and "aligned", meaning the angle difference is at most the given [maxAngle]
*
* Warning: This is computationally very expensive ( for normal ways, O(n³) ), avoid if possible */
fun ElementPolylinesGeometry.isNearAndAligned(
maxDistance: Double,
maxAngle: Double,
others: Iterable<ElementPolylinesGeometry>
): Boolean {
val bounds = getBounds().enlargedBy(maxDistance)
return others.any { other ->
bounds.intersect(other.getBounds()) &&
polylines.any { polyline ->
other.polylines.any { otherPolyline ->
polyline.isWithinDistanceAndAngleOf(otherPolyline, maxDistance, maxAngle)
}
}
}
}
private fun List<LatLon>.isWithinDistanceAndAngleOf(other: List<LatLon>, maxDistance: Double, maxAngle: Double): Boolean {
forEachLine { first, second ->
other.forEachLine { otherFirst, otherSecond ->
val bearing = first.initialBearingTo(second)
val otherBearing = otherFirst.initialBearingTo(otherSecond)
val bearingDiff = abs((bearing - otherBearing).normalizeDegrees(-180.0))
// two ways directly opposite each other should count as aligned
val alignmentDiff = if (bearingDiff > 90) 180 - bearingDiff else bearingDiff
val distance = first.distanceToArc(otherFirst, otherSecond)
if (alignmentDiff <= maxAngle && distance <= maxDistance)
return true
}
}
return false
}
fun ElementPolylinesGeometry.intersects(other: ElementPolylinesGeometry): Boolean =
getBounds().intersect(other.getBounds()) &&
polylines.any { polyline ->
other.polylines.any { otherPolyline ->
polyline.intersectsWith(otherPolyline)
}
}
|
gpl-3.0
|
0ec02d5f0fe9b564ab0769d56c68d1a3
| 40.824561 | 122 | 0.709312 | 4.638132 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/psi/shadow/XpmShadowPsiElement.kt
|
1
|
3136
|
/*
* Copyright (C) 2020-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpm.psi.shadow
import com.intellij.lang.ASTNode
import com.intellij.lang.Language
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFile
import com.intellij.psi.impl.light.LightElement
import com.intellij.psi.util.elementType
import uk.co.reecedunn.intellij.plugin.core.sequences.ancestors
import uk.co.reecedunn.intellij.plugin.core.sequences.reverse
import uk.co.reecedunn.intellij.plugin.core.sequences.siblings
import javax.swing.Icon
open class XpmShadowPsiElement(private val shadowed: PsiElement, language: Language) :
LightElement(shadowed.manager, language) {
// region LightElement
override fun getParent(): PsiElement? {
return shadowed.ancestors().map { XpmShadowPsiElementFactory.create(it) }.firstOrNull()
}
override fun getChildren(): Array<PsiElement> {
return shadowed.children.mapNotNull { XpmShadowPsiElementFactory.create(it) }.toTypedArray()
}
override fun getContainingFile(): PsiFile? = shadowed.containingFile
override fun getTextRange(): TextRange? = shadowed.textRange
override fun getStartOffsetInParent(): Int = shadowed.startOffsetInParent
override fun textToCharArray(): CharArray = shadowed.textToCharArray()
override fun textMatches(text: CharSequence): Boolean = shadowed.textMatches(text)
override fun textMatches(element: PsiElement): Boolean = shadowed.textMatches(element)
override fun findElementAt(offset: Int): PsiElement? = shadowed.findElementAt(offset)
override fun getTextOffset(): Int = shadowed.textOffset
override fun getNode(): ASTNode? = shadowed.node
override fun getText(): String? = shadowed.text
override fun accept(visitor: PsiElementVisitor): Unit = shadowed.accept(visitor)
override fun copy(): PsiElement? = XpmShadowPsiElementFactory.create(shadowed.copy())
override fun getNavigationElement(): PsiElement = shadowed.navigationElement
override fun getPrevSibling(): PsiElement? {
return reverse(shadowed.siblings()).mapNotNull { XpmShadowPsiElementFactory.create(it) }.firstOrNull()
}
override fun getNextSibling(): PsiElement? {
return shadowed.siblings().mapNotNull { XpmShadowPsiElementFactory.create(it) }.firstOrNull()
}
override fun getIcon(flags: Int): Icon? = shadowed.getIcon(flags)
override fun toString(): String = "${javaClass.simpleName}($elementType)"
// endregion
}
|
apache-2.0
|
4b267e5e19691497263ea2d206efe2bc
| 37.243902 | 110 | 0.758291 | 4.666667 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/lang-xpm/main/uk/co/reecedunn/intellij/plugin/xpm/ide/structureView/XmlStructureViewTreeElement.kt
|
1
|
1718
|
/*
* Copyright (C) 2020-2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpm.ide.structureView
import com.intellij.ide.structureView.impl.xml.XmlTagTreeElement
import com.intellij.openapi.util.Iconable
import com.intellij.psi.PsiFile
import com.intellij.psi.xml.XmlTag
import uk.co.reecedunn.intellij.plugin.xpm.psi.shadow.XpmShadowPsiElementFactory
import javax.swing.Icon
class XmlStructureViewTreeElement(tag: XmlTag) : XmlTagTreeElement(tag) {
override fun getPresentableText(): String? {
val element = element ?: return super.getPresentableText()
val id = toCanonicalForm(element.getAttributeValue("id") ?: element.getAttributeValue("name"))
return id?.let { "$id [${element.name}]" } ?: element.name // Fix IDEA-247202
}
override fun getIcon(open: Boolean): Icon? = element?.let {
val file = element as? PsiFile
val flags = when {
file == null || !file.isWritable -> Iconable.ICON_FLAG_READ_STATUS or Iconable.ICON_FLAG_VISIBILITY
else -> Iconable.ICON_FLAG_READ_STATUS
}
return (XpmShadowPsiElementFactory.create(it) ?: it).getIcon(flags)
}
}
|
apache-2.0
|
071ffd80665c153506c4351c691c2e61
| 41.95 | 111 | 0.721187 | 4.129808 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/StepperValueFormView.kt
|
1
|
3860
|
package com.habitrpg.android.habitica.ui.views.tasks.form
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.RelativeLayout
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.FormStepperValueBinding
import com.habitrpg.android.habitica.extensions.OnChangeTextWatcher
import com.habitrpg.android.habitica.extensions.asDrawable
import com.habitrpg.common.habitica.extensions.layoutInflater
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import java.text.DecimalFormat
class StepperValueFormView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
private val binding = FormStepperValueBinding.inflate(context.layoutInflater, this)
var onValueChanged: ((Double) -> Unit)? = null
private val decimalFormat = DecimalFormat("0.###")
private var editTextIsFocused = false
var value = 0.0
set(new) {
var newValue = if (new >= minValue) new else minValue
maxValue?.let {
if (newValue > it && it > 0) {
newValue = it
}
}
val oldValue = field
field = newValue
if (oldValue != new) {
valueString = decimalFormat.format(newValue)
}
binding.downButton.isEnabled = field > minValue
maxValue?.let {
if (it == 0.0) return@let
binding.upButton.isEnabled = value < it
}
onValueChanged?.invoke(value)
}
var maxValue: Double? = null
var minValue: Double = 0.0
private var valueString = ""
set(value) {
val hasChanged = field != value || binding.editText.text.toString() != field
field = value
if (value.isEmpty()) {
onValueChanged?.invoke(0.0)
return
}
if (hasChanged) {
binding.editText.setText(field)
if (editTextIsFocused) {
binding.editText.setSelection(field.length)
}
}
val newValue = field.toDoubleOrNull() ?: 0.0
if (this.value != newValue || hasChanged) {
this.value = newValue
}
}
var iconDrawable: Drawable?
get() {
return binding.editText.compoundDrawables.firstOrNull()
}
set(value) {
binding.editText.setCompoundDrawablesWithIntrinsicBounds(value, null, null, null)
}
init {
val attributes = context.theme?.obtainStyledAttributes(
attrs,
R.styleable.StepperValueFormView,
0, 0
)
// set value here, so that the setter is called and everything is set up correctly
maxValue = attributes?.getFloat(R.styleable.StepperValueFormView_maxValue, 0f)?.toDouble()
minValue = attributes?.getFloat(R.styleable.StepperValueFormView_minValue, 0f)?.toDouble() ?: 0.0
value = attributes?.getFloat(R.styleable.StepperValueFormView_defaultValue, 10.0f)?.toDouble() ?: 10.0
iconDrawable = attributes?.getDrawable(R.styleable.StepperValueFormView_iconDrawable) ?: HabiticaIconsHelper.imageOfGold().asDrawable(context.resources)
binding.upButton.setOnClickListener {
value += 1
}
binding.downButton.setOnClickListener {
value -= 1
}
binding.editText.addTextChangedListener(
OnChangeTextWatcher { s, _, _, _ ->
valueString = s.toString()
}
)
binding.editText.setOnFocusChangeListener { _, hasFocus -> editTextIsFocused = hasFocus }
}
}
|
gpl-3.0
|
5ce63242b2ffd14a63092d1b25af944c
| 34.740741 | 160 | 0.615026 | 5.065617 | false | false | false | false |
WangDaYeeeeee/GeometricWeather
|
app/src/main/java/wangdaye/com/geometricweather/common/basic/models/options/appearance/HourlyTrendDisplay.kt
|
1
|
2315
|
package wangdaye.com.geometricweather.common.basic.models.options.appearance
import android.content.Context
import android.text.TextUtils
import androidx.annotation.StringRes
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.basic.models.options._basic.BaseEnum
enum class HourlyTrendDisplay(
override val id: String,
@StringRes val nameId: Int
): BaseEnum {
TAG_TEMPERATURE("temperature", R.string.temperature),
TAG_WIND("wind", R.string.wind),
TAG_UV_INDEX("uv_index", R.string.uv_index),
TAG_PRECIPITATION("precipitation", R.string.precipitation);
companion object {
@JvmStatic
fun toHourlyTrendDisplayList(
value: String
) = if (TextUtils.isEmpty(value)) {
ArrayList()
} else try {
val cards = value.split("&").toTypedArray()
val list: MutableList<HourlyTrendDisplay> = ArrayList()
for (card in cards) {
when (card) {
"temperature" -> list.add(TAG_TEMPERATURE)
"wind" -> list.add(TAG_WIND)
"uv_index" -> list.add(TAG_UV_INDEX)
"precipitation" -> list.add(TAG_PRECIPITATION)
}
}
list
} catch (e: Exception) {
ArrayList()
}
@JvmStatic
fun toValue(list: List<HourlyTrendDisplay>): String {
val builder = StringBuilder()
for (v in list) {
builder.append("&").append(v.id)
}
if (builder.isNotEmpty() && builder[0] == '&') {
builder.deleteCharAt(0)
}
return builder.toString()
}
@JvmStatic
fun getSummary(context: Context, list: List<HourlyTrendDisplay>): String {
val builder = StringBuilder()
for (item in list) {
builder.append(",").append(item.getName(context))
}
if (builder.isNotEmpty() && builder[0] == ',') {
builder.deleteCharAt(0)
}
return builder.toString().replace(",", ", ")
}
}
override val valueArrayId = 0
override val nameArrayId = 0
override fun getName(context: Context) = context.getString(nameId)
}
|
lgpl-3.0
|
e292443c58f502d36433e55b3db1a76b
| 31.619718 | 82 | 0.563715 | 4.503891 | false | false | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/codegen/coroutines/controlFlow_tryCatch5.kt
|
1
|
1131
|
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("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 {
result = try {
s2()
} catch (t: Throwable) {
val x = s1()
println(t.message)
x
}
}
println(result)
}
|
apache-2.0
|
fc0aaa952e52613c2a87bc0c57fa08d7
| 19.581818 | 115 | 0.621574 | 3.927083 | false | false | false | false |
hitoshura25/Media-Player-Omega-Android
|
app/src/main/java/com/vmenon/mpo/MPOApplication.kt
|
1
|
4165
|
package com.vmenon.mpo
import android.content.Context
import androidx.multidex.MultiDex
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.google.android.play.core.splitcompat.SplitCompat
import com.google.android.play.core.splitcompat.SplitCompatApplication
import com.vmenon.mpo.auth.framework.di.dagger.AuthComponent
import com.vmenon.mpo.auth.framework.di.dagger.AuthComponentProvider
import com.vmenon.mpo.common.framework.di.dagger.*
import com.vmenon.mpo.core.work.RetryDownloadWorker
import com.vmenon.mpo.di.*
import com.vmenon.mpo.core.work.UpdateAllShowsWorker
import com.vmenon.mpo.downloads.framework.di.dagger.DaggerDownloadsFrameworkComponent
import com.vmenon.mpo.my_library.framework.di.dagger.DaggerLibraryFrameworkComponent
import com.vmenon.mpo.player.framework.di.dagger.DaggerPlayerFrameworkComponent
import com.vmenon.mpo.player.framework.di.dagger.PlayerFrameworkComponent
import com.vmenon.mpo.player.framework.di.dagger.PlayerFrameworkComponentProvider
import com.vmenon.mpo.system.framework.di.dagger.SystemFrameworkComponentProvider
import com.vmenon.mpo.system.framework.di.dagger.SystemFrameworkComponent
import java.util.concurrent.TimeUnit
open class MPOApplication : SplitCompatApplication(),
CommonFrameworkComponentProvider, SystemFrameworkComponentProvider, AuthComponentProvider,
PlayerFrameworkComponentProvider, AppComponentProvider {
private lateinit var appComponent: AppComponent
private lateinit var playerFrameworkComponent: PlayerFrameworkComponent
private lateinit var componentProviders: DaggerComponentProviders
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
MultiDex.install(this)
SplitCompat.install(this)
}
override fun onCreate() {
super.onCreate()
componentProviders = createComponentProviders()
val downloadsFrameworkComponent = DaggerDownloadsFrameworkComponent.builder()
.commonFrameworkComponent(commonFrameworkComponent())
.build()
val libraryFrameworkComponent = DaggerLibraryFrameworkComponent.builder()
.commonFrameworkComponent(commonFrameworkComponent())
.build()
appComponent = DaggerAppComponent.builder()
.commonFrameworkComponent(commonFrameworkComponent())
.downloadsFrameworkComponent(downloadsFrameworkComponent)
.libraryFrameworkComponent(libraryFrameworkComponent)
.build()
appComponent.thirdPartyIntegrator().initialize(this)
playerFrameworkComponent = DaggerPlayerFrameworkComponent.builder()
.commonFrameworkComponent(commonFrameworkComponent())
.build()
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"Update",
ExistingPeriodicWorkPolicy.KEEP,
PeriodicWorkRequestBuilder<UpdateAllShowsWorker>(
repeatInterval = 15,
repeatIntervalTimeUnit = TimeUnit.MINUTES
).build()
)
WorkManager.getInstance(this).enqueueUniquePeriodicWork(
"RetryDownloads",
ExistingPeriodicWorkPolicy.KEEP,
PeriodicWorkRequestBuilder<RetryDownloadWorker>(
repeatInterval = 15,
repeatIntervalTimeUnit = TimeUnit.MINUTES
).build()
)
}
protected open fun createComponentProviders(): DaggerComponentProviders =
DaggerComponentProviders(
this, "https://mpospboot.herokuapp.com/" // "http://10.0.0.208:8080/"
)
override fun commonFrameworkComponent(): CommonFrameworkComponent =
componentProviders.commonFrameworkComponent
override fun systemFrameworkComponent(): SystemFrameworkComponent =
componentProviders.systemFrameworkComponent
override fun authComponent(): AuthComponent =
componentProviders.authComponent
override fun playerFrameworkComponent(): PlayerFrameworkComponent =
playerFrameworkComponent
override fun appComponent(): AppComponent = appComponent
}
|
apache-2.0
|
986799044432a461f6c255de2e7c5c61
| 41.5 | 94 | 0.756543 | 5.729023 | false | false | false | false |
LWJGL/lwjgl3
|
modules/lwjgl/glfw/src/templates/kotlin/glfw/GLFWTypes.kt
|
1
|
29397
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package glfw
import org.lwjgl.generator.*
val GLFW_BINDING = simpleBinding(
Module.GLFW,
libraryExpression = """Configuration.GLFW_LIBRARY_NAME.get(Platform.mapLibraryNameBundled("glfw"))""",
bundledWithLWJGL = true
)
val GLFW_BINDING_DELEGATE = GLFW_BINDING.delegate("GLFW.getLibrary()")
val GLFWmonitor = "GLFWmonitor".opaque
val GLFWwindow = "GLFWwindow".opaque
val GLFWvidmode = struct(Module.GLFW, "GLFWVidMode", nativeName = "GLFWvidmode", mutable = false) {
documentation = "Describes a single video mode."
int("width", "the width, in screen coordinates, of the video mode")
int("height", "the height, in screen coordinates, of the video mode")
int("redBits", "the bit depth of the red channel of the video mode")
int("greenBits", "the bit depth of the green channel of the video mode")
int("blueBits", "the bit depth of the blue channel of the video mode")
int("refreshRate", "the refresh rate, in Hz, of the video mode")
}
val GLFWgammaramp = struct(Module.GLFW, "GLFWGammaRamp", nativeName = "GLFWgammaramp") {
documentation = "Describes the gamma ramp for a monitor."
since = "version 3.0"
unsigned_short.p("red", "an array of values describing the response of the red channel")
unsigned_short.p("green", "an array of values describing the response of the green channel")
unsigned_short.p("blue", "an array of values describing the response of the blue channel")
AutoSize("red", "green", "blue")..unsigned_int("size", "the number of elements in each array")
}
val GLFWcursor = "GLFWcursor".opaque
val GLFWimage = struct(Module.GLFW, "GLFWImage", nativeName = "GLFWimage") {
documentation =
"""
Image data.
This describes a single 2D image. See the documentation for each related function to see what the expected pixel format is.
"""
since = "version 2.1"
int("width", "the width, in pixels, of this image")
int("height", "the height, in pixels, of this image")
unsigned_char.p("pixels", "the pixel data of this image, arranged left-to-right, top-to-bottom")
}
val GLFWgamepadstate = struct(Module.GLFW, "GLFWGamepadState", nativeName = "GLFWgamepadstate") {
documentation = "Describes the input state of a gamepad."
since = "version 3.3"
unsigned_char("buttons", "the states of each gamepad button, #PRESS or #RELEASE")[15]
float("axes", "the states of each gamepad axis, in the range -1.0 to 1.0 inclusive")[6]
}
// callback functions
val GLFWallocatefun = Module.GLFW.callback {
void.p(
"GLFWAllocateCallback",
"Will be called for memory allocation requests.",
size_t("size", "the minimum size, in bytes, of the memory block"),
opaque_p("user", "the user-defined pointer from the allocator"),
returnDoc = "the address of the newly allocated memory block, or #NULL if an error occurred",
nativeType = "GLFWallocatefun"
) {
documentation =
"""
The function pointer type for memory allocation callbacks.
This is the function pointer type for memory allocation callbacks. A memory allocation callback function has the following signature:
${codeBlock("""
void* function_name(size_t size, void* user)""")}
This function must return either a memory block at least {@code size} bytes long, or #NULL if allocation failed. Note that not all parts of GLFW
handle allocation failures gracefully yet.
This function may be called during #Init() but before the library is flagged as initialized, as well as during #Terminate() after the library is no
longer flagged as initialized.
Any memory allocated by this function will be deallocated during library termination or earlier.
The size will always be greater than zero. Allocations of size zero are filtered out before reaching the custom allocator.
${note(ul(
"The returned memory block must be valid at least until it is deallocated.",
"This function should not call any GLFW function.",
"This function may be called from any thread that calls GLFW functions."
))}
"""
since = "version 3.4"
}
}
val GLFWreallocatefun = Module.GLFW.callback {
void.p(
"GLFWReallocateCallback",
"Will be called for memory reallocation requests.",
Unsafe..void.p("block", "the address of the memory block to reallocate"),
size_t("size", "the new minimum size, in bytes, of the memory block"),
opaque_p("user", "the user-defined pointer from the allocator"),
returnDoc = "the address of the newly allocated or resized memory block, or #NULL if an error occurred",
nativeType = "GLFWreallocatefun"
) {
documentation =
"""
The function pointer type for memory reallocation callbacks.
This is the function pointer type for memory reallocation callbacks. A memory reallocation callback function has the following signature:
${codeBlock("""
void* function_name(void* block, size_t size, void* user) """)}
This function must return a memory block at least {@code size} bytes long, or #NULL if allocation failed. Note that not all parts of GLFW handle
allocation failures gracefully yet.
This function may be called during #Init() but before the library is flagged as initialized, as well as during #Terminate() after the library is no
longer flagged as initialized.
Any memory allocated by this function will be deallocated during library termination or earlier.
The block address will never be #NULL and the size will always be greater than zero. Reallocations of a block to size zero are converted into
deallocations. Reallocations of #NULL to a non-zero size are converted into regular allocations.
${note(ul(
"The returned memory block must be valid at least until it is deallocated.",
"This function should not call any GLFW function.",
"This function may be called from any thread that calls GLFW functions."
))}
"""
since = "version 3.4"
}
}
val GLFWdeallocatefun = Module.GLFW.callback {
void(
"GLFWDeallocateCallback",
"Will be called for memory deallocation requests.",
Unsafe..void.p("block", "the address of the memory block to deallocate"),
opaque_p("user", "the user-defined pointer from the allocator"),
nativeType = "GLFWdeallocatefun"
) {
documentation =
"""
The function pointer type for memory deallocation callbacks.
This is the function pointer type for memory deallocation callbacks. A memory deallocation callback function has the following signature:
${codeBlock("""
void function_name(void* block, void* user)""")}
This function may deallocate the specified memory block. This memory block will have been allocated with the same allocator.
This function may be called during #Init() but before the library is flagged as initialized, as well as during #Terminate() after the library is no
longer flagged as initialized.
The block address will never be #NULL. Deallocations of #NULL are filtered out before reaching the custom allocator.
${note(ul(
"The specified memory block will not be accessed by GLFW after this function is called.",
"This function should not call any GLFW function.",
"This function may be called from any thread that calls GLFW functions."
))}
"""
since = "version 3.4"
}
}
val GLFWerrorfun = Module.GLFW.callback {
void(
"GLFWErrorCallback",
"Will be called with an error code and a human-readable description when a GLFW error occurs.",
int("error", "the error code"),
NullTerminated..charUTF8.p("description", "a pointer to a UTF-8 encoded string describing the error"),
nativeType = "GLFWerrorfun"
) {
documentation = "Instances of this interface may be passed to the #SetErrorCallback() method."
since = "version 3.0"
javaImport(
"java.io.PrintStream",
"java.util.Map",
"static org.lwjgl.glfw.GLFW.*"
)
additionalCode = """
/**
* Converts the specified {@code GLFWErrorCallback} argument to a String.
*
* <p>This method may only be used inside a GLFWErrorCallback invocation.</p>
*
* @param description pointer to the UTF-8 encoded description string
*
* @return the description as a String
*/
public static String getDescription(long description) {
return memUTF8(description);
}
/**
* Returns a {@code GLFWErrorCallback} instance that prints the error to the {@link APIUtil#DEBUG_STREAM}.
*
* @return the GLFWerrorCallback
*/
public static GLFWErrorCallback createPrint() {
return createPrint(APIUtil.DEBUG_STREAM);
}
/**
* Returns a {@code GLFWErrorCallback} instance that prints the error in the specified {@link PrintStream}.
*
* @param stream the PrintStream to use
*
* @return the GLFWerrorCallback
*/
public static GLFWErrorCallback createPrint(PrintStream stream) {
return new GLFWErrorCallback() {
private Map<Integer, String> ERROR_CODES = APIUtil.apiClassTokens((field, value) -> 0x10000 < value && value < 0x20000, null, GLFW.class);
@Override
public void invoke(int error, long description) {
String msg = getDescription(description);
StringBuilder sb = new StringBuilder(512);
sb
.append("[LWJGL] ")
.append(ERROR_CODES.get(error))
.append(" error\n")
.append("\tDescription : ")
.append(msg)
.append("\n")
.append("\tStacktrace :\n");
StackTraceElement[] stack = Thread.currentThread().getStackTrace();
for (int i = 4; i < stack.length; i++) {
sb.append("\t\t");
sb.append(stack[i]);
sb.append("\n");
}
stream.print(sb);
}
};
}
/**
* Returns a {@code GLFWErrorCallback} instance that throws an {@link IllegalStateException} when an error occurs.
*
* @return the GLFWerrorCallback
*/
public static GLFWErrorCallback createThrow() {
return new GLFWErrorCallback() {
@Override
public void invoke(int error, long description) {
throw new IllegalStateException(String.format("GLFW error [0x%X]: %s", error, getDescription(description)));
}
};
}
/** See {@link GLFW#glfwSetErrorCallback SetErrorCallback}. */
public GLFWErrorCallback set() {
glfwSetErrorCallback(this);
return this;
}
"""
}
}
val GLFWallocator = struct(Module.GLFW, "GLFWAllocator", nativeName = "GLFWallocator") {
documentation = "A custom memory allocator that can be set with #InitAllocator()."
since = "version 3.4"
GLFWallocatefun("allocate", "the memory allocation callback")
GLFWreallocatefun("reallocate", "the memory reallocation callback")
GLFWdeallocatefun("deallocate", "the memory deallocation callback")
nullable..opaque_p("user", "a user-defined pointer that will be passed to the callbacks")
}
val GLFWmonitorfun = Module.GLFW.callback {
void(
"GLFWMonitorCallback",
"Will be called when a monitor is connected to or disconnected from the system.",
GLFWmonitor.p("monitor", "the monitor that was connected or disconnected"),
int("event", "one of #CONNECTED or #DISCONNECTED. Remaining values reserved for future use."),
nativeType = "GLFWmonitorfun"
) {
documentation = "Instances of this interface may be passed to the #SetMonitorCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetMonitorCallback SetMonitorCallback}. */
public GLFWMonitorCallback set() {
glfwSetMonitorCallback(this);
return this;
}
"""
}
}
val GLFWjoystickfun = Module.GLFW.callback {
void(
"GLFWJoystickCallback",
"Will be called when a joystick is connected to or disconnected from the system.",
int("jid", "the joystick that was connected or disconnected"),
int("event", "one of #CONNECTED or #DISCONNECTED. Remaining values reserved for future use."),
nativeType = "GLFWjoystickfun"
) {
documentation = "Instances of this interface may be passed to the #SetJoystickCallback() method."
since = "version 3.2"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetJoystickCallback SetJoystickCallback}. */
public GLFWJoystickCallback set() {
glfwSetJoystickCallback(this);
return this;
}
"""
}
}
val GLFWwindowposfun = Module.GLFW.callback {
void(
"GLFWWindowPosCallback",
"Will be called when the specified window moves.",
GLFWwindow.p("window", "the window that was moved"),
int("xpos", "the new x-coordinate, in screen coordinates, of the upper-left corner of the content area of the window"),
int("ypos", "the new y-coordinate, in screen coordinates, of the upper-left corner of the content area of the window"),
nativeType = "GLFWwindowposfun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowPosCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowPosCallback SetWindowPosCallback}. */
public GLFWWindowPosCallback set(long window) {
glfwSetWindowPosCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowsizefun = Module.GLFW.callback {
void(
"GLFWWindowSizeCallback",
"Will be called when the specified window is resized.",
GLFWwindow.p("window", "the window that was resized"),
int("width", "the new width, in screen coordinates, of the window"),
int("height", "the new height, in screen coordinates, of the window"),
nativeType = "GLFWwindowsizefun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowSizeCallback() method."
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowSizeCallback SetWindowSizeCallback}. */
public GLFWWindowSizeCallback set(long window) {
glfwSetWindowSizeCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowclosefun = Module.GLFW.callback {
void(
"GLFWWindowCloseCallback",
"Will be called when the user attempts to close the specified window, for example by clicking the close widget in the title bar.",
GLFWwindow.p("window", "the window that the user attempted to close"),
nativeType = "GLFWwindowclosefun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowCloseCallback() method."
since = "version 2.5"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowCloseCallback SetWindowCloseCallback}. */
public GLFWWindowCloseCallback set(long window) {
glfwSetWindowCloseCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowrefreshfun = Module.GLFW.callback {
void(
"GLFWWindowRefreshCallback",
"""
Will be called when the client area of the specified window needs to be redrawn, for example if the window has been exposed after having been covered by
another window.
""",
GLFWwindow.p("window", "the window whose content needs to be refreshed"),
nativeType = "GLFWwindowrefreshfun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowRefreshCallback() method."
since = "version 2.5"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowRefreshCallback SetWindowRefreshCallback}. */
public GLFWWindowRefreshCallback set(long window) {
glfwSetWindowRefreshCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowfocusfun = Module.GLFW.callback {
void(
"GLFWWindowFocusCallback",
"Will be called when the specified window gains or loses focus.",
GLFWwindow.p("window", "the window that was focused or defocused"),
intb("focused", "#TRUE if the window was focused, or #FALSE if it was defocused"),
nativeType = "GLFWwindowfocusfun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowFocusCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowFocusCallback SetWindowFocusCallback}. */
public GLFWWindowFocusCallback set(long window) {
glfwSetWindowFocusCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowiconifyfun = Module.GLFW.callback {
void(
"GLFWWindowIconifyCallback",
"Will be called when the specified window is iconified or restored.",
GLFWwindow.p("window", "the window that was iconified or restored."),
intb("iconified", "#TRUE if the window was iconified, or #FALSE if it was restored"),
nativeType = "GLFWwindowiconifyfun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowIconifyCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowIconifyCallback SetWindowIconifyCallback}. */
public GLFWWindowIconifyCallback set(long window) {
glfwSetWindowIconifyCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowmaximizefun = Module.GLFW.callback {
void(
"GLFWWindowMaximizeCallback",
"Will be called when the specified window is maximized or restored.",
GLFWwindow.p("window", "the window that was maximized or restored."),
intb("maximized", "#TRUE if the window was maximized, or #FALSE if it was restored"),
nativeType = "GLFWwindowmaximizefun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowMaximizeCallback() method."
since = "version 3.3"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowMaximizeCallback SetWindowMaximizeCallback}. */
public GLFWWindowMaximizeCallback set(long window) {
glfwSetWindowMaximizeCallback(window, this);
return this;
}
"""
}
}
val GLFWframebuffersizefun = Module.GLFW.callback {
void(
"GLFWFramebufferSizeCallback",
"Will be called when the framebuffer of the specified window is resized.",
GLFWwindow.p("window", "the window whose framebuffer was resized"),
int("width", "the new width, in pixels, of the framebuffer"),
int("height", "the new height, in pixels, of the framebuffer"),
nativeType = "GLFWframebuffersizefun"
) {
documentation = "Instances of this interface may be passed to the #SetFramebufferSizeCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetFramebufferSizeCallback SetFramebufferSizeCallback}. */
public GLFWFramebufferSizeCallback set(long window) {
glfwSetFramebufferSizeCallback(window, this);
return this;
}
"""
}
}
val GLFWwindowcontentscalefun = Module.GLFW.callback {
void(
"GLFWWindowContentScaleCallback",
"Will be called when the window content scale changes.",
GLFWwindow.p("window", "the window whose content scale changed"),
float("xscale", "the new x-axis content scale of the window"),
float("yscale", "the new y-axis content scale of the window"),
nativeType = "GLFWwindowcontentscalefun"
) {
documentation = "Instances of this interface may be passed to the #SetWindowContentScaleCallback() method."
since = "version 3.3"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetWindowContentScaleCallback SetWindowContentScaleCallback}. */
public GLFWWindowContentScaleCallback set(long window) {
glfwSetWindowContentScaleCallback(window, this);
return this;
}
"""
}
}
val GLFWkeyfun = Module.GLFW.callback {
void(
"GLFWKeyCallback",
"Will be called when a key is pressed, repeated or released.",
GLFWwindow.p("window", "the window that received the event"),
int("key", "the keyboard key that was pressed or released"),
int("scancode", "the platform-specific scancode of the key"),
int("action", "the key action", "#PRESS #RELEASE #REPEAT"),
int("mods", "bitfield describing which modifiers keys were held down"),
nativeType = "GLFWkeyfun"
) {
documentation = "Instances of this interface may be passed to the #SetKeyCallback() method."
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetKeyCallback SetKeyCallback}. */
public GLFWKeyCallback set(long window) {
glfwSetKeyCallback(window, this);
return this;
}
"""
}
}
val GLFWcharfun = Module.GLFW.callback {
void(
"GLFWCharCallback",
"Will be called when a Unicode character is input.",
GLFWwindow.p("window", "the window that received the event"),
unsigned_int("codepoint", "the Unicode code point of the character"),
nativeType = "GLFWcharfun"
) {
documentation = "Instances of this interface may be passed to the #SetCharCallback() method."
since = "version 2.4"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetCharCallback SetCharCallback}. */
public GLFWCharCallback set(long window) {
glfwSetCharCallback(window, this);
return this;
}
"""
}
}
val GLFWcharmodsfun = Module.GLFW.callback {
void(
"GLFWCharModsCallback",
"Will be called when a Unicode character is input regardless of what modifier keys are used.",
GLFWwindow.p("window", "the window that received the event"),
unsigned_int("codepoint", "the Unicode code point of the character"),
int("mods", "bitfield describing which modifier keys were held down"),
nativeType = "GLFWcharmodsfun"
) {
documentation =
"""
Instances of this interface may be passed to the #SetCharModsCallback() method.
Deprecared: scheduled for removal in version 4.0.
"""
since = "version 3.1"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetCharModsCallback SetCharModsCallback}. */
public GLFWCharModsCallback set(long window) {
glfwSetCharModsCallback(window, this);
return this;
}
"""
}
}
val GLFWmousebuttonfun = Module.GLFW.callback {
void(
"GLFWMouseButtonCallback",
"Will be called when a mouse button is pressed or released.",
GLFWwindow.p("window", "the window that received the event"),
int("button", "the mouse button that was pressed or released"),
int("action", "the button action", "#PRESS #RELEASE"),
int("mods", "bitfield describing which modifiers keys were held down"),
nativeType = "GLFWmousebuttonfun"
) {
documentation = "Instances of this interface may be passed to the #SetMouseButtonCallback() method."
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetMouseButtonCallback SetMouseButtonCallback}. */
public GLFWMouseButtonCallback set(long window) {
glfwSetMouseButtonCallback(window, this);
return this;
}
"""
}
}
val GLFWcursorposfun = Module.GLFW.callback {
void(
"GLFWCursorPosCallback",
"""
Will be called when the cursor is moved.
The callback function receives the cursor position, measured in screen coordinates but relative to the top-left corner of the window client area. On
platforms that provide it, the full sub-pixel cursor position is passed on.
""",
GLFWwindow.p("window", "the window that received the event"),
double("xpos", "the new cursor x-coordinate, relative to the left edge of the content area"),
double("ypos", "the new cursor y-coordinate, relative to the top edge of the content area"),
nativeType = "GLFWcursorposfun"
) {
documentation = "Instances of this interface may be passed to the #SetCursorPosCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetCursorPosCallback SetCursorPosCallback}. */
public GLFWCursorPosCallback set(long window) {
glfwSetCursorPosCallback(window, this);
return this;
}
"""
}
}
val GLFWcursorenterfun = Module.GLFW.callback {
void(
"GLFWCursorEnterCallback",
"Will be called when the cursor enters or leaves the client area of the window.",
GLFWwindow.p("window", "the window that received the event"),
intb("entered", "#TRUE if the cursor entered the window's content area, or #FALSE if it left it"),
nativeType = "GLFWcursorenterfun"
) {
documentation = "Instances of this interface may be passed to the #SetCursorEnterCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetCursorEnterCallback SetCursorEnterCallback}. */
public GLFWCursorEnterCallback set(long window) {
glfwSetCursorEnterCallback(window, this);
return this;
}
"""
}
}
val GLFWscrollfun = Module.GLFW.callback {
void(
"GLFWScrollCallback",
"Will be called when a scrolling device is used, such as a mouse wheel or scrolling area of a touchpad.",
GLFWwindow.p("window", "the window that received the event"),
double("xoffset", "the scroll offset along the x-axis"),
double("yoffset", "the scroll offset along the y-axis"),
nativeType = "GLFWscrollfun"
) {
documentation = "Instances of this interface may be passed to the #SetScrollCallback() method."
since = "version 3.0"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/** See {@link GLFW#glfwSetScrollCallback SetScrollCallback}. */
public GLFWScrollCallback set(long window) {
glfwSetScrollCallback(window, this);
return this;
}
"""
}
}
val GLFWdropfun = Module.GLFW.callback {
void(
"GLFWDropCallback",
"Will be called when one or more dragged files are dropped on the window.",
GLFWwindow.p("window", "the window that received the event"),
AutoSize("names")..int("count", "the number of dropped files"),
char.const.p.p("names", "pointer to the array of UTF-8 encoded path names of the dropped files"),
nativeType = "GLFWdropfun"
) {
documentation = "Instances of this interface may be passed to the #SetDropCallback() method."
since = "version 3.1"
javaImport("static org.lwjgl.glfw.GLFW.*")
additionalCode = """
/**
* Decodes the specified {@link GLFWDropCallback} arguments to a String.
*
* <p>This method may only be used inside a {@code GLFWDropCallback} invocation.</p>
*
* @param names pointer to the array of UTF-8 encoded path names of the dropped files
* @param index the index to decode
*
* @return the name at the specified index as a String
*/
public static String getName(long names, int index) {
return memUTF8(memGetAddress(names + Pointer.POINTER_SIZE * index));
}
/** See {@link GLFW#glfwSetDropCallback SetDropCallback}. */
public GLFWDropCallback set(long window) {
glfwSetDropCallback(window, this);
return this;
}
"""
}
}
// OpenGL
val GLFWglproc = "GLFWglproc".handle
// Vulkan
val GLFWvkproc = "GLFWvkproc".handle
|
bsd-3-clause
|
fe7509413b5c180ecdaa036b6c90b9c5
| 37.328553 | 160 | 0.646699 | 4.62217 | false | false | false | false |
jmonad/kaybe
|
kaybe/src/main/java/com/jmonad/kaybe/Just.kt
|
1
|
373
|
package com.jmonad.kaybe
class Just<A>(value : A) : IMaybe<A> {
val value = value
override fun <B> bind(fn: (a : A) -> B): IMaybe<B> = maybe(fn(value))
override fun fromJust(): A = value
override fun fromMaybe(def: A) = value
override fun isJust() = true
override fun isNothing() = false
override fun <B> maybe(def: B, fn: (a : A) -> B): B = fn(this.value)
}
|
mit
|
844f69f39c96e4066cb17e30c526ab70
| 33 | 71 | 0.630027 | 2.869231 | false | false | false | false |
wesamhaboush/kotlin-algorithms
|
src/main/kotlin/algorithms/distinct-primes-factors.kt
|
1
|
1032
|
package algorithms
/*
Distinct primes factors
Problem 47
The first two consecutive numbers to have two distinct prime factors are:
14 = 2 × 7
15 = 3 × 5
The first three consecutive numbers to have three distinct prime factors are:
644 = 2² × 7 × 23
645 = 3 × 5 × 43
646 = 2 × 17 × 19.
Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
*/
fun uniqPrimeFactors(n: Long): Set<Long> = primeFactors(n).toSet()
fun firstNConsecutiveIntegersWithNDistinctPrimeFactors(n: Int): List<Long> =
generateSequence(1L) { it + 1 }
.map { listOfNumbers(it, n) }
.filter { allHasUniquePrimeFactorsOfSize(it, n) }
.first()
private fun allHasUniquePrimeFactorsOfSize(it: List<Long>, numberOfPrimeFactors: Int) =
it.all { uniqPrimeFactors(it).size == numberOfPrimeFactors }
private fun listOfNumbers(startFrom: Long, howMany: Int): List<Long> =
(startFrom until (startFrom + howMany)).toList()
|
gpl-3.0
|
7165f712908fee2a7b9af807add384c7
| 30.96875 | 118 | 0.69306 | 3.733577 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.