repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/sync/RestBodies.kt | 1 | 2851 | package com.nononsenseapps.feeder.sync
import com.nononsenseapps.feeder.db.room.Feed
import com.nononsenseapps.feeder.db.room.OPEN_ARTICLE_WITH_APPLICATION_DEFAULT
import java.net.URL
import org.threeten.bp.Instant
data class CreateRequest(
val deviceName: String
)
data class JoinRequest(
val deviceName: String
)
data class JoinResponse(
val syncCode: String,
val deviceId: Long
)
data class DeviceListResponse(
val devices: List<DeviceMessage>
)
data class DeviceMessage(
val deviceId: Long,
val deviceName: String,
)
data class GetReadMarksResponse(
val readMarks: List<ReadMark>
)
data class GetEncryptedReadMarksResponse(
val readMarks: List<EncryptedReadMark>
)
data class ReadMark(
val timestamp: Instant,
val feedUrl: URL,
val articleGuid: String,
)
data class EncryptedReadMark(
val timestamp: Instant,
// Of type ReadMarkContent
val encrypted: String,
)
data class SendReadMarkBulkRequest(
val items: List<SendReadMarkRequest>
)
data class SendEncryptedReadMarkBulkRequest(
val items: List<SendEncryptedReadMarkRequest>
)
data class SendReadMarkRequest(
val feedUrl: URL,
val articleGuid: String,
)
data class SendEncryptedReadMarkRequest(
val encrypted: String,
)
data class SendReadMarkResponse(
val timestamp: Instant
)
data class ReadMarkContent(
val feedUrl: URL,
val articleGuid: String,
)
data class UpdateFeedsRequest(
val contentHash: Int,
// Of type EncryptedFeeds
val encrypted: String,
)
data class UpdateFeedsResponse(
val hash: Int,
)
data class GetFeedsResponse(
val hash: Int,
// Of type EncryptedFeeds
val encrypted: String,
)
data class EncryptedFeeds(
val feeds: List<EncryptedFeed>
)
data class EncryptedFeed(
val url: URL,
val title: String = "",
val customTitle: String = "",
val tag: String = "",
val imageUrl: URL? = null,
val fullTextByDefault: Boolean = false,
val openArticlesWith: String = OPEN_ARTICLE_WITH_APPLICATION_DEFAULT,
val alternateId: Boolean = false,
val whenModified: Instant = Instant.EPOCH,
)
fun Feed.toEncryptedFeed(): EncryptedFeed =
EncryptedFeed(
url = url,
title = title,
customTitle = customTitle,
tag = tag,
imageUrl = imageUrl,
fullTextByDefault = fullTextByDefault,
openArticlesWith = openArticlesWith,
alternateId = alternateId,
whenModified = whenModified,
)
fun EncryptedFeed.updateFeedCopy(feed: Feed): Feed =
feed.copy(
url = url,
title = title,
customTitle = customTitle,
tag = tag,
imageUrl = imageUrl,
fullTextByDefault = fullTextByDefault,
openArticlesWith = openArticlesWith,
alternateId = alternateId,
whenModified = whenModified,
)
| gpl-3.0 | 127c580fa6051564343fbcc69bc2915c | 20.598485 | 78 | 0.700105 | 3.965229 | false | false | false | false |
fluidsonic/fluid-json | basic/tests-jvm/dummys/DummyJsonReader.kt | 1 | 1009 | package tests.basic
import io.fluidsonic.json.*
internal open class DummyJsonReader : JsonReader {
override fun beginValueIsolation() = JsonDepth(0)
override fun close(): Unit = error("")
override val depth: JsonDepth get() = error("")
override fun endValueIsolation(depth: JsonDepth) {}
override val isInValueIsolation: Boolean get() = false
override val nextToken: JsonToken? get() = error("")
override val offset: Int get() = error("")
override val path: JsonPath get() = error("")
override fun readBoolean(): Boolean = error("")
override fun readDouble(): Double = error("")
override fun readListEnd(): Unit = error("")
override fun readListStart(): Unit = error("")
override fun readLong(): Long = error("")
override fun readMapEnd(): Unit = error("")
override fun readMapStart(): Unit = error("")
override fun readNull(): Nothing? = error("")
override fun readNumber(): Number = error("")
override fun readString(): String = error("")
override fun terminate(): Unit = error("")
}
| apache-2.0 | f3705c9e3ff30e3b243053cdbc78781c | 36.37037 | 55 | 0.698712 | 4.152263 | false | false | false | false |
allotria/intellij-community | plugins/editorconfig/test/org/editorconfig/language/EditorConfigFormattingTest.kt | 3 | 1347 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language
import com.intellij.application.options.CodeStyle
import com.intellij.openapi.application.ex.PathManagerEx
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.psi.codeStyle.CodeStyleManager
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import com.intellij.testFramework.fixtures.BasePlatformTestCase
class EditorConfigFormattingTest : BasePlatformTestCase() {
override fun getTestDataPath() = "${PathManagerEx.getCommunityHomePath()}/plugins/editorconfig/testData/org/editorconfig/language/formatting"
private fun doTestWithSettings(settings: CommonCodeStyleSettings.() -> Unit) {
val file = myFixture.configureByFile("${getTestName(true)}/before/.editorconfig")
val languageSettings = CodeStyle.getLanguageSettings(file, EditorConfigLanguage)
languageSettings.settings()
WriteCommandAction.runWriteCommandAction(project) {
CodeStyleManager.getInstance(project).reformat(file)
}
myFixture.checkResultByFile("${getTestName(true)}/after/.editorconfig")
}
fun testAlignOnValues() = doTestWithSettings { ALIGN_GROUP_FIELD_DECLARATIONS = true }
fun testNoAlignment() = doTestWithSettings { }
}
| apache-2.0 | 36ade45a8fa7863a4d126d50164d5565 | 43.9 | 143 | 0.804009 | 5.083019 | false | true | false | false |
Kotlin/kotlinx.coroutines | integration-testing/src/mavenTest/kotlin/MavenPublicationVersionValidator.kt | 1 | 1228 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.validator
import org.junit.*
import org.junit.Test
import java.util.jar.*
import kotlin.test.*
class MavenPublicationVersionValidator {
@Test
fun testMppJar() {
val clazz = Class.forName("kotlinx.coroutines.Job")
JarFile(clazz.protectionDomain.codeSource.location.file).checkForVersion("kotlinx_coroutines_core.version")
}
@Test
fun testAndroidJar() {
val clazz = Class.forName("kotlinx.coroutines.android.HandlerDispatcher")
JarFile(clazz.protectionDomain.codeSource.location.file).checkForVersion("kotlinx_coroutines_android.version")
}
private fun JarFile.checkForVersion(file: String) {
val actualFile = "META-INF/$file"
val version = System.getenv("version")
use {
for (e in entries()) {
if (e.name == actualFile) {
val string = getInputStream(e).readAllBytes().decodeToString()
assertEquals(version, string)
return
}
}
error("File $file not found")
}
}
}
| apache-2.0 | 0f3e906e970514035d73d3d495306cfe | 29.7 | 118 | 0.62785 | 4.498168 | false | true | false | false |
CORDEA/MackerelClient | app/src/main/java/jp/cordea/mackerelclient/fragment/MonitorSettingDeleteDialogFragment.kt | 1 | 2900 | package jp.cordea.mackerelclient.fragment
import android.app.Dialog
import android.app.ProgressDialog
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import dagger.android.support.AndroidSupportInjection
import jp.cordea.mackerelclient.R
import jp.cordea.mackerelclient.api.response.MonitorDataResponse
import jp.cordea.mackerelclient.utils.DialogUtils
import jp.cordea.mackerelclient.viewmodel.MonitorSettingViewModel
import javax.inject.Inject
class MonitorSettingDeleteDialogFragment : DialogFragment() {
@Inject
lateinit var viewModel: MonitorSettingViewModel
var onSuccess = { }
private val monitor: MonitorDataResponse
get() = arguments!!.getSerializable(MONITOR_KEY) as MonitorDataResponse
override fun onAttach(context: Context?) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = context!!
return AlertDialog
.Builder(context)
.setMessage(R.string.monitor_detail_delete_dialog_title)
.setPositiveButton(R.string.delete_positive_button) { _, _ ->
val dialog = DialogUtils.progressDialog(context, R.string.progress_dialog_title)
dialog.show()
deleteMonitorSetting(dialog)
}
.create()
}
private fun deleteMonitorSetting(dialog: ProgressDialog) {
val context = context ?: return
viewModel.deleteMonitorSetting(
monitor,
onResponse = {
dialog.dismiss()
if (it != null) {
val success = DialogUtils.switchDialog(
context, it,
R.string.monitor_detail_error_dialog_title,
R.string.error_403_dialog_message
)
if (success) {
onSuccess()
}
} else {
DialogUtils.showDialog(
context,
R.string.monitor_detail_error_dialog_title
)
}
},
onFailure = {
dialog.dismiss()
DialogUtils.showDialog(
context,
R.string.monitor_detail_error_dialog_title
)
}
)
}
companion object {
private const val MONITOR_KEY = "MonitorKey"
fun newInstance(monitor: MonitorDataResponse): MonitorSettingDeleteDialogFragment =
MonitorSettingDeleteDialogFragment().apply {
arguments = Bundle().apply {
putSerializable(MONITOR_KEY, monitor)
}
}
}
}
| apache-2.0 | 1746f6f38a2e209b5448c8e0ac7d9c14 | 32.333333 | 96 | 0.588276 | 5.482042 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/Types.kt | 1 | 1837 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package slatekit.common
import slatekit.common.types.ContentFile
import slatekit.common.crypto.EncDouble
import slatekit.common.crypto.EncInt
import slatekit.common.crypto.EncLong
import slatekit.common.crypto.EncString
import org.threeten.bp.*
import slatekit.common.ids.ULIDs
import slatekit.common.ids.UPIDs
import slatekit.common.values.Vars
import java.util.*
object Types {
val JCharClass = Char.javaClass
val JStringClass = String::class.java
val JBoolClass = Boolean::class.java
val JShortClass = Short::class.java
val JIntClass = Int::class.java
val JLongClass = Long::class.java
val JFloatClass = Float::class.java
val JDoubleClass = Double::class.java
val JDateTimeClass = DateTimes.MIN.javaClass
val JLocalDateClass = LocalDate.MIN.javaClass
val JLocalTimeClass = LocalTime.MIN.javaClass
val JLocalDateTimeClass = LocalDateTime.MIN.javaClass
val JZonedDateTimeClass = ZonedDateTime.now().javaClass
val JInstantClass = Instant.MIN.javaClass
val JUUIDClass = UUID.fromString("1bd16d06-a45a-45d8-b4c9-7e864251275f").javaClass
val JULIDClass = ULIDs.create().javaClass
val JUPIDClass = UPIDs.create().javaClass
val JDocClass = ContentFile::class.java
val JVarsClass = Vars.javaClass
val JDecIntClass = EncInt.javaClass
val JDecLongClass = EncLong.javaClass
val JDecDoubleClass = EncDouble.javaClass
val JDecStringClass = EncString.javaClass
val JIntAnyClass = (0 as Any).javaClass
}
| apache-2.0 | ae3a6db9d5fe71878a350136305b0f03 | 32.4 | 86 | 0.755035 | 3.795455 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/wifi/model/WiFiVirtual.kt | 1 | 1362 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.wifi.model
private const val BSSID_LENGTH = 17
data class WiFiVirtual(val bssid: String, val frequency: Int) {
val key: String
get() = "$bssid-$frequency"
}
val WiFiDetail.wiFiVirtual: WiFiVirtual
get() =
if (BSSID_LENGTH == wiFiIdentifier.bssid.length)
WiFiVirtual(
this.wiFiIdentifier.bssid.substring(2, BSSID_LENGTH - 1),
this.wiFiSignal.primaryFrequency)
else
WiFiVirtual(
wiFiIdentifier.bssid,
wiFiSignal.primaryFrequency)
| gpl-3.0 | a64765982efb1053d71bebfeb183d17a | 33.923077 | 90 | 0.685022 | 4.25625 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/OrderingTest/sortUsingCustomComparator.kt | 2 | 799 | import kotlin.test.*
import kotlin.comparisons.*
data class Item(val name: String, val rating: Int) : Comparable<Item> {
public override fun compareTo(other: Item): Int {
return compareValuesBy(this, other, { it.rating }, { it.name })
}
}
val v1 = Item("wine", 9)
val v2 = Item("beer", 10)
fun box() {
val comparator = object : Comparator<Item> {
override fun compare(o1: Item, o2: Item): Int {
return compareValuesBy(o1, o2, { it.name }, { it.rating })
}
override fun equals(other: Any?): Boolean {
return this == other
}
}
val diff = comparator.compare(v1, v2)
assertTrue(diff > 0)
val items = arrayListOf(v1, v2).sortedWith(comparator)
assertEquals(v2, items[0])
assertEquals(v1, items[1])
}
| apache-2.0 | 489ca01b75d52ec4641a7051cd3b8c6d | 27.535714 | 71 | 0.60826 | 3.535398 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/mangling/internalOverride.kt | 5 | 582 | open class A {
internal open val field = "AF"
internal open fun test(): String = "AM"
}
fun invokeOnA(a: A) = a.test() + a.field
class Z : A() {
override val field: String = "ZF"
override fun test(): String = "ZM"
}
fun box() : String {
var invokeOnA = invokeOnA(A())
if (invokeOnA != "AMAF") return "fail 1: $invokeOnA"
invokeOnA = invokeOnA(Z())
if (invokeOnA != "ZMZF") return "fail 2: $invokeOnA"
val z = Z().test()
if (z != "ZM") return "fail 3: $z"
val f = Z().field
if (f != "ZF") return "fail 4: $f"
return "OK"
} | apache-2.0 | ff5a81654aafdd2fc5a155d032651c98 | 19.103448 | 56 | 0.553265 | 2.954315 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/wordSelection/WhenEntries/0.kt | 14 | 455 | fun main(args : Array<String>) {
for (i in 1..100) {
when {
i%3 == 0 -> {print("Fizz"); continue;}
i%5 == 0 -> {print("Buzz"); continue;}
(i%3 != 0 && i%5 != 0) -> {print(i); <selection>continue;}<caret></selection>
else -> println()
}
}
}
fun foo() : Unit {
println() {
println()
println()
println()
}
println(array(1, 2, 3))
println()
} | apache-2.0 | e50861c1c1aac00fc5c8eb994c6aa72e | 18 | 89 | 0.417582 | 3.473282 | false | false | false | false |
smmribeiro/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/GraziePlugin.kt | 1 | 1003 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.extensions.PluginId
import java.nio.file.Path
internal object GraziePlugin {
const val id = "tanvd.grazi"
object LanguageTool {
const val version = "5.5"
const val url = "https://resources.jetbrains.com/grazie/model/language-tool"
}
private val descriptor: IdeaPluginDescriptor
get() = PluginManagerCore.getPlugin(PluginId.getId(id))!!
val group: String
get() = GrazieBundle.message("grazie.group.name")
val name: String
get() = GrazieBundle.message("grazie.name")
val isBundled: Boolean
get() = descriptor.isBundled
val classLoader: ClassLoader
get() = descriptor.classLoader
val libFolder: Path
get() = descriptor.pluginPath.resolve("lib")
}
| apache-2.0 | 937a8973f9e908d9bc16f34fab92eaab | 28.5 | 140 | 0.743769 | 4.127572 | false | false | false | false |
AndrewJack/gatekeeper | mobile/src/main/java/technology/mainthread/apps/gatekeeper/service/GatekeeperStateService.kt | 1 | 6098 | package technology.mainthread.apps.gatekeeper.service
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import dagger.android.DaggerService
import io.reactivex.disposables.CompositeDisposable
import retrofit2.Response
import technology.mainthread.apps.gatekeeper.R
import technology.mainthread.apps.gatekeeper.rx.applyFlowableSchedulers
import technology.mainthread.apps.gatekeeper.data.AppStateController
import technology.mainthread.apps.gatekeeper.data.PARTICLE_AUTH
import technology.mainthread.apps.gatekeeper.data.service.GatekeeperService
import technology.mainthread.apps.gatekeeper.data.service.RxDeviceState
import technology.mainthread.apps.gatekeeper.model.event.AppEventType
import technology.mainthread.apps.gatekeeper.model.event.GatekeeperState
import technology.mainthread.apps.gatekeeper.model.particle.DeviceAction
import technology.mainthread.apps.gatekeeper.view.notificaton.NotifierHelper
import timber.log.Timber
import javax.inject.Inject
class GatekeeperStateService : DaggerService() {
@Inject
internal lateinit var gatekeeperService: GatekeeperService
@Inject
internal lateinit var rxDeviceState: RxDeviceState
@Inject
internal lateinit var notifierHelper: NotifierHelper
@Inject
internal lateinit var appStateController: AppStateController
@Inject
internal lateinit var config: FirebaseRemoteConfig
private val cs = CompositeDisposable()
private val handler = Handler()
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
val action = intent.action
if (ACTION_CHECK_STATE == action) {
checkGatekeeperState()
} else if (ACTION_UNLOCK == action) {
unlock()
} else if (ACTION_PRIME == action) {
prime()
}
return Service.START_NOT_STICKY
}
override fun onDestroy() {
handler.removeCallbacksAndMessages(null)
cs.clear()
super.onDestroy()
}
private fun checkGatekeeperState() {
val disposable = rxDeviceState.gatekeeperStateObservable()
.compose(applyFlowableSchedulers<GatekeeperState>())
.subscribe({ state ->
appStateController.updateGatekeeperState(state)
appStateController.onAppEvent(AppEventType.READY, false, 0)
}) { t -> Timber.e(t, "Throwable when unlocking") }
cs.add(disposable)
}
private fun checkGatekeeperStateInFuture(millisecondsFromNow: Int) {
handler.postDelayed({ this.checkGatekeeperState() }, millisecondsFromNow.toLong())
}
private fun unlock() {
appStateController.onAppEvent(AppEventType.UNLOCKING, false, R.string.event_unlock_in_progress)
notifierHelper.onUnlockPressed()
val disposable = gatekeeperService.unlock(config.getString(PARTICLE_AUTH))
.compose<Response<DeviceAction>>(applyFlowableSchedulers<Response<DeviceAction>>())
.subscribe({ deviceActionResponse ->
if (deviceActionResponse.isSuccessful()) {
if (deviceActionResponse.body()?.returnValue == 0) {
appStateController.onAppEvent(AppEventType.COMPLETE, true, R.string.event_unlock_success)
notifierHelper.notifyHandsetUnlocked(true)
} else {
appStateController.onAppEvent(AppEventType.COMPLETE, false, R.string.event_unlock_fail)
}
} else {
appStateController.onAppEvent(AppEventType.COMPLETE, false, R.string.event_unlock_fail)
}
}) { t ->
Timber.e(t, "Throwable when unlocking")
appStateController.onAppEvent(AppEventType.COMPLETE, false, R.string.event_unlock_fail)
}
cs.add(disposable)
}
private fun prime() {
appStateController.onAppEvent(AppEventType.PRIMING, false, R.string.event_prime_in_progress)
val disposable = gatekeeperService.prime(config.getString(PARTICLE_AUTH))
.compose<Response<DeviceAction>>(applyFlowableSchedulers<Response<DeviceAction>>())
.subscribe({ deviceActionResponse ->
if (deviceActionResponse.isSuccessful()) {
if (deviceActionResponse.body()?.returnValue == 0) {
appStateController.updateGatekeeperState(GatekeeperState.PRIMED)
appStateController.onAppEvent(AppEventType.COMPLETE, true, R.string.event_prime_success)
checkGatekeeperStateInFuture(TIME_UNTIL_PRIME_EXPIRED)
} else { // Device failure
appStateController.onAppEvent(AppEventType.COMPLETE, false, R.string.event_prime_fail)
checkGatekeeperStateInFuture(10000)
}
} else {
appStateController.onAppEvent(AppEventType.COMPLETE, false, R.string.event_prime_fail)
checkGatekeeperStateInFuture(10000)
}
}) { t ->
Timber.e(t, "Throwable when priming")
appStateController.onAppEvent(AppEventType.COMPLETE, false, R.string.event_unlock_fail)
}
cs.add(disposable)
}
}
const val ACTION_CHECK_STATE = "ACTION_CHECK_STATE"
const val ACTION_UNLOCK = "ACTION_UNLOCK"
const val ACTION_PRIME = "ACTION_PRIME"
private val TIME_UNTIL_PRIME_EXPIRED = 2 * 60 * 1000 // Default 2 mins // TODO: fetch from api
fun getGatekeeperStateIntent(context: Context, action: String): Intent {
val intent = Intent(context, GatekeeperStateService::class.java)
intent.action = action
return intent
}
| apache-2.0 | e97d7f86b3fbf9de72148e3ce6979afd | 42.248227 | 117 | 0.660544 | 4.786499 | false | false | false | false |
firebase/firebase-android-sdk | firebase-common/ktx/src/main/kotlin/com/google/firebase/ktx/Firebase.kt | 1 | 3292 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.firebase.ktx
import android.content.Context
import androidx.annotation.Keep
import com.google.firebase.FirebaseApp
import com.google.firebase.FirebaseOptions
import com.google.firebase.annotations.concurrent.Background
import com.google.firebase.annotations.concurrent.Blocking
import com.google.firebase.annotations.concurrent.Lightweight
import com.google.firebase.annotations.concurrent.UiThread
import com.google.firebase.components.Component
import com.google.firebase.components.ComponentRegistrar
import com.google.firebase.components.Dependency
import com.google.firebase.components.Qualified
import com.google.firebase.platforminfo.LibraryVersionComponent
import java.util.concurrent.Executor
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.asCoroutineDispatcher
/**
* Single access point to all firebase SDKs from Kotlin.
*
* <p>Acts as a target for extension methods provided by sdks.
*/
object Firebase
/** Returns the default firebase app instance. */
val Firebase.app: FirebaseApp
get() = FirebaseApp.getInstance()
/** Returns a named firebase app instance. */
fun Firebase.app(name: String): FirebaseApp = FirebaseApp.getInstance(name)
/** Initializes and returns a FirebaseApp. */
fun Firebase.initialize(context: Context): FirebaseApp? = FirebaseApp.initializeApp(context)
/** Initializes and returns a FirebaseApp. */
fun Firebase.initialize(context: Context, options: FirebaseOptions): FirebaseApp =
FirebaseApp.initializeApp(context, options)
/** Initializes and returns a FirebaseApp. */
fun Firebase.initialize(context: Context, options: FirebaseOptions, name: String): FirebaseApp =
FirebaseApp.initializeApp(context, options, name)
/** Returns options of default FirebaseApp */
val Firebase.options: FirebaseOptions
get() = Firebase.app.options
internal const val LIBRARY_NAME: String = "fire-core-ktx"
/** @suppress */
@Keep
class FirebaseCommonKtxRegistrar : ComponentRegistrar {
override fun getComponents(): List<Component<*>> {
return listOf(
LibraryVersionComponent.create(LIBRARY_NAME, BuildConfig.VERSION_NAME),
coroutineDispatcher<Background>(),
coroutineDispatcher<Lightweight>(),
coroutineDispatcher<Blocking>(),
coroutineDispatcher<UiThread>()
)
}
}
private inline fun <reified T : Annotation> coroutineDispatcher(): Component<CoroutineDispatcher> =
Component.builder(Qualified.qualified(T::class.java, CoroutineDispatcher::class.java))
.add(Dependency.required(Qualified.qualified(T::class.java, Executor::class.java)))
.factory { c ->
c.get(Qualified.qualified(T::class.java, Executor::class.java)).asCoroutineDispatcher()
}
.build()
| apache-2.0 | 0bb251ee26c9dfd899f04c482f29cb5e | 38.190476 | 99 | 0.778858 | 4.478912 | false | false | false | false |
mdaniel/intellij-community | plugins/git4idea/src/git4idea/index/ui/GitStageCommitPanel.kt | 1 | 5357 | // 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 git4idea.index.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.DisposableWrapperList
import com.intellij.util.ui.JBUI.Borders.empty
import com.intellij.vcs.commit.CommitProgressPanel
import com.intellij.vcs.commit.EditedCommitDetails
import com.intellij.vcs.commit.NonModalCommitPanel
import git4idea.i18n.GitBundle
import git4idea.index.ContentVersion
import git4idea.index.GitFileStatus
import git4idea.index.GitStageTracker
import git4idea.index.createChange
import kotlin.properties.Delegates.observable
private fun GitStageTracker.State.getStaged(): Set<GitFileStatus> =
rootStates.values.flatMapTo(mutableSetOf()) { it.getStaged() }
private fun GitStageTracker.RootState.getStaged(): Set<GitFileStatus> =
statuses.values.filterTo(mutableSetOf()) { it.getStagedStatus() != null }
private fun GitStageTracker.RootState.getStagedChanges(project: Project): List<Change> =
getStaged().mapNotNull { createChange(project, root, it, ContentVersion.HEAD, ContentVersion.STAGED) }
class GitStageCommitPanel(project: Project) : NonModalCommitPanel(project) {
private val progressPanel = GitStageCommitProgressPanel()
override val commitProgressUi: GitStageCommitProgressPanel get() = progressPanel
@Volatile
private var state: InclusionState = InclusionState(emptySet(), GitStageTracker.State.EMPTY)
val rootsToCommit get() = state.rootsToCommit
val includedRoots get() = state.includedRoots
val conflictedRoots get() = state.conflictedRoots
private val editedCommitListeners = DisposableWrapperList<() -> Unit>()
override var editedCommit: EditedCommitDetails? by observable(null) { _, _, _ ->
editedCommitListeners.forEach { it() }
}
init {
Disposer.register(this, commitMessage)
commitMessage.setChangesSupplier { state.stagedChanges }
progressPanel.setup(this, commitMessage.editorField)
bottomPanel = {
add(progressPanel.apply { border = empty(6) })
add(commitAuthorComponent.apply { border = empty(0, 5, 4, 0) })
add(commitActionsPanel)
}
buildLayout()
}
fun setIncludedRoots(includedRoots: Collection<VirtualFile>) {
setState(includedRoots, state.trackerState)
}
fun setTrackerState(trackerState: GitStageTracker.State) {
setState(state.includedRoots, trackerState)
}
private fun setState(includedRoots: Collection<VirtualFile>, trackerState: GitStageTracker.State) {
val newState = InclusionState(includedRoots, trackerState)
if (state != newState) {
state = newState
fireInclusionChanged()
}
}
fun addEditedCommitListener(listener: () -> Unit, parent: Disposable) {
editedCommitListeners.add(listener, parent)
}
override fun activate(): Boolean = true
override fun refreshData() = Unit
override fun getDisplayedChanges(): List<Change> = emptyList()
override fun getIncludedChanges(): List<Change> = state.stagedChanges
override fun getDisplayedUnversionedFiles(): List<FilePath> = emptyList()
override fun getIncludedUnversionedFiles(): List<FilePath> = emptyList()
private inner class InclusionState(val includedRoots: Collection<VirtualFile>, val trackerState: GitStageTracker.State) {
private val stagedStatuses: Set<GitFileStatus> = trackerState.getStaged()
val conflictedRoots: Set<VirtualFile> = trackerState.rootStates.filter { it.value.hasConflictedFiles() }.keys
val stagedChanges by lazy {
trackerState.rootStates.filterKeys {
includedRoots.contains(it)
}.values.flatMap { it.getStagedChanges(project) }
}
val rootsToCommit get() = trackerState.stagedRoots.intersect(includedRoots)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as InclusionState
if (includedRoots != other.includedRoots) return false
if (stagedStatuses != other.stagedStatuses) return false
if (conflictedRoots != other.conflictedRoots) return false
return true
}
override fun hashCode(): Int {
var result = includedRoots.hashCode()
result = 31 * result + stagedStatuses.hashCode()
result = 31 * result + conflictedRoots.hashCode()
return result
}
}
}
class GitStageCommitProgressPanel : CommitProgressPanel() {
var isEmptyRoots by stateFlag()
var isUnmerged by stateFlag()
override fun clearError() {
super.clearError()
isEmptyRoots = false
isUnmerged = false
}
override fun buildErrorText(): String? =
when {
isEmptyRoots -> GitBundle.message("error.no.selected.roots.to.commit")
isUnmerged -> GitBundle.message("error.unresolved.conflicts")
isEmptyChanges && isEmptyMessage -> GitBundle.message("error.no.staged.changes.no.commit.message")
isEmptyChanges -> GitBundle.message("error.no.staged.changes.to.commit")
isEmptyMessage -> VcsBundle.message("error.no.commit.message")
else -> null
}
}
| apache-2.0 | 8f171f91b45eea4680f82c247e887793 | 37.264286 | 140 | 0.7521 | 4.686789 | false | false | false | false |
dpisarenko/econsim-tr01 | src/main/java/cc/altruix/econsimtr01/ch0201/Sim1TimeSeriesCreator.kt | 1 | 3104 | /*
* 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.ch0201
import alice.tuprolog.Prolog
import cc.altruix.econsimtr01.DefaultTimeSeriesCreator
import cc.altruix.econsimtr01.getResults
import cc.altruix.econsimtr01.newLine
import cc.altruix.javaprologinterop.PlUtils
import java.io.File
/**
* @author Dmitri Pisarenko ([email protected])
* @version $Id$
* @since 1.0
*/
class Sim1TimeSeriesCreator : DefaultTimeSeriesCreator() {
override fun prologToCsv(input: File): String {
val builder = StringBuilder()
appendRow(builder,
"t [sec]",
"Time",
"Money @ Stacy",
"Money in savings account")
val prolog = PlUtils.createEngine()
val times = extractTimes(input, prolog)
times.forEach { t ->
val timeShort = t.toString()
val timeLong = extractTimeLongForm(prolog, t)
val moneyAtStacy = extractMoneyAtStacy(prolog, t)
val moneyInSavingsAccount = extractMoneyInSavingsAccount(prolog, t)
appendRow(builder,
timeShort,
timeLong,
moneyAtStacy,
moneyInSavingsAccount)
}
return builder.toString()
}
private fun extractMoneyInSavingsAccount(prolog: Prolog, time: Long): String =
prolog.getResults("resourceLevel($time, savingsAccount, r2, Amount).", "Amount").first()
private fun extractMoneyAtStacy(prolog: Prolog, time: Long): String =
prolog.getResults("resourceLevel($time, stacy, r2, Amount).", "Amount").first()
private fun appendRow(builder: StringBuilder,
timeShort: String,
timeLong: String,
moneyAtStacy: String,
moneyInSavingsAccount: String) {
arrayOf(timeShort,
timeLong,
moneyAtStacy,
moneyInSavingsAccount).forEach { col ->
builder.append("\"$col\";")
}
builder.newLine()
}
}
| gpl-3.0 | 55e112037a1522264249ef6a69da77f9 | 32.488889 | 100 | 0.613402 | 4.359551 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/bolone/test/Test_jsonizeForCallingFront.kt | 1 | 3736 | package bolone.test
import alraune.*
import alraune.entity.*
import bolone.BoFrontFuns
import bolone.TextField
import bolone.rp.FileField
import bolone.rp.new_FileField_Value
import bolone.rp.new_OrderFileFields
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import pieces100.*
import vgrechka.*
class Test_jsonizeForCallingFront {
@Before fun setUp() {
initStandaloneToolMode__localMemoryDBConfig()
}
@Test fun test1() {
fart(shouldContainSecrets = false)
fart(shouldContainSecrets = true) {
AlTestPile.pretendAdmin(it)}
}
private fun fart(shouldContainSecrets: Boolean, fuckContext: (Context1ProjectStuff) -> Unit = {}) {
withNewContext1 {
rctx0.al.useConnection {
val shit = BoFrontFuns.InitOrderFilesPage(
editable = true,
orderHandle = OrderHandle(id = 123L, lockId = 234L, expectedOptimisticVersion = "adfadsf").toJsonizable(),
bucket = "fsadfasdf",
tabsTopRightContainerDomid = "sadfadsf",
reloadURL = "dfasdfasdf",
reloadToFirstPageURL = "dfsdkfjskdfjk",
storikanURL = "zxcvczxv",
userKind = AlUserKind.Customer,
fileItems = listOf(
BoFrontFuns.InitOrderFilesPage.FileItem(
id = 123L,
file = new_Order_File(
id = 234L, createdAt = now(), updatedAt = now(), uuid = "27ec5886-cf26-4f26-bb98-f950979958e4",
state = Order.File.State.Unknown, title = "qweqweqwe", details = "asdfasdfasdfasdf",
// Should not be included
adminNotes = "Надо наебать этого заказчика на деньги",
toBeFixed = new_Order_ToBeFixed(
what = "Не были бы вы трижды любезны исправить вот это...",
// Should not be included
detailsForAdmin = "Дебил, бля..."),
resource = new_Order_Resource(
name = "qweeidfgd", size = 42433, downloadUrl = "sdfhhhhvv", secretKeyBase64 = "sdfjsfdjkgsdnfgs")),
editTriggerDomid = "qweqwe",
rightIconsContainerDomid = "dsfafasdf",
fields = new_OrderFileFields(
file = FileField.noError(new_FileField_Value(
name = "aaaaaaa",
size = 123123,
downloadURL = "faskdfasdfsaf",
secretKeyBase64 = "sakioisdjfaosdf")),
title = TextField.noError("asdfadsfasf"),
details = TextField.noError("kjaksdfsadfaskdfjasdf")),
copiedTo = listOf())))
val json = dyna {
fuckContext(it)
BoFrontFuns.jsonizeForCallingFront(shit, pretty = true)
}
clog(json)
val file = shit.fileItems.first().file
val secret1 = file.adminNotes!!
val secret2 = file.toBeFixed!!.detailsForAdmin
val containsSecrets = json.contains(secret1) || json.contains(secret2)
Assert.assertTrue(containsSecrets == shouldContainSecrets)
}
}
}
} | apache-2.0 | 3bec255982a6bc02d52ebcbf8b69c43f | 42.547619 | 136 | 0.509161 | 4.830911 | false | true | false | false |
jwren/intellij-community | platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/StoreSnapshotsAnalyzer.kt | 2 | 3431 | // 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
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
import com.intellij.workspaceModel.storage.impl.EntityStorageSerializerImpl
import com.intellij.workspaceModel.storage.impl.MatchedEntitySource
import com.intellij.workspaceModel.storage.impl.SimpleEntityTypesResolver
import com.intellij.workspaceModel.storage.impl.url.VirtualFileUrlManagerImpl
import com.intellij.workspaceModel.storage.toBuilder
import java.io.File
import kotlin.system.exitProcess
/**
* This is a boilerplate code for analyzing state of entity stores that were received as attachments to exceptions
*/
fun main(args: Array<String>) {
if (args.size != 1) {
println("Usage: com.intellij.workspaceModel.ide.StoreSnapshotsAnalyzerKt <path to directory with storage files>")
exitProcess(1)
}
val file = File(args[0])
if (!file.exists()) {
throw IllegalArgumentException("$file doesn't exist")
}
if (file.isFile) {
val serializer = EntityStorageSerializerImpl(SimpleEntityTypesResolver, VirtualFileUrlManagerImpl())
val storage = file.inputStream().use {
serializer.deserializeCache(it)
}
// Set a breakpoint and check
println("Cache loaded: ${storage!!.entities(ModuleEntity::class.java).toList().size} modules")
return
}
val leftFile = file.resolve("Left_Store")
val rightFile = file.resolve("Right_Store")
val rightDiffLogFile = file.resolve("Right_Diff_Log")
val converterFile = file.resolve("ClassToIntConverter")
val resFile = file.resolve("Res_Store")
val serializer = EntityStorageSerializerImpl(SimpleEntityTypesResolver, VirtualFileUrlManagerImpl())
serializer.deserializeClassToIntConverter(converterFile.inputStream())
val resStore = serializer.deserializeCache(resFile.inputStream())!!
val leftStore = serializer.deserializeCache(leftFile.inputStream()) ?: throw IllegalArgumentException("Cannot load cache")
if (file.resolve("Replace_By_Source").exists()) {
val rightStore = serializer.deserializeCache(rightFile.inputStream())!!
val allEntitySources = leftStore.entitiesBySource { true }.map { it.key }.toHashSet()
allEntitySources.addAll(rightStore.entitiesBySource { true }.map { it.key })
val pattern = if (file.resolve("Report_Wrapped").exists()) {
matchedPattern()
}
else {
val sortedSources = allEntitySources.sortedBy { it.toString() }
patternFilter(file.resolve("Replace_By_Source").readText(), sortedSources)
}
val expectedResult = leftStore.toBuilder()
expectedResult.replaceBySource(pattern, rightStore)
// Set a breakpoint and check
println("storage loaded")
}
else {
val rightStore = serializer.deserializeCacheAndDiffLog(rightFile.inputStream(), rightDiffLogFile.inputStream())!!
val expectedResult = leftStore.toBuilder()
expectedResult.addDiff(rightStore)
// Set a breakpoint and check
println("storage loaded")
}
}
fun patternFilter(pattern: String, sortedSources: List<EntitySource>): (EntitySource) -> Boolean {
return {
val idx = sortedSources.indexOf(it)
pattern[idx] == '1'
}
}
fun matchedPattern(): (EntitySource) -> Boolean {
return {
it is MatchedEntitySource
}
}
| apache-2.0 | ac9fc35f363203b548611a345913d77e | 35.5 | 140 | 0.750802 | 4.473272 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/abccomputer/models/JSONAuthUser.kt | 1 | 1205 | package com.tungnui.abccomputer.models
/**
* Created by thanh on 22/10/2017.
*/
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class JSONAuthUser(
@SerializedName("id")
@Expose
var id: Int? = null,
@SerializedName("username")
@Expose
var username: String? = null,
@SerializedName("nicename")
@Expose
var nicename: String? = null,
@SerializedName("email")
@Expose
var email: String? = null,
@SerializedName("url")
@Expose
var url: String? = null,
@SerializedName("registered")
@Expose
var registered: String? = null,
@SerializedName("displayname")
@Expose
var displayname: String? = null,
@SerializedName("firstname")
@Expose
var firstname: String? = null,
@SerializedName("lastname")
@Expose
var lastname: String? = null,
@SerializedName("nickname")
@Expose
var nickname: String? = null,
@SerializedName("description")
@Expose
var description: String? = null,
@SerializedName("capabilities")
@Expose
var capabilities: String? = null,
@SerializedName("avatar")
@Expose
var avatar: Any? = null
) | mit | 95ef4a350258f12cb4f9c791ab682df0 | 22.647059 | 49 | 0.650622 | 4.057239 | false | false | false | false |
nrizzio/Signal-Android | qr/lib/src/main/java/org/signal/qr/ImageProxyLuminanceSource.kt | 1 | 2009 | package org.signal.qr
import android.graphics.ImageFormat
import androidx.annotation.RequiresApi
import androidx.camera.core.ImageProxy
import com.google.zxing.LuminanceSource
import java.nio.ByteBuffer
/**
* Luminance source that gets data via an [ImageProxy]. The main reason for this is because
* the Y-Plane provided by the camera framework can have a row stride (number of bytes that make up a row)
* that is different than the image width.
*
* An image width can be reported as 1080 but the row stride may be 1088. Thus when representing a row-major
* 2D array as a 1D array, the math can go sideways if width is used instead of row stride.
*/
@RequiresApi(21)
class ImageProxyLuminanceSource(image: ImageProxy) : LuminanceSource(image.width, image.height) {
val yData: ByteArray
init {
require(image.format == ImageFormat.YUV_420_888) { "Invalid image format" }
yData = ByteArray(image.width * image.height)
val yBuffer: ByteBuffer = image.planes[0].buffer
yBuffer.position(0)
val yRowStride: Int = image.planes[0].rowStride
for (y in 0 until image.height) {
val yIndex: Int = y * yRowStride
yBuffer.position(yIndex)
yBuffer.get(yData, y * image.width, image.width)
}
}
override fun getRow(y: Int, row: ByteArray?): ByteArray {
require(y in 0 until height) { "Requested row is outside the image: $y" }
val toReturn: ByteArray = if (row == null || row.size < width) {
ByteArray(width)
} else {
row
}
val yIndex: Int = y * width
yData.copyInto(toReturn, 0, yIndex, yIndex + width)
return toReturn
}
override fun getMatrix(): ByteArray {
return yData
}
fun render(): IntArray {
val argbArray = IntArray(width * height)
var yValue: Int
yData.forEachIndexed { i, byte ->
yValue = (byte.toInt() and 0xff).coerceIn(0..255)
argbArray[i] = 255 shl 24 or (yValue and 255 shl 16) or (yValue and 255 shl 8) or (yValue and 255)
}
return argbArray
}
}
| gpl-3.0 | e9d7c1d18aa4a95f2d287e691379f7a6 | 27.7 | 108 | 0.687904 | 3.713494 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/platform/client/impl/data/ProtoParcelable.kt | 3 | 3858 | /*
* Copyright (C) 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.health.platform.client.impl.data
import android.annotation.SuppressLint
import android.os.Parcel
import android.os.Parcelable
import android.os.Parcelable.Creator
import android.os.SharedMemory
import androidx.annotation.RestrictTo
import androidx.health.platform.client.proto.MessageLite
/**
* Base class for parcelables backed by protos.
*
* Provided [proto] represents everything important to subclasses, they need not implement [equals]
* and [hashCode].
*/
@Suppress("ParcelCreator", "ParcelNotFinal")
@RestrictTo(RestrictTo.Scope.LIBRARY)
abstract class ProtoParcelable<T : MessageLite> : ProtoData<T>(), Parcelable {
/** Serialized representation of this object. */
private val bytes: ByteArray by lazy { proto.toByteArray() }
override fun describeContents(): Int {
return if (shouldStoreInPlace()) 0 else Parcelable.CONTENTS_FILE_DESCRIPTOR
}
/**
* Flattens the underlying proto into `dest`.
*
* @see Parcelable.writeToParcel
*/
override fun writeToParcel(dest: Parcel, flags: Int) {
if (shouldStoreInPlace()) {
dest.writeInt(STORE_IN_PLACE)
dest.writeByteArray(bytes)
} else {
dest.writeInt(STORE_SHARED_MEMORY)
@Suppress("NewApi") // API only ever used on SDK 27 and above.
SharedMemory27Impl.writeToParcelUsingSharedMemory("ProtoParcelable", bytes, dest, flags)
}
}
/** Returns whether the underlying proto should be stored as an in-place [ByteArray]. */
private fun shouldStoreInPlace(): Boolean {
return bytes.size <= MAX_IN_PLACE_SIZE
}
companion object {
/**
* Constructs and returns a [Creator] based on the provided [parser] accepting a [ByteArray]
* .
*/
internal inline fun <reified U : ProtoParcelable<*>> newCreator(
crossinline parser: (ByteArray) -> U
): Creator<U> {
return object : Creator<U> {
@SuppressLint("NewApi") // API only ever used on SDK 27 and above.
override fun createFromParcel(source: Parcel): U? {
when (val storage = source.readInt()) {
STORE_IN_PLACE -> {
val payload: ByteArray = source.createByteArray() ?: return null
return parser(payload)
}
STORE_SHARED_MEMORY -> {
return SharedMemory27Impl.parseParcelUsingSharedMemory(source) {
parser(it)
}
}
else -> throw IllegalArgumentException("Unknown storage: $storage")
}
}
override fun newArray(size: Int) = arrayOfNulls<U>(size)
}
}
}
}
/** Flag marking that a proto is stored as an in-place `byte[]` array. */
internal const val STORE_IN_PLACE = 0
/** Flag marking that a proto is stored in [SharedMemory]. */
internal const val STORE_SHARED_MEMORY = 1
/** Maximum size of a proto stored as an in-place `byte[]` array (16 KiB). */
private const val MAX_IN_PLACE_SIZE = 16 * 1024
| apache-2.0 | 01e2545598f844c823d8df6f0b9de7cc | 36.823529 | 100 | 0.625713 | 4.6538 | false | false | false | false |
HughG/yested | src/main/docsite/bootstrap/alerts.kt | 2 | 1743 | package bootstrap
import net.yested.Div
import net.yested.div
import net.yested.bootstrap.row
import net.yested.bootstrap.Medium
import net.yested.bootstrap.pageHeader
import net.yested.bootstrap.alert
import net.yested.bootstrap.AlertStyle
fun createAlertsSection(id: String): Div {
return div(id = id) {
row {
col(Medium(12)) {
pageHeader { h3 { +"Alerts" } }
}
}
row {
col(Medium(6)) {
div {
+"""Refer to Bootstrap Alerts."""
br()
a(href="http://getbootstrap.com/components/#alerts") { +"http://getbootstrap.com/components/#alerts"}
}
br()
h4 { +"Demo" }
div {
alert(style = AlertStyle.WARNING, dismissible = true) {
emph { +"Warning!" }
+ " Better check yourself, you're not looking too good."
}
alert(style = AlertStyle.DANGER, dismissible = true) {
emph { +"Oh snap!" }
+ " Change a few things up and try submitting again."
}
}
}
col(Medium(6)) {
h4 { +"Code" }
code(lang = "kotlin", content =
"""div {
alert(style = AlertStyle.WARNING, dismissible = true) {
emph { +"Warning!" }
+ " Better check yourself, you're not looking too good."
}
br()
alert(style = AlertStyle.DANGER, dismissible = true) {
emph { +"Oh snap!" }
+ " Change a few things up and try submitting again."
}
}""")
}
}
}
} | mit | adfd9b2ca5638ec87edfeadd445df70b | 29.596491 | 121 | 0.470453 | 4.492268 | false | false | false | false |
scenerygraphics/SciView | src/main/kotlin/sc/iview/ui/SwingNodePropertyEditor.kt | 1 | 15933 | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2021 SciView developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview.ui
import com.intellij.ui.components.JBPanel
import graphics.scenery.Camera
import graphics.scenery.Node
import graphics.scenery.Scene
import net.miginfocom.swing.MigLayout
import org.joml.Quaternionf
import org.joml.Vector3f
import org.scijava.Context
import org.scijava.command.CommandService
import org.scijava.event.EventHandler
import org.scijava.log.LogService
import org.scijava.module.*
import org.scijava.plugin.Parameter
import org.scijava.plugin.PluginService
import org.scijava.service.Service
import org.scijava.ui.swing.widget.SwingInputPanel
import org.scijava.util.DebugUtils
import org.scijava.widget.UIComponent
import sc.iview.SciView
import sc.iview.commands.edit.Properties
import sc.iview.commands.help.Help
import sc.iview.event.NodeActivatedEvent
import sc.iview.event.NodeAddedEvent
import sc.iview.event.NodeChangedEvent
import sc.iview.event.NodeRemovedEvent
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Component
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JMenuItem
import javax.swing.JPanel
import javax.swing.JPopupMenu
import javax.swing.JScrollPane
import javax.swing.JSplitPane
import javax.swing.JTextArea
import javax.swing.JTree
import javax.swing.WindowConstants
import javax.swing.event.TreeSelectionEvent
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.DefaultTreeModel
import javax.swing.tree.TreeNode
import javax.swing.tree.TreePath
import javax.swing.tree.TreeSelectionModel
/**
* Interactive UI for visualizing and editing the scene graph.
*
* @author Curtis Rueden
* @author Ulrik Guenther
*/
class SwingNodePropertyEditor(private val sciView: SciView) : UIComponent<JPanel> {
@Parameter
private lateinit var pluginService: PluginService
@Parameter
private lateinit var moduleService: ModuleService
@Parameter
private lateinit var commandService: CommandService
@Parameter
private lateinit var log: LogService
private var panel: JPanel? = null
private lateinit var treeModel: DefaultTreeModel
lateinit var tree: JTree
private set
lateinit var props: JBPanel<*>
fun getProps(): JPanel {
return props
}
/** Creates and displays a window containing the scene editor. */
fun show() {
val frame = JFrame("Node Properties")
frame.setLocation(200, 200)
frame.contentPane = component
// FIXME: Why doesn't the frame disappear when closed?
frame.defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE
frame.setSize(600, 400)
frame.isVisible = true
}
override fun getComponent(): JPanel {
if (panel == null) {
initPanel()
}
return panel!!
}
override fun getComponentType(): Class<JPanel> {
return JPanel::class.java
}
@EventHandler
private fun onEvent(evt: NodeAddedEvent) {
val node = evt.node ?: return
log.trace("Node added: $node");
rebuildTree()
}
@EventHandler
private fun onEvent(evt: NodeRemovedEvent) {
val node = evt.node ?: return
log.trace("Node removed: $node");
rebuildTree()
}
@EventHandler
private fun onEvent(evt: NodeChangedEvent) {
val node = evt.node ?: return
if (node == sciView.activeNode) {
updateProperties(sciView.activeNode)
}
updateTree(node)
}
@EventHandler
private fun onEvent(evt: NodeActivatedEvent) {
val node = evt.node ?: return
updateProperties(node)
updateTree(node)
}
/** Initializes [.panel]. */
@Synchronized
private fun initPanel() {
if (panel != null) return
val p = JPanel()
p.layout = BorderLayout()
createTree()
props = JBPanel<Nothing>()
props.layout = MigLayout("inset 0", "[grow,fill]", "[grow,fill]")
updateProperties(null)
val splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, //
JScrollPane(tree), //
JScrollPane(props))
splitPane.dividerLocation = 200
p.add(splitPane, BorderLayout.CENTER)
panel = p
}
private fun createTree() {
treeModel = DefaultTreeModel(SwingSceneryTreeNode(sciView))
tree = JTree(treeModel)
tree.isRootVisible = true
tree.cellRenderer = SwingNodePropertyTreeCellRenderer()
// tree.setCellEditor(new NodePropertyTreeCellEditor(sciView));
tree.selectionModel.selectionMode = TreeSelectionModel.SINGLE_TREE_SELECTION
tree.addTreeSelectionListener { e: TreeSelectionEvent ->
val sceneNode = sceneNode(e.newLeadSelectionPath)
sciView.setActiveNode(sceneNode)
updateProperties(sceneNode)
}
tree.addMouseListener(object : MouseAdapter() {
override fun mouseClicked(e: MouseEvent) {
super.mouseClicked(e)
if (e.clickCount == 2 && e.button == MouseEvent.BUTTON1) {
val n = tree.lastSelectedPathComponent as? SwingSceneryTreeNode ?: return
val node = n.userObject as? Node ?: return
sciView.setActiveCenteredNode(node)
} else if (e.button == MouseEvent.BUTTON3) {
val x = e.x
val y = e.y
val tree = e.source as JTree
val path = tree.getPathForLocation(x, y) ?: return
tree.selectionPath = path
val obj = path.lastPathComponent as? SwingSceneryTreeNode ?: return
val popup = JPopupMenu()
val labelItem = if(obj.node == null) {
return
} else {
JMenuItem(obj.node.name)
}
labelItem.isEnabled = false
popup.add(labelItem)
if (obj.node is Camera) {
val resetItem = JMenuItem("Reset camera")
resetItem.foreground = Color.RED
resetItem.addActionListener { _: ActionEvent? ->
obj.node.position = Vector3f(0.0f)
obj.node.rotation = Quaternionf(0.0f, 0.0f, 0.0f, 1.0f)
}
popup.add(resetItem)
}
val hideShow = JMenuItem("Hide")
if (obj.node.visible) {
hideShow.text = "Hide"
} else {
hideShow.text = "Show"
}
hideShow.addActionListener { _: ActionEvent? -> obj.node.visible = !obj.node.visible }
popup.add(hideShow)
val removeItem = JMenuItem("Remove")
removeItem.foreground = Color.RED
removeItem.addActionListener { _: ActionEvent? -> sciView.deleteNode(obj.node, true) }
popup.add(removeItem)
popup.show(tree, x, y)
} else {
val path = tree.getPathForLocation(e.x, e.y)
if (path != null && e.x / 1.2 < tree.getPathBounds(path).x + 16) {
val n = path.lastPathComponent as? SwingSceneryTreeNode
if (n != null) {
val node = n.node
if (node != null && node !is Camera && node !is Scene) {
node.visible = !node.visible
tree.repaint()
}
}
e.consume()
}
}
}
})
}
private fun updateTree(node: Node) {
val treeNode = getTreeNode(node, treeModel.root as TreeNode)?: return
treeModel.nodeChanged(treeNode)
}
private fun getTreeNode(node: Node, parent: TreeNode): TreeNode? {
for(i in 0..treeModel.getChildCount(parent)-1) {
val child = treeModel.getChild(parent, i) as SwingSceneryTreeNode
if(child.node == node) return child
val treeNode = getTreeNode(node, child)
if(treeNode != null) return treeNode
}
return null;
}
var currentNode: Node? = null
private set
private var currentProperties: Properties? = null
private lateinit var inputPanel: SwingInputPanel
private val updateLock = ReentrantLock()
/** Generates a properties panel for the given node. */
fun updateProperties(sceneNode: Node?) {
if (sceneNode == null) {
return
}
try {
if (updateLock.tryLock() || updateLock.tryLock(200, TimeUnit.MILLISECONDS)) {
if (currentNode === sceneNode && currentProperties != null) {
currentProperties!!.updateCommandFields()
inputPanel.refresh()
updateLock.unlock()
return
}
currentNode = sceneNode
// Prepare the Properties command module instance.
val info = commandService.getCommand(Properties::class.java)
val module = moduleService.createModule(info)
resolveInjectedInputs(module)
module.setInput("sciView", sciView)
module.setInput("sceneNode", sceneNode)
module.resolveInput("sciView")
module.resolveInput("sceneNode")
val p = module.delegateObject as Properties
currentProperties = p
p.setSceneNode(sceneNode)
val additionalUIs = sceneNode.metadata
.filter { it.key.startsWith("sciview-inspector-") }
.filter { it.value as? CustomPropertyUI != null }
@Suppress("UNCHECKED_CAST")
additionalUIs.forEach { (name, value) ->
val ui = value as CustomPropertyUI
log.info("Additional UI requested by $name, module ${ui.module.info.name}")
for (moduleItem in ui.getMutableInputs()) {
log.info("${moduleItem.name}/${moduleItem.label} added, based on ${ui.module}")
p.addInput(moduleItem, ui.module)
}
}
// Prepare the SwingInputHarvester.
val pluginInfo = pluginService.getPlugin(SwingGroupingInputHarvester::class.java)
val pluginInstance = pluginService.createInstance(pluginInfo)
val harvester = pluginInstance as SwingGroupingInputHarvester
inputPanel = harvester.createInputPanel()
inputPanel.component.layout = MigLayout("fillx,wrap 1", "[right,fill,grow]")
// Build the panel.
try {
harvester.buildPanel(inputPanel, module)
updatePropertiesPanel(inputPanel.component)
} catch (exc: ModuleException) {
log.error(exc)
val stackTrace = DebugUtils.getStackTrace(exc)
val textArea = JTextArea()
textArea.text = "<html><pre>$stackTrace</pre>"
updatePropertiesPanel(textArea)
}
updateLock.unlock()
}
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
private fun updatePropertiesPanel(c: Component?) {
props.removeAll()
if (c == null) {
val usageLabel = JLabel("<html><em>No node selected.</em><br><br>" +
Help.getBasicUsageText(sciView.publicGetInputHandler()) + "</html>")
usageLabel.preferredSize = Dimension(300, 100)
props.add(usageLabel)
} else {
props.add(c)
props.size = c.size
}
props.validate()
props.repaint()
}
private fun find(root: DefaultMutableTreeNode, n: Node): TreePath? {
val e = root.depthFirstEnumeration()
while (e.hasMoreElements()) {
val node = e.nextElement() as DefaultMutableTreeNode
if (node.userObject === n) {
return TreePath(node.path)
}
}
return null
}
/** Rebuilds the tree to match the state of the scene. */
fun rebuildTree() {
val currentPath = tree.selectionPath
treeModel.setRoot(SwingSceneryTreeNode(sciView))
// treeModel.reload();
// // TODO: retain previously expanded nodes only
// for( int i = 0; i < tree.getRowCount(); i++ ) {
// tree.expandRow( i );
// }
// updateProperties( sciView.getActiveNode() );
if (currentPath != null) {
val selectedNode = (currentPath.lastPathComponent as SwingSceneryTreeNode).node ?: return
trySelectNode(selectedNode)
}
}
fun trySelectNode(node: Node) {
val newPath = find(treeModel.root as DefaultMutableTreeNode, node)
if (newPath != null) {
tree.selectionPath = newPath
tree.scrollPathToVisible(newPath)
if (node !== sciView.activeNode) {
updateProperties(node)
}
}
}
/** Retrieves the scenery node of a given tree node. */
private fun sceneNode(treePath: TreePath?): Node? {
if (treePath == null) return null
val treeNode = treePath.lastPathComponent as? SwingSceneryTreeNode ?: return null
val userObject = treeNode.userObject
return if (userObject !is Node) null else userObject
}
/** HACK: Resolve injected [Context] and [Service] inputs. */
private fun resolveInjectedInputs(module: Module) {
for (input in module.info.inputs()) {
val type = input.type
if (Context::class.java.isAssignableFrom(type) || Service::class.java.isAssignableFrom(type)) {
module.resolveInput(input.name)
}
}
}
init {
sciView.scijavaContext!!.inject(this)
}
}
| bsd-2-clause | a70fc802111d843eab7bff6a465a8d3f | 37.026253 | 107 | 0.598569 | 4.845803 | false | false | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/ui/viewbinding/ViewBinding.kt | 1 | 1633 | package de.droidcon.berlin2018.ui.viewbinding
import android.view.View
import android.view.ViewGroup
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Controller.LifecycleListener
import com.squareup.picasso.Picasso
import de.droidcon.berlin2018.ui.MviController
import de.droidcon.berlin2018.ui.applicationComponent
import de.droidcon.berlin2018.ui.navigation.Navigator
/**
* A ViewBinder is the middle man component between a controller and the real UI widgets.
* Hence a [Controller] has no direct reference to a UI widget but is rather just the Lifecycle Container.
*
*
* To avoid memory leaks a [ViewBinding] is lifecycle aware of Controller's View Lifecycle namely
* [Controller.onCreateView] and [Controller.onDestroyView]
*
* @author Hannes Dorfmann
*/
abstract class ViewBinding : LifecycleListener(), LifecycleOwner {
lateinit protected var picasso: Picasso
lateinit protected var navigator: Navigator
lateinit protected var controller: Controller
var restoringViewState = false
private val clearCallbacks = ArrayList<() -> Unit>()
override fun postCreateView(controller: Controller, view: View) {
this.controller = controller
picasso = controller.applicationComponent().picasso()
navigator = (controller as MviController<*, *>).navigator
bindView(view as ViewGroup)
}
override fun postDestroyView(controller: Controller) {
for (callback in clearCallbacks) {
callback()
}
}
protected abstract fun bindView(rootView: ViewGroup)
override fun addListener(clearCallback: () -> Unit) {
clearCallbacks.add(clearCallback)
}
}
| apache-2.0 | 5c87ea661782edd6bf0acd5c762e6565 | 33.020833 | 106 | 0.773423 | 4.679083 | false | false | false | false |
GunoH/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSingleSecondEntityImpl.kt | 2 | 10588 | package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSingleSecondEntityImpl(val dataSource: ChildSingleSecondEntityData) : ChildSingleSecondEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(ParentSingleAbEntity::class.java,
ChildSingleAbstractBaseEntity::class.java,
ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
override val commonData: String
get() = dataSource.commonData
override val parentEntity: ParentSingleAbEntity
get() = snapshot.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this)!!
override val secondData: String
get() = dataSource.secondData
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ChildSingleSecondEntityData?) : ModifiableWorkspaceEntityBase<ChildSingleSecondEntity, ChildSingleSecondEntityData>(
result), ChildSingleSecondEntity.Builder {
constructor() : this(ChildSingleSecondEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSingleSecondEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isCommonDataInitialized()) {
error("Field ChildSingleAbstractBaseEntity#commonData should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToAbstractOneParent<WorkspaceEntityBase>(PARENTENTITY_CONNECTION_ID, this) == null) {
error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] == null) {
error("Field ChildSingleAbstractBaseEntity#parentEntity should be initialized")
}
}
if (!getEntityData().isSecondDataInitialized()) {
error("Field ChildSingleSecondEntity#secondData should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as ChildSingleSecondEntity
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.commonData != dataSource.commonData) this.commonData = dataSource.commonData
if (this.secondData != dataSource.secondData) this.secondData = dataSource.secondData
if (parents != null) {
val parentEntityNew = parents.filterIsInstance<ParentSingleAbEntity>().single()
if ((this.parentEntity as WorkspaceEntityBase).id != (parentEntityNew as WorkspaceEntityBase).id) {
this.parentEntity = parentEntityNew
}
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var commonData: String
get() = getEntityData().commonData
set(value) {
checkModificationAllowed()
getEntityData(true).commonData = value
changedProperty.add("commonData")
}
override var parentEntity: ParentSingleAbEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false,
PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity
}
else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)]!! as ParentSingleAbEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*, *>) {
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var secondData: String
get() = getEntityData().secondData
set(value) {
checkModificationAllowed()
getEntityData(true).secondData = value
changedProperty.add("secondData")
}
override fun getEntityClass(): Class<ChildSingleSecondEntity> = ChildSingleSecondEntity::class.java
}
}
class ChildSingleSecondEntityData : WorkspaceEntityData<ChildSingleSecondEntity>() {
lateinit var commonData: String
lateinit var secondData: String
fun isCommonDataInitialized(): Boolean = ::commonData.isInitialized
fun isSecondDataInitialized(): Boolean = ::secondData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ChildSingleSecondEntity> {
val modifiable = ChildSingleSecondEntityImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildSingleSecondEntity {
return getCached(snapshot) {
val entity = ChildSingleSecondEntityImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSingleSecondEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildSingleSecondEntity(commonData, secondData, entitySource) {
this.parentEntity = parents.filterIsInstance<ParentSingleAbEntity>().single()
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
res.add(ParentSingleAbEntity::class.java)
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildSingleSecondEntityData
if (this.entitySource != other.entitySource) return false
if (this.commonData != other.commonData) return false
if (this.secondData != other.secondData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildSingleSecondEntityData
if (this.commonData != other.commonData) return false
if (this.secondData != other.secondData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + commonData.hashCode()
result = 31 * result + secondData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + commonData.hashCode()
result = 31 * result + secondData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
| apache-2.0 | a37f26202c2b5aeca1cd79ed70e3051d | 37.501818 | 165 | 0.70476 | 5.662032 | false | false | false | false |
vovagrechka/fucking-everything | 1/spew/src/main/java/spew.kt | 1 | 8836 | package vgrechka.spew
//import org.jetbrains.kotlin.psi.*
//import vgrechka.*
//import java.util.*
//
//interface Spew {
// fun ignite(ktFile: KtFile, outputFilePath: String, spewResults: SpewResults, allKtFiles: List<KtFile>)
//}
//
//class SpewResults {
// val ddl = StringBuilder()
//}
//
//class SpewForInputFileOptions(val annotations: Boolean = false)
//
//fun spewForInputFiles(paths: List<String>): SpewResults {
// imf("Update this shit for recent Kotlin compiler")
//
//// val analysisResult = try {
//// clog("Working like a dog, analyzing your crappy sources...")
//// FuckedCLICompiler.doMain(FuckedK2JVMCompiler(), paths.map{it.substituteMyVars()}.toTypedArray())
//// wtf("61ea9f24-7e40-45d8-a858-e357cccff2a0")
//// } catch (e: EnoughFuckedCompiling) {
//// e
//// }
////
//// val ktFiles = analysisResult.environment.getSourceFiles()
//// val spewResults = SpewResults()
//// for (ktFile in ktFiles) {
//// for (ann in ktFile.freakingFindAnnotations(GSpit::class.simpleName!!)) {
//// val spewClassName = ann.freakingGetStringAttribute(GSpit::spewClassName.name) ?: wtf("c301fe3f-a716-44c7-9931-70353676036b")
//// val spewClass = Class.forName(spewClassName)
////
////// val spewAttributeText = ann.freakingGetClassAttributeText(GSpit::spew.name) ?: wtf("c301fe3f-a716-44c7-9931-70353676036b")
////// val colonColonIndex = spewAttributeText.indexOfOrNull("::") ?: wtf("e194e277-2f5f-40f8-9664-fd9b162f69b6")
////// val spewClass = Class.forName("vgrechka.spew.${spewAttributeText.substring(0, colonColonIndex)}")
////
//// val spew = spewClass.newInstance() as Spew
//// val outputFilePath = ann.freakingGetStringAttribute(GSpit::output.name) ?: wtf("3af6ca59-bae4-4659-8806-28e0b1395a0c")
//// spew.ignite(ktFile, outputFilePath.substituteMyVars(), spewResults, ktFiles)
//// }
//// }
////
//// return spewResults
//}
//
//object GlobalSpewContext {
// private var uid = 0L
// var opts = SpewForInputFileOptions()
// val uidToCapturedStack = mutableMapOf<Long, Exception>()
//
// fun nextUID() = ++uid
//
// fun maybeDebugInfo(): String {
// if (!opts.annotations) return ""
// return buildString {
// ln(); ln(); ln()
// ln("/*")
// for ((uid, exception) in uidToCapturedStack) {
// append(" *$uid <-- ")
// for (stackTraceElement in exception.stackTrace.drop(1)) {
// append(stackTraceElement.fileName + ":" + stackTraceElement.lineNumber + " ")
// }
// ln()
// }
// ln(" */")
// }
// }
//}
//
//class CodeShitter(val indent: Int = 0,
// val isOneForProducingDebugInfoInTheEnd: Boolean = false,
// val beforeReification: (CodeShitter) -> Unit = {}) {
// val buf = StringBuilder()
// val tag = "{{" + UUID.randomUUID().toString() + "}}"
// val subPlaces = mutableListOf<CodeShitter>()
//
// fun deleteLastCommaBeforeNewLine() {
// val shit = listOf(",\r\n", ",\n").find {buf.endsWith(it)}
// if (shit != null) {
// buf.setLength(buf.length - shit.length)
// buf.append("\n")
// }
// }
//
// fun deleteLastCommaBeforeDoubleQuoteClosingParenAndNewLine() {
// val shit = listOf(",\")\r\n", ",\")\n").find {buf.endsWith(it)}
// if (shit != null) {
// buf.setLength(buf.length - shit.length)
// buf.append("\")\n")
// }
// }
//
// fun append(text: String) {
// if (GlobalSpewContext.opts.annotations) {
// val uid = GlobalSpewContext.nextUID()
// GlobalSpewContext.uidToCapturedStack[uid] = Exception()
// buf += "/*$uid*/"
// }
// buf += text
// }
//
// fun ln(text: String = "") = appendln(text)
//
// fun appendln(text: String = "") {
// append(" ".repeat(indent) + text + "\n")
// }
//
// fun append(place: CodeShitter) {
// subPlaces += place
// buf.append(place.tag)
// }
//
// fun appendBetweenNewlines(place: CodeShitter) {
// appendln(foldableSpacerMarker)
// append(place)
// appendln(foldableSpacerMarker)
// }
//
// fun reify(): String {
// beforeReification(this)
// var res = buf.toString()
// for (subPlace in subPlaces) {
// val reifiedSubPlace = subPlace.reify()
// res = res.replace(subPlace.tag, reifiedSubPlace)
// }
//
// return res
// }
//
// fun line(text: String, numNewlines: Int = 1) {
// var s = dedent(text)
// s = reindent(indent, s)
// if (!s.endsWith("\n")) s += "\n".repeat(numNewlines)
// buf += s
// }
//
// fun linen(text: String) {
// line(text, numNewlines = 2)
// }
//
// fun bigSection(title: String) {
// line("")
// line("// ==================================================================")
// line("// $title")
// line("// ==================================================================")
// line("")
// }
//
// fun smallSection(title: String) {
// line("// ------------------------------------------------------------------")
// line("// $title")
// line("// ------------------------------------------------------------------")
// line("")
// }
//
// fun headerComment() {
// line(numNewlines = 2, text = """
// /*
// * (C) Copyright 2017 Vladimir Grechka
// *
// * YOU DON'T MESS AROUND WITH THIS SHIT, IT WAS GENERATED BY A TOOL SMARTER THAN YOU
// */""")
// }
//
// companion object {
// val foldableSpacerMarker = "// @@foldable-spacer"
//
// enum class LineFoldingState {FIRST, SECOND}
//
// fun foldSpacers(res: String): String {
// val inLines = res.lines()
// val outLines = mutableListOf<String>()
// var state = LineFoldingState.FIRST
// for (line in inLines) {
// val isFoldableSpacer = line.trim() == foldableSpacerMarker
// exhaustive=when (state) {
// LineFoldingState.FIRST -> {
// if (isFoldableSpacer) {
// outLines += ""
// state = LineFoldingState.SECOND
// } else {
// outLines += line
// }
// }
// LineFoldingState.SECOND -> {
// if (isFoldableSpacer) {
// } else {
// outLines += line
// state = LineFoldingState.FIRST
// }
// }
// }
// }
//
// return outLines.joinToString("\n")
// }
// }
//}
//
//fun KtAnnotationEntry.freakingGetStringAttribute(name: String): String? {
// return this.freakingGetAttribute(name) {it.freakingSimpleStringValue()}
//}
//
//fun KtAnnotationEntry.freakingGetClassAttributeText(name: String): String? {
// return this.freakingGetAttribute(name) {
// (it.getArgumentExpression() as KtClassLiteralExpression).text
// }
//}
//
//fun KtAnnotationEntry.freakingGetEnumAttributeText(name: String): String? {
// return this.freakingGetAttribute(name) {
// (it.getArgumentExpression() as KtDotQualifiedExpression).text
// }
//}
//
//fun <T> KtAnnotationEntry.freakingGetAttribute(name: String, convert: (KtValueArgument) -> T): T? {
// for (valueArgument in this.valueArguments) {
// val ktValueArgument = valueArgument as KtValueArgument
// val argName = ktValueArgument.getArgumentName()!!.text
// if (argName == name) {
// return convert(ktValueArgument)
// }
// }
// return null
//}
//
//fun KtValueArgument.freakingSimpleStringValue(): String =
// (getArgumentExpression() as KtStringTemplateExpression).entries[0].text
//
//fun KtAnnotated.freakingFindAnnotation(type: String) =
// annotationEntries.find {it.typeReference!!.text == type}
//
//fun KtAnnotated.freakingFindAnnotations(type: String) =
// annotationEntries.filter {it.typeReference!!.text == type}
//
//fun KtElement.freakingVisitClasses(onClass: (KtClass) -> Unit) {
// accept(object : KtVisitor<Unit, Unit>() {
// override fun visitKtFile(file: KtFile, data: Unit?) {
// for (decl in file.declarations) {
// decl.accept(this)
// }
// }
//
// override fun visitClass(klass: KtClass, data: Unit?) {
// onClass(klass)
// }
// })
//}
| apache-2.0 | 8689a69d9c35d570325856eca056c482 | 34.063492 | 140 | 0.527727 | 3.777683 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/secondStep/modulesEditor/ModulesEditorComponent.kt | 2 | 4401 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.secondStep.modulesEditor
import com.intellij.ui.JBColor
import com.intellij.ui.ScrollPaneFactory
import com.intellij.util.ui.JBUI
import org.jetbrains.kotlin.idea.statistics.WizardStatsService.UiEditorUsageStats
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.ValidationResult
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.ListSettingType
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.KotlinPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.customPanel
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.BorderFactory
import javax.swing.JComponent
class ModulesEditorComponent(
context: Context,
uiEditorUsagesStats: UiEditorUsageStats?,
needBorder: Boolean,
private val editable: Boolean,
oneEntrySelected: (data: DisplayableSettingItem?) -> Unit
) : SettingComponent<List<Module>, ListSettingType<Module>>(KotlinPlugin.modules.reference, context) {
private val tree: ModulesEditorTree =
ModulesEditorTree(
onSelected = { oneEntrySelected(it) },
context = context,
isTreeEditable = editable,
addModule = { component ->
val isMppProject = KotlinPlugin.projectKind.reference.value == ProjectKind.Singleplatform
moduleCreator.create(
target = null, // The empty tree case
allowMultiplatform = isMppProject,
allowSinglePlatformJsBrowser = isMppProject,
allowSinglePlatformJsNode = isMppProject,
allowAndroid = isMppProject,
allowIos = isMppProject,
allModules = value ?: emptyList(),
createModule = model::add
)?.showInCenterOf(component)
}
).apply {
if (editable) {
border = JBUI.Borders.emptyRight(10)
}
}
private val model = TargetsModel(tree, ::value, context, uiEditorUsagesStats)
override fun onInit() {
super.onInit()
updateModel()
if (editable) {
value?.firstOrNull()?.let(tree::selectModule)
}
}
private fun updateModel() {
model.update()
}
override fun navigateTo(error: ValidationResult.ValidationError) {
val targetModule = error.target as? Module ?: return
tree.selectModule(targetModule)
}
private val moduleCreator = NewModuleCreator()
private val toolbarDecorator = if (editable) ModulesEditorToolbarDecorator(
tree = tree,
moduleCreator = moduleCreator,
model = model,
getModules = { value ?: emptyList() },
isMultiplatformProject = { KotlinPlugin.projectKind.reference.value != ProjectKind.Singleplatform }
) else null
override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) {
customPanel {
if (needBorder) {
border = BorderFactory.createLineBorder(JBColor.border())
}
add(createEditorComponent(), BorderLayout.CENTER)
}
}
private fun createEditorComponent() =
when {
editable -> toolbarDecorator!!.createToolPanel()
else -> ScrollPaneFactory.createScrollPane(tree, true).apply {
viewport.background = JBColor.PanelBackground
}
}.apply {
preferredSize = Dimension(TREE_WIDTH, preferredSize.height)
}
override val validationIndicator: ValidationIndicator? = null
companion object {
private const val TREE_WIDTH = 260
}
}
| apache-2.0 | 7f1af48ded6e977979f3abd2a4932ad4 | 39.75 | 158 | 0.687344 | 4.961669 | false | false | false | false |
GunoH/intellij-community | plugins/devkit/intellij.devkit.workspaceModel/src/WorkspaceImplObsoleteInspection.kt | 3 | 3101 | // 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.devkit.workspaceModel
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiLiteralExpression
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.workspaceModel.storage.CodeGeneratorVersions
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.stubindex.KotlinClassShortNameIndex
import org.jetbrains.kotlin.parsing.parseNumericLiteral
import org.jetbrains.kotlin.psi.*
private val LOG = logger<WorkspaceImplObsoleteInspection>()
class WorkspaceImplObsoleteInspection: LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitClass(klass: KtClass) {
if (!klass.isWorkspaceEntity()) return
val targetApiVersion = calculateTargetApiVersion(klass.resolveScope, klass.project)
if (targetApiVersion == null) {
LOG.info("Can't evaluate target API version for ${klass.name}")
return
}
if (klass.name == "Builder") return
val foundImplClasses = KotlinClassShortNameIndex.get("${klass.name}Impl", klass.project, GlobalSearchScope.allScope(klass.project))
if (foundImplClasses.isEmpty()) return
val implClass = foundImplClasses.first()
val apiVersion = (implClass as? KtClass)?.getApiVersion()
if (apiVersion == targetApiVersion) return
holder.registerProblem(klass.nameIdentifier!!, DevKitWorkspaceModelBundle.message("inspection.workspace.msg.obsolete.implementation"),
RegenerateWorkspaceModelFix(klass.nameIdentifier!!))
}
}
private fun calculateTargetApiVersion(scope: GlobalSearchScope, project: Project): Int? {
val generatorVersionsClass = JavaPsiFacade.getInstance(project).findClass(CodeGeneratorVersions::class.java.name, scope) ?: return null
val versionField = generatorVersionsClass.findFieldByName("API_VERSION_INTERNAL", false) ?: return null
return (versionField.initializer as? PsiLiteralExpression)?.value as? Int
}
}
private class RegenerateWorkspaceModelFix(psiElement: PsiElement) : LocalQuickFixOnPsiElement(psiElement) {
override fun getText() = DevKitWorkspaceModelBundle.message("inspection.workspace.msg.regenerate.implementation")
override fun getFamilyName() = name
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
val projectFileIndex = ProjectRootManager.getInstance(project).fileIndex
val module = projectFileIndex.getModuleForFile(file.virtualFile)
WorkspaceModelGenerator.generate(project, module!!)
}
} | apache-2.0 | 4bef14d7ee176e1cdfeb24224781372b | 49.852459 | 140 | 0.7891 | 4.937898 | false | false | false | false |
smmribeiro/intellij-community | uast/uast-common/src/org/jetbrains/uast/internal/implementationUtils.kt | 2 | 3663 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.internal
import com.intellij.diagnostic.AttachmentFactory
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.RecursionManager
import com.intellij.psi.PsiElement
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.visitor.UastVisitor
fun List<UElement>.acceptList(visitor: UastVisitor) {
for (element in this) {
element.accept(visitor)
}
}
@Suppress("unused")
inline fun <reified T : UElement> T.log(text: String = ""): String {
val className = T::class.java.simpleName
return if (text.isEmpty()) className else "$className ($text)"
}
fun <U : UElement> Array<out Class<out UElement>>.accommodate(vararg makers: UElementAlternative<out U>): Sequence<U> {
val makersSeq = makers.asSequence()
return this.asSequence()
.flatMap { requiredType -> makersSeq.filter { requiredType.isAssignableFrom(it.uType) } }
.distinct()
.mapNotNull { it.make.invoke() }
}
inline fun <reified U : UElement> alternative(noinline make: () -> U?) = UElementAlternative(U::class.java, make)
class UElementAlternative<U : UElement>(val uType: Class<U>, val make: () -> U?)
inline fun <reified T : UElement> convertOrReport(psiElement: PsiElement, parent: UElement): T? =
convertOrReport(psiElement, parent, T::class.java)
fun <T : UElement> convertOrReport(psiElement: PsiElement, parent: UElement, expectedType: Class<T>): T? {
fun UElement.safeToString(): String = RecursionManager.doPreventingRecursion(this, false) {
toString()
} ?: "<recursive `toString()` computation $javaClass>"
fun mkAttachments(): Array<Attachment> = ArrayList<Attachment>().also { result ->
result.add(Attachment("info.txt", buildString {
appendLine("context: ${parent.javaClass}")
appendLine("psiElement: ${psiElement.javaClass}")
appendLine("expectedType: $expectedType")
}))
result.add(Attachment("psiElementContent.txt", runCatching { psiElement.text ?: "<null>" }.getOrElse { it.stackTraceToString() }))
result.add(Attachment("uast-plugins.list", UastFacade.languagePlugins.joinToString("\n") { it.javaClass.toString() }))
result.add(runCatching { psiElement.containingFile }
.mapCatching { it.virtualFile }
.fold({ AttachmentFactory.createAttachment(it) }, { Attachment("containingFile-exception.txt", it.stackTraceToString()) }))
}.toTypedArray()
val plugin = parent.sourcePsi?.let { UastFacade.findPlugin(it) } ?: UastFacade.findPlugin(psiElement)
if (plugin == null) {
Logger.getInstance(parent.javaClass)
.error("cant get UAST plugin for ${parent.safeToString()} to convert element $psiElement", *mkAttachments())
return null
}
val result = expectedType.cast(plugin.convertElement(psiElement, parent, expectedType))
if (result == null) {
Logger.getInstance(parent.javaClass)
.error("failed to convert element $psiElement in ${parent.safeToString()}", *mkAttachments())
}
return result
} | apache-2.0 | 27c7c11ad2530cac1ef452701b4d5175 | 42.105882 | 140 | 0.727546 | 4.21519 | false | false | false | false |
simonnorberg/dmach | app/src/main/java/net/simno/dmach/db/PatchEntity.kt | 1 | 692 | package net.simno.dmach.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(tableName = "patch", indices = [Index("title", unique = true)])
data class PatchEntity(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") val _id: Int?,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "sequence") val sequence: String,
@ColumnInfo(name = "channels") val channels: String,
@ColumnInfo(name = "selected") val selected: Int,
@ColumnInfo(name = "tempo") val tempo: Int,
@ColumnInfo(name = "swing") val swing: Int,
@ColumnInfo(name = "active") val active: Boolean
)
| gpl-3.0 | a746312533de2196f122899fc6f2f1d0 | 37.444444 | 77 | 0.700867 | 3.72043 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/SpinnerLanguagesAdapter.kt | 1 | 3754 | package fr.free.nrw.commons.upload
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import androidx.annotation.LayoutRes
import androidx.core.os.ConfigurationCompat
import fr.free.nrw.commons.R
import fr.free.nrw.commons.utils.LangCodeUtils
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.row_item_languages_spinner.*
import org.apache.commons.lang3.StringUtils
import org.wikipedia.language.AppLanguageLookUpTable
import java.util.*
/**
* This class handles the display of language spinners and their dropdown views for UploadMediaDetailFragment
*
* @property selectedLanguages - controls the enabled state of dropdown views
*
* @param context - required by super constructor
*/
class SpinnerLanguagesAdapter constructor(
context: Context,
private val selectedLanguages: HashMap<*, String>
) : ArrayAdapter<Any?>(context, -1) {
private val languageNamesList: List<String>
private val languageCodesList: List<String>
var language: AppLanguageLookUpTable = AppLanguageLookUpTable(context)
init {
languageNamesList = language.localizedNames;
languageCodesList = language.codes;
}
var selectedLangCode = ""
override fun isEnabled(position: Int) = languageCodesList[position].let {
it.isNotEmpty() && !selectedLanguages.containsValue(it) && it != selectedLangCode
}
override fun getCount() = languageNamesList.size
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup) =
(convertView ?: parent.inflate(R.layout.row_item_languages_spinner).also {
it.tag = DropDownViewHolder(it)
}).apply {
(tag as DropDownViewHolder).init(
languageCodesList[position],
languageNamesList[position],
isEnabled(position)
)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup) =
(convertView ?: parent.inflate(R.layout.row_item_languages_spinner).also {
it.tag = SpinnerViewHolder(it)
}).apply { (tag as SpinnerViewHolder).init(languageCodesList[position]) }
class SpinnerViewHolder(override val containerView: View) : LayoutContainer {
fun init(languageCode: String) {
LangCodeUtils.fixLanguageCode(languageCode).let {
tv_language.text = if (it.length > 2) it.take(2) else it
}
}
}
class DropDownViewHolder(override val containerView: View) : LayoutContainer {
fun init(languageCode: String, languageName: String, enabled: Boolean) {
tv_language.isEnabled = enabled
if (languageCode.isEmpty()) {
tv_language.text = StringUtils.capitalize(languageName)
tv_language.textAlignment = View.TEXT_ALIGNMENT_CENTER
} else {
tv_language.text =
"${StringUtils.capitalize(languageName)}" +
" [${LangCodeUtils.fixLanguageCode(languageCode)}]"
}
}
}
fun getLanguageCode(position: Int): String {
return languageCodesList[position]
}
fun getIndexOfUserDefaultLocale(context: Context): Int {
return languageCodesList.indexOf(context.locale.language)
}
fun getIndexOfLanguageCode(languageCode: String): Int {
return languageCodesList.indexOf(languageCode)
}
}
private fun ViewGroup.inflate(@LayoutRes resId: Int) =
LayoutInflater.from(context).inflate(resId, this, false)
private val Context.locale: Locale
get() = ConfigurationCompat.getLocales(resources.configuration)[0]
| apache-2.0 | 837b04f923f2964466bfdd8aa692cf29 | 36.168317 | 109 | 0.691529 | 4.72796 | false | false | false | false |
vnesek/nmote-jwt-issuer | src/main/kotlin/com/nmote/jwti/web/AdminController.kt | 1 | 4529 | /*
* Copyright 2017. Vjekoslav Nesek
* 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.nmote.jwti.web
import com.nmote.jwti.model.*
import com.nmote.jwti.repository.AppRepository
import com.nmote.jwti.repository.UserRepository
import com.nmote.jwti.service.AppNotFoundException
import com.nmote.jwti.service.JwtAuthenticationService
import com.nmote.jwti.service.ScopeService
import io.jsonwebtoken.JwtException
import org.springframework.http.HttpStatus
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.*
data class ConfigData(val app: AppData, val users: Iterable<UserData>)
@ResponseStatus(HttpStatus.NOT_FOUND)
class UserNotFoundException(id: String) : JwtException(id)
@RequestMapping("/api")
@CrossOrigin
@RestController
class AdminController(
private val users: UserRepository,
private val apps: AppRepository,
private val auth: JwtAuthenticationService,
private val scopes: ScopeService
) {
@GetMapping("health")
fun health(): Map<String, Boolean> {
val usersOk = try {
users.findById("ignored")
true
} catch (e: Throwable) {
false
}
val appsOk = try {
apps["ignored"]
true
} catch (e: Throwable) {
false
}
return mapOf(
"users" to usersOk,
"apps" to appsOk,
"running" to (usersOk && appsOk)
)
}
@GetMapping("config")
fun getConfig(): ConfigData {
auth.hasScope("issuer:admin")
return ConfigData(getApp().toAppData(), getAll())
}
private fun getApp(): App = apps.findByAudience(auth.audience) ?: throw AppNotFoundException(auth.audience)
@GetMapping("users")
fun getAll(): List<UserData> {
auth.hasScope("issuer:admin")
val app = getApp()
return users.findAll().map { it.toUserData(app) }
}
@Transactional
@PostMapping("users/merge")
fun merge(@RequestParam id: List<String>): UserData {
auth.hasScope("issuer:admin")
if (id.size < 2) throw Exception("at least two users required for merge")
val app = getApp()
val u = id.map(this::getUser)
val user = u[0]
val mergees = u.subList(1, u.size)
mergees.forEach(user::merge)
users.deleteAll(mergees)
users.save(user)
return user.toUserData(app)
}
@GetMapping("users/{id}/roles")
fun getRoles(@PathVariable id: String): Set<String> {
auth.hasScope("issuer:admin")
val app = getApp()
return getUser(id).roles[app.id] ?: emptySet()
}
@Transactional
@PutMapping("users/{id}/roles")
fun setRoles(@PathVariable id: String, @RequestBody roles: Set<String>): Set<String> {
auth.hasScope("issuer:admin")
val app = getApp()
val user = getUser(id)
user.roles[app.id] = roles
users.save(user)
return roles
}
@Transactional
@DeleteMapping("users/{id}")
fun delete(@PathVariable id: String): UserData {
auth.hasScope("issuer:admin")
val app = getApp()
val user = getUser(id)
users.deleteAll(setOf(user))
return user.toUserData(app)
}
private fun getUser(id: String) = users.findById(id).orElseThrow { UserNotFoundException(id) }
private fun User.toUserData(app: App) = UserData(
id = accountId,
username = username,
type = socialService,
name = profileName,
email = profileEmail,
image = profileImageURL,
roles = roles[app.id],
scope = scopes.scopeFor(this, app),
accounts = accounts.map { it.toUserData(app) })
private fun SocialAccount<*>.toUserData(app: App) = UserData(
id = accountId,
type = socialService,
name = profileName,
email = profileEmail,
scope = scopes.scopeFor(this, app),
image = profileImageURL)
} | apache-2.0 | e626a7045bd5a760f1080870383586e3 | 30.458333 | 111 | 0.642305 | 4.083859 | false | false | false | false |
shivamsriva31093/MovieFinder | app/src/main/java/task/application/com/colette/messaging/notifications/LatestTrailer.kt | 1 | 2728 | package task.application.com.colette.messaging.notifications
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import com.androidtmdbwrapper.model.mediadetails.MediaBasic
import com.androidtmdbwrapper.model.mediadetails.Video
import com.androidtmdbwrapper.model.movies.MovieInfo
import task.application.com.colette.R
import task.application.com.colette.messaging.PushNotificationChannel
import task.application.com.colette.messaging.PushNotificationItem
import java.util.*
/**
* Created by sHIVAM on 1/28/2018.
*/
internal class LatestTrailer(private val context: Context, private val content: MovieInfo) : PushNotificationItem {
override fun data(): MediaBasic {
return content
}
override fun channel() = PushNotificationChannel.LatestTrailerNotification()
override fun smallIcon(): Int = R.drawable.play
override fun title(): String = "Trending today!"
override fun message(): String = "Bet you didn't watch this awesome trailer!!"
override fun pendingIntent(): PendingIntent {
val resultIntent = startYouTubeIntent()
resultIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
val requestID = System.currentTimeMillis().toInt()
return PendingIntent.getActivity(context, requestID, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun startYouTubeIntent(): Intent {
val id: String = getVideoUrl()
val intent: Intent
intent = if (id.length == 11) {
// youtube video id
Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://$id"))
} else {
// url to video
Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=$id"))
}
try {
if (context.packageManager.getPackageInfo("com.google.android.youtube", 0) != null) {
intent.`package` = "com.google.android.youtube"
}
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
return intent
}
private fun getVideoUrl(): String {
var list: MutableList<Video> = mutableListOf()
try {
list = content.videos.videos
} catch (e: Exception) {
e.printStackTrace()
}
val trailerList = ArrayList<String>()
for (res in list) {
if (res.site == "YouTube")
trailerList.add(res.key)
}
return if (trailerList.isEmpty()) "" else trailerList[0]
}
companion object {
const val KEY_NOTIFICATION_GROUP = "latest_trailer"
}
} | apache-2.0 | e923fecfc0d745e86214687771f9f3c7 | 32.280488 | 115 | 0.665323 | 4.428571 | false | false | false | false |
dodyg/Kotlin101 | src/Objects/Properties/Properties.kt | 1 | 1938 | package Objects.Properties
fun main(args : Array<String>) {
//you cannot change johnClark name. It's immutable
var johnC = Person("John", "Clark")
println("The name is ${johnC.firstName} ${johnC.lastName}")
var markC = Soldier("Mark", "Chavez")
println("The name is ${markC.firstName} ${markC.lastName}")
var vanD = UniversalSoldier("Van", "Damme")
println("The name is ${vanD.firstName} ${vanD.lastName}")
var slyvesterS = UltimateSoldier("Slyvester", "Stallone")
println("The name is ${slyvesterS.firstName} ${slyvesterS.lastName}")
}
//This will make two immutable properties
class Person(val firstName : String, val lastName : String)
//This is another way to declare the immutable properties.
class Soldier(firstName : String, lastName : String) {
public val firstName : String = firstName
public val lastName : String = lastName
}
//Property with backing field
//The compiler only generates a backing field if it is used by the accessors.
class UniversalSoldier(firstName : String, lastName : String) {
public var firstName : String = firstName
get() {
return "Universal " + field
}
set(value) {
field = value
}
public var lastName : String = lastName
}
//property with old java style
class UltimateSoldier(firstName : String, lastName : String) {
private var _firstName = ""
public var firstName : String
get() {
return _firstName
}
set(value) {
_firstName = value
}
private var _lastName = ""
public var lastName : String
get() {
return _lastName
}
set(value) {
_lastName = value
}
init {
//constructor - we cannot initialize directly to the properties because this way there is no backing field
this.firstName = firstName
this.lastName = lastName
}
} | bsd-3-clause | 7723c539d81e77e91d2a97d9f435f853 | 28.378788 | 114 | 0.634675 | 4.231441 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/hypervisor/kvm/Utils.kt | 1 | 4755 | package com.github.kerubistan.kerub.hypervisor.kvm
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.VirtualMachine
import com.github.kerubistan.kerub.model.VirtualStorageLinkInfo
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation
import com.github.kerubistan.kerub.model.services.IscsiService
import com.github.kerubistan.kerub.model.services.NfsService
import com.github.kerubistan.kerub.utils.storage.iscsiStorageId
import io.github.kerubistan.kroki.io.readText
import io.github.kerubistan.kroki.xml.XmlBuilder
import io.github.kerubistan.kroki.xml.xml
import com.github.kerubistan.kerub.utils.storage.iscsiDefaultUser as iscsiUser
private const val file = "file"
private const val dev = "dev"
private const val type = "type"
private const val block = "block"
private const val source = "source"
private const val name = "name"
private const val uuid = "uuid"
private const val iscsi = "iscsi"
private const val unit = "unit"
private const val bytes = "B"
private const val boot = "boot"
private const val address = "address"
private const val allAddresses = "0.0.0.0"
val allocationTypeToDiskType = mapOf(
VirtualStorageFsAllocation::class to file,
VirtualStorageLvmAllocation::class to block
)
private fun kvmDeviceType(linkInfo: VirtualStorageLinkInfo, targetHost: Host): String =
if (isRemoteHost(linkInfo, targetHost)) {
when (linkInfo.hostServiceUsed) {
is NfsService -> file
is IscsiService -> "network"
else -> TODO("not handled service type: $linkInfo")
}
} else {
allocationTypeToDiskType[linkInfo.allocation.javaClass.kotlin] ?: TODO()
}
fun allocationType(deviceDyn: VirtualStorageLinkInfo): String = deviceDyn.allocation.let {
when (it) {
is VirtualStorageLvmAllocation -> "raw"
is VirtualStorageFsAllocation -> it.type.name.toLowerCase()
else -> TODO("not handled allocation type: ${it.javaClass.name}")
}
}
fun XmlBuilder.allocationToXml(linkInfo: VirtualStorageLinkInfo, targetHost: Host) {
if (isRemoteHost(linkInfo, targetHost)) {
when (linkInfo.hostServiceUsed) {
is NfsService -> {
!"nfs"
source(file to "/mnt/${linkInfo.allocation.hostId}/\${linkInfo.allocation.getPath(linkInfo.device.stat.id)")
}
is IscsiService -> {
!iscsi
source("protocol" to iscsi, name to "${iscsiStorageId(linkInfo.device.stat.id)}/1") {
"host"(name to linkInfo.storageHost.stat.address, "port" to 3260)
}
if (linkInfo.hostServiceUsed.password != null) {
"auth"("username" to iscsiUser) {
"secret"(type to iscsi, uuid to linkInfo.device.stat.id)
}
} else !"unauthenticated"
}
else -> TODO("not handled service type: $linkInfo")
}
} else {
when (val allocation = linkInfo.allocation) {
is VirtualStorageFsAllocation -> {
!"local ${allocation.type} file allocation"
source(file to allocation.fileName)
}
is VirtualStorageLvmAllocation -> {
!"local lvm allocation"
source(dev to allocation.path)
}
else -> TODO("not handled allocation type: ${allocation.javaClass.name}")
}
}
}
fun isRemoteHost(linkInfo: VirtualStorageLinkInfo, targetHost: Host) = linkInfo.allocation.hostId != targetHost.id
fun vmDefinitionToXml(
vm: VirtualMachine, disks: List<VirtualStorageLinkInfo>, password: String, targetHost: Host
): String = xml(root = "domain", atts = *arrayOf(type to "kvm")) {
!"vm name: ${vm.name}"
name { -vm.id }
uuid { -vm.id }
"memory"(unit to bytes) { -vm.memory.min }
"memtune" {
"hard_limit"(unit to bytes) { -vm.memory.min }
}
"memoryBacking" {
"allocation"("mode" to "ondemand")
}
"vcpu" { text(vm.nrOfCpus) }
"os" {
type("arch" to "x86_64") { -"hvm" }
boot(dev to "hd")
boot(dev to "cdrom")
}
"features" {
"acpi"()
"apic"()
"pae"()
"hap"()
}
"devices" {
"input"(type to "keyboard", "bus" to "ps2")
"graphics"(type to "spice", "autoport" to "yes", "listen" to allAddresses, "password" to password) {
"listen"(type to address, address to allAddresses)
"image"("compression" to "off")
}
"video" {
"model"(type to "qxl", "ram" to 65535, "vram" to 65535, "vgamem" to 16384, "heads" to 1)
address(type to "pci", "domain" to "0x0000")
}
var targetDev = 'a'
for (link in disks) {
"disk"(type to kvmDeviceType(link, targetHost), "device" to link.link.device.name.toLowerCase()) {
"driver"(name to "qemu", type to allocationType(link), "cache" to "none")
if (link.device.stat.readOnly || link.link.readOnly) {
"readonly"()
}
this.allocationToXml(link, targetHost)
"target"(dev to "sd$targetDev", "bus" to link.link.bus)
}
targetDev++
}
}
}.use { it.reader().readText() }
| apache-2.0 | 753840217f07b46dece1743694690a8d | 33.208633 | 114 | 0.706204 | 3.302083 | false | false | false | false |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/ticket/Ticket.kt | 2 | 1417 | package org.fossasia.openevent.general.ticket
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.PrimaryKey
import com.fasterxml.jackson.databind.PropertyNamingStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming
import com.github.jasminb.jsonapi.IntegerIdHandler
import com.github.jasminb.jsonapi.annotations.Id
import com.github.jasminb.jsonapi.annotations.Relationship
import com.github.jasminb.jsonapi.annotations.Type
import org.fossasia.openevent.general.event.Event
import org.fossasia.openevent.general.event.EventId
@Type("ticket")
@Entity(foreignKeys = [(ForeignKey(entity = Event::class, parentColumns = ["id"],
childColumns = ["event"], onDelete = CASCADE))])
@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy::class)
data class Ticket(
@Id(IntegerIdHandler::class)
@PrimaryKey
val id: Int,
val description: String?,
val type: String?,
val name: String,
val maxOrder: Int = 0,
val isFeeAbsorbed: Boolean? = false,
val isDescriptionVisible: Boolean? = false,
val price: Float,
val position: String?,
val quantity: String?,
val isHidden: Boolean?,
val salesStartsAt: String?,
val salesEndsAt: String?,
val minOrder: Int = 0,
@ColumnInfo(index = true)
@Relationship("event")
var event: EventId? = null
)
| apache-2.0 | b2a04c716841a11e3d3e264bee118707 | 32.738095 | 81 | 0.757234 | 4.014164 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/core/src/main/java/jp/hazuki/yuzubrowser/core/utility/hash/Murmur3.kt | 1 | 25069 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.core.utility.hash
private const val LONG_BYTES = 8
private const val INT_BYTES = 4
private const val SHORT_BYTES = 2
// from 64-bit linear congruential generator
const val NULL_HASHCODE = 2862933555777941757L
// Constants for 32 bit variant
private const val C1_32 = -0x3361d2af
private const val C2_32 = 0x1b873593
private const val R1_32 = 15
private const val R2_32 = 13
private const val M_32 = 5
private const val N_32 = -0x19ab949c
// Constants for 128 bit variant
private const val C1 = -0x783c846eeebdac2bL
private const val C2 = 0x4cf5ad432745937fL
private const val R1 = 31
private const val R2 = 27
private const val R3 = 33
private const val M = 5
private const val N1 = 0x52dce729
private const val N2 = 0x38495ab5
const val DEFAULT_SEED = 104729
/**
* Murmur3 32-bit variant.
*/
fun Long.murmur3Hash32(seed: Int): Int {
var hash = seed
val r0 = java.lang.Long.reverseBytes(this)
hash = mix32(r0.toInt(), hash)
hash = mix32(r0.ushr(32).toInt(), hash)
return fmix32(LONG_BYTES, hash)
}
/**
* Murmur3 32-bit variant.
*/
fun murmur3Hash32(l0: Long, l1: Long, seed: Int): Int {
var hash = seed
val r0 = java.lang.Long.reverseBytes(l0)
val r1 = java.lang.Long.reverseBytes(l1)
hash = mix32(r0.toInt(), hash)
hash = mix32(r0.ushr(32).toInt(), hash)
hash = mix32(r1.toInt(), hash)
hash = mix32(r1.ushr(32).toInt(), hash)
return fmix32(LONG_BYTES * 2, hash)
}
/**
* Murmur3 32-bit variant.
*
* @param offset - offset of data (default 0)
* @param length - length of array (default array size)
* @param seed - seed. (default DEFAULT_SEED)
* @return - hashcode
*/
fun ByteArray.murmur3Hash32(offset: Int = 0, length: Int = size, seed: Int = DEFAULT_SEED): Int {
var hash = seed
val nBlocks = length shr 2
// body
for (i in 0 until nBlocks) {
val i4 = i shl 2
val k = (this[offset + i4].toInt() and 0xff
or (this[offset + i4 + 1].toInt() and 0xff shl 8)
or (this[offset + i4 + 2].toInt() and 0xff shl 16)
or (this[offset + i4 + 3].toInt() and 0xff shl 24))
hash = mix32(k, hash)
}
// tail
val idx = nBlocks shl 2
var k1 = 0
when (length - idx) {
3 -> {
k1 = k1 xor (this[offset + idx + 2].toInt() shl 16)
k1 = k1 xor (this[offset + idx + 1].toInt() shl 8)
k1 = k1 xor this[offset + idx].toInt()
// mix functions
k1 *= C1_32
k1 = Integer.rotateLeft(k1, R1_32)
k1 *= C2_32
hash = hash xor k1
}
2 -> {
k1 = k1 xor (this[offset + idx + 1].toInt() shl 8)
k1 = k1 xor this[offset + idx].toInt()
k1 *= C1_32
k1 = Integer.rotateLeft(k1, R1_32)
k1 *= C2_32
hash = hash xor k1
}
1 -> {
k1 = k1 xor this[offset + idx].toInt()
k1 *= C1_32
k1 = Integer.rotateLeft(k1, R1_32)
k1 *= C2_32
hash = hash xor k1
}
}
return fmix32(length, hash)
}
private fun mix32(k: Int, hash: Int): Int {
var k1 = k
var mHash = hash
k1 *= C1_32
k1 = Integer.rotateLeft(k1, R1_32)
k1 *= C2_32
mHash = mHash xor k1
return Integer.rotateLeft(mHash, R2_32) * M_32 + N_32
}
private fun fmix32(length: Int, hash: Int): Int {
var mHash = hash
mHash = mHash xor length
mHash = mHash xor mHash.ushr(16)
mHash *= -0x7a143595
mHash = mHash xor mHash.ushr(13)
mHash *= -0x3d4d51cb
mHash = mHash xor mHash.ushr(16)
return mHash
}
fun Long.murmur3Hash64(): Long {
var hash = DEFAULT_SEED.toLong()
var k = java.lang.Long.reverseBytes(this)
// mix functions
k *= C1
k = java.lang.Long.rotateLeft(k, R1)
k *= C2
hash = hash xor k
hash = java.lang.Long.rotateLeft(hash, R2) * M + N1
// finalization
hash = hash xor LONG_BYTES.toLong()
hash = fmix64(hash)
return hash
}
fun Int.murmur3Hash64(): Long {
var k1 = Integer.reverseBytes(this).toLong() and (-1L).ushr(32)
var hash = DEFAULT_SEED.toLong()
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
// finalization
hash = hash xor INT_BYTES.toLong()
hash = fmix64(hash)
return hash
}
fun Short.murmur3Hash64(): Long {
var hash = DEFAULT_SEED.toLong()
var k1: Long = 0
k1 = k1 xor (this.toLong() and 0xff shl 8)
k1 = k1 xor ((this.toLong() and 0xFF00 shr 8) and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
// finalization
hash = hash xor SHORT_BYTES.toLong()
hash = fmix64(hash)
return hash
}
/**
* Murmur3 64-bit variant. This is essentially MSB 8 bytes of Murmur3 128-bit variant.
*
* @param length - length of array
* @param seed - seed. (default is 0)
* @return - hashcode
*/
fun ByteArray.murmur3Hash64(offset: Int = 0, length: Int = size, seed: Int = DEFAULT_SEED): Long {
var hash = seed.toLong()
val nBlocks = length shr 3
// body
for (i in 0 until nBlocks) {
val i8 = i shl 3
var k = (this[offset + i8].toLong() and 0xff
or (this[offset + i8 + 1].toLong() and 0xff shl 8)
or (this[offset + i8 + 2].toLong() and 0xff shl 16)
or (this[offset + i8 + 3].toLong() and 0xff shl 24)
or (this[offset + i8 + 4].toLong() and 0xff shl 32)
or (this[offset + i8 + 5].toLong() and 0xff shl 40)
or (this[offset + i8 + 6].toLong() and 0xff shl 48)
or (this[offset + i8 + 7].toLong() and 0xff shl 56))
// mix functions
k *= C1
k = java.lang.Long.rotateLeft(k, R1)
k *= C2
hash = hash xor k
hash = java.lang.Long.rotateLeft(hash, R2) * M + N1
}
// tail
var k1: Long = 0
val tailStart = nBlocks shl 3
when (length - tailStart) {
7 -> {
k1 = k1 xor (this[offset + tailStart + 6].toLong() and 0xff shl 48)
k1 = k1 xor (this[offset + tailStart + 5].toLong() and 0xff shl 40)
k1 = k1 xor (this[offset + tailStart + 4].toLong() and 0xff shl 32)
k1 = k1 xor (this[offset + tailStart + 3].toLong() and 0xff shl 24)
k1 = k1 xor (this[offset + tailStart + 2].toLong() and 0xff shl 16)
k1 = k1 xor (this[offset + tailStart + 1].toLong() and 0xff shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
}
6 -> {
k1 = k1 xor (this[offset + tailStart + 5].toLong() and 0xff shl 40)
k1 = k1 xor (this[offset + tailStart + 4].toLong() and 0xff shl 32)
k1 = k1 xor (this[offset + tailStart + 3].toLong() and 0xff shl 24)
k1 = k1 xor (this[offset + tailStart + 2].toLong() and 0xff shl 16)
k1 = k1 xor (this[offset + tailStart + 1].toLong() and 0xff shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
}
5 -> {
k1 = k1 xor (this[offset + tailStart + 4].toLong() and 0xff shl 32)
k1 = k1 xor (this[offset + tailStart + 3].toLong() and 0xff shl 24)
k1 = k1 xor (this[offset + tailStart + 2].toLong() and 0xff shl 16)
k1 = k1 xor (this[offset + tailStart + 1].toLong() and 0xff shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
}
4 -> {
k1 = k1 xor (this[offset + tailStart + 3].toLong() and 0xff shl 24)
k1 = k1 xor (this[offset + tailStart + 2].toLong() and 0xff shl 16)
k1 = k1 xor (this[offset + tailStart + 1].toLong() and 0xff shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
}
3 -> {
k1 = k1 xor (this[offset + tailStart + 2].toLong() and 0xff shl 16)
k1 = k1 xor (this[offset + tailStart + 1].toLong() and 0xff shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
}
2 -> {
k1 = k1 xor (this[offset + tailStart + 1].toLong() and 0xff shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
}
1 -> {
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
hash = hash xor k1
}
}
// finalization
hash = hash xor length.toLong()
hash = fmix64(hash)
return hash
}
private fun fmix64(h: Long): Long {
var h1 = h
h1 = h1 xor h1.ushr(33)
h1 *= -0xae502812aa7333L
h1 = h1 xor h1.ushr(33)
h1 *= -0x3b314601e57a13adL
h1 = h1 xor h1.ushr(33)
return h1
}
/**
* Murmur3 128-bit variant.
*
* @param offset - the first element of array
* @param length - length of array
* @param seed - seed. (default is 0)
* @return - hashcode (2 longs)
*/
fun ByteArray.murmur3Hash128(offset: Int = 0, length: Int = size, seed: Int = DEFAULT_SEED): LongArray {
var h1 = seed.toLong()
var h2 = seed.toLong()
val nblocks = length shr 4
// body
for (i in 0 until nblocks) {
val i16 = i shl 4
var k1 = (this[offset + i16].toLong() and 0xff
or (this[offset + i16 + 1].toLong() and 0xff shl 8)
or (this[offset + i16 + 2].toLong() and 0xff shl 16)
or (this[offset + i16 + 3].toLong() and 0xff shl 24)
or (this[offset + i16 + 4].toLong() and 0xff shl 32)
or (this[offset + i16 + 5].toLong() and 0xff shl 40)
or (this[offset + i16 + 6].toLong() and 0xff shl 48)
or (this[offset + i16 + 7].toLong() and 0xff shl 56))
var k2 = (this[offset + i16 + 8].toLong() and 0xff
or (this[offset + i16 + 9].toLong() and 0xff shl 8)
or (this[offset + i16 + 10].toLong() and 0xff shl 16)
or (this[offset + i16 + 11].toLong() and 0xff shl 24)
or (this[offset + i16 + 12].toLong() and 0xff shl 32)
or (this[offset + i16 + 13].toLong() and 0xff shl 40)
or (this[offset + i16 + 14].toLong() and 0xff shl 48)
or (this[offset + i16 + 15].toLong() and 0xff shl 56))
// mix functions for k1
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
h1 = java.lang.Long.rotateLeft(h1, R2)
h1 += h2
h1 = h1 * M + N1
// mix functions for k2
k2 *= C2
k2 = java.lang.Long.rotateLeft(k2, R3)
k2 *= C1
h2 = h2 xor k2
h2 = java.lang.Long.rotateLeft(h2, R1)
h2 += h1
h2 = h2 * M + N2
}
// tail
var k1: Long = 0
var k2: Long = 0
val tailStart = nblocks shl 4
when (length - tailStart) {
15 -> {
k2 = k2 xor ((this[offset + tailStart + 14].toLong() and 0xff) shl 48)
k2 = k2 xor ((this[offset + tailStart + 13].toLong() and 0xff) shl 40)
k2 = k2 xor ((this[offset + tailStart + 12].toLong() and 0xff) shl 32)
k2 = k2 xor ((this[offset + tailStart + 11].toLong() and 0xff) shl 24)
k2 = k2 xor ((this[offset + tailStart + 10].toLong() and 0xff) shl 16)
k2 = k2 xor ((this[offset + tailStart + 9].toLong() and 0xff) shl 8)
k2 = k2 xor (this[offset + tailStart + 8].toLong() and 0xff)
k2 *= C2
k2 = java.lang.Long.rotateLeft(k2, R3)
k2 *= C1
h2 = h2 xor k2
k1 = k1 xor ((this[offset + tailStart + 7].toLong() and 0xff) shl 56)
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
14 -> {
k2 = k2 xor ((this[offset + tailStart + 13].toLong() and 0xff) shl 40)
k2 = k2 xor ((this[offset + tailStart + 12].toLong() and 0xff) shl 32)
k2 = k2 xor ((this[offset + tailStart + 11].toLong() and 0xff) shl 24)
k2 = k2 xor ((this[offset + tailStart + 10].toLong() and 0xff) shl 16)
k2 = k2 xor ((this[offset + tailStart + 9].toLong() and 0xff) shl 8)
k2 = k2 xor (this[offset + tailStart + 8].toLong() and 0xff)
k2 *= C2
k2 = java.lang.Long.rotateLeft(k2, R3)
k2 *= C1
h2 = h2 xor k2
k1 = k1 xor ((this[offset + tailStart + 7].toLong() and 0xff) shl 56)
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
13 -> {
k2 = k2 xor ((this[offset + tailStart + 12].toLong() and 0xff) shl 32)
k2 = k2 xor ((this[offset + tailStart + 11].toLong() and 0xff) shl 24)
k2 = k2 xor ((this[offset + tailStart + 10].toLong() and 0xff) shl 16)
k2 = k2 xor ((this[offset + tailStart + 9].toLong() and 0xff) shl 8)
k2 = k2 xor (this[offset + tailStart + 8].toLong() and 0xff)
k2 *= C2
k2 = java.lang.Long.rotateLeft(k2, R3)
k2 *= C1
h2 = h2 xor k2
k1 = k1 xor ((this[offset + tailStart + 7].toLong() and 0xff) shl 56)
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
12 -> {
k2 = k2 xor ((this[offset + tailStart + 11].toLong() and 0xff) shl 24)
k2 = k2 xor ((this[offset + tailStart + 10].toLong() and 0xff) shl 16)
k2 = k2 xor ((this[offset + tailStart + 9].toLong() and 0xff) shl 8)
k2 = k2 xor (this[offset + tailStart + 8].toLong() and 0xff)
k2 *= C2
k2 = java.lang.Long.rotateLeft(k2, R3)
k2 *= C1
h2 = h2 xor k2
k1 = k1 xor ((this[offset + tailStart + 7].toLong() and 0xff) shl 56)
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
11 -> {
k2 = k2 xor ((this[offset + tailStart + 10].toLong() and 0xff) shl 16)
k2 = k2 xor ((this[offset + tailStart + 9].toLong() and 0xff) shl 8)
k2 = k2 xor (this[offset + tailStart + 8].toLong() and 0xff)
k2 *= C2
k2 = java.lang.Long.rotateLeft(k2, R3)
k2 *= C1
h2 = h2 xor k2
k1 = k1 xor ((this[offset + tailStart + 7].toLong() and 0xff) shl 56)
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
10 -> {
k2 = k2 xor ((this[offset + tailStart + 9].toLong() and 0xff) shl 8)
k2 = k2 xor (this[offset + tailStart + 8].toLong() and 0xff)
k2 *= C2
k2 = java.lang.Long.rotateLeft(k2, R3)
k2 *= C1
h2 = h2 xor k2
k1 = k1 xor ((this[offset + tailStart + 7].toLong() and 0xff) shl 56)
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
9 -> {
k2 = k2 xor (this[offset + tailStart + 8].toLong() and 0xff)
k2 *= C2
k2 = java.lang.Long.rotateLeft(k2, R3)
k2 *= C1
h2 = h2 xor k2
k1 = k1 xor ((this[offset + tailStart + 7].toLong() and 0xff) shl 56)
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
8 -> {
k1 = k1 xor ((this[offset + tailStart + 7].toLong() and 0xff) shl 56)
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
7 -> {
k1 = k1 xor ((this[offset + tailStart + 6].toLong() and 0xff) shl 48)
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
6 -> {
k1 = k1 xor ((this[offset + tailStart + 5].toLong() and 0xff) shl 40)
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
5 -> {
k1 = k1 xor ((this[offset + tailStart + 4].toLong() and 0xff) shl 32)
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
4 -> {
k1 = k1 xor ((this[offset + tailStart + 3].toLong() and 0xff) shl 24)
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
3 -> {
k1 = k1 xor ((this[offset + tailStart + 2].toLong() and 0xff) shl 16)
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
2 -> {
k1 = k1 xor ((this[offset + tailStart + 1].toLong() and 0xff) shl 8)
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
1 -> {
k1 = k1 xor (this[offset + tailStart].toLong() and 0xff)
k1 *= C1
k1 = java.lang.Long.rotateLeft(k1, R1)
k1 *= C2
h1 = h1 xor k1
}
}
// finalization
h1 = h1 xor length.toLong()
h2 = h2 xor length.toLong()
h1 += h2
h2 += h1
h1 = fmix64(h1)
h2 = fmix64(h2)
h1 += h2
h2 += h1
return longArrayOf(h1, h2)
} | apache-2.0 | 35703df0690618c3d822e56fa1fd0c3f | 38.418239 | 104 | 0.524472 | 3.15373 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/ui/util/MaterialTitleBodyListItem.kt | 1 | 2878 | package io.oversec.one.crypto.ui.util
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.Drawable
import android.support.annotation.*
import android.support.v4.content.ContextCompat
import android.util.TypedValue
import com.afollestad.materialdialogs.util.DialogUtils
class MaterialTitleBodyListItem private constructor(private val mBuilder: Builder) {
val icon: Drawable?
get() = mBuilder.mIcon
val title: CharSequence?
get() = mBuilder.mTitle
val body: CharSequence?
get() = mBuilder.mBody
val iconPadding: Int
get() = mBuilder.mIconPadding
val backgroundColor: Int
@ColorInt
get() = mBuilder.mBackgroundColor
class Builder(private val mContext: Context) {
var mIcon: Drawable? = null
var mTitle: CharSequence? = null
var mBody: CharSequence? = null
var mIconPadding: Int = 0
var mBackgroundColor= Color.parseColor("#BCBCBC")
fun icon(icon: Drawable?): Builder {
this.mIcon = icon
return this
}
fun icon(@DrawableRes iconRes: Int): Builder {
return icon(ContextCompat.getDrawable(mContext, iconRes))
}
fun iconPadding(padding: Int): Builder {
this.mIconPadding = padding
return this
}
fun iconPaddingDp( paddingDp: Int
): Builder {
this.mIconPadding = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, paddingDp.toFloat(),
mContext.resources.displayMetrics
).toInt()
return this
}
fun iconPaddingRes(@DimenRes paddingRes: Int): Builder {
return iconPadding(mContext.resources.getDimensionPixelSize(paddingRes))
}
fun title(content: CharSequence): Builder {
this.mTitle = content
return this
}
fun body(content: CharSequence): Builder {
this.mBody = content
return this
}
fun title(@StringRes contentRes: Int): Builder {
return title(mContext.getString(contentRes))
}
fun body(@StringRes contentRes: Int): Builder {
return body(mContext.getString(contentRes))
}
fun backgroundColor(@ColorInt color: Int): Builder {
this.mBackgroundColor = color
return this
}
fun backgroundColorRes(@ColorRes colorRes: Int): Builder {
return backgroundColor(DialogUtils.getColor(mContext, colorRes))
}
fun backgroundColorAttr(@AttrRes colorAttr: Int): Builder {
return backgroundColor(DialogUtils.resolveColor(mContext, colorAttr))
}
fun build(): MaterialTitleBodyListItem {
return MaterialTitleBodyListItem(this)
}
}
} | gpl-3.0 | 8de4d7fd4cafd1189f9b1db4224564f4 | 28.080808 | 84 | 0.624739 | 5.166966 | false | false | false | false |
AdamMc331/CashCaretaker | app/src/test/java/com/androidessence/cashcaretaker/ui/transactionlist/TransactionListViewModelRobot.kt | 1 | 1339 | package com.androidessence.cashcaretaker.ui.transactionlist
import com.adammcneilly.cashcaretaker.analytics.AnalyticsTracker
import com.androidessence.cashcaretaker.core.models.Transaction
import com.androidessence.cashcaretaker.data.CCRepository
import com.google.common.truth.Truth.assertThat
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.flow.flowOf
class TransactionListViewModelRobot {
private val mockRepository = mockk<CCRepository>(relaxed = true)
private val mockAnalyticsTracker = mockk<AnalyticsTracker>(relaxed = true)
private lateinit var viewModel: TransactionListViewModel
fun mockTransactionsForAccount(
accountName: String,
transactions: List<Transaction>
) = apply {
coEvery {
mockRepository.fetchTransactionsForAccount(accountName)
} returns flowOf(transactions)
}
fun buildViewModel(accountName: String) = apply {
viewModel = TransactionListViewModel(
accountName = accountName,
repository = mockRepository,
analyticsTracker = mockAnalyticsTracker
)
}
fun assertViewState(expectedViewState: TransactionListViewState) = apply {
val actualViewState = viewModel.viewState.value
assertThat(actualViewState).isEqualTo(expectedViewState)
}
}
| mit | 6ad95233e8c61eed697fdc181e7cd672 | 35.189189 | 78 | 0.75056 | 5.25098 | false | false | false | false |
artjimlop/clean-architecture-kotlin | app/src/main/java/com/example/arturo/mycomics/infrastructure/AppModule.kt | 1 | 3950 | package com.example.arturo.mycomics.infrastructure
import android.arch.persistence.room.Room
import com.example.arturo.mycomics.MyComicsApplication
import com.example.arturo.mycomics.R
import com.example.arturo.mycomics.infrastructure.threading.UIThread
import com.example.arturo.mycomics.ui.navigation.Navigator
import com.example.data.datasources.LocalComicDatasource
import com.example.data.datasources.MarvelComicDatasource
import com.example.data.datasources.RetrofitMarvelComicDatasource
import com.example.data.datasources.RoomComicDatasource
import com.example.data.infrastructure.AppDatabase
import com.example.data.net.ApiConstants
import com.example.data.net.ComicApiService
import com.example.data.net.interceptors.AuthInterceptor
import com.example.data.repositories.LocalComicsRepositoryImpl
import com.example.data.repositories.MarvelRepositoryImpl
import com.example.executor.JobExecutor
import com.example.executor.PostExecutionThread
import com.example.executor.ThreadExecutor
import com.example.repositories.LocalComicsRepository
import com.example.repositories.MarvelRepository
import dagger.Module
import dagger.Provides
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Named
import javax.inject.Singleton
@Module
class AppModule(val app: MyComicsApplication) {
@Provides @Singleton fun app() = app
fun navigator(): Navigator = Navigator()
@Provides
@Singleton
fun provideThreadExecutor(jobExecutor: JobExecutor): ThreadExecutor {
return jobExecutor
}
@Provides
@Singleton
fun providePostExecutionThread(uiThread: UIThread): PostExecutionThread {
return uiThread
}
@Provides
@Singleton
fun provideComicsRepository(marvelRepositoryImpl: MarvelRepositoryImpl): MarvelRepository {
return marvelRepositoryImpl
}
@Provides
@Singleton
fun provideRetrofitComicDataSource(retrofitMarvelComicDatasource: RetrofitMarvelComicDatasource): MarvelComicDatasource {
return retrofitMarvelComicDatasource
}
@Provides
@Singleton
fun provideRoomComicDatasource(roomComicDatasource: RoomComicDatasource): LocalComicDatasource {
return roomComicDatasource
}
@Provides
@Singleton
@Named("public_key")
fun providePublicKey(): String {
return app.getString(R.string.public_key)
}
@Provides
@Singleton
@Named("private_key")
fun providePrivateKey(): String {
return app.getString(R.string.private_key)
}
@Provides
@Singleton
@Named("character_id")
fun provideCharacterId(): Int {
return app.getString(R.string.character_id).toInt()
}
@Provides
@Singleton
fun provideComicApiService(authInterceptor: AuthInterceptor): ComicApiService {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
val httpClient = OkHttpClient.Builder().addInterceptor(loggingInterceptor).addInterceptor(authInterceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(ApiConstants.ENDPOINT)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(ComicApiService::class.java)
}
@Provides @Singleton
fun database(app: MyComicsApplication): AppDatabase
= Room.databaseBuilder(app, AppDatabase::class.java, "comics").build()
@Provides
fun comicsDao(appDatabase: AppDatabase) = appDatabase.comicsDao()
@Provides
fun imagesDao(appDatabase: AppDatabase) = appDatabase.imagesDao()
@Provides
fun provideLocalComicsRepository(localComicsRepositoryImpl: LocalComicsRepositoryImpl): LocalComicsRepository
= localComicsRepositoryImpl
} | apache-2.0 | 7eb45cf6a2c56b2202fac8cd73a408fe | 31.925 | 125 | 0.760253 | 4.817073 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/utils/FileTypeEditorNotificationProvider.kt | 1 | 3315 | package com.gmail.blueboxware.libgdxplugin.utils
import com.gmail.blueboxware.libgdxplugin.message
import com.gmail.blueboxware.libgdxplugin.settings.LibGDXPluginSettings
import com.intellij.lang.Language
import com.intellij.lang.LanguageUtil
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotificationProvider
import com.intellij.ui.EditorNotificationProvider.CONST_NULL
import com.intellij.ui.EditorNotifications
import java.util.function.Function
import javax.swing.JComponent
/*
* Copyright 2019 Blue Box Ware
*
* 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.
*/
abstract class FileTypeEditorNotificationProvider(
protected val project: Project,
private val forLanguage: Language
) : EditorNotificationProvider {
private val notifications: EditorNotifications = EditorNotifications.getInstance(project)
abstract val messageKey: String
abstract fun onYes(file: VirtualFile)
abstract fun onNo(file: VirtualFile)
abstract fun onNever(settings: LibGDXPluginSettings)
abstract fun shouldShowNotification(
currentLanguage: Language?,
file: VirtualFile,
fileEditor: TextEditor,
settings: LibGDXPluginSettings
): Boolean
override fun collectNotificationData(
project: Project,
file: VirtualFile
): Function<in FileEditor, out JComponent?> {
val currentLanguage = LanguageUtil.getLanguageForPsi(project, file)
if (currentLanguage == forLanguage) {
return CONST_NULL
}
val settings = project.getService(LibGDXPluginSettings::class.java) ?: return CONST_NULL
return Function { fileEditor ->
if (fileEditor !is TextEditor) null else
if (!shouldShowNotification(currentLanguage, file, fileEditor, settings)) null else
EditorNotificationPanel().apply {
text = message(messageKey, file.fileType.description)
createActionLabel(message("filetype.yes")) {
onYes(file)
notifications.updateAllNotifications()
}
createActionLabel(message("filetype.no")) {
onNo(file)
notifications.updateAllNotifications()
}
createActionLabel(message("filetype.do.not.bother")) {
onNever(settings)
notifications.updateAllNotifications()
}
}
}
}
}
| apache-2.0 | 8c8492ba09d08c2c6c0eb7063ce9aa0d | 34.265957 | 99 | 0.674208 | 5.461285 | false | false | false | false |
YoungPeacock/FantaF1 | app/src/main/java/com/peacock/fantafone/Drivers.kt | 1 | 3995 | package com.peacock.fantafone
/**
* Created by fabrizio on 27/12/16.
*/
class Drivers {
var level: Int = 0
var points: Int = 0
var positionD: Int = 0
var nameD: String? = null
private var fastLap = false
private var bestQ = false
private var beatTM = false
private var bRetired = false
fun setName(names: String) {
this.nameD = names
}
fun getName(): String {
if (nameD != null)
return this.nameD!!
else
return ""
}
fun setbRetired(r: Boolean) {
this.bRetired = r
}
fun setPosition(pos: Int) {
positionD = pos
}
fun setFastLap(f: Boolean) {
this.fastLap = f
}
fun setBestQ(q: Boolean) {
this.bestQ = q
}
fun setBeatTM(b: Boolean) {
this.beatTM = b
}
val calcPoints: Int
get() {
if (level == Companion.L_LOW) {
if (positionD == 1) {
points = 25
} else if (positionD in 2..3) {
points = 20
} else if (positionD in 4..6) {
points = 12
} else if (positionD in 7..10) {
points = 8
} else if (positionD in 11..16) {
points = 3
} else if (positionD in 17..18) {
points = 1
} else if (positionD in 19..20) {
points = 0
}
if (beatTM) points += 5
if (bRetired) points = 0
if (fastLap) points += 4
if (bestQ) points += 1
} else if (level == L_MED) {
if (positionD == 1) {
points = 12
} else if (positionD in 2..3) {
points = 8
} else if (positionD in 4..6) {
points = 5
} else if (positionD in 7..10) {
points = 3
} else if (positionD in 11..16) {
points = 1
} else if (positionD in 17..18) {
points = -2
} else if (positionD in 19..20) {
points = -4
}
if (beatTM) points += 5
if (bRetired) points = 0
if (fastLap) points += 2
if (bestQ) points += 2
} else if (level == Companion.L_TOP) {
if (positionD == 1) {
points = 5
} else if (positionD in 2..3) {
points = 3
} else if (positionD in 4..6) {
points = 1
} else if (positionD in 7..10) {
points = -1
} else if (positionD in 11..16) {
points = -4
} else if (positionD in 17..18) {
points = -6
} else if (positionD in 19..20) {
points = -8
}
if (beatTM) points += 5
if (bRetired) points = 0
if (fastLap) points += 1
if (bestQ) points += 1
}
return this.points
}
fun getPointsString(ddd: String): String {
var build = ddd
val pos: String
val faL: String
val beQ: String
val rit: String
val bet: String
if (fastLap) faL = "1" else faL = "0"
if (bestQ) beQ = "1" else beQ = "0"
if (bRetired) rit = "1" else rit = "0"
if (beatTM) bet = "1" else bet = "0"
if (positionD < 10)
pos = "00" + positionD.toString()
else
pos = "0" + positionD.toString()
build = build + ":" + bet + pos + "000" + faL + "000" + beQ + "000" + rit
return build
}
companion object {
val L_LOW = 0
val L_MED = 1
val L_TOP = 2
}
}
| agpl-3.0 | 137e537a64e38bcf0ff1ffe135bfc696 | 24.941558 | 81 | 0.404255 | 4.072375 | false | false | false | false |
firebase/quickstart-android | auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GoogleSignInFragment.kt | 1 | 7360 | package com.google.firebase.quickstart.auth.kotlin
import android.app.PendingIntent
import android.content.Intent
import android.content.IntentSender
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts.StartIntentSenderForResult
import com.google.android.gms.auth.api.identity.BeginSignInRequest
import com.google.android.gms.auth.api.identity.GetSignInIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import com.google.android.gms.auth.api.identity.SignInClient
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.R
import com.google.firebase.quickstart.auth.databinding.FragmentGoogleBinding
/**
* Demonstrate Firebase Authentication using a Google ID Token.
*/
class GoogleSignInFragment : BaseFragment() {
private lateinit var auth: FirebaseAuth
private var _binding: FragmentGoogleBinding? = null
private val binding: FragmentGoogleBinding
get() = _binding!!
private lateinit var signInClient: SignInClient
private val signInLauncher = registerForActivityResult(StartIntentSenderForResult()) { result ->
handleSignInResult(result.data)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentGoogleBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setProgressBar(binding.progressBar)
// Button listeners
binding.signInButton.setOnClickListener { signIn() }
binding.signOutButton.setOnClickListener { signOut() }
// Configure Google Sign In
signInClient = Identity.getSignInClient(requireContext())
// Initialize Firebase Auth
auth = Firebase.auth
// Display One-Tap Sign In if user isn't logged in
val currentUser = auth.currentUser
if (currentUser == null) {
oneTapSignIn()
}
}
override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
private fun handleSignInResult(data: Intent?) {
// Result returned from launching the Sign In PendingIntent
try {
// Google Sign In was successful, authenticate with Firebase
val credential = signInClient.getSignInCredentialFromIntent(data)
val idToken = credential.googleIdToken
if (idToken != null) {
Log.d(TAG, "firebaseAuthWithGoogle: ${credential.id}")
firebaseAuthWithGoogle(idToken)
} else {
// Shouldn't happen.
Log.d(TAG, "No ID token!")
}
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
updateUI(null)
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
showProgressBar()
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(requireActivity()) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
val view = binding.mainLayout
Snackbar.make(view, "Authentication Failed.", Snackbar.LENGTH_SHORT).show()
updateUI(null)
}
hideProgressBar()
}
}
private fun signIn() {
val signInRequest = GetSignInIntentRequest.builder()
.setServerClientId(getString(R.string.default_web_client_id))
.build()
signInClient.getSignInIntent(signInRequest)
.addOnSuccessListener { pendingIntent ->
launchSignIn(pendingIntent)
}
.addOnFailureListener { e ->
Log.e(TAG, "Google Sign-in failed", e)
}
}
private fun oneTapSignIn() {
// Configure One Tap UI
val oneTapRequest = BeginSignInRequest.builder()
.setGoogleIdTokenRequestOptions(
BeginSignInRequest.GoogleIdTokenRequestOptions.builder()
.setSupported(true)
.setServerClientId(getString(R.string.default_web_client_id))
.setFilterByAuthorizedAccounts(true)
.build()
)
.build()
// Display the One Tap UI
signInClient.beginSignIn(oneTapRequest)
.addOnSuccessListener { result ->
launchSignIn(result.pendingIntent)
}
.addOnFailureListener { e ->
// No saved credentials found. Launch the One Tap sign-up flow, or
// do nothing and continue presenting the signed-out UI.
}
}
private fun launchSignIn(pendingIntent: PendingIntent) {
try {
val intentSenderRequest = IntentSenderRequest.Builder(pendingIntent)
.build()
signInLauncher.launch(intentSenderRequest)
} catch (e: IntentSender.SendIntentException) {
Log.e(TAG, "Couldn't start Sign In: ${e.localizedMessage}")
}
}
private fun signOut() {
// Firebase sign out
auth.signOut()
// Google sign out
signInClient.signOut().addOnCompleteListener(requireActivity()) {
updateUI(null)
}
}
private fun updateUI(user: FirebaseUser?) {
hideProgressBar()
if (user != null) {
binding.status.text = getString(R.string.google_status_fmt, user.email)
binding.detail.text = getString(R.string.firebase_status_fmt, user.uid)
binding.signInButton.visibility = View.GONE
binding.signOutButton.visibility = View.VISIBLE
} else {
binding.status.setText(R.string.signed_out)
binding.detail.text = null
binding.signInButton.visibility = View.VISIBLE
binding.signOutButton.visibility = View.GONE
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
private const val TAG = "GoogleFragmentKt"
}
}
| apache-2.0 | 88b61abca2837f1bd53bac618763096d | 35.435644 | 115 | 0.633152 | 5.065382 | false | false | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/DynamicCallProblemReporting.kt | 2 | 3054 | /*
* Copyright 2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import java.util.Stack
/**
* A tool for checking if a specific problem has already been reported in the current dynamic call in the dynamic calls stack.
* A problem is identified using a key object.
* The implementation should be thread-safe and should support tracking problems in multiple threads, each with its own call stack.
*/
interface DynamicCallProblemReporting {
/**
* Begin tracking a new dynamic call on the call stack, with no problems reported in it initially.
* The [entryPoint] is stored and checked in [leaveDynamicCall] later.
*/
fun enterDynamicCall(entryPoint: Any)
/**
* End tracking a dynamic call.
* The [entryPoint] should match the one passed to [enterDynamicCall].
*/
fun leaveDynamicCall(entryPoint: Any)
/**
* Checks if the problem identified by [problemKey] has already been reported in the current dynamic call.
* Side effect: marks [problemKey] as a *reported* problem if it has not been reported yet.
*
* @return a value saying whether this problem has not been reported yet in the current dynamic call.
*/
fun unreportedProblemInCurrentCall(problemKey: Any): Boolean
}
class DefaultDynamicCallProblemReporting : DynamicCallProblemReporting {
private
class CallEntry(val entryPoint: Any) {
val problemsReportedInCurrentCall: MutableSet<Any> = HashSet(1)
}
private
class State {
val callStack = Stack<CallEntry>()
}
private
val threadLocalState = ThreadLocal.withInitial { State() }
override fun enterDynamicCall(entryPoint: Any) {
currentThreadState.callStack.push(CallEntry(entryPoint))
}
override fun leaveDynamicCall(entryPoint: Any) {
val innermostCall = currentThreadState.callStack.pop()
check(entryPoint == innermostCall.entryPoint) { "Mismatched enter-leave calls in DynamicCallProjectIsolationProblemReporting" }
}
override fun unreportedProblemInCurrentCall(problemKey: Any): Boolean {
val currentThreadCallStack = currentThreadState.callStack
check(currentThreadCallStack.isNotEmpty()) { "Expected unreportedProblemInCurrentCall to be called after enterDynamicCall" }
return currentThreadCallStack.peek().problemsReportedInCurrentCall.add(problemKey)
}
private
val currentThreadState: State
get() = threadLocalState.get()
}
| apache-2.0 | a91eccd17a7423f99b31d8e946cee081 | 36.243902 | 135 | 0.729862 | 4.620272 | false | false | false | false |
j-selby/kotgb | libgdx-core/src/net/jselby/kotgb/KotGB.kt | 1 | 14797 | package net.jselby.kotgb
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.Files
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.files.FileHandle
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.BufferUtils
import com.badlogic.gdx.utils.viewport.ScreenViewport
import com.kotcrab.vis.ui.VisUI
import com.kotcrab.vis.ui.util.dialog.Dialogs
import com.kotcrab.vis.ui.widget.Menu
import com.kotcrab.vis.ui.widget.MenuBar
import com.kotcrab.vis.ui.widget.MenuItem
import com.kotcrab.vis.ui.widget.file.FileChooser
import com.kotcrab.vis.ui.widget.file.FileChooserListener
import com.kotcrab.vis.ui.widget.file.FileTypeFilter
import mu.KotlinLogging
import net.jselby.kotgb.hw.GameboyButton
import net.jselby.kotgb.ui.*
import java.io.File
import java.io.PrintWriter
import java.io.StringWriter
import java.nio.ByteBuffer
import java.util.*
class KotGB(val args: MutableMap<String, Any>, val emuEnv: EmulationEnvironment) : ApplicationAdapter() {
private val logger = KotlinLogging.logger {}
private var batch: SpriteBatch? = null
private var texture: Texture? = null
private var buf: ByteBuffer? = null
private var renderWidth: Int = 0
private var renderHeight: Int = 0
private val buttons = ArrayList<GameboyButton>()
private var renderUI = true
private var stage: Stage? = null
private var menuBar: MenuBar? = null
private lateinit var state : StateManager
private var regViewer : RegisterViewer? = null
private var ramViewer : RamViewer? = null
private var frameTimer : FrametimeGraph? = null
private var breakpointViewer: BreakpointsViewer? = null
private var vramViewer : VramDumper? = null
private var frameTimerEnabled = false
override fun create() {
logger.info("Running via LibGDX Frontend on ${Gdx.app.type}")
renderWidth = Gdx.graphics.width
renderHeight = Gdx.graphics.height
state = StateManager({ des, e -> showError(des, e) }, emuEnv.cpuFactory)
batch = SpriteBatch()
VisUI.load(VisUI.SkinScale.X1)
stage = Stage(ScreenViewport())
val root = Table()
root.setFillParent(true)
stage!!.addActor(root)
Gdx.input.inputProcessor = stage
menuBar = MenuBar()
root.add(menuBar!!.table).expandX().fillX().row()
root.add().expand().fill()
val fileMenu = Menu("File")
FileChooser.setDefaultPrefsName("net.jselby.kotgb.filechooser")
fileMenu.addItem(MenuItem("Load...", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
/*val chooser = FileChooser(FileChooser.Mode.OPEN)
val filter = FileTypeFilter(true)
filter.addRule("Gameboy ROMs (*.gb)", ".gb")
chooser.setFileTypeFilter(filter)
chooser.isMultiSelectionEnabled = false
chooser.setDirectory(File(""))
chooser.setListener(object : FileChooserListener {
override fun selected(files: Array<FileHandle>) {
if (files.size != 1) {
logger.error {"Invalid ROM file array."}
return
}
loadRom(files.get(0))
}
override fun canceled() {
}
})
stage!!.addActor(chooser.fadeIn())*/
emuEnv.openFile {
loadRom(it)
}
}
}))
fileMenu.addSeparator()
fileMenu.addItem(MenuItem("Close", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
Gdx.app.exit()
}
}))
val emulationMenu = Menu("Emulation")
emulationMenu.addItem(MenuItem("Resume", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
state.resume()
}
}))
emulationMenu.addItem(MenuItem("Pause", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
state.pause()
}
}))
emulationMenu.addItem(MenuItem("Stop", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
state.stop()
}
}))
emulationMenu.addItem(MenuItem("Step (F7)", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
state.step()
}
}))
val debugMenu = Menu("Debug")
debugMenu.addItem(MenuItem("Registers", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
actor as MenuItem
if (actor.text.contains("-")) {
regViewer!!.fadeOut()
actor.text = actor.text.toString().replace("- ", "")
} else {
actor.text = "- ${actor.text}"
stage!!.addActor(regViewer)
}
}
}))
debugMenu.addItem(MenuItem("RAM Viewer", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
actor as MenuItem
if (actor.text.contains("-")) {
ramViewer!!.fadeOut()
actor.text = actor.text.toString().replace("- ", "")
} else {
actor.text = "- ${actor.text}"
stage!!.addActor(ramViewer)
}
}
}))
debugMenu.addItem(MenuItem("Breakpoints", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
actor as MenuItem
if (actor.text.contains("-")) {
breakpointViewer!!.fadeOut()
actor.text = actor.text.toString().replace("- ", "")
} else {
actor.text = "- ${actor.text}"
stage!!.addActor(breakpointViewer)
}
}
}))
debugMenu.addItem(MenuItem("Frametimes", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
actor as MenuItem
if (actor.text.contains("-")) {
actor.text = actor.text.toString().replace("- ", "")
frameTimerEnabled = false
} else {
actor.text = "- ${actor.text}"
frameTimerEnabled = true
}
}
}))
debugMenu.addItem(MenuItem("VRAM", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
actor as MenuItem
if (actor.text.contains("-")) {
actor.text = actor.text.toString().replace("- ", "")
vramViewer!!.fadeOut()
} else {
actor.text = "- ${actor.text}"
stage!!.addActor(vramViewer)
}
}
}))
val viewMenu = Menu("View")
viewMenu.addItem(MenuItem("Hide UI", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
renderUI = false
}
}))
viewMenu.addItem(MenuItem("Fullscreen", object : ChangeListener() {
override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) {
actor as MenuItem
if (actor.text.contains("-")) {
actor.text = actor.text.toString().replace("- ", "")
Gdx.graphics.setWindowedMode(800, 600)
} else {
actor.text = "- ${actor.text}"
Gdx.graphics.setFullscreenMode(Gdx.graphics.displayMode)
}
}
}))
menuBar!!.addMenu(fileMenu)
menuBar!!.addMenu(emulationMenu)
menuBar!!.addMenu(debugMenu)
menuBar!!.addMenu(viewMenu)
frameTimer = FrametimeGraph()
regViewer = RegisterViewer()
ramViewer = RamViewer()
breakpointViewer = BreakpointsViewer()
vramViewer = VramDumper()
if (args.containsKey("debug") && args["debug"] != null && args["debug"] as Boolean) {
stage!!.addActor(regViewer)
stage!!.addActor(ramViewer)
stage!!.addActor(breakpointViewer)
}
if (args.containsKey("breakpoints")) {
for (arg in args["breakpoints"]!! as ArrayList<*>) {
logger.debug {"Adding breakpoint: $arg"}
breakpointViewer!!.addBreakpoint(arg as String)
}
}
buf = BufferUtils.newByteBuffer(160 * 144 * 4)
texture = Texture(160, 144, Pixmap.Format.RGBA8888)
if (args.containsKey("file") && args["file"] != null) {
loadRom(Gdx.files.getFileHandle((args["file"]!! as ArrayList<*>)[0] as String, Files.FileType.Local))
}
}
private fun showError(description: String, e: Exception) {
val sw = StringWriter()
val pw = PrintWriter(sw)
e.printStackTrace(pw)
val exceptionText = sw.toString().replace("\t", " ")
val dialog = Dialogs.showErrorDialog(stage!!, description, exceptionText)
dialog.isDetailsVisible = true
}
private fun loadRom(file: FileHandle) {
if (state.isRunning) {
state.stop()
}
try {
state.launch(file)
} catch (e : Exception) {
e.printStackTrace()
showError("Failed to load ROM.", e)
return
}
breakpointViewer?.update(state.gameboy!!)
state.resume()
}
override fun render() {
stage!!.act(Math.min(Gdx.graphics.deltaTime, 1 / 30f))
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
var title = "KotGB"
if (state.isGameLoaded) {
state.withGPU {
BufferUtils.copy(it.pixelArray, 0,
buf!!, it.pixelArray.size)
if (frameTimerEnabled) {
frameTimer?.update(state)
}
if (regViewer?.isVisible!!) {
regViewer?.update(state.gameboy!!)
}
if (ramViewer?.isVisible!!) {
ramViewer?.update(state.gameboy!!)
}
if (breakpointViewer?.isVisible!!) {
breakpointViewer?.update(state.gameboy!!)
}
/*if (vramViewer?.isVisible!!) {
vramViewer?.update(state.gameboy!!)
}*/
}
synchronized(state.vsyncSignal, {
state.vsyncSignal.notifyAll()
})
// Upload texture
texture!!.bind()
Gdx.gl.glTexImage2D(GL20.GL_TEXTURE_2D, 0, GL20.GL_RGBA, 160, 144,
0, GL20.GL_RGBA, GL20.GL_UNSIGNED_BYTE, buf)
// Render texture
batch!!.transformMatrix = stage!!.viewport.camera.view
batch!!.projectionMatrix = stage!!.viewport.camera.projection
batch!!.begin()
batch!!.draw(texture, 0f, 0f, renderWidth.toFloat(),
renderHeight - if (renderUI) menuBar!!.table.height else 0f)
if (frameTimerEnabled) {
frameTimer?.render(batch!!)
}
batch!!.end()
// Update input
buttons.clear()
val toCollect = intArrayOf(Input.Keys.UP, Input.Keys.DOWN, Input.Keys.LEFT, Input.Keys.RIGHT,
Input.Keys.X, Input.Keys.Z, Input.Keys.A, Input.Keys.S)
toCollect
.filter { Gdx.input.isKeyPressed(it) }
.forEach { // Translate
when (it) {
Input.Keys.UP -> buttons.add(GameboyButton.UP)
Input.Keys.DOWN -> buttons.add(GameboyButton.DOWN)
Input.Keys.LEFT -> buttons.add(GameboyButton.LEFT)
Input.Keys.RIGHT -> buttons.add(GameboyButton.RIGHT)
Input.Keys.X -> buttons.add(GameboyButton.A)
Input.Keys.Z -> buttons.add(GameboyButton.B)
Input.Keys.A -> buttons.add(GameboyButton.SELECT)
Input.Keys.S -> buttons.add(GameboyButton.START)
}
}
state.buttonsPressed = buttons.toTypedArray()
state.doFastForward = Gdx.input.isKeyPressed(Input.Keys.TAB)
title += (" - Emulating ${state.gameName}" + if (!state.isRunning) " - " + if (state.isDebugging) "Debugging" else "Paused" else "" )
val gameboy = state.gameboy
if (gameboy != null) {
title += " - Using " + gameboy.cpu.executor::class.java.simpleName.replace("Executor", "").trim()
val state = emuEnv.cpuState.invoke(gameboy.cpu)
if (state != null) {
title += " ($state)"
}
}
}
// Handle hotkeys
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)) {
renderUI = true
}
if (Gdx.input.isKeyJustPressed(Input.Keys.F7)) {
state.step()
}
title += " - Frontend FPS: ${Gdx.graphics.framesPerSecond}"
Gdx.graphics.setTitle(title)
if (renderUI) {
stage!!.draw()
}
}
override fun resize(width: Int, height: Int) {
if (width == 0 && height == 0) return //see https://github.com/libgdx/libgdx/issues/3673#issuecomment-177606278
stage!!.viewport.update(width, height, true)
renderWidth = width
renderHeight = height
}
override fun dispose() {
VisUI.dispose()
batch!!.dispose()
texture!!.dispose()
}
}
| mit | 31f1fe560d7efc5c2b514df8dc4613bf | 35.356265 | 145 | 0.546732 | 4.647299 | false | false | false | false |
shiguredo/sora-android-sdk | sora-android-sdk/src/main/kotlin/jp/shiguredo/sora/sdk/channel/rtc/RTCLocalAudioManager.kt | 1 | 2290 | package jp.shiguredo.sora.sdk.channel.rtc
import jp.shiguredo.sora.sdk.channel.option.SoraAudioOption
import jp.shiguredo.sora.sdk.util.SoraLogger
import org.webrtc.AudioSource
import org.webrtc.AudioTrack
import org.webrtc.MediaConstraints
import org.webrtc.PeerConnectionFactory
import java.util.UUID
class RTCLocalAudioManager(
private val send: Boolean
) {
companion object {
private val TAG = RTCLocalAudioManager::class.simpleName
}
private var source: AudioSource? = null
var track: AudioTrack? = null
fun initTrack(factory: PeerConnectionFactory, audioOption: SoraAudioOption) {
SoraLogger.d(TAG, "initTrack: send=$send")
if (send) {
val constraints = createSourceConstraints(audioOption)
source = factory.createAudioSource(constraints)
SoraLogger.d(TAG, "audio source created: $source")
val trackId = UUID.randomUUID().toString()
track = factory.createAudioTrack(trackId, source)
track?.setEnabled(true)
SoraLogger.d(TAG, "audio track created: $track")
}
}
private fun createSourceConstraints(audioOption: SoraAudioOption): MediaConstraints {
val constraints = MediaConstraints()
if (!audioOption.audioProcessingEchoCancellation) {
constraints.mandatory.add(
MediaConstraints.KeyValuePair(SoraAudioOption.ECHO_CANCELLATION_CONSTRAINT, "false")
)
}
if (!audioOption.audioProcessingAutoGainControl) {
constraints.mandatory.add(
MediaConstraints.KeyValuePair(SoraAudioOption.AUTO_GAIN_CONTROL_CONSTRAINT, "false")
)
}
if (!audioOption.audioProcessingHighpassFilter) {
constraints.mandatory.add(
MediaConstraints.KeyValuePair(SoraAudioOption.HIGH_PASS_FILTER_CONSTRAINT, "false")
)
}
if (!audioOption.audioProcessingNoiseSuppression) {
constraints.mandatory.add(
MediaConstraints.KeyValuePair(SoraAudioOption.NOISE_SUPPRESSION_CONSTRAINT, "false")
)
}
return constraints
}
fun dispose() {
SoraLogger.d(TAG, "dispose")
source?.dispose()
source = null
}
}
| apache-2.0 | 8896c2ddaaaaa5fde64ee742c53b266f | 34.230769 | 100 | 0.661572 | 4.481409 | false | false | false | false |
Drakojin/livingdoc2 | livingdoc-engine/src/test/kotlin/org/livingdoc/engine/reporting/HtmlReportRendererTest.kt | 1 | 6084 | package org.livingdoc.engine.reporting
import io.mockk.mockk
import org.junit.jupiter.api.Test
import org.livingdoc.engine.execution.DocumentResult
import org.livingdoc.engine.execution.Result
import org.livingdoc.engine.execution.examples.decisiontables.model.DecisionTableResult
import org.livingdoc.engine.execution.examples.decisiontables.model.FieldResult
import org.livingdoc.engine.execution.examples.decisiontables.model.RowResult
import org.livingdoc.engine.execution.examples.scenarios.model.ScenarioResult
import org.livingdoc.engine.execution.examples.scenarios.model.StepResult
import org.livingdoc.repositories.model.decisiontable.Header
import strikt.api.expectThat
internal class HtmlReportRendererTest {
val cut = HtmlReportRenderer()
@Test
fun `decisionTableResult is rendered correctly`() {
val headerA = Header("a")
val headerB = Header("b")
val headerAPlusB = Header("a + b = ?")
val documentResult = DocumentResult(
mutableListOf(DecisionTableResult(
listOf(headerA, headerB, headerAPlusB),
listOf(
RowResult(mapOf(
headerA to FieldResult("2", Result.Executed),
headerB to FieldResult("3", Result.Executed),
headerAPlusB to FieldResult("6", Result.Failed(mockk(relaxed = true)))
), Result.Executed),
RowResult(mapOf(
headerA to FieldResult("5", Result.Skipped),
headerB to FieldResult("6", Result.Unknown),
headerAPlusB to FieldResult("11", Result.Exception(mockk(relaxed = true)))
), Result.Executed)
),
Result.Executed
)))
val renderResult = cut.render(documentResult)
expectThat(renderResult).isEqualIgnoreWhitespace(
"""
<!DOCTYPE html>
<html>
<head>
${HtmlReportTemplate.HTML_HEAD_STYLE_CONTENT}
</head>
<body>
<table>
<tr>
<th class="border-black-onepx">a</th>
<th class="border-black-onepx">b</th>
<th class="border-black-onepx">a + b = ?</th>
</tr>
<tr>
<td class="border-black-onepx background-executed"><span class="result-value">2</span></td>
<td class="border-black-onepx background-executed"><span class="result-value">3</span></td>
<td class="border-black-onepx background-failed"><span class="result-value">6</span><a href="#popup1" class="icon-failed"></a></td>
</tr>
<tr>
<td class="border-black-onepx background-skipped"><span class="result-value">5</span></td>
<td class="border-black-onepx background-unknown"><span class="result-value">6</span></td>
<td class="border-black-onepx background-exception"><span class="result-value">11</span><a href="#popup2" class="icon-exception"></a></td>
</tr>
</table>
<div id="popup1" class="overlay">
<div class="popup">
<h2></h2>
<a class="close" href="#">×</a>
<div class="content">
<pre>
</pre>
</div>
</div>
</div>
<div id="popup2" class="overlay">
<div class="popup">
<h2></h2>
<a class="close" href="#">×</a>
<div class="content">
<pre>
</pre>
</div>
</div>
</div>
</body>
</html>
""")
}
@Test
fun `scenarioResult is rendered correctly`() {
val stepResultA = StepResult("A", Result.Executed)
val stepResultB = StepResult("B", Result.Unknown)
val stepResultC = StepResult("C", Result.Skipped)
val stepResultD = StepResult("D", Result.Failed(mockk()))
val stepResultE = StepResult("E", Result.Exception(mockk()))
val documentResult = DocumentResult(
mutableListOf(ScenarioResult(
listOf(stepResultA, stepResultB, stepResultC, stepResultD, stepResultE),
Result.Executed
)))
val renderResult = cut.render(documentResult)
expectThat(renderResult).isEqualIgnoreWhitespace(
"""
<!DOCTYPE html>
<html>
<head>
${HtmlReportTemplate.HTML_HEAD_STYLE_CONTENT}
</head>
<body>
<ul>
<li class="background-executed">A</li>
<li class="background-unknown">B</li>
<li class="background-skipped">C</li>
<li class="background-failed">D</li>
<li class="background-exception">E</li>
</ul>
</body>
</html>
""")
}
}
| apache-2.0 | 1e12f1b2f50f6592be799c41f1d00d42 | 45.090909 | 170 | 0.452663 | 5.304272 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/start/args.kt | 1 | 3645 | package at.cpickl.gadsu.start
import at.cpickl.gadsu.global.GadsuException
import at.cpickl.gadsu.persistence.PersistenceModule
import org.apache.commons.cli.CommandLine
import org.apache.commons.cli.DefaultParser
import org.apache.commons.cli.HelpFormatter
import org.apache.commons.cli.Options
import org.apache.commons.cli.ParseException
//fun main(args: Array<String>) {
// parseArgs(arrayOf("--help")).help!!()
//}
/**
* @throws ArgsException if CLI args are somehow wrong.
*/
fun parseArgs(cliArgs: Array<String>): Args {
return CommonsCliArgsParser().parse(cliArgs)
}
fun parseArgsOrHelp(cliArgs: Array<String>, suppressExceptionStacktrace: Boolean = false): Args? {
val args: Args
try {
args = parseArgs(cliArgs)
} catch (e: ArgsException) {
e.help(if (suppressExceptionStacktrace) null else e)
return null
}
if (args.help != null) {
args.help.invoke(null)
return null
}
return args
}
interface ArgsParser {
fun parse(cliArgs: Array<String>): Args
}
/**
* @param databaseUrl e.g.: "jdbc:hsqldb:mem:mymemdb" or (default): "jdbc:hsqldb:file:$DB_DIR/database"
*/
data class Args(val help: ((e: ArgsException?) -> Unit)?,
val databaseUrl: String?,
val debug: Boolean,
val action: String?) {
companion object {
val EMPTY = Args(null, null, false, null)
}
}
class ArgsException(message: String, cause: Exception, val help: (e: ArgsException?) -> Unit) : GadsuException(message, cause)
/**
* See: http://commons.apache.org/proper/commons-cli/introduction.html
*/
private class CommonsCliArgsParser : ArgsParser {
companion object {
private val DATABASE_URL_SHORT = "d"
private val DATABASE_URL_LONG = "databaseUrl"
private val DEBUG_SHORT = "x"
private val DEBUG_LONG = "debug"
private val ACTION_SHORT = "a"
private val ACTION_LONG = "action"
private val HELP_SHORT = "?"
private val HELP_LONG = "help"
}
override fun parse(cliArgs: Array<String>): Args {
val options = Options()
// -databaseUrl="jdbc:hsqldb:file:/Users/wu/.gadsu_dev/database/database"
options.addOption(DATABASE_URL_SHORT, DATABASE_URL_LONG, true, "Override JDBC URL to e.g.: 'jdbc:hsqldb:mem:mymemdb' (default is: '${PersistenceModule.DEFAULT_DB_URL}').")
options.addOption(DEBUG_SHORT, DEBUG_LONG, false, "Increase log level and register additional console appender.")
options.addOption(ACTION_SHORT, ACTION_LONG, true, "Add a custom action and quit (for debugging purpose).")
options.addOption(HELP_SHORT, HELP_LONG, false, "Print this usage help.")
val parser = DefaultParser()
val commands: CommandLine
val help = HelpFormatter()
help.width = 150
val helpFunction = { e: ArgsException? ->
e?.printStackTrace()
help.printHelp("gadsu", options)
}
try {
commands = parser.parse(options, cliArgs)
} catch (e: ParseException) {
throw ArgsException("Parsing CLI arguments failed: ${e.message}! ($cliArgs)", e, helpFunction)
}
if (commands.hasOption(HELP_SHORT)) {
return Args.EMPTY.copy(help = helpFunction)
}
return Args(
null,
if (commands.hasOption(DATABASE_URL_SHORT)) commands.getOptionValue(DATABASE_URL_SHORT) else null,
commands.hasOption(DEBUG_SHORT),
if (commands.hasOption(ACTION_SHORT)) commands.getOptionValue(ACTION_SHORT) else null
)
}
}
| apache-2.0 | 4818e2161de3a7536993bf12704b0c5c | 32.75 | 179 | 0.644993 | 3.970588 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/appointment/gcal/sync/view_table.kt | 1 | 4247 | package at.cpickl.gadsu.appointment.gcal.sync
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.client.view.ClientRenderer
import at.cpickl.gadsu.service.LOG
import at.cpickl.gadsu.view.ViewConstants
import at.cpickl.gadsu.view.components.DateRangeTableCellRenderer
import at.cpickl.gadsu.view.components.MyCheckboxTableCellEditor
import at.cpickl.gadsu.view.components.MyCheckboxTableCellRenderer
import at.cpickl.gadsu.view.components.MyEnableCheckboxTableCellEditor
import at.cpickl.gadsu.view.components.MyEnableCheckboxTableCellRenderer
import at.cpickl.gadsu.view.components.MyTable
import at.cpickl.gadsu.view.components.MyTableModel
import at.cpickl.gadsu.view.registerOnStopped
import java.awt.Component
import javax.swing.AbstractCellEditor
import javax.swing.DefaultComboBoxModel
import javax.swing.JComboBox
import javax.swing.JTable
import javax.swing.table.TableCellEditor
class SyncTable(
private val model: MyTableModel<ImportAppointment>
) :
MyTable<ImportAppointment>(model, "SyncTable", columnResizeMode = JTable.AUTO_RESIZE_ALL_COLUMNS), ImportClientsProvider {
companion object {
private val COL_CHECKBOX = 0
// private val COL_TITLE = 1
private val COL_CLIENT = 2
private val COL_DATE = 3
private val COL_CONFIRMATION = 4
// private val COL_MAIL = 5
}
private val logg = LOG(javaClass)
init {
val enabledEditor = MyCheckboxTableCellEditor().apply {
registerOnStopped {
model.entityAt(selectedRow).enabled = currentState
}
}
val confirmationEditor = MyEnableCheckboxTableCellEditor().apply {
registerOnStopped {
if (selectedRow != -1) {
model.entityAt(selectedRow).sendConfirmation = currentState
}
}
}
columnModel.getColumn(COL_CHECKBOX).cellEditor = enabledEditor
columnModel.getColumn(COL_CHECKBOX).cellRenderer = MyCheckboxTableCellRenderer()
columnModel.getColumn(COL_DATE).cellRenderer = DateRangeTableCellRenderer()
columnModel.getColumn(COL_CONFIRMATION).cellEditor = confirmationEditor
columnModel.getColumn(COL_CONFIRMATION).cellRenderer = MyEnableCheckboxTableCellRenderer()
rowHeight = 40
val clientEditor = ImportAppointmentClientEditor(this).apply {
registerOnStopped {
logg.trace("Selected client: {}", currentClient)
if (selectedRow != - 1) {
val importApp = model.entityAt(selectedRow)
importApp.selectedClient = currentClient
importApp.sendConfirmation = currentClient.hasMail
}
}
}
columnModel.getColumn(COL_CLIENT).cellEditor = clientEditor
}
override fun isCellEditable(row: Int, column: Int): Boolean {
return when (column) {
COL_CHECKBOX, COL_CLIENT, COL_CONFIRMATION -> true
else -> super.isCellEditable(row, column)
}
}
override fun suggestClients(row: Int) = model.entityAt(row).allClients
override fun clientByRow(row: Int) = model.entityAt(row).selectedClient
}
private interface ImportClientsProvider {
fun suggestClients(row: Int): List<Client>
fun clientByRow(row: Int): Client
}
private class ImportAppointmentClientEditor(
private val clientsProvider: ImportClientsProvider
) : AbstractCellEditor(), TableCellEditor {
private val combo = JComboBox<Client>().apply {
renderer = ClientRenderer()
putClientProperty("JComboBox.isTableCellEditor", true)
}
val currentClient: Client get() = cellEditorValue as Client
override fun getTableCellEditorComponent(table: JTable?, value: Any?, isSelected: Boolean, row: Int, column: Int): Component {
ViewConstants.Table.changeBackground(combo, isSelected)
val selectedClient = clientsProvider.clientByRow(row)
combo.model = DefaultComboBoxModel<Client>(clientsProvider.suggestClients(row).toTypedArray())
combo.selectedItem = selectedClient
return combo
}
override fun getCellEditorValue(): Any {
return combo.selectedItem
}
}
| apache-2.0 | 8f6c5e27a58ebcedc0a63172e0f95c38 | 35.930435 | 130 | 0.70073 | 4.729399 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/foursquare/FourSquareAuthFlow.kt | 1 | 1274 | package com.baulsupp.okurl.services.foursquare
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.SimpleWebServer
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.credentials.NoToken
import com.baulsupp.okurl.kotlin.queryMap
import okhttp3.OkHttpClient
import okhttp3.Response
import java.net.URLEncoder
object FourSquareAuthFlow {
suspend fun login(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
clientId: String,
clientSecret: String
): Oauth2Token {
SimpleWebServer.forCode().use { s ->
val serverUri = s.redirectUri
val loginUrl = "https://foursquare.com/oauth2/authenticate?client_id=$clientId&redirect_uri=${URLEncoder.encode(
serverUri, "UTF-8"
)}&response_type=code"
outputHandler.openLink(loginUrl)
val code = s.waitForCode()
val tokenUrl =
"https://foursquare.com/oauth2/access_token?client_id=$clientId&client_secret=$clientSecret&grant_type=authorization_code&redirect_uri=${URLEncoder.encode(
serverUri, "UTF-8"
)}&code=$code"
val responseMap = client.queryMap<Any>(tokenUrl, NoToken)
return Oauth2Token(responseMap["access_token"] as String)
}
}
}
| apache-2.0 | 58730c3ed9ec20aadb4cc5c493cb3c57 | 30.073171 | 163 | 0.734694 | 4.006289 | false | false | false | false |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/settings/fragment/EditorSettingFragment.kt | 1 | 9561 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.settings.fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import androidx.annotation.ColorInt
import androidx.annotation.LayoutRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import jp.toastkid.lib.color.IconColorFinder
import jp.toastkid.lib.preference.ColorPair
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.view.CompoundDrawableColorApplier
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.databinding.FragmentSettingEditorBinding
import jp.toastkid.yobidashi.editor.EditorFontSize
import jp.toastkid.yobidashi.libs.Toaster
import jp.toastkid.yobidashi.settings.color.ColorChooserDialogFragment
import jp.toastkid.yobidashi.settings.color.ColorChooserDialogFragmentViewModel
/**
* Editor setting fragment.
*
* @author toastkidjp
*/
class EditorSettingFragment : Fragment() {
/**
* View data binding object.
*/
private lateinit var binding: FragmentSettingEditorBinding
/**
* Preferences wrapper.
*/
private lateinit var preferenceApplier: PreferenceApplier
/**
* Initial background color.
*/
@ColorInt
private var initialBgColor: Int = 0
/**
* Initial font color.
*/
@ColorInt
private var initialFontColor: Int = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, LAYOUT_ID, container, false)
val activityContext = context ?: return super.onCreateView(inflater, container, savedInstanceState)
preferenceApplier = PreferenceApplier(activityContext)
binding.fragment = this
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.also { editorModule ->
val backgroundColor = preferenceApplier.editorBackgroundColor()
val fontColor = preferenceApplier.editorFontColor()
initialBgColor = backgroundColor
initialFontColor = fontColor
editorModule.backgroundPalette.also { picker ->
picker.addSVBar(editorModule.backgroundSvbar)
picker.addOpacityBar(editorModule.backgroundOpacitybar)
picker.setOnColorChangedListener { editorModule.ok.setBackgroundColor(it) }
picker.color = preferenceApplier.editorBackgroundColor()
}
editorModule.fontPalette.also { picker ->
picker.addSVBar(editorModule.fontSvbar)
picker.addOpacityBar(editorModule.fontOpacitybar)
picker.setOnColorChangedListener { editorModule.ok.setTextColor(it) }
picker.color = preferenceApplier.editorFontColor()
}
editorModule.fragment = this
editorModule.ok.setOnClickListener { ok() }
editorModule.prev.setOnClickListener { reset() }
ColorPair(backgroundColor, fontColor).setTo(binding.ok)
ColorPair(initialBgColor, initialFontColor).setTo(binding.prev)
editorModule.fontSize.adapter = object : BaseAdapter() {
override fun getCount(): Int = EditorFontSize.values().size
override fun getItem(position: Int): EditorFontSize
= EditorFontSize.values()[position]
override fun getItemId(position: Int): Long
= getItem(position).ordinal.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val item = EditorFontSize.values()[position]
if (convertView == null) {
val newView = layoutInflater.inflate(
android.R.layout.simple_spinner_item,
parent,
false
)
val viewHolder = FontSpinnerViewHolder(newView)
newView.tag = viewHolder
viewHolder.bind(item)
return newView
}
val viewHolder = convertView.tag as? FontSpinnerViewHolder?
viewHolder?.bind(item)
return convertView
}
}
editorModule.fontSize.setSelection(
EditorFontSize.findIndex(preferenceApplier.editorFontSize())
)
editorModule.fontSize.onItemSelectedListener =
object: AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
preferenceApplier.setEditorFontSize(EditorFontSize.values()[position].size)
}
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
}
val context = binding.root.context
val defaultCursorColor = ContextCompat.getColor(context, R.color.editor_cursor)
editorModule.cursorPreview.setBackgroundColor(
preferenceApplier.editorCursorColor(defaultCursorColor)
)
val defaultHighlightColor = ContextCompat.getColor(context, R.color.light_blue_200_dd)
editorModule.highlightPreview.setBackgroundColor(
preferenceApplier.editorHighlightColor(defaultHighlightColor)
)
}
}
override fun onResume() {
super.onResume()
val color = IconColorFinder.from(binding.root).invoke()
CompoundDrawableColorApplier().invoke(
color,
binding.textCursor,
binding.textHighlight,
binding.textFontSize
)
}
/**
* OK button's action.
*/
private fun ok() {
val backgroundColor = binding.backgroundPalette.color
val fontColor = binding.fontPalette.color
preferenceApplier.setEditorBackgroundColor(backgroundColor)
preferenceApplier.setEditorFontColor(fontColor)
binding.backgroundPalette.color = backgroundColor
binding.fontPalette.color = fontColor
val colorPair = ColorPair(backgroundColor, fontColor)
colorPair.setTo(binding.ok)
Toaster.snackShort(binding.root, R.string.settings_color_done_commit, colorPair)
}
/**
* Reset button's action.
*/
private fun reset() {
preferenceApplier.setEditorBackgroundColor(initialBgColor)
preferenceApplier.setEditorFontColor(initialFontColor)
binding.backgroundPalette.color = initialBgColor
binding.fontPalette.color = initialFontColor
ColorPair(initialBgColor, initialFontColor).setTo(binding.ok)
Toaster.snackShort(binding.root, R.string.settings_color_done_reset, preferenceApplier.colorPair())
}
fun showCursorColorSetting() {
val activity = activity ?: return
val currentColor = preferenceApplier.editorCursorColor(
ContextCompat.getColor(activity, R.color.editor_cursor)
)
ColorChooserDialogFragment.withCurrentColor(currentColor)
.show(
activity.supportFragmentManager,
ColorChooserDialogFragment::class.java.canonicalName
)
ViewModelProvider(activity)
.get(ColorChooserDialogFragmentViewModel::class.java)
.color
.observe(activity, {
preferenceApplier.setEditorCursorColor(it)
binding.cursorPreview.setBackgroundColor(it)
})
}
fun showHighlightColorSetting() {
val activity = activity ?: return
val currentColor = preferenceApplier.editorHighlightColor(
ContextCompat.getColor(activity, R.color.light_blue_200_dd)
)
ColorChooserDialogFragment.withCurrentColor(currentColor)
.show(
activity.supportFragmentManager,
ColorChooserDialogFragment::class.java.canonicalName
)
ViewModelProvider(activity)
.get(ColorChooserDialogFragmentViewModel::class.java)
.color
.observe(activity, {
preferenceApplier.setEditorHighlightColor(it)
binding.highlightPreview.setBackgroundColor(it)
})
}
companion object : TitleIdSupplier {
@LayoutRes
private const val LAYOUT_ID = R.layout.fragment_setting_editor
@StringRes
override fun titleId() = R.string.subhead_editor
}
} | epl-1.0 | 00a6f17456137b27a93510eeb62b7ce8 | 35.776923 | 107 | 0.632988 | 5.674184 | false | false | false | false |
chat-sdk/chat-sdk-android | chat-sdk-mod-ui-extras/src/main/java/sdk/chat/ui/extras/MainDrawerActivity.kt | 1 | 11990 | package sdk.chat.ui.extras
import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.miguelcatalan.materialsearchview.MaterialSearchView
import com.mikepenz.materialdrawer.holder.ImageHolder
import com.mikepenz.materialdrawer.holder.StringHolder
import com.mikepenz.materialdrawer.model.DividerDrawerItem
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem
import com.mikepenz.materialdrawer.model.ProfileDrawerItem
import com.mikepenz.materialdrawer.model.interfaces.IProfile
import com.mikepenz.materialdrawer.model.interfaces.withIcon
import com.mikepenz.materialdrawer.model.interfaces.withName
import com.mikepenz.materialdrawer.util.AbstractDrawerImageLoader
import com.mikepenz.materialdrawer.util.DrawerImageLoader
import com.mikepenz.materialdrawer.util.updateName
import com.mikepenz.materialdrawer.widget.AccountHeaderView
import io.reactivex.Single
import io.reactivex.functions.Action
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.activity_main_drawer.*
import sdk.chat.core.events.EventType
import sdk.chat.core.events.NetworkEvent
import sdk.chat.core.hook.Executor
import sdk.chat.core.hook.Hook
import sdk.chat.core.hook.HookEvent
import sdk.chat.core.interfaces.LocalNotificationHandler
import sdk.chat.core.session.ChatSDK
import sdk.chat.ui.activities.MainActivity
import sdk.chat.ui.fragments.BaseFragment
import sdk.chat.ui.icons.Icons
import sdk.chat.ui.interfaces.SearchSupported
import sdk.chat.ui.module.UIModule
import sdk.guru.common.RX
open class MainDrawerActivity : MainActivity() {
override fun getLayout(): Int {
return R.layout.activity_main_drawer
}
public lateinit var headerView: AccountHeaderView
public lateinit var actionBarDrawerToggle: ActionBarDrawerToggle
public lateinit var profile: IProfile
public var currentFragment: Fragment? = null
public lateinit var privateThreadItem: PrimaryDrawerItem
public lateinit var publicThreadItem: PrimaryDrawerItem
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layout)
initViews()
dm.add(ChatSDK.events().sourceOnMain().filter(NetworkEvent.filterType(EventType.MessageReadReceiptUpdated, EventType.MessageAdded)).subscribe(Consumer {
// Refresh the read count
dm.add(privateTabName().subscribe(Consumer {
slider.updateName(privateThreadItem.identifier, it)
}))
}))
// Update the user details
dm.add(ChatSDK.events().sourceOnMain().filter(NetworkEvent.filterType(EventType.UserMetaUpdated)).filter(NetworkEvent.filterCurrentUser()).subscribe(Consumer {
headerView.post {
updateProfile()
headerView.updateProfile(profile)
updateHeaderBackground()
}
}))
ChatSDK.hook().addHook(Hook.sync(Executor {
headerView.post {
updateProfile()
headerView.updateProfile(profile)
updateHeaderBackground()
}
}), HookEvent.DidAuthenticate);
DrawerImageLoader.init(object : AbstractDrawerImageLoader() {
override fun set(imageView: ImageView, uri: Uri, placeholder: Drawable, tag: String?) {
Glide.with(this@MainDrawerActivity)
.load(uri)
.dontAnimate()
.placeholder(placeholder)
.into(imageView)
}
override fun cancel(imageView: ImageView) {
Glide.with(this@MainDrawerActivity).clear(imageView)
}
})
// Handle Toolbar
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
actionBarDrawerToggle = ActionBarDrawerToggle(this, root, toolbar, R.string.material_drawer_open, R.string.material_drawer_close)
buildHeader(false, savedInstanceState)
val logoutItem = PrimaryDrawerItem().withName(R.string.logout).withIcon(Icons.get(this, Icons.choose().logout, R.color.logout_button_color))
logoutItem.name = StringHolder(R.string.logout)
logoutItem.isSelectable = false
val profileItem = PrimaryDrawerItem().withName(R.string.profile).withIcon(Icons.get(this, Icons.choose().user, R.color.profile_icon_color))
profileItem.isSelectable = false
slider.apply {
for (tab in ChatSDK.ui().tabs()) {
val item = PrimaryDrawerItem().withName(tab.title).withIcon(tab.icon)
itemAdapter.add(item)
if(tab.fragment === ChatSDK.ui().privateThreadsFragment()) {
privateThreadItem = item
dm.add(privateTabName().subscribe(Consumer {
slider.updateName(privateThreadItem.identifier, it)
}))
}
if(tab.fragment === ChatSDK.ui().publicThreadsFragment()) {
publicThreadItem = item
}
}
itemAdapter.add(DividerDrawerItem())
itemAdapter.add(profileItem)
itemAdapter.add(logoutItem)
onDrawerItemClickListener = { v, drawerItem, position ->
// Logout item
if(drawerItem === logoutItem) {
logoutClicked()
} else if(drawerItem === profileItem) {
ChatSDK.ui().startProfileActivity(context, ChatSDK.currentUserID())
} else {
setFragmentForPosition(position - 1)
}
false
}
setSavedInstance(savedInstanceState)
}
setFragmentForPosition(0);
}
open fun privateTabName(): Single<StringHolder> {
return KotlinHelper.privateTabName().observeOn(RX.main())
}
open fun logoutClicked() {
ChatSDK.auth().logout().observeOn(RX.main()).doOnComplete(Action { ChatSDK.ui().startSplashScreenActivity(this@MainDrawerActivity) }).subscribe(this@MainDrawerActivity)
}
open fun updateProfile() {
val user = ChatSDK.currentUser()
profile = ProfileDrawerItem().apply {
identifier = 1
name = StringHolder(user.name)
description = StringHolder(user.status)
if(user.avatarURL != null) {
icon = ImageHolder(user.avatarURL!!)
} else {
icon = ImageHolder(UIModule.config().defaultProfilePlaceholder)
}
}
// Create the AccountHeader
}
open fun setFragmentForPosition(position: Int) {
val tabs = ChatSDK.ui().tabs()
val tab = tabs.get(position)
supportFragmentManager.beginTransaction().replace(R.id.fragment_container, tab.fragment).commit()
supportActionBar?.setTitle(tab.title)
currentFragment = tab.fragment
updateLocalNotificationsForTab()
// We mark the tab as visible. This lets us be more efficient with updates
// because we only
for (i in tabs.indices) {
val fragment: Fragment = tabs.get(i).fragment
if (fragment is BaseFragment) {
(tabs.get(i).fragment as BaseFragment).setTabVisibility(fragment === currentFragment)
}
}
}
/**
* small helper method to reuse the logic to build the AccountHeader
* this will be used to replace the header of the drawer with a compact/normal header
*
* @param compact
* @param savedInstanceState
*/
open fun buildHeader(compact: Boolean, savedInstanceState: Bundle?) {
updateProfile()
// Create the AccountHeader
headerView = AccountHeaderView(this, compact = compact).apply {
attachToSliderView(slider)
addProfiles(
profile
//don't ask but google uses 14dp for the add account icon in gmail but 20dp for the normal icons (like manage account)
// ProfileSettingDrawerItem().apply {
// name = StringHolder(R.string.logout)
// icon = ImageHolder(Icons.get(this, Icons.choose().logout, R.color.logout_button_color))
// }
)
selectionListEnabledForSingleProfile = false
withSavedInstance(savedInstanceState)
onAccountHeaderListener = { view, profile, current ->
ChatSDK.ui().startProfileActivity(context, ChatSDK.currentUserID())
false
}
// onAccountHeaderSelectionViewClickListener = { view, profile, current ->
// ChatSDK.ui().startProfileActivity(context, ChatSDK.currentUserID())
// false
// }
}
headerView.currentProfileName.setTextColor(ContextCompat.getColor(this, R.color.app_bar_text_color))
headerView.currentProfileEmail.setTextColor(ContextCompat.getColor(this, R.color.app_bar_text_color))
headerView.setBackgroundColor(ContextCompat.getColor(this, R.color.primary))
// headerView.currentProfileView.setBackgroundColor(Color.WHITE)
headerView.currentProfileView.setBackgroundDrawable(resources.getDrawable(R.drawable.shape_circle))
updateHeaderBackground()
}
open fun updateHeaderBackground() {
val user = ChatSDK.currentUser()
if(user.headerURL != null) {
// headerView.headerBackground = ImageHolder(user.headerURL)
Glide.with(this).load(user.headerURL).into(headerView.accountHeaderBackground)
} else {
headerView.headerBackground = ImageHolder(ExtrasModule.config().drawerHeaderImage)
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
actionBarDrawerToggle.onConfigurationChanged(newConfig)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
actionBarDrawerToggle.syncState()
}
override fun onSaveInstanceState(_outState: Bundle) {
var outState = _outState
//add the values which need to be saved from the drawer to the bundle
outState = slider.saveInstanceState(outState)
//add the values which need to be saved from the accountHeader to the bundle
outState = headerView.saveInstanceState(outState)
super.onSaveInstanceState(outState)
}
override fun onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (root.isDrawerOpen(slider)) {
root.closeDrawer(slider)
} else {
super.onBackPressed()
}
}
override fun searchEnabled(): Boolean {
return currentFragment is SearchSupported
}
override fun search(text: String?) {
(currentFragment as SearchSupported).filter(text)
}
override fun searchView(): MaterialSearchView {
return searchView
}
override fun reloadData() {
for (tab in ChatSDK.ui().tabs()) {
(tab.fragment as BaseFragment).reloadData()
}
}
// override fun initViews() {
// }
override fun clearData() {
for (tab in ChatSDK.ui().tabs()) {
(tab.fragment as BaseFragment).clearData()
}
}
override fun updateLocalNotificationsForTab() {
ChatSDK.ui().setLocalNotificationHandler(LocalNotificationHandler {
showLocalNotificationsForTab(currentFragment, it)
})
}
}
| apache-2.0 | 0fa2e80a2b839dc3c38b3c7dd976cba2 | 37.306709 | 176 | 0.657214 | 5.029362 | false | false | false | false |
maballesteros/vertx3-kotlin-rest-jdbc-tutorial | step05/src/tutorial05.kt | 1 | 2252 | import io.vertx.core.json.JsonObject
import io.vertx.ext.jdbc.JDBCClient
/**
* Step05 - Promisified JDBC backed REST User repository
*/
val dbConfig = JsonObject()
.put("url", "jdbc:hsqldb:mem:test?shutdown=true")
.put("driver_class", "org.hsqldb.jdbcDriver")
.put("max_pool_size", 30)
object Vertx3KotlinRestJdbcTutorial {
@JvmStatic fun main(args: Array<String>) {
val vertx = promisedVertx()
val client = JDBCClient.createShared(vertx, dbConfig);
val userService = JdbcUserService(client)
vertx.restApi(9000) {
get("/:userId") { send(userService.getUser(param("userId"))) }
post("/") { send(userService.addUser(bodyAs(User::class))) }
delete("/:userId") { send(userService.remUser(param("userId"))) }
}
}
}
//-----------------------------------------------------------------------------
// API
data class User(val id:String, val fname: String, val lname: String)
interface UserService {
fun getUser(id: String): Promise<User?>
fun addUser(user: User): Promise<Unit>
fun remUser(id: String): Promise<Unit>
}
//-----------------------------------------------------------------------------
// IMPLEMENTATION
class JdbcUserService(private val client: JDBCClient): UserService {
init {
client.execute("""
CREATE TABLE USERS
(ID VARCHAR(25) NOT NULL,
FNAME VARCHAR(25) NOT NULL,
LNAME VARCHAR(25) NOT NULL)
""").then {
val user = User("1", "user1_fname", "user1_lname")
addUser(user).then {
println("Added user $user")
}
}
}
override fun getUser(id: String): Promise<User?> =
client.queryOne("SELECT ID, FNAME, LNAME FROM USERS WHERE ID=?", listOf(id)) {
User(it.getString(0), it.getString(1), it.getString(2))
}
override fun addUser(user: User): Promise<Unit> =
client.update("INSERT INTO USERS (ID, FNAME, LNAME) VALUES (?, ?, ?)",
listOf(user.id, user.fname, user.lname)).then { }
override fun remUser(id: String): Promise<Unit> =
client.update("DELETE FROM USERS WHERE ID = ?", listOf(id)).then { }
} | apache-2.0 | ef34abb784da004f7c904a6051cd42f4 | 26.47561 | 86 | 0.554618 | 4.109489 | false | false | false | false |
nesterov-n/ProgrammerAdviceBot | src/main/kotlin/ru/nnesterov/bot/model/Message.kt | 1 | 795 | package ru.nnesterov.bot.model
import com.google.gson.annotations.SerializedName
class Message {
/**
* @return Unique message identifier
*/
@SerializedName("message_id")
val messageId: Int = 0
/**
* @return Sender
*/
@SerializedName("from")
val from: User? = null
/**
* @return Date the message was sent in Unix time
*/
@SerializedName("date")
val date: Int = 0
/**
* @return Conversation the message belongs to — [User] in case of a private message, [GroupChat] in case of a group
*/
@SerializedName("chat")
val chat: Chat? = null
/**
* *Optional.*
* @return For text messages, the actual UTF-8 text of the message
*/
@SerializedName("text")
val text: String? = null
} | apache-2.0 | 424f7cd760e7ecdf1205aea40ffc8dbf | 19.358974 | 120 | 0.59773 | 4.087629 | false | false | false | false |
google/horologist | media-data/src/main/java/com/google/android/horologist/media/data/database/dao/MediaDownloadDao.kt | 1 | 3108 | /*
* 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.media.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi
import com.google.android.horologist.media.data.database.model.MediaDownloadEntity
import com.google.android.horologist.media.data.database.model.MediaDownloadEntityStatus
import kotlinx.coroutines.flow.Flow
/**
* DAO for [MediaDownloadEntity].
*/
@ExperimentalHorologistMediaDataApi
@Dao
public interface MediaDownloadDao {
@Query(
value = """
SELECT * FROM MediaDownloadEntity
WHERE mediaId in (:mediaIds)
"""
)
public fun getList(mediaIds: List<String>): Flow<List<MediaDownloadEntity>>
@Query(
value = """
SELECT * FROM MediaDownloadEntity
WHERE status = :status
"""
)
public suspend fun getAllByStatus(
status: MediaDownloadEntityStatus
): List<MediaDownloadEntity>
@Insert(onConflict = OnConflictStrategy.IGNORE)
public suspend fun insert(mediaDownloadEntity: MediaDownloadEntity): Long
@Query(
"""
UPDATE MediaDownloadEntity
SET status = :status
WHERE mediaId = :mediaId
"""
)
public suspend fun updateStatus(mediaId: String, status: MediaDownloadEntityStatus)
@Query(
"""
UPDATE MediaDownloadEntity
SET progress = :progress,
size = :size
WHERE mediaId = :mediaId
"""
)
public suspend fun updateProgress(mediaId: String, progress: Float, size: Long)
@Update(entity = MediaDownloadEntity::class)
public suspend fun updateStatusAndProgress(statusAndProgress: StatusAndProgress)
@Query(
"""
DELETE FROM MediaDownloadEntity
WHERE mediaId = :mediaId
"""
)
public suspend fun delete(mediaId: String)
@Query(
"""
DELETE FROM MediaDownloadEntity
WHERE mediaId in (:mediaIds)
"""
)
public suspend fun delete(mediaIds: List<String>)
public data class StatusAndProgress(
val mediaId: String,
val status: MediaDownloadEntityStatus,
val progress: Float
)
public companion object {
public const val DOWNLOAD_PROGRESS_START: Float = 0f
public const val DOWNLOAD_PROGRESS_END: Float = 100f
public const val SIZE_UNKNOWN: Long = -1L
}
}
| apache-2.0 | e38be4ebf3a7660a815489d45da4cca7 | 28.320755 | 88 | 0.694337 | 4.65967 | false | false | false | false |
semonte/intellij-community | java/java-tests/testSrc/com/intellij/java/psi/impl/light/JavaModuleNameDetectionTest.kt | 1 | 1244 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.psi.impl.light
import com.intellij.psi.impl.light.LightJavaModule
import org.junit.Test
import kotlin.test.assertEquals
class JavaModuleNameDetectionTest {
@Test fun plain() = doTest("foo", "foo")
@Test fun versioned() = doTest("foo-1.2.3-SNAPSHOT", "foo")
@Test fun trailing() = doTest("foo2bar1.2.3", "foo2bar")
@Test fun replacing() = doTest("foo_bar", "foo.bar")
@Test fun collapsing() = doTest("foo...bar", "foo.bar")
@Test fun trimming() = doTest("...foo.bar...", "foo.bar")
private fun doTest(original: String, expected: String) = assertEquals(expected, LightJavaModule.moduleName(original))
} | apache-2.0 | 435fa28fd38afd00e1d972932bbef36a | 39.16129 | 119 | 0.724277 | 3.691395 | false | true | false | false |
Agusyc/DayCounter | app/src/main/java/com/agusyc/daycounter/CounterListAdapter.kt | 1 | 5256 | package com.agusyc.daycounter
import android.content.Context
import android.graphics.Color
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AlphaAnimation
import android.widget.ArrayAdapter
import android.widget.TextView
import org.joda.time.DateTime
import org.joda.time.Days
import java.text.DecimalFormat
import java.util.*
internal class CounterListAdapter(context: Context, alarms: ArrayList<Counter>) : ArrayAdapter<Counter>(context, 0, alarms) {
// This represents the context resources, for getting quantityStrings.
val res = context.resources!!
// This method runs as much times as there are counters defined by the user, so it adds everyone to the listview.
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
// We get the counter for the current position
val counter = getItem(position)
val newConvertView: View = convertView ?: LayoutInflater.from(context).inflate(R.layout.counter_row, parent, false)
// We get all the needed data, views and objects
val date = counter!!.date
val currentTime = System.currentTimeMillis()
val difference = Days.daysBetween(DateTime(date), DateTime(currentTime)).days
val absDifference = Math.abs(difference)
val formatter = DecimalFormat("#,###,###")
// We initialise all the views
val txtDays = newConvertView.findViewById<TextView>(R.id.txtDays)
// We set the days text to the *absolute* difference
txtDays.text = formatter.format(absDifference)
val txtLabel = newConvertView.findViewById<TextView>(R.id.txtLabel)
val txtThereAreHaveBeen = newConvertView.findViewById<TextView>(R.id.txtThereAreHaveBeen)
val btnReset = newConvertView.findViewById<ResetButton>(R.id.btnReset)
// We check the sign of the number (Positive or negative, since or until), so we can set up the list's views accordingly
when {
difference > 0 -> {
// The counter's date is behind current time
txtLabel.text = context.resources.getQuantityString(R.plurals.days_since, absDifference, counter.label)
btnReset.widget_id = counter.id
btnReset.isWidget = counter.isWidget
txtDays.visibility = View.VISIBLE
btnReset.visibility = View.VISIBLE
txtThereAreHaveBeen.visibility = View.VISIBLE
txtThereAreHaveBeen.text = res.getQuantityText(R.plurals.there_has_have_been, absDifference)
}
difference < 0 -> {
// The counter's date is after the current time
txtLabel.text = res.getQuantityString(R.plurals.days_until, absDifference, counter.label)
txtDays.visibility = View.VISIBLE
txtThereAreHaveBeen.visibility = View.VISIBLE
txtThereAreHaveBeen.text = res.getQuantityText(R.plurals.there_is_are, absDifference)
btnReset.visibility = View.GONE
}
else -> {
// The counter's date is today
txtLabel.text = context.getString(R.string.there_are_no_days_since, counter.label)
txtLabel.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24f)
txtDays.visibility = View.GONE
btnReset.visibility = View.GONE
txtThereAreHaveBeen.visibility = View.GONE
}
}
Log.i("CounterListAdapter", "Adding widget " + counter.id + " with label " + counter.label + ", original/target date " + date)
Log.i("CounterListAdapter", "The new difference is $difference. The current time is $currentTime")
// We get the counter's color
val color = counter.color
// We set the item's background color
newConvertView.setBackgroundColor(color)
val hsv = FloatArray(3)
Color.colorToHSV(color, hsv)
// We calculate the brightness of the background color and set icons and text color accordingly
val brightness = (1 - hsv[1] + hsv[2]) / 2
if (brightness >= 0.61) {
txtDays.setTextColor(Color.BLACK)
txtLabel.setTextColor(Color.BLACK)
(newConvertView.findViewById<TextView>(R.id.txtThereAreHaveBeen) as TextView).setTextColor(Color.BLACK)
btnReset.setColorFilter(Color.BLACK)
} else {
txtDays.setTextColor(Color.WHITE)
txtLabel.setTextColor(Color.WHITE)
(newConvertView.findViewById<TextView>(R.id.txtThereAreHaveBeen) as TextView).setTextColor(Color.WHITE)
btnReset.setColorFilter(Color.WHITE)
}
// This is for controlling the animations when adding a new widget
if (!(context as MainActivity).dontAnimate) {
val animation = AlphaAnimation(0f, 1.0f)
animation.duration = 400
animation.startOffset = 100
animation.fillAfter = true
newConvertView.startAnimation(animation)
}
// Return the completed view to render on the main activity
return newConvertView
}
}
| mit | 84009019cf1b6fba9ea7b1e79b945ab4 | 45.105263 | 134 | 0.66153 | 4.726619 | false | false | false | false |
FredJul/TaskGame | TaskGame-Hero/src/main/java/net/fred/taskgame/hero/views/BugfixedBottomSheetBehavior.kt | 1 | 1785 | /*
* Copyright (c) 2012-2017 Frederic Julian
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package net.fred.taskgame.hero.views
import android.content.Context
import android.support.design.widget.BottomSheetBehavior
import android.support.design.widget.CoordinatorLayout
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
class BugfixedBottomSheetBehavior<V : View> : BottomSheetBehavior<V> {
constructor() : super()
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onTouchEvent(parent: CoordinatorLayout?, child: V, event: MotionEvent?): Boolean {
if (state == BottomSheetBehavior.STATE_HIDDEN || state == BottomSheetBehavior.STATE_SETTLING) {
return false
}
return super.onTouchEvent(parent, child, event)
}
override fun onInterceptTouchEvent(parent: CoordinatorLayout?, child: V, event: MotionEvent?): Boolean {
if (state == BottomSheetBehavior.STATE_HIDDEN || state == BottomSheetBehavior.STATE_SETTLING) {
return false
}
return super.onInterceptTouchEvent(parent, child, event)
}
}
| gpl-3.0 | 9a56de2496255e8b12a6329b76ee4ee8 | 37.804348 | 108 | 0.731653 | 4.576923 | false | false | false | false |
silviusko/android-toolkit | toolkit/src/main/java/com/ktt/toolkit/widget/GradientMaskImageView.kt | 1 | 1684 | package com.ktt.toolkit.widget
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.widget.ImageView
/**
* Created by luke.kao on 2019/1/16.
*/
private const val VIEW_PORT_WIDTH = 100f
private const val VIEW_PORT_HEIGHT = 100f
class GradientMaskImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ImageView(context, attrs, defStyleAttr) {
private var linearGradient: LinearGradient? = null
private var localMatrix = Matrix()
private var saveLayerPaint = Paint()
private var imagePaint = Paint().apply {
isAntiAlias = true
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
}
override fun onDraw(canvas: Canvas?) {
// this must be saved before super.onDraw()
canvas?.saveLayer(0f, 0f, width.toFloat(), height.toFloat(), saveLayerPaint)
super.onDraw(canvas)
val saveCount = canvas?.save() ?: return
linearGradient?.apply {
localMatrix.reset()
localMatrix.setScale(width / VIEW_PORT_WIDTH, height / VIEW_PORT_HEIGHT)
this.setLocalMatrix(localMatrix)
imagePaint.shader = this
canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), imagePaint)
}
canvas.restoreToCount(saveCount)
}
fun setGradient(from: Int, to: Int) {
linearGradient = LinearGradient(
VIEW_PORT_WIDTH / 2,
0f,
VIEW_PORT_WIDTH / 2,
VIEW_PORT_HEIGHT,
from,
to,
Shader.TileMode.CLAMP
)
}
} | apache-2.0 | e11480f7133117b19276431b2e90828e | 28.561404 | 84 | 0.625891 | 4.317949 | false | false | false | false |
yyued/CodeX-UIKit-Android | library/src/main/java/com/yy/codex/uikit/UIImage.kt | 1 | 2716 | package com.yy.codex.uikit
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.support.v4.util.LruCache
import android.util.Base64
/**
* Created by cuiminghui on 2017/1/10.
*/
class UIImage {
enum class RenderingMode {
Automatic,
AlwaysOriginal,
AlwaysTemplate
}
constructor(scale: Double) {
bitmap = Bitmap.createBitmap(0, 0, Bitmap.Config.ARGB_8888)
this.scale = scale
}
constructor(context: Context, resID: Int) {
if (sResCache.get(resID) is Bitmap) {
bitmap = sResCache.get(resID)
when (bitmap.density) {
160 -> this.scale = 1.0
240 -> this.scale = 1.5
320 -> this.scale = 2.0
480 -> this.scale = 3.0
640 -> this.scale = 4.0
else -> this.scale = bitmap.density / 160.0
}
} else {
val options = BitmapFactory.Options()
options.inScaled = false
bitmap = BitmapFactory.decodeResource(context.resources, resID, options)
when (bitmap.density) {
160 -> this.scale = 1.0
240 -> this.scale = 1.5
320 -> this.scale = 2.0
480 -> this.scale = 3.0
640 -> this.scale = 4.0
else -> this.scale = bitmap.density / 160.0
}
sResCache.put(resID, bitmap)
}
}
constructor(data: ByteArray, scale: Double = 1.0) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.size)
this.scale = scale
}
constructor(base64String: String, scale: Double = 1.0) {
val data = Base64.decode(base64String, Base64.DEFAULT)
bitmap = BitmapFactory.decodeByteArray(data, 0, data.size)
this.scale = scale
}
constructor(bitmap: Bitmap, scale: Double = 1.0) {
this.bitmap = bitmap
this.scale = scale
}
/* Scale */
val scale: Double
/* RenderingMode */
var renderingMode = RenderingMode.Automatic
/* Bitmap instance */
val bitmap: Bitmap?
val size: CGSize
get() {
if (bitmap == null) {
return CGSize(0.0, 0.0)
}
return CGSize(Math.ceil(bitmap.width / scale), Math.ceil(bitmap.height / scale))
}
override fun equals(other: Any?): Boolean {
var other = other as? UIImage ?: return false
return scale == other.scale && renderingMode == other.renderingMode && bitmap == other.bitmap;
}
companion object {
private val sResCache = LruCache<Number, Bitmap>(8 * 1024 * 1024)
}
}
| gpl-3.0 | 4daec225b8ef4588322827ace16548d9 | 26.714286 | 102 | 0.557806 | 4.090361 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/diff/TagsDiffCallback.kt | 1 | 677 | package com.booboot.vndbandroid.diff
import androidx.recyclerview.widget.DiffUtil
import com.booboot.vndbandroid.model.vndbandroid.VNTag
class TagsDiffCallback(private var oldItems: List<VNTag>, private var newItems: List<VNTag>) : DiffUtil.Callback() {
override fun getOldListSize() = oldItems.size
override fun getNewListSize() = newItems.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldItems[oldItemPosition].tag.id == newItems[newItemPosition].tag.id
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int) =
oldItems[oldItemPosition].tag == newItems[newItemPosition].tag
} | gpl-3.0 | e2dc573845075195522c97c5512d79de | 41.375 | 116 | 0.768095 | 4.905797 | false | false | false | false |
http4k/http4k | src/docs/guide/reference/json/autoJson.kt | 1 | 1288 | package guide.reference.json
import org.http4k.core.Body
import org.http4k.core.Method.GET
import org.http4k.core.Request
import org.http4k.format.Jackson.auto
data class Email(val value: String)
data class Message(val subject: String, val from: Email, val to: Email)
fun main() {
// We can use the auto method here from either Jackson, Gson or the Xml message format objects.
// Note that the auto() method needs to be manually imported as IntelliJ won't pick it up automatically.
val messageLens = Body.auto<Message>().toLens()
val myMessage = Message("hello", Email("[email protected]"), Email("[email protected]"))
// to inject the body into the message - this also works with Response
val requestWithEmail = messageLens(myMessage, Request(GET, "/"))
println(requestWithEmail)
// Produces:
// GET / HTTP/1.1
// content-type: application/json
//
// {"subject":"hello","from":{"value":"[email protected]"},"to":{"value":"[email protected]"}}
// to extract the body from the message - this also works with Response
val extractedMessage = messageLens(requestWithEmail)
println(extractedMessage)
println(extractedMessage == myMessage)
// Produces:
// Message(subject=hello, from=Email([email protected]), to=Email([email protected]))
// true
}
| apache-2.0 | f2c9c1d3f84803012b26c91e67741e0e | 32.894737 | 108 | 0.707298 | 3.648725 | false | false | false | false |
tkiapril/Weisseliste | src/main/kotlin/kotlin/sql/Queries.kt | 1 | 6549 | package kotlin.sql
import java.util.*
import kotlin.sql.vendors.dialect
inline fun FieldSet.select(where: SqlExpressionBuilder.()->Op<Boolean>) : Query {
return select(SqlExpressionBuilder.where())
}
fun FieldSet.select(where: Op<Boolean>) : Query {
return Query(Session.get(), this, where)
}
fun FieldSet.selectAll() : Query {
return Query(Session.get(), this, null)
}
inline fun Table.deleteWhere(op: SqlExpressionBuilder.()->Op<Boolean>) {
DeleteQuery.where(Session.get(), this@deleteWhere, SqlExpressionBuilder.op())
}
inline fun Table.deleteIgnoreWhere(op: SqlExpressionBuilder.()->Op<Boolean>) {
DeleteQuery.where(Session.get(), this@deleteIgnoreWhere, SqlExpressionBuilder.op(), true)
}
fun Table.deleteAll() {
DeleteQuery.all(Session.get(), this@deleteAll)
}
fun <T:Table> T.insert(body: T.(InsertQuery)->Unit): InsertQuery {
val answer = InsertQuery(this)
body(answer)
answer.execute(Session.get())
return answer
}
fun <T:Table, E:Any> T.batchInsert(data: Iterable<E>, ignore: Boolean = false, body: BatchInsertQuery.(E)->Unit): List<Int> {
BatchInsertQuery(this, ignore).let {
for (element in data) {
it.addBatch()
it.body(element)
}
return it.execute(Session.get())
}
}
fun <T:Table> T.insertIgnore(body: T.(InsertQuery)->Unit): InsertQuery {
val answer = InsertQuery(this, isIgnore = true)
body(answer)
answer.execute(Session.get())
return answer
}
fun <T:Table> T.replace(body: T.(InsertQuery)->Unit): InsertQuery {
val answer = InsertQuery(this, isReplace = true)
body(answer)
answer.execute(Session.get())
return answer
}
fun <T:Table> T.insert (selectQuery: Query): Unit {
val answer = InsertSelectQuery (this, selectQuery)
answer.execute(Session.get())
}
fun <T:Table> T.replace(selectQuery: Query): Unit {
val answer = InsertSelectQuery (this, selectQuery, isReplace = true)
answer.execute(Session.get())
}
fun <T:Table> T.insertIgnore (selectQuery: Query): Unit {
val answer = InsertSelectQuery (this, selectQuery, isIgnore = true)
answer.execute(Session.get())
}
fun <T:Table> T.update(where: SqlExpressionBuilder.()->Op<Boolean>, limit: Int? = null, body: T.(UpdateQuery)->Unit): Int {
val query = UpdateQuery({session -> session.identity(this)}, limit, SqlExpressionBuilder.where())
body(query)
return query.execute(Session.get())
}
fun Join.update(where: (SqlExpressionBuilder.()->Op<Boolean>)? = null, limit: Int? = null, body: (UpdateQuery)->Unit) : Int {
val query = UpdateQuery({session -> this.describe(session)}, limit, where?.let { SqlExpressionBuilder.it() })
body(query)
return query.execute(Session.get())
}
fun Table.exists (): Boolean = dialect.tableExists(this)
/**
* Log entity <-> database mapping problems and returns DDL Statements to fix them
*/
fun checkMappingConsistence(vararg tables: Table): List<String> {
checkExcessiveIndices(*tables)
return checkMissingIndices(*tables).map{ it.createStatement() }
}
fun checkExcessiveIndices(vararg tables: Table) {
val excessiveConstraints = dialect.columnConstraints(*tables).filter { it.value.size > 1 }
if (!excessiveConstraints.isEmpty()) {
exposedLogger.warn("List of excessive foreign key constraints:")
excessiveConstraints.forEach {
val (pair, fk) = it
val constraint = fk.first()
exposedLogger.warn("\t\t\t'${pair.first}'.'${pair.second}' -> '${constraint.referencedTable}'.'${constraint.referencedColumn}':\t${fk.map{it.fkName}.joinToString(", ")}")
}
exposedLogger.info("SQL Queries to remove excessive keys:");
excessiveConstraints.forEach {
it.value.take(it.value.size - 1).forEach {
exposedLogger.info("\t\t\t${it.dropStatement()};")
}
}
}
val excessiveIndices = dialect.existingIndices(*tables).flatMap { it.value }.groupBy { Triple(it.tableName, it.unique, it.columns.joinToString()) }.filter { it.value.size > 1}
if (!excessiveIndices.isEmpty()) {
exposedLogger.warn("List of excessive indices:")
excessiveIndices.forEach {
val (triple, indices) = it
exposedLogger.warn("\t\t\t'${triple.first}'.'${triple.third}' -> ${indices.map{it.indexName}.joinToString(", ")}")
}
exposedLogger.info("SQL Queries to remove excessive indices:");
excessiveIndices.forEach {
it.value.take(it.value.size - 1).forEach {
exposedLogger.info("\t\t\t${it.dropStatement()};")
}
}
}
}
/** Returns list of indices missed in database **/
private fun checkMissingIndices(vararg tables: Table): List<Index> {
fun Collection<Index>.log(mainMessage: String) {
if (isNotEmpty()) {
exposedLogger.warn(mainMessage)
forEach {
exposedLogger.warn("\t\t$it")
}
}
}
val fKeyConstraints = dialect.columnConstraints(*tables).keys
fun List<Index>.filterFKeys() = filterNot { it.tableName to it.columns.singleOrNull()?.orEmpty() in fKeyConstraints}
val allExistingIndices = dialect.existingIndices(*tables)
val missingIndices = HashSet<Index>()
val notMappedIndices = HashMap<String, MutableSet<Index>>()
val nameDiffers = HashSet<Index>()
for (table in tables) {
val existingTableIndices = allExistingIndices[table.tableName].orEmpty().filterFKeys()
val mappedIndices = table.indices.map { Index.forColumns(*it.first, unique = it.second)}.filterFKeys()
existingTableIndices.forEach { index ->
mappedIndices.firstOrNull { it.onlyNameDiffer(index) }?.let {
exposedLogger.trace("Index on table '${table.tableName}' differs only in name: in db ${index.indexName} -> in mapping ${it.indexName}")
nameDiffers.add(index)
nameDiffers.add(it)
}
}
notMappedIndices.getOrPut(table.javaClass.simpleName, {hashSetOf()}).addAll(existingTableIndices.subtract(mappedIndices))
missingIndices.addAll(mappedIndices.subtract(existingTableIndices))
}
val toCreate = missingIndices.subtract(nameDiffers)
toCreate.log("Indices missed from database (will be created):")
notMappedIndices.forEach { it.value.subtract(nameDiffers).log("Indices exist in database and not mapped in code on class '${it.key}':") }
return toCreate.toList()
}
internal val dialect = Session.get().vendor.dialect()
| agpl-3.0 | 452878805adb0711dddc831be685c9d5 | 36.210227 | 182 | 0.667125 | 3.94994 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/template/Replacement.kt | 1 | 3133 | /****************************************************************************************
* Copyright (c) 2020 Arthur Milchior <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki.template
import androidx.annotation.VisibleForTesting
import com.ichi2.libanki.template.TemplateError.FieldNotFound
import com.ichi2.libanki.template.TemplateFilters.apply_filter
import com.ichi2.utils.KotlinCleanup
@KotlinCleanup("IDE Lint")
class Replacement(
/**
* The name of the field to show
*/
private val key: String,
/**
* List of filter to apply (from right to left)
*/
private val filters: List<String>,
/**
* The entire content between {{ and }}
*/
private val tag: String
) : ParsedNode() {
// Only used for test
@VisibleForTesting
constructor(key: String, vararg filters: String?) : this(
key,
filters.map { it!! },
""
) {
}
override fun template_is_empty(nonempty_fields: Set<String>): Boolean {
return !nonempty_fields.contains(key)
}
@Throws(FieldNotFound::class)
override fun render_into(
fields: Map<String, String>,
nonempty_fields: Set<String>,
builder: StringBuilder
) {
var txt = fields[key]
if (txt == null) {
txt = if (key.trim { it <= ' ' }.isEmpty() && !filters.isEmpty()) {
""
} else {
throw FieldNotFound(filters, key)
}
}
for (filter in filters) {
txt = apply_filter(txt!!, filter, key, tag)
}
builder.append(txt)
}
override fun equals(other: Any?): Boolean {
if (other !is Replacement) {
return false
}
return other.key == key && other.filters == filters
}
override fun toString(): String {
return "new Replacement(\"" + key.replace("\\", "\\\\") + ", " + filters + "\")"
}
}
| gpl-3.0 | f1ace4e690b02367fff9bc5e61fb3a71 | 37.207317 | 90 | 0.490903 | 5.045089 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/crypto/HdWalletBuilder.kt | 1 | 8555 | /*
*
* * Copyright (c) 2018. Toshi Inc
* *
* * This program is free software: you can redistribute it and/or modify
* * it under the terms of the GNU General Public License as published by
* * the Free Software Foundation, either version 3 of the License, or
* * (at your option) any later version.
* *
* * This program is distributed in the hope that it will be useful,
* * but WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* * GNU General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.toshi.crypto
import android.content.Context
import com.toshi.crypto.hdshim.EthereumKeyChainGroup
import com.toshi.crypto.keyStore.KeyStoreHandler
import com.toshi.exception.InvalidMasterSeedException
import com.toshi.exception.KeyStoreException
import com.toshi.util.logging.LogUtil
import com.toshi.util.sharedPrefs.WalletPrefs
import com.toshi.util.sharedPrefs.WalletPrefsInterface
import com.toshi.view.BaseApplication
import org.bitcoinj.core.NetworkParameters
import org.bitcoinj.crypto.DeterministicKey
import org.bitcoinj.crypto.MnemonicException
import org.bitcoinj.wallet.DeterministicSeed
import org.bitcoinj.wallet.KeyChain
import org.bitcoinj.wallet.UnreadableWalletException
import org.bitcoinj.wallet.Wallet
import rx.Single
import java.io.IOException
class HdWalletBuilder(
private val walletPrefs: WalletPrefsInterface = WalletPrefs(),
private val context: Context = BaseApplication.get()
) {
companion object {
private const val ALIAS = "MasterSeedAlias"
}
fun createWalletAndOverrideWalletSeedOnDisk(): Single<HDWallet> {
return Single.fromCallable {
val networkParameters = getNetworkParameters()
val walletForSeed = Wallet(networkParameters)
val seed = walletForSeed.keyChainSeed
val wallet = constructFromSeed(seed)
val masterSeed = seedToString(seed)
saveMasterSeedToStorage(masterSeed)
return@fromCallable createFromWallet(wallet)
}
.doOnError { LogUtil.exception("Error while creating new wallet", it) }
}
private fun createFromWallet(wallet: Wallet): HDWallet {
val identityKey = deriveKeyFromIdentityWallet(wallet)
val paymentKeys = deriveKeysFromPaymentWallet(wallet)
val masterSeed = seedToString(wallet.keyChainSeed)
return HDWallet(walletPrefs, identityKey, paymentKeys, masterSeed)
}
@Throws(IllegalStateException::class)
private fun saveMasterSeedToStorage(masterSeed: String?) {
try {
val keyStoreHandler = KeyStoreHandler(context, ALIAS)
val encryptedMasterSeed = keyStoreHandler.encrypt(masterSeed)
saveMasterSeed(encryptedMasterSeed)
} catch (e: KeyStoreException) {
LogUtil.exception("Error while saving master seed from storage", e)
throw IllegalStateException(e)
}
}
private fun deriveKeyFromIdentityWallet(wallet: Wallet): ECKey {
try {
return deriveKeyFromWallet(wallet, 0, KeyChain.KeyPurpose.AUTHENTICATION)
} catch (ex: UnreadableWalletException) {
LogUtil.exception("Error while deriving keys from wallet", ex)
throw RuntimeException("Error deriving keys: $ex")
} catch (ex: IOException) {
LogUtil.exception("Error while deriving keys from wallet", ex)
throw RuntimeException("Error deriving keys: $ex")
}
}
@Throws(UnreadableWalletException::class, IOException::class)
private fun deriveKeyFromWallet(wallet: Wallet, iteration: Int, keyPurpose: KeyChain.KeyPurpose): ECKey {
var key: DeterministicKey? = null
for (i in 0..iteration) {
key = wallet.freshKey(keyPurpose)
}
if (key == null) {
throw IOException("Unable to derive key")
}
return ECKey.fromPrivate(key.privKey)
}
private fun deriveKeysFromPaymentWallet(wallet: Wallet): List<ECKey> {
try {
return deriveKeysFromWallet(wallet, 10, KeyChain.KeyPurpose.RECEIVE_FUNDS)
} catch (ex: UnreadableWalletException) {
LogUtil.exception("Error while deriving keys from wallet", ex)
throw RuntimeException("Error deriving keys: $ex")
} catch (ex: IOException) {
LogUtil.exception("Error while deriving keys from wallet", ex)
throw RuntimeException("Error deriving keys: $ex")
}
}
@Throws(IOException::class)
private fun deriveKeysFromWallet(
wallet: Wallet,
numberOfKeys: Int,
keyPurpose: KeyChain.KeyPurpose
): List<ECKey> {
val deterministicKeys = wallet.freshKeys(keyPurpose, numberOfKeys)
val ecKeys = ArrayList<ECKey>(numberOfKeys)
for (key in deterministicKeys) {
if (key == null) throw IOException("Unable to derive key")
ecKeys.add(ECKey.fromPrivate(key.privKey))
}
return ecKeys
}
private fun getNetworkParameters(): NetworkParameters {
return NetworkParameters.fromID(NetworkParameters.ID_MAINNET)
?: throw NullPointerException("Network parameters are null")
}
@Throws(IllegalStateException::class)
private fun seedToString(seed: DeterministicSeed): String {
val mnemonic = seed.mnemonicCode ?: throw IllegalStateException("Invalid mnemonic")
return mnemonic.joinToString(separator = " ")
}
private fun saveMasterSeed(masterSeed: String) = walletPrefs.setMasterSeed(masterSeed)
fun buildFromMasterSeed(masterSeed: String): Single<HDWallet> {
return Single.fromCallable {
try {
val seed = getSeed(masterSeed)
seed.check()
val wallet = constructFromSeed(seed)
saveMasterSeedToStorage(masterSeed)
return@fromCallable createFromWallet(wallet)
} catch (e: UnreadableWalletException) {
LogUtil.exception("Error while creating wallet from master seed", e)
throw InvalidMasterSeedException(e)
} catch (e: MnemonicException) {
LogUtil.exception("Error while creating wallet from master seed", e)
throw InvalidMasterSeedException(e)
}
}
}
fun getExistingWallet(): Single<HDWallet> {
return Single.fromCallable {
val masterSeed = readMasterSeedFromStorage()
?: throw InvalidMasterSeedException(Throwable("Master seed is null"))
val wallet = initFromMasterSeed(masterSeed)
return@fromCallable createFromWallet(wallet)
}
.doOnError { LogUtil.exception("Error while getting existing wallet", it) }
}
private fun initFromMasterSeed(masterSeed: String): Wallet {
try {
val seed = getSeed(masterSeed)
seed.check()
return constructFromSeed(seed)
} catch (e: UnreadableWalletException) {
LogUtil.exception("Error while initiating from from master seed", e)
throw RuntimeException("Unable to create wallet. Seed is invalid")
} catch (e: MnemonicException) {
LogUtil.exception("Error while initiating from from master seed", e)
throw RuntimeException("Unable to create wallet. Seed is invalid")
}
}
@Throws(UnreadableWalletException::class)
private fun getSeed(masterSeed: String): DeterministicSeed {
return DeterministicSeed(masterSeed, null, "", 0)
}
private fun constructFromSeed(seed: DeterministicSeed): Wallet {
val networkParameters = getNetworkParameters()
return Wallet(networkParameters, EthereumKeyChainGroup(networkParameters, seed))
}
private fun readMasterSeedFromStorage(): String? {
try {
val keyStoreHandler = KeyStoreHandler(context, ALIAS)
val encryptedMasterSeed = walletPrefs.getMasterSeed() ?: return null
return keyStoreHandler.decrypt(encryptedMasterSeed, { this.saveMasterSeed(it) })
} catch (e: KeyStoreException) {
LogUtil.exception("Error while reading master seed from storage", e)
throw IllegalStateException(e)
}
}
} | gpl-3.0 | 292363a79aaa05a354a0d01e7a1e9bc1 | 39.169014 | 109 | 0.669901 | 4.659586 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/board_type/AddBoardType.kt | 1 | 1435 | package de.westnordost.streetcomplete.quests.board_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.RARE
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.OUTDOORS
class AddBoardType : OsmFilterQuestType<BoardType>() {
override val elementFilter = """
nodes with information = board
and access !~ private|no
and (!board_type or board_type ~ yes|board)
"""
override val commitMessage = "Add board type"
override val wikiLink = "Key:board_type"
override val icon = R.drawable.ic_quest_board_type
override val isDeleteElementEnabled = true
override val questTypeAchievements = listOf(RARE, CITIZEN, OUTDOORS)
override fun getTitle(tags: Map<String, String>) = R.string.quest_board_type_title
override fun createForm() = AddBoardTypeForm()
override fun applyAnswerTo(answer: BoardType, changes: StringMapChangesBuilder) {
if(answer == BoardType.MAP) {
changes.modify("information", "map")
} else {
changes.addOrModify("board_type", answer.osmValue)
}
}
}
| gpl-3.0 | 5abd1668ee65f859dfdf183d8da9a0eb | 40 | 89 | 0.746341 | 4.512579 | false | false | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/utils/ViewUtils.kt | 1 | 5195 | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.utils
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.support.annotation.StringRes
import android.support.design.widget.Snackbar
import android.support.v4.content.ContextCompat
import android.support.v4.view.ViewCompat
import android.view.Gravity
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import org.mozilla.focus.R
import java.lang.ref.WeakReference
object ViewUtils {
private const val MENU_ITEM_ALPHA_ENABLED = 255
private const val MENU_ITEM_ALPHA_DISABLED = 130
/**
* Flag of imeOptions: used to request that the IME does not update any personalized data such
* as typing history and personalized language model based on what the user typed on this text
* editing object.
*/
const val IME_FLAG_NO_PERSONALIZED_LEARNING = 0x01000000
/**
* Runnable to show the keyboard for a specific view.
*/
@Suppress("ReturnCount")
private class ShowKeyboard internal constructor(view: View?) : Runnable {
companion object {
private const val INTERVAL_MS = 100
private const val MAX_TRIES = 10
}
private val viewReference: WeakReference<View?> = WeakReference(view)
private val handler: Handler = Handler(Looper.getMainLooper())
private var tries: Int = MAX_TRIES
override fun run() {
val myView = viewReference.get() ?: return
val activity: Activity? = myView.context?.asActivity() ?: return
val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager ?: return
when {
tries <= 0 -> return
!myView.isFocusable -> return
!myView.isFocusableInTouchMode -> return
!myView.requestFocus() -> {
post()
return
}
!imm.isActive(myView) -> {
post()
return
}
!imm.showSoftInput(myView, InputMethodManager.SHOW_IMPLICIT) -> {
post()
}
}
}
internal fun post() {
tries--
handler.postDelayed(this, INTERVAL_MS.toLong())
}
}
fun showKeyboard(view: View?) {
val showKeyboard = ShowKeyboard(view)
showKeyboard.post()
}
fun hideKeyboard(view: View?) {
val imm = view?.context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
/**
* Create a snackbar with Focus branding (See #193).
*/
fun showBrandedSnackbar(view: View?, @StringRes resId: Int, delayMillis: Int) {
val context = view!!.context
val snackbar = Snackbar.make(view, resId, Snackbar.LENGTH_LONG)
val snackbarView = snackbar.view
snackbarView.setBackgroundColor(ContextCompat.getColor(context, R.color.snackbarBackground))
val snackbarTextView = snackbarView.findViewById<View>(android.support.design.R.id.snackbar_text) as TextView
snackbarTextView.setTextColor(ContextCompat.getColor(context, R.color.snackbarTextColor))
snackbarTextView.gravity = Gravity.CENTER
snackbarTextView.textAlignment = View.TEXT_ALIGNMENT_CENTER
view.postDelayed({ snackbar.show() }, delayMillis.toLong())
}
fun getBrandedSnackbar(view: View, @StringRes resId: Int): Snackbar {
val context = view.context
val snackbar = Snackbar.make(view, resId, Snackbar.LENGTH_LONG)
val snackbarView = snackbar.view
snackbarView.setBackgroundColor(ContextCompat.getColor(context, R.color.snackbarBackground))
val snackbarTextView = snackbarView.findViewById<TextView>(android.support.design.R.id.snackbar_text)
snackbarTextView.setTextColor(ContextCompat.getColor(context, R.color.snackbarTextColor))
snackbar.setActionTextColor(ContextCompat.getColor(context, R.color.snackbarActionText))
return snackbar
}
fun isRTL(view: View): Boolean {
return ViewCompat.getLayoutDirection(view) == ViewCompat.LAYOUT_DIRECTION_RTL
}
/**
* Enable or disable a [MenuItem]
* If the menu item is disabled it can not be clicked and the menu icon is semi-transparent
*
* @param menuItem the menu item to enable/disable
* @param enabled true if the menu item should be enabled
*/
fun setMenuItemEnabled(menuItem: MenuItem, enabled: Boolean) {
menuItem.isEnabled = enabled
val icon = menuItem.icon
if (icon != null) {
icon.mutate().alpha = if (enabled) MENU_ITEM_ALPHA_ENABLED else MENU_ITEM_ALPHA_DISABLED
}
}
}
| mpl-2.0 | 9c504946b7a2de0a60b4d198c458429d | 36.919708 | 117 | 0.66025 | 4.630125 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/protobuf/commonTest/src/kotlinx/serialization/TestUtils.kt | 1 | 972 | /*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization
import kotlin.test.*
internal inline fun <reified T> assertSerializedToBinaryAndRestored(
original: T,
serializer: KSerializer<T>,
format: BinaryFormat,
printResult: Boolean = false,
hexResultToCheck: String? = null
) {
val bytes = format.encodeToByteArray(serializer, original)
val hexString = HexConverter.printHexBinary(bytes, lowerCase = true)
if (printResult) {
println("[Serialized form] $hexString")
}
if (hexResultToCheck != null) {
assertEquals(
hexResultToCheck.lowercase(),
hexString,
"Expected serialized binary to be equal in hex representation"
)
}
val restored = format.decodeFromByteArray(serializer, bytes)
if (printResult) println("[Restored form] $restored")
assertEquals(original, restored)
}
| apache-2.0 | f3a98476e61ba1d0ed5e36b7b9070dc4 | 30.354839 | 102 | 0.685185 | 4.606635 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/queries/StreamRequisitions.kt | 1 | 4120 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.queries
import com.google.cloud.spanner.Statement
import org.wfanet.measurement.gcloud.common.toGcloudTimestamp
import org.wfanet.measurement.gcloud.spanner.appendClause
import org.wfanet.measurement.gcloud.spanner.bind
import org.wfanet.measurement.internal.kingdom.StreamRequisitionsRequest
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.RequisitionReader
class StreamRequisitions(requestFilter: StreamRequisitionsRequest.Filter, limit: Int = 0) :
SimpleSpannerQuery<RequisitionReader.Result>() {
override val reader =
RequisitionReader().fillStatementBuilder {
appendWhereClause(requestFilter)
appendClause("ORDER BY ExternalDataProviderId ASC, ExternalRequisitionId ASC")
if (limit > 0) {
appendClause("LIMIT @$LIMIT")
bind(LIMIT to limit.toLong())
}
}
private fun Statement.Builder.appendWhereClause(filter: StreamRequisitionsRequest.Filter) {
val conjuncts = mutableListOf<String>()
if (filter.externalMeasurementConsumerId != 0L) {
conjuncts.add("ExternalMeasurementConsumerId = @$EXTERNAL_MEASUREMENT_CONSUMER_ID")
bind(EXTERNAL_MEASUREMENT_CONSUMER_ID to filter.externalMeasurementConsumerId)
}
if (filter.externalMeasurementId != 0L) {
conjuncts.add("ExternalMeasurementId = @$EXTERNAL_MEASUREMENT_ID")
bind(EXTERNAL_MEASUREMENT_ID to filter.externalMeasurementId)
}
if (filter.externalDataProviderId != 0L) {
conjuncts.add("ExternalDataProviderId = @$EXTERNAL_DATA_PROVIDER_ID")
bind(EXTERNAL_DATA_PROVIDER_ID to filter.externalDataProviderId)
}
if (filter.statesValueList.isNotEmpty()) {
conjuncts.add("Requisitions.State IN UNNEST(@$STATES)")
bind(STATES).toInt64Array(filter.statesValueList.map { it.toLong() })
}
if (filter.measurementStatesValueList.isNotEmpty()) {
conjuncts.add("Measurements.State IN UNNEST(@$MEASUREMENT_STATES)")
bind(MEASUREMENT_STATES).toInt64Array(filter.measurementStatesValueList.map { it.toLong() })
}
if (filter.hasUpdatedAfter()) {
conjuncts.add("Requisitions.UpdateTime > @$UPDATED_AFTER")
bind(UPDATED_AFTER to filter.updatedAfter.toGcloudTimestamp())
}
if (filter.externalRequisitionIdAfter != 0L && filter.externalDataProviderIdAfter != 0L) {
conjuncts.add(
"""
(ExternalDataProviderId > @$EXTERNAL_DATA_PROVIDER_ID_AFTER
OR (ExternalDataProviderId = @$EXTERNAL_DATA_PROVIDER_ID_AFTER
AND ExternalRequisitionId > @$EXTERNAL_REQUISITION_ID_AFTER))
"""
.trimIndent()
)
bind(EXTERNAL_DATA_PROVIDER_ID_AFTER).to(filter.externalDataProviderIdAfter)
bind(EXTERNAL_REQUISITION_ID_AFTER).to(filter.externalRequisitionIdAfter)
}
if (conjuncts.isEmpty()) {
return
}
appendClause("WHERE ")
append(conjuncts.joinToString(" AND "))
}
companion object {
const val LIMIT = "limit"
const val EXTERNAL_MEASUREMENT_CONSUMER_ID = "externalMeasurementConsumerId"
const val EXTERNAL_MEASUREMENT_ID = "externalMeasurementId"
const val EXTERNAL_DATA_PROVIDER_ID = "externalDataProviderId"
const val STATES = "states"
const val UPDATED_AFTER = "updatedAfter"
const val EXTERNAL_REQUISITION_ID_AFTER = "externalRequisitionIdAfter"
const val EXTERNAL_DATA_PROVIDER_ID_AFTER = "externalDataProviderIdAfter"
const val MEASUREMENT_STATES = "measurementStates"
}
}
| apache-2.0 | 99e3ee0d723dd61260a89c28cda1f090 | 41.040816 | 98 | 0.734951 | 4.238683 | false | false | false | false |
sabi0/intellij-community | platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.kt | 1 | 66367 | // 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.execution.impl
import com.intellij.execution.*
import com.intellij.execution.configuration.ConfigurationFactoryEx
import com.intellij.execution.configurations.*
import com.intellij.execution.impl.RunConfigurable.Companion.collectNodesRecursively
import com.intellij.execution.impl.RunConfigurableNodeKind.*
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.options.SettingsEditorConfigurable
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.LabeledComponent.create
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.Trinity
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.IdeFocusManager.getGlobalInstance
import com.intellij.ui.*
import com.intellij.ui.RowsDnDSupport.RefinedDropSupport.Position.*
import com.intellij.ui.components.labels.ActionLink
import com.intellij.ui.mac.TouchbarDataKeys
import com.intellij.ui.treeStructure.Tree
import com.intellij.util.ArrayUtilRt
import com.intellij.util.IconUtil
import com.intellij.util.PlatformIcons
import com.intellij.util.containers.TreeTraversal
import com.intellij.util.containers.nullize
import com.intellij.util.ui.*
import com.intellij.util.ui.tree.TreeUtil
import gnu.trove.THashMap
import gnu.trove.THashSet
import gnu.trove.TObjectIntHashMap
import net.miginfocom.swing.MigLayout
import java.awt.BorderLayout
import java.awt.FlowLayout
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.event.KeyEvent
import java.util.*
import java.util.function.ToIntFunction
import javax.swing.*
import javax.swing.event.DocumentEvent
import javax.swing.tree.*
private const val TEMPLATE_GROUP_NODE_NAME = "Templates"
private val TEMPLATES = object : Any() {
override fun toString() = TEMPLATE_GROUP_NODE_NAME
}
private const val INITIAL_VALUE_KEY = "initialValue"
private val LOG = logger<RunConfigurable>()
private fun getName(userObject: Any): String {
return when {
userObject is ConfigurationType -> userObject.displayName
userObject === TEMPLATES -> TEMPLATE_GROUP_NODE_NAME
userObject is ConfigurationFactory -> userObject.name
//Folder objects are strings
else -> if (userObject is SingleConfigurationConfigurable<*>) userObject.nameText else (userObject as? RunnerAndConfigurationSettingsImpl)?.name ?: userObject.toString()
}
}
open class RunConfigurable @JvmOverloads constructor(private val project: Project, var runDialog: RunDialogBase? = null) : Configurable, Disposable {
@Volatile private var isDisposed: Boolean = false
val root: DefaultMutableTreeNode = DefaultMutableTreeNode("Root")
val treeModel: MyTreeModel = MyTreeModel(root)
val tree: Tree = Tree(treeModel)
private val rightPanel = JPanel(BorderLayout())
private val splitter = JBSplitter("RunConfigurable.dividerProportion", 0.3f)
private var wholePanel: JPanel? = null
private var selectedConfigurable: Configurable? = null
private val recentsLimit = JTextField("5", 2)
private val confirmation = JCheckBox(ExecutionBundle.message("rerun.confirmation.checkbox"), true)
private val additionalSettings = ArrayList<Pair<UnnamedConfigurable, JComponent>>()
private val storedComponents = THashMap<ConfigurationFactory, Configurable>()
private var toolbarDecorator: ToolbarDecorator? = null
private var isFolderCreating: Boolean = false
private val toolbarAddAction = MyToolbarAddAction()
private val runDashboardTypesPanel = RunDashboardTypesPanel(project)
private var isModified = false
companion object {
fun collectNodesRecursively(parentNode: DefaultMutableTreeNode, nodes: MutableList<DefaultMutableTreeNode>, vararg allowed: RunConfigurableNodeKind) {
for (i in 0 until parentNode.childCount) {
val child = parentNode.getChildAt(i) as DefaultMutableTreeNode
if (ArrayUtilRt.find(allowed, getKind(child)) != -1) {
nodes.add(child)
}
collectNodesRecursively(child, nodes, *allowed)
}
}
fun getKind(node: DefaultMutableTreeNode?): RunConfigurableNodeKind {
if (node == null) {
return UNKNOWN
}
val userObject = node.userObject
return when (userObject) {
is SingleConfigurationConfigurable<*>, is RunnerAndConfigurationSettings -> {
val settings = getSettings(node) ?: return UNKNOWN
if (settings.isTemporary) TEMPORARY_CONFIGURATION else CONFIGURATION
}
is String -> FOLDER
else -> if (userObject is ConfigurationType) CONFIGURATION_TYPE else UNKNOWN
}
}
}
override fun getDisplayName(): String = ExecutionBundle.message("run.configurable.display.name")
private fun initTree() {
tree.isRootVisible = false
tree.showsRootHandles = true
UIUtil.setLineStyleAngled(tree)
TreeUtil.installActions(tree)
TreeSpeedSearch(tree) { o ->
val node = o.lastPathComponent as DefaultMutableTreeNode
val userObject = node.userObject
when (userObject) {
is RunnerAndConfigurationSettingsImpl -> return@TreeSpeedSearch userObject.name
is SingleConfigurationConfigurable<*> -> return@TreeSpeedSearch userObject.nameText
else -> if (userObject is ConfigurationType) {
return@TreeSpeedSearch userObject.displayName
}
else if (userObject is String) {
return@TreeSpeedSearch userObject
}
}
o.toString()
}
tree.cellRenderer = object : ColoredTreeCellRenderer() {
override fun customizeCellRenderer(tree: JTree, value: Any, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean) {
if (value is DefaultMutableTreeNode) {
val userObject = value.userObject
var shared: Boolean? = null
val name = getName(userObject)
if (userObject is ConfigurationType) {
append(name, if ((value.parent as DefaultMutableTreeNode).isRoot) SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES else SimpleTextAttributes.REGULAR_ATTRIBUTES)
icon = userObject.icon
}
else if (userObject === TEMPLATES) {
append(name, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES)
icon = AllIcons.General.Settings
}
else if (userObject is String) {//Folders
append(name, SimpleTextAttributes.REGULAR_ATTRIBUTES)
icon = AllIcons.Nodes.Folder
}
else if (userObject is ConfigurationFactory) {
append(name)
icon = userObject.icon
}
else {
var configuration: RunnerAndConfigurationSettings? = null
if (userObject is SingleConfigurationConfigurable<*>) {
val configurationSettings: RunnerAndConfigurationSettings = userObject.settings
configuration = configurationSettings
shared = userObject.isStoreProjectConfiguration
icon = ProgramRunnerUtil.getConfigurationIcon(configurationSettings, !userObject.isValid)
}
else if (userObject is RunnerAndConfigurationSettingsImpl) {
val settings = userObject as RunnerAndConfigurationSettings
shared = settings.isShared
icon = runManager.getConfigurationIcon(settings)
configuration = settings
}
if (configuration != null) {
append(name, if (configuration.isTemporary)
SimpleTextAttributes.GRAY_ATTRIBUTES
else
SimpleTextAttributes.REGULAR_ATTRIBUTES)
}
}
if (shared != null) {
val icon = icon
val layeredIcon = LayeredIcon(icon, if (shared) AllIcons.Nodes.Shared else EmptyIcon.ICON_16)
setIcon(layeredIcon)
iconTextGap = 0
}
else {
iconTextGap = 2
}
}
}
}
val manager = runManager
for (type in manager.configurationFactories) {
val configurations = manager.getConfigurationSettingsList(type).nullize() ?: continue
val typeNode = DefaultMutableTreeNode(type)
root.add(typeNode)
val folderMapping = THashMap<String, DefaultMutableTreeNode>()
for (configuration in configurations) {
val folder = configuration.folderName
if (folder == null) {
typeNode.add(DefaultMutableTreeNode(configuration))
}
else {
val node = folderMapping.getOrPut(folder) {
val node = DefaultMutableTreeNode(folder)
typeNode.insert(node, folderMapping.size)
node
}
node.add(DefaultMutableTreeNode(configuration))
}
}
}
// add templates
val templates = DefaultMutableTreeNode(TEMPLATES)
for (type in manager.configurationFactoriesWithoutUnknown) {
val configurationFactories = type.configurationFactories
val typeNode = DefaultMutableTreeNode(type)
templates.add(typeNode)
if (configurationFactories.size != 1) {
for (factory in configurationFactories) {
typeNode.add(DefaultMutableTreeNode(factory))
}
}
}
if (templates.childCount > 0) {
root.add(templates)
}
tree.addTreeSelectionListener {
val selectionPath = tree.selectionPath
if (selectionPath != null) {
val node = selectionPath.lastPathComponent as DefaultMutableTreeNode
val userObject = getSafeUserObject(node)
if (userObject is SingleConfigurationConfigurable<*>) {
@Suppress("UNCHECKED_CAST")
updateRightPanel(userObject as SingleConfigurationConfigurable<RunConfiguration>)
}
else if (userObject is String) {
showFolderField(node, userObject)
}
else {
if (userObject is ConfigurationType || userObject === TEMPLATES) {
val parent = node.parent as DefaultMutableTreeNode
if (parent.isRoot) {
drawPressAddButtonMessage(if (userObject === TEMPLATES) null else userObject as ConfigurationType)
}
else {
val factories = (userObject as ConfigurationType).configurationFactories
if (factories.size == 1) {
showTemplateConfigurable(factories[0])
}
else {
drawPressAddButtonMessage(userObject)
}
}
}
else if (userObject is ConfigurationFactory) {
showTemplateConfigurable(userObject)
}
}
}
updateDialog()
}
tree.registerKeyboardAction({ clickDefaultButton() }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED)
sortTopLevelBranches()
(tree.model as DefaultTreeModel).reload()
}
fun selectConfigurableOnShow(option: Boolean): RunConfigurable {
if (!option) return this
SwingUtilities.invokeLater {
if (isDisposed) return@invokeLater
tree.requestFocusInWindow()
val settings = runManager.selectedConfiguration
if (settings != null) {
if (selectConfiguration(settings.configuration)) {
return@invokeLater
}
}
else {
selectedConfigurable = null
}
//TreeUtil.selectInTree(defaults, true, myTree);
drawPressAddButtonMessage(null)
}
return this
}
private fun selectConfiguration(configuration: RunConfiguration): Boolean {
val enumeration = root.breadthFirstEnumeration()
while (enumeration.hasMoreElements()) {
val node = enumeration.nextElement() as DefaultMutableTreeNode
var userObject = node.userObject
if (userObject is SettingsEditorConfigurable<*>) {
userObject = userObject.settings
}
if (userObject is RunnerAndConfigurationSettingsImpl) {
val otherConfiguration = (userObject as RunnerAndConfigurationSettings).configuration
if (otherConfiguration.factory?.type?.id == configuration.factory?.type?.id && otherConfiguration.name == configuration.name) {
TreeUtil.selectInTree(node, true, tree)
return true
}
}
}
return false
}
private fun showTemplateConfigurable(factory: ConfigurationFactory) {
var configurable: Configurable? = storedComponents[factory]
if (configurable == null) {
configurable = TemplateConfigurable(runManager.getConfigurationTemplate(factory))
storedComponents.put(factory, configurable)
configurable.reset()
}
updateRightPanel(configurable)
}
private fun showFolderField(node: DefaultMutableTreeNode, folderName: String) {
rightPanel.removeAll()
val p = JPanel(MigLayout("ins ${toolbarDecorator!!.actionsPanel.height} 5 0 0, flowx"))
val textField = JTextField(folderName)
textField.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
node.userObject = textField.text
treeModel.reload(node)
}
})
textField.addActionListener { getGlobalInstance().doWhenFocusSettlesDown { getGlobalInstance().requestFocus(tree, true) } }
p.add(JLabel("Folder name:"), "gapright 5")
p.add(textField, "pushx, growx, wrap")
p.add(JLabel(ExecutionBundle.message("run.configuration.rename.folder.disclaimer")), "gaptop 5, spanx 2")
rightPanel.add(p)
rightPanel.revalidate()
rightPanel.repaint()
if (isFolderCreating) {
textField.selectAll()
getGlobalInstance().doWhenFocusSettlesDown { getGlobalInstance().requestFocus(textField, true) }
}
}
private fun getSafeUserObject(node: DefaultMutableTreeNode): Any {
val userObject = node.userObject
if (userObject is RunnerAndConfigurationSettingsImpl) {
val configurationConfigurable = SingleConfigurationConfigurable.editSettings<RunConfiguration>(userObject as RunnerAndConfigurationSettings, null)
installUpdateListeners(configurationConfigurable)
node.userObject = configurationConfigurable
return configurationConfigurable
}
return userObject
}
fun updateRightPanel(configurable: Configurable) {
rightPanel.removeAll()
selectedConfigurable = configurable
val configurableComponent = configurable.createComponent()
rightPanel.add(BorderLayout.CENTER, configurableComponent)
if (configurable is SingleConfigurationConfigurable<*>) {
rightPanel.add(configurable.validationComponent, BorderLayout.SOUTH)
ApplicationManager.getApplication().invokeLater { configurable.updateWarning() }
if (configurableComponent != null) {
val dataProvider = DataManager.getDataProvider(configurableComponent)
if (dataProvider != null) {
DataManager.registerDataProvider(rightPanel, dataProvider)
}
}
}
setupDialogBounds()
}
private fun sortTopLevelBranches() {
val expandedPaths = TreeUtil.collectExpandedPaths(tree)
TreeUtil.sortRecursively(root) { o1, o2 ->
val userObject1 = o1.userObject
val userObject2 = o2.userObject
when {
userObject1 is ConfigurationType && userObject2 is ConfigurationType -> (userObject1).displayName.compareTo(userObject2.displayName, true)
userObject1 === TEMPLATES && userObject2 is ConfigurationType -> 1
userObject2 === TEMPLATES && userObject1 is ConfigurationType -> - 1
else -> 0
}
}
TreeUtil.restoreExpandedPaths(tree, expandedPaths)
}
private fun update() {
updateDialog()
val selectionPath = tree.selectionPath
if (selectionPath != null) {
val node = selectionPath.lastPathComponent as DefaultMutableTreeNode
treeModel.reload(node)
}
}
private fun installUpdateListeners(info: SingleConfigurationConfigurable<RunConfiguration>) {
val changed = booleanArrayOf(false)
info.editor.addSettingsEditorListener { editor ->
update()
val configuration = info.configuration
if (configuration is LocatableConfiguration) {
if (configuration.isGeneratedName && !changed[0]) {
try {
val snapshot = editor.snapshot.configuration as LocatableConfiguration
val generatedName = snapshot.suggestedName()
if (generatedName != null && generatedName.isNotEmpty()) {
info.nameText = generatedName
changed[0] = false
}
}
catch (ignore: ConfigurationException) {
}
}
}
setupDialogBounds()
}
info.addNameListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
changed[0] = true
update()
}
})
info.addSharedListener {
changed[0] = true
update()
}
}
private fun drawPressAddButtonMessage(configurationType: ConfigurationType?) {
val messagePanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0))
messagePanel.border = JBUI.Borders.empty(30, 0, 0, 0)
messagePanel.add(JLabel("Click the"))
val addIcon = ActionLink("", IconUtil.getAddIcon(), toolbarAddAction)
addIcon.border = JBUI.Borders.empty(0, 3, 0, 3)
messagePanel.add(addIcon)
val configurationTypeDescription = when {
configurationType != null -> configurationType.configurationTypeDescription
else -> ExecutionBundle.message("run.configuration.default.type.description")
}
messagePanel.add(JLabel(ExecutionBundle.message("empty.run.configuration.panel.text.label3", configurationTypeDescription)))
rightPanel.removeAll()
val panel = JPanel(BorderLayout())
panel.add(messagePanel, BorderLayout.CENTER)
val scrollPane = ScrollPaneFactory.createScrollPane(panel, true)
rightPanel.add(scrollPane, BorderLayout.CENTER)
if (configurationType == null) {
val settingsPanel = JPanel(GridBagLayout())
val grid = GridBag().setDefaultAnchor(GridBagConstraints.NORTHWEST)
for (each in additionalSettings) {
settingsPanel.add(each.second, grid.nextLine().next())
}
settingsPanel.add(createSettingsPanel(), grid.nextLine().next())
val settingsWrapper = JPanel(BorderLayout())
settingsWrapper.add(settingsPanel, BorderLayout.WEST)
settingsWrapper.add(Box.createGlue(), BorderLayout.CENTER)
val wrapper = JPanel(BorderLayout())
wrapper.add(runDashboardTypesPanel, BorderLayout.CENTER)
runDashboardTypesPanel.addChangeListener(this::defaultsSettingsChanged)
runDashboardTypesPanel.border = JBUI.Borders.empty(0, 0, 20, 0)
wrapper.add(settingsWrapper, BorderLayout.SOUTH)
panel.add(wrapper, BorderLayout.SOUTH)
}
rightPanel.revalidate()
rightPanel.repaint()
}
private fun createLeftPanel(): JPanel {
initTree()
val removeAction = MyRemoveAction()
val moveUpAction = MyMoveAction(ExecutionBundle.message("move.up.action.name"), null, IconUtil.getMoveUpIcon(), -1)
val moveDownAction = MyMoveAction(ExecutionBundle.message("move.down.action.name"), null, IconUtil.getMoveDownIcon(), 1)
toolbarDecorator = ToolbarDecorator.createDecorator(tree).setAsUsualTopToolbar()
.setAddAction(toolbarAddAction).setAddActionName(ExecutionBundle.message("add.new.run.configuration.action2.name"))
.setRemoveAction(removeAction).setRemoveActionUpdater(removeAction)
.setRemoveActionName(ExecutionBundle.message("remove.run.configuration.action.name"))
.setMoveUpAction(moveUpAction).setMoveUpActionName(ExecutionBundle.message("move.up.action.name")).setMoveUpActionUpdater(
moveUpAction)
.setMoveDownAction(moveDownAction).setMoveDownActionName(ExecutionBundle.message("move.down.action.name")).setMoveDownActionUpdater(
moveDownAction)
.addExtraAction(AnActionButton.fromAction(MyCopyAction()))
.addExtraAction(AnActionButton.fromAction(MySaveAction()))
.addExtraAction(AnActionButton.fromAction(MyEditTemplatesAction()))
.addExtraAction(AnActionButton.fromAction(MyCreateFolderAction()))
.addExtraAction(AnActionButton.fromAction(MySortFolderAction()))
.setMinimumSize(JBDimension(200, 200))
.setButtonComparator(ExecutionBundle.message("add.new.run.configuration.action2.name"),
ExecutionBundle.message("remove.run.configuration.action.name"),
ExecutionBundle.message("copy.configuration.action.name"),
ExecutionBundle.message("action.name.save.configuration"),
ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
ExecutionBundle.message("move.up.action.name"),
ExecutionBundle.message("move.down.action.name"),
ExecutionBundle.message("run.configuration.create.folder.text")
).setForcedDnD()
return toolbarDecorator!!.createPanel()
}
private fun defaultsSettingsChanged() {
isModified = recentsLimit.text != recentsLimit.getClientProperty(INITIAL_VALUE_KEY) ||
confirmation.isSelected != confirmation.getClientProperty(INITIAL_VALUE_KEY) ||
runDashboardTypesPanel.isModified()
}
private fun createSettingsPanel(): JPanel {
val bottomPanel = JPanel(GridBagLayout())
val g = GridBag()
bottomPanel.add(confirmation, g.nextLine().coverLine())
bottomPanel.add(create(recentsLimit, ExecutionBundle.message("temporary.configurations.limit"), BorderLayout.WEST),
g.nextLine().insets(JBUI.insets(10, 0, 0, 0)).anchor(GridBagConstraints.WEST))
recentsLimit.document.addDocumentListener(object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) {
defaultsSettingsChanged()
}
})
confirmation.addChangeListener {
defaultsSettingsChanged()
}
return bottomPanel
}
private val selectedConfigurationType: ConfigurationType?
get() {
val configurationTypeNode = selectedConfigurationTypeNode
return if (configurationTypeNode != null) configurationTypeNode.userObject as ConfigurationType else null
}
override fun createComponent(): JComponent? {
for (each in Extensions.getExtensions(RunConfigurationsSettings.EXTENSION_POINT, project)) {
val configurable = each.createConfigurable()
additionalSettings.add(Pair.create(configurable, configurable.createComponent()))
}
val touchbarActions = DefaultActionGroup(toolbarAddAction)
TouchbarDataKeys.putActionDescriptor(touchbarActions).setShowText(true).isCombineWithDlgButtons = true
wholePanel = JPanel(BorderLayout())
DataManager.registerDataProvider(wholePanel!!) { dataId ->
when (dataId) {
RunConfigurationSelector.KEY.name -> RunConfigurationSelector { configuration -> selectConfiguration(configuration) }
TouchbarDataKeys.ACTIONS_KEY.name -> touchbarActions
else -> null
}
}
splitter.firstComponent = createLeftPanel()
splitter.setHonorComponentsMinimumSize(true)
splitter.secondComponent = rightPanel
wholePanel!!.add(splitter, BorderLayout.CENTER)
updateDialog()
val d = wholePanel!!.preferredSize
d.width = Math.max(d.width, 800)
d.height = Math.max(d.height, 600)
wholePanel!!.preferredSize = d
return wholePanel
}
override fun reset() {
val manager = runManager
val config = manager.config
recentsLimit.text = Integer.toString(config.recentsLimit)
recentsLimit.putClientProperty(INITIAL_VALUE_KEY, recentsLimit.text)
confirmation.isSelected = config.isRestartRequiresConfirmation
confirmation.putClientProperty(INITIAL_VALUE_KEY, confirmation.isSelected)
runDashboardTypesPanel.reset()
for (each in additionalSettings) {
each.first.reset()
}
isModified = false
}
@Throws(ConfigurationException::class)
override fun apply() {
val manager = runManager
manager.fireBeginUpdate()
try {
val settingsToOrder = TObjectIntHashMap<RunnerAndConfigurationSettings>()
var order = 0
val toDeleteSettings = THashSet(manager.allSettings)
val selectedSettings = selectedSettings
for (i in 0 until root.childCount) {
val node = root.getChildAt(i) as DefaultMutableTreeNode
val userObject = node.userObject
if (userObject is ConfigurationType) {
for (bean in applyByType(node, userObject, selectedSettings)) {
settingsToOrder.put(bean.settings, order++)
toDeleteSettings.remove(bean.settings)
}
}
}
manager.removeConfigurations(toDeleteSettings)
val recentLimit = Math.max(RunManagerConfig.MIN_RECENT_LIMIT, StringUtil.parseInt(recentsLimit.text, 0))
if (manager.config.recentsLimit != recentLimit) {
manager.config.recentsLimit = recentLimit
manager.checkRecentsLimit()
}
recentsLimit.text = "" + recentLimit
recentsLimit.putClientProperty(INITIAL_VALUE_KEY, recentsLimit.text)
manager.config.isRestartRequiresConfirmation = confirmation.isSelected
confirmation.putClientProperty(INITIAL_VALUE_KEY, confirmation.isSelected)
runDashboardTypesPanel.apply()
for (configurable in storedComponents.values) {
if (configurable.isModified) {
configurable.apply()
}
}
additionalSettings.forEach { it.first.apply() }
manager.setOrder(Comparator.comparingInt(ToIntFunction<RunnerAndConfigurationSettings> { settingsToOrder.get(it) }))
}
finally {
manager.fireEndUpdate()
}
updateActiveConfigurationFromSelected()
isModified = false
tree.repaint()
}
fun updateActiveConfigurationFromSelected() {
val selectedConfigurable = selectedConfigurable
if (selectedConfigurable is SingleConfigurationConfigurable<*>) {
runManager.selectedConfiguration = selectedConfigurable.settings
}
}
@Throws(ConfigurationException::class)
private fun applyByType(typeNode: DefaultMutableTreeNode,
type: ConfigurationType,
selectedSettings: RunnerAndConfigurationSettings?): List<RunConfigurationBean> {
var indexToMove = -1
val configurationBeans = ArrayList<RunConfigurationBean>()
val names = THashSet<String>()
val configurationNodes = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION)
for (node in configurationNodes) {
val userObject = node.userObject
var configurationBean: RunConfigurationBean? = null
var settings: RunnerAndConfigurationSettings? = null
if (userObject is SingleConfigurationConfigurable<*>) {
settings = userObject.settings as RunnerAndConfigurationSettings
applyConfiguration(typeNode, userObject)
configurationBean = RunConfigurationBean(userObject)
}
else if (userObject is RunnerAndConfigurationSettingsImpl) {
settings = userObject
configurationBean = RunConfigurationBean(settings)
}
if (configurationBean != null) {
val configurable = configurationBean.configurable
val nameText = if (configurable != null) configurable.nameText else configurationBean.settings.name
if (!names.add(nameText)) {
TreeUtil.selectNode(tree, node)
throw ConfigurationException(type.displayName + " with name \'" + nameText + "\' already exists")
}
configurationBeans.add(configurationBean)
if (settings === selectedSettings) {
indexToMove = configurationBeans.size - 1
}
}
}
val folderNodes = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(typeNode, folderNodes, FOLDER)
names.clear()
for (node in folderNodes) {
val folderName = node.userObject as String
if (folderName.isEmpty()) {
TreeUtil.selectNode(tree, node)
throw ConfigurationException("Folder name shouldn't be empty")
}
if (!names.add(folderName)) {
TreeUtil.selectNode(tree, node)
throw ConfigurationException("Folders name \'$folderName\' is duplicated")
}
}
// try to apply all
for (bean in configurationBeans) {
applyConfiguration(typeNode, bean.configurable)
}
// just saved as 'stable' configuration shouldn't stay between temporary ones (here we order model to save)
var shift = 0
if (selectedSettings != null && selectedSettings.type === type) {
shift = adjustOrder()
}
if (shift != 0 && indexToMove != -1) {
configurationBeans.add(indexToMove - shift, configurationBeans.removeAt(indexToMove))
}
return configurationBeans
}
private fun getConfigurationTypeNode(type: ConfigurationType): DefaultMutableTreeNode? {
for (i in 0 until root.childCount) {
val node = root.getChildAt(i) as DefaultMutableTreeNode
if (node.userObject === type) {
return node
}
}
return null
}
@Throws(ConfigurationException::class)
private fun applyConfiguration(typeNode: DefaultMutableTreeNode, configurable: SingleConfigurationConfigurable<*>?) {
try {
if (configurable != null && configurable.isModified) {
configurable.apply()
}
}
catch (e: ConfigurationException) {
for (i in 0 until typeNode.childCount) {
val node = typeNode.getChildAt(i) as DefaultMutableTreeNode
if (configurable == node.userObject) {
TreeUtil.selectNode(tree, node)
break
}
}
throw e
}
}
override fun isModified(): Boolean {
if (isModified) {
return true
}
val runManager = runManager
val allSettings = runManager.allSettings
var currentSettingCount = 0
for (i in 0 until root.childCount) {
val typeNode = root.getChildAt(i) as DefaultMutableTreeNode
val configurationType = typeNode.userObject as? ConfigurationType ?: continue
val configurationNodes = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION)
val allTypeSettings = allSettings.filter { it.type == configurationType }
if (allTypeSettings.size != configurationNodes.size) {
return true
}
var currentTypeSettingsCount = 0
for (configurationNode in configurationNodes) {
val userObject = configurationNode.userObject
val settings: RunnerAndConfigurationSettings
if (userObject is SingleConfigurationConfigurable<*>) {
if (userObject.isModified) {
return true
}
settings = userObject.settings as RunnerAndConfigurationSettings
}
else if (userObject is RunnerAndConfigurationSettings) {
settings = userObject
}
else {
continue
}
currentSettingCount++
val index = currentTypeSettingsCount++
// we compare by instance, equals is not implemented and in any case object modification is checked by other logic
// we compare by index among current types settings because indexes among all configurations may differ
// since temporary configurations are stored in the end
if (allTypeSettings.size <= index || allTypeSettings.get(index) !== settings) {
return true
}
}
}
return allSettings.size != currentSettingCount || storedComponents.values.any { it.isModified } || additionalSettings.any { it.first.isModified }
}
override fun disposeUIResources() {
Disposer.dispose(this)
}
override fun dispose() {
isDisposed = true
storedComponents.values.forEach { it.disposeUIResources() }
storedComponents.clear()
additionalSettings.forEach { it.first.disposeUIResources() }
TreeUtil.treeNodeTraverser(root)
.traverse(TreeTraversal.PRE_ORDER_DFS)
.processEach { node ->
((node as? DefaultMutableTreeNode)?.userObject as? SingleConfigurationConfigurable<*>)?.disposeUIResources()
true
}
rightPanel.removeAll()
splitter.dispose()
}
private fun updateDialog() {
val runDialog = runDialog
val executor = runDialog?.executor ?: return
val buffer = StringBuilder()
buffer.append(executor.id)
val configuration = selectedConfiguration
if (configuration != null) {
buffer.append(" - ")
buffer.append(configuration.nameText)
}
runDialog.setOKActionEnabled(canRunConfiguration(configuration, executor))
runDialog.setTitle(buffer.toString())
}
private fun setupDialogBounds() {
SwingUtilities.invokeLater { UIUtil.setupEnclosingDialogBounds(wholePanel!!) }
}
private val selectedConfiguration: SingleConfigurationConfigurable<RunConfiguration>?
get() {
val selectionPath = tree.selectionPath
if (selectionPath != null) {
val treeNode = selectionPath.lastPathComponent as DefaultMutableTreeNode
val userObject = treeNode.userObject
if (userObject is SingleConfigurationConfigurable<*>) {
@Suppress("UNCHECKED_CAST")
return userObject as SingleConfigurationConfigurable<RunConfiguration>
}
}
return null
}
open val runManager: RunManagerImpl
get() = RunManagerImpl.getInstanceImpl(project)
override fun getHelpTopic(): String? {
return selectedConfigurationType?.helpTopic ?: "reference.dialogs.rundebug"
}
private fun clickDefaultButton() {
runDialog?.clickDefaultButton()
}
private val selectedConfigurationTypeNode: DefaultMutableTreeNode?
get() {
val selectionPath = tree.selectionPath
var node: DefaultMutableTreeNode? = if (selectionPath != null) selectionPath.lastPathComponent as DefaultMutableTreeNode else null
while (node != null) {
val userObject = node.userObject
if (userObject is ConfigurationType) {
return node
}
node = node.parent as? DefaultMutableTreeNode
}
return null
}
private fun getNode(row: Int) = tree.getPathForRow(row).lastPathComponent as DefaultMutableTreeNode
fun getAvailableDropPosition(direction: Int): Trinity<Int, Int, RowsDnDSupport.RefinedDropSupport.Position>? {
val rows = tree.selectionRows
if (rows == null || rows.size != 1) {
return null
}
val oldIndex = rows[0]
var newIndex = oldIndex + direction
if (!getKind(tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode).supportsDnD()) {
return null
}
while (newIndex > 0 && newIndex < tree.rowCount) {
val targetPath = tree.getPathForRow(newIndex)
val allowInto = getKind(targetPath.lastPathComponent as DefaultMutableTreeNode) == FOLDER && !tree.isExpanded(targetPath)
val position = when {
allowInto && treeModel.isDropInto(tree, oldIndex, newIndex) -> INTO
direction > 0 -> BELOW
else -> ABOVE
}
val oldNode = getNode(oldIndex)
val newNode = getNode(newIndex)
if (oldNode.parent !== newNode.parent && getKind(newNode) != FOLDER) {
var copy = position
if (position == BELOW) {
copy = ABOVE
}
else if (position == ABOVE) {
copy = BELOW
}
if (treeModel.canDrop(oldIndex, newIndex, copy)) {
return Trinity.create(oldIndex, newIndex, copy)
}
}
if (treeModel.canDrop(oldIndex, newIndex, position)) {
return Trinity.create(oldIndex, newIndex, position)
}
when {
position == BELOW && newIndex < tree.rowCount - 1 && treeModel.canDrop(oldIndex, newIndex + 1, ABOVE) -> return Trinity.create(oldIndex, newIndex + 1, ABOVE)
position == ABOVE && newIndex > 1 && treeModel.canDrop(oldIndex, newIndex - 1, BELOW) -> return Trinity.create(oldIndex, newIndex - 1, BELOW)
position == BELOW && treeModel.canDrop(oldIndex, newIndex, ABOVE) -> return Trinity.create(oldIndex, newIndex, ABOVE)
position == ABOVE && treeModel.canDrop(oldIndex, newIndex, BELOW) -> return Trinity.create(oldIndex, newIndex, BELOW)
else -> newIndex += direction
}
}
return null
}
private fun createNewConfiguration(settings: RunnerAndConfigurationSettings,
node: DefaultMutableTreeNode?,
selectedNode: DefaultMutableTreeNode?): SingleConfigurationConfigurable<RunConfiguration> {
val configurationConfigurable = SingleConfigurationConfigurable.editSettings<RunConfiguration>(settings, null)
installUpdateListeners(configurationConfigurable)
val nodeToAdd = DefaultMutableTreeNode(configurationConfigurable)
treeModel.insertNodeInto(nodeToAdd, node!!, if (selectedNode != null) node.getIndex(selectedNode) + 1 else node.childCount)
TreeUtil.selectNode(tree, nodeToAdd)
return configurationConfigurable
}
fun createNewConfiguration(factory: ConfigurationFactory): SingleConfigurationConfigurable<RunConfiguration> {
var node: DefaultMutableTreeNode
var selectedNode: DefaultMutableTreeNode? = null
val selectionPath = tree.selectionPath
if (selectionPath != null) {
selectedNode = selectionPath.lastPathComponent as? DefaultMutableTreeNode
}
var typeNode = getConfigurationTypeNode(factory.type)
if (typeNode == null) {
typeNode = DefaultMutableTreeNode(factory.type)
root.add(typeNode)
sortTopLevelBranches()
(tree.model as DefaultTreeModel).reload()
}
node = typeNode
if (selectedNode != null && typeNode.isNodeDescendant(selectedNode)) {
node = selectedNode
if (getKind(node).isConfiguration) {
node = node.parent as DefaultMutableTreeNode
}
}
val settings = runManager.createConfiguration(createUniqueName(typeNode, null, CONFIGURATION, TEMPORARY_CONFIGURATION), factory)
@Suppress("UNCHECKED_CAST")
(factory as? ConfigurationFactoryEx<RunConfiguration>)?.onNewConfigurationCreated(settings.configuration)
return createNewConfiguration(settings, node, selectedNode)
}
private inner class MyToolbarAddAction : AnAction(ExecutionBundle.message("add.new.run.configuration.action2.name"),
ExecutionBundle.message("add.new.run.configuration.action2.name"),
IconUtil.getAddIcon()), AnActionButtonRunnable {
init {
registerCustomShortcutSet(CommonShortcuts.INSERT, tree)
}
override fun actionPerformed(e: AnActionEvent) {
showAddPopup(true)
}
override fun run(button: AnActionButton) {
showAddPopup(true)
}
private fun showAddPopup(showApplicableTypesOnly: Boolean) {
val allTypes = runManager.configurationFactoriesWithoutUnknown
val configurationTypes: MutableList<ConfigurationType?> = getTypesToShow(showApplicableTypesOnly, allTypes).toMutableList()
configurationTypes.sortWith(kotlin.Comparator { type1, type2 -> type1!!.displayName.compareTo(type2!!.displayName, ignoreCase = true) })
val hiddenCount = allTypes.size - configurationTypes.size
if (hiddenCount > 0) {
configurationTypes.add(null)
}
val popup = NewRunConfigurationPopup.createAddPopup(configurationTypes,
ExecutionBundle.message("show.irrelevant.configurations.action.name",
hiddenCount),
{ factory -> createNewConfiguration(factory) }, selectedConfigurationType,
{ showAddPopup(false) }, true)
//new TreeSpeedSearch(myTree);
popup.showUnderneathOf(toolbarDecorator!!.actionsPanel)
}
private fun getTypesToShow(showApplicableTypesOnly: Boolean, allTypes: List<ConfigurationType>): List<ConfigurationType> {
if (showApplicableTypesOnly) {
val applicableTypes = allTypes.filter { it.configurationFactories.any { it.isApplicable(project) } }
if (applicableTypes.size < (allTypes.size - 3)) {
return applicableTypes
}
}
return allTypes
}
}
private inner class MyRemoveAction : AnAction(ExecutionBundle.message("remove.run.configuration.action.name"),
ExecutionBundle.message("remove.run.configuration.action.name"),
IconUtil.getRemoveIcon()), AnActionButtonRunnable, AnActionButtonUpdater {
init {
registerCustomShortcutSet(CommonShortcuts.getDelete(), tree)
}
override fun actionPerformed(e: AnActionEvent) {
doRemove()
}
override fun run(button: AnActionButton) {
doRemove()
}
private fun doRemove() {
val selections = tree.selectionPaths
tree.clearSelection()
var nodeIndexToSelect = -1
var parentToSelect: DefaultMutableTreeNode? = null
val changedParents = HashSet<DefaultMutableTreeNode>()
var wasRootChanged = false
for (each in selections!!) {
val node = each.lastPathComponent as DefaultMutableTreeNode
val parent = node.parent as DefaultMutableTreeNode
val kind = getKind(node)
if (!kind.isConfiguration && kind != FOLDER)
continue
if (node.userObject is SingleConfigurationConfigurable<*>) {
(node.userObject as SingleConfigurationConfigurable<*>).disposeUIResources()
}
nodeIndexToSelect = parent.getIndex(node)
parentToSelect = parent
treeModel.removeNodeFromParent(node)
changedParents.add(parent)
if (kind == FOLDER) {
val children = ArrayList<DefaultMutableTreeNode>()
for (i in 0 until node.childCount) {
val child = node.getChildAt(i) as DefaultMutableTreeNode
val userObject = getSafeUserObject(child)
if (userObject is SingleConfigurationConfigurable<*>) {
userObject.folderName = null
}
children.add(0, child)
}
var confIndex = 0
for (i in 0 until parent.childCount) {
if (getKind(parent.getChildAt(i) as DefaultMutableTreeNode).isConfiguration) {
confIndex = i
break
}
}
for (child in children) {
if (getKind(child) == CONFIGURATION)
treeModel.insertNodeInto(child, parent, confIndex)
}
confIndex = parent.childCount
for (i in 0 until parent.childCount) {
if (getKind(parent.getChildAt(i) as DefaultMutableTreeNode) == TEMPORARY_CONFIGURATION) {
confIndex = i
break
}
}
for (child in children) {
if (getKind(child) == TEMPORARY_CONFIGURATION) {
treeModel.insertNodeInto(child, parent, confIndex)
}
}
}
if (parent.childCount == 0 && parent.userObject is ConfigurationType) {
changedParents.remove(parent)
wasRootChanged = true
nodeIndexToSelect = root.getIndex(parent)
nodeIndexToSelect = Math.max(0, nodeIndexToSelect - 1)
parentToSelect = root
parent.removeFromParent()
}
}
if (wasRootChanged) {
(tree.model as DefaultTreeModel).reload()
}
else {
for (each in changedParents) {
treeModel.reload(each)
tree.expandPath(TreePath(each))
}
}
selectedConfigurable = null
if (root.childCount == 0) {
drawPressAddButtonMessage(null)
}
else {
if (parentToSelect!!.childCount > 0) {
val nodeToSelect = if (nodeIndexToSelect < parentToSelect.childCount) {
parentToSelect.getChildAt(nodeIndexToSelect)
}
else {
parentToSelect.getChildAt(nodeIndexToSelect - 1)
}
TreeUtil.selectInTree(nodeToSelect as DefaultMutableTreeNode, true, tree)
}
}
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = isEnabled(e)
}
override fun isEnabled(e: AnActionEvent): Boolean {
var enabled = false
val selections = tree.selectionPaths
if (selections != null) {
for (each in selections) {
val kind = getKind(each.lastPathComponent as DefaultMutableTreeNode)
if (kind.isConfiguration || kind == FOLDER) {
enabled = true
break
}
}
}
return enabled
}
}
private inner class MyCopyAction : AnAction(ExecutionBundle.message("copy.configuration.action.name"),
ExecutionBundle.message("copy.configuration.action.name"), PlatformIcons.COPY_ICON) {
init {
val action = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_DUPLICATE)
registerCustomShortcutSet(action.shortcutSet, tree)
}
override fun actionPerformed(e: AnActionEvent) {
val configuration = selectedConfiguration
LOG.assertTrue(configuration != null)
try {
val typeNode = selectedConfigurationTypeNode!!
val settings = configuration!!.snapshot
val copyName = createUniqueName(typeNode, configuration.nameText, CONFIGURATION, TEMPORARY_CONFIGURATION)
settings!!.name = copyName
val factory = settings.factory
@Suppress("UNCHECKED_CAST")
(factory as? ConfigurationFactoryEx<RunConfiguration>)?.onConfigurationCopied(settings.configuration)
val configurable = createNewConfiguration(settings, typeNode, selectedNode)
IdeFocusManager.getInstance(project).requestFocus(configurable.nameTextField, true)
configurable.nameTextField.selectionStart = 0
configurable.nameTextField.selectionEnd = copyName.length
}
catch (e1: ConfigurationException) {
Messages.showErrorDialog(toolbarDecorator!!.actionsPanel, e1.message, e1.title)
}
}
override fun update(e: AnActionEvent) {
val configuration = selectedConfiguration
e.presentation.isEnabled = configuration != null && configuration.configuration !is UnknownRunConfiguration
}
}
private inner class MySaveAction : AnAction(ExecutionBundle.message("action.name.save.configuration"), null,
AllIcons.Actions.Menu_saveall) {
override fun actionPerformed(e: AnActionEvent) {
val configurationConfigurable = selectedConfiguration
LOG.assertTrue(configurationConfigurable != null)
val originalConfiguration = configurationConfigurable!!.settings
if (originalConfiguration.isTemporary) {
//todo Don't make 'stable' real configurations here but keep the set 'they want to be stable' until global 'Apply' action
runManager.makeStable(originalConfiguration)
adjustOrder()
}
tree.repaint()
}
override fun update(e: AnActionEvent) {
val configuration = selectedConfiguration
val presentation = e.presentation
val enabled: Boolean
if (configuration == null) {
enabled = false
}
else {
val settings = configuration.settings
enabled = settings != null && settings.isTemporary
}
presentation.isEnabledAndVisible = enabled
}
}
/**
* Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order nodes in JTree only)
* @return shift (positive) for move configuration "up" to other stable configurations. Zero means "there is nothing to change"
*/
private fun adjustOrder(): Int {
val selectionPath = tree.selectionPath ?: return 0
val treeNode = selectionPath.lastPathComponent as DefaultMutableTreeNode
val selectedSettings = getSettings(treeNode)
if (selectedSettings == null || selectedSettings.isTemporary) {
return 0
}
val parent = treeNode.parent as MutableTreeNode
val initialPosition = parent.getIndex(treeNode)
var position = initialPosition
var node: DefaultMutableTreeNode? = treeNode.previousSibling
while (node != null) {
val settings = getSettings(node)
if (settings != null && settings.isTemporary) {
position--
}
else {
break
}
node = node.previousSibling
}
for (i in 0 until initialPosition - position) {
TreeUtil.moveSelectedRow(tree, -1)
}
return initialPosition - position
}
private inner class MyMoveAction(text: String, description: String?, icon: Icon, private val direction: Int) :
AnAction(text, description, icon), AnActionButtonRunnable, AnActionButtonUpdater {
override fun actionPerformed(e: AnActionEvent) {
doMove()
}
private fun doMove() {
getAvailableDropPosition(direction)?.let {
treeModel.drop(it.first, it.second, it.third)
}
}
override fun run(button: AnActionButton) {
doMove()
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabled = isEnabled(e)
}
override fun isEnabled(e: AnActionEvent) = getAvailableDropPosition(direction) != null
}
private inner class MyEditTemplatesAction : AnAction(ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
ExecutionBundle.message("run.configuration.edit.default.configuration.settings.description"),
AllIcons.General.Settings) {
override fun actionPerformed(e: AnActionEvent) {
var templates = TreeUtil.findNodeWithObject(TEMPLATES, tree.model, root) ?: return
selectedConfigurationType?.let {
templates = TreeUtil.findNodeWithObject(it, tree.model, templates) ?: return
}
val templatesNode = templates as DefaultMutableTreeNode? ?: return
val path = TreeUtil.getPath(root, templatesNode)
tree.expandPath(path)
TreeUtil.selectInTree(templatesNode, true, tree)
tree.scrollPathToVisible(path)
}
override fun update(e: AnActionEvent) {
var isEnabled = TreeUtil.findNodeWithObject(TEMPLATES, tree.model, root) != null
val path = tree.selectionPath
if (path != null) {
var o = path.lastPathComponent
if (o is DefaultMutableTreeNode && o.userObject == TEMPLATES) {
isEnabled = false
}
o = path.parentPath.lastPathComponent
if (o is DefaultMutableTreeNode && o.userObject == TEMPLATES) {
isEnabled = false
}
}
e.presentation.isEnabled = isEnabled
}
}
private inner class MyCreateFolderAction : AnAction(ExecutionBundle.message("run.configuration.create.folder.text"),
ExecutionBundle.message("run.configuration.create.folder.description"),
AllIcons.Actions.NewFolder) {
override fun actionPerformed(e: AnActionEvent) {
val type = selectedConfigurationType ?: return
val selectedNodes = selectedNodes
val typeNode = getConfigurationTypeNode(type) ?: return
val folderName = createUniqueName(typeNode, "New Folder", FOLDER)
val folders = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(getConfigurationTypeNode(type)!!, folders, FOLDER)
val folderNode = DefaultMutableTreeNode(folderName)
treeModel.insertNodeInto(folderNode, typeNode, folders.size)
isFolderCreating = true
try {
for (node in selectedNodes) {
val folderRow = tree.getRowForPath(TreePath(folderNode.path))
val rowForPath = tree.getRowForPath(TreePath(node.path))
if (getKind(node).isConfiguration && treeModel.canDrop(rowForPath, folderRow, INTO)) {
treeModel.drop(rowForPath, folderRow, INTO)
}
}
tree.selectionPath = TreePath(folderNode.path)
}
finally {
isFolderCreating = false
}
}
override fun update(e: AnActionEvent) {
var isEnabled = false
var toMove = false
val selectedNodes = selectedNodes
var selectedType: ConfigurationType? = null
for (node in selectedNodes) {
val type = getType(node)
if (selectedType == null) {
selectedType = type
}
else {
if (type != selectedType) {
isEnabled = false
break
}
}
val kind = getKind(node)
if (kind.isConfiguration || kind == CONFIGURATION_TYPE && node.parent === root || kind == FOLDER) {
isEnabled = true
}
if (kind.isConfiguration) {
toMove = true
}
}
e.presentation.text = ExecutionBundle.message("run.configuration.create.folder.description${if (toMove) ".move" else ""}")
e.presentation.isEnabled = isEnabled
}
}
private inner class MySortFolderAction : AnAction(ExecutionBundle.message("run.configuration.sort.folder.text"),
ExecutionBundle.message("run.configuration.sort.folder.description"),
AllIcons.ObjectBrowser.Sorted), Comparator<DefaultMutableTreeNode> {
override fun compare(node1: DefaultMutableTreeNode, node2: DefaultMutableTreeNode): Int {
val kind1 = getKind(node1)
val kind2 = getKind(node2)
if (kind1 == FOLDER) {
return if (kind2 == FOLDER) node1.parent.getIndex(node1) - node2.parent.getIndex(node2) else -1
}
if (kind2 == FOLDER) {
return 1
}
val name1 = getName(node1.userObject)
val name2 = getName(node2.userObject)
return when (kind1) {
TEMPORARY_CONFIGURATION -> if (kind2 == TEMPORARY_CONFIGURATION) name1.compareTo(name2) else 1
else -> if (kind2 == TEMPORARY_CONFIGURATION) -1 else name1.compareTo(name2)
}
}
override fun actionPerformed(e: AnActionEvent) {
val selectedNodes = selectedNodes
val foldersToSort = ArrayList<DefaultMutableTreeNode>()
for (node in selectedNodes) {
val kind = getKind(node)
if (kind == CONFIGURATION_TYPE || kind == FOLDER) {
foldersToSort.add(node)
}
}
for (folderNode in foldersToSort) {
val children = ArrayList<DefaultMutableTreeNode>()
for (i in 0 until folderNode.childCount) {
children.add(folderNode.getChildAt(i) as DefaultMutableTreeNode)
}
children.sortWith(this)
for (child in children) {
folderNode.add(child)
}
treeModel.nodeStructureChanged(folderNode)
}
}
override fun update(e: AnActionEvent) {
val selectedNodes = selectedNodes
for (node in selectedNodes) {
val kind = getKind(node)
if (kind == CONFIGURATION_TYPE || kind == FOLDER) {
e.presentation.isEnabled = true
return
}
}
e.presentation.isEnabled = false
}
}
private val selectedNodes: Array<DefaultMutableTreeNode>
get() = tree.getSelectedNodes(DefaultMutableTreeNode::class.java, null)
private val selectedNode: DefaultMutableTreeNode?
get() = tree.getSelectedNodes(DefaultMutableTreeNode::class.java, null).firstOrNull()
private val selectedSettings: RunnerAndConfigurationSettings?
get() {
val selectionPath = tree.selectionPath ?: return null
return getSettings(selectionPath.lastPathComponent as DefaultMutableTreeNode)
}
inner class MyTreeModel(root: TreeNode) : DefaultTreeModel(root), EditableModel, RowsDnDSupport.RefinedDropSupport {
override fun addRow() {}
override fun removeRow(index: Int) {}
override fun exchangeRows(oldIndex: Int, newIndex: Int) {
//Do nothing, use drop() instead
}
//Legacy, use canDrop() instead
override fun canExchangeRows(oldIndex: Int, newIndex: Int): Boolean = false
override fun canDrop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position): Boolean {
if (tree.rowCount <= oldIndex || tree.rowCount <= newIndex || oldIndex < 0 || newIndex < 0) {
return false
}
val oldNode = tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode
val newNode = tree.getPathForRow(newIndex).lastPathComponent as DefaultMutableTreeNode
val oldParent = oldNode.parent as DefaultMutableTreeNode
val newParent = newNode.parent as DefaultMutableTreeNode
val oldKind = getKind(oldNode)
val newKind = getKind(newNode)
val oldType = getType(oldNode)
val newType = getType(newNode)
if (oldParent === newParent) {
if (oldNode.previousSibling === newNode && position == BELOW) {
return false
}
if (oldNode.nextSibling === newNode && position == ABOVE) {
return false
}
}
when {
oldType == null -> return false
oldType !== newType -> {
val typeNode = getConfigurationTypeNode(oldType)
if (getKind(oldParent) == FOLDER && typeNode != null && typeNode.nextSibling === newNode && position == ABOVE) {
return true
}
return getKind(oldParent) == CONFIGURATION_TYPE &&
oldKind == FOLDER &&
typeNode != null &&
typeNode.nextSibling === newNode &&
position == ABOVE &&
oldParent.lastChild !== oldNode &&
getKind(oldParent.lastChild as DefaultMutableTreeNode) == FOLDER
}
newParent === oldNode || oldParent === newNode -> return false
oldKind == FOLDER && newKind != FOLDER -> return newKind.isConfiguration &&
position == ABOVE &&
getKind(newParent) == CONFIGURATION_TYPE &&
newIndex > 1 &&
getKind(tree.getPathForRow(newIndex - 1).parentPath.lastPathComponent as DefaultMutableTreeNode) == FOLDER
!oldKind.supportsDnD() || !newKind.supportsDnD() -> return false
oldKind.isConfiguration && newKind == FOLDER && position == ABOVE -> return false
oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == ABOVE -> return false
oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == BELOW -> return false
oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == ABOVE -> return newNode.previousSibling == null ||
getKind(newNode.previousSibling) == CONFIGURATION ||
getKind(newNode.previousSibling) == FOLDER
oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == BELOW -> return newNode.nextSibling == null || getKind(newNode.nextSibling) == TEMPORARY_CONFIGURATION
oldParent === newParent -> //Same parent
if (oldKind.isConfiguration && newKind.isConfiguration) {
return oldKind == newKind//both are temporary or saved
}
else if (oldKind == FOLDER) {
return !tree.isExpanded(newIndex) || position == ABOVE
}
}
return true
}
override fun isDropInto(component: JComponent, oldIndex: Int, newIndex: Int): Boolean {
val oldPath = tree.getPathForRow(oldIndex)
val newPath = tree.getPathForRow(newIndex)
if (oldPath == null || newPath == null) {
return false
}
val oldNode = oldPath.lastPathComponent as DefaultMutableTreeNode
val newNode = newPath.lastPathComponent as DefaultMutableTreeNode
return getKind(oldNode).isConfiguration && getKind(newNode) == FOLDER
}
override fun drop(oldIndex: Int, newIndex: Int, position: RowsDnDSupport.RefinedDropSupport.Position) {
val oldNode = tree.getPathForRow(oldIndex).lastPathComponent as DefaultMutableTreeNode
val newNode = tree.getPathForRow(newIndex).lastPathComponent as DefaultMutableTreeNode
var newParent = newNode.parent as DefaultMutableTreeNode
val oldKind = getKind(oldNode)
val wasExpanded = tree.isExpanded(TreePath(oldNode.path))
if (isDropInto(tree, oldIndex, newIndex)) { //Drop in folder
removeNodeFromParent(oldNode)
var index = newNode.childCount
if (oldKind.isConfiguration) {
var middleIndex = newNode.childCount
for (i in 0 until newNode.childCount) {
if (getKind(newNode.getChildAt(i) as DefaultMutableTreeNode) == TEMPORARY_CONFIGURATION) {
middleIndex = i//index of first temporary configuration in target folder
break
}
}
if (position != INTO) {
if (oldIndex < newIndex) {
index = if (oldKind == CONFIGURATION) 0 else middleIndex
}
else {
index = if (oldKind == CONFIGURATION) middleIndex else newNode.childCount
}
}
else {
index = if (oldKind == TEMPORARY_CONFIGURATION) newNode.childCount else middleIndex
}
}
insertNodeInto(oldNode, newNode, index)
tree.expandPath(TreePath(newNode.path))
}
else {
val type = getType(oldNode)!!
removeNodeFromParent(oldNode)
var index: Int
if (type !== getType(newNode)) {
val typeNode = getConfigurationTypeNode(type)!!
newParent = typeNode
index = newParent.childCount
}
else {
index = newParent.getIndex(newNode)
if (position == BELOW) {
index++
}
}
insertNodeInto(oldNode, newParent, index)
}
val treePath = TreePath(oldNode.path)
tree.selectionPath = treePath
if (wasExpanded) {
tree.expandPath(treePath)
}
}
override fun insertNodeInto(newChild: MutableTreeNode, parent: MutableTreeNode, index: Int) {
super.insertNodeInto(newChild, parent, index)
if (!getKind(newChild as DefaultMutableTreeNode).isConfiguration) {
return
}
val userObject = getSafeUserObject(newChild)
val newFolderName = if (getKind(parent as DefaultMutableTreeNode) == FOLDER) parent.userObject as String else null
if (userObject is SingleConfigurationConfigurable<*>) {
userObject.folderName = newFolderName
}
}
override fun reload(node: TreeNode?) {
super.reload(node)
val userObject = (node as DefaultMutableTreeNode).userObject
if (userObject is String) {
for (i in 0 until node.childCount) {
val safeUserObject = getSafeUserObject(node.getChildAt(i) as DefaultMutableTreeNode)
if (safeUserObject is SingleConfigurationConfigurable<*>) {
safeUserObject.folderName = userObject
}
}
}
}
private fun getType(treeNode: DefaultMutableTreeNode?): ConfigurationType? {
val userObject = treeNode?.userObject ?: return null
return when (userObject) {
is SingleConfigurationConfigurable<*> -> userObject.configuration.type
is RunnerAndConfigurationSettings -> userObject.type
is ConfigurationType -> userObject
else -> if (treeNode.parent is DefaultMutableTreeNode) getType(treeNode.parent as DefaultMutableTreeNode) else null
}
}
}
}
private fun canRunConfiguration(configuration: SingleConfigurationConfigurable<RunConfiguration>?, executor: Executor): Boolean {
return try {
configuration != null && RunManagerImpl.canRunConfiguration(configuration.snapshot!!, executor)
}
catch (e: ConfigurationException) {
false
}
}
private fun createUniqueName(typeNode: DefaultMutableTreeNode, baseName: String?, vararg kinds: RunConfigurableNodeKind): String {
val str = baseName ?: ExecutionBundle.message("run.configuration.unnamed.name.prefix")
val configurationNodes = ArrayList<DefaultMutableTreeNode>()
collectNodesRecursively(typeNode, configurationNodes, *kinds)
val currentNames = ArrayList<String>()
for (node in configurationNodes) {
val userObject = node.userObject
when (userObject) {
is SingleConfigurationConfigurable<*> -> currentNames.add(userObject.nameText)
is RunnerAndConfigurationSettingsImpl -> currentNames.add((userObject as RunnerAndConfigurationSettings).name)
is String -> currentNames.add(userObject)
}
}
return RunManager.suggestUniqueName(str, currentNames)
}
private fun getType(_node: DefaultMutableTreeNode?): ConfigurationType? {
var node = _node
while (node != null) {
(node.userObject as? ConfigurationType)?.let {
return it
}
node = node.parent as? DefaultMutableTreeNode
}
return null
}
private fun getSettings(treeNode: DefaultMutableTreeNode?): RunnerAndConfigurationSettings? {
if (treeNode == null) {
return null
}
val settings: RunnerAndConfigurationSettings? = null
return when {
treeNode.userObject is SingleConfigurationConfigurable<*> -> (treeNode.userObject as SingleConfigurationConfigurable<*>).settings as RunnerAndConfigurationSettings
treeNode.userObject is RunnerAndConfigurationSettings -> treeNode.userObject as RunnerAndConfigurationSettings
else -> settings
}
}
| apache-2.0 | d5dae51e00f1cd686503ea7d5ff5a1cf | 39.125151 | 188 | 0.673392 | 5.48669 | false | true | false | false |
lettuce-io/lettuce-core | src/main/kotlin/io/lettuce/core/api/coroutines/RedisSortedSetCoroutinesCommandsImpl.kt | 1 | 11954 | /*
* Copyright 2020-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 io.lettuce.core.api.coroutines
import io.lettuce.core.*
import io.lettuce.core.api.reactive.RedisSortedSetReactiveCommands
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.reactive.asFlow
import kotlinx.coroutines.reactive.awaitFirstOrNull
/**
* Coroutine executed commands (based on reactive commands) for Sorted Sets.
*
* @param <K> Key type.
* @param <V> Value type.
* @author Mikhael Sokolov
* @since 6.0
*
* @generated by io.lettuce.apigenerator.CreateKotlinCoroutinesReactiveImplementation
*/
@ExperimentalLettuceCoroutinesApi
internal class RedisSortedSetCoroutinesCommandsImpl<K : Any, V : Any>(internal val ops: RedisSortedSetReactiveCommands<K, V>) : RedisSortedSetCoroutinesCommands<K, V> {
override suspend fun bzpopmin(
timeout: Long,
vararg keys: K
): KeyValue<K, ScoredValue<V>>? = ops.bzpopmin(timeout, *keys).awaitFirstOrNull()
override suspend fun bzpopmin(
timeout: Double,
vararg keys: K
): KeyValue<K, ScoredValue<V>>? = ops.bzpopmin(timeout, *keys).awaitFirstOrNull()
override suspend fun bzpopmax(
timeout: Long,
vararg keys: K
): KeyValue<K, ScoredValue<V>>? = ops.bzpopmax(timeout, *keys).awaitFirstOrNull()
override suspend fun bzpopmax(
timeout: Double,
vararg keys: K
): KeyValue<K, ScoredValue<V>>? = ops.bzpopmax(timeout, *keys).awaitFirstOrNull()
override suspend fun zadd(key: K, score: Double, member: V): Long? =
ops.zadd(key, score, member).awaitFirstOrNull()
override suspend fun zadd(key: K, vararg scoresAndValues: Any): Long? =
ops.zadd(key, *scoresAndValues).awaitFirstOrNull()
override suspend fun zadd(key: K, vararg scoredValues: ScoredValue<V>): Long? =
ops.zadd(key, *scoredValues).awaitFirstOrNull()
override suspend fun zadd(
key: K,
zAddArgs: ZAddArgs,
score: Double,
member: V
): Long? = ops.zadd(key, zAddArgs, score, member).awaitFirstOrNull()
override suspend fun zadd(
key: K,
zAddArgs: ZAddArgs,
vararg scoresAndValues: Any
): Long? = ops.zadd(key, zAddArgs, *scoresAndValues).awaitFirstOrNull()
override suspend fun zadd(key: K, zAddArgs: ZAddArgs, vararg scoredValues: ScoredValue<V>): Long? = ops.zadd(key, zAddArgs, *scoredValues).awaitFirstOrNull()
override suspend fun zaddincr(key: K, score: Double, member: V): Double? = ops.zaddincr(key, score, member).awaitFirstOrNull()
override suspend fun zaddincr(key: K, zAddArgs: ZAddArgs, score: Double, member: V): Double? = ops.zaddincr(key, zAddArgs, score, member).awaitFirstOrNull()
override suspend fun zcard(key: K): Long? = ops.zcard(key).awaitFirstOrNull()
override suspend fun zcount(key: K, range: Range<out Number>): Long? = ops.zcount(key, range).awaitFirstOrNull()
override fun zdiff(vararg keys: K): Flow<V> = ops.zdiff(*keys).asFlow()
override suspend fun zdiffstore(destKey: K, vararg srcKeys: K): Long? = ops.zdiffstore(destKey, *srcKeys).awaitFirstOrNull()
override fun zdiffWithScores(vararg keys: K): Flow<ScoredValue<V>> = ops.zdiffWithScores(*keys).asFlow()
override suspend fun zincrby(key: K, amount: Double, member: V): Double? = ops.zincrby(key, amount, member).awaitFirstOrNull()
override fun zinter(vararg keys: K): Flow<V> = ops.zinter(*keys).asFlow()
override fun zinter(aggregateArgs: ZAggregateArgs, vararg keys: K): Flow<V> = ops.zinter(aggregateArgs, *keys).asFlow()
override suspend fun zintercard(vararg keys: K): Long? = ops.zintercard(*keys).awaitFirstOrNull()
override suspend fun zintercard(limit: Long, vararg keys: K): Long? =
ops.zintercard(limit, *keys).awaitFirstOrNull()
override fun zinterWithScores(vararg keys: K): Flow<ScoredValue<V>> = ops.zinterWithScores(*keys).asFlow()
override fun zinterWithScores(aggregateArgs: ZAggregateArgs, vararg keys: K): Flow<ScoredValue<V>> = ops.zinterWithScores(aggregateArgs, *keys).asFlow()
override suspend fun zinterstore(destination: K, vararg keys: K): Long? = ops.zinterstore(destination, *keys).awaitFirstOrNull()
override suspend fun zinterstore(destination: K, storeArgs: ZStoreArgs, vararg keys: K): Long? = ops.zinterstore(destination, storeArgs, *keys).awaitFirstOrNull()
override suspend fun zlexcount(key: K, range: Range<out V>): Long? = ops.zlexcount(key, range).awaitFirstOrNull()
override suspend fun zmscore(key: K, vararg members: V): List<Double?> = ops.zmscore(key, *members).awaitFirstOrNull().orEmpty()
override suspend fun zpopmin(key: K): ScoredValue<V>? =
ops.zpopmin(key).awaitFirstOrNull()
override fun zpopmin(key: K, count: Long): Flow<ScoredValue<V>> =
ops.zpopmin(key, count).asFlow()
override suspend fun zpopmax(key: K): ScoredValue<V>? =
ops.zpopmax(key).awaitFirstOrNull()
override fun zpopmax(key: K, count: Long): Flow<ScoredValue<V>> =
ops.zpopmax(key, count).asFlow()
override suspend fun zrandmember(key: K): V? = ops.zrandmember(key).awaitFirstOrNull()
override suspend fun zrandmember(key: K, count: Long): List<V> =
ops.zrandmember(key, count).asFlow().toList()
override suspend fun zrandmemberWithScores(key: K): ScoredValue<V>? =
ops.zrandmemberWithScores(key).awaitFirstOrNull()
override suspend fun zrandmemberWithScores(
key: K,
count: Long
): List<ScoredValue<V>> = ops.zrandmemberWithScores(key, count).asFlow().toList()
override fun zrange(key: K, start: Long, stop: Long): Flow<V> =
ops.zrange(key, start, stop).asFlow()
override fun zrangeWithScores(key: K, start: Long, stop: Long): Flow<ScoredValue<V>> =
ops.zrangeWithScores(key, start, stop).asFlow()
override fun zrangebylex(key: K, range: Range<out V>): Flow<V> =
ops.zrangebylex(key, range).asFlow()
override fun zrangebylex(key: K, range: Range<out V>, limit: Limit): Flow<V> =
ops.zrangebylex(key, range, limit).asFlow()
override fun zrangebyscore(key: K, range: Range<out Number>): Flow<V> =
ops.zrangebyscore(key, range).asFlow()
override fun zrangebyscore(key: K, range: Range<out Number>, limit: Limit): Flow<V> =
ops.zrangebyscore(key, range, limit).asFlow()
override fun zrangebyscoreWithScores(
key: K,
range: Range<out Number>
): Flow<ScoredValue<V>> = ops.zrangebyscoreWithScores(key, range).asFlow()
override fun zrangebyscoreWithScores(
key: K,
range: Range<out Number>,
limit: Limit
): Flow<ScoredValue<V>> = ops.zrangebyscoreWithScores(key, range, limit).asFlow()
override suspend fun zrangestore(dstKey: K, srcKey: K, range: Range<Long>): Long? =
ops.zrangestore(dstKey, srcKey, range).awaitFirstOrNull()
override suspend fun zrangestorebylex(
dstKey: K,
srcKey: K,
range: Range<out V>,
limit: Limit
): Long? = ops.zrangestorebylex(dstKey, srcKey, range, limit).awaitFirstOrNull()
override suspend fun zrangestorebyscore(
dstKey: K,
srcKey: K,
range: Range<out Number>,
limit: Limit
): Long? = ops.zrangestorebyscore(dstKey, srcKey, range, limit).awaitFirstOrNull()
override suspend fun zrank(key: K, member: V): Long? =
ops.zrank(key, member).awaitFirstOrNull()
override suspend fun zrem(key: K, vararg members: V): Long? =
ops.zrem(key, *members).awaitFirstOrNull()
override suspend fun zremrangebylex(key: K, range: Range<out V>): Long? =
ops.zremrangebylex(key, range).awaitFirstOrNull()
override suspend fun zremrangebyrank(key: K, start: Long, stop: Long): Long? = ops.zremrangebyrank(key, start, stop).awaitFirstOrNull()
override suspend fun zremrangebyscore(key: K, range: Range<out Number>): Long? = ops.zremrangebyscore(key, range).awaitFirstOrNull()
override fun zrevrange(key: K, start: Long, stop: Long): Flow<V> = ops.zrevrange(key, start, stop).asFlow()
override fun zrevrangeWithScores(key: K, start: Long, stop: Long): Flow<ScoredValue<V>> = ops.zrevrangeWithScores(key, start, stop).asFlow()
override fun zrevrangebylex(key: K, range: Range<out V>): Flow<V> = ops.zrevrangebylex(key, range).asFlow()
override fun zrevrangebylex(key: K, range: Range<out V>, limit: Limit): Flow<V> =
ops.zrevrangebylex(key, range, limit).asFlow()
override fun zrevrangebyscore(key: K, range: Range<out Number>): Flow<V> =
ops.zrevrangebyscore(key, range).asFlow()
override fun zrevrangebyscore(
key: K,
range: Range<out Number>,
limit: Limit
): Flow<V> = ops.zrevrangebyscore(key, range, limit).asFlow()
override fun zrevrangebyscoreWithScores(
key: K,
range: Range<out Number>
): Flow<ScoredValue<V>> = ops.zrevrangebyscoreWithScores(key, range).asFlow()
override fun zrevrangebyscoreWithScores(
key: K,
range: Range<out Number>,
limit: Limit
): Flow<ScoredValue<V>> = ops.zrevrangebyscoreWithScores(key, range, limit).asFlow()
override suspend fun zrevrangestore(dstKey: K, srcKey: K, range: Range<Long>): Long? =
ops.zrevrangestore(dstKey, srcKey, range).awaitFirstOrNull()
override suspend fun zrevrangestorebylex(
dstKey: K,
srcKey: K,
range: Range<out V>,
limit: Limit
): Long? = ops.zrevrangestorebylex(dstKey, srcKey, range, limit).awaitFirstOrNull()
override suspend fun zrevrangestorebyscore(
dstKey: K,
srcKey: K,
range: Range<out Number>,
limit: Limit
): Long? = ops.zrevrangestorebyscore(dstKey, srcKey, range, limit).awaitFirstOrNull()
override suspend fun zrevrank(key: K, member: V): Long? =
ops.zrevrank(key, member).awaitFirstOrNull()
override suspend fun zscan(key: K): ScoredValueScanCursor<V>? =
ops.zscan(key).awaitFirstOrNull()
override suspend fun zscan(key: K, scanArgs: ScanArgs): ScoredValueScanCursor<V>? =
ops.zscan(key, scanArgs).awaitFirstOrNull()
override suspend fun zscan(key: K, scanCursor: ScanCursor, scanArgs: ScanArgs): ScoredValueScanCursor<V>? = ops.zscan(key, scanCursor, scanArgs).awaitFirstOrNull()
override suspend fun zscan(key: K, scanCursor: ScanCursor): ScoredValueScanCursor<V>? = ops.zscan(key, scanCursor).awaitFirstOrNull()
override suspend fun zscore(key: K, member: V): Double? = ops.zscore(key, member).awaitFirstOrNull()
override fun zunion(vararg keys: K): Flow<V> = ops.zunion(*keys).asFlow()
override fun zunion(aggregateArgs: ZAggregateArgs, vararg keys: K): Flow<V> = ops.zunion(aggregateArgs, *keys).asFlow()
override fun zunionWithScores(vararg keys: K): Flow<ScoredValue<V>> = ops.zunionWithScores(*keys).asFlow()
override fun zunionWithScores(aggregateArgs: ZAggregateArgs, vararg keys: K): Flow<ScoredValue<V>> = ops.zunionWithScores(aggregateArgs, *keys).asFlow()
override suspend fun zunionstore(destination: K, vararg keys: K): Long? = ops.zunionstore(destination, *keys).awaitFirstOrNull()
override suspend fun zunionstore(destination: K, storeArgs: ZStoreArgs, vararg keys: K): Long? = ops.zunionstore(destination, storeArgs, *keys).awaitFirstOrNull()
}
| apache-2.0 | 9c3269af262f1fa9066184677039e686 | 42 | 168 | 0.695834 | 3.884953 | false | false | false | false |
danwime/eazyajax | core/src/me/danwi/ezajax/container/Loader.kt | 1 | 883 | package me.danwi.ezajax.container
import me.danwi.ezajax.annotation.Ajax
/**
* 加载器
* Created by demon on 2017/2/14.
*/
val container: MutableMap<String, AjaxModule> = mutableMapOf()
/**
* 加载所有的ezajax类模块
*/
fun loadAllClasses() {
val classNames = scanAllClasses()
//找出所有的Ajax模块类
val ajaxClasses = classNames.filter {
try {
val clazz = Class.forName(it)
val annotaion = clazz.getAnnotation(Ajax::class.java)
annotaion != null
} catch (e: Exception) {
false
}
}.map { Class.forName(it) }
//解析ajax类,并把他们添加了容器里面
ajaxClasses.forEach {
val module = AjaxModule(it)
container[module.name] = module
println("Found Ajax Module: ${it.simpleName}")
}
println("All Ajax Modules Loaded")
}
| apache-2.0 | bcb3924ac67cd4a11eb86ccae1800ee8 | 19.948718 | 65 | 0.610771 | 3.615044 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/reporter/TableDataFile.kt | 1 | 2127 | // 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 com.google.common.collect.Table
import org.droidmate.exploration.modelFeatures.misc.plot
import org.droidmate.misc.withExtension
import java.nio.file.Files
import java.nio.file.Path
class TableDataFile<R, C, V>(val table: Table<R, C, V>,
private val file: Path) {
fun write() {
Files.write(file, tableString.toByteArray())
}
fun writeOutPlot(resourceDir: Path) {
plot(file.toAbsolutePath().toString(), plotFile.toAbsolutePath().toString(), resourceDir)
}
private val tableString: String by lazy {
val headerRowString = table.columnKeySet().joinToString(separator = "\t")
val dataRowsStrings: List<String> = table.rowMap().map {
val rowValues = it.value.values
rowValues.joinToString(separator = "\t")
}
val tableString = headerRowString + System.lineSeparator() + dataRowsStrings.joinToString(separator = System.lineSeparator())
tableString
}
private val plotFile = file.withExtension("pdf")
override fun toString(): String {
return file.toString()
}
}
| gpl-3.0 | 34e6cebe88bb57b0b75dbdf38c6285a9 | 31.723077 | 127 | 0.737189 | 3.924354 | false | false | false | false |
m4gr3d/GAST | core/src/plugins/java/org/godotengine/plugin/gast/plugins/webview/GastWebviewPlugin.kt | 1 | 3247 | package org.godotengine.plugin.gast.plugins.webview
import android.app.Activity
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.ViewGroup
import org.godotengine.godot.Godot
import org.godotengine.godot.plugin.UsedByGodot
import org.godotengine.plugin.gast.GastNode
import org.godotengine.plugin.gast.R
import org.godotengine.plugin.gast.extension.GastExtension
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
/**
* * GAST-Webview plugin
*
* This plugin is used to display a webview in the Godot engine.
* It uses Android built-in webview API for its webview implementation.
*/
class GastWebviewPlugin(godot: Godot) : GastExtension(godot) {
companion object {
private val TAG = GastWebviewPlugin::class.java.simpleName
private const val INVALID_WEBVIEW_ID = -1
}
private val webPanelsCounter = AtomicInteger(0)
private val webPanelsById = ConcurrentHashMap<Int, WebPanel>()
private lateinit var webPanelsContainerView: ViewGroup
override fun getPluginName() = "gast-webview"
override fun onMainCreate(activity: Activity): View? {
super.onMainCreate(activity)
webPanelsContainerView =
activity.layoutInflater.inflate(R.layout.web_panels_container, null) as ViewGroup
return webPanelsContainerView
}
override fun onMainResume() {
super.onMainResume()
for (webPanel in webPanelsById.values) {
webPanel.onResume()
}
}
override fun onMainPause() {
super.onMainPause()
for (webPanel in webPanelsById.values) {
webPanel.onPause()
}
}
override fun onMainDestroy() {
super.onMainDestroy()
for (webPanel in webPanelsById.values) {
webPanel.onDestroy()
}
webPanelsById.clear()
}
@Suppress("unused")
@UsedByGodot
private fun initializeWebView(parentNodePath: String): Int {
if (TextUtils.isEmpty(parentNodePath)) {
Log.e(TAG, "Invalid parent node path value: $parentNodePath")
return INVALID_WEBVIEW_ID
}
val parentActivity = activity ?: return INVALID_WEBVIEW_ID
// Create a gast node in the given parent node.
val gastNode = GastNode(gastManager, parentNodePath)
// Generate the web panel
val webPanel = WebPanel(parentActivity, webPanelsContainerView, gastManager, gastNode)
val webPanelId = webPanelsCounter.getAndIncrement()
webPanelsById[webPanelId] = webPanel
return webPanelId
}
@Suppress("unused")
@UsedByGodot
private fun loadUrl(webViewId: Int, url: String) {
val webPanel = webPanelsById[webViewId] ?: return
webPanel.loadUrl(url)
}
@Suppress("unused")
@UsedByGodot
private fun setWebViewSize(webViewId: Int, width: Float, height: Float) {
val webPanel = webPanelsById[webViewId] ?: return
webPanel.setSize(width, height)
}
@Suppress("unused")
@UsedByGodot
private fun shutdownWebView(webViewId: Int) {
val webPanel = webPanelsById.remove(webViewId) ?: return
webPanel.onDestroy()
}
}
| mit | 210dc1f8a1a14cb6d372aa629cccb3a8 | 29.064815 | 94 | 0.68648 | 4.2893 | false | false | false | false |
Light-Team/ModPE-IDE-Source | features/feature-themes/src/main/kotlin/com/brackeys/ui/feature/themes/fragments/ThemesFragment.kt | 1 | 6623 | /*
* Copyright 2021 Brackeys IDE contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.brackeys.ui.feature.themes.fragments
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.widget.AppCompatSpinner
import androidx.appcompat.widget.SearchView
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.afollestad.materialdialogs.utils.MDUtil.getStringArray
import com.brackeys.ui.domain.model.themes.ThemeModel
import com.brackeys.ui.feature.themes.R
import com.brackeys.ui.feature.themes.adapters.ThemeAdapter
import com.brackeys.ui.feature.themes.databinding.FragmentThemesBinding
import com.brackeys.ui.feature.themes.utils.GridSpacingItemDecoration
import com.brackeys.ui.feature.themes.utils.readAssetFileText
import com.brackeys.ui.feature.themes.viewmodel.ThemesViewModel
import com.brackeys.ui.utils.extensions.debounce
import com.brackeys.ui.utils.extensions.hasExternalStorageAccess
import com.brackeys.ui.utils.extensions.showToast
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ThemesFragment : Fragment(R.layout.fragment_themes) {
private val viewModel: ThemesViewModel by viewModels()
private lateinit var binding: FragmentThemesBinding
private lateinit var navController: NavController
private lateinit var adapter: ThemeAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentThemesBinding.bind(view)
navController = findNavController()
observeViewModel()
val gridLayoutManager = binding.recyclerView.layoutManager as GridLayoutManager
val gridSpacingDecoration = GridSpacingItemDecoration(8, gridLayoutManager.spanCount)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.addItemDecoration(gridSpacingDecoration)
binding.recyclerView.adapter = ThemeAdapter(object : ThemeAdapter.Actions {
override fun selectTheme(themeModel: ThemeModel) = viewModel.selectTheme(themeModel)
override fun exportTheme(themeModel: ThemeModel) {
if (requireContext().hasExternalStorageAccess()) {
viewModel.exportTheme(themeModel)
} else {
context?.showToast(R.string.message_access_required)
}
}
override fun editTheme(themeModel: ThemeModel) {
val bundle = bundleOf(NewThemeFragment.NAV_THEME_UUID to themeModel.uuid)
navController.navigate(R.id.newThemeFragment, bundle)
}
override fun removeTheme(themeModel: ThemeModel) = viewModel.removeTheme(themeModel)
override fun showInfo(themeModel: ThemeModel) {
context?.showToast(text = themeModel.description)
}
}).also {
adapter = it
}
binding.actionAdd.setOnClickListener {
val bundle = bundleOf(NewThemeFragment.NAV_THEME_UUID to null)
navController.navigate(R.id.newThemeFragment, bundle)
}
viewModel.fetchThemes()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.menu_themes, menu)
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem?.actionView as? SearchView
if (viewModel.searchQuery.isNotEmpty()) {
searchItem.expandActionView()
searchView?.setQuery(viewModel.searchQuery, false)
}
val spinnerItem = menu.findItem(R.id.spinner)
val spinnerView = spinnerItem?.actionView as? AppCompatSpinner
spinnerView?.adapter = ArrayAdapter.createFromResource(
requireContext(),
R.array.language_names,
android.R.layout.simple_spinner_dropdown_item
)
spinnerView?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) = Unit
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val path = requireContext().getStringArray(R.array.language_paths)[position]
val extension = requireContext().getStringArray(R.array.language_extensions)[position]
adapter.codeSnippet = requireContext().readAssetFileText(path) to extension
}
}
searchView?.debounce(viewLifecycleOwner.lifecycleScope) {
viewModel.searchQuery = it
viewModel.fetchThemes()
}
}
private fun observeViewModel() {
viewModel.toastEvent.observe(viewLifecycleOwner) {
context?.showToast(it)
}
viewModel.themesEvent.observe(viewLifecycleOwner) {
adapter.submitList(it)
binding.emptyView.isVisible = it.isEmpty()
}
viewModel.selectEvent.observe(viewLifecycleOwner) {
context?.showToast(text = getString(R.string.message_selected, it))
}
viewModel.exportEvent.observe(viewLifecycleOwner) {
context?.showToast(
text = getString(R.string.message_theme_exported, it),
duration = Toast.LENGTH_LONG
)
}
viewModel.removeEvent.observe(viewLifecycleOwner) {
context?.showToast(text = getString(R.string.message_theme_removed, it))
}
}
} | apache-2.0 | a2abd52b7257f8cf0427f9455137b34d | 40.924051 | 104 | 0.707685 | 4.953628 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/graphql/GQLRootQueryGitIssueInfo.kt | 1 | 2473 | package net.nemerosa.ontrack.extension.git.graphql
import graphql.Scalars.GraphQLString
import graphql.schema.DataFetchingEnvironment
import graphql.schema.GraphQLFieldDefinition
import graphql.schema.GraphQLNonNull
import net.nemerosa.ontrack.extension.git.GitIssueSearchExtension
import net.nemerosa.ontrack.extension.git.model.OntrackGitIssueInfo
import net.nemerosa.ontrack.extension.git.service.GitService
import net.nemerosa.ontrack.graphql.schema.GQLRootQuery
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.SearchRequest
import net.nemerosa.ontrack.model.structure.SearchService
import org.springframework.stereotype.Component
@Component
class GQLRootQueryGitIssueInfo(
private val ontrackGitIssueInfo: OntrackGitIssueInfoGQLType,
private val searchService: SearchService,
private val gitService: GitService
) : GQLRootQuery {
override fun getFieldDefinition(): GraphQLFieldDefinition =
GraphQLFieldDefinition.newFieldDefinition()
.name("gitIssueInfo")
.description("Getting Ontrack information about a Git issue and a project.")
.argument {
it.name(ARG_ISSUE)
.description("Issue key")
.type(GraphQLNonNull(GraphQLString))
}
.type(ontrackGitIssueInfo.typeRef)
.dataFetcher { env -> getOntrackGitIssueInfo(env) }
.build()
private fun getOntrackGitIssueInfo(env: DataFetchingEnvironment): OntrackGitIssueInfo? {
val issue: String = env.getArgument(ARG_ISSUE)
// Looking for the project based on the commit only
val results = searchService.paginatedSearch(SearchRequest(
token = issue,
type = GitIssueSearchExtension.GIT_ISSUE_SEARCH_RESULT_TYPE
))
// Getting the project
val project: Project? = if (results.items.isEmpty() || results.items.size > 1) {
null
} else {
val result = results.items.first()
val data = result.data
data?.get(GitIssueSearchExtension.GIT_ISSUE_SEARCH_RESULT_DATA_PROJECT) as? Project?
}
// Calling the Git service
return project?.let { gitService.getIssueProjectInfo(it.id, issue) }
}
companion object {
const val ARG_ISSUE = "issue"
}
} | mit | 4166052f3c3ca1bf60e4bb5c29e73ae7 | 41.655172 | 96 | 0.670036 | 5.016227 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/view/filter/ComposedFilter.kt | 1 | 2153 | package com.soywiz.korge.view.filter
import com.soywiz.korge.render.*
import com.soywiz.korge.view.*
import com.soywiz.korim.color.*
import com.soywiz.korma.geom.*
import com.soywiz.korui.UiContainer
/**
* Allows to create a single [Filter] that will render several [filters] in order.
*/
class ComposedFilter(val filters: List<Filter>) : Filter {
constructor(vararg filters: Filter) : this(filters.toList())
override val allFilters: List<Filter> get() = filters.flatMap { it.allFilters }
override val border get() = filters.sumBy { it.border }
override fun render(
ctx: RenderContext,
matrix: Matrix,
texture: Texture,
texWidth: Int,
texHeight: Int,
renderColorAdd: ColorAdd,
renderColorMul: RGBA,
blendMode: BlendMode
) {
if (filters.isEmpty()) {
IdentityFilter.render(ctx, matrix, texture, texWidth, texHeight, renderColorAdd, renderColorMul, blendMode)
} else {
renderIndex(ctx, matrix, texture, texWidth, texHeight, renderColorAdd, renderColorMul, blendMode, filters.size - 1)
}
}
private val identity = Matrix()
fun renderIndex(
ctx: RenderContext,
matrix: Matrix,
texture: Texture,
texWidth: Int,
texHeight: Int,
renderColorAdd: ColorAdd,
renderColorMul: RGBA,
blendMode: BlendMode,
level: Int
) {
val filter = filters[filters.size - level - 1]
val newTexWidth = texWidth + filter.border
val newTexHeight = texHeight + filter.border
// @TODO: We only need two render textures
ctx.renderToTexture(newTexWidth, newTexHeight, {
filter.render(ctx, identity, texture, newTexWidth, newTexHeight, renderColorAdd, renderColorMul, blendMode)
}, { newtex ->
if (level > 0) {
renderIndex(ctx, matrix, newtex, newTexWidth, newTexHeight, renderColorAdd, renderColorMul, blendMode, level - 1)
} else {
filter.render(ctx, matrix, newtex, newTexWidth, newTexHeight, renderColorAdd, renderColorMul, blendMode)
}
})
}
override fun buildDebugComponent(views: Views, container: UiContainer) {
for (filter in filters) {
filter.buildDebugComponent(views, container)
}
}
}
| apache-2.0 | fa379334fbf2316fa9ce669ce101a52e | 30.202899 | 119 | 0.699489 | 3.612416 | false | false | false | false |
yukuku/androidbible | Alkitab/src/main/java/yuku/alkitab/base/verses/VersesControllerImpl.kt | 1 | 28494 | package yuku.alkitab.base.verses
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.net.Uri
import android.text.SpannableStringBuilder
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import yuku.afw.storage.Preferences
import yuku.alkitab.base.S
import yuku.alkitab.base.util.AppLog
import yuku.alkitab.base.util.Appearances
import yuku.alkitab.base.util.TargetDecoder
import yuku.alkitab.base.util.TextColorUtil
import yuku.alkitab.base.verses.VersesDataModel.ItemType
import yuku.alkitab.base.widget.AriParallelClickData
import yuku.alkitab.base.widget.DictionaryLinkInfo
import yuku.alkitab.base.widget.DictionaryLinkSpan
import yuku.alkitab.base.widget.FormattedTextRenderer
import yuku.alkitab.base.widget.ParallelClickData
import yuku.alkitab.base.widget.ParallelSpan
import yuku.alkitab.base.widget.PericopeHeaderItem
import yuku.alkitab.base.widget.ReferenceParallelClickData
import yuku.alkitab.base.widget.ScrollbarSetter.setVerticalThumb
import yuku.alkitab.base.widget.VerseRendererHelper
import yuku.alkitab.debug.R
import yuku.alkitab.model.SingleChapterVerses
import yuku.alkitab.util.Ari
import yuku.alkitab.util.IntArrayList
import java.util.concurrent.atomic.AtomicInteger
import yuku.alkitab.base.util.safeQuery
private const val TAG = "VersesControllerImpl"
class VersesControllerImpl(
private val rv: EmptyableRecyclerView,
override val name: String,
versesDataModel: VersesDataModel = VersesDataModel.EMPTY,
versesUiModel: VersesUiModel = VersesUiModel.EMPTY,
versesListeners: VersesListeners = VersesListeners.EMPTY
) : VersesController {
private val checkedPositions = mutableSetOf<Int>()
private val attention = Attention()
private val dataVersionNumber = AtomicInteger()
private val layoutManager: LinearLayoutManager
private val adapter: VersesAdapter
init {
val layoutManager = LinearLayoutManager(rv.context)
this.layoutManager = layoutManager
rv.layoutManager = layoutManager
rv.addOnScrollListener(rvScrollListener)
val adapter = VersesAdapter(
attention = attention,
isChecked = { position -> position in checkedPositions },
toggleChecked = { position ->
if (position !in checkedPositions) {
checkedPositions += position
} else {
checkedPositions -= position
}
notifyItemChanged(position)
if (checkedPositions.size > 0) {
listeners.selectedVersesListener.onSomeVersesSelected(getCheckedVerses_1())
} else {
listeners.selectedVersesListener.onNoVersesSelected()
}
}
)
this.adapter = adapter
rv.adapter = adapter
}
private val rvScrollListener
get() = object : RecyclerView.OnScrollListener() {
var scrollState = RecyclerView.SCROLL_STATE_IDLE
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
this.scrollState = newState
}
override fun onScrolled(view: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(view, dx, dy)
val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
val firstChild = layoutManager.findViewByPosition(firstVisibleItemPosition) ?: return
var prop = 0f
var position = -1
val remaining = firstChild.bottom // padding top is ignored
if (remaining >= 0) { // bottom of first child is lower than top padding
position = firstVisibleItemPosition
prop = 1f - remaining.toFloat() / firstChild.height
} else { // we should have a second child
layoutManager.findViewByPosition(firstVisibleItemPosition + 1)?.let { secondChild ->
position = firstVisibleItemPosition + 1
prop = (-remaining).toFloat() / secondChild.height
}
}
val verse_1 = versesDataModel.getVerseOrPericopeFromPosition(position)
if (scrollState != RecyclerView.SCROLL_STATE_IDLE) {
if (verse_1 > 0) {
versesListeners.verseScrollListener.onVerseScroll(false, verse_1, prop)
} else {
versesListeners.verseScrollListener.onVerseScroll(true, 0, 0f)
}
if (position == 0 && firstChild.top == view.paddingTop) {
// we are really at the top
versesListeners.verseScrollListener.onScrollToTop()
}
}
}
}
/**
* Data for adapter: Verse data
*/
override var versesDataModel = versesDataModel
set(value) {
field = value
dataVersionNumber.incrementAndGet()
attention.clear()
render()
}
/**
* Data for adapter: UI data
*/
override var versesUiModel = versesUiModel
set(value) {
field = value
render()
}
/**
* Data for adapter: Callbacks
*/
override var versesListeners = versesListeners
set(value) {
field = value
render()
}
override fun uncheckAllVerses(callSelectedVersesListener: Boolean) {
// Animate
for (checkedPosition in checkedPositions) {
adapter.notifyItemChanged(checkedPosition)
}
checkedPositions.clear()
if (callSelectedVersesListener) {
versesListeners.selectedVersesListener.onNoVersesSelected()
}
}
override fun checkVerses(verses_1: IntArrayList, callSelectedVersesListener: Boolean) {
uncheckAllVerses(false)
var checked_count = 0
var i = 0
val len = verses_1.size()
while (i < len) {
val verse_1 = verses_1.get(i)
val count = versesDataModel.itemCount
val pos = versesDataModel.getPositionIgnoringPericopeFromVerse(verse_1)
if (pos != -1 && pos < count) {
checkedPositions += pos
checked_count++
}
i++
}
// Animate
for (checkedPosition in checkedPositions) {
adapter.notifyItemChanged(checkedPosition)
}
if (callSelectedVersesListener) {
if (checked_count > 0) {
versesListeners.selectedVersesListener.onSomeVersesSelected(getCheckedVerses_1())
} else {
versesListeners.selectedVersesListener.onNoVersesSelected()
}
}
}
override fun getCheckedVerses_1(): IntArrayList {
val checkedVerses_1 = mutableSetOf<Int>()
for (checkedPosition in checkedPositions) {
val verse_1 = versesDataModel.getVerse_1FromPosition(checkedPosition)
if (verse_1 >= 1) {
checkedVerses_1 += verse_1
}
}
val res = IntArrayList(checkedVerses_1.size)
for (verse_1 in checkedVerses_1.sorted()) {
res.add(verse_1)
}
return res
}
override fun scrollToTop() {
rv.scrollToPosition(0)
}
override fun scrollToVerse(verse_1: Int) {
val position = versesDataModel.getPositionOfPericopeBeginningFromVerse(verse_1)
if (position == -1) {
AppLog.w(TAG, "could not find verse_1=$verse_1, weird!")
} else {
val vn = dataVersionNumber.get()
rv.post {
// this may happen async from above, so check data version first
if (vn != dataVersionNumber.get()) return@post
// negate padding offset, unless this is the first verse
val paddingNegator = if (position == 0) 0 else -rv.paddingTop
layoutManager.scrollToPositionWithOffset(position, paddingNegator)
}
}
}
override fun scrollToVerse(verse_1: Int, prop: Float) {
val position = versesDataModel.getPositionIgnoringPericopeFromVerse(verse_1)
if (position == -1) {
AppLog.d(TAG, "could not find verse_1: $verse_1")
return
}
rv.post(fun() {
// this may happen async from above, so check first if pos is still valid
if (position >= versesDataModel.itemCount) return
// negate padding offset, unless this is the first verse
val paddingNegator = if (position == 0) 0 else -rv.paddingTop
val firstPos = layoutManager.findFirstVisibleItemPosition()
val lastPos = layoutManager.findLastVisibleItemPosition()
if (position in firstPos..lastPos) {
// we have the child on screen, no need to measure
val child = layoutManager.findViewByPosition(position) ?: return
rv.stopScroll()
layoutManager.scrollToPositionWithOffset(position, -(prop * child.height).toInt() + paddingNegator)
return
}
val measuredHeight = getMeasuredItemHeight(position)
rv.stopScroll()
layoutManager.scrollToPositionWithOffset(position, -(prop * measuredHeight).toInt() + paddingNegator)
})
}
private fun getMeasuredItemHeight(position: Int): Int {
// child needed is not on screen, we need to measure
val viewType = adapter.getItemViewType(position)
val holder = adapter.createViewHolder(rv, viewType)
adapter.bindViewHolder(holder, position)
val child = holder.itemView
child.measure(
View.MeasureSpec.makeMeasureSpec(rv.width - rv.paddingLeft - rv.paddingRight, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
)
return child.measuredHeight
}
/**
* Returns -1 if there is no visible child (e.g. when split is collapsed until the height is 0).
*/
private fun getPositionBasedOnScroll(): Int {
val pos = layoutManager.findFirstVisibleItemPosition()
// check if the top one has been scrolled
val child = layoutManager.findViewByPosition(pos)
if (child != null) {
val top = child.top
if (top == 0) {
return pos
}
val bottom = child.bottom
return if (bottom > 0) {
pos
} else {
pos + 1
}
}
return pos
}
override fun getVerse_1BasedOnScroll(): Int {
return versesDataModel.getVerse_1FromPosition(getPositionBasedOnScroll())
}
override fun pageDown(): VersesController.PressResult {
val oldPos = layoutManager.findFirstVisibleItemPosition()
var newPos = layoutManager.findLastVisibleItemPosition()
if (oldPos == newPos && oldPos < versesDataModel.itemCount - 1) { // in case of very long item
newPos = oldPos + 1
}
// negate padding offset, unless this is the first item
val paddingNegator = if (newPos == 0) 0 else -rv.paddingTop
// TODO(VersesView revamp): It previously scrolled smoothly
layoutManager.scrollToPositionWithOffset(newPos, paddingNegator)
return VersesController.PressResult.Consumed(versesDataModel.getVerse_1FromPosition(newPos))
}
override fun pageUp(): VersesController.PressResult {
val oldPos = layoutManager.findFirstVisibleItemPosition()
val targetHeight = (rv.height - rv.paddingTop - rv.paddingBottom).coerceAtLeast(0)
var totalHeight = 0
// consider how long the first child has been scrolled up
val firstChild = layoutManager.findViewByPosition(oldPos)
if (firstChild != null) {
totalHeight += -firstChild.top
}
var curPos = oldPos
// try until totalHeight exceeds targetHeight
while (true) {
curPos--
if (curPos < 0) {
break
}
totalHeight += getMeasuredItemHeight(curPos)
if (totalHeight > targetHeight) {
break
}
}
var newPos = curPos + 1
if (oldPos == newPos && oldPos > 0) { // move at least one
newPos = oldPos - 1
}
// negate padding offset, unless this is the first item
val paddingNegator = if (newPos == 0) 0 else -rv.paddingTop
// TODO(VersesView revamp): It previously scrolled smoothly
layoutManager.scrollToPositionWithOffset(newPos, paddingNegator)
return VersesController.PressResult.Consumed(versesDataModel.getVerse_1FromPosition(newPos))
}
override fun verseDown(): VersesController.PressResult {
val oldVerse_1 = getVerse_1BasedOnScroll()
val newVerse_1 = if (oldVerse_1 < versesDataModel.verses_.verseCount) {
oldVerse_1 + 1
} else {
oldVerse_1
}
rv.stopScroll()
scrollToVerse(newVerse_1)
return VersesController.PressResult.Consumed(newVerse_1)
}
override fun verseUp(): VersesController.PressResult {
val oldVerse_1 = getVerse_1BasedOnScroll()
val newVerse_1 = if (oldVerse_1 > 1) { // can still go prev
oldVerse_1 - 1
} else {
oldVerse_1
}
rv.stopScroll()
scrollToVerse(newVerse_1)
return VersesController.PressResult.Consumed(newVerse_1)
}
override fun setViewVisibility(visibility: Int) {
rv.visibility = visibility
}
override fun setViewPadding(padding: Rect) {
rv.setPadding(padding.left, padding.top, padding.right, padding.bottom)
}
override fun setViewScrollbarThumb(thumb: Drawable) {
rv.setVerticalThumb(thumb)
}
override fun setViewLayoutSize(width: Int, height: Int) {
val lp = rv.layoutParams
lp.width = width
lp.height = height
rv.layoutParams = lp
}
override fun callAttentionForVerse(verse_1: Int) {
val pos = versesDataModel.getPositionIgnoringPericopeFromVerse(verse_1)
if (pos == -1) return
attention.verses_1 += verse_1
attention.start = System.currentTimeMillis()
layoutManager.findViewByPosition(pos)?.invalidate()
}
override fun setEmptyMessage(message: CharSequence?, textColor: Int) {
rv.emptyMessage = message
rv.emptyMessagePaint.color = textColor
}
fun render() {
adapter.data = versesDataModel
adapter.ui = versesUiModel
adapter.listeners = versesListeners
}
}
/**
* For calling attention. All attentioned verses have the same start time.
* The last call to callAttentionForVerse() decides as when the animation starts.
*/
class Attention(var start: Long = 0L, val verses_1: MutableSet<Int> = mutableSetOf()) {
fun clear() {
start = 0L
verses_1.clear()
}
fun hasAny() = start != 0L && verses_1.isNotEmpty()
}
sealed class ItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class VerseTextHolder(private val view: VerseItem) : ItemHolder(view) {
/**
* @param index the index of verse
*/
fun bind(
data: VersesDataModel,
ui: VersesUiModel,
listeners: VersesListeners,
attention: Attention,
checked: Boolean,
toggleChecked: (position: Int) -> Unit,
index: Int
) {
val verse_1 = index + 1
val ari = Ari.encodeWithBc(data.ari_bc_, verse_1)
val text = data.verses_.getVerse(index)
val verseNumberText = data.verses_.getVerseNumberText(index)
val highlightInfo = data.versesAttributes.highlightInfoMap_[index]
val lText = view.lText
val lVerseNumber = view.lVerseNumber
val startVerseTextPos = VerseRendererHelper.render(
lText = lText,
lVerseNumber = lVerseNumber,
isVerseNumberShown = ui.isVerseNumberShown,
ari = ari,
text = text,
verseNumberText = verseNumberText,
highlightInfo = highlightInfo,
checked = checked,
inlineLinkSpanFactory = listeners.inlineLinkSpanFactory_
)
val textSizeMult = if (data.verses_ is SingleChapterVerses.WithTextSizeMult) {
data.verses_.getTextSizeMult(index)
} else {
ui.textSizeMult
}
Appearances.applyTextAppearance(lText, textSizeMult)
Appearances.applyVerseNumberAppearance(lVerseNumber, textSizeMult)
if (checked) { // override text color with black or white!
val selectedTextColor = TextColorUtil.getForCheckedVerse(Preferences.getInt(R.string.pref_selectedVerseBgColor_key, R.integer.pref_selectedVerseBgColor_default))
lText.setTextColor(selectedTextColor)
lVerseNumber.setTextColor(selectedTextColor)
}
val attributeView = view.attributeView
attributeView.setScale(scaleForAttributeView(S.applied().fontSize2dp * ui.textSizeMult))
attributeView.bookmarkCount = data.versesAttributes.bookmarkCountMap_[index]
attributeView.noteCount = data.versesAttributes.noteCountMap_[index]
attributeView.progressMarkBits = data.versesAttributes.progressMarkBitsMap_[index]
attributeView.hasMaps = data.versesAttributes.hasMapsMap_[index]
attributeView.setAttributeListener(listeners.attributeListener, data.version_, data.versionId_, ari)
view.checked = checked
view.collapsed = text.isEmpty() && !attributeView.isShowingSomething
view.onPinDropped = { presetId ->
val adapterPosition = adapterPosition
if (adapterPosition != -1) {
listeners.pinDropListener.onPinDropped(presetId, Ari.encodeWithBc(data.ari_bc_, data.getVerse_1FromPosition(adapterPosition)))
}
}
/*
* Dictionary mode is activated on either of these conditions:
* 1. user manually activate dictionary mode after selecting verses
* 2. automatic lookup is on and this verse is selected (checked)
*/
if (ari in ui.dictionaryModeAris || checked && Preferences.getBoolean(view.context.getString(R.string.pref_autoDictionaryAnalyze_key), view.resources.getBoolean(R.bool.pref_autoDictionaryAnalyze_default))) {
val renderedText = lText.text
val verseText = if (renderedText is SpannableStringBuilder) renderedText else SpannableStringBuilder(renderedText)
// we have to exclude the verse numbers from analyze text
val analyzeString = verseText.toString().substring(startVerseTextPos)
val uri = Uri.parse("content://org.sabda.kamus.provider/analyze").buildUpon().appendQueryParameter("text", analyzeString).build()
try {
view.context.contentResolver.safeQuery(uri, null, null, null, null)?.use { c ->
val col_offset = c.getColumnIndexOrThrow("offset")
val col_len = c.getColumnIndexOrThrow("len")
val col_key = c.getColumnIndexOrThrow("key")
while (c.moveToNext()) {
val offset = c.getInt(col_offset)
val len = c.getInt(col_len)
val key = c.getString(col_key)
val word = analyzeString.substring(offset, offset + len)
val span = DictionaryLinkSpan(DictionaryLinkInfo(word, key), listeners.dictionaryListener_)
verseText.setSpan(span, startVerseTextPos + offset, startVerseTextPos + offset + len, 0)
}
}
lText.text = verseText
} catch (e: Exception) {
AppLog.e(TAG, "Error when querying dictionary content provider", e)
}
}
// { // DUMP
// Log.d(TAG, "==== DUMP verse " + (id + 1));
// SpannedString sb = (SpannedString) lText.getText();
// Object[] spans = sb.getSpans(0, sb.length(), Object.class);
// for (Object span: spans) {
// int start = sb.getSpanStart(span);
// int end = sb.getSpanEnd(span);
// Log.d(TAG, "Span " + span.getClass().getSimpleName() + " " + start + ".." + end + ": " + sb.toString().substring(start, end));
// }
// }
// Do we need to call attention?
if (attention.hasAny() && verse_1 in attention.verses_1) {
view.callAttention(attention.start)
} else {
view.callAttention(0L)
}
// Click listener on the whole item view
view.setOnClickListener {
when (ui.verseSelectionMode) {
VersesController.VerseSelectionMode.none -> {
}
VersesController.VerseSelectionMode.singleClick -> {
val adapterPosition = adapterPosition
if (adapterPosition != -1) {
listeners.selectedVersesListener.onVerseSingleClick(data.getVerse_1FromPosition(adapterPosition))
}
}
VersesController.VerseSelectionMode.multiple -> {
val adapterPosition = adapterPosition
if (adapterPosition != -1) {
toggleChecked(adapterPosition)
}
}
}
}
}
private fun scaleForAttributeView(fontSizeDp: Float) = when {
fontSizeDp >= 13 /* 72% */ && fontSizeDp < 24 /* 133% */ -> 1f
fontSizeDp < 8 -> 0.5f // 0 ~ 44%
fontSizeDp < 18 -> 0.75f // 44% ~ 72%
fontSizeDp >= 36 -> 2f // 200% ~
else -> 1.5f // 24 to 36 // 133% ~ 200%
}
}
class PericopeHolder(private val view: PericopeHeaderItem) : ItemHolder(view) {
/**
* @param index the index of verse
*/
fun bind(data: VersesDataModel, ui: VersesUiModel, listeners: VersesListeners, position: Int, index: Int) {
val pericopeBlock = data.pericopeBlocks_[index]
val lCaption = view.findViewById<TextView>(R.id.lCaption)
val lParallels = view.findViewById<TextView>(R.id.lParallels)
lCaption.text = FormattedTextRenderer.render(pericopeBlock.title)
// turn off top padding if the position == 0 OR before this is also a pericope title
val paddingTop = if (position == 0 || data.getItemViewType(position - 1) == ItemType.pericope) {
0
} else {
S.applied().pericopeSpacingTop
}
this.itemView.setPadding(0, paddingTop, 0, S.applied().pericopeSpacingBottom)
Appearances.applyPericopeTitleAppearance(lCaption, ui.textSizeMult)
// make parallel gone if not exist
if (pericopeBlock.parallels.isEmpty()) {
lParallels.visibility = GONE
} else {
lParallels.visibility = VISIBLE
val sb = SpannableStringBuilder("(")
val total = pericopeBlock.parallels.size
for (i in 0 until total) {
val parallel = pericopeBlock.parallels[i]
if (i > 0) {
// force new line for certain parallel patterns
if (total == 6 && i == 3 || total == 4 && i == 2 || total == 5 && i == 3) {
sb.append("; \n")
} else {
sb.append("; ")
}
}
appendParallel(sb, parallel, listeners.parallelListener_)
}
sb.append(')')
lParallels.setText(sb, TextView.BufferType.SPANNABLE)
Appearances.applyPericopeParallelTextAppearance(lParallels, ui.textSizeMult)
}
}
private fun appendParallel(sb: SpannableStringBuilder, parallel: String, parallelListener: (ParallelClickData) -> Unit) {
val sb_len = sb.length
fun link(): Boolean {
if (!parallel.startsWith("@")) {
return false
}
// look for the end
val targetEndPos = parallel.indexOf(' ', 1)
if (targetEndPos == -1) {
return false
}
val target = parallel.substring(1, targetEndPos)
val ariRanges = TargetDecoder.decode(target)
if (ariRanges == null || ariRanges.size() == 0) {
return false
}
val display = parallel.substring(targetEndPos + 1)
// if we reach this, data and display should have values, and we must not go to fallback below
sb.append(display)
sb.setSpan(ParallelSpan(AriParallelClickData(ariRanges.get(0)), parallelListener), sb_len, sb.length, 0)
return true
}
val completed = link()
if (!completed) {
// fallback if the above code fails
sb.append(parallel)
sb.setSpan(ParallelSpan(ReferenceParallelClickData(parallel), parallelListener), sb_len, sb.length, 0)
}
}
}
class VersesAdapter(
private val attention: Attention,
private val isChecked: VersesAdapter.(position: Int) -> Boolean,
private val toggleChecked: VersesAdapter.(position: Int) -> Unit
) : RecyclerView.Adapter<ItemHolder>() {
init {
setHasStableIds(true)
}
var data = VersesDataModel.EMPTY
set(value) {
field = value
notifyDataSetChanged()
}
var ui = VersesUiModel.EMPTY
set(value) {
field = value
notifyDataSetChanged()
}
var listeners = VersesListeners.EMPTY
set(value) {
field = value
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return data.itemCount
}
/**
* Id assignment for nice animation, keeping verses animated.
* For verses, it is always verse_1 * 1000
* For pericopes, it is located between verses, so it is assigned to be the next verse_1 * 1000 - distance to that verse.
*
* For example:
* [verse 1, pericope, verse 2, verse 3, pericope, pericope, verse 4] will have ids
* [1000, 1999, 2000, 3000, 3998, 3999, 4000]
*/
override fun getItemId(position: Int): Long {
return when (data.getItemViewType(position)) {
ItemType.verseText -> data.getVerse_1FromPosition(position) * 1000L
ItemType.pericope -> {
when (val locateResult = data.locateVerse_1FromPosition(position)) {
LocateResult.EMPTY -> 1000000L + position
else -> locateResult.verse_1 * 1000L - locateResult.distanceToNextVerse
}
}
}
}
override fun getItemViewType(position: Int) = data.getItemViewType(position).ordinal
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
ItemType.verseText.ordinal -> {
VerseTextHolder(inflater.inflate(R.layout.item_verse, parent, false) as VerseItem)
}
ItemType.pericope.ordinal -> {
PericopeHolder(inflater.inflate(R.layout.item_pericope_header, parent, false) as PericopeHeaderItem)
}
else -> throw RuntimeException("Unknown viewType $viewType")
}
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
when (holder) {
is VerseTextHolder -> {
val index = data.getVerse_0(position)
holder.bind(data, ui, listeners, attention, isChecked(position), { toggleChecked(it) }, index)
}
is PericopeHolder -> {
val index = data.getPericopeIndex(position)
holder.bind(data, ui, listeners, position, index)
}
}
}
}
| apache-2.0 | 6a5165de1ffcea08c890e5abb7da96eb | 35.530769 | 215 | 0.608514 | 4.73008 | false | false | false | false |
pennlabs/penn-mobile-android | PennMobile/src/main/java/com/pennapps/labs/pennmobile/DiningFragment.kt | 1 | 11889 | package com.pennapps.labs.pennmobile
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.annotation.RequiresApi
import androidx.preference.PreferenceManager
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.analytics.FirebaseAnalytics
import com.pennapps.labs.pennmobile.adapters.DiningAdapter
import com.pennapps.labs.pennmobile.api.StudentLife
import com.pennapps.labs.pennmobile.classes.DiningHall
import com.pennapps.labs.pennmobile.classes.Venue
import kotlinx.android.synthetic.main.fragment_dining.*
import kotlinx.android.synthetic.main.fragment_dining.internetConnectionDining
import kotlinx.android.synthetic.main.fragment_dining.internetConnection_message_dining
import kotlinx.android.synthetic.main.fragment_dining.view.*
import kotlinx.android.synthetic.main.loading_panel.*
import kotlinx.android.synthetic.main.no_results.*
import rx.Observable
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
class DiningFragment : Fragment() {
private lateinit var mActivity: MainActivity
private lateinit var mStudentLife: StudentLife
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mStudentLife = MainActivity.studentLifeInstance
mActivity = activity as MainActivity
mActivity.closeKeyboard()
setHasOptionsMenu(true)
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "1")
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Dining")
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "App Feature")
FirebaseAnalytics.getInstance(mActivity).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(true)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_dining, container, false)
v.dining_swiperefresh?.setColorSchemeResources(R.color.color_accent, R.color.color_primary)
v.dining_halls_recycler_view?.layoutManager = LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false)
v.dining_swiperefresh.setOnRefreshListener { getDiningHalls() }
// initAppBar(v)
return v
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getDiningHalls()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.dining_sort, menu)
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
// sort the dining halls in the user-specified order
val order = sp.getString("dining_sortBy", "RESIDENTIAL")
when (order) {
"RESIDENTIAL" -> {
menu.findItem(R.id.action_sort_residential).isChecked = true
}
"NAME" -> {
menu.findItem(R.id.action_sort_name).isChecked = true
}
else -> {
menu.findItem(R.id.action_sort_open).isChecked = true
}
}
val diningInfoFragment = fragmentManager?.findFragmentByTag("DINING_INFO_FRAGMENT")
menu.setGroupVisible(R.id.action_sort_by, diningInfoFragment == null || !diningInfoFragment.isVisible)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun setSortByMethod(method: String) {
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
val editor = sp.edit()
editor.putString("dining_sortBy", method)
editor.apply()
getDiningHalls()
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle presses on the action bar items
when (item.itemId) {
android.R.id.home -> {
mActivity.onBackPressed()
return true
}
R.id.action_sort_open -> {
setSortByMethod("OPEN")
item.isChecked = true
return true
}
R.id.action_sort_residential -> {
setSortByMethod("RESIDENTIAL")
item.isChecked = true
return true
}
R.id.action_sort_name -> {
setSortByMethod("NAME")
item.isChecked = true
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
@RequiresApi(Build.VERSION_CODES.O)
private fun getDiningHalls() {
//displays banner if not connected
if (!isOnline(context)) {
internetConnectionDining?.setBackgroundColor(resources.getColor(R.color.darkRedBackground))
internetConnection_message_dining?.setText("Not Connected to Internet")
internetConnectionDining?.visibility = View.VISIBLE
} else {
internetConnectionDining?.visibility = View.GONE
}
// Map each item in the list of venues to a Venue Observable, then map each Venue to a DiningHall Observable
mStudentLife.venues()
.flatMap { venues -> Observable.from(venues) }
.flatMap { venue ->
val hall = createHall(venue)
Observable.just(hall)
}
.toList()
.subscribe({ diningHalls ->
mActivity.runOnUiThread {
getMenus(diningHalls)
val adapter = DiningAdapter(diningHalls)
dining_halls_recycler_view?.adapter = adapter
loadingPanel?.visibility = View.GONE
if (diningHalls.size > 0) {
no_results?.visibility = View.GONE
}
dining_swiperefresh?.isRefreshing = false
view?.let {displaySnack(it, "Just Updated")}
}
}, {
Log.e("DiningFragment", "Error getting dining halls", it);
mActivity.runOnUiThread {
Log.e("Dining", "Could not load Dining page", it)
loadingPanel?.visibility = View.GONE
dining_swiperefresh?.isRefreshing = false
}
})
}
override fun onResume() {
super.onResume()
mActivity.removeTabs()
mActivity.setTitle(R.string.dining)
if (Build.VERSION.SDK_INT > 17) {
mActivity.setSelectedTab(MainActivity.DINING)
}
}
/**
* Shows SnackBar message right below the app bar
*/
@Suppress("DEPRECATION")
private fun displaySnack(view: View, text: String) {
val snackBar = Snackbar.make(view.snack_bar_dining, text, Snackbar.LENGTH_SHORT)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
snackBar.setTextColor(resources.getColor(R.color.white, context?.theme))
snackBar.setBackgroundTint(resources.getColor(R.color.penn_mobile_grey, context?.theme))
} else {
snackBar.setTextColor(resources.getColor(R.color.white))
snackBar.setBackgroundTint(resources.getColor(R.color.penn_mobile_grey))
}
// SnackBar message and action TextViews are placed inside a LinearLayout
val snackBarLayout = snackBar.view as Snackbar.SnackbarLayout
for (i in 0 until snackBarLayout.childCount) {
val parent = snackBarLayout.getChildAt(i)
if (parent is LinearLayout) {
parent.rotation = 180F
break
}
}
snackBar.show()
}
companion object {
// Gets the dining hall menus
@RequiresApi(Build.VERSION_CODES.O)
fun getMenus(venues: MutableList<DiningHall>) : Unit {
val idVenueMap = mutableMapOf<Int, DiningHall>()
venues.forEach { idVenueMap[it.id] = it }
val current = LocalDateTime.now()
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val formatted = current.format(formatter)
val studentLife = MainActivity.studentLifeInstance
studentLife.getMenus(formatted).subscribe({ menus ->
menus.forEach { menu ->
val id = menu.venue?.venue_id
val diningHall = idVenueMap[id]
val diningHallMenus = diningHall?.menus ?: mutableListOf()
diningHallMenus.add(menu)
diningHall?.sortMeals(diningHallMenus)
}
}, { throwable ->
Log.e("DiningFragment", "Error getting Menus", throwable)
})
}
// Takes a venue then adds an image and modifies venue name if name is too long
fun createHall(venue: Venue): DiningHall {
when (venue.id) {
593 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_commons)
636 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_hill_house)
637 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_kceh)
638 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_hillel)
639 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_houston)
640 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_marks)
641 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_accenture)
642 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_joes_cafe)
1442 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_nch)
747 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_mcclelland)
1057 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_gourmet_grocer)
1058 -> return DiningHall(venue.id, "Tortas Frontera", venue.isResidential, venue.getHours(), venue, R.drawable.dining_tortas)
1163 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_commons)
1731 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_nch)
1732 -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_mba_cafe)
1733 -> return DiningHall(venue.id, "Pret a Manger Locust", venue.isResidential, venue.getHours(), venue, R.drawable.dining_pret_a_manger)
else -> return DiningHall(venue.id, venue.name, venue.isResidential, venue.getHours(), venue, R.drawable.dining_commons)
}
}
}
}
| mit | 6eb78ebe4820f3104e39878682a8dd1f | 46.178571 | 154 | 0.637144 | 4.510243 | false | false | false | false |
RocketChat/Rocket.Chat.Android.Lily | app/src/main/java/chat/rocket/android/members/adapter/MembersAdapter.kt | 2 | 1945 | package chat.rocket.android.members.adapter
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import chat.rocket.android.R
import chat.rocket.android.members.uimodel.MemberUiModel
import chat.rocket.android.util.extensions.content
import chat.rocket.android.util.extensions.inflate
import kotlinx.android.synthetic.main.avatar.view.*
import kotlinx.android.synthetic.main.item_member.view.*
class MembersAdapter(
private val listener: (MemberUiModel) -> Unit
) : RecyclerView.Adapter<MembersAdapter.ViewHolder>() {
private var dataSet: List<MemberUiModel> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(parent.inflate(R.layout.item_member))
override fun onBindViewHolder(holder: ViewHolder, position: Int) =
holder.bind(dataSet[position], listener)
override fun getItemCount(): Int = dataSet.size
fun clearData() {
dataSet = emptyList()
notifyDataSetChanged()
}
fun prependData(dataSet: List<MemberUiModel>) {
this.dataSet = dataSet
notifyItemRangeInserted(0, dataSet.size)
}
fun appendData(dataSet: List<MemberUiModel>) {
val previousDataSetSize = this.dataSet.size
this.dataSet += dataSet
notifyItemRangeInserted(previousDataSetSize, dataSet.size)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(memberUiModel: MemberUiModel, listener: (MemberUiModel) -> Unit) = with(itemView) {
image_avatar.setImageURI(memberUiModel.avatarUri)
text_member.content = memberUiModel.displayName
text_member.setCompoundDrawablesRelativeWithIntrinsicBounds(
DrawableHelper.getUserStatusDrawable(memberUiModel.status, context), null, null, null)
setOnClickListener { listener(memberUiModel) }
}
}
}
| mit | e0da26e3a1ebadf77addfcd98b89b0a7 | 36.403846 | 106 | 0.727506 | 4.664269 | false | false | false | false |
shlusiak/Freebloks-Android | app/src/main/java/de/saschahlusiak/freebloks/view/FreebloksRenderer.kt | 1 | 9261 | package de.saschahlusiak.freebloks.view
import android.content.Context
import android.opengl.GLSurfaceView
import android.opengl.GLU
import android.util.Log
import de.saschahlusiak.freebloks.model.Board
import de.saschahlusiak.freebloks.model.colorOf
import de.saschahlusiak.freebloks.theme.ColorThemes
import de.saschahlusiak.freebloks.utils.PointF
import de.saschahlusiak.freebloks.view.scene.Scene
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
import javax.microedition.khronos.opengles.GL11
import kotlin.math.cos
import kotlin.math.sin
class FreebloksRenderer(private val context: Context, private val scene: Scene) : GLSurfaceView.Renderer {
private val tag = FreebloksRenderer::class.java.simpleName
private val lightAmbientColor = floatArrayOf(0.35f, 0.35f, 0.35f, 1.0f)
private val lightDiffuseColor = floatArrayOf(0.8f, 0.8f, 0.8f, 1.0f)
private val lightSpecularColor = floatArrayOf(1.0f, 1.0f, 1.0f, 1.0f)
val lightPos = floatArrayOf(2.5f, 5f, -2.0f, 0.0f)
private var width = 1f
private var height = 1f
private var isSoftwareRenderer = false
private var isEmulator = false
val fixedZoom = 55.0f
private val mAngleX = 70.0f
var zoom = 0f
private val viewport = IntArray(4)
private val projectionMatrix = FloatArray(16)
private val modelViewMatrix = FloatArray(16)
val boardRenderer = BoardRenderer(context.resources)
val backgroundRenderer = BackgroundRenderer(context.resources, ColorThemes.Blue)
private val outputFar = FloatArray(4)
private val outputNear = FloatArray(4)
var updateModelViewMatrix = true
fun init(boardSize: Int) {
boardRenderer.setBoardSize(boardSize)
}
fun windowToModel(point: PointF): PointF {
synchronized(outputFar) {
GLU.gluUnProject(point.x, viewport[3] - point.y, 0.0f, modelViewMatrix, 0, projectionMatrix, 0, viewport, 0, outputNear, 0)
GLU.gluUnProject(point.x, viewport[3] - point.y, 1.0f, modelViewMatrix, 0, projectionMatrix, 0, viewport, 0, outputFar, 0)
}
val x1 = outputFar[0] / outputFar[3]
val y1 = outputFar[1] / outputFar[3]
val z1 = outputFar[2] / outputFar[3]
val x2 = outputNear[0] / outputNear[3]
val y2 = outputNear[1] / outputNear[3]
val z2 = outputNear[2] / outputNear[3]
val u = (0.0f - y1) / (y2 - y1)
return PointF(
x1 + u * (x2 - x1),
z1 + u * (z2 - z1)
)
}
@Synchronized
override fun onDrawFrame(gl: GL10) {
val gl11 = gl as GL11
val cameraDistance = zoom
val cameraAngle = scene.baseAngle
val boardAngle = scene.boardObject.currentAngle
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY)
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY)
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY)
gl.glMatrixMode(GL10.GL_MODELVIEW)
val intro = scene.intro
if (intro != null) {
intro.render(gl11, this)
return
}
gl.glLoadIdentity()
if (scene.verticalLayout) {
gl.glTranslatef(0f, 7.0f, 0f)
} else gl.glTranslatef(-5.0f, 0.6f, 0f)
GLU.gluLookAt(gl,
(fixedZoom / cameraDistance * sin(cameraAngle * Math.PI / 180.0) * cos(mAngleX * Math.PI / 180.0f)).toFloat(),
(fixedZoom / cameraDistance * sin(mAngleX * Math.PI / 180.0f)).toFloat(),
(fixedZoom / cameraDistance * cos(mAngleX * Math.PI / 180.0f) * cos(-cameraAngle * Math.PI / 180.0f)).toFloat(),
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f)
if (updateModelViewMatrix) synchronized(outputFar) {
if (isSoftwareRenderer) {
/* FIXME: add path for software renderer */
} else {
gl11.glGetFloatv(GL11.GL_MODELVIEW_MATRIX, modelViewMatrix, 0)
}
updateModelViewMatrix = false
}
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPos, 0)
/* render board */
gl.glDisable(GL10.GL_DEPTH_TEST)
gl.glRotatef(boardAngle, 0f, 1f, 0f)
backgroundRenderer.render(gl11)
boardRenderer.renderBoard(gl11, scene.board, scene.boardObject.showSeedsPlayer)
val game = scene.game
val gameMode = game.gameMode
val board = game.board
val colors = arrayOf(
gameMode.colorOf(0),
gameMode.colorOf(1),
gameMode.colorOf(2),
gameMode.colorOf(3)
)
/* render player stones on board, unless they are "effected" */
gl.glPushMatrix()
gl.glTranslatef(-BoardRenderer.stoneSize * (scene.board.width - 1).toFloat(), 0f, -BoardRenderer.stoneSize * (scene.board.width - 1).toFloat())
gl.glEnable(GL10.GL_BLEND)
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA)
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SPECULAR, BoardRenderer.materialStoneSpecular, 0)
gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SHININESS, BoardRenderer.materialStoneShininess, 0)
boardRenderer.stone.bindBuffers(gl11)
synchronized(scene.effects) {
// Synchronized with [Board.startNewGame]
synchronized(board) {
for (y in 0 until board.height) {
var x = 0
while (x < board.width) {
val field = board.getFieldPlayer(y, x)
if (field != Board.FIELD_FREE) {
// value between 0 and 3
if (scene.effects.none { it.isEffected(x, y) }) {
boardRenderer.renderSingleStone(gl11, colors[field], BoardRenderer.defaultStoneAlpha)
}
}
gl.glTranslatef(BoardRenderer.stoneSize * 2.0f, 0f, 0f)
x++
}
gl.glTranslatef(-x * BoardRenderer.stoneSize * 2.0f, 0f, BoardRenderer.stoneSize * 2.0f)
}
}
}
gl.glDisable(GL10.GL_BLEND)
gl.glPopMatrix()
gl.glDisable(GL10.GL_DEPTH_TEST)
/* render all effects */
synchronized(scene.effects) {
for (i in scene.effects.indices) {
scene.effects[i].renderShadow(gl11, boardRenderer)
}
gl.glEnable(GL10.GL_DEPTH_TEST)
for (i in scene.effects.indices) {
scene.effects[i].render(gl11, boardRenderer)
}
}
gl.glDisable(GL10.GL_DEPTH_TEST)
gl.glRotatef(-boardAngle, 0f, 1f, 0f)
gl.glPushMatrix()
/* reverse the cameraAngle to always fix wheel in front of camera */
gl.glRotatef(cameraAngle, 0f, 1f, 0f)
if (!scene.verticalLayout) gl.glRotatef(90.0f, 0f, 1f, 0f)
scene.wheel.render(this, gl11)
gl.glPopMatrix()
/* render current player stone on the field */
if (game.isLocalPlayer()) scene.currentStone.render(this, gl11)
}
override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
val gl11 = gl as GL11
Log.d(tag, "onSurfaceChanged: $width, $height")
gl.glViewport(0, 0, width, height)
viewport[0] = 0
viewport[1] = 0
viewport[2] = width
viewport[3] = height
this.width = width.toFloat()
this.height = height.toFloat()
scene.verticalLayout = height >= width
val fovY = if (scene.verticalLayout) 35.0f else 21.0f
gl.glMatrixMode(GL10.GL_PROJECTION)
gl.glLoadIdentity()
GLU.gluPerspective(gl, fovY, this.width / this.height, 1.0f, 300.0f)
gl.glMatrixMode(GL10.GL_MODELVIEW)
synchronized(outputFar) {
if (isSoftwareRenderer) {
/* FIXME: add path for software renderer */
} else {
gl11.glGetFloatv(GL11.GL_PROJECTION_MATRIX, projectionMatrix, 0)
}
}
}
override fun onSurfaceCreated(gl: GL10, config: EGLConfig) {
val renderer = gl.glGetString(GL10.GL_RENDERER)
isEmulator = renderer.contains("Android Emulator OpenGL")
isSoftwareRenderer = renderer.contains("PixelFlinger") || isEmulator
gl as GL11
Log.i(tag, "Renderer: $renderer")
with(gl) {
glDisable(GL10.GL_DITHER)
glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST)
glEnable(GL10.GL_CULL_FACE)
glShadeModel(GL10.GL_SMOOTH)
glEnable(GL10.GL_DEPTH_TEST)
glEnable(GL10.GL_NORMALIZE)
glEnable(GL10.GL_LIGHTING)
glEnable(GL10.GL_LIGHT0)
glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, lightPos, 0)
glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, lightAmbientColor, 0)
glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, lightDiffuseColor, 0)
glLightfv(GL10.GL_LIGHT0, GL10.GL_SPECULAR, lightSpecularColor, 0)
}
updateModelViewMatrix = true
scene.currentStone.updateTexture(context, gl)
boardRenderer.onSurfaceChanged(gl)
backgroundRenderer.updateTexture(gl)
}
} | gpl-2.0 | 5767f1ea9c72419df3f2ee46476997d6 | 37.431535 | 151 | 0.610517 | 3.659028 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/dataclient/restbase/EditCount.kt | 1 | 543 | package org.wikipedia.dataclient.restbase
import kotlinx.serialization.Serializable
@Serializable
@Suppress("unused")
class EditCount {
val count: Int = 0
val limit: Boolean = false
companion object {
const val EDIT_TYPE_ANONYMOUS = "anonymous"
const val EDIT_TYPE_BOT = "bot"
const val EDIT_TYPE_EDITORS = "editors"
const val EDIT_TYPE_EDITS = "edits"
const val EDIT_TYPE_MINOR = "minor"
const val EDIT_TYPE_REVERTED = "reverted"
const val EDIT_TYPE_ALL = "all"
}
}
| apache-2.0 | bcd826dbd09b8aa652ddf2e9914729c7 | 24.857143 | 51 | 0.651934 | 3.823944 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/login/LoginActivity.kt | 1 | 10422 | package org.wikipedia.login
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.contract.ActivityResultContracts
import com.google.android.material.textfield.TextInputLayout
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.BaseActivity
import org.wikipedia.analytics.LoginFunnel
import org.wikipedia.auth.AccountUtil.updateAccount
import org.wikipedia.createaccount.CreateAccountActivity
import org.wikipedia.databinding.ActivityLoginBinding
import org.wikipedia.login.LoginClient.LoginFailedException
import org.wikipedia.notifications.PollNotificationWorker
import org.wikipedia.page.PageTitle
import org.wikipedia.push.WikipediaFirebaseMessagingService.Companion.updateSubscription
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter
import org.wikipedia.settings.Prefs
import org.wikipedia.util.DeviceUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.UriUtil.visitInExternalBrowser
import org.wikipedia.util.log.L
import org.wikipedia.views.NonEmptyValidator
class LoginActivity : BaseActivity() {
private lateinit var binding: ActivityLoginBinding
private lateinit var loginSource: String
private var firstStepToken: String? = null
private var funnel: LoginFunnel = LoginFunnel(WikipediaApp.instance)
private val loginClient = LoginClient()
private val loginCallback = LoginCallback()
private var shouldLogLogin = true
private val createAccountLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
logLoginStart()
when (it.resultCode) {
CreateAccountActivity.RESULT_ACCOUNT_CREATED -> {
binding.loginUsernameText.editText?.setText(it.data!!.getStringExtra(CreateAccountActivity.CREATE_ACCOUNT_RESULT_USERNAME))
binding.loginPasswordInput.editText?.setText(it.data?.getStringExtra(CreateAccountActivity.CREATE_ACCOUNT_RESULT_PASSWORD))
funnel.logCreateAccountSuccess()
FeedbackUtil.showMessage(this, R.string.create_account_account_created_toast)
doLogin()
}
CreateAccountActivity.RESULT_ACCOUNT_NOT_CREATED -> finish()
else -> funnel.logCreateAccountFailure()
}
}
private val resetPasswordLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == RESULT_OK) {
onLoginSuccess()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.viewLoginError.backClickListener = View.OnClickListener { onBackPressed() }
binding.viewLoginError.retryClickListener = View.OnClickListener { binding.viewLoginError.visibility = View.GONE }
// Don't allow user to attempt login until they've put in a username and password
NonEmptyValidator(binding.loginButton, binding.loginUsernameText, binding.loginPasswordInput)
binding.loginPasswordInput.editText?.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
validateThenLogin()
return@setOnEditorActionListener true
}
false
}
loginSource = intent.getStringExtra(LOGIN_REQUEST_SOURCE).orEmpty()
if (loginSource.isNotEmpty() && loginSource == LoginFunnel.SOURCE_SUGGESTED_EDITS) {
Prefs.isSuggestedEditsHighestPriorityEnabled = true
}
// always go to account creation before logging in, unless we arrived here through the
// system account creation workflow
if (savedInstanceState == null && !intent.hasExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)) {
startCreateAccountActivity()
}
setAllViewsClickListener()
// Assume no login by default
setResult(RESULT_LOGIN_FAIL)
}
override fun onBackPressed() {
DeviceUtil.hideSoftKeyboard(this)
super.onBackPressed()
}
override fun onStop() {
binding.viewProgressBar.visibility = View.GONE
loginClient.cancel()
super.onStop()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("loginShowing", true)
}
private fun setAllViewsClickListener() {
binding.loginButton.setOnClickListener { validateThenLogin() }
binding.loginCreateAccountButton.setOnClickListener { startCreateAccountActivity() }
binding.inflateLoginAndAccount.privacyPolicyLink.setOnClickListener { FeedbackUtil.showPrivacyPolicy(this) }
binding.inflateLoginAndAccount.forgotPasswordLink.setOnClickListener {
val title = PageTitle("Special:PasswordReset", WikipediaApp.instance.wikiSite)
visitInExternalBrowser(this, Uri.parse(title.uri))
}
}
private fun getText(input: TextInputLayout): String {
return input.editText?.text?.toString().orEmpty()
}
private fun clearErrors() {
binding.loginUsernameText.isErrorEnabled = false
binding.loginPasswordInput.isErrorEnabled = false
}
private fun validateThenLogin() {
clearErrors()
if (!CreateAccountActivity.USERNAME_PATTERN.matcher(getText(binding.loginUsernameText)).matches()) {
binding.loginUsernameText.requestFocus()
binding.loginUsernameText.error = getString(R.string.create_account_username_error)
return
}
doLogin()
}
private fun logLoginStart() {
if (shouldLogLogin && loginSource.isNotEmpty()) {
if (loginSource == LoginFunnel.SOURCE_EDIT) {
funnel.logStart(
LoginFunnel.SOURCE_EDIT,
intent.getStringExtra(EDIT_SESSION_TOKEN).orEmpty()
)
} else {
funnel.logStart(loginSource)
}
shouldLogLogin = false
}
}
private fun startCreateAccountActivity() {
funnel.logCreateAccountAttempt()
createAccountLauncher.launch(CreateAccountActivity.newIntent(this, funnel.sessionToken, loginSource))
}
private fun onLoginSuccess() {
funnel.logSuccess()
DeviceUtil.hideSoftKeyboard(this@LoginActivity)
setResult(RESULT_LOGIN_SUCCESS)
// Set reading list syncing to enabled (without the explicit setup instruction),
// so that the sync adapter can run at least once and check whether syncing is enabled
// on the server side.
Prefs.isReadingListSyncEnabled = true
Prefs.readingListPagesDeletedIds = emptySet()
Prefs.readingListsDeletedIds = emptySet()
ReadingListSyncAdapter.manualSyncWithForce()
PollNotificationWorker.schedulePollNotificationJob(this)
Prefs.isPushNotificationOptionsSet = false
updateSubscription()
finish()
}
private fun doLogin() {
val username = getText(binding.loginUsernameText)
val password = getText(binding.loginPasswordInput)
val twoFactorCode = getText(binding.login2faText)
showProgressBar(true)
if (twoFactorCode.isNotEmpty() && !firstStepToken.isNullOrEmpty()) {
loginClient.login(WikipediaApp.instance.wikiSite, username, password,
null, twoFactorCode, firstStepToken!!, loginCallback)
} else {
loginClient.request(WikipediaApp.instance.wikiSite, username, password, loginCallback)
}
}
private inner class LoginCallback : LoginClient.LoginCallback {
override fun success(result: LoginResult) {
showProgressBar(false)
if (result.pass()) {
val response = intent.extras?.getParcelable<AccountAuthenticatorResponse>(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)
updateAccount(response, result)
onLoginSuccess()
} else if (result.fail()) {
val message = result.message.orEmpty()
FeedbackUtil.showMessage(this@LoginActivity, message)
funnel.logError(message)
L.w("Login failed with result $message")
}
}
override fun twoFactorPrompt(caught: Throwable, token: String?) {
showProgressBar(false)
firstStepToken = token
binding.login2faText.visibility = View.VISIBLE
binding.login2faText.requestFocus()
FeedbackUtil.showError(this@LoginActivity, caught)
}
override fun passwordResetPrompt(token: String?) {
resetPasswordLauncher.launch(ResetPasswordActivity.newIntent(this@LoginActivity, getText(binding.loginUsernameText), token))
}
override fun error(caught: Throwable) {
showProgressBar(false)
if (caught is LoginFailedException) {
FeedbackUtil.showError(this@LoginActivity, caught)
} else {
showError(caught)
}
}
}
private fun showProgressBar(enable: Boolean) {
binding.viewProgressBar.visibility = if (enable) View.VISIBLE else View.GONE
binding.loginButton.isEnabled = !enable
binding.loginButton.setText(if (enable) R.string.login_in_progress_dialog_message else R.string.menu_login)
}
private fun showError(caught: Throwable) {
binding.viewLoginError.setError(caught)
binding.viewLoginError.visibility = View.VISIBLE
}
companion object {
const val RESULT_LOGIN_SUCCESS = 1
const val RESULT_LOGIN_FAIL = 2
const val LOGIN_REQUEST_SOURCE = "login_request_source"
const val EDIT_SESSION_TOKEN = "edit_session_token"
fun newIntent(context: Context, source: String, token: String? = null): Intent {
return Intent(context, LoginActivity::class.java)
.putExtra(LOGIN_REQUEST_SOURCE, source)
.putExtra(EDIT_SESSION_TOKEN, token)
}
}
}
| apache-2.0 | febf24e206c32e4961aaf2ef871a147b | 40.357143 | 140 | 0.689215 | 5.151755 | false | false | false | false |
QingMings/flashair | src/main/kotlin/com/iezview/service/DownLoadService.kt | 1 | 1231 | package com.iezview.service
import com.iezview.controller.SolutionController
import com.iezview.model.Camera
import com.iezview.util.API
import javafx.concurrent.Service
import javafx.concurrent.Task
import tornadofx.*
/**
* Created by shishifanbuxie on 2017/4/23.
* 下载文件服务
*/
class DownLoadService(camera: Camera, solutionController: SolutionController): Service<String>() {
var c=camera
val api= Rest()
var sc=solutionController
override fun createTask(): Task<String> {
return object: DownLoadTask<String>(c,api,sc){}
}
}
/**
* 下载文件任务
*/
open class DownLoadTask<String>(camera: Camera, api: Rest, solutionController: SolutionController): Task<kotlin.String>(){
val queue=camera.queue
var api=api// 网络访问 每个相机一个实例,互不干扰
val c=camera//方案控制器
val sc=solutionController //当前相机
override fun call(): kotlin.String {
api.engine.requestInterceptor={(it as HttpURLRequest).connection.readTimeout=10000}
api.baseURI="${API.Base}${c.ipProperty().value}"
while (true){
val filepath=queue.take()
sc.downloadJPG(filepath,api,c)
}
return ""
}
} | mit | f855ffbe90bfc544e9e728ce0d4860ef | 25.272727 | 122 | 0.690909 | 3.678344 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/AlbumPrivacy.kt | 1 | 845 | @file:JvmName("AlbumPrivacyUtils")
package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.enums.AlbumViewPrivacyType
import com.vimeo.networking2.enums.asEnum
/**
* The privacy set for an album.
*
* @param password The privacy-enabled password to see this album. Present only when privacy.view is password.
* @param viewPrivacy Who can view the album. See [AlbumPrivacy.viewPrivacyType].
*/
@JsonClass(generateAdapter = true)
data class AlbumPrivacy(
@Json(name = "password")
val password: String? = null,
@Json(name = "view")
val viewPrivacy: String? = null
)
/**
* @see AlbumPrivacy.viewPrivacy
* @see AlbumViewPrivacyType
*/
val AlbumPrivacy.viewPrivacyType: AlbumViewPrivacyType
get() = viewPrivacy.asEnum(AlbumViewPrivacyType.UNKNOWN)
| mit | 9026759b479664bb05caa33aa6d54a99 | 26.258065 | 110 | 0.757396 | 3.789238 | false | false | false | false |
AndroidX/androidx | collection/collection/src/nativeMain/kotlin/androidx/collection/SparseArrayCompat.native.kt | 3 | 9945 | /*
* 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.collection
import androidx.collection.internal.EMPTY_INTS
import androidx.collection.internal.EMPTY_OBJECTS
import androidx.collection.internal.idealIntArraySize
/**
* SparseArrays map integers to Objects. Unlike a normal array of Objects,
* there can be gaps in the indices. It is intended to be more memory efficient
* than using a HashMap to map Integers to Objects, both because it avoids
* auto-boxing keys and its data structure doesn't rely on an extra entry object
* for each mapping.
*
* Note that this container keeps its mappings in an array data structure,
* using a binary search to find keys. The implementation is not intended to be appropriate for
* data structures
* that may contain large numbers of items. It is generally slower than a traditional
* HashMap, since lookups require a binary search and adds and removes require inserting
* and deleting entries in the array. For containers holding up to hundreds of items,
* the performance difference is not significant, less than 50%.
*
* To help with performance, the container includes an optimization when removing
* keys: instead of compacting its array immediately, it leaves the removed entry marked
* as deleted. The entry can then be re-used for the same key, or compacted later in
* a single garbage collection step of all removed entries. This garbage collection will
* need to be performed at any time the array needs to be grown or the map size or
* entry values are retrieved.
*
* It is possible to iterate over the items in this container using [keyAt] and [valueAt].
* Iterating over the keys using [keyAt] with ascending values of the index will return the
* keys in ascending order, or the values corresponding to the keys in ascending
* order in the case of [valueAt].
*
* @constructor Creates a new SparseArray containing no mappings that will not require any
* additional memory allocation to store the specified number of mappings. If you supply an initial
* capacity of 0, the sparse array will be initialized with a light-weight representation not
* requiring any additional array allocations.
*
* @param initialCapacity initial capacity of the array. The array will not require any additional
* memory allocation to store the specified number of mappings. If you supply an initialCapacity of
* 0, the sparse array will be initialized with a light-weight representation not requiring any
* additional array allocations. Default initialCapacity is 10.
*/
public actual open class SparseArrayCompat<E> public actual constructor(initialCapacity: Int) {
internal actual var garbage = false
internal actual var keys: IntArray
internal actual var values: Array<Any?>
internal actual var size = 0
init {
if (initialCapacity == 0) {
keys = EMPTY_INTS
values = EMPTY_OBJECTS
} else {
val capacity = idealIntArraySize(initialCapacity)
keys = IntArray(capacity)
values = arrayOfNulls(capacity)
}
}
/**
* Gets the Object mapped from the specified key, or `null` if no such mapping has been made.
*/
public actual open operator fun get(key: Int): E? = commonGet(key)
/**
* Gets the Object mapped from the specified [key], or [defaultValue] if no such mapping
* has been made.
*/
public actual open fun get(key: Int, defaultValue: E): E = commonGet(key, defaultValue)
/**
* Removes the mapping from the specified key, if there was any.
*/
public actual open fun remove(key: Int): Unit = commonRemove(key)
/**
* Remove an existing key from the array map only if it is currently mapped to [value].
* @param key The key of the mapping to remove.
* @param value The value expected to be mapped to the key.
* @return Returns `true` if the mapping was removed.
*/
// Note: value is Any? here for JVM source compatibility.
public actual open fun remove(key: Int, value: Any?): Boolean = commonRemove(key, value)
/**
* Removes the mapping at the specified index.
*/
public actual open fun removeAt(index: Int): Unit = commonRemoveAt(index)
/**
* Remove a range of mappings as a batch.
*
* @param index Index to begin at
* @param size Number of mappings to remove
*/
public actual open fun removeAtRange(index: Int, size: Int): Unit =
commonRemoveAtRange(index, size)
/**
* Replace the mapping for [key] only if it is already mapped to a value.
* @param key The key of the mapping to replace.
* @param value The value to store for the given key.
* @return Returns the previous mapped value or `null`.
*/
public actual open fun replace(key: Int, value: E): E? = commonReplace(key, value)
/**
* Replace the mapping for [key] only if it is already mapped to a value.
*
* @param key The key of the mapping to replace.
* @param oldValue The value expected to be mapped to the key.
* @param newValue The value to store for the given key.
* @return Returns `true` if the value was replaced.
*/
public actual open fun replace(key: Int, oldValue: E, newValue: E): Boolean =
commonReplace(key, oldValue, newValue)
/**
* Adds a mapping from the specified key to the specified [value], replacing the previous
* mapping from the specified [key] if there was one.
*/
public actual open fun put(key: Int, value: E): Unit = commonPut(key, value)
/**
* Copies all of the mappings from the [other] to this map. The effect of this call is
* equivalent to that of calling [put] on this map once for each mapping from key to value in
* [other].
*/
public actual open fun putAll(other: SparseArrayCompat<out E>): Unit = commonPutAll(other)
/**
* Add a new value to the array map only if the key does not already have a value or it is
* mapped to `null`.
* @param key The key under which to store the value.
* @param value The value to store for the given key.
* @return Returns the value that was stored for the given key, or `null` if there
* was no such key.
*/
public actual open fun putIfAbsent(key: Int, value: E): E? = commonPutIfAbsent(key, value)
/**
* Returns the number of key-value mappings that this SparseArray currently stores.
*/
public actual open fun size(): Int = commonSize()
/**
* Return true if [size] is 0.
* @return true if [size] is 0.
*/
public actual open fun isEmpty(): Boolean = commonIsEmpty()
/**
* Given an index in the range `0...size()-1`, returns
* the key from the [index]th key-value mapping that this
* SparseArray stores.
*/
public actual open fun keyAt(index: Int): Int = commonKeyAt(index)
/**
* Given an index in the range `0...size()-1`, returns the value from the [index]th key-value
* mapping that this SparseArray stores.
*/
public actual open fun valueAt(index: Int): E = commonValueAt(index)
/**
* Given an index in the range `0...size()-1`, sets a new value for the [index]th key-value
* mapping that this SparseArray stores.
*/
public actual open fun setValueAt(index: Int, value: E): Unit = commonSetValueAt(index, value)
/**
* Returns the index for which [keyAt] would return the specified [key], or a negative number if
* the specified [key] is not mapped.
*
* @param key the key to search for
* @return the index for which [keyAt] would return the specified [key], or a negative number if
* the specified [key] is not mapped
*/
public actual open fun indexOfKey(key: Int): Int = commonIndexOfKey(key)
/**
* Returns an index for which [valueAt] would return the specified key, or a negative number if
* no keys map to the specified [value].
*
* Beware that this is a linear search, unlike lookups by key, and that multiple keys can map to
* the same value and this will find only one of them.
*
* Note also that unlike most collections' [indexOf] methods, this method compares values using
* `===` rather than [equals].
*/
public actual open fun indexOfValue(value: E): Int = commonIndexOfValue(value)
/** Returns true if the specified key is mapped. */
public actual open fun containsKey(key: Int): Boolean = commonContainsKey(key)
/** Returns true if the specified value is mapped from any key. */
public actual open fun containsValue(value: E): Boolean = commonContainsValue(value)
/**
* Removes all key-value mappings from this SparseArray.
*/
public actual open fun clear(): Unit = commonClear()
/**
* Puts a key/value pair into the array, optimizing for the case where
* the key is greater than all existing keys in the array.
*/
public actual open fun append(key: Int, value: E): Unit = commonAppend(key, value)
/**
* Returns a string representation of the object.
*
* This implementation composes a string by iterating over its mappings. If this map contains
* itself as a value, the string "(this Map)" will appear in its place.
*/
public actual override fun toString(): String = commonToString()
}
| apache-2.0 | 775f11e6463ca0c75c0f698aebc0efa6 | 41.5 | 100 | 0.689191 | 4.394609 | false | false | false | false |
noud02/Akatsuki | src/main/kotlin/moe/kyubey/akatsuki/commands/Reason.kt | 1 | 5417 | /*
* Copyright (c) 2017-2019 Yui
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package moe.kyubey.akatsuki.commands
import me.aurieh.ares.exposed.async.asyncTransaction
import moe.kyubey.akatsuki.Akatsuki
import moe.kyubey.akatsuki.annotations.Argument
import moe.kyubey.akatsuki.annotations.Arguments
import moe.kyubey.akatsuki.annotations.Load
import moe.kyubey.akatsuki.annotations.Perm
import moe.kyubey.akatsuki.db.schema.Modlogs
import moe.kyubey.akatsuki.entities.Command
import moe.kyubey.akatsuki.entities.Context
import moe.kyubey.akatsuki.utils.I18n
import net.dv8tion.jda.core.Permission
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.update
@Load
@Perm(Permission.MANAGE_SERVER)
@Arguments(
Argument("case", "string"),
Argument("reason", "string")
)
class Reason : Command() {
override val guildOnly = true
override val desc = "Give a reason for a case in modlogs."
override fun run(ctx: Context) {
if (ctx.storedGuild!!.modlogChannel == null) {
return ctx.send(
I18n.parse(
ctx.lang.getString("no_modlog_channel"),
mapOf("username" to ctx.author.name)
)
)
}
val reasonArg = ctx.args["reason"] as String
if (reasonArg.length > 512) {
return ctx.send(
I18n.parse(
ctx.lang.getString("reason_too_long"),
mapOf("username" to ctx.author.name)
)
)
}
val caseArg = (ctx.args["case"] as String).toLowerCase()
asyncTransaction(Akatsuki.pool) {
val cases = Modlogs.select { Modlogs.guildId eq ctx.guild!!.idLong }
val caseIds: List<Int> = when (caseArg) {
"l" -> listOf(cases.count())
else -> {
if (caseArg.toIntOrNull() == null) {
if (!caseArg.matches("\\d+\\.\\.\\d+".toRegex())) {
return@asyncTransaction
}
val first = caseArg.split("..")[0].toInt()
val second = caseArg.split("..")[1].toInt()
if (first > second) {
return@asyncTransaction ctx.send(
I18n.parse(
ctx.lang.getString("case_num_err"),
mapOf("username" to ctx.author.name)
)
)
}
var list = listOf<Int>()
for (i in first..second) {
list += i
}
list
} else
listOf(caseArg.toInt())
}
}
for (id in caseIds) {
Modlogs.update({ Modlogs.guildId.eq(ctx.guild!!.idLong) and Modlogs.caseId.eq(id) }) { it[reason] = reasonArg }
val log = cases.firstOrNull { it[Modlogs.caseId] == id }
if (log != null) {
ctx.guild!!
.getTextChannelById(ctx.storedGuild.modlogChannel ?: return@asyncTransaction)
.getMessageById(log[Modlogs.messageId])
.queue({
it.editMessage(
it.contentRaw.replace(
"\\*\\*Reason\\*\\*: .+\n\\*\\*Responsible moderator\\*\\*: .+".toRegex(),
"**Reason**: $reasonArg\n" +
"**Responsible moderator**: ${ctx.author.name}#${ctx.author.discriminator} (${ctx.author.id})"
)
).queue()
}) {
ctx.sendError(it)
it.printStackTrace()
}
}
}
ctx.send("\uD83D\uDC4C")
}.execute()
}
} | mit | 33522b4f3707593a26dce3fc381b5d52 | 38.838235 | 150 | 0.507846 | 4.853943 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/ui/ConsoleDimensionsSpec.kt | 1 | 8066 | /*
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
import batect.os.Dimensions
import batect.os.NativeMethods
import batect.os.NoConsoleException
import batect.os.SignalListener
import batect.os.unix.UnixNativeMethodException
import batect.testutils.createForEachTest
import batect.testutils.createLoggerForEachTest
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.runForEachTest
import com.natpryce.hamkrest.absent
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.throws
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import jnr.constants.platform.Errno
import jnr.constants.platform.Signal
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object ConsoleDimensionsSpec : Spek({
describe("console dimensions") {
val nativeMethods by createForEachTest { mock<NativeMethods>() }
val signalListener by createForEachTest { mock<SignalListener>() }
val logger by createLoggerForEachTest()
describe("when created") {
given("the current console dimensions are available") {
beforeEachTest { whenever(nativeMethods.getConsoleDimensions()).thenReturn(Dimensions(123, 456)) }
val dimensions by createForEachTest { ConsoleDimensions(nativeMethods, signalListener, logger) }
it("registers a listener for the SIGWINCH signal") {
verify(signalListener).start(eq(Signal.SIGWINCH), any())
}
it("returns the current dimensions when requested") {
assertThat(dimensions.current, equalTo(Dimensions(123, 456)))
}
}
given("the current console dimensions are not available because the terminal is not a TTY") {
beforeEachTest { whenever(nativeMethods.getConsoleDimensions()).thenThrow(NoConsoleException()) }
val dimensions by createForEachTest { ConsoleDimensions(nativeMethods, signalListener, logger) }
it("registers a listener for the SIGWINCH signal") {
verify(signalListener).start(eq(Signal.SIGWINCH), any())
}
it("returns null when the current dimensions are requested") {
assertThat(dimensions.current, absent())
}
}
given("the current console dimensions are not available for another reason") {
val exception = UnixNativeMethodException("ioctl", Errno.EEXIST)
beforeEachTest { whenever(nativeMethods.getConsoleDimensions()).thenThrow(exception) }
val dimensions by createForEachTest { ConsoleDimensions(nativeMethods, signalListener, logger) }
it("registers a listener for the SIGWINCH signal") {
verify(signalListener).start(eq(Signal.SIGWINCH), any())
}
it("throws an exception when the current dimensions are requested") {
assertThat({ dimensions.current }, throws<Throwable>(equalTo(exception)))
}
}
}
describe("when the console dimensions have not changed") {
beforeEachTest { whenever(nativeMethods.getConsoleDimensions()).thenReturn(Dimensions(123, 456)) }
val dimensions by createForEachTest { ConsoleDimensions(nativeMethods, signalListener, logger) }
beforeEachTest { repeat(10) { dimensions.current } }
it("does not query the operating system multiple times") {
verify(nativeMethods, times(1)).getConsoleDimensions()
}
}
describe("when the console dimensions change") {
beforeEachTest { whenever(nativeMethods.getConsoleDimensions()).thenReturn(Dimensions(1, 1)) }
val dimensions by createForEachTest { ConsoleDimensions(nativeMethods, signalListener, logger) }
val signalHandler by runForEachTest {
val handlerCaptor = argumentCaptor<() -> Unit>()
verify(signalListener).start(eq(Signal.SIGWINCH), handlerCaptor.capture())
handlerCaptor.firstValue
}
given("the current console dimensions are available") {
var notifiedListener = false
beforeEachTest {
whenever(nativeMethods.getConsoleDimensions()).thenReturn(Dimensions(123, 456))
dimensions.registerListener { notifiedListener = true }
signalHandler()
}
it("returns the updated dimensions when requested") {
assertThat(dimensions.current, equalTo(Dimensions(123, 456)))
}
it("notifies any registered listeners that the dimensions have changed") {
assertThat(notifiedListener, equalTo(true))
}
}
given("the current console dimensions are not available because the terminal is not a TTY") {
var notifiedListener = false
beforeEachTest {
whenever(nativeMethods.getConsoleDimensions()).thenThrow(NoConsoleException())
dimensions.registerListener { notifiedListener = true }
signalHandler()
}
it("returns null when the current dimensions are requested") {
assertThat(dimensions.current, absent())
}
it("notifies any registered listeners that the dimensions have changed") {
assertThat(notifiedListener, equalTo(true))
}
}
given("the current console dimensions are not available for another reason") {
val exception = UnixNativeMethodException("ioctl", Errno.EEXIST)
beforeEachTest {
whenever(nativeMethods.getConsoleDimensions()).thenThrow(exception)
signalHandler()
}
it("throws an exception when the current dimensions are requested") {
assertThat({ dimensions.current }, throws<Throwable>(equalTo(exception)))
}
}
}
describe("after removing a change listener") {
beforeEachTest { whenever(nativeMethods.getConsoleDimensions()).thenReturn(Dimensions(123, 456)) }
val dimensions by createForEachTest { ConsoleDimensions(nativeMethods, signalListener, logger) }
val signalHandler by runForEachTest {
val handlerCaptor = argumentCaptor<() -> Unit>()
verify(signalListener).start(eq(Signal.SIGWINCH), handlerCaptor.capture())
handlerCaptor.firstValue
}
var notifiedListener = false
beforeEachTest {
val cleanup = dimensions.registerListener { notifiedListener = true }
cleanup.close()
signalHandler()
}
it("does not receive a notification when the console dimensions change") {
assertThat(notifiedListener, equalTo(false))
}
}
}
})
| apache-2.0 | f74ee642088f53a66a5aebff2a59d6e2 | 39.532663 | 114 | 0.637987 | 5.736842 | false | true | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/maps/clustering/ScoutingGroepController.kt | 1 | 5371 | package nl.rsdt.japp.jotial.maps.clustering
import android.os.Bundle
import android.util.Log
import com.google.gson.reflect.TypeToken
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.IntentCreatable
import nl.rsdt.japp.jotial.Recreatable
import nl.rsdt.japp.jotial.data.structures.area348.ScoutingGroepInfo
import nl.rsdt.japp.jotial.io.AppData
import nl.rsdt.japp.jotial.maps.clustering.osm.OsmScoutingGroepClusterManager
import nl.rsdt.japp.jotial.maps.management.MapItemUpdatable
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap
import nl.rsdt.japp.jotial.maps.wrapper.google.GoogleJotiMap
import nl.rsdt.japp.jotial.maps.wrapper.osm.OsmJotiMap
import nl.rsdt.japp.jotial.net.apis.ScoutingGroepApi
import nl.rsdt.japp.service.cloud.data.UpdateInfo
import org.acra.ktx.sendWithAcra
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.*
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 29-8-2016
* Description...
*/
class ScoutingGroepController : Recreatable, IntentCreatable, MapItemUpdatable<ArrayList<ScoutingGroepInfo>>, Callback<ArrayList<ScoutingGroepInfo>> {
var clusterManager: ClusterManagerInterface? = null
protected set
internal var buffer: ArrayList<ScoutingGroepInfo>? = ArrayList()
override fun onIntentCreate(bundle: Bundle) {
if (bundle.containsKey(BUNDLE_ID)) {
val localBuffer: ArrayList<ScoutingGroepInfo> = bundle.getParcelableArrayList(BUNDLE_ID)!!
buffer = localBuffer
if (clusterManager != null) {
clusterManager!!.addItems(localBuffer)
clusterManager!!.cluster()
buffer = null
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
if (savedInstanceState?.containsKey(BUNDLE_ID) ==true) {
val items = savedInstanceState.getParcelableArrayList<ScoutingGroepInfo>(BUNDLE_ID)
if (items != null && !items.isEmpty()) {
if (clusterManager != null) {
clusterManager!!.addItems(items)
clusterManager!!.cluster()
} else {
buffer = items
}
}
}
}
override fun onSaveInstanceState(saveInstanceState: Bundle?) {
if (clusterManager != null) {
val items = clusterManager!!.items
if (items is ArrayList<*>) {
saveInstanceState?.putParcelableArrayList(BUNDLE_ID, items as ArrayList<ScoutingGroepInfo?>)
} else {
saveInstanceState?.putParcelableArrayList(BUNDLE_ID, ArrayList(items))
}
}
}
fun onMapReady(jotiMap: IJotiMap) {
when (jotiMap) {
is GoogleJotiMap -> clusterManager = ScoutingGroepClusterManager(Japp.instance!!, jotiMap?.googleMap!!)
is OsmJotiMap -> clusterManager = OsmScoutingGroepClusterManager(jotiMap)
else -> clusterManager = NoneClusterManager()
}
val lBuffer = buffer
if (lBuffer != null) {
clusterManager!!.addItems(lBuffer)
clusterManager!!.cluster()
buffer = null
}
}
override fun onResponse(call: Call<ArrayList<ScoutingGroepInfo>>, response: Response<ArrayList<ScoutingGroepInfo>>) {
if (response.code() == 200) {
if (clusterManager != null) {
if (clusterManager!!.items.isEmpty()) {
response.body()?.also { clusterManager!!.addItems(it) }
} else {
clusterManager!!.clearItems()
response.body()?.also { clusterManager!!.addItems(it) }
}
} else {
buffer = response.body()
}
AppData.saveObjectAsJsonInBackground(response.body(), STORAGE_ID)
}
}
override fun onFailure(call: Call<ArrayList<ScoutingGroepInfo>>, t: Throwable) {
Log.e(TAG, t.toString(), t)
t.sendWithAcra()
}
override fun update(mode: String, callback: Callback<ArrayList<ScoutingGroepInfo>>) {
val api = Japp.getApi(ScoutingGroepApi::class.java)
when (mode) {
MapItemUpdatable.MODE_ALL -> api.getAll(JappPreferences.accountKey).enqueue(callback)
MapItemUpdatable.MODE_LATEST -> api.getAll(JappPreferences.accountKey).enqueue(callback)
}
}
override fun onUpdateInvoked() {
update(MapItemUpdatable.MODE_ALL, this)
}
override fun onUpdateMessage(info: UpdateInfo) {
val call: Call<ArrayList<ScoutingGroepInfo>>?
when (info.type) {
UpdateInfo.ACTION_NEW -> update(MapItemUpdatable.MODE_ALL, this)
UpdateInfo.ACTION_UPDATE -> update(MapItemUpdatable.MODE_ALL, this)
}
}
companion object {
val TAG = "ScoutingGroepController"
val STORAGE_ID = "SC"
val BUNDLE_ID = "SC"
fun loadAndPutToBundle(bundle: Bundle) {
val list = AppData.getObject<ArrayList<ScoutingGroepInfo>>(STORAGE_ID,
object : TypeToken<ArrayList<ScoutingGroepInfo>>() {}.type)
if (list != null && list.isNotEmpty()) {
bundle.putParcelableArrayList(BUNDLE_ID, list)
}
}
}
}
| apache-2.0 | 90bd50409d0e59b62bf89a14e1fd1653 | 34.569536 | 150 | 0.634705 | 4.356042 | false | false | false | false |
michael71/LanbahnPanel | app/src/main/java/de/blankedv/lanbahnpanel/elements/PanelElement.kt | 1 | 11449 | package de.blankedv.lanbahnpanel.elements
import android.graphics.Canvas
import android.graphics.Point
import android.graphics.Rect
import android.preference.PreferenceManager
import android.util.Log
import de.blankedv.lanbahnpanel.util.LPaints
import de.blankedv.lanbahnpanel.model.*
/**
* generic panel element - this can be a passive (never changing)
* panel element or an active (lanbahn status dependent)
* element.
*
* @author mblank
*/
open class PanelElement {
var name = ""
var x: Int = 0 // starting point
var y: Int = 0
var x2 = INVALID_INT // endpoint - x2 always >x
var y2 = INVALID_INT
var xt = INVALID_INT // "thrown" position for turnout
var yt = INVALID_INT
var adr = INVALID_INT
var adr2 = INVALID_INT // needed for DCC sensors and signals
var state = STATE_UNKNOWN
var train = INVALID_INT // train number displayed on track or sensor
var nbit = 1 // for multi-aspect signals, nbit=2 => 4 possible values 0,1,2,3
var inRoute = false // handled separately because sensors often have
// 2 different addresses, one covering a real SX address (=occupied) and a second
// virtual (lanbahn) address with the inroute info
var route = ""
var invert = DISP_STANDARD // not inverted
var invert2 = DISP_STANDARD // ONLY for elements with secondary address
/** get the type-name which is used in the XML panel definition file
*
* @return
*/
val type: String
get() {
val className = this.javaClass.simpleName
when (className) {
"SignalElement" -> return "signal"
"PanelElement" -> return "track"
"TurnoutElement" -> return "turnout"
"SensorElement" -> return "sensor"
"ActivePanelElement" -> return "other"
"RouteButtonElement" -> return "routebutton"
"DoubleslipElement" -> return "doubleslip"
else -> {
Log.d(TAG, "could not determine type of panel element")
return "error"
}
}
}
constructor()
constructor(x: Int, y: Int) {
this.x = x
this.y = y
name = ""
}
constructor(poi: Point, closed: Point, thrown: Point) {
this.x = poi.x
this.y = poi.y
this.x2 = closed.x
this.y2 = closed.y
this.xt = thrown.x
this.yt = thrown.y
name = ""
}
open fun doDraw(canvas: Canvas) {
if (y == y2) { // horizontal line
// draw a line and not a bitmap
canvas.drawLine((x * prescale).toFloat(), (y * prescale).toFloat(), (x2 * prescale).toFloat(), (y2 * prescale).toFloat(), LPaints.linePaint)
} else { // diagonal, draw with round stroke
canvas.drawLine((x * prescale).toFloat(), (y * prescale).toFloat(), (x2 * prescale).toFloat(), (y2 * prescale).toFloat(), LPaints.linePaint2)
}
}
open fun isSelected(lastTouchX: Int, lastTouchY: Int): Boolean {
return false
}
open fun setExpired() {
// do nothing for non changing element
}
open fun isExpired() : Boolean {
return false // non changing element
}
open fun toggle() {
// do nothing for non changing element
}
open fun hasAdrX(address: Int): Boolean {
return false
}
open fun updateData(data: Int) {
// do nothing for non changing element
}
companion object {
var flipState : Boolean = true
/* NOT WORKING if there are 2 Panel Elements with identical address !!!
i.e. works for signals, but certainly not for turnouts */
fun getFirstPeByAddress(address: Int): PanelElement? {
for (pe in panelElements) {
if (pe.adr == address) {
return pe
}
}
return null
}
fun getAllPesByAddress(address: Int) : List<PanelElement> {
return panelElements.filter { it.adr == address}
}
fun update(addr: Int, data: Int) {
for (pe in panelElements.filter { it.adr == addr }) {
pe.state = data
}
}
fun updateAcc(addr: Int, data: Int) {
for (pe in panelElements.filter { it.adr == addr }
.filter { (it is SignalElement) or (it is TurnoutElement) or (it is DoubleslipElement) }) {
pe.state = data
}
}
// both the value for the primary sensor address "adr" and the secondary "adr2" are updated
fun updateSensor(addr: Int, data: Int) {
for (pe in panelElements.filter { it.adr == addr }.filter { it is SensorElement }) {
pe.state = data // used for "occupied" info
}
for (pe in panelElements.filter { it.adr2 == addr }.filter { it is SensorElement }) {
pe.inRoute = data != 0 // used for "inRoute" info
}
}
fun updateSensorTrain(addr: Int, data: Int) {
var found = false
for (pe in panelElements.filter { it.adr == addr }.filter { it is SensorElement }) {
pe.train = data // used for train info
if (DEBUG) Log.d(TAG,"pe(adr=${pe.adr}) set to train=$data")
found = true
}
if (!found) Log.d(TAG, "pe(adr=${addr}) not found in sensors")
}
/** relocate panel origin for better fit on display and for possible "upside down"
* display (=view from other side of the layout -
*
*/
fun relocatePanelOrigin() {
// in WriteConfig the NEW values are written !!
if (DEBUG) Log.d(TAG,"relocatePanelOrigin")
val rec = getMinMaxXY()
if (DEBUG) {
Log.d(TAG, "relocatePanelOrigin: before adding 10: xmin=" + (rec.left) + " xmax="
+ (rec.right) + " ymin=" + (rec.top) + " ymax=" + (rec.bottom) + " ----------------")
}
// now move origin to (10,10)
val deltaX = 10 - rec.left
val deltaY = 10 - rec.top
if (DEBUG) {
Log.d(TAG, "relocatePanelOrigin: move by dx=" + deltaX + " dy=" + deltaY + " ----------------")
}
for (pe in panelElements) {
if (pe.x != INVALID_INT)
pe.x += deltaX
if (pe.x2 != INVALID_INT)
pe.x2 += deltaX
if (pe.xt != INVALID_INT)
pe.xt += deltaX
if (pe.y != INVALID_INT)
pe.y += deltaY
if (pe.y2 != INVALID_INT)
pe.y2 += deltaY
if (pe.yt != INVALID_INT)
pe.yt += deltaY
if (pe is DoubleslipElement) {
pe.initDxEtc()
}
}
panelRect = Rect(0, 0, (rec.right + deltaX + 10) * prescale, (rec.bottom + deltaY + 10) * prescale)
if (DEBUG) {
Log.d(TAG, "relocatePanelOrigin: after origin move mult by prescale (incl border) xmin=" + panelRect.left + " xmax="
+ panelRect.right + " ymin=" + panelRect.top
+ " ymax=" + panelRect.bottom + " ----------------")
}
configHasChanged = true
}
/** flip current panel elements upside down, current state (flipped or
* original) is stored in flipState variable
*
*/
fun flipPanel() {
// in WriteConfig the NEW values are written !!
if (DEBUG) Log.d(TAG,"flipPanel (toggle)")
flipState = !flipState
val rec = getMinMaxXY()
for (pe in panelElements) {
if (pe.x != INVALID_INT)
pe.x = 10 + (rec.right - pe.x)
if (pe.x2 != INVALID_INT)
pe.x2 = 10 + (rec.right - pe.x2)
if (pe.xt != INVALID_INT)
pe.xt = 10 + (rec.right - pe.xt)
if (pe.y != INVALID_INT)
pe.y = 10 + (rec.bottom - pe.y)
if (pe.y2 != INVALID_INT)
pe.y2 = 10 + (rec.bottom - pe.y2)
if (pe.yt != INVALID_INT)
pe.yt = 10 + (rec.bottom - pe.yt)
}
panelRect = Rect(0, 0, (rec.right) * prescale, (rec.bottom) * prescale)
if (DEBUG) {
Log.d(TAG, "flipPanel: new Rect (should be equal old Rect!) " + panelRect.left + " xmax="
+ panelRect.right + " ymin=" + panelRect.top
+ " ymax=" + panelRect.bottom + " ----------------")
}
configHasChanged = true
}
fun printPES() {
var i = 0
Log.d(TAG, "pe# " + "(x,x2)/(y,y2)")
for (pe in panelElements) {
Log.d(TAG, "pe#" + i + "(" + pe.x + "," + pe.x2 + ")/(" + pe.y + "," + pe.y2 + ")")
i++
}
}
fun printTracks() {
var i = 0
Log.d(TAG, "pe# " + "(x,x2)/(y,y2)")
for (pe in panelElements.filter { !(it is ActivePanelElement) }) {
Log.d(TAG, "pe#" + i + "(" + pe.x + "," + pe.x2 + ")/(" + pe.y + "," + pe.y2 + ")")
i++
}
}
private fun getMinMaxXY() : Rect {
var xmin = INVALID_INT // = left
var xmax = INVALID_INT // = right
var ymin = INVALID_INT // = top
var ymax = INVALID_INT // = bottom
var first = true
for (pe in panelElements) {
if (first) {
xmax = pe.x
xmin = xmax
ymax = pe.y
ymin = ymax
first = false
}
if (pe.x != INVALID_INT && pe.x < xmin)
xmin = pe.x
if (pe.x != INVALID_INT && pe.x > xmax)
xmax = pe.x
if (pe.x2 != INVALID_INT && pe.x2 < xmin)
xmin = pe.x2
if (pe.x2 != INVALID_INT && pe.x2 > xmax)
xmax = pe.x2
if (pe.xt != INVALID_INT && pe.xt < xmin)
xmin = pe.xt
if (pe.xt != INVALID_INT && pe.xt > xmax)
xmax = pe.xt
if (pe.y != INVALID_INT && pe.y < ymin)
ymin = pe.y
if (pe.y != INVALID_INT && pe.y > ymax)
ymax = pe.y
if (pe.y2 != INVALID_INT && pe.y2 < ymin)
ymin = pe.y2
if (pe.y2 != INVALID_INT && pe.y2 > ymax)
ymax = pe.y2
if (pe.yt != INVALID_INT && pe.yt < ymin)
ymin = pe.yt
if (pe.yt != INVALID_INT && pe.yt > ymax)
ymax = pe.yt
}
if (DEBUG) {
Log.d(TAG, "getMinMaxXY: xmin=" + xmin + " xmax="
+ xmax + " ymin=" + ymin
+ " ymax=" + ymax )
}
return Rect(xmin,ymin,xmax,ymax)
}
}
}
| gpl-3.0 | 67ed043be5aa86cfe194ec46b3769eaa | 34.119632 | 153 | 0.469648 | 4.008754 | false | false | false | false |
pbreault/adb-idea | src/main/kotlin/com/developerphil/adbidea/adb/command/GrantPermissionsCommand.kt | 1 | 2894 | package com.developerphil.adbidea.adb.command
import com.android.ddmlib.IDevice
import com.developerphil.adbidea.adb.AdbUtil
import com.developerphil.adbidea.adb.command.receiver.GenericReceiver
import com.developerphil.adbidea.ui.NotificationHelper
import com.intellij.openapi.project.Project
import org.jetbrains.android.facet.AndroidFacet
import java.util.*
import java.util.concurrent.TimeUnit
import java.util.function.Consumer
class GrantPermissionsCommand : Command {
override fun run(project: Project, device: IDevice, facet: AndroidFacet, packageName: String): Boolean {
try {
if (deviceHasMarshmallow(device)) if (AdbUtil.isAppInstalled(device, packageName)) {
val shellOutputReceiver = GenericReceiver()
device.executeShellCommand("dumpsys package $packageName", shellOutputReceiver, 15L, TimeUnit.SECONDS)
val adbOutputLines = getRequestedPermissions(shellOutputReceiver.adbOutputLines)
NotificationHelper.info(adbOutputLines.toTypedArray().contentToString())
adbOutputLines.forEach(Consumer { s: String ->
try {
device.executeShellCommand("pm grant $packageName $s", GenericReceiver(), 15L, TimeUnit.SECONDS)
NotificationHelper.info(String.format("Permission <b>%s</b> granted on %s", s, device.name))
} catch (e: Exception) {
NotificationHelper.error(String.format("Granting %s failed on %s: %s", s, device.name, e.message))
}
})
return true
} else {
NotificationHelper.error(String.format("<b>%s</b> is not installed on %s", packageName, device.name))
} else {
NotificationHelper.error(String.format("%s must be at least api level 23", device.name))
}
} catch (e1: Exception) {
NotificationHelper.error("Granting permissions fail... " + e1.message)
}
return false
}
private fun deviceHasMarshmallow(device: IDevice): Boolean {
return device.version.apiLevel >= 23
}
private fun getRequestedPermissions(list: List<String>): List<String> {
var requestedPermissionsSection = false
val requestPermissions: MutableList<String> = ArrayList()
for (s in list) {
if (!s.contains(".permission.")) {
requestedPermissionsSection = false
}
if (s.contains("requested permissions:")) {
requestedPermissionsSection = true
continue
}
if (requestedPermissionsSection) {
val permissionName = s.replace(":", "").trim { it <= ' ' }
requestPermissions.add(permissionName)
}
}
return requestPermissions
}
} | apache-2.0 | 3731e067b41c398ca2ad635462ca595b | 44.952381 | 122 | 0.625432 | 4.930153 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/selection/SelectionManager.kt | 3 | 36078 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package androidx.compose.foundation.text.selection
import androidx.compose.foundation.fastFold
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.text.Handle
import androidx.compose.foundation.text.TextDragObserver
import androidx.compose.foundation.text.selection.Selection.AnchorInfo
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.hapticfeedback.HapticFeedback
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.key.KeyEvent
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.input.pointer.PointerInputScope
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInWindow
import androidx.compose.ui.platform.ClipboardManager
import androidx.compose.ui.platform.TextToolbar
import androidx.compose.ui.platform.TextToolbarStatus
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.unit.IntSize
import kotlin.math.absoluteValue
import kotlin.math.max
import kotlin.math.min
/**
* A bridge class between user interaction to the text composables for text selection.
*/
internal class SelectionManager(private val selectionRegistrar: SelectionRegistrarImpl) {
private val _selection: MutableState<Selection?> = mutableStateOf(null)
/**
* The current selection.
*/
var selection: Selection?
get() = _selection.value
set(value) {
_selection.value = value
if (value != null) {
updateHandleOffsets()
}
}
/**
* Is touch mode active
*/
var touchMode: Boolean = true
/**
* The manager will invoke this every time it comes to the conclusion that the selection should
* change. The expectation is that this callback will end up causing `setSelection` to get
* called. This is what makes this a "controlled component".
*/
var onSelectionChange: (Selection?) -> Unit = {}
/**
* [HapticFeedback] handle to perform haptic feedback.
*/
var hapticFeedBack: HapticFeedback? = null
/**
* [ClipboardManager] to perform clipboard features.
*/
var clipboardManager: ClipboardManager? = null
/**
* [TextToolbar] to show floating toolbar(post-M) or primary toolbar(pre-M).
*/
var textToolbar: TextToolbar? = null
/**
* Focus requester used to request focus when selection becomes active.
*/
var focusRequester: FocusRequester = FocusRequester()
/**
* Return true if the corresponding SelectionContainer is focused.
*/
var hasFocus: Boolean by mutableStateOf(false)
/**
* Modifier for selection container.
*/
val modifier
get() = Modifier
.onClearSelectionRequested { onRelease() }
.onGloballyPositioned { containerLayoutCoordinates = it }
.focusRequester(focusRequester)
.onFocusChanged { focusState ->
if (!focusState.isFocused && hasFocus) {
onRelease()
}
hasFocus = focusState.isFocused
}
.focusable()
.onKeyEvent {
if (isCopyKeyEvent(it)) {
copy()
true
} else {
false
}
}
.then(if (shouldShowMagnifier) Modifier.selectionMagnifier(this) else Modifier)
private var previousPosition: Offset? = null
/**
* Layout Coordinates of the selection container.
*/
var containerLayoutCoordinates: LayoutCoordinates? = null
set(value) {
field = value
if (hasFocus && selection != null) {
val positionInWindow = value?.positionInWindow()
if (previousPosition != positionInWindow) {
previousPosition = positionInWindow
updateHandleOffsets()
updateSelectionToolbarPosition()
}
}
}
/**
* The beginning position of the drag gesture. Every time a new drag gesture starts, it wil be
* recalculated.
*/
internal var dragBeginPosition by mutableStateOf(Offset.Zero)
private set
/**
* The total distance being dragged of the drag gesture. Every time a new drag gesture starts,
* it will be zeroed out.
*/
internal var dragTotalDistance by mutableStateOf(Offset.Zero)
private set
/**
* The calculated position of the start handle in the [SelectionContainer] coordinates. It
* is null when handle shouldn't be displayed.
* It is a [State] so reading it during the composition will cause recomposition every time
* the position has been changed.
*/
var startHandlePosition: Offset? by mutableStateOf(null)
private set
/**
* The calculated position of the end handle in the [SelectionContainer] coordinates. It
* is null when handle shouldn't be displayed.
* It is a [State] so reading it during the composition will cause recomposition every time
* the position has been changed.
*/
var endHandlePosition: Offset? by mutableStateOf(null)
private set
/**
* The handle that is currently being dragged, or null when no handle is being dragged. To get
* the position of the last drag event, use [currentDragPosition].
*/
var draggingHandle: Handle? by mutableStateOf(null)
private set
/**
* When a handle is being dragged (i.e. [draggingHandle] is non-null), this is the last position
* of the actual drag event. It is not clamped to handle positions. Null when not being dragged.
*/
var currentDragPosition: Offset? by mutableStateOf(null)
private set
private val shouldShowMagnifier get() = draggingHandle != null
init {
selectionRegistrar.onPositionChangeCallback = { selectableId ->
if (
selectableId == selection?.start?.selectableId ||
selectableId == selection?.end?.selectableId
) {
updateHandleOffsets()
updateSelectionToolbarPosition()
}
}
selectionRegistrar.onSelectionUpdateStartCallback =
{ layoutCoordinates, position, selectionMode ->
val positionInContainer = convertToContainerCoordinates(
layoutCoordinates,
position
)
if (positionInContainer != null) {
startSelection(
position = positionInContainer,
isStartHandle = false,
adjustment = selectionMode
)
focusRequester.requestFocus()
hideSelectionToolbar()
}
}
selectionRegistrar.onSelectionUpdateSelectAll =
{ selectableId ->
val (newSelection, newSubselection) = selectAll(
selectableId = selectableId,
previousSelection = selection,
)
if (newSelection != selection) {
selectionRegistrar.subselections = newSubselection
onSelectionChange(newSelection)
}
focusRequester.requestFocus()
hideSelectionToolbar()
}
selectionRegistrar.onSelectionUpdateCallback =
{ layoutCoordinates, newPosition, previousPosition, isStartHandle, selectionMode ->
val newPositionInContainer =
convertToContainerCoordinates(layoutCoordinates, newPosition)
val previousPositionInContainer =
convertToContainerCoordinates(layoutCoordinates, previousPosition)
updateSelection(
newPosition = newPositionInContainer,
previousPosition = previousPositionInContainer,
isStartHandle = isStartHandle,
adjustment = selectionMode
)
}
selectionRegistrar.onSelectionUpdateEndCallback = {
showSelectionToolbar()
// This property is set by updateSelection while dragging, so we need to clear it after
// the original selection drag.
draggingHandle = null
currentDragPosition = null
}
selectionRegistrar.onSelectableChangeCallback = { selectableKey ->
if (selectableKey in selectionRegistrar.subselections) {
// clear the selection range of each Selectable.
onRelease()
selection = null
}
}
selectionRegistrar.afterSelectableUnsubscribe = { selectableKey ->
if (
selectableKey == selection?.start?.selectableId ||
selectableKey == selection?.end?.selectableId
) {
// The selectable that contains a selection handle just unsubscribed.
// Hide selection handles for now
startHandlePosition = null
endHandlePosition = null
}
}
}
/**
* Returns the [Selectable] responsible for managing the given [AnchorInfo], or null if the
* anchor is not from a currently-registered [Selectable].
*/
internal fun getAnchorSelectable(anchor: AnchorInfo): Selectable? {
return selectionRegistrar.selectableMap[anchor.selectableId]
}
private fun updateHandleOffsets() {
val selection = selection
val containerCoordinates = containerLayoutCoordinates
val startSelectable = selection?.start?.let(::getAnchorSelectable)
val endSelectable = selection?.end?.let(::getAnchorSelectable)
val startLayoutCoordinates = startSelectable?.getLayoutCoordinates()
val endLayoutCoordinates = endSelectable?.getLayoutCoordinates()
if (
selection == null ||
containerCoordinates == null ||
!containerCoordinates.isAttached ||
startLayoutCoordinates == null ||
endLayoutCoordinates == null
) {
this.startHandlePosition = null
this.endHandlePosition = null
return
}
val startHandlePosition = containerCoordinates.localPositionOf(
startLayoutCoordinates,
startSelectable.getHandlePosition(
selection = selection,
isStartHandle = true
)
)
val endHandlePosition = containerCoordinates.localPositionOf(
endLayoutCoordinates,
endSelectable.getHandlePosition(
selection = selection,
isStartHandle = false
)
)
val visibleBounds = containerCoordinates.visibleBounds()
this.startHandlePosition =
if (visibleBounds.containsInclusive(startHandlePosition)) startHandlePosition else null
this.endHandlePosition =
if (visibleBounds.containsInclusive(endHandlePosition)) endHandlePosition else null
}
/**
* Returns non-nullable [containerLayoutCoordinates].
*/
internal fun requireContainerCoordinates(): LayoutCoordinates {
val coordinates = containerLayoutCoordinates
require(coordinates != null)
require(coordinates.isAttached)
return coordinates
}
internal fun selectAll(
selectableId: Long,
previousSelection: Selection?
): Pair<Selection?, Map<Long, Selection>> {
val subselections = mutableMapOf<Long, Selection>()
val newSelection = selectionRegistrar.sort(requireContainerCoordinates())
.fastFold(null) { mergedSelection: Selection?, selectable: Selectable ->
val selection = if (selectable.selectableId == selectableId)
selectable.getSelectAllSelection() else null
selection?.let { subselections[selectable.selectableId] = it }
merge(mergedSelection, selection)
}
if (newSelection != previousSelection) {
hapticFeedBack?.performHapticFeedback(HapticFeedbackType.TextHandleMove)
}
return Pair(newSelection, subselections)
}
internal fun getSelectedText(): AnnotatedString? {
val selectables = selectionRegistrar.sort(requireContainerCoordinates())
var selectedText: AnnotatedString? = null
selection?.let {
for (i in selectables.indices) {
val selectable = selectables[i]
// Continue if the current selectable is before the selection starts.
if (selectable.selectableId != it.start.selectableId &&
selectable.selectableId != it.end.selectableId &&
selectedText == null
) continue
val currentSelectedText = getCurrentSelectedText(
selectable = selectable,
selection = it
)
selectedText = selectedText?.plus(currentSelectedText) ?: currentSelectedText
// Break if the current selectable is the last selected selectable.
if (selectable.selectableId == it.end.selectableId && !it.handlesCrossed ||
selectable.selectableId == it.start.selectableId && it.handlesCrossed
) break
}
}
return selectedText
}
internal fun copy() {
val selectedText = getSelectedText()
selectedText?.let { clipboardManager?.setText(it) }
}
/**
* This function get the selected region as a Rectangle region, and pass it to [TextToolbar]
* to make the FloatingToolbar show up in the proper place. In addition, this function passes
* the copy method as a callback when "copy" is clicked.
*/
internal fun showSelectionToolbar() {
if (hasFocus) {
selection?.let {
textToolbar?.showMenu(
getContentRect(),
onCopyRequested = {
copy()
onRelease()
}
)
}
}
}
internal fun hideSelectionToolbar() {
if (hasFocus && textToolbar?.status == TextToolbarStatus.Shown) {
textToolbar?.hide()
}
}
private fun updateSelectionToolbarPosition() {
if (hasFocus && textToolbar?.status == TextToolbarStatus.Shown) {
showSelectionToolbar()
}
}
/**
* Calculate selected region as [Rect]. The top is the top of the first selected
* line, and the bottom is the bottom of the last selected line. The left is the leftmost
* handle's horizontal coordinates, and the right is the rightmost handle's coordinates.
*/
private fun getContentRect(): Rect {
val selection = selection ?: return Rect.Zero
val startSelectable = getAnchorSelectable(selection.start)
val endSelectable = getAnchorSelectable(selection.end)
val startLayoutCoordinates = startSelectable?.getLayoutCoordinates() ?: return Rect.Zero
val endLayoutCoordinates = endSelectable?.getLayoutCoordinates() ?: return Rect.Zero
val localLayoutCoordinates = containerLayoutCoordinates
if (localLayoutCoordinates != null && localLayoutCoordinates.isAttached) {
var startOffset = localLayoutCoordinates.localPositionOf(
startLayoutCoordinates,
startSelectable.getHandlePosition(
selection = selection,
isStartHandle = true
)
)
var endOffset = localLayoutCoordinates.localPositionOf(
endLayoutCoordinates,
endSelectable.getHandlePosition(
selection = selection,
isStartHandle = false
)
)
startOffset = localLayoutCoordinates.localToRoot(startOffset)
endOffset = localLayoutCoordinates.localToRoot(endOffset)
val left = min(startOffset.x, endOffset.x)
val right = max(startOffset.x, endOffset.x)
var startTop = localLayoutCoordinates.localPositionOf(
startLayoutCoordinates,
Offset(
0f,
startSelectable.getBoundingBox(selection.start.offset).top
)
)
var endTop = localLayoutCoordinates.localPositionOf(
endLayoutCoordinates,
Offset(
0.0f,
endSelectable.getBoundingBox(selection.end.offset).top
)
)
startTop = localLayoutCoordinates.localToRoot(startTop)
endTop = localLayoutCoordinates.localToRoot(endTop)
val top = min(startTop.y, endTop.y)
val bottom = max(startOffset.y, endOffset.y) + (HandleHeight.value * 4.0).toFloat()
return Rect(
left,
top,
right,
bottom
)
}
return Rect.Zero
}
// This is for PressGestureDetector to cancel the selection.
fun onRelease() {
selectionRegistrar.subselections = emptyMap()
hideSelectionToolbar()
if (selection != null) {
onSelectionChange(null)
hapticFeedBack?.performHapticFeedback(HapticFeedbackType.TextHandleMove)
}
}
fun handleDragObserver(isStartHandle: Boolean): TextDragObserver = object : TextDragObserver {
override fun onDown(point: Offset) {
val selection = selection ?: return
val anchor = if (isStartHandle) selection.start else selection.end
val selectable = getAnchorSelectable(anchor) ?: return
// The LayoutCoordinates of the composable where the drag gesture should begin. This
// is used to convert the position of the beginning of the drag gesture from the
// composable coordinates to selection container coordinates.
val beginLayoutCoordinates = selectable.getLayoutCoordinates() ?: return
// The position of the character where the drag gesture should begin. This is in
// the composable coordinates.
val beginCoordinates = getAdjustedCoordinates(
selectable.getHandlePosition(
selection = selection, isStartHandle = isStartHandle
)
)
// Convert the position where drag gesture begins from composable coordinates to
// selection container coordinates.
currentDragPosition = requireContainerCoordinates().localPositionOf(
beginLayoutCoordinates,
beginCoordinates
)
draggingHandle = if (isStartHandle) Handle.SelectionStart else Handle.SelectionEnd
}
override fun onUp() {
draggingHandle = null
currentDragPosition = null
}
override fun onStart(startPoint: Offset) {
hideSelectionToolbar()
val selection = selection!!
val startSelectable =
selectionRegistrar.selectableMap[selection.start.selectableId]
val endSelectable =
selectionRegistrar.selectableMap[selection.end.selectableId]
// The LayoutCoordinates of the composable where the drag gesture should begin. This
// is used to convert the position of the beginning of the drag gesture from the
// composable coordinates to selection container coordinates.
val beginLayoutCoordinates = if (isStartHandle) {
startSelectable?.getLayoutCoordinates()!!
} else {
endSelectable?.getLayoutCoordinates()!!
}
// The position of the character where the drag gesture should begin. This is in
// the composable coordinates.
val beginCoordinates = getAdjustedCoordinates(
if (isStartHandle) {
startSelectable!!.getHandlePosition(
selection = selection, isStartHandle = true
)
} else {
endSelectable!!.getHandlePosition(
selection = selection, isStartHandle = false
)
}
)
// Convert the position where drag gesture begins from composable coordinates to
// selection container coordinates.
dragBeginPosition = requireContainerCoordinates().localPositionOf(
beginLayoutCoordinates,
beginCoordinates
)
// Zero out the total distance that being dragged.
dragTotalDistance = Offset.Zero
}
override fun onDrag(delta: Offset) {
dragTotalDistance += delta
val endPosition = dragBeginPosition + dragTotalDistance
val consumed = updateSelection(
newPosition = endPosition,
previousPosition = dragBeginPosition,
isStartHandle = isStartHandle,
adjustment = SelectionAdjustment.CharacterWithWordAccelerate
)
if (consumed) {
dragBeginPosition = endPosition
dragTotalDistance = Offset.Zero
}
}
override fun onStop() {
showSelectionToolbar()
draggingHandle = null
currentDragPosition = null
}
override fun onCancel() {
showSelectionToolbar()
draggingHandle = null
currentDragPosition = null
}
}
/**
* Detect tap without consuming the up event.
*/
private suspend fun PointerInputScope.detectNonConsumingTap(onTap: (Offset) -> Unit) {
awaitEachGesture {
waitForUpOrCancellation()?.let {
onTap(it.position)
}
}
}
private fun Modifier.onClearSelectionRequested(block: () -> Unit): Modifier {
return if (hasFocus) pointerInput(Unit) { detectNonConsumingTap { block() } } else this
}
private fun convertToContainerCoordinates(
layoutCoordinates: LayoutCoordinates,
offset: Offset
): Offset? {
val coordinates = containerLayoutCoordinates
if (coordinates == null || !coordinates.isAttached) return null
return requireContainerCoordinates().localPositionOf(layoutCoordinates, offset)
}
/**
* Cancel the previous selection and start a new selection at the given [position].
* It's used for long-press, double-click, triple-click and so on to start selection.
*
* @param position initial position of the selection. Both start and end handle is considered
* at this position.
* @param isStartHandle whether it's considered as the start handle moving. This parameter
* will influence the [SelectionAdjustment]'s behavior. For example,
* [SelectionAdjustment.Character] only adjust the moving handle.
* @param adjustment the selection adjustment.
*/
private fun startSelection(
position: Offset,
isStartHandle: Boolean,
adjustment: SelectionAdjustment
) {
updateSelection(
startHandlePosition = position,
endHandlePosition = position,
previousHandlePosition = null,
isStartHandle = isStartHandle,
adjustment = adjustment
)
}
/**
* Updates the selection after one of the selection handle moved.
*
* @param newPosition the new position of the moving selection handle.
* @param previousPosition the previous position of the moving selection handle.
* @param isStartHandle whether the moving selection handle is the start handle.
* @param adjustment the [SelectionAdjustment] used to adjust the raw selection range and
* produce the final selection range.
*
* @return a boolean representing whether the movement is consumed.
*
* @see SelectionAdjustment
*/
internal fun updateSelection(
newPosition: Offset?,
previousPosition: Offset?,
isStartHandle: Boolean,
adjustment: SelectionAdjustment,
): Boolean {
if (newPosition == null) return false
val otherHandlePosition = selection?.let { selection ->
val otherSelectableId = if (isStartHandle) {
selection.end.selectableId
} else {
selection.start.selectableId
}
val otherSelectable =
selectionRegistrar.selectableMap[otherSelectableId] ?: return@let null
convertToContainerCoordinates(
otherSelectable.getLayoutCoordinates()!!,
getAdjustedCoordinates(
otherSelectable.getHandlePosition(selection, !isStartHandle)
)
)
} ?: return false
val startHandlePosition = if (isStartHandle) newPosition else otherHandlePosition
val endHandlePosition = if (isStartHandle) otherHandlePosition else newPosition
return updateSelection(
startHandlePosition = startHandlePosition,
endHandlePosition = endHandlePosition,
previousHandlePosition = previousPosition,
isStartHandle = isStartHandle,
adjustment = adjustment
)
}
/**
* Updates the selection after one of the selection handle moved.
*
* To make sure that [SelectionAdjustment] works correctly, it's expected that only one
* selection handle is updated each time. The only exception is that when a new selection is
* started. In this case, [previousHandlePosition] is always null.
*
* @param startHandlePosition the position of the start selection handle.
* @param endHandlePosition the position of the end selection handle.
* @param previousHandlePosition the position of the moving handle before the update.
* @param isStartHandle whether the moving selection handle is the start handle.
* @param adjustment the [SelectionAdjustment] used to adjust the raw selection range and
* produce the final selection range.
*
* @return a boolean representing whether the movement is consumed. It's useful for the case
* where a selection handle is updating consecutively. When the return value is true, it's
* expected that the caller will update the [startHandlePosition] to be the given
* [endHandlePosition] in following calls.
*
* @see SelectionAdjustment
*/
internal fun updateSelection(
startHandlePosition: Offset,
endHandlePosition: Offset,
previousHandlePosition: Offset?,
isStartHandle: Boolean,
adjustment: SelectionAdjustment,
): Boolean {
draggingHandle = if (isStartHandle) Handle.SelectionStart else Handle.SelectionEnd
currentDragPosition = if (isStartHandle) startHandlePosition else endHandlePosition
val newSubselections = mutableMapOf<Long, Selection>()
var moveConsumed = false
val newSelection = selectionRegistrar.sort(requireContainerCoordinates())
.fastFold(null) { mergedSelection: Selection?, selectable: Selectable ->
val previousSubselection =
selectionRegistrar.subselections[selectable.selectableId]
val (selection, consumed) = selectable.updateSelection(
startHandlePosition = startHandlePosition,
endHandlePosition = endHandlePosition,
previousHandlePosition = previousHandlePosition,
isStartHandle = isStartHandle,
containerLayoutCoordinates = requireContainerCoordinates(),
adjustment = adjustment,
previousSelection = previousSubselection,
)
moveConsumed = moveConsumed || consumed
selection?.let { newSubselections[selectable.selectableId] = it }
merge(mergedSelection, selection)
}
if (newSelection != selection) {
hapticFeedBack?.performHapticFeedback(HapticFeedbackType.TextHandleMove)
selectionRegistrar.subselections = newSubselections
onSelectionChange(newSelection)
}
return moveConsumed
}
fun contextMenuOpenAdjustment(position: Offset) {
val isEmptySelection = selection?.toTextRange()?.collapsed ?: true
// TODO(b/209483184) the logic should be more complex here, it should check that current
// selection doesn't include click position
if (isEmptySelection) {
startSelection(
position = position,
isStartHandle = true,
adjustment = SelectionAdjustment.Word
)
}
}
}
internal fun merge(lhs: Selection?, rhs: Selection?): Selection? {
return lhs?.merge(rhs) ?: rhs
}
internal expect fun isCopyKeyEvent(keyEvent: KeyEvent): Boolean
internal expect fun Modifier.selectionMagnifier(manager: SelectionManager): Modifier
internal fun calculateSelectionMagnifierCenterAndroid(
manager: SelectionManager,
magnifierSize: IntSize
): Offset {
fun getMagnifierCenter(anchor: AnchorInfo, isStartHandle: Boolean): Offset {
val selectable = manager.getAnchorSelectable(anchor) ?: return Offset.Unspecified
val containerCoordinates = manager.containerLayoutCoordinates ?: return Offset.Unspecified
val selectableCoordinates = selectable.getLayoutCoordinates() ?: return Offset.Unspecified
// The end offset is exclusive.
val offset = if (isStartHandle) anchor.offset else anchor.offset - 1
// The horizontal position doesn't snap to cursor positions but should directly track the
// actual drag.
val localDragPosition = selectableCoordinates.localPositionOf(
containerCoordinates,
manager.currentDragPosition!!
)
val dragX = localDragPosition.x
// But it is constrained by the horizontal bounds of the current line.
val centerX = selectable.getRangeOfLineContaining(offset).let { line ->
val lineMin = selectable.getBoundingBox(line.min)
// line.end is exclusive, but we want the bounding box of the actual last character in
// the line.
val lineMax = selectable.getBoundingBox((line.max - 1).coerceAtLeast(line.min))
val minX = minOf(lineMin.left, lineMax.left)
val maxX = maxOf(lineMin.right, lineMax.right)
dragX.coerceIn(minX, maxX)
}
// Hide the magnifier when dragged too far (outside the horizontal bounds of how big the
// magnifier actually is). See
// https://cs.android.com/android/platform/superproject/+/master:frameworks/base/core/java/android/widget/Editor.java;l=5228-5231;drc=2fdb6bd709be078b72f011334362456bb758922c
if ((dragX - centerX).absoluteValue > magnifierSize.width / 2) {
return Offset.Unspecified
}
// Let the selectable determine the vertical position of the magnifier, since it should be
// clamped to the center of text lines.
val anchorBounds = selectable.getBoundingBox(offset)
val centerY = anchorBounds.center.y
return containerCoordinates.localPositionOf(
sourceCoordinates = selectableCoordinates,
relativeToSource = Offset(centerX, centerY)
)
}
val selection = manager.selection ?: return Offset.Unspecified
return when (manager.draggingHandle) {
null -> return Offset.Unspecified
Handle.SelectionStart -> getMagnifierCenter(selection.start, isStartHandle = true)
Handle.SelectionEnd -> getMagnifierCenter(selection.end, isStartHandle = false)
Handle.Cursor -> error("SelectionContainer does not support cursor")
}
}
internal fun getCurrentSelectedText(
selectable: Selectable,
selection: Selection
): AnnotatedString {
val currentText = selectable.getText()
return if (
selectable.selectableId != selection.start.selectableId &&
selectable.selectableId != selection.end.selectableId
) {
// Select the full text content if the current selectable is between the
// start and the end selectables.
currentText
} else if (
selectable.selectableId == selection.start.selectableId &&
selectable.selectableId == selection.end.selectableId
) {
// Select partial text content if the current selectable is the start and
// the end selectable.
if (selection.handlesCrossed) {
currentText.subSequence(selection.end.offset, selection.start.offset)
} else {
currentText.subSequence(selection.start.offset, selection.end.offset)
}
} else if (selectable.selectableId == selection.start.selectableId) {
// Select partial text content if the current selectable is the start
// selectable.
if (selection.handlesCrossed) {
currentText.subSequence(0, selection.start.offset)
} else {
currentText.subSequence(selection.start.offset, currentText.length)
}
} else {
// Selectable partial text content if the current selectable is the end
// selectable.
if (selection.handlesCrossed) {
currentText.subSequence(selection.end.offset, currentText.length)
} else {
currentText.subSequence(0, selection.end.offset)
}
}
}
/** Returns the boundary of the visible area in this [LayoutCoordinates]. */
internal fun LayoutCoordinates.visibleBounds(): Rect {
// globalBounds is the global boundaries of this LayoutCoordinates after it's clipped by
// parents. We can think it as the global visible bounds of this Layout. Here globalBounds
// is convert to local, which is the boundary of the visible area within the LayoutCoordinates.
val boundsInWindow = boundsInWindow()
return Rect(
windowToLocal(boundsInWindow.topLeft),
windowToLocal(boundsInWindow.bottomRight)
)
}
internal fun Rect.containsInclusive(offset: Offset): Boolean =
offset.x in left..right && offset.y in top..bottom
| apache-2.0 | 7c26fe941dfa8ad2725eb81a67a15364 | 38.997783 | 182 | 0.63651 | 5.543639 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/ide/actions/ElmCreateFileAction.kt | 1 | 3698 | package org.elm.ide.actions
import com.intellij.ide.actions.CreateFileFromTemplateAction
import com.intellij.ide.actions.CreateFileFromTemplateDialog
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import org.elm.lang.core.ElmFileType
import org.elm.openapiext.pathAsPath
import org.elm.workspace.ElmProject
import org.elm.workspace.elmWorkspace
import java.nio.file.Path
class ElmCreateFileAction : CreateFileFromTemplateAction(CAPTION, "", ElmFileType.icon) {
private val log = logger<ElmCreateFileAction>()
override fun getActionName(directory: PsiDirectory?, newName: String, templateName: String?): String =
CAPTION
override fun buildDialog(project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder) {
// TODO add additional "kinds" here (e.g. an `elm-test` skeleton module)
builder.setTitle(CAPTION)
.addKind("Module", ElmFileType.icon, ELM_MODULE_KIND)
}
override fun createFile(name: String?, templateName: String, dir: PsiDirectory): PsiFile? {
if (name == null) return null
val cleanedName = name.removeSuffix(".elm")
val newFile = super.createFile(cleanedName, templateName, dir) ?: return null
if (templateName == ELM_MODULE_KIND) {
// HACK: I use an empty template to generate the file and then fill in the contents here
// TODO ask around to find out what's the right way to do this
newFile.viewProvider.document?.setText("module ${qualifyModuleName(dir, cleanedName)} exposing (..)")
}
return newFile
}
private fun qualifyModuleName(dir: PsiDirectory, name: String): String {
log.debug("trying to determine fully-qualified module name prefix based on parent dir")
val elmProject = dir.project.elmWorkspace.findProjectForFile(dir.virtualFile)
if (elmProject == null) log.warn("failed to determine the Elm project that owns the dir")
var rootDirPath = elmProject?.rootDirContaining(dir)
if (rootDirPath == null) {
log.warn("failed to determine root dir within the Elm project that owns the dir")
rootDirPath = dir.virtualFile.pathAsPath
}
val qualifier = rootDirPath.relativize(dir.virtualFile.pathAsPath).joinToString(".")
log.debug("using qualifier: '$qualifier'")
return if (qualifier == "") name else "$qualifier.$name"
}
/** A helper utility intended only to be called from test code */
fun testHelperCreateFile(name: String, dir: PsiDirectory): PsiFile? =
createFile(name, ELM_MODULE_KIND, dir)
override fun isAvailable(dataContext: DataContext): Boolean {
if (!super.isAvailable(dataContext)) return false
val file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext) ?: return false
val project = PlatformDataKeys.PROJECT.getData(dataContext)!!
return project.elmWorkspace.findProjectForFile(file) != null
}
private companion object {
private const val CAPTION = "Elm Module"
private const val ELM_MODULE_KIND = "Elm Module" // must match name of internal template stored in JAR resources
}
}
private fun ElmProject.rootDirContaining(dir: PsiDirectory): Path? {
val dirPath = dir.virtualFile.pathAsPath
return (absoluteSourceDirectories + listOf(testsDirPath))
.find { dirPath.startsWith(it) }
}
| mit | 68fd8d3fb1e06a9a9a6d55ae1e630e94 | 44.654321 | 120 | 0.716604 | 4.610973 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/GL43.kt | 1 | 53926 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val GL43 = "GL43".nativeClassGL("GL43") {
documentation =
"""
The core OpenGL 4.3 functionality. OpenGL 4.3 implementations support revision 4.30 of the OpenGL Shading Language.
Extensions promoted to core in this release:
${ul(
registryLinkTo("ARB", "arrays_of_arrays"),
registryLinkTo("ARB", "ES3_compatibility"),
registryLinkTo("ARB", "clear_buffer_object"),
registryLinkTo("ARB", "compute_shader"),
registryLinkTo("ARB", "copy_image"),
registryLinkTo("ARB", "debug_group"),
registryLinkTo("ARB", "debug_label"),
registryLinkTo("ARB", "debug_output2"),
registryLinkTo("ARB", "debug_output"),
registryLinkTo("ARB", "explicit_uniform_location"),
registryLinkTo("ARB", "fragment_layer_viewport"),
registryLinkTo("ARB", "framebuffer_no_attachments"),
registryLinkTo("ARB", "internalformat_query2"),
registryLinkTo("ARB", "invalidate_subdata"),
registryLinkTo("ARB", "multi_draw_indirect"),
registryLinkTo("ARB", "program_interface_query"),
registryLinkTo("ARB", "robust_buffer_access_behavior"),
registryLinkTo("ARB", "shader_image_size"),
registryLinkTo("ARB", "shader_storage_buffer_object"),
registryLinkTo("ARB", "stencil_texturing"),
registryLinkTo("ARB", "texture_buffer_range"),
registryLinkTo("ARB", "texture_query_levels"),
registryLinkTo("ARB", "texture_storage_multisample"),
registryLinkTo("ARB", "texture_view"),
registryLinkTo("ARB", "vertex_attrib_binding")
)}
"""
IntConstant(
"No. of supported Shading Language Versions. Accepted by the {@code pname} parameter of GetIntegerv.",
"NUM_SHADING_LANGUAGE_VERSIONS"..0x82E9
)
IntConstant(
"Vertex attrib array has unconverted doubles. Accepted by the {@code pname} parameter of GetVertexAttribiv.",
"VERTEX_ATTRIB_ARRAY_LONG"..0x874E
)
// ARB_ES3_compatibility
IntConstant(
"Accepted by the {@code internalformat} parameter of CompressedTexImage2D.",
"COMPRESSED_RGB8_ETC2"..0x9274,
"COMPRESSED_SRGB8_ETC2"..0x9275,
"COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"..0x9276,
"COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"..0x9277,
"COMPRESSED_RGBA8_ETC2_EAC"..0x9278,
"COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"..0x9279,
"COMPRESSED_R11_EAC"..0x9270,
"COMPRESSED_SIGNED_R11_EAC"..0x9271,
"COMPRESSED_RG11_EAC"..0x9272,
"COMPRESSED_SIGNED_RG11_EAC"..0x9273
)
IntConstant(
"Accepted by the {@code target} parameter of Enable and Disable.",
"PRIMITIVE_RESTART_FIXED_INDEX"..0x8D69
)
IntConstant(
"Accepted by the {@code target} parameter of BeginQuery, EndQuery, GetQueryIndexediv and GetQueryiv.",
"ANY_SAMPLES_PASSED_CONSERVATIVE"..0x8D6A
)
IntConstant(
"Accepted by the {@code value} parameter of the GetInteger* functions.",
"MAX_ELEMENT_INDEX"..0x8D6B
)
IntConstant(
"Accepted by the {@code pname} parameters of GetTexParameterfv and GetTexParameteriv.",
"TEXTURE_IMMUTABLE_LEVELS"..0x82DF
)
// ARB_clear_buffer_object
void(
"ClearBufferData",
"Fills a buffer object's data store with a fixed value.",
GLenum.IN("target", "the target of the operation", BUFFER_OBJECT_TARGETS),
GLenum.IN("internalformat", "the internal format with which the data will be stored in the buffer object"),
GLenum.IN("format", "the format of the data in memory addressed by {@code data}", PIXEL_DATA_FORMATS),
GLenum.IN("type", "the type of the data in memory addressed by {@code data}", PIXEL_DATA_TYPES),
nullable..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..const..void_p.IN(
"data",
"""
the buffer containing the data to be used as the source of the constant fill value. The elements of data are converted by the GL into the format
specified by internalformat, and then used to fill the specified range of the destination buffer. If data is $NULL, then it is ignored and the
sub-range of the buffer is filled with zeros.
"""
)
)
void(
"ClearBufferSubData",
"Fills all or part of buffer object's data store with a fixed value.",
GLenum.IN("target", "the target of the operation", BUFFER_OBJECT_TARGETS),
GLenum.IN("internalformat", "the internal format with which the data will be stored in the buffer object"),
GLintptr.IN("offset", "the offset, in basic machine units into the buffer object's data store at which to start filling"),
GLsizeiptr.IN("size", "the size, in basic machine units of the range of the data store to fill"),
GLenum.IN("format", "the format of the data in memory addressed by {@code data}", PIXEL_DATA_FORMATS),
GLenum.IN("type", "the type of the data in memory addressed by {@code data}", PIXEL_DATA_TYPES),
nullable..MultiType(
PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT
)..const..void_p.IN(
"data",
"""
the buffer containing the data to be used as the source of the constant fill value. The elements of data are converted by the GL into the format
specified by internalformat, and then used to fill the specified range of the destination buffer. If data is $NULL, then it is ignored and the
sub-range of the buffer is filled with zeros.
"""
)
)
// ARB_compute_shader
IntConstant(
"Accepted by the {@code type} parameter of CreateShader and returned in the {@code params} parameter by GetShaderiv.",
"COMPUTE_SHADER"..0x91B9
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetFloatv, GetDoublev and GetInteger64v.",
"MAX_COMPUTE_UNIFORM_BLOCKS"..0x91BB,
"MAX_COMPUTE_TEXTURE_IMAGE_UNITS"..0x91BC,
"MAX_COMPUTE_IMAGE_UNIFORMS"..0x91BD,
"MAX_COMPUTE_SHARED_MEMORY_SIZE"..0x8262,
"MAX_COMPUTE_UNIFORM_COMPONENTS"..0x8263,
"MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS"..0x8264,
"MAX_COMPUTE_ATOMIC_COUNTERS"..0x8265,
"MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS"..0x8266,
"MAX_COMPUTE_WORK_GROUP_INVOCATIONS"..0x90EB
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegeri_v, GetBooleani_v, GetFloati_v, GetDoublei_v and GetInteger64i_v.",
"MAX_COMPUTE_WORK_GROUP_COUNT"..0x91BE,
"MAX_COMPUTE_WORK_GROUP_SIZE"..0x91BF
)
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"COMPUTE_WORK_GROUP_SIZE"..0x8267
)
IntConstant(
"Accepted by the {@code pname} parameter of GetActiveUniformBlockiv.",
"UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER"..0x90EC
)
IntConstant(
"Accepted by the {@code pname} parameter of GetActiveAtomicCounterBufferiv.",
"ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER"..0x90ED
)
IntConstant(
"Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, and GetBufferPointerv.",
"DISPATCH_INDIRECT_BUFFER"..0x90EE
)
IntConstant(
"Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetInteger64v, GetFloatv, and GetDoublev.",
"DISPATCH_INDIRECT_BUFFER_BINDING"..0x90EF
)
IntConstant(
"Accepted by the {@code stages} parameter of UseProgramStages.",
"COMPUTE_SHADER_BIT"..0x00000020
)
void(
"DispatchCompute",
"Launches one or more compute work groups.",
GLuint.IN("num_groups_x", "the number of work groups to be launched in the X dimension"),
GLuint.IN("num_groups_y", "the number of work groups to be launched in the Y dimension"),
GLuint.IN("num_groups_z", "the number of work groups to be launched in the Z dimension")
)
void(
"DispatchComputeIndirect",
"""
Launches one or more compute work groups using parameters stored in a buffer.
The parameters addressed by indirect are packed a structure, which takes the form (in C):
${codeBlock("""
typedef struct {
uint num_groups_x;
uint num_groups_y;
uint num_groups_z;
} DispatchIndirectCommand;
""")}
A call to {@code glDispatchComputeIndirect} is equivalent, assuming no errors are generated, to:
${codeBlock("""
cmd = (const DispatchIndirectCommand *)indirect;
glDispatchCompute(cmd->num_groups_x, cmd->num_groups_y, cmd->num_groups_z);
""")}
""",
DISPATCH_INDIRECT_BUFFER..GLintptr.IN(
"indirect",
"""
the offset into the buffer object currently bound to the #DISPATCH_INDIRECT_BUFFER buffer target at which the dispatch parameters are
stored.
"""
)
)
// ARB_copy_image
void(
"CopyImageSubData",
"Performs a raw data copy between two images.",
GLuint.IN("srcName", "the name of a texture or renderbuffer object from which to copy"),
GLenum.IN("srcTarget", "the target representing the namespace of the source name {@code srcName}"),
GLint.IN("srcLevel", "the mipmap level to read from the source"),
GLint.IN("srcX", "the X coordinate of the left edge of the souce region to copy"),
GLint.IN("srcY", "the Y coordinate of the top edge of the souce region to copy"),
GLint.IN("srcZ", "the Z coordinate of the near edge of the souce region to copy"),
GLuint.IN("dstName", "the name of a texture or renderbuffer object to which to copy"),
GLenum.IN("dstTarget", "the target representing the namespace of the destination name {@code dstName}"),
GLint.IN("dstLevel", "the mipmap level to write to the source"),
GLint.IN("dstX", "the X coordinate of the left edge of the destination region"),
GLint.IN("dstY", "the Y coordinate of the top edge of the destination region"),
GLint.IN("dstZ", "the Z coordinate of the near edge of the destination region"),
GLsizei.IN("srcWidth", "the width of the region to be copied"),
GLsizei.IN("srcHeight", "the height of the region to be copied"),
GLsizei.IN("srcDepth", "the depth of the region to be copied")
)
// KHR_debug
IntConstant(
"Tokens accepted by the {@code target} parameters of Enable, Disable, and IsEnabled.",
"DEBUG_OUTPUT"..0x92E0,
"DEBUG_OUTPUT_SYNCHRONOUS"..0x8242
)
IntConstant(
"Returned by GetIntegerv when {@code pname} is CONTEXT_FLAGS.",
"CONTEXT_FLAG_DEBUG_BIT"..0x00000002
)
IntConstant(
"Tokens accepted by the {@code value} parameters of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev and GetInteger64v.",
"MAX_DEBUG_MESSAGE_LENGTH"..0x9143,
"MAX_DEBUG_LOGGED_MESSAGES"..0x9144,
"DEBUG_LOGGED_MESSAGES"..0x9145,
"DEBUG_NEXT_LOGGED_MESSAGE_LENGTH"..0x8243,
"MAX_DEBUG_GROUP_STACK_DEPTH"..0x826C,
"DEBUG_GROUP_STACK_DEPTH"..0x826D,
"MAX_LABEL_LENGTH"..0x82E8
)
IntConstant(
"Tokens accepted by the {@code pname} parameter of GetPointerv.",
"DEBUG_CALLBACK_FUNCTION"..0x8244,
"DEBUG_CALLBACK_USER_PARAM"..0x8245
)
val DebugSources = IntConstant(
"""
Tokens accepted or provided by the {@code source} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC, and the {@code sources} parameter
of GetDebugMessageLog.
""",
"DEBUG_SOURCE_API"..0x8246,
"DEBUG_SOURCE_WINDOW_SYSTEM"..0x8247,
"DEBUG_SOURCE_SHADER_COMPILER"..0x8248,
"DEBUG_SOURCE_THIRD_PARTY"..0x8249,
"DEBUG_SOURCE_APPLICATION"..0x824A,
"DEBUG_SOURCE_OTHER"..0x824B
).javaDocLinks
val DebugTypes = IntConstant(
"""
Tokens accepted or provided by the {@code type} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC, and the {@code types} parameter of
GetDebugMessageLog.
""",
"DEBUG_TYPE_ERROR"..0x824C,
"DEBUG_TYPE_DEPRECATED_BEHAVIOR"..0x824D,
"DEBUG_TYPE_UNDEFINED_BEHAVIOR"..0x824E,
"DEBUG_TYPE_PORTABILITY"..0x824F,
"DEBUG_TYPE_PERFORMANCE"..0x8250,
"DEBUG_TYPE_OTHER"..0x8251,
"DEBUG_TYPE_MARKER"..0x8268
).javaDocLinks
IntConstant(
"""
Tokens accepted or provided by the {@code type} parameters of DebugMessageControl and DEBUGPROC, and the {@code types} parameter of GetDebugMessageLog.
""",
"DEBUG_TYPE_PUSH_GROUP"..0x8269,
"DEBUG_TYPE_POP_GROUP"..0x826A
)
val DebugSeverities = IntConstant(
"""
Tokens accepted or provided by the {@code severity} parameters of DebugMessageControl, DebugMessageInsert and DEBUGPROC callback functions, and the
{@code severities} parameter of GetDebugMessageLog.
""",
"DEBUG_SEVERITY_HIGH"..0x9146,
"DEBUG_SEVERITY_MEDIUM"..0x9147,
"DEBUG_SEVERITY_LOW"..0x9148,
"DEBUG_SEVERITY_NOTIFICATION"..0x826B
).javaDocLinks
val DebugIdentifiers = IntConstant(
"Tokens accepted or provided by the {@code identifier} parameters of ObjectLabel and GetObjectLabel.",
"BUFFER"..0x82E0,
"SHADER"..0x82E1,
"PROGRAM"..0x82E2,
"QUERY"..0x82E3,
"PROGRAM_PIPELINE"..0x82E4,
"SAMPLER"..0x82E6,
"DISPLAY_LIST"..0x82E7
).javaDocLinks
void(
"DebugMessageControl",
"""
Controls the volume of debug output in the active debug group, by disabling specific or groups of messages.
If {@code enabled} is GL11#TRUE, the referenced subset of messages will be enabled. If GL11#FALSE, then those messages will be disabled.
This command can reference different subsets of messages by first considering the set of all messages, and filtering out messages based on the following
ways:
${ul(
"""
If {@code source}, {@code type}, or {@code severity} is GL11#DONT_CARE, the messages from all sources, of all types, or of all severities are
referenced respectively.
""",
"""
When values other than GL11#DONT_CARE are specified, all messages whose source, type, or severity match the specified {@code source}, {@code type},
or {@code severity} respectively will be referenced.
""",
"""
If {@code count} is greater than zero, then {@code ids} is an array of {@code count} message IDs for the specified combination of {@code source} and
{@code type}. In this case, if {@code source} or {@code type} is GL11#DONT_CARE, or {@code severity} is not GL11#DONT_CARE, the error
GL11#INVALID_OPERATION is generated.
"""
)}
Unrecognized message IDs in {@code ids} are ignored. If {@code count} is zero, the value if {@code ids} is ignored.
Although messages are grouped into an implicit hierarchy by their sources and types, there is no explicit per-source, per-type or per-severity enabled
state. Instead, the enabled state is stored individually for each message. There is no difference between disabling all messages from one source in a
single call, and individually disabling all messages from that source using their types and IDs.
If the #DEBUG_OUTPUT state is disabled the GL operates the same as if messages of every {@code source}, {@code type} or {@code severity} are disabled.
""",
GLenum.IN("source", "the source of debug messages to enable or disable", DebugSources),
GLenum.IN("type", "the type of debug messages to enable or disable", DebugTypes),
GLenum.IN("severity", "the severity of debug messages to enable or disable", DebugSeverities),
AutoSize("ids")..GLsizei.IN("count", "the length of the array {@code ids}"),
SingleValue("id")..nullable..const..GLuint_p.IN("ids", "an array of unsigned integers containing the ids of the messages to enable or disable"),
GLboolean.IN("enabled", "whether the selected messages should be enabled or disabled")
)
void(
"DebugMessageInsert",
"""
This function can be called by applications and third-party libraries to generate their own messages, such as ones containing timestamp information or
signals about specific render system events.
The value of {@code id} specifies the ID for the message and {@code severity} indicates its severity level as defined by the caller. The string
{@code buf} contains the string representation of the message. The parameter {@code length} contains the number of characters in {@code buf}. If
{@code length} is negative, it is implied that {@code buf} contains a null terminated string. The error GL11#INVALID_VALUE will be generated if the
number of characters in {@code buf}, excluding the null terminator when {@code length} is negative, is not less than the value of
#MAX_DEBUG_MESSAGE_LENGTH.
If the #DEBUG_OUTPUT state is disabled calls to DebugMessageInsert are discarded and do not generate an error.
""",
GLenum.IN("source", "the source of the debug message to insert", DebugSources),
GLenum.IN("type", "the type of the debug message insert", DebugTypes),
GLuint.IN("id", "the user-supplied identifier of the message to insert", DebugSeverities),
GLenum.IN("severity", "the severity of the debug messages to insert"),
AutoSize("message")..GLsizei.IN("length", "the length of the string contained in the character array whose address is given by {@code message}"),
const..GLcharUTF8_p.IN("message", "a character array containing the message to insert")
)
void(
"DebugMessageCallback",
"""
Specifies a callback to receive debugging messages from the GL.
The function's prototype must follow the type definition of DEBUGPROC including its platform-dependent calling convention. Anything else will result in
undefined behavior. Only one debug callback can be specified for the current context, and further calls overwrite the previous callback. Specifying
$NULL as the value of {@code callback} clears the current callback and disables message output through callbacks. Applications can provide
user-specified data through the pointer {@code userParam}. The context will store this pointer and will include it as one of the parameters in each call
to the callback function.
If the application has specified a callback function for receiving debug output, the implementation will call that function whenever any enabled message
is generated. The source, type, ID, and severity of the message are specified by the DEBUGPROC parameters {@code source}, {@code type}, {@code id}, and
{@code severity}, respectively. The string representation of the message is stored in {@code message} and its length (excluding the null-terminator) is
stored in {@code length}. The parameter {@code userParam} is the user-specified parameter that was given when calling DebugMessageCallback.
Applications can query the current callback function and the current user-specified parameter by obtaining the values of #DEBUG_CALLBACK_FUNCTION and
#DEBUG_CALLBACK_USER_PARAM, respectively.
Applications that specify a callback function must be aware of certain special conditions when executing code inside a callback when it is called by the
GL, regardless of the debug source.
The memory for {@code message} is owned and managed by the GL, and should only be considered valid for the duration of the function call.
The behavior of calling any GL or window system function from within the callback function is undefined and may lead to program termination.
Care must also be taken in securing debug callbacks for use with asynchronous debug output by multi-threaded GL implementations.
If the #DEBUG_OUTPUT state is disabled then the GL will not call the callback function.
""",
nullable..GLDEBUGPROC.IN("callback", "a callback function that will be called when a debug message is generated"),
nullable..const..voidptr.IN(
"userParam",
"a user supplied pointer that will be passed on each invocation of {@code callback}"
)
)
GLuint(
"GetDebugMessageLog",
"""
Retrieves messages from the debug message log.
This function fetches a maximum of {@code count} messages from the message log, and will return the number of messages successfully fetched.
Messages will be fetched from the log in order of oldest to newest. Those messages that were fetched will be removed from the log.
The sources, types, severities, IDs, and string lengths of fetched messages will be stored in the application-provided arrays {@code sources},
{@code types}, {@code severities}, {@code ids}, and {@code lengths}, respectively. The application is responsible for allocating enough space for each
array to hold up to {@code count} elements. The string representations of all fetched messages are stored in the {@code messageLog} array. If multiple
messages are fetched, their strings are concatenated into the same {@code messageLog} array and will be separated by single null terminators. The last
string in the array will also be null-terminated. The maximum size of {@code messageLog}, including the space used by all null terminators, is given by
{@code bufSize}. If {@code bufSize} is less than zero and {@code messageLog} is not $NULL, an GL11#INVALID_VALUE error will be generated. If a message's
string, including its null terminator, can not fully fit within the {@code messageLog} array's remaining space, then that message and any subsequent
messages will not be fetched and will remain in the log. The string lengths stored in the array {@code lengths} include the space for the null
terminator of each string.
Any or all of the arrays {@code sources}, {@code types}, {@code ids}, {@code severities}, {@code lengths} and {@code messageLog} can also be null
pointers, which causes the attributes for such arrays to be discarded when messages are fetched, however those messages will still be removed from the
log. Thus to simply delete up to {@code count} messages from the message log while ignoring their attributes, the application can call the function
with null pointers for all attribute arrays.
If the context was created without the #CONTEXT_FLAG_DEBUG_BIT in the GL30#CONTEXT_FLAGS state, then the GL can opt to never add messages to the
message log so GetDebugMessageLog will always return zero.
""",
GLuint.IN("count", "the number of debug messages to retrieve from the log"),
AutoSize("messageLog")..GLsizei.IN("bufsize", "the size of the buffer whose address is given by {@code messageLog}"),
Check("count")..nullable..GLenum_p.OUT("sources", "an array of variables to receive the sources of the retrieved messages"),
Check("count")..nullable..GLenum_p.OUT("types", "an array of variables to receive the types of the retrieved messages"),
Check("count")..nullable..GLuint_p.OUT("ids", "an array of unsigned integers to receive the ids of the retrieved messages"),
Check("count")..nullable..GLenum_p.OUT("severities", "an array of variables to receive the severites of the retrieved messages"),
Check("count")..nullable..GLsizei_p.OUT("lengths", "an array of variables to receive the lengths of the received messages"),
nullable..GLcharUTF8_p.OUT("messageLog", "an array of characters that will receive the messages")
)
void(
"PushDebugGroup",
"""
Pushes a debug group described by the string {@code message} into the command stream. The value of {@code id} specifies the ID of messages generated.
The parameter {@code length} contains the number of characters in {@code message}. If {@code length} is negative, it is implied that {@code message}
contains a null terminated string. The message has the specified {@code source} and {@code id}, {@code type} #DEBUG_TYPE_PUSH_GROUP, and
{@code severity} #DEBUG_SEVERITY_NOTIFICATION. The GL will put a new debug group on top of the debug group stack which inherits the control of the
volume of debug output of the debug group previously residing on the top of the debug group stack. Because debug groups are strictly hierarchical, any
additional control of the debug output volume will only apply within the active debug group and the debug groups pushed on top of the active debug group.
An GL11#INVALID_ENUM error is generated if the value of {@code source} is neither #DEBUG_SOURCE_APPLICATION nor #DEBUG_SOURCE_THIRD_PARTY. An
GL11#INVALID_VALUE error is generated if {@code length} is negative and the number of characters in {@code message}, excluding the null-terminator, is
not less than the value of #MAX_DEBUG_MESSAGE_LENGTH.
""",
GLenum.IN("source", "the source of the debug message", "#DEBUG_SOURCE_APPLICATION #DEBUG_SOURCE_THIRD_PARTY"),
GLuint.IN("id", "the identifier of the message"),
AutoSize("message")..GLsizei.IN("length", "the length of the message to be sent to the debug output stream"),
const..GLcharUTF8_p.IN("message", "a string containing the message to be sent to the debug output stream")
)
void(
"PopDebugGroup",
"""
Pops the active debug group. When a debug group is popped, the GL will also generate a debug output message describing its cause based on the
{@code message} string, the source {@code source}, and an ID {@code id} submitted to the associated #PushDebugGroup() command. #DEBUG_TYPE_PUSH_GROUP
and #DEBUG_TYPE_POP_GROUP share a single namespace for message {@code id}. {@code severity} has the value #DEBUG_SEVERITY_NOTIFICATION. The {@code type}
has the value #DEBUG_TYPE_POP_GROUP. Popping a debug group restores the debug output volume control of the parent debug group.
Attempting to pop the default debug group off the stack generates a GL11#STACK_UNDERFLOW error; pushing a debug group onto a stack containing
#MAX_DEBUG_GROUP_STACK_DEPTH minus one elements will generate a GL11#STACK_OVERFLOW error.
"""
)
void(
"ObjectLabel",
"Labels a named object identified within a namespace.",
GLenum.IN(
"identifier",
"the namespace from which the name of the object is allocated",
DebugIdentifiers + " GL11#VERTEX_ARRAY GL11#TEXTURE GL30#RENDERBUFFER GL30#FRAMEBUFFER GL40#TRANSFORM_FEEDBACK"
),
GLuint.IN("name", "the name of the object to label"),
AutoSize("label")..GLsizei.IN("length", "the length of the label to be used for the object"),
const..GLcharUTF8_p.IN("label", "a string containing the label to assign to the object")
)
void(
"GetObjectLabel",
"Retrieves the label of a named object identified within a namespace.",
GLenum.IN(
"identifier",
"the namespace from which the name of the object is allocated",
DebugIdentifiers + " GL11#VERTEX_ARRAY GL11#TEXTURE GL30#RENDERBUFFER GL30#FRAMEBUFFER GL40#TRANSFORM_FEEDBACK"
),
GLuint.IN("name", "the name of the object whose label to retrieve"),
AutoSize("label")..GLsizei.IN("bufSize", "the length of the buffer whose address is in {@code label}"),
Check(1)..nullable..GLsizei_p.OUT("length", "the address of a variable to receive the length of the object label"),
Return("length", "GL11.glGetInteger(GL_MAX_LABEL_LENGTH)")..GLcharUTF8_p.OUT("label", "a string that will receive the object label")
)
void(
"ObjectPtrLabel",
"Labels a sync object identified by a pointer.",
voidptr.IN("ptr", "a pointer identifying a sync object"),
AutoSize("label")..GLsizei.IN("length", "the length of the label to be used for the object"),
const..GLcharUTF8_p.IN("label", "a string containing the label to assign to the object")
)
void(
"GetObjectPtrLabel",
"Retrieves the label of a sync object identified by a pointer.",
voidptr.IN("ptr", "the name of the sync object whose label to retrieve"),
AutoSize("label")..GLsizei.IN("bufSize", "the length of the buffer whose address is in {@code label}"),
Check(1)..nullable..GLsizei_p.OUT("length", "a variable to receive the length of the object label"),
Return("length", "GL11.glGetInteger(GL_MAX_LABEL_LENGTH)")..GLcharUTF8_p.OUT("label", "a string that will receive the object label")
)
// ARB_explicit_uniform_location
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev, and GetInteger64v.",
"MAX_UNIFORM_LOCATIONS"..0x826E
)
// ARB_framebuffer_no_attachments
val FramebufferParameters = IntConstant(
"""
Accepted by the {@code pname} parameter of FramebufferParameteri, GetFramebufferParameteriv, NamedFramebufferParameteriEXT, and
GetNamedFramebufferParameterivEXT.
""",
"FRAMEBUFFER_DEFAULT_WIDTH"..0x9310,
"FRAMEBUFFER_DEFAULT_HEIGHT"..0x9311,
"FRAMEBUFFER_DEFAULT_LAYERS"..0x9312,
"FRAMEBUFFER_DEFAULT_SAMPLES"..0x9313,
"FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS"..0x9314
).javaDocLinks
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetInteger64v, GetFloatv, and GetDoublev.",
"MAX_FRAMEBUFFER_WIDTH"..0x9315,
"MAX_FRAMEBUFFER_HEIGHT"..0x9316,
"MAX_FRAMEBUFFER_LAYERS"..0x9317,
"MAX_FRAMEBUFFER_SAMPLES"..0x9318
)
void(
"FramebufferParameteri",
"Sets a named parameter of a framebuffer.",
GLenum.IN("target", "target of the operation", "GL30#READ_FRAMEBUFFER GL30#DRAW_FRAMEBUFFER GL30#FRAMEBUFFER"),
GLenum.IN("pname", "a token indicating the parameter to be modified", FramebufferParameters),
GLint.IN("param", "the new value for the parameter named {@code pname}")
)
void(
"GetFramebufferParameteriv",
"Retrieves a named parameter from a framebuffer.",
GLenum.IN("target", "target of the operation", "GL30#READ_FRAMEBUFFER GL30#DRAW_FRAMEBUFFER GL30#FRAMEBUFFER"),
GLenum.IN("pname", "a token indicating the parameter to be retrieved", FramebufferParameters),
Check(1)..ReturnParam..GLint_p.OUT("params", "a variable to receive the value of the parameter named {@code pname}")
)
// ARB_internalformat_query2
IntConstant(
"Accepted by the {@code pname} parameter of GetInternalformativ and GetInternalformati64v.",
"INTERNALFORMAT_SUPPORTED"..0x826F,
"INTERNALFORMAT_PREFERRED"..0x8270,
"INTERNALFORMAT_RED_SIZE"..0x8271,
"INTERNALFORMAT_GREEN_SIZE"..0x8272,
"INTERNALFORMAT_BLUE_SIZE"..0x8273,
"INTERNALFORMAT_ALPHA_SIZE"..0x8274,
"INTERNALFORMAT_DEPTH_SIZE"..0x8275,
"INTERNALFORMAT_STENCIL_SIZE"..0x8276,
"INTERNALFORMAT_SHARED_SIZE"..0x8277,
"INTERNALFORMAT_RED_TYPE"..0x8278,
"INTERNALFORMAT_GREEN_TYPE"..0x8279,
"INTERNALFORMAT_BLUE_TYPE"..0x827A,
"INTERNALFORMAT_ALPHA_TYPE"..0x827B,
"INTERNALFORMAT_DEPTH_TYPE"..0x827C,
"INTERNALFORMAT_STENCIL_TYPE"..0x827D,
"MAX_WIDTH"..0x827E,
"MAX_HEIGHT"..0x827F,
"MAX_DEPTH"..0x8280,
"MAX_LAYERS"..0x8281,
"MAX_COMBINED_DIMENSIONS"..0x8282,
"COLOR_COMPONENTS"..0x8283,
"DEPTH_COMPONENTS"..0x8284,
"STENCIL_COMPONENTS"..0x8285,
"COLOR_RENDERABLE"..0x8286,
"DEPTH_RENDERABLE"..0x8287,
"STENCIL_RENDERABLE"..0x8288,
"FRAMEBUFFER_RENDERABLE"..0x8289,
"FRAMEBUFFER_RENDERABLE_LAYERED"..0x828A,
"FRAMEBUFFER_BLEND"..0x828B,
"READ_PIXELS"..0x828C,
"READ_PIXELS_FORMAT"..0x828D,
"READ_PIXELS_TYPE"..0x828E,
"TEXTURE_IMAGE_FORMAT"..0x828F,
"TEXTURE_IMAGE_TYPE"..0x8290,
"GET_TEXTURE_IMAGE_FORMAT"..0x8291,
"GET_TEXTURE_IMAGE_TYPE"..0x8292,
"MIPMAP"..0x8293,
"MANUAL_GENERATE_MIPMAP"..0x8294,
"AUTO_GENERATE_MIPMAP"..0x8295,
"COLOR_ENCODING"..0x8296,
"SRGB_READ"..0x8297,
"SRGB_WRITE"..0x8298,
"FILTER"..0x829A,
"VERTEX_TEXTURE"..0x829B,
"TESS_CONTROL_TEXTURE"..0x829C,
"TESS_EVALUATION_TEXTURE"..0x829D,
"GEOMETRY_TEXTURE"..0x829E,
"FRAGMENT_TEXTURE"..0x829F,
"COMPUTE_TEXTURE"..0x82A0,
"TEXTURE_SHADOW"..0x82A1,
"TEXTURE_GATHER"..0x82A2,
"TEXTURE_GATHER_SHADOW"..0x82A3,
"SHADER_IMAGE_LOAD"..0x82A4,
"SHADER_IMAGE_STORE"..0x82A5,
"SHADER_IMAGE_ATOMIC"..0x82A6,
"IMAGE_TEXEL_SIZE"..0x82A7,
"IMAGE_COMPATIBILITY_CLASS"..0x82A8,
"IMAGE_PIXEL_FORMAT"..0x82A9,
"IMAGE_PIXEL_TYPE"..0x82AA,
"SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST"..0x82AC,
"SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST"..0x82AD,
"SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE"..0x82AE,
"SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE"..0x82AF,
"TEXTURE_COMPRESSED_BLOCK_WIDTH"..0x82B1,
"TEXTURE_COMPRESSED_BLOCK_HEIGHT"..0x82B2,
"TEXTURE_COMPRESSED_BLOCK_SIZE"..0x82B3,
"CLEAR_BUFFER"..0x82B4,
"TEXTURE_VIEW"..0x82B5,
"VIEW_COMPATIBILITY_CLASS"..0x82B6
)
IntConstant(
"Returned as possible responses for various {@code pname} queries to GetInternalformativ and GetInternalformati64v.",
"FULL_SUPPORT"..0x82B7,
"CAVEAT_SUPPORT"..0x82B8,
"IMAGE_CLASS_4_X_32"..0x82B9,
"IMAGE_CLASS_2_X_32"..0x82BA,
"IMAGE_CLASS_1_X_32"..0x82BB,
"IMAGE_CLASS_4_X_16"..0x82BC,
"IMAGE_CLASS_2_X_16"..0x82BD,
"IMAGE_CLASS_1_X_16"..0x82BE,
"IMAGE_CLASS_4_X_8"..0x82BF,
"IMAGE_CLASS_2_X_8"..0x82C0,
"IMAGE_CLASS_1_X_8"..0x82C1,
"IMAGE_CLASS_11_11_10"..0x82C2,
"IMAGE_CLASS_10_10_10_2"..0x82C3,
"VIEW_CLASS_128_BITS"..0x82C4,
"VIEW_CLASS_96_BITS"..0x82C5,
"VIEW_CLASS_64_BITS"..0x82C6,
"VIEW_CLASS_48_BITS"..0x82C7,
"VIEW_CLASS_32_BITS"..0x82C8,
"VIEW_CLASS_24_BITS"..0x82C9,
"VIEW_CLASS_16_BITS"..0x82CA,
"VIEW_CLASS_8_BITS"..0x82CB,
"VIEW_CLASS_S3TC_DXT1_RGB"..0x82CC,
"VIEW_CLASS_S3TC_DXT1_RGBA"..0x82CD,
"VIEW_CLASS_S3TC_DXT3_RGBA"..0x82CE,
"VIEW_CLASS_S3TC_DXT5_RGBA"..0x82CF,
"VIEW_CLASS_RGTC1_RED"..0x82D0,
"VIEW_CLASS_RGTC2_RG"..0x82D1,
"VIEW_CLASS_BPTC_UNORM"..0x82D2,
"VIEW_CLASS_BPTC_FLOAT"..0x82D3
)
void(
"GetInternalformati64v",
"Retrieves information about implementation-dependent support for internal formats.",
GLenum.IN(
"target",
"the usage of the internal format",
"""
GL11#TEXTURE_1D $TEXTURE_2D_TARGETS $TEXTURE_3D_TARGETS GL30#RENDERBUFFER GL31#TEXTURE_BUFFER GL32#TEXTURE_2D_MULTISAMPLE
GL32#TEXTURE_2D_MULTISAMPLE_ARRAY
"""
),
GLenum.IN("internalformat", "the internal format about which to retrieve information"),
GLenum.IN("pname", "the type of information to query"),
AutoSize("params")..GLsizei.IN("bufSize", "the maximum number of values that may be written to params by the function"),
ReturnParam..GLint64_p.OUT("params", "a variable into which to write the retrieved information")
)
// ARB_invalidate_subdata
void(
"InvalidateTexSubImage",
"Invalidates a region of a texture image.",
GLuint.IN("texture", "the name of a texture object a subregion of which to invalidate"),
GLint.IN("level", "the level of detail of the texture object within which the region resides"),
GLint.IN("xoffset", "the X offset of the region to be invalidated"),
GLint.IN("yoffset", "the Y offset of the region to be invalidated"),
GLint.IN("zoffset", "the Z offset of the region to be invalidated"),
GLsizei.IN("width", "the width of the region to be invalidated"),
GLsizei.IN("height", "the height of the region to be invalidated"),
GLsizei.IN("depth", "the depth of the region to be invalidated")
)
void(
"InvalidateTexImage",
"Invalidates the entirety of a texture image.",
GLuint.IN("texture", "the name of a texture object to invalidate"),
GLint.IN("level", "the level of detail of the texture object to invalidate")
)
void(
"InvalidateBufferSubData",
"Invalidates a region of a buffer object's data store.",
GLuint.IN("buffer", "the name of a buffer object, a subrange of whose data store to invalidate"),
GLintptr.IN("offset", "the offset within the buffer's data store of the start of the range to be invalidated"),
GLsizeiptr.IN("length", "the length of the range within the buffer's data store to be invalidated")
)
void(
"InvalidateBufferData",
"Invalidates the content of a buffer object's data store.",
GLuint.IN("buffer", "the name of a buffer object whose data store to invalidate")
)
void(
"InvalidateFramebuffer",
"Invalidate the content some or all of a framebuffer object's attachments.",
GLenum.IN("target", "the target to which the framebuffer is attached", "GL30#FRAMEBUFFER GL30#DRAW_FRAMEBUFFER GL30#READ_FRAMEBUFFER"),
AutoSize("attachments")..GLsizei.IN("numAttachments", "the number of entries in the {@code attachments} array"),
SingleValue("attachment")..const..GLenum_p.IN("attachments", "the address of an array identifying the attachments to be invalidated")
)
void(
"InvalidateSubFramebuffer",
"Invalidates the content of a region of some or all of a framebuffer object's attachments.",
GLenum.IN("target", "the target to which the framebuffer is attached", "GL30#FRAMEBUFFER GL30#DRAW_FRAMEBUFFER GL30#READ_FRAMEBUFFER"),
AutoSize("attachments")..GLsizei.IN("numAttachments", "the number of entries in the {@code attachments} array"),
SingleValue("attachment")..const..GLenum_p.IN("attachments", "an array identifying the attachments to be invalidated"),
GLint.IN("x", "the X offset of the region to be invalidated"),
GLint.IN("y", "the Y offset of the region to be invalidated"),
GLsizei.IN("width", "the width of the region to be invalidated"),
GLsizei.IN("height", "the height of the region to be invalidated")
)
// ARB_multi_draw_indirect
void(
"MultiDrawArraysIndirect",
"""
Renders multiple sets of primitives from array data, taking parameters from memory.
The parameters addressed by {@code indirect} are packed into an array of structures, each element of which takes the form (in C):
${codeBlock("""
typedef struct {
uint count;
uint primCount;
uint first;
uint baseInstance;
} DrawArraysIndirectCommand;
""")}
A single call to {@code glMultiDrawArraysIndirect} is equivalent, assuming no errors are generated to:
${codeBlock("""
const ubyte *ptr = (const ubyte *)indirect;
for ( i = 0; i < primcount; i++ ) {
DrawArraysIndirect(mode, (DrawArraysIndirectCommand*)ptr);
if ( stride == 0 )
ptr += sizeof(DrawArraysIndirectCommand);
else
ptr += stride;
}
""")}
""",
GLenum.IN("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
Check("primcount * (stride == 0 ? (4 * 4) : stride)")..MultiType(
PointerMapping.DATA_INT
)..DRAW_INDIRECT_BUFFER..const..void_p.IN("indirect", "an array of structures containing the draw parameters"),
GLsizei.IN("primcount", "the number of elements in the array of draw parameter structures"),
GLsizei.IN("stride", "the distance in basic machine units between elements of the draw parameter array")
)
void(
"MultiDrawElementsIndirect",
"""
Renders multiple indexed primitives from array data, taking parameters from memory.
The parameters addressed by indirect are packed into a structure that takes the form (in C):
${codeBlock("""
typedef struct {
uint count;
uint primCount;
uint firstIndex;
uint baseVertex;
uint baseInstance;
} DrawElementsIndirectCommand;
""")}
A single call to {@code glMultiDrawElementsIndirect} is equivalent, assuming no errors are generated to:
${codeBlock("""
const ubyte *ptr = (const ubyte *)indirect;
for ( i = 0; i < primcount; i++ ) {
DrawElementsIndirect(mode, type, (DrawElementsIndirectCommand *)ptr);
if ( stride == 0 )
ptr += sizeof(DrawElementsIndirectCommand);
else
ptr += stride;
}
""")}
""",
GLenum.IN("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
GLenum.IN("type", "the type of data in the buffer bound to the GL_ELEMENT_ARRAY_BUFFER binding", "GL11#UNSIGNED_BYTE GL11#UNSIGNED_SHORT GL11#UNSIGNED_INT"),
Check("primcount * (stride == 0 ? (5 * 4) : stride)")..MultiType(
PointerMapping.DATA_INT
)..DRAW_INDIRECT_BUFFER..const..void_p.IN("indirect", "a structure containing an array of draw parameters"),
GLsizei.IN("primcount", "the number of elements in the array addressed by {@code indirect}"),
GLsizei.IN("stride", "the distance in basic machine units between elements of the draw parameter array")
)
// ARB_program_interface_query
val ProgramInterfaces = IntConstant(
"""
Accepted by the {@code programInterface} parameter of GetProgramInterfaceiv, GetProgramResourceIndex, GetProgramResourceName, GetProgramResourceiv,
GetProgramResourceLocation, and GetProgramResourceLocationIndex.
""",
"UNIFORM"..0x92E1,
"UNIFORM_BLOCK"..0x92E2,
"PROGRAM_INPUT"..0x92E3,
"PROGRAM_OUTPUT"..0x92E4,
"BUFFER_VARIABLE"..0x92E5,
"SHADER_STORAGE_BLOCK"..0x92E6,
"VERTEX_SUBROUTINE"..0x92E8,
"TESS_CONTROL_SUBROUTINE"..0x92E9,
"TESS_EVALUATION_SUBROUTINE"..0x92EA,
"GEOMETRY_SUBROUTINE"..0x92EB,
"FRAGMENT_SUBROUTINE"..0x92EC,
"COMPUTE_SUBROUTINE"..0x92ED,
"VERTEX_SUBROUTINE_UNIFORM"..0x92EE,
"TESS_CONTROL_SUBROUTINE_UNIFORM"..0x92EF,
"TESS_EVALUATION_SUBROUTINE_UNIFORM"..0x92F0,
"GEOMETRY_SUBROUTINE_UNIFORM"..0x92F1,
"FRAGMENT_SUBROUTINE_UNIFORM"..0x92F2,
"COMPUTE_SUBROUTINE_UNIFORM"..0x92F3,
"TRANSFORM_FEEDBACK_VARYING"..0x92F4
).javaDocLinks + " GL42#ATOMIC_COUNTER_BUFFER"
val ProgramInterfaceParameters = IntConstant(
"Accepted by the {@code pname} parameter of GetProgramInterfaceiv.",
"ACTIVE_RESOURCES"..0x92F5,
"MAX_NAME_LENGTH"..0x92F6,
"MAX_NUM_ACTIVE_VARIABLES"..0x92F7,
"MAX_NUM_COMPATIBLE_SUBROUTINES"..0x92F8
).javaDocLinks
IntConstant(
"Accepted in the {@code props} array of GetProgramResourceiv.",
"NAME_LENGTH"..0x92F9,
"TYPE"..0x92FA,
"ARRAY_SIZE"..0x92FB,
"OFFSET"..0x92FC,
"BLOCK_INDEX"..0x92FD,
"ARRAY_STRIDE"..0x92FE,
"MATRIX_STRIDE"..0x92FF,
"IS_ROW_MAJOR"..0x9300,
"ATOMIC_COUNTER_BUFFER_INDEX"..0x9301,
"BUFFER_BINDING"..0x9302,
"BUFFER_DATA_SIZE"..0x9303,
"NUM_ACTIVE_VARIABLES"..0x9304,
"ACTIVE_VARIABLES"..0x9305,
"REFERENCED_BY_VERTEX_SHADER"..0x9306,
"REFERENCED_BY_TESS_CONTROL_SHADER"..0x9307,
"REFERENCED_BY_TESS_EVALUATION_SHADER"..0x9308,
"REFERENCED_BY_GEOMETRY_SHADER"..0x9309,
"REFERENCED_BY_FRAGMENT_SHADER"..0x930A,
"REFERENCED_BY_COMPUTE_SHADER"..0x930B,
"TOP_LEVEL_ARRAY_SIZE"..0x930C,
"TOP_LEVEL_ARRAY_STRIDE"..0x930D,
"LOCATION"..0x930E,
"LOCATION_INDEX"..0x930F,
"IS_PER_PATCH"..0x92E7
)
void(
"GetProgramInterfaceiv",
"Queries a property of an interface in a program.",
GLuint.IN("program", "the name of a program object whose interface to query"),
GLenum.IN("programInterface", "a token identifying the interface within {@code program} to query", ProgramInterfaces),
GLenum.IN("pname", "the name of the parameter within {@code programInterface} to query", ProgramInterfaceParameters),
Check(1)..ReturnParam..GLint_p.OUT("params", "a variable to retrieve the value of {@code pname} for the program interface")
)
GLuint(
"GetProgramResourceIndex",
"Queries the index of a named resource within a program.",
GLuint.IN("program", "the name of a program object whose resources to query"),
GLenum.IN("programInterface", "a token identifying the interface within {@code program} containing the resource named {Wcode name}", ProgramInterfaces),
const..GLcharUTF8_p.IN("name", "the name of the resource to query the index of")
)
void(
"GetProgramResourceName",
"Queries the name of an indexed resource within a program.",
GLuint.IN("program", "the name of a program object whose resources to query"),
GLenum.IN("programInterface", "a token identifying the interface within {@code program} containing the indexed resource", ProgramInterfaces),
GLuint.IN("index", "the index of the resource within {@code programInterface} of {@code program}"),
AutoSize("name")..GLsizei.IN("bufSize", "the size of the character array whose address is given by {@code name}"),
Check(1)..nullable..GLsizei_p.OUT("length", "a variable which will receive the length of the resource name"),
Return("length", "glGetProgramInterfacei(program, programInterface, GL_MAX_NAME_LENGTH)")..GLcharASCII_p.OUT(
"name",
"a character array into which will be written the name of the resource"
)
)
void(
"GetProgramResourceiv",
"Retrieves values for multiple properties of a single active resource within a program object.",
GLuint.IN("program", "the name of a program object whose resources to query"),
GLenum.IN("programInterface", "a token identifying the interface within {@code program} containing the resource named {@code name}.", ProgramInterfaces),
GLuint.IN("index", "the active resource index"),
AutoSize("props")..GLsizei.IN("propCount", "the number of properties in {@code props}"),
const..GLenum_p.IN("props", "an array that will receive the active resource properties"),
AutoSize("params")..GLsizei.IN("bufSize", "the size of the integer array whose address is given by {@code params}"),
Check(1)..nullable..GLsizei_p.OUT("length", "a variable which will receive the number of values returned"),
GLint_p.OUT("params", "an array that will receive the property values")
)
GLint(
"GetProgramResourceLocation",
"Queries the location of a named resource within a program.",
GLuint.IN("program", "the name of a program object whose resources to query"),
GLenum.IN("programInterface", "a token identifying the interface within {@code program} containing the resource named {@code name}"),
const..GLcharASCII_p.IN("name", "the name of the resource to query the location of")
)
GLint(
"GetProgramResourceLocationIndex",
"Queries the fragment color index of a named variable within a program.",
GLuint.IN("program", "the name of a program object whose resources to query"),
GLenum.IN(
"programInterface",
"a token identifying the interface within {@code program} containing the resource named {@code name}.",
"#PROGRAM_OUTPUT"
),
const..GLcharASCII_p.IN("name", "the name of the resource to query the location of")
)
// ARB_shader_storage_buffer_object
IntConstant(
"Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, and GetBufferPointerv.",
"SHADER_STORAGE_BUFFER"..0x90D2
)
IntConstant(
"""
Accepted by the {@code pname} parameter of GetIntegerv, GetIntegeri_v, GetBooleanv, GetInteger64v, GetFloatv, GetDoublev, GetBooleani_v, GetIntegeri_v,
GetFloati_v, GetDoublei_v, and GetInteger64i_v.
""",
"SHADER_STORAGE_BUFFER_BINDING"..0x90D3
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegeri_v, GetBooleani_v, GetIntegeri_v, GetFloati_v, GetDoublei_v, and GetInteger64i_v.",
"SHADER_STORAGE_BUFFER_START"..0x90D4,
"SHADER_STORAGE_BUFFER_SIZE"..0x90D5
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegerv, GetBooleanv, GetInteger64v, GetFloatv, and GetDoublev.",
"MAX_VERTEX_SHADER_STORAGE_BLOCKS"..0x90D6,
"MAX_GEOMETRY_SHADER_STORAGE_BLOCKS"..0x90D7,
"MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS"..0x90D8,
"MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS"..0x90D9,
"MAX_FRAGMENT_SHADER_STORAGE_BLOCKS"..0x90DA,
"MAX_COMPUTE_SHADER_STORAGE_BLOCKS"..0x90DB,
"MAX_COMBINED_SHADER_STORAGE_BLOCKS"..0x90DC,
"MAX_SHADER_STORAGE_BUFFER_BINDINGS"..0x90DD,
"MAX_SHADER_STORAGE_BLOCK_SIZE"..0x90DE,
"SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT"..0x90DF
)
IntConstant(
"Accepted in the {@code barriers} bitfield in glMemoryBarrier.",
"SHADER_STORAGE_BARRIER_BIT"..0x2000
)
IntConstant(
"Alias for the existing token MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS.",
"MAX_COMBINED_SHADER_OUTPUT_RESOURCES"..0x8F39
)
void(
"ShaderStorageBlockBinding",
"Changes an active shader storage block binding.",
GLuint.IN("program", "the name of the program containing the block whose binding to change"),
GLuint.IN("storageBlockIndex", "the index storage block within the program"),
GLuint.IN("storageBlockBinding", "the index storage block binding to associate with the specified storage block")
)
// ARB_stencil_texturing
IntConstant(
"Accepted by the {@code pname} parameter of TexParameter* and GetTexParameter*.",
"DEPTH_STENCIL_TEXTURE_MODE"..0x90EA
)
// ARB_texture_buffer_range
IntConstant(
"Accepted by the {@code pname} parameter of GetTexLevelParameter.",
"TEXTURE_BUFFER_OFFSET"..0x919D,
"TEXTURE_BUFFER_SIZE"..0x919E
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"TEXTURE_BUFFER_OFFSET_ALIGNMENT"..0x919F
)
void(
"TexBufferRange",
"Binds a range of a buffer's data store to a buffer texture.",
GLenum.IN("target", "the target of the operation", "GL31#TEXTURE_BUFFER"),
GLenum.IN("internalformat", "the internal format of the data in the store belonging to {@code buffer}"),
GLuint.IN("buffer", "the name of the buffer object whose storage to attach to the active buffer texture"),
GLintptr.IN("offset", "the offset of the start of the range of the buffer's data store to attach"),
GLsizeiptr.IN("size", "the size of the range of the buffer's data store to attach")
)
// ARB_texture_storage_multisample
void(
"TexStorage2DMultisample",
"Specifies storage for a two-dimensional multisample texture.",
GLenum.IN("target", "the target of the operation", "GL32#TEXTURE_2D_MULTISAMPLE GL32#PROXY_TEXTURE_2D_MULTISAMPLE"),
GLsizei.IN("samples", "the number of samples in the texture"),
GLenum.IN("internalformat", "the sized internal format to be used to store texture image data"),
GLsizei.IN("width", "the width of the texture, in texels"),
GLsizei.IN("height", "the height of the texture, in texels"),
GLboolean.IN(
"fixedsamplelocations",
"""
whether the image will use identical sample locations and the same number of samples for all texels in the image, and the sample locations will not
depend on the internal format or size of the image
"""
)
)
void(
"TexStorage3DMultisample",
"Specifies storage for a two-dimensional multisample array texture.",
GLenum.IN("target", "the target of the operation", "GL32#TEXTURE_2D_MULTISAMPLE_ARRAY GL32#PROXY_TEXTURE_2D_MULTISAMPLE"),
GLsizei.IN("samples", "the number of samples in the texture"),
GLenum.IN("internalformat", "the sized internal format to be used to store texture image data"),
GLsizei.IN("width", "the width of the texture, in texels"),
GLsizei.IN("height", "the height of the texture, in texels"),
GLsizei.IN("depth", "the depth of the texture, in texels"),
GLboolean.IN(
"fixedsamplelocations",
"""
whether the image will use identical sample locations and the same number of samples for all texels in the image, and the sample locations will not
depend on the internal format or size of the image
"""
)
)
// ARB_texture_view
IntConstant(
"Accepted by the {@code pname} parameters of GetTexParameterfv and GetTexParameteriv.",
"TEXTURE_VIEW_MIN_LEVEL"..0x82DB,
"TEXTURE_VIEW_NUM_LEVELS"..0x82DC,
"TEXTURE_VIEW_MIN_LAYER"..0x82DD,
"TEXTURE_VIEW_NUM_LAYERS"..0x82DE
)
void(
"TextureView",
"Initializes a texture as a data alias of another texture's data store.",
GLuint.IN("texture", "the texture object to be initialized as a view"),
GLenum.IN("target", "the target to be used for the newly initialized texture"),
GLuint.IN("origtexture", "the name of a texture object of which to make a view"),
GLenum.IN("internalformat", "the internal format for the newly created view"),
GLuint.IN("minlevel", "the lowest level of detail of the view"),
GLuint.IN("numlevels", "the number of levels of detail to include in the view"),
GLuint.IN("minlayer", "the index of the first layer to include in the view"),
GLuint.IN("numlayers", "the number of layers to include in the view")
)
// ARB_vertex_attrib_binding
IntConstant(
"Accepted by the {@code pname} parameter of GetVertexAttrib*v.",
"VERTEX_ATTRIB_BINDING"..0x82D4,
"VERTEX_ATTRIB_RELATIVE_OFFSET"..0x82D5
)
IntConstant(
"Accepted by the {@code target} parameter of GetBooleani_v, GetIntegeri_v, GetFloati_v, GetDoublei_v, and GetInteger64i_v.",
"VERTEX_BINDING_DIVISOR"..0x82D6,
"VERTEX_BINDING_OFFSET"..0x82D7,
"VERTEX_BINDING_STRIDE"..0x82D8,
"VERTEX_BINDING_BUFFER"..0x8F4F
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegerv, ....",
"MAX_VERTEX_ATTRIB_RELATIVE_OFFSET"..0x82D9,
"MAX_VERTEX_ATTRIB_BINDINGS"..0x82DA
)
void(
"BindVertexBuffer",
"Binds a buffer to a vertex buffer bind point.",
GLuint.IN("bindingindex", "the index of the vertex buffer binding point to which to bind the buffer"),
GLuint.IN("buffer", "the name of an existing buffer to bind to the vertex buffer binding point"),
GLintptr.IN("offset", "the offset of the first element of the buffer"),
GLsizei.IN("stride", "the distance between elements within the buffer")
)
void(
"VertexAttribFormat",
"Specifies the organization of data in vertex arrays.",
GLuint.IN("attribindex", "the generic vertex attribute array being described"),
GLint.IN("size", "the number of values per vertex that are stored in the array", "1 2 3 4 GL12#BGRA"),
GLenum.IN("type", "the type of the data stored in the array"),
GLboolean.IN(
"normalized",
"""
if true then integer data is normalized to the range [-1, 1] or [0, 1] if it is signed or unsigned, respectively. If false then integer data is
directly converted to floating point.
"""
),
GLuint.IN(
"relativeoffset",
"the offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from"
)
)
void(
"VertexAttribIFormat",
"Specifies the organization of pure integer data in vertex arrays.",
GLuint.IN("attribindex", "the generic vertex attribute array being described"),
GLint.IN("size", "the number of values per vertex that are stored in the array", "1 2 3 4 GL12#BGRA"),
GLenum.IN("type", "the type of the data stored in the array"),
GLuint.IN(
"relativeoffset",
"the offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from"
)
)
void(
"VertexAttribLFormat",
"Specifies the organization of 64-bit double data in vertex arrays.",
GLuint.IN("attribindex", "the generic vertex attribute array being described"),
GLint.IN("size", "the number of values per vertex that are stored in the array", "1 2 3 4 GL12#BGRA"),
GLenum.IN("type", "the type of the data stored in the array"),
GLuint.IN(
"relativeoffset",
"the offset, measured in basic machine units of the first element relative to the start of the vertex buffer binding this attribute fetches from"
)
)
void(
"VertexAttribBinding",
"Associate a vertex attribute and a vertex buffer binding.",
GLuint.IN("attribindex", "the index of the attribute to associate with a vertex buffer binding"),
GLuint.IN("bindingindex", "the index of the vertex buffer binding with which to associate the generic vertex attribute")
)
void(
"VertexBindingDivisor",
"Modifies the rate at which generic vertex attributes advance during instanced rendering.",
GLuint.IN("bindingindex", "the index of the generic vertex attribute"),
GLuint.IN("divisor", "the number of instances that will pass between updates of the generic attribute at slot {@code index}")
)
}
| bsd-3-clause | 348e7c17020641ab3935aac4bb628502 | 40.577487 | 159 | 0.731762 | 3.563706 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/service/FileDownloader.kt | 1 | 6597 | /*
* Copyright (C) 2014 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.service
import io.vavr.control.Try
import org.andstatus.app.account.MyAccount
import org.andstatus.app.context.MyContext
import org.andstatus.app.context.MyStorage
import org.andstatus.app.data.DownloadData
import org.andstatus.app.data.DownloadFile
import org.andstatus.app.data.DownloadStatus
import org.andstatus.app.net.http.HttpRequest
import org.andstatus.app.net.social.ApiRoutineEnum
import org.andstatus.app.net.social.Connection
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.TryUtils
import org.andstatus.app.util.TryUtils.onFailureAsConnectionException
abstract class FileDownloader protected constructor(val myContext: MyContext, val data: DownloadData) {
private var connectionStub: Connection? = null
private var connectionRequired: ConnectionRequired = ConnectionRequired.ANY
fun load(commandData: CommandData): Try<Boolean> =
if (data.getStatus() == DownloadStatus.LOADED) { TryUtils.TRUE }
else doDownloadFile()
.onFailureAsConnectionException { ce ->
if (ce.isHardError) {
data.hardErrorLogged("load", ce)
commandData.getResult().incrementParseExceptions()
} else {
data.softErrorLogged("load", ce)
commandData.getResult().incrementNumIoExceptions()
}
ce.message?.let { message ->
commandData.getResult().setMessage(message)
}
}
.also { data.saveToDatabase() }
.onSuccess { onSuccessfulLoad() }
.map { true }
protected abstract fun onSuccessfulLoad()
private fun doDownloadFile(): Try<Boolean> {
val method = this::doDownloadFile.name
val fileTemp = DownloadFile(
MyStorage.TEMP_FILENAME_PREFIX + MyLog.uniqueCurrentTimeMS + "_" + data.filenameNew
)
if (fileTemp.existsNow()) fileTemp.delete()
data.beforeDownload()
.flatMap {
if (fileTemp.existsNow()) {
TryUtils.failure("$method; Couldn't delete existing temp file $fileTemp")
} else TryUtils.TRUE
}
.flatMap {
val ma = findBestAccountForDownload()
if (ma.isValidAndSucceeded()) {
val connection = connectionStub ?: ma.connection
MyLog.v(this) {
("About to download " + data.toString() + "; connection"
+ (if (connectionStub == null) "" else " (stubbed)")
+ ": " + connection
+ "; account:" + ma.getAccountName())
}
HttpRequest
.of(ApiRoutineEnum.DOWNLOAD_FILE, data.getUri())
.withConnectionRequired(connectionRequired)
.withFile(fileTemp.getFile())
.let(connection::execute)
.map { true }
} else {
TryUtils.failure("No account to download " + data.toString() + "; account:" + ma.getAccountName())
}
}
.flatMap {
if (fileTemp.existsNow()) TryUtils.TRUE
else TryUtils.failure("$method; New temp file doesn't exist $fileTemp")
}
.flatMap {
val fileNew = DownloadFile(data.filenameNew)
MyLog.v(this) { "$method; Renaming $fileTemp to $fileNew" }
fileNew.delete()
if (fileNew.existsNow()) {
TryUtils.failure("$method; Couldn't delete existing file $fileNew")
} else {
val file1 = fileTemp.getFile()
val file2 = fileNew.getFile()
if (file1 == null) {
TryUtils.failure("$method; file1 is null ???")
} else if (file2 == null) {
TryUtils.failure<Boolean>("$method; file2 is null ???")
} else {
if (file1.renameTo(file2)) {
if (!fileNew.existsNow()) {
TryUtils.failure<Boolean>(
"$method; After renamingfrom $fileTemp" +
" new file doesn't exist $fileNew"
)
} else TryUtils.TRUE
} else {
TryUtils.failure("$method; Couldn't rename file $fileTemp to $fileNew")
}
}
}
}
.flatMap { data.onDownloaded() }
.onFailure {
fileTemp.delete()
data.onNoFile()
}
.let { return it }
}
fun setConnectionRequired(connectionRequired: ConnectionRequired): FileDownloader {
this.connectionRequired = connectionRequired
return this
}
fun getStatus(): DownloadStatus {
return data.getStatus()
}
protected abstract fun findBestAccountForDownload(): MyAccount
fun setConnectionStub(connectionStub: Connection?): FileDownloader {
this.connectionStub = connectionStub
return this
}
companion object {
fun newForDownloadData(myContext: MyContext, data: DownloadData): FileDownloader {
return if (data.actorId != 0L) {
AvatarDownloader(myContext, data)
} else {
AttachmentDownloader(myContext, data)
}
}
fun load(downloadData: DownloadData, commandData: CommandData): Try<Boolean> {
val downloader = newForDownloadData(commandData.myAccount.myContext, downloadData)
return downloader.load(commandData)
}
}
}
| apache-2.0 | 7490470ed49b2107bd1f70cc2bffc7ca | 40.23125 | 118 | 0.557526 | 5.043578 | false | false | false | false |
edx/edx-app-android | OpenEdXMobile/src/main/java/org/edx/mobile/view/LockedCourseUnitFragment.kt | 1 | 2533 | package org.edx.mobile.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import com.google.inject.Inject
import org.edx.mobile.R
import org.edx.mobile.databinding.FragmentLockedCourseUnitBinding
import org.edx.mobile.model.api.CourseUpgradeResponse
import org.edx.mobile.model.api.EnrolledCoursesResponse
import org.edx.mobile.model.course.CourseComponent
import org.edx.mobile.module.analytics.Analytics
import org.edx.mobile.module.analytics.AnalyticsRegistry
class LockedCourseUnitFragment : CourseUnitFragment() {
@Inject
var analyticsRegistry: AnalyticsRegistry? = null
companion object {
@JvmStatic
fun newInstance(unit: CourseComponent,
courseData: EnrolledCoursesResponse,
courseUpgradeData: CourseUpgradeResponse): LockedCourseUnitFragment {
val fragment = LockedCourseUnitFragment()
val bundle = Bundle()
bundle.putSerializable(Router.EXTRA_COURSE_UNIT, unit)
bundle.putSerializable(Router.EXTRA_COURSE_DATA, courseData)
bundle.putParcelable(Router.EXTRA_COURSE_UPGRADE_DATA, courseUpgradeData)
fragment.arguments = bundle
return fragment
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding: FragmentLockedCourseUnitBinding =
DataBindingUtil.inflate(inflater, R.layout.fragment_locked_course_unit, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val courseUpgradeData = arguments?.getParcelable(Router.EXTRA_COURSE_UPGRADE_DATA) as CourseUpgradeResponse
val courseData = arguments?.getSerializable(Router.EXTRA_COURSE_DATA) as EnrolledCoursesResponse
loadPaymentBannerFragment(courseData, courseUpgradeData)
analyticsRegistry?.trackScreenView(Analytics.Screens.COURSE_UNIT_LOCKED)
}
private fun loadPaymentBannerFragment(courseData: EnrolledCoursesResponse,
courseUpgradeData: CourseUpgradeResponse) {
PaymentsBannerFragment.loadPaymentsBannerFragment(R.id.fragment_container, courseData, unit,
courseUpgradeData, false, childFragmentManager, false)
}
}
| apache-2.0 | a760b9000894af5296dd48a792ac1f7b | 44.232143 | 115 | 0.727201 | 5.233471 | false | false | false | false |
inorichi/tachiyomi-extensions | src/all/hitomi/src/eu/kanade/tachiyomi/extension/all/hitomi/Hitomi.kt | 1 | 19029 | package eu.kanade.tachiyomi.extension.all.hitomi
import android.app.Application
import android.content.SharedPreferences
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.ConfigurableSource
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.util.asJsoup
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import rx.Single
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import uy.kohesive.injekt.injectLazy
import java.util.Locale
import androidx.preference.CheckBoxPreference as AndroidXCheckBoxPreference
import androidx.preference.PreferenceScreen as AndroidXPreferenceScreen
/**
* Ported from TachiyomiSy
* Original work by NerdNumber9 for TachiyomiEH
*/
open class Hitomi(override val lang: String, private val nozomiLang: String) : HttpSource(), ConfigurableSource {
override val supportsLatest = true
override val name = if (nozomiLang == "all") "Hitomi.la unfiltered" else "Hitomi.la"
override val baseUrl = BASE_URL
private val json: Json by injectLazy()
// Popular
override fun fetchPopularManga(page: Int): Observable<MangasPage> {
return client.newCall(popularMangaRequest(page))
.asObservableSuccess()
.flatMap { responseToMangas(it) }
}
override fun popularMangaRequest(page: Int) = HitomiNozomi.rangedGet(
"$LTN_BASE_URL/popular-$nozomiLang.nozomi",
100L * (page - 1),
99L + 100 * (page - 1)
)
private fun responseToMangas(response: Response): Observable<MangasPage> {
val range = response.header("Content-Range")!!
val total = range.substringAfter('/').toLong()
val end = range.substringBefore('/').substringAfter('-').toLong()
val body = response.body!!
return parseNozomiPage(body.bytes())
.map {
MangasPage(it, end < total - 1)
}
}
private fun parseNozomiPage(array: ByteArray): Observable<List<SManga>> {
val cursor = ByteCursor(array)
val ids = (1..array.size / 4).map {
cursor.nextInt()
}
return nozomiIdsToMangas(ids).toObservable()
}
private fun nozomiIdsToMangas(ids: List<Int>): Single<List<SManga>> {
return Single.zip(
ids.map { int ->
client.newCall(GET("$LTN_BASE_URL/galleryblock/$int.html"))
.asObservableSuccess()
.subscribeOn(Schedulers.io()) // Perform all these requests in parallel
.map { parseGalleryBlock(it) }
.toSingle()
}
) { it.map { m -> m as SManga } }
}
private fun parseGalleryBlock(response: Response): SManga {
val doc = response.asJsoup()
return SManga.create().apply {
val titleElement = doc.selectFirst("h1")
title = titleElement.text()
thumbnail_url = "https:" + if (useHqThumbPref()) {
doc.selectFirst("img").attr("srcset").substringBefore(' ')
} else {
doc.selectFirst("img").attr("src")
}
url = titleElement.child(0).attr("href")
}
}
override fun popularMangaParse(response: Response) = throw UnsupportedOperationException("Not used")
// Latest
override fun fetchLatestUpdates(page: Int): Observable<MangasPage> {
return client.newCall(latestUpdatesRequest(page))
.asObservableSuccess()
.flatMap { responseToMangas(it) }
}
override fun latestUpdatesRequest(page: Int) = HitomiNozomi.rangedGet(
"$LTN_BASE_URL/index-$nozomiLang.nozomi",
100L * (page - 1),
99L + 100 * (page - 1)
)
override fun latestUpdatesParse(response: Response) = throw UnsupportedOperationException("Not used")
// Search
private var cachedTagIndexVersion: Long? = null
private var tagIndexVersionCacheTime: Long = 0
private fun tagIndexVersion(): Single<Long> {
val sCachedTagIndexVersion = cachedTagIndexVersion
return if (sCachedTagIndexVersion == null ||
tagIndexVersionCacheTime + INDEX_VERSION_CACHE_TIME_MS < System.currentTimeMillis()
) {
HitomiNozomi.getIndexVersion(client, "tagindex").subscribeOn(Schedulers.io()).doOnNext {
cachedTagIndexVersion = it
tagIndexVersionCacheTime = System.currentTimeMillis()
}.toSingle()
} else {
Single.just(sCachedTagIndexVersion)
}
}
private var cachedGalleryIndexVersion: Long? = null
private var galleryIndexVersionCacheTime: Long = 0
private fun galleryIndexVersion(): Single<Long> {
val sCachedGalleryIndexVersion = cachedGalleryIndexVersion
return if (sCachedGalleryIndexVersion == null ||
galleryIndexVersionCacheTime + INDEX_VERSION_CACHE_TIME_MS < System.currentTimeMillis()
) {
HitomiNozomi.getIndexVersion(client, "galleriesindex").subscribeOn(Schedulers.io()).doOnNext {
cachedGalleryIndexVersion = it
galleryIndexVersionCacheTime = System.currentTimeMillis()
}.toSingle()
} else {
Single.just(sCachedGalleryIndexVersion)
}
}
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> {
return if (query.startsWith(PREFIX_ID_SEARCH)) {
val id = NOZOMI_ID_PATTERN.find(query.removePrefix(PREFIX_ID_SEARCH))!!.value.toInt()
nozomiIdsToMangas(listOf(id)).map { mangas ->
MangasPage(mangas, false)
}.toObservable()
} else {
if (query.isBlank()) {
val area = filters.filterIsInstance<TypeFilter>()
.joinToString("") {
(it as UriPartFilter).toUriPart()
}
val keyword = filters.filterIsInstance<Text>().toString()
.replace("[", "").replace("]", "")
val popular = filters.filterIsInstance<SortFilter>()
.joinToString("") {
(it as UriPartFilter).toUriPart()
} == "true"
// TODO Cache the results coming out of HitomiNozomi (this TODO dates back to TachiyomiEH)
val hn = Single.zip(tagIndexVersion(), galleryIndexVersion()) { tv, gv -> tv to gv }
.map { HitomiNozomi(client, it.first, it.second) }
val base = hn.flatMap { n ->
n.getGalleryIdsForQuery("$area:$keyword", nozomiLang, popular).map { n to it.toSet() }
}
base.flatMap { (_, ids) ->
val chunks = ids.chunked(PAGE_SIZE)
nozomiIdsToMangas(chunks[page - 1]).map { mangas ->
MangasPage(mangas, page < chunks.size)
}
}.toObservable()
} else {
val splitQuery = query.toLowerCase(Locale.ENGLISH).split(" ")
val positive = splitQuery.filter {
COMMON_WORDS.any { word ->
it !== word
} && !it.startsWith('-')
}.toMutableList()
if (nozomiLang != "all") positive += "language:$nozomiLang"
val negative = (splitQuery - positive).map { it.removePrefix("-") }
// TODO Cache the results coming out of HitomiNozomi (this TODO dates back to TachiyomiEH)
val hn = Single.zip(tagIndexVersion(), galleryIndexVersion()) { tv, gv -> tv to gv }
.map { HitomiNozomi(client, it.first, it.second) }
var base = if (positive.isEmpty()) {
hn.flatMap { n ->
n.getGalleryIdsFromNozomi(null, "index", "all", false)
.map { n to it.toSet() }
}
} else {
val q = positive.removeAt(0)
hn.flatMap { n -> n.getGalleryIdsForQuery(q, nozomiLang, false).map { n to it.toSet() } }
}
base = positive.fold(base) { acc, q ->
acc.flatMap { (nozomi, mangas) ->
nozomi.getGalleryIdsForQuery(q, nozomiLang, false).map {
nozomi to mangas.intersect(it)
}
}
}
base = negative.fold(base) { acc, q ->
acc.flatMap { (nozomi, mangas) ->
nozomi.getGalleryIdsForQuery(q, nozomiLang, false).map {
nozomi to (mangas - it)
}
}
}
base.flatMap { (_, ids) ->
val chunks = ids.chunked(PAGE_SIZE)
nozomiIdsToMangas(chunks[page - 1]).map { mangas ->
MangasPage(mangas, page < chunks.size)
}
}.toObservable()
}
}
}
override fun searchMangaRequest(page: Int, query: String, filters: FilterList) = throw UnsupportedOperationException("Not used")
override fun searchMangaParse(response: Response) = throw UnsupportedOperationException("Not used")
// Filter
override fun getFilterList() = FilterList(
Filter.Header(Filter_SEARCH_MESSAGE),
Filter.Separator(),
SortFilter(),
TypeFilter(),
Text("Keyword")
)
private class TypeFilter : UriPartFilter(
"category",
Array(FILTER_CATEGORIES.size) { i ->
val category = FILTER_CATEGORIES[i]
Pair(category, category)
}
)
private class SortFilter : UriPartFilter(
"Ordered by",
arrayOf(
Pair("Date Added", "false"),
Pair("Popularity", "true")
)
)
private open class UriPartFilter(
displayName: String,
val pair: Array<Pair<String, String>>,
defaultState: Int = 0
) : Filter.Select<String>(displayName, pair.map { it.first }.toTypedArray(), defaultState) {
open fun toUriPart() = pair[state].second
}
private class Text(name: String) : Filter.Text(name) {
override fun toString(): String {
return state
}
}
// Details
override fun mangaDetailsParse(response: Response): SManga {
val document = response.asJsoup()
fun String.replaceSpaces() = this.replace(" ", "_")
return SManga.create().apply {
title = document.select("div.gallery h1 a").joinToString { it.text() }
thumbnail_url = document.select("div.cover img").attr("abs:src")
author = document.select("div.gallery h2 a").joinToString { it.text() }
val tableInfo = document.select("table tr")
.map { tr ->
val key = tr.select("td:first-child").text()
val value = with(tr.select("td:last-child a")) {
when (key) {
"Series", "Characters" -> {
if (text().isNotEmpty())
joinToString { "${attr("href").removePrefix("/").substringBefore("/")}:${it.text().replaceSpaces()}" } else null
}
"Tags" -> joinToString { element ->
element.text().let {
when {
it.contains("♀") -> "female:${it.substringBeforeLast(" ").replaceSpaces()}"
it.contains("♂") -> "male:${it.substringBeforeLast(" ").replaceSpaces()}"
else -> it
}
}
}
else -> joinToString { it.text() }
}
}
Pair(key, value)
}
.plus(Pair("Date uploaded", document.select("div.gallery span.date").text()))
.toMap()
description = tableInfo.filterNot { it.value.isNullOrEmpty() || it.key in listOf("Series", "Characters", "Tags") }.entries.joinToString("\n") { "${it.key}: ${it.value}" }
genre = listOfNotNull(tableInfo["Series"], tableInfo["Characters"], tableInfo["Tags"]).joinToString()
}
}
// Chapters
override fun fetchChapterList(manga: SManga): Observable<List<SChapter>> {
return Observable.just(
listOf(
SChapter.create().apply {
url = manga.url
name = "Chapter"
chapter_number = 0.0f
}
)
)
}
override fun chapterListParse(response: Response) = throw UnsupportedOperationException("Not used")
// Pages
private fun hlIdFromUrl(url: String) =
url.split('/').last().split('-').last().substringBeforeLast('.')
override fun pageListRequest(chapter: SChapter): Request {
return GET("$LTN_BASE_URL/galleries/${hlIdFromUrl(chapter.url)}.js")
}
override fun pageListParse(response: Response): List<Page> {
val str = response.body!!.string()
val json = json.decodeFromString<HitomiChapterDto>(str.removePrefix("var galleryinfo = "))
return json.files.mapIndexed { i, jsonElement ->
val hash = jsonElement.hash
val ext = if (jsonElement.haswebp == 0 || !hitomiAlwaysWebp()) jsonElement.name.split('.').last() else "webp"
val path = if (jsonElement.haswebp == 0 || !hitomiAlwaysWebp()) "images" else "webp"
val hashPath1 = hash.takeLast(1)
val hashPath2 = hash.takeLast(3).take(2)
// https://ltn.hitomi.la/reader.js
// function make_image_element()
val secondSubdomain = if (jsonElement.haswebp == 0 && jsonElement.hasavif == 0) "b" else "a"
Page(i, "", "https://${firstSubdomainFromGalleryId(hashPath2)}$secondSubdomain.hitomi.la/$path/$hashPath1/$hashPath2/$hash.$ext")
}
}
// https://ltn.hitomi.la/common.js
// function subdomain_from_url()
// Change g's if statment from !isNaN(g)
private fun firstSubdomainFromGalleryId(pathSegment: String): Char {
val source = getScrambler()
var numberOfFrontends = 3
var g = pathSegment.toInt(16)
if (g < source[0]) numberOfFrontends = 2
if (g < source[1]) g = 1
return (97 + g.rem(numberOfFrontends)).toChar()
}
private fun getScrambler(): List<Int> {
val response = client.newCall(GET("$LTN_BASE_URL/common.js")).execute()
return HEXADECIMAL.findAll(response.body!!.string()).map { Integer.decode(it.value) }.toList()
}
override fun imageRequest(page: Page): Request {
val request = super.imageRequest(page)
val hlId = request.url.pathSegments.let {
it[it.lastIndex - 1]
}
return request.newBuilder()
.header("Referer", "$BASE_URL/reader/$hlId.html")
.build()
}
override fun imageUrlParse(response: Response) = throw UnsupportedOperationException("Not used")
companion object {
private const val INDEX_VERSION_CACHE_TIME_MS = 1000 * 60 * 10
private const val PAGE_SIZE = 25
const val PREFIX_ID_SEARCH = "id:"
val NOZOMI_ID_PATTERN = "[0-9]*(?=.html)".toRegex()
val HEXADECIMAL = "0[xX][0-9a-fA-F]+".toRegex()
// Common English words and Japanese particles
private val COMMON_WORDS = listOf(
"a", "be", "boy", "de", "girl", "ga", "i", "is", "ka", "na",
"ni", "ne", "no", "suru", "to", "wa", "wo", "yo",
"b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
)
// From HitomiSearchMetaData
const val LTN_BASE_URL = "https://ltn.hitomi.la"
const val BASE_URL = "https://hitomi.la"
// Filter
private val FILTER_CATEGORIES = listOf(
"tag", "male", "female", "type",
"artist", "series", "character", "group"
)
private const val Filter_SEARCH_MESSAGE = "NOTE: Ignored if using text search!"
// Preferences
private const val WEBP_PREF_KEY = "HITOMI_WEBP"
private const val WEBP_PREF_TITLE = "Webp pages"
private const val WEBP_PREF_SUMMARY = "Download webp pages instead of jpeg (when available)"
private const val WEBP_PREF_DEFAULT_VALUE = true
private const val COVER_PREF_KEY = "HITOMI_COVERS"
private const val COVER_PREF_TITLE = "Use HQ covers"
private const val COVER_PREF_SUMMARY = "See HQ covers while browsing"
private const val COVER_PREF_DEFAULT_VALUE = true
}
// Preferences
private val preferences: SharedPreferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
override fun setupPreferenceScreen(screen: AndroidXPreferenceScreen) {
val webpPref = AndroidXCheckBoxPreference(screen.context).apply {
key = "${WEBP_PREF_KEY}_$lang"
title = WEBP_PREF_TITLE
summary = WEBP_PREF_SUMMARY
setDefaultValue(WEBP_PREF_DEFAULT_VALUE)
setOnPreferenceChangeListener { _, newValue ->
val checkValue = newValue as Boolean
preferences.edit().putBoolean("${WEBP_PREF_KEY}_$lang", checkValue).commit()
}
}
val coverPref = AndroidXCheckBoxPreference(screen.context).apply {
key = "${COVER_PREF_KEY}_$lang"
title = COVER_PREF_TITLE
summary = COVER_PREF_SUMMARY
setDefaultValue(COVER_PREF_DEFAULT_VALUE)
setOnPreferenceChangeListener { _, newValue ->
val checkValue = newValue as Boolean
preferences.edit().putBoolean("${COVER_PREF_KEY}_$lang", checkValue).commit()
}
}
screen.addPreference(webpPref)
screen.addPreference(coverPref)
}
private fun hitomiAlwaysWebp(): Boolean = preferences.getBoolean("${WEBP_PREF_KEY}_$lang", WEBP_PREF_DEFAULT_VALUE)
private fun useHqThumbPref(): Boolean = preferences.getBoolean("${COVER_PREF_KEY}_$lang", COVER_PREF_DEFAULT_VALUE)
}
| apache-2.0 | 266b6bd65c1d43b6342694c1bb3d7590 | 39.478723 | 182 | 0.569882 | 4.575517 | false | false | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/model/changelog/ChangeLog.kt | 1 | 2845 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* Represents a change log entry.
*/
package dk.etiktak.backend.model.changelog
import dk.etiktak.backend.model.BaseModel
import dk.etiktak.backend.model.user.Client
import org.springframework.format.annotation.DateTimeFormat
import java.util.*
import javax.persistence.*
@Entity(name = "change_logs")
open class ChangeLog : BaseModel() {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "change_log_id")
var id: Long = 0
@ManyToOne(optional = false)
@JoinColumn(name = "client_id")
var client = Client()
@Column(name = "changed_entity_type")
var changedEntityType = ChangedEntityType.Unknown
@Column(name = "entity_uuid", nullable = true)
var entityUuid: String? = null
@Column(name = "change_type")
var changeType = ChangeType.Unknown
@Column(name = "change_text", nullable = true, columnDefinition="TEXT")
var changeText: String? = null
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
var creationTime = Date()
@PrePersist
fun prePersist() {
creationTime = Date()
}
}
enum class ChangedEntityType {
Unknown,
Product,
ProductCategory,
ProductLabel,
Company,
InfoSource,
InfoChannel
}
enum class ChangeType {
Unknown,
Created,
Edited
}
| bsd-3-clause | 173bdc398f044db27752b847178b449e | 31.701149 | 83 | 0.728998 | 4.363497 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lexer/XQDocLexer.kt | 1 | 11170 | /*
* Copyright (C) 2016-2022 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.xquery.lexer
import com.intellij.psi.tree.IElementType
import uk.co.reecedunn.intellij.plugin.core.lexer.*
import xqt.platform.xml.lexer.*
import xqt.platform.xml.model.XmlChar
import xqt.platform.xml.model.XmlCharReader
@Suppress("DuplicatedCode")
class XQDocLexer : LexerImpl(STATE_CONTENTS) {
companion object {
private const val STATE_CONTENTS = 1
private const val STATE_TAGGED_CONTENTS = 2
private const val STATE_ELEM_CONSTRUCTOR = 3
private const val STATE_ELEM_CONTENTS = 4
private const val STATE_ELEM_CONSTRUCTOR_CLOSING = 5
private const val STATE_ATTRIBUTE_VALUE_QUOTE = 6
private const val STATE_ATTRIBUTE_VALUE_APOS = 7
private const val STATE_TRIM = 8
private const val STATE_PARAM_TAG_CONTENTS_START = 9
private const val STATE_PARAM_TAG_VARNAME = 10
private const val STATE_XQUERY_CONTENTS = 11
private const val STATE_XQUERY_CONTENTS_TRIM = 12
private val TAG_NAMES = mapOf(
"author" to XQDocTokenType.T_AUTHOR,
"deprecated" to XQDocTokenType.T_DEPRECATED,
"error" to XQDocTokenType.T_ERROR,
"param" to XQDocTokenType.T_PARAM,
"return" to XQDocTokenType.T_RETURN,
"see" to XQDocTokenType.T_SEE,
"since" to XQDocTokenType.T_SINCE,
"version" to XQDocTokenType.T_VERSION
)
private val ContentCharExcludedChars = setOf(
XmlCharReader.EndOfBuffer,
LineFeed,
CarriageReturn,
LessThanSign,
Ampersand
)
}
private fun matchEntityReference(): IElementType = when (characters.matchEntityReference()) {
EntityReferenceType.EmptyEntityReference -> XQDocTokenType.EMPTY_ENTITY_REFERENCE
EntityReferenceType.PartialEntityReference -> XQDocTokenType.PARTIAL_ENTITY_REFERENCE
EntityReferenceType.CharacterReference -> XQDocTokenType.CHARACTER_REFERENCE
else -> XQDocTokenType.PREDEFINED_ENTITY_REFERENCE
}
private fun stateDefault(): IElementType? = when (characters.currentChar) {
XmlCharReader.EndOfBuffer -> null
Tilde -> {
characters.advance()
pushState(STATE_CONTENTS)
pushState(STATE_TRIM)
XQDocTokenType.XQDOC_COMMENT_MARKER
}
else -> {
pushState(STATE_XQUERY_CONTENTS)
pushState(STATE_XQUERY_CONTENTS_TRIM)
advance()
tokenType
}
}
private fun stateContents(): IElementType? = when (characters.currentChar) {
XmlCharReader.EndOfBuffer -> null
LessThanSign -> {
characters.advance()
pushState(STATE_ELEM_CONSTRUCTOR)
XQDocTokenType.OPEN_XML_TAG
}
LineFeed, CarriageReturn -> {
pushState(STATE_TRIM)
stateTrim(STATE_TRIM)
}
Ampersand -> matchEntityReference() // XML PredefinedEntityRef and CharRef
else -> run {
characters.advanceUntil { it in ContentCharExcludedChars }
if (characters.currentChar == LineFeed || characters.currentChar == CarriageReturn) {
pushState(STATE_TRIM)
}
XQDocTokenType.CONTENTS
}
}
private fun stateXQueryContents(): IElementType? = when (characters.currentChar) {
XmlCharReader.EndOfBuffer -> null
LineFeed, CarriageReturn -> {
pushState(STATE_XQUERY_CONTENTS_TRIM)
stateTrim(STATE_XQUERY_CONTENTS_TRIM)
}
else -> {
characters.advanceUntil { it == XmlCharReader.EndOfBuffer || it == LineFeed || it == CarriageReturn }
if (characters.currentChar == LineFeed || characters.currentChar == CarriageReturn) {
pushState(STATE_XQUERY_CONTENTS_TRIM)
}
XQDocTokenType.CONTENTS
}
}
private fun stateTaggedContents(): IElementType? = when (characters.currentChar) {
in AlphaNumeric -> {
characters.advanceWhile { it in AlphaNumeric }
val tokenType = TAG_NAMES[tokenText] ?: XQDocTokenType.TAG
if (tokenType === XQDocTokenType.T_PARAM) {
popState()
pushState(STATE_PARAM_TAG_CONTENTS_START)
}
tokenType
}
Space, CharacterTabulation -> {
characters.advanceWhile { it == Space || it == CharacterTabulation }
popState()
XQDocTokenType.WHITE_SPACE
}
else -> {
popState()
stateContents()
}
}
private fun stateParamTagContentsStart(): IElementType? = when (characters.currentChar) {
Space, CharacterTabulation -> {
characters.advanceWhile { it == Space || it == CharacterTabulation }
XQDocTokenType.WHITE_SPACE
}
DollarSign -> {
characters.advance()
popState()
pushState(STATE_PARAM_TAG_VARNAME)
XQDocTokenType.VARIABLE_INDICATOR
}
else -> {
popState()
stateContents()
}
}
private fun stateParamTagVarName(): IElementType? = when (characters.currentChar) {
in S -> {
characters.advanceWhile { it in S }
popState()
XQDocTokenType.WHITE_SPACE
}
// XQuery/XML NCName token rules.
in NameStartChar -> {
characters.advanceWhile { it in NameChar }
XQDocTokenType.NCNAME
}
else -> {
popState()
stateContents()
}
}
private fun stateElemConstructor(state: Int): IElementType? = when (characters.currentChar) {
XmlCharReader.EndOfBuffer -> null
in AlphaNumeric -> {
characters.advanceWhile { it in AlphaNumeric }
XQDocTokenType.XML_TAG
}
in S -> {
characters.advanceWhile { it in S }
XQDocTokenType.WHITE_SPACE
}
EqualsSign -> {
characters.advance()
XQDocTokenType.XML_EQUAL
}
QuotationMark -> {
characters.advance()
pushState(STATE_ATTRIBUTE_VALUE_QUOTE)
XQDocTokenType.XML_ATTRIBUTE_VALUE_START
}
Apostrophe -> {
characters.advance()
pushState(STATE_ATTRIBUTE_VALUE_APOS)
XQDocTokenType.XML_ATTRIBUTE_VALUE_START
}
Solidus -> {
characters.advance()
if (characters.currentChar == GreaterThanSign) {
characters.advance()
popState()
XQDocTokenType.SELF_CLOSING_XML_TAG
} else {
XQDocTokenType.INVALID
}
}
GreaterThanSign -> {
characters.advance()
popState()
if (state == STATE_ELEM_CONSTRUCTOR) {
pushState(STATE_ELEM_CONTENTS)
}
XQDocTokenType.END_XML_TAG
}
else -> {
characters.advance()
XQDocTokenType.INVALID
}
}
private fun stateElemContents(): IElementType? = when (characters.currentChar) {
XmlCharReader.EndOfBuffer -> null
LessThanSign -> {
characters.advance()
if (characters.currentChar == Solidus) {
characters.advance()
popState()
pushState(STATE_ELEM_CONSTRUCTOR_CLOSING)
XQDocTokenType.CLOSE_XML_TAG
} else {
pushState(STATE_ELEM_CONSTRUCTOR)
XQDocTokenType.OPEN_XML_TAG
}
}
Ampersand -> matchEntityReference() // XML PredefinedEntityRef and CharRef
else -> {
characters.advance()
characters.advanceUntil { it == XmlCharReader.EndOfBuffer || it == LessThanSign || it == Ampersand }
XQDocTokenType.XML_ELEMENT_CONTENTS
}
}
private fun stateAttributeValue(endChar: XmlChar): IElementType? = when (characters.currentChar) {
XmlCharReader.EndOfBuffer -> null
endChar -> {
characters.advance()
popState()
XQDocTokenType.XML_ATTRIBUTE_VALUE_END
}
else -> {
characters.advanceWhile { it != XmlCharReader.EndOfBuffer && it != endChar }
XQDocTokenType.XML_ATTRIBUTE_VALUE_CONTENTS
}
}
private fun stateTrim(state: Int): IElementType? = when (characters.currentChar) {
XmlCharReader.EndOfBuffer -> null
Space, CharacterTabulation -> {
characters.advanceWhile { it == Space || it == CharacterTabulation }
XQDocTokenType.WHITE_SPACE
}
LineFeed, CarriageReturn -> {
val pc = characters.currentChar
characters.advance()
if (pc == CarriageReturn && characters.currentChar == LineFeed) {
characters.advance()
}
characters.advanceWhile { it == Space || it == CharacterTabulation }
if (characters.currentChar == Colon) {
characters.advance()
}
XQDocTokenType.TRIM
}
CommercialAt -> {
if (state == STATE_TRIM) {
characters.advance()
popState()
pushState(STATE_TAGGED_CONTENTS)
XQDocTokenType.TAG_MARKER
} else {
popState()
advance()
tokenType
}
}
else -> {
popState()
advance()
tokenType
}
}
override fun advance(state: Int): IElementType? = when (state) {
STATE_DEFAULT -> stateDefault()
STATE_CONTENTS -> stateContents()
STATE_TAGGED_CONTENTS -> stateTaggedContents()
STATE_ELEM_CONSTRUCTOR, STATE_ELEM_CONSTRUCTOR_CLOSING -> stateElemConstructor(state)
STATE_ELEM_CONTENTS -> stateElemContents()
STATE_ATTRIBUTE_VALUE_QUOTE -> stateAttributeValue(QuotationMark)
STATE_ATTRIBUTE_VALUE_APOS -> stateAttributeValue(Apostrophe)
STATE_TRIM, STATE_XQUERY_CONTENTS_TRIM -> stateTrim(state)
STATE_PARAM_TAG_CONTENTS_START -> stateParamTagContentsStart()
STATE_PARAM_TAG_VARNAME -> stateParamTagVarName()
STATE_XQUERY_CONTENTS -> stateXQueryContents()
else -> throw AssertionError("Invalid state: $state")
}
}
| apache-2.0 | 12117868e137f950a05de1d72b553525 | 32.543544 | 113 | 0.587377 | 4.800172 | false | false | false | false |
luanalbineli/popularmovies | app/src/main/java/com/themovielist/moviedetail/MovieDetailPresenter.kt | 1 | 4527 | package com.themovielist.moviedetail
import com.themovielist.base.BasePresenterImpl
import com.themovielist.model.MovieModel
import com.themovielist.model.MovieWithGenreModel
import com.themovielist.model.response.MovieDetailResponseModel
import com.themovielist.repository.movie.CommonRepository
import com.themovielist.repository.movie.MovieRepository
import timber.log.Timber
import javax.inject.Inject
class MovieDetailPresenter @Inject
internal constructor(movieRepository: MovieRepository, private val mCommonRepository: CommonRepository) : BasePresenterImpl(movieRepository), MovieDetailContract.Presenter {
private lateinit var mView: MovieDetailContract.View
private lateinit var mMovieWithGenreModel: MovieWithGenreModel
private lateinit var mMovieDetailResponseModel: MovieDetailResponseModel
private var isFavorite = false
override fun start(movieModel: MovieModel) {
mView.showLoadingMovieDetailIndicator()
mCommonRepository.getAllGenres().subscribe({ genreMap ->
val genreList = mCommonRepository.fillMovieGenresList(movieModel, genreMap)
mMovieWithGenreModel = MovieWithGenreModel(movieModel, genreList)
mView.showMovieInfo(mMovieWithGenreModel)
fetchMovieDetailInfo()
}, { error ->
mView.showErrorLoadingMovieDetail(error)
})
mMovieRepository.isMovieFavorite(movieModel.id).subscribe({ isFavorite, _ ->
mView.setFavoriteButtonState(isFavorite)
this.isFavorite = isFavorite
})
}
private fun fetchMovieDetailInfo() {
mView.showLoadingMovieDetailIndicator()
mMovieRepository.getMovieDetail(mMovieWithGenreModel.movieModel.id)
.subscribe(this::handleGetMovieDetailResponseSuccess, { error ->
mView.showErrorLoadingMovieDetail(error)
})
}
private fun handleGetMovieDetailResponseSuccess(movieDetailResponseModel: MovieDetailResponseModel) {
mMovieDetailResponseModel = movieDetailResponseModel
mView.showMovieDetailInfo()
mView.bindMovieReviewInfo(mMovieDetailResponseModel.reviewsResponseModel.results)
mView.bindMovieTrailerInfo(mMovieDetailResponseModel.trailerResponseModel.trailerList)
val hourMinute = convertRuntimeToHourMinute(movieDetailResponseModel.runtime)
mView.showMovieRuntime(hourMinute)
mView.hideLoadingMovieDetailIndicator()
}
private fun convertRuntimeToHourMinute(runtime: Int): Pair<Int, Int> {
val hours = runtime / 60
val minutes = runtime % 60
return Pair(hours, minutes)
}
override fun setView(view: MovieDetailContract.View) {
mView = view
}
override fun showAllReviews() {
mView.showAllReviews(mMovieDetailResponseModel.reviewsResponseModel.results, mMovieDetailResponseModel.reviewsResponseModel.hasMorePages(), mMovieDetailResponseModel.id)
}
override fun showAllTrailers() {
mView.showAllTrailers(mMovieDetailResponseModel.trailerResponseModel.trailerList)
}
fun toggleFavoriteMovie() {
val request = if (isFavorite) {
mMovieRepository.removeFavoriteMovie(mMovieWithGenreModel.movieModel)
} else {
mMovieRepository.saveFavoriteMovie(mMovieWithGenreModel.movieModel)
}
mView.setFavoriteButtonEnabled(false)
request
.doOnTerminate {
mView.setFavoriteButtonState(isFavorite)
mView.setFavoriteButtonEnabled(true)
}
.subscribe(
{
if (isFavorite) {
mView.showSuccessMessageRemoveFavoriteMovie()
} else {
mView.showSuccessMessageAddFavoriteMovie()
}
isFavorite = !isFavorite
mView.setFavoriteButtonState(isFavorite)
mView.dispatchFavoriteMovieEvent(mMovieWithGenreModel.movieModel, isFavorite)
}
) { throwable ->
Timber.e(throwable, "An error occurred while tried to remove the favorite movie")
mView.showErrorMessageRemoveFavoriteMovie()
}
}
override fun tryFecthMovieDetailAgain() = fetchMovieDetailInfo()
override fun getMovieName() = mMovieWithGenreModel.movieModel.title
}
| apache-2.0 | 180c10ee8d578d14bafce5a3f3d9580b | 40.53211 | 177 | 0.683234 | 5.752224 | false | false | false | false |
savvasdalkitsis/gameframe | workspace/src/main/java/com/savvasdalkitsis/gameframe/feature/workspace/element/palette/model/Palettes.kt | 1 | 2086 | /**
* Copyright 2017 Savvas Dalkitsis
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.workspace.element.palette.model
import android.support.annotation.ArrayRes
import com.savvasdalkitsis.gameframe.feature.workspace.R
import com.savvasdalkitsis.gameframe.infra.injector.ApplicationInjector
object Palettes {
private val resources = ApplicationInjector.application().resources
private const val EMPTY_INDEX = 0
private const val DEFAULT_INDEX = 1
fun preLoaded() = arrayOf(
palette("Empty", R.array.palette_empty),
palette("MS Paint", R.array.palette_ms_paint),
palette("Apple II", R.array.palette_apple_II),
palette("Commodore 64", R.array.palette_c64),
palette("CGA", R.array.palette_cga),
palette("Gameboy", R.array.palette_gameboy),
palette("MSX", R.array.palette_msx),
palette("NES 1", R.array.palette_nes1),
palette("NES 2", R.array.palette_nes2),
palette("NES 3", R.array.palette_nes3),
palette("NES 4", R.array.palette_nes4),
palette("ZX Spectrum", R.array.palette_zx_spectrum)
)
internal fun defaultPalette() = preLoaded()[DEFAULT_INDEX].replicateMoment()
internal fun emptyPalette() = preLoaded()[EMPTY_INDEX].replicateMoment()
private fun palette(title: String, @ArrayRes resource: Int) =
Palette(title = title, colors = resources.getIntArray(resource).toMutableList())
}
| apache-2.0 | 291e5a5fa4e5b1387839b3687a47b3e0 | 40.72 | 92 | 0.694631 | 4.114398 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.