repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jwren/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUField.kt | 4 | 3110 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UField
import org.jetbrains.uast.UFieldEx
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.visitor.UastVisitor
@ApiStatus.Internal
open class KotlinUField(
psi: PsiField,
override val sourcePsi: KtElement?,
givenParent: UElement?
) : AbstractKotlinUVariable(givenParent), UFieldEx, PsiField by psi {
override fun getSourceElement() = sourcePsi ?: this
override val javaPsi = unwrap<UField, PsiField>(psi)
override val psi = javaPsi
override fun getType(): PsiType {
return delegateExpression?.getExpressionType() ?: javaPsi.type
}
override fun acceptsAnnotationTarget(target: AnnotationUseSiteTarget?): Boolean =
target == AnnotationUseSiteTarget.FIELD ||
target == AnnotationUseSiteTarget.PROPERTY_DELEGATE_FIELD ||
(sourcePsi is KtProperty) && (target == null || target == AnnotationUseSiteTarget.PROPERTY)
override fun getInitializer(): PsiExpression? {
return super<AbstractKotlinUVariable>.getInitializer()
}
override fun getOriginalElement(): PsiElement? {
return super<AbstractKotlinUVariable>.getOriginalElement()
}
override fun getNameIdentifier(): PsiIdentifier {
return super.getNameIdentifier()
}
override fun getContainingFile(): PsiFile {
return super.getContainingFile()
}
override fun isPhysical(): Boolean {
return true
}
override fun accept(visitor: UastVisitor) {
if (visitor.visitField(this)) return
uAnnotations.acceptList(visitor)
uastInitializer?.accept(visitor)
delegateExpression?.accept(visitor)
visitor.afterVisitField(this)
}
override fun asRenderString(): String = buildString {
if (uAnnotations.isNotEmpty()) {
uAnnotations.joinTo(this, separator = " ", postfix = " ") { it.asRenderString() }
}
append(javaPsi.renderModifiers())
// NB: use of (potentially delegated) `type`, instead of `javaPsiInternal.type`, is the only major difference.
append("var ").append(javaPsi.name).append(": ").append(type.getCanonicalText(false))
uastInitializer?.let { initializer -> append(" = " + initializer.asRenderString()) }
}
}
// copy of internal org.jetbrains.uast.InternalUastUtilsKt.renderModifiers
// original function should be used instead as soon as becomes public
private fun PsiModifierListOwner.renderModifiers(): String {
val modifiers = PsiModifier.MODIFIERS.filter { hasModifierProperty(it) }.joinToString(" ")
return if (modifiers.isEmpty()) "" else modifiers + " "
}
| apache-2.0 | 2113e876a1860ea1560e5b92bd7994e7 | 37.875 | 158 | 0.717363 | 4.960128 | false | false | false | false |
Pinkal7600/Todo | app/src/main/java/com/pinkal/todo/task/adapter/TaskAdapter.kt | 1 | 3833 | package com.pinkal.todo.task.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pinkal.todo.R
import com.pinkal.todo.task.database.DBManagerTask
import com.pinkal.todo.task.model.TaskModel
import com.pinkal.todo.utils.views.recyclerview.itemdrag.ItemTouchHelperAdapter
import kotlinx.android.synthetic.main.row_task.view.*
import java.util.*
/**
* Created by Pinkal on 31/5/17.
*/
class TaskAdapter(val mContext: Context, var mArrayList: ArrayList<TaskModel>) :
RecyclerView.Adapter<TaskAdapter.ViewHolder>(), ItemTouchHelperAdapter {
val TAG: String = TaskAdapter::class.java.simpleName
val dbManager: DBManagerTask = DBManagerTask(mContext)
override fun getItemCount(): Int {
return mArrayList.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val mView = LayoutInflater.from(mContext).inflate(R.layout.row_task, parent, false)
return ViewHolder(mView)
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
val androidColors = mContext.resources.getIntArray(R.array.random_color)
val randomAndroidColor = androidColors[Random().nextInt(androidColors.size)]
holder!!.viewColorTag.setBackgroundColor(randomAndroidColor)
Log.e(TAG, "title : " + mArrayList[position].title)
Log.e(TAG, "task : " + mArrayList[position].task)
Log.e(TAG, "category : " + mArrayList[position].category)
holder.txtShowTitle.text = mArrayList[position].title
holder.txtShowTask.text = mArrayList[position].task
holder.txtShowCategory.text = mArrayList[position].category
}
/**
* Clear list data
* */
fun clearAdapter() {
this.mArrayList.clear()
notifyDataSetChanged()
}
/**
* Set new data list
* */
fun setList(mArrayList: ArrayList<TaskModel>) {
this.mArrayList = mArrayList
notifyDataSetChanged()
}
fun getList(): ArrayList<TaskModel> {
return this.mArrayList
}
fun deleteTask(position: Int) {
dbManager.delete(mArrayList[position].id!!)
mArrayList.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, mArrayList.size)
}
fun finishTask(position: Int) {
dbManager.finishTask(mArrayList[position].id!!)
mArrayList.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, mArrayList.size)
}
fun unFinishTask(position: Int) {
dbManager.unFinishTask(mArrayList[position].id!!)
mArrayList.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, mArrayList.size)
}
override fun onItemDismiss(position: Int) {
mArrayList.removeAt(position)
notifyItemRemoved(position)
}
override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
Collections.swap(mArrayList, fromPosition, toPosition)
notifyItemMoved(fromPosition, toPosition)
return true
}
override fun getItemViewType(position: Int): Int {
return position
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val viewColorTag = view.viewColorTag!!
val txtShowTitle = view.txtShowTitle!!
val txtShowTask = view.txtShowTask!!
val txtShowCategory = view.txtShowCategory!!
val txtShowDate = view.txtShowDate!!
val textDate = view.textDate!!
val txtShowTime = view.txtShowTime!!
val textTime = view.textTime!!
val textTitle = view.textTitle!!
val textTask = view.textTask!!
}
} | apache-2.0 | c10bf37c54bfd4a9f0e905b7860c94ae | 31.491525 | 91 | 0.690321 | 4.360637 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/refactoring-detector/src/com/intellij/refactoring/detector/actions/FindRefactoringInCommitAction.kt | 4 | 3062 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.detector.actions
import com.intellij.CommonBundle
import com.intellij.json.JsonFileType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages.showDialog
import com.intellij.openapi.ui.Messages.showInfoMessage
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.refactoring.detector.RefactoringDetectorBundle.Companion.message
import com.intellij.testFramework.LightVirtualFile
import com.intellij.vcs.log.VcsLogDataKeys
import org.jetbrains.research.kotlinrminer.ide.KotlinRMiner
import org.jetbrains.research.kotlinrminer.ide.Refactoring
class FindRefactoringInCommitAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val log = e.getData(VcsLogDataKeys.VCS_LOG)
e.presentation.isEnabledAndVisible = e.project != null && log != null && log.selectedCommits.isNotEmpty()
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val changes = e.getData(VcsDataKeys.CHANGES)?.toList() ?: return
runBackgroundableTask(message("progress.find.refactoring.title"), project, false) {
val refactorings = runReadAction { KotlinRMiner.detectRefactorings(project, changes) }
runInEdt {
if (refactorings.isEmpty()) {
showInfoMessage(project, message("message.no.refactorings.found"), message("message.find.refactoring.dialog.title"))
}
else {
val message = message("message.found.refactorings", refactorings.size, refactorings.joinToString(separator = "\n"))
val title = message("message.find.refactoring.dialog.title")
if (showDialog(project, message, title, arrayOf(message("button.show"), CommonBundle.getCancelButtonText()), 0, null) == 0) {
showRefactoringsInEditor(project, refactorings)
}
}
}
}
}
private fun List<Refactoring>.toJsonRepresentation(): String =
"""[${joinToString(separator = ",\n", transform = Refactoring::toJSON)}]"""
private fun showRefactoringsInEditor(project: Project, refactorings: List<Refactoring>) {
val jsonFile = InMemoryJsonVirtualFile(refactorings.toJsonRepresentation())
OpenFileDescriptor(project, jsonFile, 0).navigate(true)
}
private class InMemoryJsonVirtualFile(private val content: String) : LightVirtualFile(message("refactorings.file.name")) {
override fun getContent(): CharSequence = content
override fun getPath(): String = name
override fun getFileType(): FileType = JsonFileType.INSTANCE
}
}
| apache-2.0 | 533a9ad80fcf4a0cb7cf0e1796a499c2 | 46.107692 | 158 | 0.764533 | 4.604511 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/database/SessionDatabase.kt | 1 | 7798 | package org.thoughtcrime.securesms.database
import android.content.Context
import org.signal.core.util.CursorUtil
import org.signal.core.util.SqlUtil
import org.signal.core.util.logging.Log
import org.signal.core.util.requireInt
import org.signal.core.util.requireNonNullBlob
import org.signal.core.util.requireNonNullString
import org.signal.core.util.select
import org.signal.libsignal.protocol.SignalProtocolAddress
import org.signal.libsignal.protocol.state.SessionRecord
import org.whispersystems.signalservice.api.push.ServiceId
import org.whispersystems.signalservice.api.push.SignalServiceAddress
import java.io.IOException
import java.util.LinkedList
class SessionDatabase(context: Context, databaseHelper: SignalDatabase) : Database(context, databaseHelper) {
companion object {
private val TAG = Log.tag(SessionDatabase::class.java)
const val TABLE_NAME = "sessions"
const val ID = "_id"
const val ACCOUNT_ID = "account_id"
const val ADDRESS = "address"
const val DEVICE = "device"
const val RECORD = "record"
const val CREATE_TABLE = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY AUTOINCREMENT,
$ACCOUNT_ID TEXT NOT NULL,
$ADDRESS TEXT NOT NULL,
$DEVICE INTEGER NOT NULL,
$RECORD BLOB NOT NULL,
UNIQUE($ACCOUNT_ID, $ADDRESS, $DEVICE)
)
"""
}
fun store(serviceId: ServiceId, address: SignalProtocolAddress, record: SessionRecord) {
require(address.name[0] != '+') { "Cannot insert an e164 into this table!" }
writableDatabase.compileStatement("INSERT INTO $TABLE_NAME ($ACCOUNT_ID, $ADDRESS, $DEVICE, $RECORD) VALUES (?, ?, ?, ?) ON CONFLICT ($ACCOUNT_ID, $ADDRESS, $DEVICE) DO UPDATE SET $RECORD = excluded.$RECORD").use { statement ->
statement.apply {
bindString(1, serviceId.toString())
bindString(2, address.name)
bindLong(3, address.deviceId.toLong())
bindBlob(4, record.serialize())
execute()
}
}
}
fun load(serviceId: ServiceId, address: SignalProtocolAddress): SessionRecord? {
val projection = arrayOf(RECORD)
val selection = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?"
val args = SqlUtil.buildArgs(serviceId, address.name, address.deviceId)
readableDatabase.query(TABLE_NAME, projection, selection, args, null, null, null).use { cursor ->
if (cursor.moveToFirst()) {
try {
return SessionRecord(cursor.requireNonNullBlob(RECORD))
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return null
}
fun load(serviceId: ServiceId, addresses: List<SignalProtocolAddress>): List<SessionRecord?> {
val projection = arrayOf(ADDRESS, DEVICE, RECORD)
val query = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?"
val args: MutableList<Array<String>> = ArrayList(addresses.size)
val sessions: HashMap<SignalProtocolAddress, SessionRecord?> = LinkedHashMap(addresses.size)
for (address in addresses) {
args.add(SqlUtil.buildArgs(serviceId, address.name, address.deviceId))
sessions[address] = null
}
for (combinedQuery in SqlUtil.buildCustomCollectionQuery(query, args)) {
readableDatabase.query(TABLE_NAME, projection, combinedQuery.where, combinedQuery.whereArgs, null, null, null).use { cursor ->
while (cursor.moveToNext()) {
val address = cursor.requireNonNullString(ADDRESS)
val device = cursor.requireInt(DEVICE)
try {
val record = SessionRecord(cursor.requireNonNullBlob(RECORD))
sessions[SignalProtocolAddress(address, device)] = record
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
}
return sessions.values.toList()
}
fun getAllFor(serviceId: ServiceId, addressName: String): List<SessionRow> {
val results: MutableList<SessionRow> = mutableListOf()
readableDatabase.query(TABLE_NAME, null, "$ACCOUNT_ID = ? AND $ADDRESS = ?", SqlUtil.buildArgs(serviceId, addressName), null, null, null).use { cursor ->
while (cursor.moveToNext()) {
try {
results.add(
SessionRow(
CursorUtil.requireString(cursor, ADDRESS),
CursorUtil.requireInt(cursor, DEVICE),
SessionRecord(CursorUtil.requireBlob(cursor, RECORD))
)
)
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return results
}
fun getAllFor(serviceId: ServiceId, addressNames: List<String?>): List<SessionRow> {
val query: SqlUtil.Query = SqlUtil.buildSingleCollectionQuery(ADDRESS, addressNames)
val results: MutableList<SessionRow> = LinkedList()
val queryString = "$ACCOUNT_ID = ? AND (${query.where})"
val queryArgs: Array<String> = arrayOf(serviceId.toString()) + query.whereArgs
readableDatabase.query(TABLE_NAME, null, queryString, queryArgs, null, null, null).use { cursor ->
while (cursor.moveToNext()) {
try {
results.add(
SessionRow(
address = CursorUtil.requireString(cursor, ADDRESS),
deviceId = CursorUtil.requireInt(cursor, DEVICE),
record = SessionRecord(cursor.requireNonNullBlob(RECORD))
)
)
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return results
}
fun getAll(serviceId: ServiceId): List<SessionRow> {
val results: MutableList<SessionRow> = mutableListOf()
readableDatabase.query(TABLE_NAME, null, "$ACCOUNT_ID = ?", SqlUtil.buildArgs(serviceId), null, null, null).use { cursor ->
while (cursor.moveToNext()) {
try {
results.add(
SessionRow(
address = cursor.requireNonNullString(ADDRESS),
deviceId = cursor.requireInt(DEVICE),
record = SessionRecord(cursor.requireNonNullBlob(RECORD))
)
)
} catch (e: IOException) {
Log.w(TAG, e)
}
}
}
return results
}
fun getSubDevices(serviceId: ServiceId, addressName: String): List<Int> {
val projection = arrayOf(DEVICE)
val selection = "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE != ?"
val args = SqlUtil.buildArgs(serviceId, addressName, SignalServiceAddress.DEFAULT_DEVICE_ID)
val results: MutableList<Int> = mutableListOf()
readableDatabase.query(TABLE_NAME, projection, selection, args, null, null, null).use { cursor ->
while (cursor.moveToNext()) {
results.add(cursor.requireInt(DEVICE))
}
}
return results
}
fun delete(serviceId: ServiceId, address: SignalProtocolAddress) {
writableDatabase.delete(TABLE_NAME, "$ACCOUNT_ID = ? AND $ADDRESS = ? AND $DEVICE = ?", SqlUtil.buildArgs(serviceId, address.name, address.deviceId))
}
fun deleteAllFor(serviceId: ServiceId, addressName: String) {
writableDatabase.delete(TABLE_NAME, "$ACCOUNT_ID = ? AND $ADDRESS = ?", SqlUtil.buildArgs(serviceId, addressName))
}
fun hasSessionFor(serviceId: ServiceId, addressName: String): Boolean {
val query = "$ACCOUNT_ID = ? AND $ADDRESS = ?"
val args = SqlUtil.buildArgs(serviceId, addressName)
readableDatabase.query(TABLE_NAME, arrayOf("1"), query, args, null, null, null, "1").use { cursor ->
return cursor.moveToFirst()
}
}
/**
* @return True if a session exists with this address for _any_ of your identities.
*/
fun hasAnySessionFor(addressName: String): Boolean {
readableDatabase
.select("1")
.from(TABLE_NAME)
.where("$ADDRESS = ?", addressName)
.run()
.use { cursor ->
return cursor.moveToFirst()
}
}
class SessionRow(val address: String, val deviceId: Int, val record: SessionRecord)
}
| gpl-3.0 | 2af92a5497defbb8199f273c349dc6bd | 35.439252 | 231 | 0.654655 | 4.363738 | false | false | false | false |
androidx/androidx | lifecycle/lifecycle-runtime-ktx/src/main/java/androidx/lifecycle/RepeatOnLifecycle.kt | 3 | 6855 | /*
* 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.
*/
package androidx.lifecycle
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume
/**
* Runs the given [block] in a new coroutine when `this` [Lifecycle] is at least at [state] and
* suspends the execution until `this` [Lifecycle] is [Lifecycle.State.DESTROYED].
*
* The [block] will cancel and re-launch as the lifecycle moves in and out of the target state.
*
* ```
* class MyActivity : AppCompatActivity() {
* override fun onCreate(savedInstanceState: Bundle?) {
* /* ... */
* // Runs the block of code in a coroutine when the lifecycle is at least STARTED.
* // The coroutine will be cancelled when the ON_STOP event happens and will
* // restart executing if the lifecycle receives the ON_START event again.
* lifecycleScope.launch {
* lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
* uiStateFlow.collect { uiState ->
* updateUi(uiState)
* }
* }
* }
* }
* }
* ```
*
* The best practice is to call this function when the lifecycle is initialized. For
* example, `onCreate` in an Activity, or `onViewCreated` in a Fragment. Otherwise, multiple
* repeating coroutines doing the same could be created and be executed at the same time.
*
* Repeated invocations of `block` will run serially, that is they will always wait for the
* previous invocation to fully finish before re-starting execution as the state moves in and out
* of the required state.
*
* Warning: [Lifecycle.State.INITIALIZED] is not allowed in this API. Passing it as a
* parameter will throw an [IllegalArgumentException].
*
* @param state [Lifecycle.State] in which `block` runs in a new coroutine. That coroutine
* will cancel if the lifecycle falls below that state, and will restart if it's in that state
* again.
* @param block The block to run when the lifecycle is at least in [state] state.
*/
public suspend fun Lifecycle.repeatOnLifecycle(
state: Lifecycle.State,
block: suspend CoroutineScope.() -> Unit
) {
require(state !== Lifecycle.State.INITIALIZED) {
"repeatOnLifecycle cannot start work with the INITIALIZED lifecycle state."
}
if (currentState === Lifecycle.State.DESTROYED) {
return
}
// This scope is required to preserve context before we move to Dispatchers.Main
coroutineScope {
withContext(Dispatchers.Main.immediate) {
// Check the current state of the lifecycle as the previous check is not guaranteed
// to be done on the main thread.
if (currentState === Lifecycle.State.DESTROYED) return@withContext
// Instance of the running repeating coroutine
var launchedJob: Job? = null
// Registered observer
var observer: LifecycleEventObserver? = null
try {
// Suspend the coroutine until the lifecycle is destroyed or
// the coroutine is cancelled
suspendCancellableCoroutine<Unit> { cont ->
// Lifecycle observers that executes `block` when the lifecycle reaches certain state, and
// cancels when it falls below that state.
val startWorkEvent = Lifecycle.Event.upTo(state)
val cancelWorkEvent = Lifecycle.Event.downFrom(state)
val mutex = Mutex()
observer = LifecycleEventObserver { _, event ->
if (event == startWorkEvent) {
// Launch the repeating work preserving the calling context
launchedJob = [email protected] {
// Mutex makes invocations run serially,
// coroutineScope ensures all child coroutines finish
mutex.withLock {
coroutineScope {
block()
}
}
}
return@LifecycleEventObserver
}
if (event == cancelWorkEvent) {
launchedJob?.cancel()
launchedJob = null
}
if (event == Lifecycle.Event.ON_DESTROY) {
cont.resume(Unit)
}
}
[email protected](observer as LifecycleEventObserver)
}
} finally {
launchedJob?.cancel()
observer?.let {
[email protected](it)
}
}
}
}
}
/**
* [LifecycleOwner]'s extension function for [Lifecycle.repeatOnLifecycle] to allow an easier
* call to the API from LifecycleOwners such as Activities and Fragments.
*
* ```
* class MyActivity : AppCompatActivity() {
* override fun onCreate(savedInstanceState: Bundle?) {
* /* ... */
* // Runs the block of code in a coroutine when the lifecycle is at least STARTED.
* // The coroutine will be cancelled when the ON_STOP event happens and will
* // restart executing if the lifecycle receives the ON_START event again.
* lifecycleScope.launch {
* repeatOnLifecycle(Lifecycle.State.STARTED) {
* uiStateFlow.collect { uiState ->
* updateUi(uiState)
* }
* }
* }
* }
* }
* ```
*
* @see Lifecycle.repeatOnLifecycle
*/
public suspend fun LifecycleOwner.repeatOnLifecycle(
state: Lifecycle.State,
block: suspend CoroutineScope.() -> Unit
): Unit = lifecycle.repeatOnLifecycle(state, block)
| apache-2.0 | e298312cabd2742086bdbd0c32eb455f | 40.79878 | 110 | 0.606856 | 5.201062 | false | false | false | false |
androidx/androidx | benchmark/benchmark-darwin-gradle-plugin/src/test/kotlin/XcResultParserTest.kt | 3 | 2540 | /*
* 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.
*/
import androidx.benchmark.darwin.gradle.skia.Metrics
import androidx.benchmark.darwin.gradle.xcode.GsonHelpers
import androidx.benchmark.darwin.gradle.xcode.XcResultParser
import com.google.common.truth.Truth.assertThat
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class XcResultParserTest {
@Test
fun parseXcResultFileTest() {
val operatingSystem = System.getProperty("os.name")
// Only run this test on an `Mac OS X` machine.
assumeTrue(operatingSystem.contains("Mac", ignoreCase = true))
val xcResultFile = testData("sample-xcode.xcresult")
val parser = XcResultParser(xcResultFile) { args ->
val builder = ProcessBuilder(*args.toTypedArray())
val process = builder.start()
val resultCode = process.waitFor()
require(resultCode == 0) {
"Process terminated unexpectedly (${args.joinToString(separator = " ")})"
}
process.inputStream.use {
it.reader().readText()
}
}
val (record, summaries) = parser.parseResults()
// Usually corresponds to the size of the test suite
// In the case of KMP benchmarks, this is always 1 per module.
assertThat(record.actions.testReferences().size).isEqualTo(1)
assertThat(record.actions.isSuccessful()).isTrue()
// Metrics typically correspond to the number of tests
assertThat(record.metrics.size()).isEqualTo(2)
assertThat(summaries.isNotEmpty()).isTrue()
val metrics = Metrics.buildMetrics(record, summaries)
val json = GsonHelpers.gsonBuilder()
.setPrettyPrinting()
.create()
.toJson(metrics)
println()
println(json)
println()
assertThat(json).isNotEmpty()
}
}
| apache-2.0 | ed1077a51724c88cc13cf48d4f1cebc4 | 39.31746 | 89 | 0.673228 | 4.503546 | false | true | false | false |
GunoH/intellij-community | platform/reproducible-builds/src/FileTreeContentComparison.kt | 1 | 9361 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.reproducibleBuilds.diffTool
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.Decompressor
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.attribute.PosixFileAttributeView
import java.nio.file.attribute.PosixFilePermission
import java.security.DigestInputStream
import java.security.MessageDigest
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.io.path.*
class FileTreeContentComparison(private val diffDir: Path = Path.of(System.getProperty("user.dir")).resolve(".diff"),
private val tempDir: Path = Files.createTempDirectory(this::class.java.simpleName)) {
private companion object {
fun process(vararg command: String, workDir: Path? = null, ignoreExitCode: Boolean = false): ProcessCallResult {
val process = ProcessBuilder(*command).directory(workDir?.toFile()).start()
val output = process.inputStream.bufferedReader().use { it.readText() }
if (!process.waitFor(10, TimeUnit.MINUTES)) {
process.destroyForcibly().waitFor()
error("${command.joinToString(separator = " ")} timed out")
}
require(ignoreExitCode || process.exitValue() == 0) { output }
return ProcessCallResult(process.exitValue(), output)
}
class ProcessCallResult(val exitCode: Int, val stdOut: String)
val isUnsquashfsAvailable by lazy {
process("unsquashfs", "-help").exitCode == 0
}
val isDiffoscopeAvailable by lazy {
process("diffoscope", "--version").exitCode == 0
}
@JvmStatic
fun main(args: Array<String>) {
require(args.count() == 2)
val path1 = Path.of(args[0])
val path2 = Path.of(args[1])
require(path1.exists())
require(path2.exists())
val test = FileTreeContentComparison()
val assertion = when {
path1.isDirectory() && path2.isDirectory() -> test.assertTheSameDirectoryContent(path1, path2).error
path1.isRegularFile() && path2.isRegularFile() -> test.assertTheSameFile(path1, path2)
else -> throw IllegalArgumentException()
}
if (assertion != null) throw assertion
println("Done.")
}
}
init {
FileUtil.delete(diffDir)
Files.createDirectories(diffDir)
}
private fun listingDiff(firstIteration: Set<Path>, nextIteration: Set<Path>) =
((firstIteration - nextIteration) + (nextIteration - firstIteration))
private fun assertTheSameFile(relativeFilePath: Path, dir1: Path, dir2: Path): AssertionError? {
val path1 = dir1.resolve(relativeFilePath)
val path2 = dir2.resolve(relativeFilePath)
return assertTheSameFile(path1, path2, "$relativeFilePath")
}
private fun assertTheSameFile(path1: Path, path2: Path, relativeFilePath: String = path1.name): AssertionError? {
if (!Files.exists(path1) ||
!Files.exists(path2) ||
!path1.isRegularFile() ||
path1.checksum() == path2.checksum() &&
path1.permissions() == path2.permissions()) {
return null
}
println("Failed for $relativeFilePath")
require(path1.extension == path2.extension)
val contentError = when (path1.extension) {
"tar.gz", "gz", "tar" -> assertTheSameDirectoryContent(
path1.unpackingDir().also { Decompressor.Tar(path1).extract(it) },
path2.unpackingDir().also { Decompressor.Tar(path2).extract(it) }
).error ?: AssertionError("No difference in $relativeFilePath content. Timestamp or ordering issue?")
"zip", "jar", "ijx", "sit" -> assertTheSameDirectoryContent(
path1.unpackingDir().also { Decompressor.Zip(path1).withZipExtensions().extract(it) },
path2.unpackingDir().also { Decompressor.Zip(path2).withZipExtensions().extract(it) }
).error ?: AssertionError("No difference in $relativeFilePath content. Timestamp or ordering issue?")
"dmg" -> {
println(".dmg cannot be built reproducibly, content comparison is required")
if (SystemInfo.isMac) {
path1.mountDmg { dmg1Content ->
path2.mountDmg { dmg2Content ->
assertTheSameDirectoryContent(dmg1Content, dmg2Content).error
}
}
}
else {
println("macOS is required to compare content of .dmg, skipping")
null
}
}
"snap" -> {
println(".snap cannot be built reproducibly, content comparison is required")
if (isUnsquashfsAvailable) {
assertTheSameDirectoryContent(
path1.unSquash(path1.unpackingDir()),
path2.unSquash(path2.unpackingDir())
).error
}
else {
println("unsquashfs should be installed to compare content of .snap, skipping")
null
}
}
else -> if (path1.checksum() != path2.checksum()) {
saveDiff(relativeFilePath, path1, path2)
AssertionError("Checksum mismatch for $relativeFilePath")
}
else null
}
if (path1.permissions() != path2.permissions()) {
val permError = AssertionError("Permissions mismatch for $relativeFilePath: ${path1.permissions()} vs ${path2.permissions()}")
contentError?.addSuppressed(permError) ?: return permError
}
return contentError
}
private fun saveDiff(relativePath: String, file1: Path, file2: Path) {
fun fileIn(subdir: String, path: String = relativePath) =
diffDir.resolve(subdir).resolve(path).apply {
parent.createDirectories()
}
val artifacts1 = fileIn("artifacts1")
val artifacts2 = fileIn("artifacts2")
file1.writeContent(artifacts1)
file2.writeContent(artifacts2)
fileIn("diff", relativePath.removeSuffix(".txt") + ".diff.txt")
.writeText(diff(artifacts1, artifacts2))
}
private fun Path.checksum(): String = inputStream().buffered().use { input ->
val digest = MessageDigest.getInstance("SHA-256")
DigestInputStream(input, digest).use {
var bytesRead = 0
val buffer = ByteArray(1024 * 8)
while (bytesRead != -1) {
bytesRead = it.read(buffer)
}
}
Base64.getEncoder().encodeToString(digest.digest())
}
private fun Path.permissions(): Set<PosixFilePermission> =
Files.getFileAttributeView(this, PosixFileAttributeView::class.java)
?.readAttributes()?.permissions() ?: emptySet()
private fun Path.writeContent(target: Path) {
when (extension) {
"jar", "zip", "tar.gz", "gz", "tar", "ijx", "sit" -> error("$this is expected to be already unpacked")
"class" -> target.writeText(process("javap", "-verbose", "$this").stdOut)
"dmg" -> target.writeText(process("7z", "l", "$this", ignoreExitCode = true).stdOut)
else -> copyTo(target, overwrite = true)
}
}
private fun Path.unpackingDir(): Path {
val unpackingDir = tempDir
.resolve("unpacked")
.resolve("$fileName".replace(".", "_"))
.resolve(UUID.randomUUID().toString())
FileUtil.delete(unpackingDir)
Files.createDirectories(unpackingDir)
return unpackingDir
}
private fun diff(path1: Path, path2: Path): String {
return if (isDiffoscopeAvailable) {
process("diffoscope", "$path1", "$path2",
ignoreExitCode = true).stdOut
}
else {
process("git", "diff", "--no-index", "--", "$path1", "$path2",
ignoreExitCode = true).stdOut
}
}
private fun <T> Path.mountDmg(action: (mountPoint: Path) -> T): T {
require(SystemInfo.isMac)
require(extension == "dmg")
val mountPoint = Path.of("/Volumes/${UUID.randomUUID()}")
require(!mountPoint.exists())
process("hdiutil", "attach", "-mountpoint", "$mountPoint", "$this")
return try {
action(mountPoint)
}
finally {
process("diskutil", "unmount", "$mountPoint")
}
}
private fun Path.unSquash(target: Path): Path {
process("unsquashfs", "$this", workDir = target)
return target
}
private fun Path.listDirectory(): List<Path> {
require(isDirectory()) {
"$this is expected to be directory"
}
return Files.walk(this).use { paths ->
paths.filter { it.name != ".DS_Store" }.toList()
}
}
fun assertTheSameDirectoryContent(dir1: Path, dir2: Path): ComparisonResult {
val listing1 = dir1.listDirectory()
val listing2 = dir2.listDirectory()
val relativeListing1 = listing1.map(dir1::relativize)
val listingDiff = listingDiff(relativeListing1.toSet(), listing2.map(dir2::relativize).toSet())
val contentComparisonErrors = relativeListing1.mapNotNull { assertTheSameFile(it, dir1, dir2) }
val error = when {
listingDiff.isNotEmpty() -> AssertionError(listingDiff.joinToString(prefix = "Listing diff for $dir1 and $dir2:\n", separator = "\n"))
contentComparisonErrors.isNotEmpty() -> AssertionError("$dir1 doesn't match $dir2")
else -> null
}?.apply {
contentComparisonErrors.forEach(::addSuppressed)
}
val comparedFiles = listing1
.filterNot { it.isDirectory() }
.map(dir1::relativize)
.minus(listingDiff.toSet())
return ComparisonResult(comparedFiles, error)
}
class ComparisonResult(val comparedFiles: List<Path>, val error: AssertionError?)
}
| apache-2.0 | 570fad7f5abc7165aa6c563085dbb872 | 38.004167 | 140 | 0.661575 | 4.188367 | false | false | false | false |
GunoH/intellij-community | plugins/full-line/src/org/jetbrains/completion/full/line/services/LocalModelsCache.kt | 1 | 2371 | package org.jetbrains.completion.full.line.services
import com.intellij.lang.Language
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.ProjectManager
import com.intellij.util.concurrency.AppExecutorUtil
import org.jetbrains.completion.full.line.currentOpenProject
import org.jetbrains.completion.full.line.models.CachingLocalPipeline
import org.jetbrains.completion.full.line.platform.diagnostics.DiagnosticsService
import org.jetbrains.completion.full.line.platform.diagnostics.FullLinePart
import org.jetbrains.completion.full.line.services.managers.ConfigurableModelsManager
import org.jetbrains.completion.full.line.settings.FullLineNotifications
import java.util.concurrent.ConcurrentHashMap
private val LOG = logger<LocalModelsCache>()
@Service
class LocalModelsCache {
private val models: MutableMap<String, CachingLocalPipeline> = ConcurrentHashMap()
fun tryGetModel(language: Language): CachingLocalPipeline? {
val languageId = language.id
if (languageId !in models) {
scheduleModelLoad(languageId)
}
return models[languageId]
}
fun invalidate() {
models.clear()
}
private fun scheduleModelLoad(languageId: String) {
val startTimestamp = System.currentTimeMillis()
val suitableModel = service<ConfigurableModelsManager>().modelsSchema.targetLanguage(languageId.toLowerCase())
if (suitableModel != null) {
MODELS_LOADER.submit {
try {
val tracer = DiagnosticsService.getInstance().logger(FullLinePart.BEAM_SEARCH, log = LOG)
models[languageId] = suitableModel.loadModel { msg -> tracer.debug(msg) }
LOG.info("Loading local model with key: \"$languageId\" took ${System.currentTimeMillis() - startTimestamp}ms.")
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
else {
val project = ProjectManager.getInstanceIfCreated()?.currentOpenProject()
if (project != null) {
FullLineNotifications.Local.showMissingModel(project, Language.findLanguageByID(languageId)!!)
}
}
}
companion object {
fun getInstance(): LocalModelsCache = service()
val MODELS_LOADER = AppExecutorUtil.createBoundedApplicationPoolExecutor("Full Line local models loader", 1)
}
}
| apache-2.0 | 5af7f122b4ac52e6ac372fbcae5d9ece | 36.046875 | 122 | 0.752425 | 4.568401 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/repl/src/org/jetbrains/kotlin/console/CommandExecutor.kt | 4 | 1743 | // 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.console
import com.intellij.execution.process.BaseOSProcessHandler
import com.intellij.openapi.command.WriteCommandAction
import org.jetbrains.kotlin.cli.common.repl.replInputAsXml
import org.jetbrains.kotlin.console.actions.logError
class CommandExecutor(private val runner: KotlinConsoleRunner) {
private val commandHistory = runner.commandHistory
private val historyUpdater = HistoryUpdater(runner)
fun executeCommand() = WriteCommandAction.runWriteCommandAction(runner.project) {
val commandText = getTrimmedCommandText()
if (commandText.isEmpty()) {
return@runWriteCommandAction
}
val historyDocumentRange = historyUpdater.printNewCommandInHistory(commandText)
commandHistory.addEntry(CommandHistory.Entry(commandText, historyDocumentRange))
sendCommandToProcess(commandText)
}
private fun getTrimmedCommandText(): String {
val consoleView = runner.consoleView
val document = consoleView.editorDocument
return document.text.trim()
}
private fun sendCommandToProcess(command: String) {
val processHandler = runner.processHandler
val processInputOS = processHandler.processInput ?: return logError(this::class.java, "<p>Broken process stream</p>")
val charset = (processHandler as? BaseOSProcessHandler)?.charset ?: Charsets.UTF_8
val xmlRes = command.replInputAsXml()
val bytes = ("$xmlRes\n").toByteArray(charset)
processInputOS.write(bytes)
processInputOS.flush()
}
} | apache-2.0 | d514b4a399717b3e434bb2aecba441d9 | 39.55814 | 158 | 0.740677 | 4.841667 | false | false | false | false |
craftsmenlabs/gareth-jvm | gareth-core/src/main/kotlin/org/craftsmenlabs/gareth/validator/time/DurationExpressionParser.kt | 1 | 2186 | package org.craftsmenlabs.gareth.validator.time
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.time.Duration
import java.time.temporal.ChronoUnit
import java.time.temporal.TemporalUnit
import java.util.regex.Pattern
/**
* Utility to parse common time expression to a Duration, e.g. 1 minute, 5 hours, 3 days
*/
@Component
open class DurationExpressionParser constructor(@Autowired val dateTimeService: TimeService) {
private val PATTERN = Pattern.compile("(\\d{1,5}) ?([a-zA-Z]{3,7})")
fun parse(text: String): Duration? {
val matcher = PATTERN.matcher(text)
if (matcher == null || !matcher.matches()) {
return null
}
return parse(matcher.group(1), matcher.group(2))
}
private fun parse(amount: String, unit: String): Duration? {
val value = amount.toInt()
if (value < 1 || value > 99999) {
return null
}
when (TimeUnit.safeParse(unit)) {
TimeUnit.SECOND, TimeUnit.SECONDS -> return getFixedDuration(ChronoUnit.SECONDS, value)
TimeUnit.MINUTE, TimeUnit.MINUTES -> return getFixedDuration(ChronoUnit.MINUTES, value)
TimeUnit.HOUR, TimeUnit.HOURS -> return getFixedDuration(ChronoUnit.HOURS, value)
TimeUnit.DAY, TimeUnit.DAYS -> return getFixedDuration(ChronoUnit.DAYS, value)
TimeUnit.WEEK, TimeUnit.WEEKS -> return getFlexibleDuration(ChronoUnit.WEEKS, value)
TimeUnit.MONTH, TimeUnit.MONTHS -> return getFlexibleDuration(ChronoUnit.MONTHS, value)
TimeUnit.YEAR, TimeUnit.YEARS -> return getFlexibleDuration(ChronoUnit.YEARS, value)
else -> return null
}
}
private fun getFixedDuration(unit: ChronoUnit, amount: Int): Duration {
return Duration.of(amount.toLong(), unit)
}
private fun getFlexibleDuration(unit: TemporalUnit, amount: Int): Duration {
val now = dateTimeService.now()
val later = now.plus(amount.toLong(), unit)
val millisBetween = Duration.between(now, later).toMillis()
return Duration.ofMillis(millisBetween)
}
}
| gpl-2.0 | 2920a1c2ca5c6a983c520de8b51a8306 | 38.035714 | 99 | 0.680238 | 4.345924 | false | false | false | false |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/ui/statusbar/StatusActionGroupPopup.kt | 1 | 2301 | package zielu.gittoolbox.ui.statusbar
import com.intellij.dvcs.ui.LightActionGroup
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.Separator
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Conditions
import com.intellij.ui.popup.PopupFactoryImpl.ActionGroupPopup
import zielu.gittoolbox.ResBundle.message
import zielu.gittoolbox.ui.statusbar.StatusBarActions.actionsFor
import zielu.gittoolbox.ui.statusbar.actions.RefreshStatusAction
import zielu.gittoolbox.ui.statusbar.actions.UpdateAction
import zielu.gittoolbox.ui.util.AppUiUtil
import zielu.gittoolbox.util.GtUtil
import zielu.gittoolbox.util.GtUtil.getRepositories
import zielu.gittoolbox.util.GtUtil.sort
internal class StatusActionGroupPopup(
title: String,
myProject: Project
) : ActionGroupPopup(
title,
createActions(myProject),
createDataContext(myProject),
false,
false,
true,
false,
null,
-1,
Conditions.alwaysTrue(),
null
) {
private companion object {
private val log = Logger.getInstance(StatusActionGroupPopup::class.java)
fun createDataContext(project: Project): DataContext {
return AppUiUtil.prepareDataContextWithContextComponent(project)
}
fun createActions(project: Project): ActionGroup {
val actionGroup = LightActionGroup()
actionGroup.add(RefreshStatusAction())
actionGroup.add(UpdateAction())
actionGroup.addAll(createPerRepositoryActions(project))
return actionGroup
}
private fun createPerRepositoryActions(project: Project): List<AnAction> {
val actions = mutableListOf<AnAction>()
var repositories = getRepositories(project)
repositories = sort(repositories)
val repos = repositories.filter { GtUtil.hasRemotes(it) }
if (repos.isNotEmpty()) {
actions.add(Separator.create(message("statusBar.status.menu.repositories.title")))
if (repos.size == 1) {
val repo = repos[0]
actions.addAll(actionsFor(repo))
} else {
actions.addAll(repos.map { RepositoryActions(it) })
}
}
return actions
}
}
}
| apache-2.0 | 86865f3163517662ad3a6829a7b6d776 | 31.871429 | 90 | 0.755758 | 4.425 | false | false | false | false |
80998062/Fank | domain/src/main/java/com/sinyuk/fanfou/domain/api/RestAPI.kt | 1 | 4939 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.domain.api
import android.arch.lifecycle.LiveData
import com.google.gson.annotations.SerializedName
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.DO.Status
import com.sinyuk.fanfou.domain.DO.Trend
import retrofit2.Call
import retrofit2.http.*
import java.util.*
/**
* Created by sinyuk on 2017/11/28.
*
*/
@Suppress("FunctionName")
interface RestAPI {
@GET("users/show.json?format=html")
fun show_user(@Query("id") uniqueId: String): LiveData<ApiResponse<Player>>
@GET("account/verify_credentials.json?format=html")
fun verify_credentials(): LiveData<ApiResponse<Player>>
@GET("account/verify_credentials.json?format=html")
fun fetch_profile(): Call<Player>
@GET("statuses/{path}.json?format=html")
fun fetch_from_path(@Path("path") path: String,
@Query("count") count: Int,
@Query("since_id") since: String? = null,
@Query("max_id") max: String? = null,
@Query("id") id: String? = null,
@Query("page") page: Int? = null): Call<MutableList<Status>>
@GET("favorites/id.json?format=html")
fun fetch_favorites(@Query("id") id: String? = null,
@Query("count") count: Int,
@Query("page") page: Int): Call<MutableList<Status>>
// @GET("/search/public_timeline.json?format=html")
// fun search_statuses(@Query(value = "q", encoded = false) query: String,
// @Query("count") count: Int,
// @Query("page") page: Int? = null): Call<MutableList<Status>>
companion object {
fun buildQueryUrl(query: String, count: Int, page: Int? = null): String = "http://api.fanfou.com/search/public_timeline.json?format=html&q=\"圣诞\"&count=50&page=1"
}
@GET
fun search_statuses(@Url url: String): Call<MutableList<Status>>
@GET("/search/user_timeline.json?format=html")
fun search_user_statuses(@Query(value = "q", encoded = false) query: String,
@Query("count") count: Int,
@Query("id") id: String,
@Query("page") page: Int? = null): Call<MutableList<Status>>
@GET("/search/users.json?format=html")
fun search_users(@Query(value = "q", encoded = false) query: String,
@Query("count") count: Int,
@Query("id") id: String,
@Query("page") page: Int? = null): Call<PlayerList>
data class PlayerList @JvmOverloads constructor(@SerializedName("total_number") var total: Int = 0,
@SerializedName("users") var data: MutableList<Player> = mutableListOf())
@GET("/users/friends.json?format=html")
fun fetch_friends(@Query("id") id: String?,
@Query("count") count: Int,
@Query("page") page: Int? = null): Call<MutableList<Player>>
@GET("/users/followers.json?format=html")
fun fetch_followers(@Query("id") id: String?,
@Query("count") count: Int,
@Query("page") page: Int? = null): Call<MutableList<Player>>
@GET("trends/list.json")
fun trends(): Call<TrendList>
data class TrendList @JvmOverloads constructor(@SerializedName("as_of") var date: Date? = null,
@SerializedName("trends") var data: MutableList<Trend> = mutableListOf())
@POST("favorites/create/{id}.json?format=html")
fun createFavorite(@Path("id") id: String): Call<Status>
@POST("favorites/destroy/{id}.json?format=html")
fun deleteFavorite(@Path("id") id: String): Call<Status>
@POST("statuses/destroy.json?format=html")
fun deleteStatus(@Query("id") id: String): Call<Status>
/**
* 获取有照片的状态
*/
@GET("photos/user_timeline.json?format=html")
fun photos(@Query("count") count: Int,
@Query("since_id") since: String? = null,
@Query("max_id") max: String? = null,
@Query("id") id: String? = null,
@Query("page") page: Int? = null): Call<MutableList<Status>>
} | mit | 7a11d97bd92dcac7f779401a782acf88 | 36.846154 | 170 | 0.591177 | 3.876281 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/data/repository/settings/SettingsImpl.kt | 1 | 5387 | package com.ivanovsky.passnotes.data.repository.settings
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.StringRes
import androidx.preference.PreferenceManager
import com.ivanovsky.passnotes.R
import com.ivanovsky.passnotes.data.repository.settings.SettingsImpl.Pref.AUTO_CLEAR_CLIPBOARD_DELAY_IN_MS
import com.ivanovsky.passnotes.data.repository.settings.SettingsImpl.Pref.AUTO_LOCK_DELAY_IN_MS
import com.ivanovsky.passnotes.data.repository.settings.SettingsImpl.Pref.DROPBOX_AUTH_TOKEN
import com.ivanovsky.passnotes.data.repository.settings.SettingsImpl.Pref.IS_EXTERNAL_STORAGE_CACHE_ENABLED
import com.ivanovsky.passnotes.data.repository.settings.SettingsImpl.Pref.IS_LOCK_NOTIFICATION_VISIBLE
import com.ivanovsky.passnotes.data.repository.settings.SettingsImpl.PrefType.BOOLEAN
import com.ivanovsky.passnotes.data.repository.settings.SettingsImpl.PrefType.INT
import com.ivanovsky.passnotes.data.repository.settings.SettingsImpl.PrefType.STRING
import com.ivanovsky.passnotes.domain.ResourceProvider
import java.util.concurrent.TimeUnit
class SettingsImpl(
private val resourceProvider: ResourceProvider,
context: Context
) : Settings {
private val preferences = PreferenceManager.getDefaultSharedPreferences(context)
private val nameResIdToPreferenceMap: Map<Int, Pref> = Pref.values().associateBy { it.keyId }
override var isExternalStorageCacheEnabled: Boolean
get() = getBoolean(IS_EXTERNAL_STORAGE_CACHE_ENABLED)
set(value) {
putBoolean(IS_EXTERNAL_STORAGE_CACHE_ENABLED, value)
}
override var isLockNotificationVisible: Boolean
get() = getBoolean(IS_LOCK_NOTIFICATION_VISIBLE)
set(value) {
putBoolean(IS_LOCK_NOTIFICATION_VISIBLE, value)
}
override var autoLockDelayInMs: Int
get() = getString(AUTO_LOCK_DELAY_IN_MS)?.toInt()
?: (AUTO_LOCK_DELAY_IN_MS.defaultValue as String).toInt()
set(value) {
putString(AUTO_LOCK_DELAY_IN_MS, value.toString())
}
override var autoClearClipboardDelayInMs: Int
get() = getString(AUTO_CLEAR_CLIPBOARD_DELAY_IN_MS)?.toInt()
?: (AUTO_CLEAR_CLIPBOARD_DELAY_IN_MS.defaultValue as String).toInt()
set(value) {
putString(AUTO_CLEAR_CLIPBOARD_DELAY_IN_MS, value.toString())
}
override var dropboxAuthToken: String?
get() = getString(DROPBOX_AUTH_TOKEN)
set(value) {
putString(DROPBOX_AUTH_TOKEN, value)
}
override fun initDefaultIfNeed(pref: Pref) {
if (preferences.contains(keyFor(pref))) {
return
}
when (pref.type) {
BOOLEAN -> putBoolean(pref, getDefaultValue(pref))
INT -> putInt(pref, getDefaultValue(pref))
STRING -> putString(pref, getDefaultValue(pref))
}
}
fun clean() {
val editor = preferences.edit()
editor.clear()
editor.apply()
}
private fun getBoolean(pref: Pref): Boolean {
return preferences.getBoolean(keyFor(pref), getDefaultValue(pref))
}
private fun getString(pref: Pref): String? {
return preferences.getString(keyFor(pref), getDefaultValue(pref))
}
private fun getInt(pref: Pref): Int {
return preferences.getInt(keyFor(pref), getDefaultValue(pref))
}
private fun putBoolean(pref: Pref, value: Boolean) {
putValue {
putBoolean(keyFor(pref), value)
}
}
private fun putString(pref: Pref, value: String?) {
putValue {
putString(keyFor(pref), value)
}
}
private fun putInt(pref: Pref, value: Int) {
putValue {
putInt(keyFor(pref), value)
}
}
private inline fun putValue(action: SharedPreferences.Editor.() -> Unit) {
val editor = preferences.edit()
action.invoke(editor)
editor.apply()
}
private fun keyFor(pref: Pref) = resourceProvider.getString(pref.keyId)
private inline fun <reified T> getDefaultValue(pref: Pref): T {
return nameResIdToPreferenceMap[pref.keyId]?.defaultValue as T
}
enum class PrefType {
BOOLEAN,
INT,
STRING
}
enum class Pref(
@StringRes val keyId: Int,
val type: PrefType,
val defaultValue: Any?
) {
// Boolean prefs
IS_EXTERNAL_STORAGE_CACHE_ENABLED(
keyId = R.string.pref_is_external_storage_cache_enabled,
type = BOOLEAN,
defaultValue = false
),
IS_LOCK_NOTIFICATION_VISIBLE(
keyId = R.string.pref_is_lock_notification_visible,
type = BOOLEAN,
defaultValue = true
),
// Int prefs
AUTO_LOCK_DELAY_IN_MS(
keyId = R.string.pref_auto_lock_delay_in_ms,
type = STRING,
defaultValue = TimeUnit.MINUTES.toMillis(5).toString()
),
AUTO_CLEAR_CLIPBOARD_DELAY_IN_MS(
keyId = R.string.pref_auto_clear_clipboard_delay_in_ms,
type = STRING,
defaultValue = TimeUnit.SECONDS.toMillis(30).toString()
),
// String prefs
DROPBOX_AUTH_TOKEN(
keyId = R.string.pref_dropbox_auth_token,
type = STRING,
defaultValue = null
)
}
} | gpl-2.0 | ae3874ad0d5772b89f9858050d6a3c18 | 32.465839 | 107 | 0.651569 | 4.326908 | false | false | false | false |
Suomaa/androidLearning | LoginApp/app/src/main/java/com/example/loginapp/ui/login/LoginViewModel.kt | 1 | 1936 | package com.example.loginapp.ui.login
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import android.util.Patterns
import com.example.loginapp.data.LoginRepository
import com.example.loginapp.data.Result
import com.example.loginapp.R
class LoginViewModel(private val loginRepository: LoginRepository) : ViewModel() {
private val _loginForm = MutableLiveData<LoginFormState>()
val loginFormState: LiveData<LoginFormState> = _loginForm
private val _loginResult = MutableLiveData<LoginResult>()
val loginResult: LiveData<LoginResult> = _loginResult
fun login(username: String, password: String) {
// can be launched in a separate asynchronous job
val result = loginRepository.login(username, password)
if (result is Result.Success) {
_loginResult.value = LoginResult(success = LoggedInUserView(displayName = result.data.displayName))
} else {
_loginResult.value = LoginResult(error = R.string.login_failed)
}
}
fun loginDataChanged(username: String, password: String) {
if (!isUserNameValid(username)) {
_loginForm.value = LoginFormState(usernameError = R.string.invalid_username)
} else if (!isPasswordValid(password)) {
_loginForm.value = LoginFormState(passwordError = R.string.invalid_password)
} else {
_loginForm.value = LoginFormState(isDataValid = true)
}
}
// A placeholder username validation check
private fun isUserNameValid(username: String): Boolean {
return if (username.contains('@')) {
Patterns.EMAIL_ADDRESS.matcher(username).matches()
} else {
username.isNotBlank()
}
}
// A placeholder password validation check
private fun isPasswordValid(password: String): Boolean {
return password.length > 5
}
}
| apache-2.0 | 54deb07f2229db3b9dcc2f6267911fd5 | 34.851852 | 111 | 0.691632 | 4.587678 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/listener/PlayerInteractEntityListener.kt | 1 | 3084 | /*
* Copyright 2016 Ross Binden
*
* 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.rpkit.characters.bukkit.listener
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerInteractEntityEvent
import org.bukkit.inventory.EquipmentSlot.HAND
/**
* Player interact entity listener for character cards.
* This shows character cards upon right-clicking players.
*/
class PlayerInteractEntityListener(private val plugin: RPKCharactersBukkit): Listener {
@EventHandler
fun onPlayerInteractEntity(event: PlayerInteractEntityEvent) {
if (event.hand == HAND) {
if (event.player.isSneaking || !plugin.config.getBoolean("characters.view-card-requires-sneak")) {
if (event.rightClicked is Player) {
if (event.player.hasPermission("rpkit.characters.command.character.card.other")) {
val bukkitPlayer = event.rightClicked as Player
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer)
if (minecraftProfile != null) {
val character = characterProvider.getActiveCharacter(minecraftProfile)
if (character != null) {
val rightClicker = minecraftProfileProvider.getMinecraftProfile(event.player)
if (rightClicker != null) {
character.showCharacterCard(rightClicker)
}
} else {
event.player.sendMessage(plugin.messages["no-character-other"])
}
} else {
event.player.sendMessage(plugin.messages["no-minecraft-profile"])
}
} else {
event.player.sendMessage(plugin.messages["no-permission-character-card-other"])
}
}
}
}
}
}
| apache-2.0 | 79089b2c96ec322d8e423a93c21c9370 | 47.1875 | 136 | 0.634241 | 5.429577 | false | false | false | false |
square/sqldelight | sqldelight-gradle-plugin/src/main/kotlin/com/squareup/sqldelight/gradle/GenerateSchemaTask.kt | 1 | 3995 | package com.squareup.sqldelight.gradle
import com.squareup.sqldelight.VERSION
import com.squareup.sqldelight.core.SqlDelightCompilationUnit
import com.squareup.sqldelight.core.SqlDelightDatabaseProperties
import com.squareup.sqldelight.core.SqlDelightEnvironment
import com.squareup.sqldelight.core.lang.SqlDelightQueriesFile
import com.squareup.sqldelight.core.lang.util.forInitializationStatements
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileTree
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Nested
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SkipWhenEmpty
import org.gradle.api.tasks.TaskAction
import org.gradle.workers.WorkAction
import org.gradle.workers.WorkParameters
import java.io.File
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
@Suppress("UnstableApiUsage") // Worker API
@CacheableTask
abstract class GenerateSchemaTask : SqlDelightWorkerTask() {
@Suppress("unused") // Required to invalidate the task on version updates.
@Input val pluginVersion = VERSION
@get:OutputDirectory
var outputDirectory: File? = null
@Input val projectName: Property<String> = project.objects.property(String::class.java)
@Nested lateinit var properties: SqlDelightDatabasePropertiesImpl
@Nested lateinit var compilationUnit: SqlDelightCompilationUnitImpl
@Input var verifyMigrations: Boolean = false
@TaskAction
fun generateSchemaFile() {
workQueue().submit(GenerateSchema::class.java) {
it.outputDirectory.set(outputDirectory)
it.moduleName.set(projectName)
it.properties.set(properties)
it.verifyMigrations.set(verifyMigrations)
it.compilationUnit.set(compilationUnit)
}
}
@InputFiles
@SkipWhenEmpty
@PathSensitive(PathSensitivity.RELATIVE)
override fun getSource(): FileTree {
return super.getSource()
}
interface GenerateSchemaWorkParameters : WorkParameters {
val outputDirectory: DirectoryProperty
val moduleName: Property<String>
val properties: Property<SqlDelightDatabaseProperties>
val compilationUnit: Property<SqlDelightCompilationUnit>
val verifyMigrations: Property<Boolean>
}
abstract class GenerateSchema : WorkAction<GenerateSchemaWorkParameters> {
private val sourceFolders: List<File>
get() = parameters.compilationUnit.get().sourceFolders.map { it.folder }
override fun execute() {
val environment = SqlDelightEnvironment(
sourceFolders = sourceFolders.filter { it.exists() },
dependencyFolders = emptyList(),
moduleName = parameters.moduleName.get(),
properties = parameters.properties.get(),
verifyMigrations = parameters.verifyMigrations.get(),
compilationUnit = parameters.compilationUnit.get(),
)
var maxVersion = 1
environment.forMigrationFiles { migrationFile ->
maxVersion = maxOf(maxVersion, migrationFile.version + 1)
}
val outputDirectory = parameters.outputDirectory.get().asFile
File("$outputDirectory/$maxVersion.db").apply {
if (exists()) delete()
}
createConnection("$outputDirectory/$maxVersion.db").use { connection ->
val sourceFiles = ArrayList<SqlDelightQueriesFile>()
environment.forSourceFiles { file ->
if (file is SqlDelightQueriesFile) sourceFiles.add(file)
}
sourceFiles.forInitializationStatements { sqlText ->
connection.prepareStatement(sqlText).execute()
}
}
}
private fun createConnection(path: String): Connection {
return try {
DriverManager.getConnection("jdbc:sqlite:$path")
} catch (e: SQLException) {
DriverManager.getConnection("jdbc:sqlite:$path")
}
}
}
}
| apache-2.0 | 5c0859714eee4122dd48444f1373e91f | 34.353982 | 89 | 0.750688 | 4.716647 | false | false | false | false |
EMResearch/EvoMaster | e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/mutation/type/Flower.kt | 1 | 207 | package com.foo.graphql.mutation.type
data class Flower (
var id: Int? = null,
var name: String? = null,
var type: String? = null,
var color: String? = null,
var price: Int? = null) | lgpl-3.0 | 314e8041a6ace4e8f96a158b3c516cab | 25 | 37 | 0.608696 | 3.393443 | false | false | false | false |
grote/Liberario | app/src/main/java/de/grobox/transportr/data/locations/LocationRepository.kt | 1 | 4946 | /*
* Transportr
*
* Copyright (c) 2013 - 2018 Torsten Grote
*
* 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 de.grobox.transportr.data.locations
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import androidx.annotation.WorkerThread
import de.grobox.transportr.AbstractManager
import de.grobox.transportr.data.locations.FavoriteLocation.FavLocationType
import de.grobox.transportr.locations.WrapLocation
import de.grobox.transportr.locations.WrapLocation.WrapType.NORMAL
import de.grobox.transportr.networks.TransportNetworkManager
import de.schildbach.pte.NetworkId
import de.schildbach.pte.dto.LocationType.ADDRESS
import de.schildbach.pte.dto.LocationType.COORD
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class LocationRepository @Inject
constructor(private val locationDao: LocationDao, transportNetworkManager: TransportNetworkManager) : AbstractManager() {
private val networkId: LiveData<NetworkId> = transportNetworkManager.networkId
val homeLocation: LiveData<HomeLocation> = Transformations.switchMap(networkId, locationDao::getHomeLocation)
val workLocation: LiveData<WorkLocation> = Transformations.switchMap(networkId, locationDao::getWorkLocation)
val favoriteLocations: LiveData<List<FavoriteLocation>> = Transformations.switchMap(networkId, locationDao::getFavoriteLocations)
fun setHomeLocation(location: WrapLocation) {
runOnBackgroundThread {
// add also as favorite location if it doesn't exist already
val favoriteLocation = getFavoriteLocation(networkId.value, location)
if (favoriteLocation == null) locationDao.addFavoriteLocation(FavoriteLocation(networkId.value, location))
locationDao.addHomeLocation(HomeLocation(networkId.value!!, location))
}
}
fun setWorkLocation(location: WrapLocation) {
runOnBackgroundThread {
// add also as favorite location if it doesn't exist already
val favoriteLocation = getFavoriteLocation(networkId.value, location)
if (favoriteLocation == null) locationDao.addFavoriteLocation(FavoriteLocation(networkId.value, location))
locationDao.addWorkLocation(WorkLocation(networkId.value!!, location))
}
}
@WorkerThread
fun addFavoriteLocation(wrapLocation: WrapLocation, type: FavLocationType): FavoriteLocation? {
if (wrapLocation.type == COORD || wrapLocation.wrapType != NORMAL) return null
val favoriteLocation = if (wrapLocation is FavoriteLocation) {
wrapLocation
} else {
val location = findExistingLocation(wrapLocation)
location as? FavoriteLocation ?: FavoriteLocation(networkId.value, wrapLocation)
}
favoriteLocation.add(type)
return if (favoriteLocation.uid != 0L) {
locationDao.addFavoriteLocation(favoriteLocation)
favoriteLocation
} else {
val existingLocation = getFavoriteLocation(networkId.value, favoriteLocation)
if (existingLocation != null) {
existingLocation.add(type)
locationDao.addFavoriteLocation(existingLocation)
existingLocation
} else {
val uid = locationDao.addFavoriteLocation(favoriteLocation)
FavoriteLocation(uid, networkId.value, favoriteLocation)
}
}
}
@WorkerThread
private fun getFavoriteLocation(networkId: NetworkId?, l: WrapLocation?): FavoriteLocation? {
return if (l == null) null else locationDao.getFavoriteLocation(networkId, l.type, l.id, l.lat, l.lon, l.place, l.name)
}
/**
* This checks existing ADDRESS Locations for geographic proximity
* before adding the given location as a favorite.
* The idea is too prevent duplicates of addresses with slightly different coordinates.
*
* @return The given {@link WrapLocation} or if found, the existing one
*/
private fun findExistingLocation(location: WrapLocation): WrapLocation {
favoriteLocations.value?.filter {
it.type == ADDRESS && it.name != null && it.name == location.name && it.isSamePlace(location)
}?.forEach { return it }
return location
}
}
| gpl-3.0 | 8473705c9accfe95aefbdbce0ddeb5a2 | 42.769912 | 133 | 0.716539 | 4.806608 | false | false | false | false |
Esri/arcgis-runtime-samples-android | kotlin/trace-utility-network/src/main/java/com/esri/arcgisruntime/sample/traceutilitynetwork/MainActivity.kt | 1 | 23917 | /*
* Copyright 2019 Esri
*
* 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.esri.arcgisruntime.sample.traceutilitynetwork
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.data.ArcGISFeature
import com.esri.arcgisruntime.data.QueryParameters
import com.esri.arcgisruntime.data.ServiceGeodatabase
import com.esri.arcgisruntime.geometry.*
import com.esri.arcgisruntime.layers.FeatureLayer
import com.esri.arcgisruntime.loadable.LoadStatus
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.BasemapStyle
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.MapView
import com.esri.arcgisruntime.sample.traceutilitynetwork.databinding.ActivityMainBinding
import com.esri.arcgisruntime.security.UserCredential
import com.esri.arcgisruntime.symbology.SimpleLineSymbol
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.esri.arcgisruntime.symbology.UniqueValueRenderer
import com.esri.arcgisruntime.utilitynetworks.*
import kotlin.math.roundToInt
class MainActivity : AppCompatActivity() {
private val activityMainBinding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
private val mapView: MapView by lazy {
activityMainBinding.mapView
}
private val progressIndicator: ProgressBar by lazy {
activityMainBinding.progressIndicator
}
private val startingLocationsRadioButton: RadioButton by lazy {
activityMainBinding.controlsLayout.startingLocationsRadioButton
}
private val statusTextView: TextView by lazy {
activityMainBinding.controlsLayout.statusTextView
}
private val resetButton: Button by lazy {
activityMainBinding.controlsLayout.resetButton
}
private val traceButton: Button by lazy {
activityMainBinding.controlsLayout.traceButton
}
private val traceTypeSpinner: Spinner by lazy {
activityMainBinding.controlsLayout.traceTypeSpinner
}
private var mediumVoltageTier: UtilityTier? = null
private val graphicsOverlay: GraphicsOverlay by lazy { GraphicsOverlay() }
private val featureServiceUrl =
"https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer"
private val serviceGeodatabase by lazy {
ServiceGeodatabase(featureServiceUrl).apply {
// define user credentials for authenticating with the service
// NOTE: a licensed user is required to perform utility network operations
credential = UserCredential("viewer01", "I68VGU^nMurF")
}
}
private val utilityNetwork: UtilityNetwork by lazy {
UtilityNetwork(featureServiceUrl).apply {
// define user credentials for authenticating with the service
// NOTE: a licensed user is required to perform utility network operations
credential = UserCredential("viewer01", "I68VGU^nMurF")
}
}
// create lists for starting locations and barriers
private val utilityElementStartingLocations: MutableList<UtilityElement> by lazy { ArrayList() }
private val utilityElementBarriers: MutableList<UtilityElement> by lazy { ArrayList() }
// create symbols for the starting point and barriers
private val startingPointSymbol: SimpleMarkerSymbol by lazy {
SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CROSS, Color.GREEN, 25f)
}
private val barrierPointSymbol: SimpleMarkerSymbol by lazy {
SimpleMarkerSymbol(SimpleMarkerSymbol.Style.X, Color.RED, 25f)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(activityMainBinding.root)
// authentication with an API key or named user is required to access basemaps and other
// location services
ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY)
serviceGeodatabase.loadAsync()
serviceGeodatabase.addDoneLoadingListener {
serviceGeodatabase.loadStatus
// create electrical distribution line layer from the service geodatabase
val electricalDistributionFeatureLayer =
FeatureLayer(serviceGeodatabase.getTable(3)).apply {
// define a solid line for medium voltage lines
val mediumVoltageValue = UniqueValueRenderer.UniqueValue(
"N/A",
"Medium voltage",
SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.CYAN, 3f),
listOf(5)
)
// define a dashed line for low voltage lines
val lowVoltageValue = UniqueValueRenderer.UniqueValue(
"N/A",
"Low voltage",
SimpleLineSymbol(SimpleLineSymbol.Style.DASH, Color.CYAN, 3f),
listOf(3)
)
// create and apply a solid light gray renderer
renderer =
UniqueValueRenderer(
listOf("ASSETGROUP"),
listOf(mediumVoltageValue, lowVoltageValue),
"",
SimpleLineSymbol()
)
}
// create electrical device layerfrom the service geodatabase
val electricalDeviceFeatureLayer =
FeatureLayer(serviceGeodatabase.getTable(0))
// setup the map view
mapView.apply {
// add a map with streets night vector basemap
map = ArcGISMap(BasemapStyle.ARCGIS_STREETS_NIGHT).apply {
operationalLayers.apply {
add(electricalDistributionFeatureLayer)
add(electricalDeviceFeatureLayer)
}
// add the utility network to the map
utilityNetworks.add(utilityNetwork)
}
// set the viewpoint to a section in the southeast of the network
setViewpointAsync(
Viewpoint(
Envelope(
-9813547.35557238,
5129980.36635111,
-9813185.0602376,
5130215.41254146,
SpatialReferences.getWebMercator()
)
)
)
// set the selection color for features in the map view
selectionProperties.color = Color.YELLOW
// add a graphics overlay
graphicsOverlays.add(graphicsOverlay)
// handle taps on the map view
onTouchListener =
object : DefaultMapViewOnTouchListener(applicationContext, mapView) {
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
// only pass taps to identify nearest utility element once the utility network has loaded
if (utilityNetwork.loadStatus == LoadStatus.LOADED) {
identifyNearestUtilityElement(
android.graphics.Point(e.x.roundToInt(), e.y.roundToInt())
)
return true
}
return false
}
}
}
// load the utility network
utilityNetwork.addDoneLoadingListener {
if (utilityNetwork.loadStatus == LoadStatus.LOADED) {
// update the status text
statusTextView.text = getString(R.string.click_to_add_points)
// get the utility tier used for traces in this network, in this case "Medium Voltage Radial"
val domainNetwork =
utilityNetwork.definition.getDomainNetwork("ElectricDistribution")
mediumVoltageTier = domainNetwork.getTier("Medium Voltage Radial")
} else {
reportError("Error loading utility network: " + utilityNetwork.loadError.cause?.message)
}
}
utilityNetwork.loadAsync()
}
// add all utility trace types to the trace type spinner as strings
traceTypeSpinner.adapter = ArrayAdapter(
applicationContext,
android.R.layout.simple_spinner_item,
arrayOf("CONNECTED", "SUBNETWORK", "UPSTREAM", "DOWNSTREAM")
)
}
/**
* Uses the tapped point to identify any utility elements in the utility network at the tapped
* location. Based on the selection mode, the tapped utility element is added either to the
* starting locations or barriers for the trace parameters. An appropriate graphic is created at
* the tapped location to mark the element as either a starting location or barrier.
*
* @param screenPoint used to identify utility elements in the utility network
*/
private fun identifyNearestUtilityElement(screenPoint: android.graphics.Point) {
// get the clicked map point
val mapPoint = mapView.screenToLocation(screenPoint)
// identify the feature to be used
val identifyLayerResultFuture = mapView.identifyLayersAsync(screenPoint, 10.0, false)
identifyLayerResultFuture.addDoneListener {
// get the result of the query
try {
val identifyResults = identifyLayerResultFuture.get()
// if the identify returns a result, retrieve the geoelement as an ArcGISFeature
(identifyResults.getOrNull(0)?.elements?.get(0) as? ArcGISFeature)?.let { identifiedFeature ->
// get the network source of the identified feature
val utilityNetworkSource =
utilityNetwork.definition.getNetworkSource(identifiedFeature.featureTable.tableName)
// check if the network source is a junction or an edge
when (utilityNetworkSource.sourceType) {
UtilityNetworkSource.Type.JUNCTION -> {
// create a utility element with the identified feature
createUtilityElement(identifiedFeature, utilityNetworkSource)
}
UtilityNetworkSource.Type.EDGE -> {
// create a utility element with the identified feature
utilityNetwork.createElement(identifiedFeature, null).apply {
// calculate how far the clicked location is along the edge feature
fractionAlongEdge = GeometryEngine.fractionAlong(
GeometryEngine.removeZ(identifiedFeature.geometry) as Polyline,
mapPoint,
-1.0
)
// set the trace location graphic to the nearest coordinate to the tapped point
addUtilityElementToMap(identifiedFeature, mapPoint, this)
}.also {
// update the status label text
statusTextView.text =
getString(R.string.fraction_message, it.fractionAlongEdge)
}
}
else -> error("Unexpected utility network source type!")
}
}
} catch (e: Exception) {
reportError("Error getting identify results: " + e.message)
}
}
}
/**
* Add utility element to either the starting locations or barriers list and add a graphic
* representing it to the graphics overlay.
*
* @param identifiedFeature the feature identified by a tap
* @param mapPoint the map location of the tap
* @param utilityElement to be added to the map
*/
private fun addUtilityElementToMap(
identifiedFeature: ArcGISFeature,
mapPoint: Point,
utilityElement: UtilityElement
) {
graphicsOverlay.graphics.add(
Graphic(
GeometryEngine.nearestCoordinate(
identifiedFeature.geometry,
mapPoint
).coordinate
).apply {
// add the element to the appropriate list (starting locations or barriers), and add the
// appropriate symbol to the graphic
symbol = if (startingLocationsRadioButton.isChecked) {
utilityElementStartingLocations.add(utilityElement)
startingPointSymbol
} else {
utilityElementBarriers.add(utilityElement)
barrierPointSymbol
}
})
}
/**
* Uses a UtilityNetworkSource to create a UtilityElement object out of an ArcGISFeature.
*
* @param identifiedFeature an ArcGISFeature object that will be used to create a UtilityElement
* @param networkSource the UtilityNetworkSource to which the created UtilityElement is associated
*/
private fun createUtilityElement(
identifiedFeature: ArcGISFeature,
networkSource: UtilityNetworkSource
) {
// find the code matching the asset group name in the feature's attributes
val assetGroupCode =
identifiedFeature.attributes[identifiedFeature.featureTable.subtypeField] as Int
// find the network source's asset group with the matching code
networkSource.assetGroups.filter { it.code == assetGroupCode }[0].assetTypes
// find the asset group type code matching the feature's asset type code
.filter { it.code == identifiedFeature.attributes["assettype"].toString().toInt() }[0]
.let { utilityAssetType ->
// get the list of terminals for the feature
val terminals = utilityAssetType.terminalConfiguration.terminals
// if there is only one terminal, use it to create a utility element
when (terminals.size) {
1 -> {
// create a utility element
utilityNetwork.createElement(identifiedFeature, terminals[0]).also {
// add the utility element to the map
addUtilityElementToMap(
identifiedFeature,
identifiedFeature.geometry as Point,
it
)
}
}
// if there is more than one terminal, prompt the user to select one
else -> {
// get a list of terminal names from the terminals
val terminalNames =
utilityAssetType.terminalConfiguration.terminals.map { it.name }
AlertDialog.Builder(this).apply {
setTitle("Select utility terminal:")
setItems(terminalNames.toTypedArray()) { _, which ->
// create a utility element
utilityNetwork.createElement(identifiedFeature, terminals[which])
.also {
// add the utility element to the map
addUtilityElementToMap(
identifiedFeature,
identifiedFeature.geometry as Point,
it
)
// show the utility element name in the UI
showTerminalNameInStatusLabel(it.terminal)
}
}
}.show()
}
}
}
}
/**
* Shows the name of a UtilityTerminal in the status label in the UI.
*
* @param terminal to show information about
*/
private fun showTerminalNameInStatusLabel(terminal: UtilityTerminal) {
statusTextView.text =
getString(
R.string.terminal_name,
if (!terminal.name.isNullOrEmpty()) terminal.name else "default"
)
}
/**
* Uses the elements selected as starting locations and (optionally) barriers to perform a connected trace,
* then selects all connected elements found in the trace to highlight them.
*/
fun traceUtilityNetwork(view: View) {
// check that the utility trace parameters are valid
if (utilityElementStartingLocations.isEmpty()) {
reportError("No starting locations provided for trace.")
return
}
// show the progress indicator and update the status text
progressIndicator.visibility = View.VISIBLE
statusTextView.text = getString(R.string.find_connected_features_message)
disableButtons()
// create utility trace parameters for the given trace type
val traceType = UtilityTraceType.valueOf(traceTypeSpinner.selectedItem.toString())
// create trace parameters
val traceParameters =
UtilityTraceParameters(traceType, utilityElementStartingLocations).apply {
// if any barriers have been created, add them to the parameters
barriers.addAll(utilityElementBarriers)
// set the trace configuration using the tier from the utility domain network
traceConfiguration = mediumVoltageTier?.traceConfiguration
}
// run the utility trace and get the results
val utilityTraceResultsFuture = utilityNetwork.traceAsync(traceParameters)
utilityTraceResultsFuture.addDoneListener {
try {
// get the utility trace result's first result as a utility element trace result
(utilityTraceResultsFuture.get()[0] as? UtilityElementTraceResult)?.let { utilityElementTraceResult ->
// ensure the result is not empty
if (utilityElementTraceResult.elements.isNotEmpty()) {
// iterate through the map's feature layers
mapView.map.operationalLayers.filterIsInstance<FeatureLayer>()
.forEach { featureLayer ->
// clear previous selection
featureLayer.clearSelection()
// create query parameters to find features who's network source name matches the layer's feature table name
with(QueryParameters()) {
utilityElementTraceResult.elements.filter { it.networkSource.name == featureLayer.featureTable.tableName }
.forEach { utilityElement ->
this.objectIds.add(utilityElement.objectId)
}
// select features that match the query
featureLayer.selectFeaturesAsync(
this,
FeatureLayer.SelectionMode.NEW
)
.addDoneListener {
// when done, update status text, enable buttons and hide progress indicator
statusTextView.text =
getString(R.string.trace_completed)
enableButtons()
progressIndicator.visibility = View.GONE
}
}
}
} else {
Toast.makeText(this, "No elements in trace result", Toast.LENGTH_LONG)
.show()
progressIndicator.visibility = View.GONE
enableButtons()
}
}
} catch (e: Exception) {
statusTextView.text = getString(R.string.failed_message)
progressIndicator.visibility = View.GONE
enableButtons()
reportError("Error running connected trace: " + e.message)
}
}
}
/**
* Enables both buttons.
*/
private fun enableButtons() {
// enable the UI
resetButton.isEnabled = true
traceButton.isEnabled = true
}
/**
* Disables both buttons.
*/
private fun disableButtons() {
// enable the UI
resetButton.isEnabled = false
traceButton.isEnabled = false
}
/**
* Restores the sample to the startup-state by resetting the status text, hiding the progress indicator, clearing
* the trace parameters, de-selecting all features and removing any graphics
*/
fun reset(view: View) {
statusTextView.text = getString(R.string.add_utility_element)
progressIndicator.visibility = View.GONE
// clear the utility trace parameters
utilityElementStartingLocations.clear()
utilityElementBarriers.clear()
// clear any selected features in the map's feature layers
mapView.map.operationalLayers.filterIsInstance<FeatureLayer>().forEach {
it.clearSelection()
}
// clear the graphics overlay
graphicsOverlay.graphics.clear()
// enable the trace button
traceButton.isEnabled = true
}
/**
* Report the given error to the user by toast and log.
*
* @param error as a string
*/
private fun reportError(error: String) {
Toast.makeText(this, error, Toast.LENGTH_LONG).show()
Log.e(this::class.java.simpleName, error)
}
override fun onPause() {
mapView.pause()
super.onPause()
}
override fun onResume() {
super.onResume()
mapView.resume()
}
override fun onDestroy() {
mapView.dispose()
super.onDestroy()
}
}
| apache-2.0 | 81b3f97e53ac434e68912945da9a808b | 43.621269 | 142 | 0.576494 | 5.91127 | false | false | false | false |
libktx/ktx | assets-async/src/test/kotlin/ktx/assets/async/assetStorageLoadingTest.kt | 1 | 40601 | package ktx.assets.async
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetDescriptor
import com.badlogic.gdx.assets.AssetLoaderParameters
import com.badlogic.gdx.assets.loaders.resolvers.ClasspathFileHandleResolver
import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3NativesLoader
import com.badlogic.gdx.backends.lwjgl3.audio.OpenALLwjgl3Audio
import com.badlogic.gdx.graphics.Cubemap
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.ParticleEffect
import com.badlogic.gdx.graphics.g2d.PolygonRegion
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g3d.Model
import com.badlogic.gdx.graphics.glutils.ShaderProgram
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.utils.I18NBundle
import com.badlogic.gdx.utils.Logger
import com.nhaarman.mockitokotlin2.mock
import io.kotlintest.matchers.shouldThrow
import kotlinx.coroutines.runBlocking
import ktx.assets.TextAssetLoader
import ktx.async.AsyncTest
import org.junit.After
import org.junit.AfterClass
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNotSame
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TestName
import java.util.IdentityHashMap
import com.badlogic.gdx.graphics.g3d.particles.ParticleEffect as ParticleEffect3D
/**
* [AssetStorage] has 3 main variants of asset loading: [AssetStorage.load], [AssetStorage.loadAsync]
* and [AssetStorage.loadSync]. To test each one, a common abstract test suite is provided.
*
* This test suite ensures that each method supports loading of every default asset type
* and performs basic asset loading logic tests.
*
* Note that variants consuming [String] path and reified asset types could not be easily tested,
* as they cannot be invoked in abstract methods. However, since all of them are just aliases and
* contain no logic other than [AssetDescriptor] or [Identifier] initiation, the associated loading
* methods are still tested.
*
* See also: [AssetStorageTest].
*/
abstract class AbstractAssetStorageLoadingTest : AsyncTest() {
@get:Rule
var testName = TestName()
/**
* Must be overridden with the tested loading method variant.
* Blocks the current thread until the selected asset is loaded.
*/
protected abstract fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T
private inline fun <reified T> AssetStorage.testLoad(
path: String,
parameters: AssetLoaderParameters<T>? = null
): T = testLoad(path, T::class.java, parameters)
// --- Asset support tests:
@Test
fun `should load text assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
// When:
val asset = storage.testLoad<String>(path)
// Then:
assertEquals("Content.", asset)
assertTrue(storage.isLoaded<String>(path))
assertSame(asset, storage.get<String>(path))
assertEquals(1, storage.getReferenceCount<String>(path))
assertEquals(emptyList<String>(), storage.getDependencies<String>(path))
}
@Test
fun `should load text assets with parameters`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
// When:
val asset = storage.testLoad(path, parameters = TextAssetLoader.TextAssetLoaderParameters("UTF-8"))
// Then:
assertEquals("Content.", asset)
assertTrue(storage.isLoaded<String>(path))
assertSame(asset, storage.get<String>(path))
assertEquals(1, storage.getReferenceCount<String>(path))
assertEquals(emptyList<String>(), storage.getDependencies<String>(path))
}
@Test
fun `should unload text assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
storage.testLoad<String>(path)
// When:
runBlocking { storage.unload<String>(path) }
// Then:
assertFalse(storage.isLoaded<String>(path))
assertEquals(0, storage.getReferenceCount<String>(path))
}
@Test
fun `should load BitmapFont assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "com/badlogic/gdx/utils/lsans-15.fnt"
val dependency = "com/badlogic/gdx/utils/lsans-15.png"
// When:
val asset = storage.testLoad<BitmapFont>(path)
// Then:
assertTrue(storage.isLoaded<BitmapFont>(path))
assertSame(asset, storage.get<BitmapFont>(path))
assertEquals(1, storage.getReferenceCount<BitmapFont>(path))
assertEquals(listOf(storage.getIdentifier<Texture>(dependency)), storage.getDependencies<BitmapFont>(path))
// Font dependencies:
assertTrue(storage.isLoaded<Texture>(dependency))
assertEquals(1, storage.getReferenceCount<Texture>(dependency))
assertSame(asset.region.texture, storage.get<Texture>(dependency))
storage.dispose()
}
@Test
fun `should unload BitmapFont with dependencies`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "com/badlogic/gdx/utils/lsans-15.fnt"
val dependency = "com/badlogic/gdx/utils/lsans-15.png"
storage.testLoad<BitmapFont>(path)
// When:
runBlocking { storage.unload<BitmapFont>(path) }
// Then:
assertFalse(storage.isLoaded<BitmapFont>(path))
assertEquals(0, storage.getReferenceCount<BitmapFont>(path))
assertFalse(storage.isLoaded<Texture>(dependency))
assertEquals(0, storage.getReferenceCount<Texture>(path))
}
@Test
fun `should load Music assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/sound.ogg"
// When:
val asset = storage.testLoad<Music>(path)
// Then:
assertTrue(storage.isLoaded<Music>(path))
assertSame(asset, storage.get<Music>(path))
assertEquals(1, storage.getReferenceCount<Music>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Music>(path))
storage.dispose()
}
@Test
fun `should unload Music assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/sound.ogg"
storage.testLoad<Music>(path)
// When:
runBlocking { storage.unload<Music>(path) }
// Then:
assertFalse(storage.isLoaded<Music>(path))
assertEquals(0, storage.getReferenceCount<Music>(path))
}
@Test
fun `should load Sound assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/sound.ogg"
// When:
val asset = storage.testLoad<Sound>(path)
// Then:
assertTrue(storage.isLoaded<Sound>(path))
assertSame(asset, storage.get<Sound>(path))
assertEquals(1, storage.getReferenceCount<Sound>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Sound>(path))
storage.dispose()
}
@Test
fun `should unload Sound assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/sound.ogg"
storage.testLoad<Sound>(path)
// When:
runBlocking { storage.unload<Sound>(path) }
// Then:
assertFalse(storage.isLoaded<Sound>(path))
assertEquals(0, storage.getReferenceCount<Sound>(path))
}
@Test
fun `should load TextureAtlas assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.atlas"
val dependency = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<TextureAtlas>(path)
// Then:
assertTrue(storage.isLoaded<TextureAtlas>(path))
assertSame(asset, storage.get<TextureAtlas>(path))
assertEquals(1, storage.getReferenceCount<TextureAtlas>(path))
assertEquals(listOf(storage.getIdentifier<Texture>(dependency)), storage.getDependencies<TextureAtlas>(path))
// Atlas dependencies:
assertTrue(storage.isLoaded<Texture>(dependency))
assertSame(asset.textures.first(), storage.get<Texture>(dependency))
assertEquals(1, storage.getReferenceCount<Texture>(dependency))
storage.dispose()
}
@Test
fun `should unload TextureAtlas assets with dependencies`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.atlas"
val dependency = "ktx/assets/async/texture.png"
storage.testLoad<TextureAtlas>(path)
// When:
runBlocking { storage.unload<TextureAtlas>(path) }
// Then:
assertFalse(storage.isLoaded<TextureAtlas>(path))
assertEquals(0, storage.getReferenceCount<TextureAtlas>(path))
assertFalse(storage.isLoaded<Texture>(dependency))
assertEquals(0, storage.getReferenceCount<Texture>(dependency))
}
@Test
fun `should load Texture assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<Texture>(path)
// Then:
assertTrue(storage.isLoaded<Texture>(path))
assertSame(asset, storage.get<Texture>(path))
assertEquals(1, storage.getReferenceCount<Texture>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Texture>(path))
storage.dispose()
}
@Test
fun `should unload Texture assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
storage.testLoad<Texture>(path)
// When:
runBlocking { storage.unload<Texture>(path) }
// Then:
assertFalse(storage.isLoaded<Texture>(path))
assertEquals(0, storage.getReferenceCount<Texture>(path))
}
@Test
fun `should load Pixmap assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<Pixmap>(path)
// Then:
assertTrue(storage.isLoaded<Pixmap>(path))
assertSame(asset, storage.get<Pixmap>(path))
assertEquals(1, storage.getReferenceCount<Pixmap>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Pixmap>(path))
storage.dispose()
}
@Test
fun `should unload Pixmap assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
storage.testLoad<Pixmap>(path)
// When:
runBlocking { storage.unload<Pixmap>(path) }
// Then:
assertFalse(storage.isLoaded<Pixmap>(path))
assertEquals(0, storage.getReferenceCount<Pixmap>(path))
}
@Test
fun `should load Skin assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.json"
val atlas = "ktx/assets/async/skin.atlas"
val texture = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<Skin>(path)
// Then:
assertTrue(storage.isLoaded<Skin>(path))
assertSame(asset, storage.get<Skin>(path))
assertNotNull(asset.get("default", Button.ButtonStyle::class.java))
assertEquals(1, storage.getReferenceCount<Skin>(path))
assertEquals(listOf(storage.getIdentifier<TextureAtlas>(atlas)), storage.getDependencies<Skin>(path))
// Skin dependencies:
assertTrue(storage.isLoaded<TextureAtlas>(atlas))
assertEquals(1, storage.getReferenceCount<TextureAtlas>(atlas))
assertSame(asset.atlas, storage.get<TextureAtlas>(atlas))
assertEquals(listOf(storage.getIdentifier<Texture>(texture)), storage.getDependencies<TextureAtlas>(atlas))
// Atlas dependencies:
assertTrue(storage.isLoaded<Texture>(texture))
assertSame(asset.atlas.textures.first(), storage.get<Texture>(texture))
assertEquals(1, storage.getReferenceCount<Texture>(texture))
storage.dispose()
}
@Test
fun `should unload Skin assets with dependencies`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.json"
val atlas = "ktx/assets/async/skin.atlas"
val texture = "ktx/assets/async/texture.png"
storage.testLoad<Skin>(path)
// When:
runBlocking { storage.unload<Skin>(path) }
// Then:
assertFalse(storage.isLoaded<Skin>(path))
assertEquals(0, storage.getReferenceCount<Skin>(path))
assertFalse(storage.isLoaded<TextureAtlas>(atlas))
assertEquals(0, storage.getReferenceCount<TextureAtlas>(atlas))
assertFalse(storage.isLoaded<Texture>(texture))
assertEquals(0, storage.getReferenceCount<Texture>(texture))
}
@Test
fun `should load I18NBundle assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/i18n"
// When:
val asset = storage.testLoad<I18NBundle>(path)
// Then:
assertTrue(storage.isLoaded<I18NBundle>(path))
assertEquals("Value.", asset["key"])
assertSame(asset, storage.get<I18NBundle>(path))
assertEquals(1, storage.getReferenceCount<I18NBundle>(path))
assertEquals(emptyList<String>(), storage.getDependencies<I18NBundle>(path))
storage.dispose()
}
@Test
fun `should unload I18NBundle assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/i18n"
storage.testLoad<I18NBundle>(path)
// When:
runBlocking { storage.unload<I18NBundle>(path) }
// Then:
assertFalse(storage.isLoaded<I18NBundle>(path))
assertEquals(0, storage.getReferenceCount<I18NBundle>(path))
}
@Test
fun `should load ParticleEffect assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/particle.p2d"
// When:
val asset = storage.testLoad<ParticleEffect>(path)
// Then:
assertTrue(storage.isLoaded<ParticleEffect>(path))
assertSame(asset, storage.get<ParticleEffect>(path))
assertEquals(1, storage.getReferenceCount<ParticleEffect>(path))
assertEquals(emptyList<String>(), storage.getDependencies<ParticleEffect>(path))
storage.dispose()
}
@Test
fun `should unload ParticleEffect assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/particle.p2d"
storage.testLoad<ParticleEffect>(path)
// When:
runBlocking { storage.unload<ParticleEffect>(path) }
// Then:
assertFalse(storage.isLoaded<ParticleEffect>(path))
assertEquals(0, storage.getReferenceCount<ParticleEffect>(path))
}
@Test
fun `should load ParticleEffect3D assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/particle.p3d"
val dependency = "ktx/assets/async/texture.png"
// When:
val asset = storage.testLoad<ParticleEffect3D>(path)
// Then:
assertTrue(storage.isLoaded<ParticleEffect3D>(path))
assertSame(asset, storage.get<ParticleEffect3D>(path))
assertEquals(1, storage.getReferenceCount<ParticleEffect3D>(path))
assertEquals(listOf(storage.getIdentifier<Texture>(dependency)), storage.getDependencies<ParticleEffect3D>(path))
// Particle dependencies:
assertTrue(storage.isLoaded<Texture>(dependency))
assertNotNull(storage.get<Texture>(dependency))
assertEquals(1, storage.getReferenceCount<Texture>(dependency))
storage.dispose()
}
@Test
fun `should unload ParticleEffect3D assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/particle.p3d"
val dependency = "ktx/assets/async/texture.png"
storage.testLoad<ParticleEffect3D>(path)
// When:
runBlocking { storage.unload<ParticleEffect3D>(path) }
// Then:
assertFalse(storage.isLoaded<ParticleEffect3D>(path))
assertEquals(0, storage.getReferenceCount<ParticleEffect3D>(path))
assertFalse(storage.isLoaded<Texture>(dependency))
assertEquals(0, storage.getReferenceCount<Texture>(dependency))
}
@Test
fun `should load PolygonRegion assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/polygon.psh"
val dependency = "ktx/assets/async/polygon.png"
// When:
val asset = storage.testLoad<PolygonRegion>(path)
// Then:
assertTrue(storage.isLoaded<PolygonRegion>(path))
assertSame(asset, storage.get<PolygonRegion>(path))
assertEquals(1, storage.getReferenceCount<PolygonRegion>(path))
assertEquals(listOf(storage.getIdentifier<Texture>(dependency)), storage.getDependencies<PolygonRegion>(path))
// Polygon region dependencies:
assertTrue(storage.isLoaded<Texture>(dependency))
assertSame(asset.region.texture, storage.get<Texture>(dependency))
assertEquals(1, storage.getReferenceCount<Texture>(dependency))
storage.dispose()
}
@Test
fun `should unload PolygonRegion assets with dependencies`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/polygon.psh"
val dependency = "ktx/assets/async/polygon.png"
storage.testLoad<PolygonRegion>(path)
// When:
runBlocking { storage.unload<PolygonRegion>(path) }
// Then:
assertFalse(storage.isLoaded<PolygonRegion>(path))
assertEquals(0, storage.getReferenceCount<PolygonRegion>(path))
assertFalse(storage.isLoaded<Texture>(dependency))
assertEquals(0, storage.getReferenceCount<Texture>(dependency))
}
@Test
fun `should load OBJ Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.obj"
// When:
val asset = storage.testLoad<Model>(path)
// Then:
assertTrue(storage.isLoaded<Model>(path))
assertSame(asset, storage.get<Model>(path))
assertEquals(1, storage.getReferenceCount<Model>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Model>(path))
storage.dispose()
}
@Test
fun `should unload OBJ Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.obj"
storage.testLoad<Model>(path)
// When:
runBlocking { storage.unload<Model>(path) }
// Then:
assertFalse(storage.isLoaded<Model>(path))
assertEquals(0, storage.getReferenceCount<Model>(path))
}
@Test
fun `should load G3DJ Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.g3dj"
// When:
val asset = storage.testLoad<Model>(path)
// Then:
assertTrue(storage.isLoaded<Model>(path))
assertSame(asset, storage.get<Model>(path))
assertEquals(1, storage.getReferenceCount<Model>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Model>(path))
storage.dispose()
}
@Test
fun `should unload G3DJ Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.g3dj"
storage.testLoad<Model>(path)
// When:
runBlocking { storage.unload<Model>(path) }
// Then:
assertFalse(storage.isLoaded<Model>(path))
assertEquals(0, storage.getReferenceCount<Model>(path))
}
@Test
fun `should load G3DB Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.g3db"
// When:
val asset = storage.testLoad<Model>(path)
// Then:
assertTrue(storage.isLoaded<Model>(path))
assertSame(asset, storage.get<Model>(path))
assertEquals(1, storage.getReferenceCount<Model>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Model>(path))
storage.dispose()
}
@Test
fun `should unload G3DB Model assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/model.g3db"
storage.testLoad<Model>(path)
// When:
runBlocking { storage.unload<Model>(path) }
// Then:
assertFalse(storage.isLoaded<Model>(path))
assertEquals(0, storage.getReferenceCount<Model>(path))
}
@Test
fun `should load ShaderProgram assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/shader.frag"
// Silencing logs - shader will fail to compile, as GL is mocked:
storage.logger.level = Logger.NONE
// When:
val asset = storage.testLoad<ShaderProgram>(path)
// Then:
assertTrue(storage.isLoaded<ShaderProgram>(path))
assertSame(asset, storage.get<ShaderProgram>(path))
assertEquals(1, storage.getReferenceCount<ShaderProgram>(path))
assertEquals(emptyList<String>(), storage.getDependencies<ShaderProgram>(path))
storage.dispose()
}
@Test
fun `should unload ShaderProgram assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/shader.frag"
// Silencing logs - shader will fail to compile, as GL is mocked:
storage.logger.level = Logger.NONE
storage.testLoad<ShaderProgram>(path)
// When:
runBlocking { storage.unload<ShaderProgram>(path) }
// Then:
assertFalse(storage.isLoaded<ShaderProgram>(path))
assertEquals(0, storage.getReferenceCount<ShaderProgram>(path))
}
@Test
fun `should load Cubemap assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/cubemap.zktx"
// When:
val asset = storage.testLoad<Cubemap>(path)
// Then:
assertTrue(storage.isLoaded<Cubemap>(path))
assertSame(asset, storage.get<Cubemap>(path))
assertEquals(1, storage.getReferenceCount<Cubemap>(path))
assertEquals(emptyList<String>(), storage.getDependencies<Cubemap>(path))
storage.dispose()
}
@Test
fun `should unload Cubemap assets`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/cubemap.zktx"
storage.testLoad<Cubemap>(path)
// When:
runBlocking { storage.unload<Cubemap>(path) }
// Then:
assertFalse(storage.isLoaded<Cubemap>(path))
assertEquals(0, storage.getReferenceCount<Cubemap>(path))
}
@Test
fun `should dispose of multiple assets of different types without errors`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
storage.logger.level = Logger.NONE
val assets = listOf(
storage.getIdentifier<String>("ktx/assets/async/string.txt"),
storage.getIdentifier<BitmapFont>("com/badlogic/gdx/utils/lsans-15.fnt"),
storage.getIdentifier<Music>("ktx/assets/async/sound.ogg"),
storage.getIdentifier<TextureAtlas>("ktx/assets/async/skin.atlas"),
storage.getIdentifier<Texture>("ktx/assets/async/texture.png"),
storage.getIdentifier<Skin>("ktx/assets/async/skin.json"),
storage.getIdentifier<I18NBundle>("ktx/assets/async/i18n"),
storage.getIdentifier<ParticleEffect>("ktx/assets/async/particle.p2d"),
storage.getIdentifier<ParticleEffect3D>("ktx/assets/async/particle.p3d"),
storage.getIdentifier<PolygonRegion>("ktx/assets/async/polygon.psh"),
storage.getIdentifier<Model>("ktx/assets/async/model.obj"),
storage.getIdentifier<Model>("ktx/assets/async/model.g3dj"),
storage.getIdentifier<Model>("ktx/assets/async/model.g3db"),
storage.getIdentifier<ShaderProgram>("ktx/assets/async/shader.frag"),
storage.getIdentifier<Cubemap>("ktx/assets/async/cubemap.zktx")
)
assets.forEach {
storage.testLoad(it.path, it.type, parameters = null)
assertTrue(storage.isLoaded(it))
}
// When:
storage.dispose()
// Then:
assets.forEach {
assertFalse(it in storage)
assertFalse(storage.isLoaded(it))
assertEquals(0, storage.getReferenceCount(it))
assertEquals(emptyList<String>(), storage.getDependencies(it))
shouldThrow<MissingAssetException> {
storage[it]
}
}
}
// --- Behavior tests:
@Test
fun `should return same asset instance with subsequent load calls on loaded asset`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
val loaded = storage.testLoad<Texture>(path)
// When:
val assets = (1..10).map { storage.testLoad<Texture>(path) }
// Then:
assertEquals(11, storage.getReferenceCount<Texture>(path))
assets.forEach { asset ->
assertSame(loaded, asset)
}
checkProgress(storage, loaded = 1, warn = true)
storage.dispose()
}
@Test
fun `should obtain loaded asset with path`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
// When:
storage.testLoad<String>(path)
// Then:
assertTrue(storage.contains<String>(path))
assertTrue(storage.isLoaded<String>(path))
assertEquals("Content.", storage.get<String>(path))
assertEquals("Content.", storage.getOrNull<String>(path))
assertEquals("Content.", runBlocking { storage.getAsync<String>(path).await() })
assertEquals(emptyList<String>(), storage.getDependencies<String>(path))
checkProgress(storage, loaded = 1, warn = true)
}
@Test
fun `should obtain loaded asset with identifier`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val identifier = storage.getIdentifier<String>("ktx/assets/async/string.txt")
// When:
storage.testLoad<String>(identifier.path)
// Then:
assertTrue(identifier in storage)
assertTrue(storage.isLoaded(identifier))
assertEquals("Content.", storage[identifier])
assertEquals("Content.", storage.getOrNull(identifier))
assertEquals("Content.", runBlocking { storage.getAsync(identifier).await() })
assertEquals(emptyList<String>(), storage.getDependencies(identifier))
checkProgress(storage, loaded = 1, warn = true)
}
@Test
fun `should obtain loaded asset with descriptor`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val descriptor = storage.getAssetDescriptor<String>("ktx/assets/async/string.txt")
// When:
storage.testLoad<String>(descriptor.fileName)
// Then:
assertTrue(descriptor in storage)
assertTrue(storage.isLoaded(descriptor))
assertEquals("Content.", storage[descriptor])
assertEquals("Content.", storage.getOrNull(descriptor))
assertEquals("Content.", runBlocking { storage.getAsync(descriptor).await() })
assertEquals(emptyList<String>(), storage.getDependencies(descriptor))
checkProgress(storage, loaded = 1, warn = true)
}
@Test
fun `should unload assets with path`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
storage.testLoad<String>(path)
// When:
runBlocking { storage.unload<String>(path) }
// Then:
assertFalse(storage.isLoaded<String>(path))
assertEquals(0, storage.getReferenceCount<String>(path))
checkProgress(storage, total = 0, warn = true)
}
@Test
fun `should unload assets with descriptor`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
val descriptor = storage.getAssetDescriptor<String>(path)
storage.testLoad<String>(path)
// When:
runBlocking { storage.unload(descriptor) }
// Then:
assertFalse(storage.isLoaded(descriptor))
assertEquals(0, storage.getReferenceCount(descriptor))
checkProgress(storage, total = 0, warn = true)
}
@Test
fun `should unload assets with identifier`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
val identifier = storage.getIdentifier<String>(path)
storage.testLoad<String>(path)
// When:
runBlocking { storage.unload(identifier) }
// Then:
assertFalse(storage.isLoaded(identifier))
assertEquals(0, storage.getReferenceCount(identifier))
checkProgress(storage, total = 0, warn = true)
}
@Test
fun `should allow to load multiple assets with different type and same path`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/texture.png"
// When:
storage.testLoad<Texture>(path)
storage.testLoad<Pixmap>(path)
// Then:
assertTrue(storage.isLoaded<Texture>(path))
assertTrue(storage.isLoaded<Pixmap>(path))
assertEquals(1, storage.getReferenceCount<Texture>(path))
assertEquals(1, storage.getReferenceCount<Pixmap>(path))
assertNotSame(storage.get<Texture>(path), storage.get<Pixmap>(path))
checkProgress(storage, loaded = 2, warn = true)
storage.dispose()
}
@Test
fun `should increase references count and return the same asset when trying to load asset with same path`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
val elements = IdentityHashMap<String, Boolean>()
// When:
repeat(3) {
val asset = storage.testLoad<String>(path)
elements[asset] = true
}
// Then:
assertEquals(3, storage.getReferenceCount<String>(path))
assertEquals(1, elements.size)
}
@Test
fun `should fail to load asset with missing loader`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/string.txt"
// When:
shouldThrow<MissingLoaderException> {
storage.testLoad<Vector2>(path)
}
// Then:
assertFalse(storage.contains<Vector2>(path))
checkProgress(storage, total = 0)
}
@Test
fun `should increase references counts of dependencies when loading same asset`() {
// Given:
val storage = AssetStorage(fileResolver = ClasspathFileHandleResolver())
val path = "ktx/assets/async/skin.json"
val dependencies = arrayOf(
storage.getIdentifier<TextureAtlas>("ktx/assets/async/skin.atlas"),
storage.getIdentifier<Texture>("ktx/assets/async/texture.png")
)
val loadedAssets = IdentityHashMap<Skin, Boolean>()
// When:
repeat(3) {
val asset = storage.testLoad<Skin>(path)
loadedAssets[asset] = true
}
// Then:
assertEquals(3, storage.getReferenceCount<Skin>(path))
dependencies.forEach {
assertEquals(3, storage.getReferenceCount(it))
}
assertEquals(1, loadedAssets.size)
checkProgress(storage, loaded = 3, warn = true)
}
@Test
fun `should handle loading exceptions`() {
// Given:
val loader = AssetStorageTest.FakeSyncLoader(
onLoad = { throw IllegalStateException("Expected.") }
)
val storage = AssetStorage(useDefaultLoaders = false)
storage.setLoader { loader }
val path = "fake path"
// When:
shouldThrow<AssetLoadingException> {
storage.testLoad<AssetStorageTest.FakeAsset>(path)
}
// Then: asset should still be in storage, but rethrowing original exception:
assertTrue(storage.contains<AssetStorageTest.FakeAsset>(path))
assertEquals(1, storage.getReferenceCount<AssetStorageTest.FakeAsset>(path))
shouldThrow<AssetLoadingException> {
storage.get<AssetStorageTest.FakeAsset>(path)
}
shouldThrow<AssetLoadingException> {
storage.getOrNull<AssetStorageTest.FakeAsset>(path)
}
val reference = storage.getAsync<AssetStorageTest.FakeAsset>(path)
shouldThrow<AssetLoadingException> {
runBlocking { reference.await() }
}
checkProgress(storage, failed = 1, warn = true)
}
@Test
fun `should handle asynchronous loading exceptions`() {
// Given:
val loader = AssetStorageTest.FakeAsyncLoader(
onAsync = { throw IllegalStateException("Expected.") },
onSync = {}
)
val storage = AssetStorage(useDefaultLoaders = false)
storage.setLoader { loader }
val path = "fake path"
// When:
shouldThrow<AssetLoadingException> {
storage.testLoad<AssetStorageTest.FakeAsset>(path)
}
// Then: asset should still be in storage, but rethrowing original exception:
assertTrue(storage.contains<AssetStorageTest.FakeAsset>(path))
assertEquals(1, storage.getReferenceCount<AssetStorageTest.FakeAsset>(path))
shouldThrow<AssetLoadingException> {
storage.get<AssetStorageTest.FakeAsset>(path)
}
shouldThrow<AssetLoadingException> {
storage.getOrNull<AssetStorageTest.FakeAsset>(path)
}
val reference = storage.getAsync<AssetStorageTest.FakeAsset>(path)
shouldThrow<AssetLoadingException> {
runBlocking { reference.await() }
}
checkProgress(storage, failed = 1, warn = true)
}
@Test
fun `should handle synchronous loading exceptions`() {
// Given:
val loader = AssetStorageTest.FakeAsyncLoader(
onAsync = { },
onSync = { throw IllegalStateException("Expected.") }
)
val storage = AssetStorage(useDefaultLoaders = false)
storage.setLoader { loader }
val path = "fake path"
// When:
shouldThrow<AssetLoadingException> {
storage.testLoad<AssetStorageTest.FakeAsset>(path)
}
// Then: asset should still be in storage, but rethrowing original exception:
assertTrue(storage.contains<AssetStorageTest.FakeAsset>(path))
assertEquals(1, storage.getReferenceCount<AssetStorageTest.FakeAsset>(path))
shouldThrow<AssetLoadingException> {
storage.get<AssetStorageTest.FakeAsset>(path)
}
shouldThrow<AssetLoadingException> {
storage.getOrNull<AssetStorageTest.FakeAsset>(path)
}
val reference = storage.getAsync<AssetStorageTest.FakeAsset>(path)
shouldThrow<AssetLoadingException> {
runBlocking { reference.await() }
}
checkProgress(storage, failed = 1, warn = true)
}
@Test
fun `should not fail to unload asset that was loaded exceptionally`() {
// Given:
val loader = AssetStorageTest.FakeSyncLoader(
onLoad = { throw IllegalStateException("Expected.") }
)
val storage = AssetStorage(useDefaultLoaders = false)
val path = "fake path"
storage.setLoader { loader }
storage.logger.level = Logger.NONE // Disposing exception will be logged.
try {
storage.testLoad<AssetStorageTest.FakeAsset>(path)
} catch (exception: AssetLoadingException) {
// Expected.
}
// When:
val unloaded = runBlocking {
storage.unload<AssetStorageTest.FakeAsset>(path)
}
// Then:
assertTrue(unloaded)
assertFalse(storage.contains<AssetStorageTest.FakeAsset>(path))
assertEquals(0, storage.getReferenceCount<AssetStorageTest.FakeAsset>(path))
}
/**
* Allows to validate state of [LoadingProgress] without failing the test case.
* Pass [warn] not to fail the test on progress mismatch.
*
* Progress is eventually consistent. It does not have to be up to date with the [AssetStorage] state.
* Usually it will be and all tests would pass just fine, but there are these rare situations where
* the asserts are evaluated before the progress is updated. That's why if such case is possible,
* only a warning will be printed instead of failing the test.
*
* If the warnings are common, it might point to a bug within the progress updating.
*/
private fun checkProgress(
storage: AssetStorage,
loaded: Int = 0,
failed: Int = 0,
total: Int = loaded + failed,
warn: Boolean = false
) {
if (warn) {
val progress = storage.progress
if (total != progress.total || loaded != progress.loaded || failed != progress.failed) {
System.err.println(
"""
Warning: mismatch in progress value in `${testName.methodName}`.
Value | Expected | Actual
total | ${"%8d".format(total)} | ${progress.total}
loaded | ${"%8d".format(loaded)} | ${progress.loaded}
failed | ${"%8d".format(failed)} | ${progress.failed}
If this warning is repeated consistently, there might be a related bug in progress reporting.
""".trimIndent()
)
}
} else {
assertEquals(total, storage.progress.total)
assertEquals(loaded, storage.progress.loaded)
assertEquals(failed, storage.progress.failed)
}
}
companion object {
@JvmStatic
@BeforeClass
fun `load libGDX statics`() {
// Necessary for libGDX asset loaders to work.
Lwjgl3NativesLoader.load()
Gdx.graphics = mock()
Gdx.gl20 = mock()
Gdx.gl = Gdx.gl20
}
@JvmStatic
@AfterClass
fun `dispose of libGDX statics`() {
Gdx.graphics = null
Gdx.audio = null
Gdx.gl20 = null
Gdx.gl = null
}
}
@Before
override fun `setup libGDX application`() {
super.`setup libGDX application`()
if (System.getenv("TEST_PROFILE") != "ci") {
Gdx.audio = OpenALLwjgl3Audio()
}
}
@After
override fun `exit libGDX application`() {
super.`exit libGDX application`()
(Gdx.audio as? OpenALLwjgl3Audio)?.dispose()
}
}
/**
* Performs asset loading tests with [AssetStorage.loadAsync] consuming [AssetDescriptor].
*/
class AssetStorageLoadingTestWithAssetDescriptorLoadAsync : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = runBlocking {
loadAsync(AssetDescriptor(path, type, parameters)).await()
}
}
/**
* Performs asset loading tests with [AssetStorage.loadAsync] consuming [Identifier].
*/
class AssetStorageLoadingTestWithIdentifierLoadAsync : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = runBlocking {
loadAsync(Identifier(path, type), parameters).await()
}
}
/**
* Performs asset loading tests with [AssetStorage.load] consuming [AssetDescriptor].
*/
class AssetStorageLoadingTestWithAssetDescriptorLoad : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = runBlocking {
load(AssetDescriptor(path, type, parameters))
}
}
/**
* Performs asset loading tests with [AssetStorage.load] consuming [Identifier].
*/
class AssetStorageLoadingTestWithIdentifierLoad : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = runBlocking {
load(Identifier(path, type), parameters)
}
}
/**
* Performs asset loading tests with [AssetStorage.loadSync] consuming [AssetDescriptor].
*/
class AssetStorageLoadingTestWithAssetDescriptorLoadSync : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = loadSync(AssetDescriptor(path, type, parameters))
}
/**
* Performs asset loading tests with [AssetStorage.loadSync] consuming [Identifier].
*/
class AssetStorageLoadingTestWithIdentifierLoadSync : AbstractAssetStorageLoadingTest() {
override fun <T> AssetStorage.testLoad(
path: String,
type: Class<T>,
parameters: AssetLoaderParameters<T>?
): T = loadSync(Identifier(path, type), parameters)
}
| cc0-1.0 | eb866a6461e29721b37198525dc70fb9 | 31.901945 | 117 | 0.7055 | 4.392621 | false | true | false | false |
janicduplessis/react-native | packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/utils/Os.kt | 3 | 883 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.utils
object Os {
fun isWindows(): Boolean =
System.getProperty("os.name")?.lowercase()?.contains("windows") ?: false
fun isMac(): Boolean = System.getProperty("os.name")?.lowercase()?.contains("mac") ?: false
fun isLinuxAmd64(): Boolean {
val osNameMatch = System.getProperty("os.name")?.lowercase()?.contains("linux") ?: false
val archMatch = System.getProperty("os.arch")?.lowercase()?.contains("amd64") ?: false
return osNameMatch && archMatch
}
fun String.unixifyPath() =
this.replace('\\', '/').replace(":", "").let {
if (!it.startsWith("/")) {
"/$it"
} else {
it
}
}
}
| mit | 60050344aabe5c037bb73c456e987a9c | 27.483871 | 93 | 0.614949 | 4.165094 | false | false | false | false |
klose911/klose911.github.io | src/kotlin/src/tutorial/coroutine/concurrency/SharingVariable.kt | 1 | 784 | package tutorial.coroutine.concurrency
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun massiveRun(action: suspend () -> Unit) {
val n = 100 // 启动的协程数量
val k = 1000 // 每个协程重复执行同一动作的次数
val time = measureTimeMillis {
coroutineScope {
// 协程的作用域
repeat(n) {
launch {
repeat(k) {
action()
}
}
}
}
}
println("Completed ${n * k} actions in $time ms")
}
var counter1 = 0
fun main() = runBlocking {
withContext(Dispatchers.Default) {
massiveRun {
counter1++
}
}
println("Counter = $counter1")
}
| bsd-2-clause | 4e1510cf0e7f59b1277ca7e4435264e2 | 21.060606 | 53 | 0.506868 | 4.385542 | false | false | false | false |
BracketCove/PosTrainer | app/src/test/java/com/bracketcove/postrainer/ReminderLogicTest.kt | 1 | 7491 | package com.bracketcove.postrainer
import com.bracketcove.postrainer.dependencyinjection.AndroidReminderProvider
import com.bracketcove.postrainer.reminder.ReminderDetailContract
import com.bracketcove.postrainer.reminder.ReminderDetailEvent
import com.bracketcove.postrainer.reminder.ReminderDetailLogic
import com.wiseassblog.common.ReminderRepositoryException
import com.wiseassblog.common.ResultWrapper
import com.wiseassblog.domain.usecase.DeleteReminder
import com.wiseassblog.domain.usecase.GetReminder
import com.wiseassblog.domain.usecase.UpdateOrCreateReminder
import io.mockk.*
import kotlinx.coroutines.Dispatchers
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class ReminderLogicTest {
private val view: ReminderDetailContract.View = mockk(relaxed = true)
private val viewModel: ReminderDetailContract.ViewModel = mockk(relaxed = true)
private val provider: AndroidReminderProvider = mockk()
/*
Use Cases for this feature:
GetReminder
UpdateOrCreateReminder
*/
private val getReminder: GetReminder = mockk()
private val deleteReminder: DeleteReminder = mockk()
private val updateReminder: UpdateOrCreateReminder = mockk()
private val alarmDetailLogic = ReminderDetailLogic(
view,
viewModel,
provider,
Dispatchers.Unconfined
)
@BeforeEach
fun setUp() {
clearAllMocks()
every { provider.getReminder } returns getReminder
every { provider.updateOrCreateReminder } returns updateReminder
every { provider.deleteReminder } returns deleteReminder
}
/**
* Note: ViewModel will have a dummy reminder added to it within the Dependency Injection class, which will contain the Reminder ID which was passed in to this feature. However, the rest of the state
* for that dummy reminder is wrong, so it will need to be updated immediately on start.
* 1. Ask ViewModel for id
* 2. Call getReminder(id)
* 3. update ViewModel
* 4. update View
*/
@Test
fun `On Start id valid`() {
val ALARM = getReminder()
every { viewModel.getReminder() } returns ALARM
coEvery { getReminder.execute(any()) } returns ResultWrapper.build { com.bracketcove.postrainer.getReminder() }
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnStart)
verify { viewModel.getReminder() }
verify { viewModel.setReminder(ALARM) }
verify { view.setPickerTime(ALARM.hourOfDay, ALARM.minute) }
verify { view.setReminderTitle(ALARM.reminderTitle) }
verify { view.setVibrateOnly(ALARM.isVibrateOnly) }
verify { view.setRenewAutomatically(ALARM.isRenewAutomatically) }
coVerify { getReminder.execute(any()) }
}
/**
* Blank id indicates that the user wants to create a new reminder.
* 1. Retrieve reminder from VM
* 2. Write reminder back to VM with newly generated id
*/
@Test
fun `On Start id blank`() {
val ALARM = getReminder(id = "")
every { viewModel.getReminder() } returns ALARM
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnStart)
verify { viewModel.getReminder() }
verify { viewModel.setReminder(any()) }
verify { view.setPickerTime(ALARM.hourOfDay, ALARM.minute) }
verify { view.setReminderTitle(ALARM.reminderTitle) }
verify { view.setVibrateOnly(ALARM.isVibrateOnly) }
verify { view.setRenewAutomatically(ALARM.isRenewAutomatically) }
coVerify(exactly = 0) { getReminder.execute(any()) }
}
@Test
fun `On Start id invalid`() {
val ALARM = getReminder(id = null)
every { viewModel.getReminder() } returns ALARM
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnStart)
verify(exactly = 1) { viewModel.getReminder() }
verify(exactly = 1) { view.startReminderListActivity() }
verify(exactly = 1) { view.showMessage(ERROR_GENERIC) }
}
/**
* On done: User is ready to add/update the current reminder and return to Reminder List
* 1. Grab current state of the View (includes Title, picker time, vibrateOnly, renewAutomatically)
* 2. Create new copy from View State + proper ID from ViewModel
* 3. Give that copy to updateOrCreateReminder use case: Success
* 4. StartList Activity
*/
@Test
fun `On Done Update Successful`() {
val ALARM = getReminder()
every { view.getState() } returns ALARM
every { viewModel.getReminder() } returns ALARM
coEvery { updateReminder.execute(ALARM) } returns ResultWrapper.build { Unit }
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnDoneIconPress)
verify(exactly = 1) { viewModel.getReminder() }
verify(exactly = 1) { view.getState() }
verify(exactly = 1) { view.showMessage(REMINDER_UPDATED) }
verify(exactly = 1) { view.startReminderListActivity() }
coVerify { updateReminder.execute(ALARM) }
}
@Test
fun `On Done Update unsuccessful`() {
val ALARM = getReminder()
every { view.getState() } returns ALARM
every { viewModel.getReminder() } returns ALARM
coEvery { updateReminder.execute(ALARM) } returns ResultWrapper.build { throw ReminderRepositoryException }
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnDoneIconPress)
verify(exactly = 1) { viewModel.getReminder() }
verify(exactly = 1) { view.getState() }
verify(exactly = 1) { view.showMessage(ERROR_GENERIC) }
verify(exactly = 1) { view.startReminderListActivity() }
coVerify { updateReminder.execute(ALARM) }
}
@Test
fun `On Done empty reminder name`() {
val ALARM = getReminder(id = "")
every { view.getState() } returns ALARM
every { viewModel.getReminder() } returns ALARM
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnDoneIconPress)
verify(exactly = 1) { viewModel.getReminder() }
verify(exactly = 1) { view.getState() }
verify(exactly = 1) { view.showMessage(PROMPT_ENTER_NAME) }
coVerify { updateReminder.execute(ALARM) }
}
/**
*On back: User wishes to return to List View without updates
* 1. Tell view to navigate
*/
@Test
fun `On Back`() {
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnBackIconPress)
verify(exactly = 1) { view.startReminderListActivity() }
}
/**
*On Delete: User probably wants to delete the reminder
* 1. Ask user for confirmation
*/
@Test
fun `On Delete Icon Press`() {
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnDeleteIconPress)
verify(exactly = 1) { view.showDeleteConfirm() }
}
/**
*On Delete confirmed: User definitely wants to delete the reminder
* 1. Ask viewModel for id
* 2. Give id to deleteReminder use case
* 3. start list activity
*/
@Test
fun `On Delete confirmed`() {
val ALARM = getReminder()
every { viewModel.getReminder() } returns ALARM
coEvery{ deleteReminder.execute(ALARM)} returns ResultWrapper.build { Unit }
alarmDetailLogic.handleEvent(ReminderDetailEvent.OnDeleteConfirmed)
verify(exactly = 1) { view.startReminderListActivity() }
verify(exactly = 1) { view.showMessage(REMINDER_DELETED) }
coVerify(exactly = 1) { deleteReminder.execute(ALARM) }
}
}
| apache-2.0 | db8b9381b129b7ad25b42c269dab455f | 34.671429 | 203 | 0.681618 | 4.461584 | false | true | false | false |
nfrankel/kaadin | kaadin-core/src/main/kotlin/ch/frankel/kaadin/Interaction.kt | 1 | 5374 | /*
* Copyright 2016 Nicolas Fränkel
*
* 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 ch.frankel.kaadin
import com.vaadin.data.*
import com.vaadin.server.*
import com.vaadin.shared.ui.*
import com.vaadin.shared.ui.BorderStyle.*
import com.vaadin.ui.*
import com.vaadin.ui.MenuBar.*
import com.vaadin.ui.Notification.Type.*
/**
* see http://demo.vaadin.com/sampler/#ui/interaction
*/
fun HasComponents.button(caption: String? = null,
icon: Resource? = null,
onClick: ((Button.ClickEvent) -> Unit)? = null,
init: Button.() -> Unit = {}) = Button()
.addTo(this)
.apply(init)
.apply {
caption?.let { this.caption = caption }
icon?.let { this.icon = icon }
onClick?.let { addClickListener(onClick) }
}
fun Button.enable() {
isEnabled = true
}
fun Button.disable() {
isEnabled = false
}
fun HasComponents.nativeButton(caption: String? = null,
clickListener: ((Button.ClickEvent) -> Unit)? = null,
init: NativeButton.() -> Unit = {}) = NativeButton()
.addTo(this)
.apply(init)
.apply {
caption?.let { this.caption = caption }
clickListener?.let { addClickListener(clickListener) }
}
fun HasComponents.link(caption: String,
resource: Resource? = null,
targetName: String? = null,
width: Int = -1,
height: Int = -1,
border: BorderStyle = NONE,
init: Link.() -> Unit = {}) = Link()
.addTo(this)
.apply(init)
.apply {
this.caption = caption
resource?.let { this.resource = resource }
targetName?.let { this.targetName = targetName }
this.targetWidth = width
this.targetHeight = height
this.targetBorder = border
}
fun HasComponents.progressBar(progress: Float = 0f,
init: ProgressBar.() -> Unit = {}) = ProgressBar()
.addTo(this)
.apply(init)
.apply {
value = progress
addTo(this@progressBar)
}
fun HasComponents.progressBar(dataSource: Property<out Float>,
init: ProgressBar.() -> Unit = {}) = ProgressBar()
.addTo(this)
.apply(init)
.apply {
this.propertyDataSource = dataSource
addTo(this@progressBar)
}
fun HasComponents.menuBar(init: MenuBar.() -> Unit = {}): MenuBar {
return MenuBar()
.addTo(this)
.apply(init)
}
// FIXME Works only with auto-open?
fun MenuBar.menuItem(caption: String, icon: Resource? = null,
onClick: (MenuBar.MenuItem) -> Unit = {},
checkable: Boolean = false,
checked: Boolean = false,
enabled: Boolean = true,
init: MenuItem.() -> Unit = {}): MenuItem? = addItem(caption, icon, Command(onClick))
.apply {
this.isCheckable = checkable
this.isChecked = checked
this.isEnabled = enabled
}
.apply(init)
fun MenuItem.menuItem(caption: String, icon: Resource? = null,
onClick: (MenuBar.MenuItem) -> Unit = {},
checkable: Boolean = false,
checked: Boolean = false,
enabled: Boolean = true,
init: MenuItem.() -> Unit = {}): MenuItem? = addItem(caption, icon, Command(onClick))
.apply {
this.isCheckable = checkable
this.isChecked = checked
this.isEnabled = enabled
}
.apply(init)
fun MenuItem.separator(): MenuItem? = addSeparator()
fun MenuItem.select() = command?.menuSelected(this)
private fun Notification.process(init: Notification.() -> Unit) { apply(init).show(Page.getCurrent()) }
fun show(message: String, description: String? = null, html: Boolean = false, init: Notification.() -> Unit = {}) = Notification(message, description, HUMANIZED_MESSAGE, html)
.process(init)
fun warn(message: String, description: String? = null, html: Boolean = false, init: Notification.() -> Unit = {}) = Notification(message, description, WARNING_MESSAGE, html)
.process(init)
fun error(message: String, description: String? = null, html: Boolean = false, init: Notification.() -> Unit = {}) = Notification(message, description, ERROR_MESSAGE, html)
.process(init)
fun tray(message: String, description: String? = null, html: Boolean = false, init: Notification.() -> Unit = {}) = Notification(message, description, TRAY_NOTIFICATION, html)
.process(init)
| apache-2.0 | 47f94c1e6d99139bbc034e0a133827fd | 37.378571 | 175 | 0.572678 | 4.503772 | false | false | false | false |
vincentvalenlee/XCRM | src/main/kotlin/org/rocfish/domain/ql/QLBuilder.kt | 1 | 333 | package org.rocfish.domain.ql
/**
* 支持类似:
* <p>
* name=**** key=value key=value
* machine { name=*** key=*** }
* | { //或者条件
* res { name=*** version>*** key=***}
* }
* - { 非条件
* ins {time>*** time<*** key % *** key=****}
* }
* QL查询语句的语法构建器
*/
abstract class QLBuilder {
} | apache-2.0 | e12d25707e6e87e767f4beba8037d31a | 16.058824 | 48 | 0.480969 | 2.428571 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/actions/ShowFileInUnityAction.kt | 1 | 2343 | package com.jetbrains.rider.plugins.unity.actions
import com.intellij.ide.actions.RevealFileAction
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.jetbrains.rider.plugins.unity.isConnectedToEditor
import com.jetbrains.rider.plugins.unity.isUnityProject
import com.jetbrains.rider.plugins.unity.model.frontendBackend.frontendBackendModel
import com.jetbrains.rider.plugins.unity.util.Utils
import com.jetbrains.rider.projectView.solution
open class ShowFileInUnityAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val file = getFile(e) ?: return
execute(project, file)
}
override fun update(e: AnActionEvent) {
val project = e.project ?: return
// see `com.intellij.ide.actions.RevealFileAction.update`
// Cleanup context menu on selection (IDEA-245559)
val editor = e.getData(CommonDataKeys.EDITOR)
e.presentation.isEnabledAndVisible = project.isUnityProject() && getFile(e) != null &&
(!ActionPlaces.isPopupPlace(e.place) || editor == null || !editor.selectionModel.hasSelection())
e.presentation.isEnabled = project.isConnectedToEditor()
super.update(e)
}
companion object {
private fun getFile(e: AnActionEvent): VirtualFile? {
return RevealFileAction.findLocalFile(e.getData(CommonDataKeys.VIRTUAL_FILE))
}
fun execute(
project: Project,
file: VirtualFile
) {
val model = project.solution.frontendBackendModel
val value = model.unityApplicationData.valueOrNull?.unityProcessId
if (value != null)
Utils.AllowUnitySetForegroundWindow(value)
model.showFileInUnity.fire(file.path)
}
}
}
class ShowFileInUnityFromExplorerAction: ShowFileInUnityAction() {
// This action should be used in Explorers (Solution/FileSystem/UnityExplorer) where we do not want to have 'open in' IDEA action group
// See RiderRevealFileAction and RIDER-52651
} | apache-2.0 | 57a964f5f8551874e2e9ca84ce750815 | 39.413793 | 139 | 0.721724 | 4.630435 | false | false | false | false |
tom-kita/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/activity/TimelineActivity.kt | 2 | 4923 | package com.bl_lia.kirakiratter.presentation.activity
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.content.res.ResourcesCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.AdapterView
import com.bl_lia.kirakiratter.App
import com.bl_lia.kirakiratter.R
import com.bl_lia.kirakiratter.presentation.adapter.timeline.TimelineFragmentPagerAdapter
import com.bl_lia.kirakiratter.presentation.adapter.timeline.TimelineSpinnerAdapter
import com.bl_lia.kirakiratter.presentation.fragment.NavigationDrawerFragment
import com.bl_lia.kirakiratter.presentation.fragment.ScrollableFragment
import com.bl_lia.kirakiratter.presentation.internal.di.component.DaggerTimelineActivityComponent
import com.bl_lia.kirakiratter.presentation.internal.di.component.TimelineActivityComponent
import com.bl_lia.kirakiratter.presentation.presenter.TimelineActivityPresenter
import kotlinx.android.synthetic.main.activity_timeline.*
import javax.inject.Inject
class TimelineActivity : AppCompatActivity() {
val timelines: List<String> = listOf("home", "local")
val spinnerAdapter: TimelineSpinnerAdapter by lazy {
TimelineSpinnerAdapter(this, android.R.layout.simple_spinner_dropdown_item, timelines)
}
val timelineFragmentAdapter by lazy { TimelineFragmentPagerAdapter(supportFragmentManager) }
@Inject
lateinit var presenter: TimelineActivityPresenter
private var isSpinnerInitialized: Boolean = false
private val component: TimelineActivityComponent by lazy {
DaggerTimelineActivityComponent.builder()
.applicationComponent((application as App).component)
.build()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_timeline)
component.inject(this)
view_pager.adapter = timelineFragmentAdapter
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction().also { transaction ->
val fragment = NavigationDrawerFragment.newInstance()
transaction.add(R.id.left_drawer, fragment)
}.commit()
}
initView()
}
private fun initView() {
button_katsu.setOnClickListener {
val intent = Intent(this, KatsuActivity::class.java)
startActivity(intent)
}
button_menu.setOnClickListener {
if (!layout_drawer.isDrawerOpen(left_drawer)) {
layout_drawer.openDrawer(left_drawer)
}
}
spinner_timeline.adapter = spinnerAdapter
spinner_timeline.onItemSelectedListener = object: AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (!isSpinnerInitialized) {
isSpinnerInitialized = true
return
}
showTimeline(position)
presenter.setSelectedTimeline(timelines[position])
}
override fun onNothingSelected(p0: AdapterView<*>?) {
val position = spinner_timeline.selectedItemPosition
view_pager.currentItem = position
}
}
button_account.setOnClickListener {
val intent = Intent(this, AccountActivity::class.java)
startActivity(intent)
}
button_notification.setOnClickListener { view_pager.setCurrentItem(2, false) }
button_search.setOnClickListener { showNothing() }
view_pager.post {
presenter.getSelectedTimeline()
.subscribe { timeline, error ->
val index = timelines.indexOf(timeline)
if (index > -1) {
showTimeline(index)
}
}
}
toolbar_space_left.setOnClickListener {
val innerFragment = timelineFragmentAdapter.getItem(view_pager.currentItem)
if(innerFragment is ScrollableFragment) {
innerFragment.scrollToTop()
}
}
}
private fun showTimeline(position: Int) {
when (position) {
0 -> {
spinner_timeline.background = ResourcesCompat.getDrawable(resources, R.drawable.ic_home_kira_18px, null)
view_pager.setCurrentItem(0, false)
}
1 -> {
spinner_timeline.background = ResourcesCompat.getDrawable(resources, R.drawable.ic_group_kira_18px, null)
view_pager.setCurrentItem(1, false)
}
}
}
private fun showNothing() {
Snackbar.make(layout_drawer, "まだないよ!", Snackbar.LENGTH_SHORT).show()
}
} | mit | 253ce7838348ddcc57d7af9c8ba40053 | 36.784615 | 121 | 0.657096 | 5.10499 | false | false | false | false |
meh/watch_doge | src/main/java/meh/watchdoge/backend/Module.kt | 1 | 4162 | package meh.watchdoge.backend;
import meh.watchdoge.Request;
import meh.watchdoge.request.Request as RequestBuilder;
import meh.watchdoge.Response;
import meh.watchdoge.response.Control;
import java.util.HashMap;
import java.util.HashSet;
import nl.komponents.kovenant.*;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.content.ContextWrapper;
import org.msgpack.core.MessagePacker;
import org.msgpack.core.MessageUnpacker;
abstract class Module(backend: Backend): ContextWrapper(backend.getApplicationContext()) {
protected val _backend: Backend;
protected val _unpacker: MessageUnpacker;
init {
_backend = backend;
_unpacker = backend.unpacker();
}
fun response(req: Request, status: Int, body: (Control.() -> Unit)? = null): Int {
return _backend.response(req, status, body);
}
fun forward(req: Request, body: (MessagePacker) -> Unit): Int {
return _backend.forward(req, body);
}
abstract fun receive();
abstract fun response(messenger: Messenger, req: Request, status: Int);
abstract fun request(req: Request): Boolean;
abstract class Connection(conn: meh.watchdoge.backend.Connection) {
protected val _connection = conn;
fun request(body: RequestBuilder.() -> Unit): Promise<Response, Response.Exception> {
return _connection.request(body);
}
abstract fun handle(msg: Message): Boolean;
interface ISubscription {
fun unsubscribe();
}
abstract class Subscription<T: IEvent>(body: (T) -> Unit): ISubscription {
protected val _body = body;
fun unsubscribe(sub: ISubscriber<T>) {
sub.with {
it.remove(_body);
}
}
}
abstract class SubscriptionWithId<T: IEventWithId>(id: Int, body: (T) -> Unit): ISubscription {
protected val _id = id;
protected val _body = body;
fun unsubscribe(sub: ISubscriberWithId<T>) {
sub.with {
it.get(_id)?.remove(_body);
}
}
}
interface IEmitter<T: IEvent> {
fun emit(event: T);
}
interface ISubscriberWithId<T: IEventWithId>: IEmitter<T> {
fun with(body: (HashMap<Int, HashSet<(T) -> Unit>>) -> Unit);
fun empty(id: Int): Boolean;
fun subscribe(id: Int, body: (T) -> Unit);
}
interface ISubscriber<T: IEvent>: IEmitter<T> {
fun with(body: (HashSet<(T) -> Unit>) -> Unit);
fun empty(): Boolean;
fun subscribe(body: (T) -> Unit);
}
open class Subscriber<T: IEvent>: ISubscriber<T> {
protected val _set: HashSet<(T) -> Unit> = HashSet();
override fun with(body: (HashSet<(T) -> Unit>) -> Unit) {
synchronized(_set) {
body(_set);
}
}
override fun empty(): Boolean {
synchronized(_set) {
return _set.isEmpty();
}
}
override fun subscribe(body: (T) -> Unit) {
synchronized(_set) {
_set.add(body);
}
}
override fun emit(event: T) {
synchronized(_set) {
for (sub in _set) {
sub(event);
}
}
}
}
open class SubscriberWithId<T: IEventWithId>: ISubscriberWithId<T> {
protected val _map: HashMap<Int, HashSet<(T) -> Unit>> = HashMap();
override fun with(body: (HashMap<Int, HashSet<(T) -> Unit>>) -> Unit) {
synchronized(_map) {
body(_map);
}
}
override fun empty(id: Int): Boolean {
synchronized(_map) {
if (!_map.containsKey(id)) {
return true;
}
return _map.get(id)!!.isEmpty();
}
}
override fun subscribe(id: Int, body: (T) -> Unit) {
synchronized(_map) {
if (!_map.containsKey(id)) {
_map.put(id, HashSet());
}
_map.get(id)!!.add(body);
}
}
override fun emit(event: T) {
synchronized(_map) {
val subs = _map.get(event.id());
if (subs != null) {
for (sub in subs) {
sub(event)
}
}
}
}
}
}
interface IEvent {
fun bundle(): Bundle;
}
interface IEventWithId: IEvent {
fun id(): Int;
}
open class Event(bundle: Bundle): IEvent {
protected val _bundle = bundle;
override fun bundle(): Bundle {
return _bundle;
}
}
open class EventWithId(id: Int, bundle: Bundle): Event(bundle), IEventWithId {
protected val _id = id;
override fun id(): Int {
return _id;
}
}
}
| agpl-3.0 | 09253d4311901f5825773c698fd9790d | 21.138298 | 97 | 0.630947 | 3.177099 | false | false | false | false |
EyeBody/EyeBody | EyeBody2/app/src/main/java/com/example/android/eyebody/management/config/subcontent/CMBaseSubContent.kt | 1 | 1351 | package com.example.android.eyebody.management.config.subcontent
import junit.framework.Assert
/**
* Created by YOON on 2017-11-19
*/
/**
* preference are saved false or true
* actually it saved 0, 1, 2, 3, ~.
*
* switch used when need boolean type selector,
* switch not used when need string type selector (using dialog)
* @param preferenceValueExplanation optional param, {false, true} for explanation string when using switch, {preferenceValueList} for explanation when not using switch.
*/
open class CMBaseSubContent(val text: String = "", val hasSwitch: Boolean, val preferenceName: String?,
val preferenceValueExplanation: List<String>? = null) {
/*
text 가 큰 글씨로 써지고
그 밑에 preferenceValueExplanation 이 써짐 (현재 value 에 따라 출력, null 일 경우 안 씀)
*/
init {
Assert.assertTrue("Assertion failed : more than 1 preferenceValueExplanation needs preferenceName\n" +
"if not needed, preferenceName must be null\n" +
"preferenceName : is null : ${preferenceName == null}\n" +
"preferenceValueExplanation : size : ${preferenceValueExplanation?.size ?: "null"}",
(preferenceName == null) == (preferenceValueExplanation == null || preferenceValueExplanation.size <= 1))
}
}
| mit | d844afa3b84e58611c23d63f7ec2786b | 42.3 | 169 | 0.674365 | 3.972477 | false | false | false | false |
Shashi-Bhushan/General | cp-trials/src/main/kotlin/in/shabhushan/cp_trials/contest/march7/DecreasingString.kt | 1 | 687 | package `in`.shabhushan.cp_trials.contest.march7
import java.util.*
object DecreasingString {
fun sortString(s: String): String {
val map = TreeMap<String, Int>()
s.split("").filter { it.isNotBlank() }.forEach {
map[it] = map.getOrDefault(it, 0) + 1
}
val sb = StringBuilder()
val keys = map.keys.toTypedArray()
while (map.isNotEmpty()) {
keys.mapNotNull {
if (map.containsKey(it) && map[it] != 0) {
map[it] = map[it]!! - 1
it
} else {
map.remove(it)
null
}
}.joinToString("").let {
sb.append(it)
}
keys.reverse()
}
return sb.toString()
}
}
| gpl-2.0 | b3a849b0950b176505c961487d5108b7 | 18.628571 | 52 | 0.528384 | 3.596859 | false | false | false | false |
jainaman224/Algo_Ds_Notes | Quick_Sort/Quick_Sort.kt | 1 | 1259 | /* QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array
around the picked pivot.It's Best case complexity is n*log(n) & Worst case complexity is n^2. */
//partition array
fun quick_sort(A: Array<Int>, p: Int, r: Int) {
if (p < r) {
var q: Int = partition(A, p, r)
quick_sort(A, p, q - 1)
quick_sort(A, q + 1, r)
}
}
//assign last value as pivot
fun partition(A: Array<Int>, p: Int, r: Int): Int {
var x = A[r]
var i = p - 1
for (j in p until r) {
if (A[j] <= x) {
i++
exchange(A, i, j)
}
}
exchange(A, i + 1, r)
return i + 1
}
//swap
fun exchange(A: Array<Int>, i: Int, j: Int) {
var temp = A[i]
A[i] = A[j]
A[j] = temp
}
fun main(arg: Array<String>) {
print("Enter no. of elements :")
var n = readLine()!!.toInt()
println("Enter elements : ")
var A = Array(n, { 0 })
for (i in 0 until n)
A[i] = readLine()!!.toInt()
quick_sort(A, 0, A.size - 1)
println("Sorted array is : ")
for (i in 0 until n)
print("${A[i]} ")
}
/*-------OUTPUT--------------
Enter no. of elements :6
Enter elements :
4
8
5
9
2
6
Sorted array is :
2 4 5 6 8 9
*/
| gpl-3.0 | 5aeda3313ca6e11c5b14ed77dae416e0 | 18.984127 | 108 | 0.51946 | 2.867882 | false | false | false | false |
semonte/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/cellReader/ExtendedJTreeCellReader.kt | 1 | 2062 | /*
* 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.testGuiFramework.cellReader
import com.intellij.ui.SimpleColoredComponent
import org.fest.swing.cell.JTreeCellReader
import org.fest.swing.core.BasicRobot
import org.fest.swing.driver.BasicJTreeCellReader
import org.fest.swing.exception.ComponentLookupException
import java.awt.Component
import java.awt.Container
import javax.swing.JLabel
import javax.swing.JTree
/**
* @author Sergey Karashevich
*/
class ExtendedJTreeCellReader : BasicJTreeCellReader(), JTreeCellReader {
override fun valueAt(tree: JTree, modelValue: Any?): String? {
if (modelValue == null) return null
val cellRendererComponent = tree.cellRenderer.getTreeCellRendererComponent(tree, modelValue, false, false, false, 0, false)
when (cellRendererComponent) {
is JLabel -> return cellRendererComponent.text
is SimpleColoredComponent -> return cellRendererComponent.getText()
else -> return cellRendererComponent.findLabel()?.text
}
}
private fun SimpleColoredComponent.getText(): String?
= this.iterator().asSequence().joinToString()
private fun Component.findLabel(): JLabel? {
try {
assert(this is Container)
val label = BasicRobot.robotWithNewAwtHierarchyWithoutScreenLock().finder().find(
this as Container) { component -> component is JLabel }
assert(label is JLabel)
return label as JLabel
}
catch (ignored: ComponentLookupException) {
return null
}
}
}
| apache-2.0 | a0f8dbac4964ab61252c9ac1213dbd3b | 33.366667 | 127 | 0.746363 | 4.561947 | false | false | false | false |
FredJul/TaskGame | TaskGame/src/main/java/net/fred/taskgame/receivers/AlarmReceiver.kt | 1 | 5283 | /*
* 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.receivers
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import net.fred.taskgame.R
import net.fred.taskgame.activities.SnoozeActivity
import net.fred.taskgame.models.Task
import net.fred.taskgame.utils.Constants
import net.fred.taskgame.utils.DbUtils
import net.fred.taskgame.utils.NotificationsHelper
import net.fred.taskgame.utils.PrefUtils
import net.fred.taskgame.utils.date.DateHelper
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
class AlarmReceiver : BroadcastReceiver(), AnkoLogger {
override fun onReceive(context: Context, intent: Intent) {
try {
val task = DbUtils.getTask(intent.extras.getString(Constants.EXTRA_TASK_ID))
if (task != null) {
createNotification(context, task)
}
} catch (e: Exception) {
error("Error while creating reminder notification", e)
}
}
private fun createNotification(context: Context, task: Task) {
// Prepare text contents
val title = if (task.title.isNotEmpty()) task.title else task.content
val alarmText = DateHelper.getDateTimeShort(context, task.alarmDate)
val text = if (task.title.isNotEmpty() && task.content.isNotEmpty()) task.content else alarmText
val doneIntent = Intent(context, SnoozeActivity::class.java)
doneIntent.action = Constants.ACTION_DONE
doneIntent.putExtra(Constants.EXTRA_TASK_ID, task.id) // Do not use parcelable with API 24+ for PendingIntent
doneIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val piDone = PendingIntent.getActivity(context, 0, doneIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val snoozeIntent = Intent(context, SnoozeActivity::class.java)
snoozeIntent.action = Constants.ACTION_SNOOZE
snoozeIntent.putExtra(Constants.EXTRA_TASK_ID, task.id) // Do not use parcelable with API 24+ for PendingIntent
snoozeIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val piSnooze = PendingIntent.getActivity(context, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT)
val postponeIntent = Intent(context, SnoozeActivity::class.java)
postponeIntent.action = Constants.ACTION_POSTPONE
postponeIntent.putExtra(Constants.EXTRA_TASK_ID, task.id) // Do not use parcelable with API 24+ for PendingIntent
snoozeIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val piPostpone = PendingIntent.getActivity(context, 0, postponeIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
val snoozeDelay = PrefUtils.getString(PrefUtils.PREF_SETTINGS_NOTIFICATION_SNOOZE_DELAY, "10")
// Next create the bundle and initialize it
val intent = Intent(context, SnoozeActivity::class.java)
intent.putExtra(Constants.EXTRA_TASK_ID, task.id) // Do not use parcelable with API 24+ for PendingIntent
// Sets the Activity to start in a new, empty task
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// Workaround to fix problems with multiple notifications
intent.action = Constants.ACTION_NOTIFICATION_CLICK + java.lang.Long.toString(System.currentTimeMillis())
// Creates the PendingIntent
val notifyIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT)
val notificationsHelper = NotificationsHelper(context)
.createNotification(R.drawable.ic_assignment_white_24dp, title, notifyIntent)
.setLargeIcon(R.mipmap.ic_launcher)
.setMessage(text)
notificationsHelper.builder
?.addAction(R.drawable.ic_done_white_24dp, context.getString(R.string.done), piDone)
?.addAction(R.drawable.ic_update_white_24dp, context.getString(R.string.snooze, java.lang.Long.valueOf(snoozeDelay)), piSnooze)
?.addAction(R.drawable.ic_alarm_white_24dp, context.getString(R.string.set_reminder), piPostpone)
// Ringtone options
val ringtone = PrefUtils.getString(PrefUtils.PREF_SETTINGS_NOTIFICATION_RINGTONE, "")
if (!ringtone.isEmpty()) {
notificationsHelper.setRingtone(ringtone)
}
// Vibration options
val pattern = longArrayOf(500, 500)
if (PrefUtils.getBoolean(PrefUtils.PREF_SETTINGS_NOTIFICATION_VIBRATION, true))
notificationsHelper.setVibration(pattern)
notificationsHelper.show(task.id!!.hashCode().toLong())
}
}
| gpl-3.0 | e83589c077379564177df3b760785d4e | 46.169643 | 143 | 0.710392 | 4.35173 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/executors/msc/TempRoleCommands.kt | 1 | 3476 | package me.mrkirby153.KirBot.command.executors.msc
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist
import me.mrkirby153.KirBot.command.annotations.LogInModlogs
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.infraction.InfractionType
import me.mrkirby153.KirBot.infraction.Infractions
import me.mrkirby153.KirBot.user.CLEARANCE_ADMIN
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.FuzzyMatchException
import me.mrkirby153.KirBot.utils.canAssign
import me.mrkirby153.KirBot.utils.logName
import me.mrkirby153.KirBot.utils.nameAndDiscrim
import me.mrkirby153.kcutils.Time
import net.dv8tion.jda.api.Permission
import java.sql.Timestamp
import java.time.Instant
import javax.inject.Inject
class TempRoleCommands @Inject constructor(private val infractions: Infractions) {
@Command(name = "temprole",
arguments = ["<user:snowflake>", "<role:string>", "<duration:string>", "[reason:string...]"],
clearance = CLEARANCE_ADMIN, permissions = [Permission.MANAGE_ROLES], category = CommandCategory.MODERATION)
@LogInModlogs
@CommandDescription("Temporarily assign a role to a user")
@IgnoreWhitelist
fun execute(context: Context, cmdContext: CommandContext) {
val userId = cmdContext.get<String>("user")!!
val durationRaw = cmdContext.get<String>("duration")!!
val reason = cmdContext.get<String>("reason")
val roleQuery = cmdContext.get<String>("role")!!
val duration = try {
Time.parse(durationRaw)
} catch (e: IllegalArgumentException) {
throw CommandException(
e.message ?: "An unknown error occurred when parsing the duration")
}
val timestamp = Instant.now().plusMillis(duration)
val target = context.guild.getMemberById(userId) ?: throw CommandException("User not found")
val role = try {
context.kirbotGuild.matchRole(roleQuery) ?: throw CommandException(
"No roles found for that query")
} catch (e: FuzzyMatchException.TooManyMatchesException) {
throw CommandException(
"Too many matches for that query. Try a more specific query or the role id")
} catch (e: FuzzyMatchException.NoMatchesException) {
throw CommandException("No roles found for that query")
}
RoleCommands.checkManipulate(context.member!!, target)
RoleCommands.checkAssignment(context.member!!, role)
if (!context.guild.selfMember.canAssign(role))
throw CommandException("I cannot assign that role")
if (role in target.roles)
throw CommandException("${target.user.nameAndDiscrim} is already in that role")
context.guild.addRoleToMember(target, role).queue {
infractions.createInfraction(userId, context.guild, context.author.id,
"${role.name} - $reason",
InfractionType.TEMPROLE, Timestamp.from(timestamp), role.id)
context.send().success(
"${target.user.logName} is now in ${role.name} for ${Time.format(1,
duration)}").queue()
}
}
} | mit | 4df6e59716b751109aace15da323589a | 44.155844 | 120 | 0.695915 | 4.439336 | false | false | false | false |
SimpleTimeTracking/StandaloneClient | src/main/kotlin/org/stt/gui/jfx/TimeTrackingItemCellWithActions.kt | 1 | 6775 | package org.stt.gui.jfx
import com.sun.javafx.geom.BaseBounds
import com.sun.javafx.geom.transform.BaseTransform
import com.sun.javafx.jmx.MXNodeAlgorithm
import com.sun.javafx.jmx.MXNodeAlgorithmContext
import com.sun.javafx.sg.prism.NGNode
import javafx.animation.FadeTransition
import javafx.beans.binding.Bindings
import javafx.beans.property.DoubleProperty
import javafx.beans.property.SimpleDoubleProperty
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.*
import javafx.scene.layout.*
import javafx.scene.paint.Color
import javafx.scene.text.Font
import org.stt.gui.jfx.Glyph.Companion.GLYPH_SIZE_MEDIUM
import org.stt.gui.jfx.Glyph.Companion.glyph
import org.stt.model.TimeTrackingItem
import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle
import java.util.*
import java.util.concurrent.Callable
import java.util.function.Predicate
internal open class TimeTrackingItemCellWithActions(fontAwesome: Font,
localization: ResourceBundle,
private val lastItemOfDay: Predicate<TimeTrackingItem>,
actionsHandler: ActionsHandler,
labelToNodeMapper: ActivityTextDisplayProcessor) : ListCell<TimeTrackingItem>() {
private val cellPane = HBox(2.0)
val editButton: Button
val continueButton: Button
val deleteButton: Button
val stopButton: Button
private val lastItemOnDayPane: BorderPane
private val newDayNode: Node
private val itemNodes: TimeTrackingItemNodes
private val actions: HBox
init {
itemNodes = TimeTrackingItemNodes(labelToNodeMapper, TIME_FORMATTER, fontAwesome, 450, 180, localization)
editButton = FramelessButton(glyph(fontAwesome, Glyph.PENCIL, GLYPH_SIZE_MEDIUM))
continueButton = FramelessButton(glyph(fontAwesome, Glyph.PLAY_CIRCLE, GLYPH_SIZE_MEDIUM, Color.DARKGREEN))
deleteButton = FramelessButton(glyph(fontAwesome, Glyph.TRASH, GLYPH_SIZE_MEDIUM, Color.web("e26868")))
stopButton = FramelessButton(glyph(fontAwesome, Glyph.STOP_CIRCLE, GLYPH_SIZE_MEDIUM, Color.GOLDENROD))
setupTooltips(localization)
continueButton.setOnAction { actionsHandler.continueItem(item) }
editButton.setOnAction { actionsHandler.edit(item) }
deleteButton.setOnAction { actionsHandler.delete(item) }
stopButton.setOnAction { actionsHandler.stop(item) }
actions = HBox(continueButton, editButton, deleteButton)
StackPane.setAlignment(actions, Pos.CENTER)
val timeOrActions = StackPaneWithoutResize()
actions.opacityProperty().bind(fadeOnHoverProperty())
val one = SimpleDoubleProperty(1.0)
val timePaneOpacity = one.subtract(Bindings.min(one, fadeOnHoverProperty().multiply(2)))
itemNodes.appendNodesTo(timeOrActions, timePaneOpacity, cellPane.children)
timeOrActions.children.add(actions)
cellPane.alignment = Pos.CENTER_LEFT
lastItemOnDayPane = BorderPane()
newDayNode = createDateSubheader(fontAwesome)
contentDisplay = ContentDisplay.GRAPHIC_ONLY
}
private fun fadeOnHoverProperty(): DoubleProperty {
val placeHolder = DummyNode()
placeHolder.opacity = 0.0
val fade = FadeTransition()
fade.fromValue = 0.0
fade.toValue = 1.0
fade.node = placeHolder
cellPane.hoverProperty().addListener { _, _, newValue ->
fade.rate = (if (newValue) 1 else -1).toDouble()
fade.play()
}
return placeHolder.opacityProperty()
}
private fun createDateSubheader(fontAwesome: Font): Node {
val newDayHbox = HBox(5.0)
newDayHbox.padding = Insets(2.0)
val calenderIcon = glyph(fontAwesome, Glyph.CALENDAR)
calenderIcon.textFill = Color.BLACK
newDayHbox.children.add(calenderIcon)
val dayLabel = Label()
dayLabel.textFill = Color.BLACK
dayLabel.textProperty().bind(Bindings.createStringBinding(
Callable { if (itemProperty().get() == null) "" else DATE_FORMATTER.format(itemProperty().get().start) },
itemProperty()))
newDayHbox.children.add(dayLabel)
newDayHbox.background = Background(BackgroundFill(Color.LIGHTSTEELBLUE, null, null))
return newDayHbox
}
fun setupTooltips(localization: ResourceBundle) {
editButton.tooltip = Tooltip(localization
.getString("itemList.edit"))
continueButton.tooltip = Tooltip(localization
.getString("itemList.continue"))
deleteButton.tooltip = Tooltip(localization
.getString("itemList.delete"))
stopButton.tooltip = Tooltip(localization
.getString("itemList.stop"))
}
public override fun updateItem(item: TimeTrackingItem?, empty: Boolean) {
super.updateItem(item, empty)
if (empty || item == null) {
graphic = null
} else {
actions.children[0] = if (item.end != null) continueButton else stopButton
itemNodes.setItem(item)
graphic = if (lastItemOfDay.test(item)) {
setupLastItemOfDayPane()
lastItemOnDayPane
} else {
setupCellPane()
cellPane
}
}
}
private fun setupCellPane() {
lastItemOnDayPane.center = null
lastItemOnDayPane.top = null
}
private fun setupLastItemOfDayPane() {
lastItemOnDayPane.center = cellPane
lastItemOnDayPane.top = newDayNode
BorderPane.setMargin(newDayNode, Insets(10.0, 0.0, 10.0, 0.0))
}
interface ActionsHandler {
fun continueItem(item: TimeTrackingItem)
fun edit(item: TimeTrackingItem)
fun delete(item: TimeTrackingItem)
fun stop(item: TimeTrackingItem)
}
private class DummyNode : Node() {
override fun impl_createPeer(): NGNode? {
return null
}
override fun impl_computeGeomBounds(bounds: BaseBounds, tx: BaseTransform): BaseBounds? {
return null
}
override fun impl_computeContains(localX: Double, localY: Double): Boolean {
return false
}
override fun impl_processMXNode(alg: MXNodeAlgorithm, ctx: MXNodeAlgorithmContext): Any? {
return null
}
}
companion object {
private val TIME_FORMATTER = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM)
private val DATE_FORMATTER = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)
}
}
| gpl-3.0 | f4c84f0cb3207d6a67f0c52fd9ea685f | 36.638889 | 133 | 0.666568 | 4.516667 | false | false | false | false |
uber/RIBs | android/demos/compose/src/main/kotlin/com/uber/rib/compose/root/main/logged_in/LoggedInView.kt | 1 | 2428 | /*
* Copyright (C) 2021. Uber Technologies
*
* 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.uber.rib.compose.root.main.logged_in
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.uber.rib.compose.util.CustomButton
import com.uber.rib.compose.util.EventStream
@Composable
fun LoggedInView(
eventStream: EventStream<LoggedInEvent>,
childContent: LoggedInRouter.ChildContent,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Top,
modifier = Modifier
.fillMaxSize()
.background(Color.Green)
) {
Text("Logged In! (Compose RIB)")
Spacer(Modifier.height(16.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.weight(1.0f)
.padding(4.dp)
.background(Color.LightGray)
) {
childContent.fullScreenSlot.value.invoke()
}
CustomButton(
analyticsId = "8a570808-07a4",
onClick = { eventStream.notify(LoggedInEvent.LogOutClick) },
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
Text(text = "LOGOUT")
}
}
}
@Preview
@Composable
fun LoggedInViewPreview() {
LoggedInView(EventStream(), LoggedInRouter.ChildContent())
}
| apache-2.0 | 8f99025c42786c5095810ecec550e6f3 | 30.947368 | 75 | 0.747941 | 4.080672 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/collections/processors/UpdateEntitySetCollectionTemplateProcessor.kt | 1 | 960 | package com.openlattice.collections.processors
import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor
import com.openlattice.collections.EntitySetCollection
import java.util.*
class UpdateEntitySetCollectionTemplateProcessor(val template: MutableMap<UUID, UUID>) : AbstractRhizomeEntryProcessor<UUID, EntitySetCollection, EntitySetCollection?>() {
override fun process(entry: MutableMap.MutableEntry<UUID, EntitySetCollection>): EntitySetCollection? {
val collection = entry.value
collection.template = template
entry.setValue(collection)
return null
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as UpdateEntitySetCollectionTemplateProcessor
return template == other.template
}
override fun hashCode(): Int {
return template.hashCode()
}
} | gpl-3.0 | c9d9bcb47ae75e0825cc70d8c57ae610 | 29.03125 | 171 | 0.735417 | 5.517241 | false | false | false | false |
square/moshi | moshi-kotlin-codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/AdapterGenerator.kt | 1 | 28128 | /*
* Copyright (C) 2018 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.squareup.moshi.kotlin.codegen.api
import com.squareup.kotlinpoet.ARRAY
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.AnnotationSpec.UseSiteTarget.FILE
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.INT
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.MemberName
import com.squareup.kotlinpoet.NameAllocator
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.ParameterizedTypeName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.joinToCode
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.codegen.api.FromJsonComponent.ParameterOnly
import com.squareup.moshi.kotlin.codegen.api.FromJsonComponent.ParameterProperty
import com.squareup.moshi.kotlin.codegen.api.FromJsonComponent.PropertyOnly
import java.lang.reflect.Constructor
import java.lang.reflect.Type
import org.objectweb.asm.Type as AsmType
private const val MOSHI_UTIL_PACKAGE = "com.squareup.moshi.internal"
private const val TO_STRING_PREFIX = "GeneratedJsonAdapter("
private const val TO_STRING_SIZE_BASE = TO_STRING_PREFIX.length + 1 // 1 is the closing paren
/** Generates a JSON adapter for a target type. */
@InternalMoshiCodegenApi
public class AdapterGenerator(
private val target: TargetType,
private val propertyList: List<PropertyGenerator>
) {
private companion object {
private val INT_TYPE_BLOCK = CodeBlock.of("%T::class.javaPrimitiveType", INT)
private val DEFAULT_CONSTRUCTOR_MARKER_TYPE_BLOCK = CodeBlock.of(
"%M",
MemberName(MOSHI_UTIL_PACKAGE, "DEFAULT_CONSTRUCTOR_MARKER")
)
private val CN_MOSHI = Moshi::class.asClassName()
private val CN_TYPE = Type::class.asClassName()
private val COMMON_SUPPRESS = arrayOf(
// https://github.com/square/moshi/issues/1023
"DEPRECATION",
// Because we look it up reflectively
"unused",
"UNUSED_PARAMETER",
// Because we include underscores
"ClassName",
// Because we generate redundant `out` variance for some generics and there's no way
// for us to know when it's redundant.
"REDUNDANT_PROJECTION",
// Because we may generate redundant explicit types for local vars with default values.
// Example: 'var fooSet: Boolean = false'
"RedundantExplicitType",
// NameAllocator will just add underscores to differentiate names, which Kotlin doesn't
// like for stylistic reasons.
"LocalVariableName",
// KotlinPoet always generates explicit public modifiers for public members.
"RedundantVisibilityModifier",
// For LambdaTypeNames we have to import kotlin.functions.* types
"PLATFORM_CLASS_MAPPED_TO_KOTLIN",
// Cover for calling fromJson() on a Nothing property type. Theoretically nonsensical but we
// support it
"IMPLICIT_NOTHING_TYPE_ARGUMENT_IN_RETURN_POSITION"
).let { suppressions ->
AnnotationSpec.builder(Suppress::class)
.useSiteTarget(FILE)
.addMember(
suppressions.indices.joinToString { "%S" },
*suppressions
)
.build()
}
}
private val nonTransientProperties = propertyList.filterNot { it.isTransient }
private val className = target.typeName.rawType()
private val visibility = target.visibility
private val typeVariables = target.typeVariables
private val typeVariableResolver = typeVariables.toTypeVariableResolver()
private val targetConstructorParams = target.constructor.parameters
.mapKeys { (_, param) -> param.index }
private val nameAllocator = NameAllocator()
private val adapterName = "${className.simpleNames.joinToString(separator = "_")}JsonAdapter"
private val originalTypeName = target.typeName.stripTypeVarVariance(typeVariableResolver)
private val originalRawTypeName = originalTypeName.rawType()
private val moshiParam = ParameterSpec.builder(
nameAllocator.newName("moshi"),
CN_MOSHI
).build()
private val typesParam = ParameterSpec.builder(
nameAllocator.newName("types"),
ARRAY.parameterizedBy(CN_TYPE)
)
.build()
private val readerParam = ParameterSpec.builder(
nameAllocator.newName("reader"),
JsonReader::class
)
.build()
private val writerParam = ParameterSpec.builder(
nameAllocator.newName("writer"),
JsonWriter::class
)
.build()
// Don't use NameAllocator here because it will add `_` to the name since it's a keyword, and that
// results in it warning about not matching the overridden function's params.
// https://github.com/square/moshi/issues/1502
private val valueParam = ParameterSpec.builder(
"value",
originalTypeName.copy(nullable = true)
)
.build()
private val jsonAdapterTypeName = JsonAdapter::class.asClassName().parameterizedBy(
originalTypeName
)
// selectName() API setup
private val optionsProperty = PropertySpec.builder(
nameAllocator.newName("options"),
JsonReader.Options::class.asTypeName(),
KModifier.PRIVATE
)
.initializer(
"%T.of(%L)",
JsonReader.Options::class.asTypeName(),
nonTransientProperties
.map { CodeBlock.of("%S", it.jsonName) }
.joinToCode(", ")
)
.build()
private val constructorProperty = PropertySpec.builder(
nameAllocator.newName("constructorRef"),
Constructor::class.asClassName().parameterizedBy(originalTypeName).copy(nullable = true),
KModifier.PRIVATE
)
.addAnnotation(Volatile::class)
.mutable(true)
.initializer("null")
.build()
public fun prepare(generateProguardRules: Boolean, typeHook: (TypeSpec) -> TypeSpec = { it }): PreparedAdapter {
val reservedSimpleNames = mutableSetOf<String>()
for (property in nonTransientProperties) {
// Allocate names for simple property types first to avoid collisions
// See https://github.com/square/moshi/issues/1277
property.target.type.findRawType()?.simpleName?.let { simpleNameToReserve ->
if (reservedSimpleNames.add(simpleNameToReserve)) {
nameAllocator.newName(simpleNameToReserve)
}
}
property.allocateNames(nameAllocator)
}
val generatedAdapter = generateType().let(typeHook)
val result = FileSpec.builder(className.packageName, adapterName)
result.addFileComment("Code generated by moshi-kotlin-codegen. Do not edit.")
result.addAnnotation(COMMON_SUPPRESS)
result.addType(generatedAdapter)
val proguardConfig = if (generateProguardRules) {
generatedAdapter.createProguardRule()
} else {
null
}
return PreparedAdapter(result.build(), proguardConfig)
}
private fun TypeSpec.createProguardRule(): ProguardConfig {
val adapterConstructorParams = when (requireNotNull(primaryConstructor).parameters.size) {
1 -> listOf(CN_MOSHI.reflectionName())
2 -> listOf(CN_MOSHI.reflectionName(), "${CN_TYPE.reflectionName()}[]")
// Should never happen
else -> error("Unexpected number of arguments on primary constructor: $primaryConstructor")
}
var hasDefaultProperties = false
var parameterTypes = emptyList<String>()
target.constructor.signature?.let { constructorSignature ->
if (constructorSignature.startsWith("constructor-impl")) {
// Inline class, we don't support this yet.
// This is a static method with signature like 'constructor-impl(I)I'
return@let
}
hasDefaultProperties = propertyList.any { it.hasDefault }
parameterTypes = AsmType.getArgumentTypes(constructorSignature.removePrefix("<init>"))
.map { it.toReflectionString() }
}
return ProguardConfig(
targetClass = className,
adapterName = adapterName,
adapterConstructorParams = adapterConstructorParams,
targetConstructorHasDefaults = hasDefaultProperties,
targetConstructorParams = parameterTypes,
)
}
private fun generateType(): TypeSpec {
val result = TypeSpec.classBuilder(adapterName)
result.superclass(jsonAdapterTypeName)
if (typeVariables.isNotEmpty()) {
result.addTypeVariables(typeVariables.map { it.stripTypeVarVariance(typeVariableResolver) as TypeVariableName })
// require(types.size == 1) {
// "TypeVariable mismatch: Expecting 1 type(s) for generic type variables [T], but received ${types.size} with values $types"
// }
result.addInitializerBlock(
CodeBlock.builder()
.beginControlFlow("require(types.size == %L)", typeVariables.size)
.addStatement(
"buildString·{·append(%S).append(%L).append(%S).append(%S).append(%S).append(%L)·}",
"TypeVariable mismatch: Expecting ",
typeVariables.size,
" ${if (typeVariables.size == 1) "type" else "types"} for generic type variables [",
typeVariables.joinToString(", ") { it.name },
"], but received ",
"${typesParam.name}.size"
)
.endControlFlow()
.build()
)
}
// TODO make this configurable. Right now it just matches the source model
if (visibility == KModifier.INTERNAL) {
result.addModifiers(KModifier.INTERNAL)
}
result.primaryConstructor(generateConstructor())
val typeRenderer: TypeRenderer = object : TypeRenderer() {
override fun renderTypeVariable(typeVariable: TypeVariableName): CodeBlock {
val index = typeVariables.indexOfFirst { it == typeVariable }
check(index != -1) { "Unexpected type variable $typeVariable" }
return CodeBlock.of("%N[%L]", typesParam, index)
}
}
result.addProperty(optionsProperty)
for (uniqueAdapter in nonTransientProperties.distinctBy { it.delegateKey }) {
result.addProperty(
uniqueAdapter.delegateKey.generateProperty(
nameAllocator,
typeRenderer,
moshiParam,
uniqueAdapter.name
)
)
}
result.addFunction(generateToStringFun())
result.addFunction(generateFromJsonFun(result))
result.addFunction(generateToJsonFun())
return result.build()
}
private fun generateConstructor(): FunSpec {
val result = FunSpec.constructorBuilder()
result.addParameter(moshiParam)
if (typeVariables.isNotEmpty()) {
result.addParameter(typesParam)
}
return result.build()
}
private fun generateToStringFun(): FunSpec {
val name = originalRawTypeName.simpleNames.joinToString(".")
val size = TO_STRING_SIZE_BASE + name.length
return FunSpec.builder("toString")
.addModifiers(KModifier.OVERRIDE)
.returns(String::class)
.addStatement(
"return %M(%L)·{ append(%S).append(%S).append('%L') }",
MemberName("kotlin.text", "buildString"),
size,
TO_STRING_PREFIX,
name,
")"
)
.build()
}
private fun generateFromJsonFun(classBuilder: TypeSpec.Builder): FunSpec {
val result = FunSpec.builder("fromJson")
.addModifiers(KModifier.OVERRIDE)
.addParameter(readerParam)
.returns(originalTypeName)
for (property in nonTransientProperties) {
result.addCode("%L", property.generateLocalProperty())
if (property.hasLocalIsPresentName) {
result.addCode("%L", property.generateLocalIsPresentProperty())
}
}
val propertiesByIndex = propertyList.asSequence()
.filter { it.hasConstructorParameter }
.associateBy { it.target.parameterIndex }
val components = mutableListOf<FromJsonComponent>()
// Add parameters (± properties) first, their index matters
for ((index, parameter) in targetConstructorParams) {
val property = propertiesByIndex[index]
if (property == null) {
components += ParameterOnly(parameter)
} else {
components += ParameterProperty(parameter, property)
}
}
// Now add the remaining properties that aren't parameters
for (property in propertyList) {
if (property.target.parameterIndex in targetConstructorParams) {
continue // Already handled
}
if (property.isTransient) {
continue // We don't care about these outside of constructor parameters
}
components += PropertyOnly(property)
}
// Calculate how many masks we'll need. Round up if it's not evenly divisible by 32
val propertyCount = targetConstructorParams.size
val maskCount = if (propertyCount == 0) {
0
} else {
(propertyCount + 31) / 32
}
// Allocate mask names
val maskNames = Array(maskCount) { index ->
nameAllocator.newName("mask$index")
}
val maskAllSetValues = Array(maskCount) { -1 }
val useDefaultsConstructor = components.filterIsInstance<ParameterComponent>()
.any { it.parameter.hasDefault }
if (useDefaultsConstructor) {
// Initialize all our masks, defaulting to fully unset (-1)
for (maskName in maskNames) {
result.addStatement("var %L = -1", maskName)
}
}
result.addStatement("%N.beginObject()", readerParam)
result.beginControlFlow("while (%N.hasNext())", readerParam)
result.beginControlFlow("when (%N.selectName(%N))", readerParam, optionsProperty)
// We track property index and mask index separately, because mask index is based on _all_
// constructor arguments, while property index is only based on the index passed into
// JsonReader.Options.
var propertyIndex = 0
val constructorPropertyTypes = mutableListOf<CodeBlock>()
//
// Track important indices for masks. Masks generally increment with each parameter (including
// transient).
//
// Mask name index is an index into the maskNames array we initialized above.
//
// Once the maskIndex reaches 32, we've filled up that mask and have to move to the next mask
// name. Reset the maskIndex relative to here and continue incrementing.
//
var maskIndex = 0
var maskNameIndex = 0
val updateMaskIndexes = {
maskIndex++
if (maskIndex == 32) {
// Move to the next mask
maskIndex = 0
maskNameIndex++
}
}
for (input in components) {
if (input is ParameterOnly ||
(input is ParameterProperty && input.property.isTransient)
) {
updateMaskIndexes()
constructorPropertyTypes += input.type.asTypeBlock()
continue
} else if (input is PropertyOnly && input.property.isTransient) {
continue
}
// We've removed all parameter-only types by this point
val property = (input as PropertyComponent).property
// Proceed as usual
if (property.hasLocalIsPresentName || property.hasConstructorDefault) {
result.beginControlFlow("%L ->", propertyIndex)
if (property.delegateKey.nullable) {
result.addStatement(
"%N = %N.fromJson(%N)",
property.localName,
nameAllocator[property.delegateKey],
readerParam
)
} else {
val exception = unexpectedNull(property, readerParam)
result.addStatement(
"%N = %N.fromJson(%N) ?: throw·%L",
property.localName,
nameAllocator[property.delegateKey],
readerParam,
exception
)
}
if (property.hasConstructorDefault) {
val inverted = (1 shl maskIndex).inv()
if (input is ParameterComponent && input.parameter.hasDefault) {
maskAllSetValues[maskNameIndex] = maskAllSetValues[maskNameIndex] and inverted
}
result.addComment("\$mask = \$mask and (1 shl %L).inv()", maskIndex)
result.addStatement(
"%1L = %1L and 0x%2L.toInt()",
maskNames[maskNameIndex],
Integer.toHexString(inverted)
)
} else {
// Presence tracker for a mutable property
result.addStatement("%N = true", property.localIsPresentName)
}
result.endControlFlow()
} else {
if (property.delegateKey.nullable) {
result.addStatement(
"%L -> %N = %N.fromJson(%N)",
propertyIndex,
property.localName,
nameAllocator[property.delegateKey],
readerParam
)
} else {
val exception = unexpectedNull(property, readerParam)
result.addStatement(
"%L -> %N = %N.fromJson(%N) ?: throw·%L",
propertyIndex,
property.localName,
nameAllocator[property.delegateKey],
readerParam,
exception
)
}
}
if (property.hasConstructorParameter) {
constructorPropertyTypes += property.target.type.asTypeBlock()
}
propertyIndex++
updateMaskIndexes()
}
result.beginControlFlow("-1 ->")
result.addComment("Unknown name, skip it.")
result.addStatement("%N.skipName()", readerParam)
result.addStatement("%N.skipValue()", readerParam)
result.endControlFlow()
result.endControlFlow() // when
result.endControlFlow() // while
result.addStatement("%N.endObject()", readerParam)
var separator = "\n"
val resultName = nameAllocator.newName("result")
val hasNonConstructorProperties = nonTransientProperties.any { !it.hasConstructorParameter }
val returnOrResultAssignment = if (hasNonConstructorProperties) {
// Save the result var for reuse
result.addStatement("val %N: %T", resultName, originalTypeName)
CodeBlock.of("%N = ", resultName)
} else {
CodeBlock.of("return·")
}
// Used to indicate we're in an if-block that's assigning our result value and
// needs to be closed with endControlFlow
var closeNextControlFlowInAssignment = false
if (useDefaultsConstructor) {
// Happy path - all parameters with defaults are set
val allMasksAreSetBlock = maskNames.withIndex()
.map { (index, maskName) ->
CodeBlock.of("$maskName·== 0x${Integer.toHexString(maskAllSetValues[index])}.toInt()")
}
.joinToCode("·&& ")
result.beginControlFlow("if (%L)", allMasksAreSetBlock)
result.addComment("All parameters with defaults are set, invoke the constructor directly")
result.addCode("«%L·%T(", returnOrResultAssignment, originalTypeName)
var localSeparator = "\n"
val paramsToSet = components.filterIsInstance<ParameterProperty>()
.filterNot { it.property.isTransient }
// Set all non-transient property parameters
for (input in paramsToSet) {
result.addCode(localSeparator)
val property = input.property
result.addCode("%N = %N", property.name, property.localName)
if (property.isRequired) {
result.addMissingPropertyCheck(property, readerParam)
} else if (!input.type.isNullable) {
// Unfortunately incurs an intrinsic null-check even though we know it's set, but
// maybe in the future we can use contracts to omit them.
result.addCode("·as·%T", input.type)
}
localSeparator = ",\n"
}
result.addCode("\n»)\n")
result.nextControlFlow("else")
closeNextControlFlowInAssignment = true
classBuilder.addProperty(constructorProperty)
result.addComment("Reflectively invoke the synthetic defaults constructor")
// Dynamic default constructor call
val nonNullConstructorType = constructorProperty.type.copy(nullable = false)
val args = constructorPropertyTypes
.plus(0.until(maskCount).map { INT_TYPE_BLOCK }) // Masks, one every 32 params
.plus(DEFAULT_CONSTRUCTOR_MARKER_TYPE_BLOCK) // Default constructor marker is always last
.joinToCode(", ")
val coreLookupBlock = CodeBlock.of(
"%T::class.java.getDeclaredConstructor(%L)",
originalRawTypeName,
args
)
val lookupBlock = if (originalTypeName is ParameterizedTypeName) {
CodeBlock.of("(%L·as·%T)", coreLookupBlock, nonNullConstructorType)
} else {
coreLookupBlock
}
val initializerBlock = CodeBlock.of(
"this.%1N·?: %2L.also·{ this.%1N·= it }",
constructorProperty,
lookupBlock
)
val localConstructorProperty = PropertySpec.builder(
nameAllocator.newName("localConstructor"),
nonNullConstructorType
)
.addAnnotation(
AnnotationSpec.builder(Suppress::class)
.addMember("%S", "UNCHECKED_CAST")
.build()
)
.initializer(initializerBlock)
.build()
result.addCode("%L", localConstructorProperty)
result.addCode(
"«%L%N.newInstance(",
returnOrResultAssignment,
localConstructorProperty
)
} else {
// Standard constructor call. Don't omit generics for parameterized types even if they can be
// inferred, as calculating the right condition for inference exceeds the value gained from
// being less pedantic.
result.addCode("«%L%T(", returnOrResultAssignment, originalTypeName)
}
for (input in components.filterIsInstance<ParameterComponent>()) {
result.addCode(separator)
if (useDefaultsConstructor) {
if (input is ParameterOnly || (input is ParameterProperty && input.property.isTransient)) {
// We have to use the default primitive for the available type in order for
// invokeDefaultConstructor to properly invoke it. Just using "null" isn't safe because
// the transient type may be a primitive type.
// Inline a little comment for readability indicating which parameter is it's referring to
result.addCode(
"/*·%L·*/·%L",
input.parameter.name,
input.type.rawType().defaultPrimitiveValue()
)
} else {
result.addCode("%N", (input as ParameterProperty).property.localName)
}
} else if (input !is ParameterOnly) {
val property = (input as ParameterProperty).property
result.addCode("%N = %N", property.name, property.localName)
}
if (input is PropertyComponent) {
val property = input.property
if (!property.isTransient && property.isRequired) {
result.addMissingPropertyCheck(property, readerParam)
}
}
separator = ",\n"
}
if (useDefaultsConstructor) {
// Add the masks and a null instance for the trailing default marker instance
result.addCode(",\n%L,\n/*·DefaultConstructorMarker·*/·null", maskNames.map { CodeBlock.of("%L", it) }.joinToCode(", "))
}
result.addCode("\n»)\n")
// Close the result assignment control flow, if any
if (closeNextControlFlowInAssignment) {
result.endControlFlow()
}
// Assign properties not present in the constructor.
for (property in nonTransientProperties) {
if (property.hasConstructorParameter) {
continue // Property already handled.
}
if (property.hasLocalIsPresentName) {
result.beginControlFlow("if (%N)", property.localIsPresentName)
result.addStatement(
"%N.%N = %N",
resultName,
property.name,
property.localName
)
result.endControlFlow()
} else {
result.addStatement(
"%1N.%2N = %3N ?: %1N.%2N",
resultName,
property.name,
property.localName
)
}
}
if (hasNonConstructorProperties) {
result.addStatement("return·%1N", resultName)
}
return result.build()
}
private fun unexpectedNull(property: PropertyGenerator, reader: ParameterSpec): CodeBlock {
return CodeBlock.of(
"%M(%S, %S, %N)",
MemberName(MOSHI_UTIL_PACKAGE, "unexpectedNull"),
property.localName,
property.jsonName,
reader
)
}
private fun generateToJsonFun(): FunSpec {
val result = FunSpec.builder("toJson")
.addModifiers(KModifier.OVERRIDE)
.addParameter(writerParam)
.addParameter(valueParam)
result.beginControlFlow("if (%N == null)", valueParam)
result.addStatement(
"throw·%T(%S)",
NullPointerException::class,
"${valueParam.name} was null! Wrap in .nullSafe() to write nullable values."
)
result.endControlFlow()
result.addStatement("%N.beginObject()", writerParam)
nonTransientProperties.forEach { property ->
// We manually put in quotes because we know the jsonName is already escaped
result.addStatement("%N.name(%S)", writerParam, property.jsonName)
result.addStatement(
"%N.toJson(%N, %N.%N)",
nameAllocator[property.delegateKey],
writerParam,
valueParam,
property.name
)
}
result.addStatement("%N.endObject()", writerParam)
return result.build()
}
}
private fun FunSpec.Builder.addMissingPropertyCheck(property: PropertyGenerator, readerParam: ParameterSpec) {
val missingPropertyBlock =
CodeBlock.of(
"%M(%S, %S, %N)",
MemberName(MOSHI_UTIL_PACKAGE, "missingProperty"),
property.localName,
property.jsonName,
readerParam
)
addCode(" ?: throw·%L", missingPropertyBlock)
}
/** Represents a prepared adapter with its [spec] and optional associated [proguardConfig]. */
@InternalMoshiCodegenApi
public data class PreparedAdapter(val spec: FileSpec, val proguardConfig: ProguardConfig?)
private fun AsmType.toReflectionString(): String {
return when (this) {
AsmType.VOID_TYPE -> "void"
AsmType.BOOLEAN_TYPE -> "boolean"
AsmType.CHAR_TYPE -> "char"
AsmType.BYTE_TYPE -> "byte"
AsmType.SHORT_TYPE -> "short"
AsmType.INT_TYPE -> "int"
AsmType.FLOAT_TYPE -> "float"
AsmType.LONG_TYPE -> "long"
AsmType.DOUBLE_TYPE -> "double"
else -> when (sort) {
AsmType.ARRAY -> "${elementType.toReflectionString()}[]"
// Object type
else -> className
}
}
}
private interface PropertyComponent {
val property: PropertyGenerator
val type: TypeName
}
private interface ParameterComponent {
val parameter: TargetParameter
val type: TypeName
}
/**
* Type hierarchy for describing fromJson() components. Specifically - parameters, properties, and
* parameter properties. All three of these scenarios participate in fromJson() parsing.
*/
private sealed class FromJsonComponent {
abstract val type: TypeName
data class ParameterOnly(
override val parameter: TargetParameter
) : FromJsonComponent(), ParameterComponent {
override val type: TypeName = parameter.type
}
data class PropertyOnly(
override val property: PropertyGenerator
) : FromJsonComponent(), PropertyComponent {
override val type: TypeName = property.target.type
}
data class ParameterProperty(
override val parameter: TargetParameter,
override val property: PropertyGenerator
) : FromJsonComponent(), ParameterComponent, PropertyComponent {
override val type: TypeName = parameter.type
}
}
| apache-2.0 | 6bfd66e493b7116bbf4f4c8d42e5d2e5 | 35.346701 | 133 | 0.673014 | 4.634774 | false | false | false | false |
squark-io/yggdrasil | yggdrasil-maven-plugin/src/main/kotlin/io/squark/yggdrasil/maven/YggdrasilMojo.kt | 1 | 12565 | package io.squark.yggdrasil.maven
import org.apache.commons.io.IOUtils
import org.apache.maven.RepositoryUtils
import org.apache.maven.plugin.AbstractMojo
import org.apache.maven.plugin.MojoExecutionException
import org.apache.maven.plugin.MojoFailureException
import org.apache.maven.plugin.descriptor.PluginDescriptor
import org.apache.maven.plugins.annotations.Component
import org.apache.maven.plugins.annotations.LifecyclePhase
import org.apache.maven.plugins.annotations.Mojo
import org.apache.maven.plugins.annotations.Parameter
import org.apache.maven.plugins.annotations.ResolutionScope
import org.apache.maven.project.DefaultDependencyResolutionRequest
import org.apache.maven.project.MavenProject
import org.apache.maven.project.MavenProjectHelper
import org.apache.maven.project.ProjectDependenciesResolver
import org.eclipse.aether.RepositorySystem
import org.eclipse.aether.RepositorySystemSession
import org.eclipse.aether.collection.CollectRequest
import org.eclipse.aether.graph.Dependency
import org.eclipse.aether.graph.DependencyNode
import org.eclipse.aether.resolution.DependencyRequest
import org.eclipse.aether.util.artifact.JavaScopes
import org.eclipse.aether.util.filter.ScopeDependencyFilter
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.nio.file.Files
import java.nio.file.attribute.BasicFileAttributes
import java.util.jar.Attributes
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import java.util.jar.Manifest
/**
* Yggdrasil Maven Plugin
*
* Plugin for creating Yggdrasil applications conforming to the microprofile.io standard
* @see <a href="http://microprofile.io">microprofile.io</a>
*
* Created by Erik Håkansson on 2017-03-25.
* Copyright 2017
*
*/
@Mojo(name = "yggdrasil", requiresDependencyResolution = ResolutionScope.COMPILE, defaultPhase = LifecyclePhase.PACKAGE)
class YggdrasilMojo : AbstractMojo() {
/**
* The MavenProject object.
* @parameter expression="${project}"
* *
* @readonly
*/
@Parameter(defaultValue = "\${project}", readonly = true, required = true)
private lateinit var project: MavenProject
@Parameter(defaultValue = "\${plugin}", readonly = true) // Maven 3 only
private lateinit var plugin: PluginDescriptor
@Component
private lateinit var dependenciesResolver: ProjectDependenciesResolver
@Component
private lateinit var repositorySystem: RepositorySystem
@Parameter(defaultValue = "\${repositorySystemSession}", readonly = true, required = true)
private lateinit var repositorySystemSession: RepositorySystemSession
@Component
private lateinit var mavenProjectHelper: MavenProjectHelper
private var classesDir: File? = null
private val addedResources = mutableListOf<String>()
private val addedDeps = mutableMapOf<InternalDependencyCoordinate, Dependency>()
private val EMPTY_BEANS_XML = "META-INF/standins/empty-beans.xml"
private val BEANS_XML = "META-INF/beans.xml"
private val YGGDRASIL_LIBS_PATH = "META-INF/libs/"
private val YGGDRASIL_MAIN_CLASS = "io.squark.yggdrasil.bootstrap.Yggdrasil"
private val DELEGATED_MAIN_CLASS = "Delegated-Main-Class"
/**
* Performs packaging of the Yggdrasil jar
*
* @throws MojoExecutionException if an unexpected problem occurs.
* Throwing this exception causes a "BUILD ERROR" message to be displayed.
* @throws MojoFailureException if an expected problem (such as a compilation failure) occurs.
* Throwing this exception causes a "BUILD FAILURE" message to be displayed.
*/
override fun execute() {
classesDir = File(project.build.outputDirectory)
val manifest = generateAndReturnManifest()
addedResources += JarFile.MANIFEST_NAME
val targetFile = File(project.build.directory, getTargetJarName())
val targetJar = createTargetJar(targetFile, manifest)
log.info("Building jar: ${targetFile.absolutePath}")
targetJar.use {
addFile(classesDir!!, null, it)
val beansXML = File(classesDir, BEANS_XML)
if (!beansXML.exists()) {
addBeansXml(it)
}
addYggdrasilDependencies(it)
addDependencies(it)
}
targetJar.close()
mavenProjectHelper.attachArtifact(project, project.artifact.type, "yggdrasil", targetFile)
log.info("Built jar: ${targetFile.absolutePath}")
}
private fun addYggdrasilDependencies(jarOutputStream: JarOutputStream) {
val yggdrasilArtifacts = plugin.artifacts.filter { it.groupId == "io.squark.yggdrasil" }.associateBy { it.artifactId }
val bootstrapDependency = RepositoryUtils.toDependency(yggdrasilArtifacts["yggdrasil-bootstrap"]!!, null)
val coreDependency = RepositoryUtils.toDependency(yggdrasilArtifacts["yggdrasil-core"]!!, null)
val collectRequest = CollectRequest(listOf(bootstrapDependency, coreDependency), null,
project.remoteProjectRepositories)
val result = repositorySystem.resolveDependencies(repositorySystemSession,
DependencyRequest(collectRequest, ScopeDependencyFilter(listOf(JavaScopes.COMPILE), null)))
val bootstrapNode = result.root.children.filter { it.artifact.artifactId == "yggdrasil-bootstrap" }.first()
val bootstrapDeps = listOf(bootstrapNode.dependency) + getDependencyChildren(bootstrapNode)
bootstrapDeps.forEach {
addedDeps.put(InternalDependencyCoordinate(it.artifact.groupId, it.artifact.artifactId, it.artifact.classifier,
it.artifact.extension), it)
if (it.artifact.file == null || !it.artifact.file.exists()) {
throw MojoExecutionException("Couldn't find artifact file for ${it.artifact}")
}
val jarFile = JarFile(it.artifact.file)
explodeJar(jarFile, jarOutputStream)
}
val coreNode = result.root.children.filter { it.artifact.artifactId == "yggdrasil-core" }.first()
addFile(coreNode.artifact.file, null, jarOutputStream, YGGDRASIL_LIBS_PATH)
addedDeps.put(InternalDependencyCoordinate(coreNode.artifact.groupId, coreNode.artifact.artifactId,
coreNode.artifact.classifier, coreNode.artifact.extension), coreNode.dependency)
addDependencyGraph(coreNode, jarOutputStream)
}
private fun explodeJar(jarFile: JarFile, jarOutputStream: JarOutputStream) {
jarFile.entries().iterator().forEachRemaining {
log.debug("Writing ${it.name}")
if (!it.isDirectory) {
if (addedResources.contains(it.name)) {
log.debug("$it.name already written. Skipping.")
} else {
addedResources += it.name
jarOutputStream.putNextEntry(it)
val jarInputStream = jarFile.getInputStream(it)
val buffer = ByteArray(2048)
var len = jarInputStream.read(buffer)
while (len > 0) {
jarOutputStream.write(buffer, 0, len)
len = jarInputStream.read(buffer)
}
jarOutputStream.closeEntry()
}
}
}
}
private fun addDependencies(jarOutputStream: JarOutputStream) {
val resolutionRequest = DefaultDependencyResolutionRequest(project, repositorySystemSession)
val result = dependenciesResolver.resolve(resolutionRequest)
if (result.collectionErrors.size > 0) {
throw MojoFailureException(
"Failed to resolve some dependencies: \n${result.collectionErrors.joinToString(separator = "\n")}")
}
addDependencyGraph(result.dependencyGraph, jarOutputStream)
}
private fun addDependencyGraph(dependencyGraph: DependencyNode,
jarOutputStream: JarOutputStream) {
val flatList = getDependencyChildren(dependencyGraph)
val addedPlusNew = addedDeps.values + flatList
val duplicates = getDependencyDuplicates(addedPlusNew)
duplicates.forEach {
val versions = it.value.joinToString(transform = { it.artifact.version })
log.warn(
"Found differing dependency versions for \"${it.key}\". Will use the first one found. Versions: $versions")
}
flatList.forEach {
val coordinate = InternalDependencyCoordinate(it.artifact.groupId, it.artifact.artifactId, it.artifact.classifier,
it.artifact.extension)
if (!addedDeps.keys.contains(coordinate)) {
if (it.artifact.file == null) {
throw MojoFailureException("Failed to resolve dependency $it")
}
addFile(it.artifact.file, null, jarOutputStream, YGGDRASIL_LIBS_PATH)
addedDeps.put(coordinate, it)
}
}
}
private fun getDependencyDuplicates(flatList: List<Dependency>): Map<InternalDependencyCoordinate, List<Dependency>> {
val grouped = flatList.groupBy {
InternalDependencyCoordinate(it.artifact.groupId, it.artifact.artifactId, it.artifact.classifier,
it.artifact.extension)
}
return grouped.filterValues { deps ->
deps.size > 1 && deps.any { it.artifact.version != deps[0].artifact.version }
}
}
private fun getDependencyChildren(dependencyNode: DependencyNode): List<Dependency> {
val flatList = dependencyNode.children.map { it.dependency }.filter { it.scope == JavaScopes.COMPILE }.toMutableList()
dependencyNode.children.forEach { flatList.addAll(getDependencyChildren(it)) }
return flatList
}
private fun addBeansXml(jarOutputStream: JarOutputStream) {
val standin = this::class.java.classLoader.getResourceAsStream(EMPTY_BEANS_XML)
val jarEntry = JarEntry(BEANS_XML)
log.debug("Writing ${jarEntry.name}")
jarOutputStream.putNextEntry(jarEntry)
IOUtils.copy(standin, jarOutputStream)
jarOutputStream.closeEntry()
}
private fun addFile(file: File, prefix: String?, jarOutputStream: JarOutputStream, targetPath: String? = null) {
if (file.isDirectory) {
file.listFiles().forEach { addFile(it, prefix, jarOutputStream) }
} else {
addEntry(file, prefix, jarOutputStream, targetPath)
}
}
private fun addEntry(file: File, prefix: String?, jarOutputStream: JarOutputStream, targetPath: String?) {
val name = if (targetPath == null) {
"${prefix ?: ""}${classesDir!!.toPath().relativize(file.toPath())}"
} else {
var slash = ""
if (!targetPath.endsWith('/')) slash = "/"
"${prefix ?: ""}$targetPath$slash${file.toPath().fileName}"
}
log.debug("Writing $name")
if (addedResources.contains(name)) {
log.debug("$name already written. Skipping.")
return
}
addedResources += name
val jarEntry = JarEntry(name)
val attributes = Files.readAttributes(file.toPath(), BasicFileAttributes::class.java)
jarEntry.let {
it.creationTime = attributes.creationTime()
it.lastAccessTime = attributes.lastAccessTime()
it.lastModifiedTime = attributes.lastModifiedTime()
}
jarOutputStream.putNextEntry(jarEntry)
IOUtils.copy(file.inputStream(), jarOutputStream)
jarOutputStream.closeEntry()
}
private fun getTargetJarName(): String {
return project.artifactId + "-" + project.version + "-yggdrasil." + project.packaging
}
@Throws(IOException::class)
private fun createTargetJar(targetFile: File, manifest: Manifest): JarOutputStream {
return JarOutputStream(FileOutputStream(targetFile), manifest)
}
@Throws(MojoExecutionException::class)
private fun generateAndReturnManifest(): Manifest {
val manifestFile = File(project.build.outputDirectory, JarFile.MANIFEST_NAME)
val manifest: Manifest
if (manifestFile.exists()) {
try {
val fileInputStream = FileInputStream(manifestFile)
manifest = Manifest(fileInputStream)
fileInputStream.close()
} catch (e: IOException) {
log.error(e)
throw MojoExecutionException(e.message)
}
if (manifest.mainAttributes[Attributes.Name.MAIN_CLASS] != null) {
manifest.mainAttributes.putValue(DELEGATED_MAIN_CLASS,
manifest.mainAttributes[Attributes.Name.MAIN_CLASS].toString())
}
} else {
manifest = Manifest()
}
if (!manifest.mainAttributes.containsKey(Attributes.Name.MANIFEST_VERSION.toString())) {
manifest.mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0")
}
if (!manifest.mainAttributes.containsKey("Build-Jdk")) {
manifest.mainAttributes.put(Attributes.Name("Build-Jdk"), System.getProperty("java.version"))
}
manifest.mainAttributes.put(Attributes.Name.MAIN_CLASS, YGGDRASIL_MAIN_CLASS)
return manifest
}
private data class InternalDependencyCoordinate(val groupId: String, val artifactId: String, val classifier: String,
val type: String)
}
| apache-2.0 | 4a6f0b8c85d23571935db69ae371f265 | 41.161074 | 122 | 0.730739 | 4.436441 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/ui/MainActivity.kt | 1 | 60986 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui
import android.Manifest
import android.app.PendingIntent
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.content.res.ColorStateList
import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.graphics.drawable.Icon
import android.location.LocationManager
import android.nfc.NfcAdapter
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.speech.SpeechRecognizer
import android.text.SpannableStringBuilder
import android.text.style.RelativeSizeSpan
import android.util.Base64
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import androidx.core.graphics.drawable.DrawableCompat
import androidx.core.graphics.drawable.toDrawable
import androidx.core.location.LocationManagerCompat
import androidx.core.text.inSpans
import androidx.core.view.GravityCompat
import androidx.core.view.forEach
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.ContentLoadingProgressBar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.navigation.NavigationView
import com.google.android.material.snackbar.Snackbar
import java.nio.charset.Charset
import java.util.concurrent.CancellationException
import javax.jmdns.ServiceInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import okhttp3.Request
import org.openhab.habdroid.BuildConfig
import org.openhab.habdroid.R
import org.openhab.habdroid.background.BackgroundTasksManager
import org.openhab.habdroid.background.EventListenerService
import org.openhab.habdroid.background.NotificationUpdateObserver
import org.openhab.habdroid.core.CloudMessagingHelper
import org.openhab.habdroid.core.OpenHabApplication
import org.openhab.habdroid.core.UpdateBroadcastReceiver
import org.openhab.habdroid.core.connection.CloudConnection
import org.openhab.habdroid.core.connection.Connection
import org.openhab.habdroid.core.connection.ConnectionFactory
import org.openhab.habdroid.core.connection.ConnectionNotInitializedException
import org.openhab.habdroid.core.connection.DemoConnection
import org.openhab.habdroid.core.connection.NetworkNotAvailableException
import org.openhab.habdroid.core.connection.NoUrlInformationException
import org.openhab.habdroid.core.connection.WrongWifiException
import org.openhab.habdroid.model.LinkedPage
import org.openhab.habdroid.model.ServerConfiguration
import org.openhab.habdroid.model.ServerProperties
import org.openhab.habdroid.model.Sitemap
import org.openhab.habdroid.model.WebViewUi
import org.openhab.habdroid.model.sortedWithDefaultName
import org.openhab.habdroid.model.toTagData
import org.openhab.habdroid.ui.activity.ContentController
import org.openhab.habdroid.ui.homescreenwidget.ItemUpdateWidget
import org.openhab.habdroid.ui.homescreenwidget.VoiceWidget
import org.openhab.habdroid.ui.homescreenwidget.VoiceWidgetWithIcon
import org.openhab.habdroid.ui.preference.toItemUpdatePrefValue
import org.openhab.habdroid.ui.widget.LockableDrawerLayout
import org.openhab.habdroid.util.AsyncServiceResolver
import org.openhab.habdroid.util.CrashReportingHelper
import org.openhab.habdroid.util.HttpClient
import org.openhab.habdroid.util.ImageConversionPolicy
import org.openhab.habdroid.util.PendingIntent_Immutable
import org.openhab.habdroid.util.PrefKeys
import org.openhab.habdroid.util.ScreenLockMode
import org.openhab.habdroid.util.Util
import org.openhab.habdroid.util.addToPrefs
import org.openhab.habdroid.util.areSitemapsShownInDrawer
import org.openhab.habdroid.util.determineDataUsagePolicy
import org.openhab.habdroid.util.getActiveServerId
import org.openhab.habdroid.util.getConfiguredServerIds
import org.openhab.habdroid.util.getCurrentWifiSsid
import org.openhab.habdroid.util.getDefaultSitemap
import org.openhab.habdroid.util.getGroupItems
import org.openhab.habdroid.util.getHumanReadableErrorMessage
import org.openhab.habdroid.util.getPrefs
import org.openhab.habdroid.util.getPrimaryServerId
import org.openhab.habdroid.util.getRemoteUrl
import org.openhab.habdroid.util.getSecretPrefs
import org.openhab.habdroid.util.getStringOrNull
import org.openhab.habdroid.util.getWifiManager
import org.openhab.habdroid.util.hasPermissions
import org.openhab.habdroid.util.isDebugModeEnabled
import org.openhab.habdroid.util.isEventListenerEnabled
import org.openhab.habdroid.util.isScreenTimerDisabled
import org.openhab.habdroid.util.openInAppStore
import org.openhab.habdroid.util.putActiveServerId
import org.openhab.habdroid.util.updateDefaultSitemap
class MainActivity : AbstractBaseActivity(), ConnectionFactory.UpdateListener {
private lateinit var prefs: SharedPreferences
private var serviceResolveJob: Job? = null
private lateinit var drawerLayout: LockableDrawerLayout
private lateinit var drawerToggle: ActionBarDrawerToggle
private lateinit var drawerMenu: Menu
private lateinit var drawerModeSelectorContainer: View
private lateinit var drawerModeToggle: ImageView
private lateinit var drawerServerNameView: TextView
private var drawerIconTintList: ColorStateList? = null
lateinit var viewPool: RecyclerView.RecycledViewPool
private set
private var progressBar: ContentLoadingProgressBar? = null
private var sitemapSelectionDialog: AlertDialog? = null
var connection: Connection? = null
private set
private var pendingAction: PendingAction? = null
private lateinit var controller: ContentController
var serverProperties: ServerProperties? = null
private set
private var propsUpdateHandle: ServerProperties.Companion.UpdateHandle? = null
private var retryJob: Job? = null
private var isStarted: Boolean = false
private var shortcutManager: ShortcutManager? = null
private val backgroundTasksManager = BackgroundTasksManager()
private var inServerSelectionMode = false
private var wifiSsidDuringLastOnStart: String? = null
private val preferenceActivityCallback =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
CrashReportingHelper.d(TAG, "preferenceActivityCallback: $result")
val data = result.data ?: return@registerForActivityResult
if (data.getBooleanExtra(PreferencesActivity.RESULT_EXTRA_SITEMAP_CLEARED, false)) {
updateSitemapDrawerEntries()
executeOrStoreAction(PendingAction.ChooseSitemap())
}
if (data.getBooleanExtra(PreferencesActivity.RESULT_EXTRA_SITEMAP_DRAWER_CHANGED, false)) {
updateSitemapDrawerEntries()
}
if (data.getBooleanExtra(PreferencesActivity.RESULT_EXTRA_THEME_CHANGED, false)) {
recreate()
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
CrashReportingHelper.d(TAG, "onNewIntent()")
processIntent(intent)
}
override fun onCreate(savedInstanceState: Bundle?) {
CrashReportingHelper.d(TAG, "onCreate()")
prefs = getPrefs()
// Disable screen timeout if set in preferences
if (prefs.isScreenTimerDisabled()) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
super.onCreate(savedInstanceState)
val controllerClassName = resources.getString(R.string.controller_class)
try {
val controllerClass = Class.forName(controllerClassName)
val constructor = controllerClass.getConstructor(MainActivity::class.java)
controller = constructor.newInstance(this) as ContentController
} catch (e: Exception) {
Log.wtf(TAG, "Could not instantiate activity controller class '$controllerClassName'")
throw RuntimeException(e)
}
setContentView(R.layout.activity_main)
// inflate the controller dependent content view
controller.inflateViews(findViewById(R.id.content_stub))
setupToolbar()
setupDrawer()
viewPool = RecyclerView.RecycledViewPool()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
shortcutManager = getSystemService(ShortcutManager::class.java)
}
// Check if we have openHAB page url in saved instance state?
if (savedInstanceState != null) {
serverProperties = savedInstanceState.getParcelable(STATE_KEY_SERVER_PROPERTIES)
val lastConnectionHash = savedInstanceState.getInt(STATE_KEY_CONNECTION_HASH)
if (lastConnectionHash != -1) {
val c = ConnectionFactory.activeUsableConnection?.connection
if (c != null && c.hashCode() == lastConnectionHash) {
connection = c
}
}
controller.onRestoreInstanceState(savedInstanceState)
val lastControllerClass = savedInstanceState.getString(STATE_KEY_CONTROLLER_NAME)
if (controller.javaClass.canonicalName != lastControllerClass) {
// Our controller type changed, so we need to make the new controller aware of the
// page hierarchy. If the controller didn't change, the hierarchy will be restored
// via the fragment state restoration.
controller.recreateFragmentState()
}
if (savedInstanceState.getBoolean(STATE_KEY_SITEMAP_SELECTION_SHOWN)) {
showSitemapSelectionDialog()
}
updateSitemapDrawerEntries()
}
processIntent(intent)
if (prefs.getBoolean(PrefKeys.FIRST_START, true) ||
prefs.getBoolean(PrefKeys.RECENTLY_RESTORED, false)
) {
NotificationUpdateObserver.createNotificationChannels(this)
Log.d(TAG, "Start intro")
val intent = Intent(this, IntroActivity::class.java)
startActivity(intent)
}
UpdateBroadcastReceiver.updateComparableVersion(prefs.edit())
val isSpeechRecognizerAvailable = SpeechRecognizer.isRecognitionAvailable(this)
launch {
showPushNotificationWarningIfNeeded()
manageVoiceRecognitionShortcut(isSpeechRecognizerAvailable)
setVoiceWidgetComponentEnabledSetting(VoiceWidget::class.java, isSpeechRecognizerAvailable)
setVoiceWidgetComponentEnabledSetting(VoiceWidgetWithIcon::class.java, isSpeechRecognizerAvailable)
}
EventListenerService.startOrStopService(this)
ItemUpdateWidget.updateAllWidgets(this)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
CrashReportingHelper.d(TAG, "onPostCreate()")
super.onPostCreate(savedInstanceState)
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState()
}
override fun onConfigurationChanged(newConfig: Configuration) {
CrashReportingHelper.d(TAG, "onConfigurationChanged()")
super.onConfigurationChanged(newConfig)
drawerToggle.onConfigurationChanged(newConfig)
}
override fun onStart() {
CrashReportingHelper.d(TAG, "onStart()")
super.onStart()
isStarted = true
ConnectionFactory.addListener(this)
updateDrawerServerEntries()
onActiveConnectionChanged()
if (connection != null && serverProperties == null) {
controller.clearServerCommunicationFailure()
queryServerProperties()
}
val currentWifiSsid = getCurrentWifiSsid(OpenHabApplication.DATA_ACCESS_TAG_SELECT_SERVER_WIFI)
val switchToServer = determineServerIdToSwitchToBasedOnWifi(currentWifiSsid, wifiSsidDuringLastOnStart)
wifiSsidDuringLastOnStart = currentWifiSsid
if (pendingAction == null && switchToServer != -1) {
switchServerBasedOnWifi(switchToServer)
}
handlePendingAction()
}
public override fun onStop() {
CrashReportingHelper.d(TAG, "onStop()")
isStarted = false
super.onStop()
ConnectionFactory.removeListener(this)
serviceResolveJob?.cancel()
serviceResolveJob = null
if (sitemapSelectionDialog?.isShowing == true) {
sitemapSelectionDialog?.dismiss()
}
propsUpdateHandle?.cancel()
}
override fun onResume() {
CrashReportingHelper.d(TAG, "onResume()")
super.onResume()
val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
if (nfcAdapter != null) {
val intent = Intent(this, javaClass)
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
val pi = PendingIntent.getActivity(this, 0, intent, PendingIntent_Immutable)
nfcAdapter.enableForegroundDispatch(this, pi, null, null)
}
updateTitle()
showMissingPermissionsWarningIfNeeded()
val intentFilter = BackgroundTasksManager.getIntentFilterForForeground(this)
if (intentFilter.countActions() != 0 && !prefs.isEventListenerEnabled()) {
registerReceiver(backgroundTasksManager, intentFilter)
}
showDataSaverHintSnackbarIfNeeded()
}
override fun onPause() {
CrashReportingHelper.d(TAG, "onPause()")
super.onPause()
retryJob?.cancel(CancellationException("onPause() was called"))
val nfcAdapter = NfcAdapter.getDefaultAdapter(this)
try {
nfcAdapter?.disableForegroundDispatch(this)
} catch (e: IllegalStateException) {
// See #1776
}
try {
unregisterReceiver(backgroundTasksManager)
} catch (e: IllegalArgumentException) {
// Receiver isn't registered
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
CrashReportingHelper.d(TAG, "onCreateOptionsMenu()")
val inflater = menuInflater
inflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
CrashReportingHelper.d(TAG, "onPrepareOptionsMenu()")
menu.findItem(R.id.mainmenu_voice_recognition).isVisible =
connection != null && SpeechRecognizer.isRecognitionAvailable(this)
menu.findItem(R.id.mainmenu_crash).isVisible = BuildConfig.DEBUG
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
CrashReportingHelper.d(TAG, "onOptionsItemSelected()")
// Handle back navigation arrow
if (item.itemId == android.R.id.home && controller.canGoBack()) {
controller.goBack()
return true
}
// Handle hamburger menu
if (drawerToggle.onOptionsItemSelected(item)) {
return true
}
// Handle menu items
return when (item.itemId) {
R.id.mainmenu_voice_recognition -> {
launchVoiceRecognition()
true
}
R.id.mainmenu_crash -> {
throw Exception("Crash menu item pressed")
}
else -> super.onOptionsItemSelected(item)
}
}
public override fun onSaveInstanceState(savedInstanceState: Bundle) {
CrashReportingHelper.d(TAG, "onSaveInstanceState()")
isStarted = false
with(savedInstanceState) {
putParcelable(STATE_KEY_SERVER_PROPERTIES, serverProperties)
putBoolean(STATE_KEY_SITEMAP_SELECTION_SHOWN, sitemapSelectionDialog?.isShowing == true)
putString(STATE_KEY_CONTROLLER_NAME, controller.javaClass.canonicalName)
putInt(STATE_KEY_CONNECTION_HASH, connection?.hashCode() ?: -1)
controller.onSaveInstanceState(this)
}
super.onSaveInstanceState(savedInstanceState)
}
override fun onBackPressed() {
CrashReportingHelper.d(TAG, "onBackPressed()")
when {
drawerLayout.isDrawerOpen(findViewById<NavigationView>(R.id.left_drawer)) -> drawerLayout.closeDrawers()
controller.canGoBack() -> controller.goBack()
isFullscreenEnabled -> when {
lastSnackbar?.isShown != true ->
showSnackbar(
SNACKBAR_TAG_PRESS_AGAIN_EXIT,
R.string.press_back_to_exit
)
lastSnackbar?.view?.tag?.toString() == SNACKBAR_TAG_PRESS_AGAIN_EXIT -> super.onBackPressed()
else -> showSnackbar(
SNACKBAR_TAG_PRESS_AGAIN_EXIT,
R.string.press_back_to_exit
)
}
else -> super.onBackPressed()
}
}
override fun onActiveConnectionChanged() {
CrashReportingHelper.d(TAG, "onActiveConnectionChanged()")
val result = ConnectionFactory.activeUsableConnection
val newConnection = result?.connection
val failureReason = result?.failureReason
if (ConnectionFactory.activeCloudConnection?.connection != null) {
manageNotificationShortcut(true)
}
if (newConnection != null && newConnection === connection) {
updateDrawerItemVisibility()
return
}
retryJob?.cancel(CancellationException("onAvailableConnectionChanged() was called"))
connection = newConnection
hideSnackbar(SNACKBAR_TAG_CONNECTION_ESTABLISHED)
hideSnackbar(SNACKBAR_TAG_SSE_ERROR)
hideSnackbar(SNACKBAR_TAG_DEMO_MODE_ACTIVE)
serverProperties = null
handlePendingAction()
val wifiManager = getWifiManager(OpenHabApplication.DATA_ACCESS_TAG_SUGGEST_TURN_ON_WIFI)
when {
newConnection != null -> {
handleConnectionChange()
controller.updateConnection(newConnection, null, 0)
}
failureReason is WrongWifiException -> {
val activeConfig = ServerConfiguration.load(prefs, getSecretPrefs(), prefs.getActiveServerId())
val ssids = activeConfig?.wifiSsids?.joinToString(", ")
controller.indicateWrongWifi(getString(R.string.error_wifi_restricted, activeConfig?.name, ssids))
}
failureReason is NoUrlInformationException -> {
// Attempt resolving only if we're connected locally and
// no local connection is configured yet
if (failureReason.wouldHaveUsedLocalConnection() && ConnectionFactory.activeLocalConnection == null) {
if (serviceResolveJob == null) {
val resolver = AsyncServiceResolver(
this,
AsyncServiceResolver.OPENHAB_SERVICE_TYPE,
this
)
serviceResolveJob = launch {
handleServiceResolveResult(resolver.resolve())
serviceResolveJob = null
}
controller.updateConnection(null,
getString(R.string.resolving_openhab),
R.drawable.ic_home_search_outline_grey_340dp)
}
} else {
val officialServer = !failureReason.wouldHaveUsedLocalConnection() &&
prefs.getRemoteUrl().matches("^(home.)?myopenhab.org$".toRegex())
controller.indicateMissingConfiguration(false, officialServer)
}
}
failureReason is NetworkNotAvailableException && !wifiManager.isWifiEnabled -> {
controller.indicateNoNetwork(getString(R.string.error_wifi_not_available), true)
}
failureReason is ConnectionNotInitializedException -> {
controller.updateConnection(null, null, 0)
}
else -> {
controller.indicateNoNetwork(getString(R.string.error_network_not_available), false)
scheduleRetry {
ConnectionFactory.restartNetworkCheck()
recreate()
}
}
}
viewPool.clear()
updateSitemapDrawerEntries()
updateDrawerItemVisibility()
updateDrawerServerEntries()
invalidateOptionsMenu()
updateTitle()
}
fun scheduleRetry(runAfterDelay: () -> Unit) {
retryJob?.cancel(CancellationException("scheduleRetry() was called"))
retryJob = CoroutineScope(Dispatchers.Main + Job()).launch {
delay(30000)
Log.d(TAG, "runAfterDelay()")
runAfterDelay()
}
}
override fun onPrimaryConnectionChanged() {
// no-op
}
override fun onActiveCloudConnectionChanged(connection: CloudConnection?) {
CrashReportingHelper.d(TAG, "onActiveCloudConnectionChanged()")
updateDrawerItemVisibility()
handlePendingAction()
}
override fun onPrimaryCloudConnectionChanged(connection: CloudConnection?) {
CrashReportingHelper.d(TAG, "onPrimaryCloudConnectionChanged()")
handlePendingAction()
launch {
showPushNotificationWarningIfNeeded()
}
}
/**
* Determines whether to switch the server based on the wifi ssid. Returns -1 if no switch is required,
* the server id otherwise.
*/
private fun determineServerIdToSwitchToBasedOnWifi(ssid: String?, prevSsid: String?): Int {
val allServers = prefs
.getConfiguredServerIds()
.map { id -> ServerConfiguration.load(prefs, getSecretPrefs(), id) }
val anyServerHasSetWifi = allServers
.any { config -> config?.wifiSsids?.isNotEmpty() == true }
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
val requiredPermissions = when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
val anyServerIsRestrictedToWifi = allServers.any { config -> config?.restrictToWifiSsids == true }
if (anyServerIsRestrictedToWifi) {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION)
} else {
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
}
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ->
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION)
else -> null
}
when {
!anyServerHasSetWifi -> {
Log.d(TAG, "Cannot auto select server: No server with configured wifi")
return -1
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
!LocationManagerCompat.isLocationEnabled(locationManager) -> {
Log.d(TAG, "Cannot auto select server: Location off")
showSnackbar(
SNACKBAR_TAG_SWITCHED_SERVER,
R.string.settings_multi_server_wifi_ssid_location_off,
)
return -1
}
requiredPermissions != null && !hasPermissions(requiredPermissions) -> {
Log.d(TAG, "Cannot auto select server: Missing permission ${requiredPermissions.contentToString()}")
showSnackbar(
SNACKBAR_TAG_SWITCHED_SERVER,
R.string.settings_multi_server_wifi_ssid_missing_permissions,
actionResId = R.string.settings_background_tasks_permission_allow
) {
requestPermissionsIfRequired(requiredPermissions, REQUEST_CODE_PERMISSIONS)
}
return -1
}
ssid == prevSsid -> {
Log.d(TAG, "Cannot auto select server: SSID didn't change since the last check")
return -1
}
ssid.isNullOrEmpty() -> {
Log.d(TAG, "Cannot auto select server: SSID empty, probably not connected to wifi")
return -1
}
}
val serverForCurrentWifi = prefs
.getConfiguredServerIds()
.map { id -> ServerConfiguration.load(prefs, getSecretPrefs(), id) }
.firstOrNull { config -> config?.wifiSsids?.contains(ssid) == true }
?: return -1
val currentActive = prefs.getActiveServerId()
if (serverForCurrentWifi.id == currentActive) {
Log.d(TAG, "Server for current wifi already active")
return -1
}
return serverForCurrentWifi.id
}
private fun switchServerBasedOnWifi(serverId: Int) {
val prevActiveServer = prefs.getActiveServerId()
val serverForCurrentWifi = ServerConfiguration.load(prefs, getSecretPrefs(), serverId) ?: return
prefs.edit {
putActiveServerId(serverForCurrentWifi.id)
}
showSnackbar(
SNACKBAR_TAG_SWITCHED_SERVER,
getString(R.string.settings_multi_server_wifi_ssid_switched, serverForCurrentWifi.name),
Snackbar.LENGTH_LONG,
R.string.undo
) {
prefs.edit {
putActiveServerId(prevActiveServer)
}
}
}
private fun handleConnectionChange() {
if (connection is DemoConnection) {
showSnackbar(
SNACKBAR_TAG_DEMO_MODE_ACTIVE,
R.string.info_demo_mode_short,
actionResId = R.string.turn_off
) {
prefs.edit {
putBoolean(PrefKeys.DEMO_MODE, false)
}
}
} else {
val hasLocalAndRemote =
ConnectionFactory.activeLocalConnection != null && ConnectionFactory.activeRemoteConnection != null
val type = connection?.connectionType
if (hasLocalAndRemote && type == Connection.TYPE_LOCAL) {
showSnackbar(
SNACKBAR_TAG_CONNECTION_ESTABLISHED,
R.string.info_conn_url,
Snackbar.LENGTH_SHORT
)
} else if (hasLocalAndRemote && type == Connection.TYPE_REMOTE) {
showSnackbar(
SNACKBAR_TAG_CONNECTION_ESTABLISHED,
R.string.info_conn_rem_url,
Snackbar.LENGTH_SHORT
)
}
}
queryServerProperties()
}
fun enableWifiAndIndicateStartup() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val panelIntent = Intent(Settings.Panel.ACTION_WIFI)
startActivity(panelIntent)
} else {
val wifiManager = getWifiManager(OpenHabApplication.DATA_ACCESS_TAG_SUGGEST_TURN_ON_WIFI)
@Suppress("DEPRECATION")
wifiManager.isWifiEnabled = true
controller.updateConnection(null, getString(R.string.waiting_for_wifi),
R.drawable.ic_wifi_strength_outline_grey_24dp)
}
}
fun retryServerPropertyQuery() {
controller.clearServerCommunicationFailure()
queryServerProperties()
}
override fun doesLockModeRequirePrompt(mode: ScreenLockMode): Boolean {
return mode == ScreenLockMode.Enabled
}
private fun queryServerProperties() {
propsUpdateHandle?.cancel()
retryJob?.cancel(CancellationException("queryServerProperties() was called"))
val successCb: (ServerProperties) -> Unit = { props ->
serverProperties = props
updateSitemapDrawerEntries()
if (props.sitemaps.isEmpty()) {
Log.e(TAG, "openHAB returned empty Sitemap list")
controller.indicateServerCommunicationFailure(getString(R.string.error_empty_sitemap_list))
scheduleRetry {
retryServerPropertyQuery()
}
} else {
chooseSitemap()
}
if (connection !is DemoConnection) {
prefs.edit {
putInt(PrefKeys.PREV_SERVER_FLAGS, props.flags)
}
}
handlePendingAction()
}
propsUpdateHandle = ServerProperties.fetch(this, connection!!,
successCb, this::handlePropertyFetchFailure)
BackgroundTasksManager.KNOWN_KEYS.forEach { key ->
BackgroundTasksManager.scheduleWorker(this, key, false)
}
}
private fun chooseSitemap() {
val sitemap = selectConfiguredSitemapFromList()
if (sitemap != null) {
controller.openSitemap(sitemap)
} else {
showSitemapSelectionDialog()
}
}
private fun handleServiceResolveResult(info: ServiceInfo?) {
if (info != null && prefs.getConfiguredServerIds().isEmpty()) {
info.addToPrefs(this)
} else {
Log.d(TAG, "Failed to discover openHAB server")
controller.indicateMissingConfiguration(resolveAttempted = true, wouldHaveUsedOfficialServer = false)
}
}
private fun processIntent(intent: Intent) {
Log.d(TAG, "Got intent: $intent")
if (intent.action == Intent.ACTION_MAIN) {
intent.action = prefs.getStringOrNull(PrefKeys.START_PAGE)
}
when (intent.action) {
NfcAdapter.ACTION_NDEF_DISCOVERED, Intent.ACTION_VIEW -> {
val tag = intent.data?.toTagData()
BackgroundTasksManager.enqueueNfcUpdateIfNeeded(this, tag)
val sitemapUrl = tag?.sitemap
if (!sitemapUrl.isNullOrEmpty()) {
executeOrStoreAction(PendingAction.OpenSitemapUrl(sitemapUrl, 0))
}
}
ACTION_NOTIFICATION_SELECTED -> {
CloudMessagingHelper.onNotificationSelected(this, intent)
val notificationId = intent.getStringExtra(EXTRA_PERSISTED_NOTIFICATION_ID).orEmpty()
executeActionIfPossible(PendingAction.OpenNotification(notificationId, true))
}
ACTION_HABPANEL_SELECTED, ACTION_OH3_UI_SELECTED, ACTION_FRONTAIL_SELECTED -> {
val serverId = intent.getIntExtra(EXTRA_SERVER_ID, prefs.getActiveServerId())
val ui = when (intent.action) {
ACTION_HABPANEL_SELECTED -> WebViewUi.HABPANEL
ACTION_FRONTAIL_SELECTED -> WebViewUi.FRONTAIL
else -> WebViewUi.OH3_UI
}
val subpage = intent.getStringExtra(EXTRA_SUBPAGE)
executeOrStoreAction(PendingAction.OpenWebViewUi(ui, serverId, subpage))
}
ACTION_VOICE_RECOGNITION_SELECTED -> executeOrStoreAction(PendingAction.LaunchVoiceRecognition())
ACTION_SITEMAP_SELECTED -> {
val sitemapUrl = intent.getStringExtra(EXTRA_SITEMAP_URL) ?: return
val serverId = intent.getIntExtra(EXTRA_SERVER_ID, prefs.getActiveServerId())
executeOrStoreAction(PendingAction.OpenSitemapUrl(sitemapUrl, serverId))
}
}
}
fun triggerPageUpdate(pageUrl: String, forceReload: Boolean) {
controller.triggerPageUpdate(pageUrl, forceReload)
}
private fun setupToolbar() {
val toolbar = findViewById<Toolbar>(R.id.openhab_toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
progressBar = toolbar.findViewById(R.id.toolbar_progress_bar)
setProgressIndicatorVisible(false)
}
private fun setupDrawer() {
drawerLayout = findViewById(R.id.activity_content)
drawerToggle = ActionBarDrawerToggle(this, drawerLayout,
R.string.drawer_open, R.string.drawer_close)
drawerLayout.addDrawerListener(drawerToggle)
drawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() {
override fun onDrawerOpened(drawerView: View) {
if (serverProperties != null && propsUpdateHandle == null) {
propsUpdateHandle = ServerProperties.updateSitemaps(this@MainActivity,
serverProperties!!, connection!!,
{ props ->
serverProperties = props
updateSitemapDrawerEntries()
},
this@MainActivity::handlePropertyFetchFailure)
}
}
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
updateDrawerMode(false)
}
})
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START)
val drawerView = findViewById<NavigationView>(R.id.left_drawer)
drawerView.inflateMenu(R.menu.left_drawer)
drawerMenu = drawerView.menu
// We only want to tint the menu icons, but not our loaded sitemap icons. NavigationView
// unfortunately doesn't support this directly, so we tint the icon drawables manually
// instead of letting NavigationView do it.
drawerIconTintList = drawerView.itemIconTintList
drawerView.itemIconTintList = null
drawerMenu.forEach { item -> item.icon = applyDrawerIconTint(item.icon) }
drawerView.setNavigationItemSelectedListener { item ->
drawerLayout.closeDrawers()
var handled = false
when (item.itemId) {
R.id.notifications -> {
openNotifications(null, false)
handled = true
}
R.id.nfc -> {
val intent = Intent(this, NfcItemPickerActivity::class.java)
startActivity(intent)
handled = true
}
R.id.habpanel -> {
openWebViewUi(WebViewUi.HABPANEL, false, null)
handled = true
}
R.id.oh3_ui -> {
openWebViewUi(WebViewUi.OH3_UI, false, null)
handled = true
}
R.id.frontail -> {
openWebViewUi(WebViewUi.FRONTAIL, false, null)
handled = true
}
R.id.settings -> {
val settingsIntent = Intent(this@MainActivity, PreferencesActivity::class.java)
settingsIntent.putExtra(PreferencesActivity.START_EXTRA_SERVER_PROPERTIES, serverProperties)
preferenceActivityCallback.launch(settingsIntent)
handled = true
}
R.id.about -> {
val aboutIntent = Intent(this, AboutActivity::class.java)
aboutIntent.putExtra("serverProperties", serverProperties)
startActivity(aboutIntent)
handled = true
}
R.id.default_sitemap -> {
val sitemap = serverProperties?.sitemaps?.firstOrNull { s ->
s.name == prefs.getDefaultSitemap(connection)?.name
}
if (sitemap != null) {
controller.openSitemap(sitemap)
handled = true
} else if (prefs.getDefaultSitemap(connection) != null) {
executeOrStoreAction(PendingAction.ChooseSitemap())
handled = true
}
}
}
if (item.groupId == R.id.sitemaps) {
val sitemap = serverProperties?.sitemaps?.firstOrNull { s -> s.name.hashCode() == item.itemId }
if (sitemap != null) {
controller.openSitemap(sitemap)
handled = true
}
}
if (item.groupId == R.id.servers) {
prefs.edit {
putActiveServerId(item.itemId)
}
updateServerNameInDrawer()
// Menu views aren't updated in a click handler, so defer the menu update
launch {
updateDrawerMode(false)
}
handled = true
}
handled
}
drawerModeSelectorContainer = drawerView.inflateHeaderView(R.layout.drawer_header)
drawerModeSelectorContainer.setOnClickListener { updateDrawerMode(!inServerSelectionMode) }
drawerModeToggle = drawerModeSelectorContainer.findViewById(R.id.drawer_mode_switcher)
drawerServerNameView = drawerModeSelectorContainer.findViewById(R.id.server_name)
}
private fun updateDrawerServerEntries() {
// Remove existing items from server group
drawerMenu.getGroupItems(R.id.servers)
.forEach { item -> drawerMenu.removeItem(item.itemId) }
// Add new items
val configs = prefs.getConfiguredServerIds()
.mapNotNull { id -> ServerConfiguration.load(prefs, getSecretPrefs(), id) }
configs.forEachIndexed { index, config -> drawerMenu.add(R.id.servers, config.id, index, config.name) }
if (configs.size > 1 && connection !is DemoConnection) {
drawerModeSelectorContainer.isVisible = true
} else {
drawerModeSelectorContainer.isGone = true
inServerSelectionMode = false
}
updateServerNameInDrawer()
updateDrawerItemVisibility()
}
private fun updateSitemapDrawerEntries() {
val defaultSitemapItem = drawerMenu.findItem(R.id.default_sitemap)
val sitemaps = serverProperties?.sitemaps
?.sortedWithDefaultName(prefs.getDefaultSitemap(connection)?.name.orEmpty())
drawerMenu.getGroupItems(R.id.sitemaps)
.filter { item -> item !== defaultSitemapItem }
.forEach { item -> drawerMenu.removeItem(item.itemId) }
if (sitemaps?.isNotEmpty() != true) {
return
}
if (prefs.areSitemapsShownInDrawer()) {
sitemaps.forEachIndexed { index, sitemap ->
val item = drawerMenu.add(R.id.sitemaps, sitemap.name.hashCode(), index, sitemap.label)
loadSitemapIcon(sitemap, item)
}
} else {
val sitemap = serverProperties?.sitemaps?.firstOrNull { s ->
s.name == prefs.getDefaultSitemap(connection)?.name.orEmpty()
}
if (sitemap != null) {
defaultSitemapItem.title = sitemap.label
loadSitemapIcon(sitemap, defaultSitemapItem)
} else {
defaultSitemapItem.title = getString(R.string.mainmenu_openhab_selectsitemap)
defaultSitemapItem.icon =
applyDrawerIconTint(ContextCompat.getDrawable(this, R.drawable.ic_openhab_appicon_24dp))
}
}
updateDrawerItemVisibility()
}
private fun updateServerNameInDrawer() {
val activeConfig = ServerConfiguration.load(prefs, getSecretPrefs(), prefs.getActiveServerId())
drawerServerNameView.text = activeConfig?.name
}
private fun updateDrawerItemVisibility() {
val serverItems = drawerMenu.getGroupItems(R.id.servers)
drawerMenu.setGroupVisible(R.id.servers, serverItems.size > 1 && inServerSelectionMode)
if (serverProperties?.sitemaps?.isNotEmpty() == true && !inServerSelectionMode) {
drawerMenu.setGroupVisible(R.id.sitemaps, true)
val defaultSitemapItem = drawerMenu.findItem(R.id.default_sitemap)
defaultSitemapItem.isVisible = !prefs.areSitemapsShownInDrawer()
} else {
drawerMenu.setGroupVisible(R.id.sitemaps, false)
}
if (inServerSelectionMode) {
drawerMenu.setGroupVisible(R.id.options, false)
} else {
drawerMenu.setGroupVisible(R.id.options, true)
val notificationsItem = drawerMenu.findItem(R.id.notifications)
notificationsItem.isVisible = ConnectionFactory.activeCloudConnection?.connection != null
val habPanelItem = drawerMenu.findItem(R.id.habpanel)
habPanelItem.isVisible = serverProperties?.hasWebViewUiInstalled(WebViewUi.HABPANEL) == true &&
prefs.getBoolean(PrefKeys.DRAWER_ENTRY_HABPANEL, true)
manageHabPanelShortcut(serverProperties?.hasWebViewUiInstalled(WebViewUi.HABPANEL) == true)
val oh3UiItem = drawerMenu.findItem(R.id.oh3_ui)
oh3UiItem.isVisible = serverProperties?.hasWebViewUiInstalled(WebViewUi.OH3_UI) == true &&
prefs.getBoolean(PrefKeys.DRAWER_ENTRY_OH3_UI, true)
val frontailItem = drawerMenu.findItem(R.id.frontail)
frontailItem.isVisible = serverProperties != null &&
connection?.connectionType == Connection.TYPE_LOCAL &&
prefs.getBoolean(PrefKeys.DRAWER_ENTRY_FRONTAIL, false)
val nfcItem = drawerMenu.findItem(R.id.nfc)
nfcItem.isVisible = serverProperties != null &&
(NfcAdapter.getDefaultAdapter(this) != null || Util.isEmulator()) &&
prefs.getPrimaryServerId() == prefs.getActiveServerId() &&
prefs.getBoolean(PrefKeys.DRAWER_ENTRY_NFC, true)
}
}
private fun updateDrawerMode(inServerMode: Boolean) {
if (inServerMode == inServerSelectionMode) {
return
}
inServerSelectionMode = inServerMode
drawerModeToggle.setImageResource(
if (inServerSelectionMode) R.drawable.ic_menu_up_24dp else R.drawable.ic_menu_down_24dp
)
updateDrawerItemVisibility()
}
private fun loadSitemapIcon(sitemap: Sitemap, item: MenuItem) {
val defaultIcon = ContextCompat.getDrawable(this, R.drawable.ic_openhab_appicon_24dp)
item.icon = applyDrawerIconTint(defaultIcon)
val conn = connection
if (sitemap.icon == null || conn == null) {
return
}
launch {
try {
item.icon = conn.httpClient.get(
sitemap.icon.toUrl(this@MainActivity, determineDataUsagePolicy().loadIconsWithState)
)
.asBitmap(defaultIcon!!.intrinsicWidth, ImageConversionPolicy.ForceTargetSize)
.response
.toDrawable(resources)
} catch (e: HttpClient.HttpException) {
Log.w(TAG, "Could not fetch icon for sitemap ${sitemap.name}")
}
}
}
private fun applyDrawerIconTint(icon: Drawable?): Drawable? {
if (icon == null) {
return null
}
val wrapped = DrawableCompat.wrap(icon.mutate())
DrawableCompat.setTintList(wrapped, drawerIconTintList)
return wrapped
}
private fun executeOrStoreAction(action: PendingAction) {
if (!executeActionIfPossible(action)) {
pendingAction = action
}
}
private fun handlePendingAction() {
val action = pendingAction
if (action != null && executeActionIfPossible(action)) {
pendingAction = null
}
}
private fun executeActionIfPossible(action: PendingAction): Boolean = when {
action is PendingAction.ChooseSitemap && isStarted -> {
chooseSitemap()
true
}
action is PendingAction.OpenSitemapUrl && isStarted && serverProperties != null -> {
executeActionForServer(action.serverId) { buildUrlAndOpenSitemap(action.url) }
}
action is PendingAction.OpenWebViewUi && isStarted &&
serverProperties?.hasWebViewUiInstalled(action.ui) == true -> {
executeActionForServer(action.serverId) { openWebViewUi(action.ui, true, action.subpage) }
}
action is PendingAction.LaunchVoiceRecognition && serverProperties != null -> {
launchVoiceRecognition()
true
}
action is PendingAction.OpenNotification && isStarted -> {
val conn = if (action.primary) {
ConnectionFactory.primaryCloudConnection
} else {
ConnectionFactory.activeCloudConnection
}
if (conn?.connection != null) {
openNotifications(action.notificationId, action.primary)
true
} else {
false
}
}
else -> false
}
private fun executeActionForServer(serverId: Int, action: () -> Unit): Boolean = when {
serverId !in prefs.getConfiguredServerIds() -> {
showSnackbar(
SNACKBAR_TAG_SERVER_MISSING,
R.string.home_shortcut_server_has_been_deleted
)
true
}
serverId != prefs.getActiveServerId() -> {
prefs.edit {
putActiveServerId(serverId)
}
updateDrawerServerEntries()
false
}
else -> {
action()
true
}
}
private fun selectConfiguredSitemapFromList(): Sitemap? {
val configuredSitemap = prefs.getDefaultSitemap(connection)?.name.orEmpty()
val sitemaps = serverProperties?.sitemaps
val result = when {
sitemaps == null -> null
// We only have one sitemap, use it
sitemaps.size == 1 -> sitemaps[0]
// Select configured sitemap if still present, nothing otherwise
configuredSitemap.isNotEmpty() -> sitemaps.firstOrNull { sitemap -> sitemap.name == configuredSitemap }
// Nothing configured -> can't auto-select anything
else -> null
}
Log.d(TAG, "Configured sitemap is '$configuredSitemap', selected $result")
if (result == null && configuredSitemap.isNotEmpty()) {
// clear old configuration
prefs.updateDefaultSitemap(connection, null)
} else if (result != null && (configuredSitemap.isEmpty() || configuredSitemap != result.name)) {
// update result
prefs.updateDefaultSitemap(connection, result)
updateSitemapDrawerEntries()
}
return result
}
private fun showSitemapSelectionDialog() {
Log.d(TAG, "Opening sitemap selection dialog")
if (sitemapSelectionDialog?.isShowing == true) {
sitemapSelectionDialog?.dismiss()
}
val sitemaps = serverProperties?.sitemaps
if (isFinishing || sitemaps == null) {
return
}
val sitemapLabels = sitemaps.map { s -> s.label }.toTypedArray()
sitemapSelectionDialog = AlertDialog.Builder(this)
.setTitle(R.string.mainmenu_openhab_selectsitemap)
.setItems(sitemapLabels) { _, which ->
val sitemap = sitemaps[which]
Log.d(TAG, "Selected sitemap $sitemap")
prefs.updateDefaultSitemap(connection, sitemap)
controller.openSitemap(sitemap)
updateSitemapDrawerEntries()
}
.show()
}
private fun openNotifications(highlightedId: String?, primaryServer: Boolean) {
controller.openNotifications(highlightedId, primaryServer)
drawerToggle.isDrawerIndicatorEnabled = false
}
private fun openWebViewUi(ui: WebViewUi, isStackRoot: Boolean, subpage: String?) {
hideSnackbar(SNACKBAR_TAG_SSE_ERROR)
controller.showWebViewUi(ui, isStackRoot, subpage)
drawerToggle.isDrawerIndicatorEnabled = isStackRoot
}
private fun buildUrlAndOpenSitemap(partUrl: String) {
controller.openPage("rest/sitemaps$partUrl")
}
fun onWidgetSelected(linkedPage: LinkedPage, source: WidgetListFragment) {
Log.d(TAG, "Got widget link = ${linkedPage.link}")
controller.openPage(linkedPage, source)
}
fun updateTitle() {
val title = controller.currentTitle
val activeServerName = ServerConfiguration.load(prefs, getSecretPrefs(), prefs.getActiveServerId())?.name
setTitle(title ?: activeServerName ?: getString(R.string.app_name))
drawerToggle.isDrawerIndicatorEnabled = !controller.canGoBack()
}
fun setProgressIndicatorVisible(visible: Boolean) {
if (visible) {
progressBar?.show()
} else {
progressBar?.hide()
}
}
private fun launchVoiceRecognition() {
val speechIntent = BackgroundTasksManager.buildVoiceRecognitionIntent(this, false)
try {
startActivity(speechIntent)
} catch (e: ActivityNotFoundException) {
showSnackbar(
SNACKBAR_TAG_NO_VOICE_RECOGNITION_INSTALLED,
R.string.error_no_speech_to_text_app_found,
actionResId = R.string.install
) {
openInAppStore("com.google.android.googlequicksearchbox")
}
}
}
private suspend fun showPushNotificationWarningIfNeeded() {
val status = CloudMessagingHelper.getPushNotificationStatus(this@MainActivity)
if (status.notifyUser) {
showSnackbar(SNACKBAR_TAG_PUSH_NOTIFICATION_FAIL, status.message)
}
}
fun showRefreshHintSnackbarIfNeeded() {
if (prefs.getBoolean(PrefKeys.SWIPE_REFRESH_EXPLAINED, false)) {
return
}
showSnackbar(
SNACKBAR_TAG_NO_MANUAL_REFRESH_REQUIRED,
R.string.swipe_to_refresh_description,
actionResId = R.string.got_it
) {
prefs.edit {
putBoolean(PrefKeys.SWIPE_REFRESH_EXPLAINED, true)
}
}
}
fun showDataSaverHintSnackbarIfNeeded() {
if (prefs.getBoolean(PrefKeys.DATA_SAVER_EXPLAINED, false) ||
determineDataUsagePolicy().loadIconsWithState
) {
return
}
showSnackbar(
SNACKBAR_TAG_DATA_SAVER_ON,
R.string.data_saver_snackbar,
actionResId = R.string.got_it
) {
prefs.edit {
putBoolean(PrefKeys.DATA_SAVER_EXPLAINED, true)
}
}
}
fun setDrawerLocked(locked: Boolean) {
drawerLayout.isSwipeDisabled = locked
}
private fun handlePropertyFetchFailure(request: Request, statusCode: Int, error: Throwable) {
Log.e(TAG, "Error: $error", error)
Log.e(TAG, "HTTP status code: $statusCode")
var message = getHumanReadableErrorMessage(request.url.toString(), statusCode, error, false)
if (prefs.isDebugModeEnabled()) {
message = SpannableStringBuilder(message).apply {
inSpans(RelativeSizeSpan(0.8f)) {
append("\n\nURL: ").append(request.url.toString())
val authHeader = request.header("Authorization")
if (authHeader?.startsWith("Basic") == true) {
val base64Credentials = authHeader.substring("Basic".length).trim()
val credentials = String(Base64.decode(base64Credentials, Base64.DEFAULT),
Charset.forName("UTF-8"))
append("\nUsername: ")
append(credentials.substring(0, credentials.indexOf(":")))
}
append("\nException stack:\n")
}
inSpans(RelativeSizeSpan(0.6f)) {
var origError: Throwable?
var cause: Throwable? = error
do {
append(cause?.toString()).append('\n')
origError = cause
cause = origError?.cause
} while (cause != null && origError !== cause)
}
}
}
controller.indicateServerCommunicationFailure(message)
scheduleRetry {
retryServerPropertyQuery()
}
propsUpdateHandle = null
}
private fun showMissingPermissionsWarningIfNeeded() {
val missingPermissions = BackgroundTasksManager.KNOWN_KEYS
.filter { entry ->
val requiredPermissions = BackgroundTasksManager.getRequiredPermissionsForTask(entry)
prefs.getStringOrNull(entry)?.toItemUpdatePrefValue()?.first == true &&
requiredPermissions != null && !hasPermissions(requiredPermissions)
}
.mapNotNull { entry -> BackgroundTasksManager.getRequiredPermissionsForTask(entry)?.toList() }
.flatten()
.toSet()
.filter { !hasPermissions(arrayOf(it)) }
.toMutableList()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R &&
missingPermissions.contains(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
) {
if (missingPermissions.size > 1) {
Log.d(TAG, "Remove background location from permissions to request")
missingPermissions.remove(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
} else {
showSnackbar(
SNACKBAR_TAG_BG_TASKS_MISSING_PERMISSION_LOCATION,
getString(
R.string.settings_background_tasks_permission_denied_background_location,
packageManager.backgroundPermissionOptionLabel
),
actionResId = android.R.string.ok
) {
Intent(Settings.ACTION_APPLICATION_SETTINGS).apply {
putExtra(Settings.EXTRA_APP_PACKAGE, BuildConfig.APPLICATION_ID)
startActivity(this)
}
}
return
}
}
if (missingPermissions.isNotEmpty()) {
Log.d(TAG, "At least one permission for background tasks has been denied")
showSnackbar(
SNACKBAR_TAG_BG_TASKS_MISSING_PERMISSIONS,
R.string.settings_background_tasks_permission_denied,
actionResId = R.string.settings_background_tasks_permission_allow
) {
requestPermissionsIfRequired(
missingPermissions.toTypedArray(),
REQUEST_CODE_PERMISSIONS
)
}
}
}
private fun manageHabPanelShortcut(visible: Boolean) {
manageShortcut(visible, "habpanel", ACTION_HABPANEL_SELECTED,
R.string.mainmenu_openhab_habpanel, R.mipmap.ic_shortcut_habpanel,
R.string.app_shortcut_disabled_habpanel)
}
private fun manageNotificationShortcut(visible: Boolean) {
manageShortcut(visible, "notification", ACTION_NOTIFICATION_SELECTED,
R.string.app_notifications, R.mipmap.ic_shortcut_notifications,
R.string.app_shortcut_disabled_notifications)
}
private fun manageVoiceRecognitionShortcut(visible: Boolean) {
manageShortcut(visible, "voice_recognition", ACTION_VOICE_RECOGNITION_SELECTED,
R.string.mainmenu_openhab_voice_recognition,
R.mipmap.ic_shortcut_voice_recognition,
R.string.app_shortcut_disabled_voice_recognition)
}
private fun manageShortcut(
visible: Boolean,
id: String,
action: String,
@StringRes shortLabel: Int,
@DrawableRes icon: Int,
@StringRes disableMessage: Int
) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
return
}
if (visible) {
val intent = Intent(this, MainActivity::class.java)
.setAction(action)
val shortcut = ShortcutInfo.Builder(this, id)
.setShortLabel(getString(shortLabel))
.setIcon(Icon.createWithResource(this, icon))
.setIntent(intent)
.build()
try {
shortcutManager?.addDynamicShortcuts(listOf(shortcut))
} catch (e: IllegalArgumentException) {
Log.e(TAG, "Failed to add shortcut $id", e)
}
} else {
shortcutManager?.disableShortcuts(listOf(id), getString(disableMessage))
}
}
private fun setVoiceWidgetComponentEnabledSetting(component: Class<*>, isSpeechRecognizerAvailable: Boolean) {
val voiceWidget = ComponentName(this, component)
val newState = if (isSpeechRecognizerAvailable)
PackageManager.COMPONENT_ENABLED_STATE_ENABLED
else
PackageManager.COMPONENT_ENABLED_STATE_DISABLED
packageManager.setComponentEnabledSetting(voiceWidget, newState, PackageManager.DONT_KILL_APP)
}
private sealed class PendingAction {
class ChooseSitemap : PendingAction()
class OpenSitemapUrl constructor(val url: String, val serverId: Int) : PendingAction()
class OpenWebViewUi constructor(val ui: WebViewUi, val serverId: Int, val subpage: String?) : PendingAction()
class LaunchVoiceRecognition : PendingAction()
class OpenNotification constructor(val notificationId: String, val primary: Boolean) : PendingAction()
}
companion object {
const val ACTION_NOTIFICATION_SELECTED = "org.openhab.habdroid.action.NOTIFICATION_SELECTED"
const val ACTION_HABPANEL_SELECTED = "org.openhab.habdroid.action.HABPANEL_SELECTED"
const val ACTION_OH3_UI_SELECTED = "org.openhab.habdroid.action.OH3_UI_SELECTED"
const val ACTION_FRONTAIL_SELECTED = "org.openhab.habdroid.action.FRONTAIL"
const val ACTION_VOICE_RECOGNITION_SELECTED = "org.openhab.habdroid.action.VOICE_SELECTED"
const val ACTION_SITEMAP_SELECTED = "org.openhab.habdroid.action.SITEMAP_SELECTED"
const val EXTRA_SITEMAP_URL = "sitemapUrl"
const val EXTRA_SERVER_ID = "serverId"
const val EXTRA_SUBPAGE = "subpage"
const val EXTRA_PERSISTED_NOTIFICATION_ID = "persistedNotificationId"
const val SNACKBAR_TAG_DEMO_MODE_ACTIVE = "demoModeActive"
const val SNACKBAR_TAG_PRESS_AGAIN_EXIT = "pressAgainToExit"
const val SNACKBAR_TAG_CONNECTION_ESTABLISHED = "connectionEstablished"
const val SNACKBAR_TAG_PUSH_NOTIFICATION_FAIL = "pushNotificationFail"
const val SNACKBAR_TAG_DATA_SAVER_ON = "dataSaverOn"
const val SNACKBAR_TAG_NO_VOICE_RECOGNITION_INSTALLED = "noVoiceRecognitionInstalled"
const val SNACKBAR_TAG_NO_MANUAL_REFRESH_REQUIRED = "noManualRefreshRequired"
const val SNACKBAR_TAG_BG_TASKS_MISSING_PERMISSIONS = "bgTasksMissingPermissions"
const val SNACKBAR_TAG_BG_TASKS_MISSING_PERMISSION_LOCATION = "bgTasksMissingPermissionLocation"
const val SNACKBAR_TAG_SSE_ERROR = "sseError"
const val SNACKBAR_TAG_SHORTCUT_INFO = "shortcutInfo"
const val SNACKBAR_TAG_SERVER_MISSING = "serverMissing"
const val SNACKBAR_TAG_SWITCHED_SERVER = "switchedServer"
private const val STATE_KEY_SERVER_PROPERTIES = "serverProperties"
private const val STATE_KEY_SITEMAP_SELECTION_SHOWN = "isSitemapSelectionDialogShown"
private const val STATE_KEY_CONTROLLER_NAME = "controller"
private const val STATE_KEY_CONNECTION_HASH = "connectionHash"
private val TAG = MainActivity::class.java.simpleName
// Activities request codes
private const val REQUEST_CODE_PERMISSIONS = 1001
}
}
| epl-1.0 | e1b26e052f3d7ccf9343c014e9a0ac9b | 40.799863 | 118 | 0.633211 | 5.037251 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/sched/SchedV2.kt | 1 | 101461 | /****************************************************************************************
* Copyright (c) 2011 Norbert Nagold <[email protected]> *
* Copyright (c) 2012 Kostas Spyropoulos <[email protected]> *
* Copyright (c) 2013 Houssam Salem <[email protected]> *
* Copyright (c) 2018 Chris Williams <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General private 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 private License for more details. *
* *
* You should have received a copy of the GNU General private License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki.sched
import android.annotation.SuppressLint
import android.app.Activity
import android.database.SQLException
import android.database.sqlite.SQLiteConstraintException
import android.text.TextUtils
import androidx.annotation.VisibleForTesting
import com.ichi2.async.CancelListener
import com.ichi2.async.CancelListener.Companion.isCancelled
import com.ichi2.async.CollectionTask.Reset
import com.ichi2.async.TaskManager
import com.ichi2.libanki.*
import com.ichi2.libanki.Collection
import com.ichi2.libanki.Consts.BUTTON_TYPE
import com.ichi2.libanki.Consts.CARD_QUEUE
import com.ichi2.libanki.Consts.DYN_PRIORITY
import com.ichi2.libanki.Consts.NEW_CARD_ORDER
import com.ichi2.libanki.Consts.REVLOG_TYPE
import com.ichi2.libanki.SortOrder.AfterSqlOrderBy
import com.ichi2.libanki.sched.Counts.Queue.*
import com.ichi2.libanki.sched.SchedV2.CountMethod
import com.ichi2.libanki.sched.SchedV2.LimitMethod
import com.ichi2.libanki.stats.Stats
import com.ichi2.libanki.utils.Time
import com.ichi2.libanki.utils.TimeManager
import com.ichi2.utils.*
import net.ankiweb.rsdroid.BackendFactory
import net.ankiweb.rsdroid.RustCleanup
import org.intellij.lang.annotations.Language
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
import java.lang.ref.WeakReference
import java.util.*
@KotlinCleanup("IDE Lint")
@KotlinCleanup("much to do - keep in line with libAnki")
@SuppressLint("VariableNamingDetector") // mCurrentCard: complex setter
open class SchedV2(col: Collection) : AbstractSched(col) {
protected val mQueueLimit = 50
protected var mReportLimit = 99999
private val mDynReportLimit = 99999
override var reps = 0
protected set
protected var haveQueues = false
protected var mHaveCounts = false
protected var mToday: Int? = null
@KotlinCleanup("replace Sched.getDayCutoff() with dayCutoff")
final override var dayCutoff: Long = 0
private var mLrnCutoff: Long = 0
protected var mNewCount = 0
@VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
internal var mLrnCount = 0
protected var mRevCount = 0
private var mNewCardModulus = 0
// Queues
protected val mNewQueue = SimpleCardQueue(this)
protected val mLrnQueue = LrnCardQueue(this)
protected val mLrnDayQueue = SimpleCardQueue(this)
protected val mRevQueue = SimpleCardQueue(this)
private var mNewDids = LinkedList<Long>()
protected var mLrnDids = LinkedList<Long>()
// Not in libanki
protected var mContextReference: WeakReference<Activity>? = null
fun interface LimitMethod {
fun operation(g: Deck): Int
}
/** Given a deck, compute the number of cards to see today, taking its pre-computed limit into consideration. It
* considers either review or new cards. Used by WalkingCount to consider all subdecks and parents of a specific
* decks. */
fun interface CountMethod {
fun operation(did: Long, lim: Int): Int
}
/**
* The card currently being reviewed.
*
* Must not be returned during prefetching (as it is currently shown)
*/
@KotlinCleanup("fix naming")
protected var mCurrentCard: Card? = null
/** The list of parent decks of the current card.
* Cached for performance .
*
* Null iff mNextCard is null. */
protected var currentCardParentsDid: List<Long>? =
null
/**
* Pop the next card from the queue. null if finished.
*/
override val card: Card?
get() {
_checkDay()
if (!haveQueues) {
resetQueues(false)
}
var card = _getCard()
if (card == null && !mHaveCounts) {
// maybe we didn't refill queues because counts were not
// set. This could only occur if the only card is a buried
// sibling. So let's try to set counts and check again.
reset()
card = _getCard()
}
if (card != null) {
col.log(card)
incrReps()
// In upstream, counts are decremented when the card is
// gotten; i.e. in _getLrnCard, _getRevCard and
// _getNewCard. This can not be done anymore since we use
// those methods to pre-fetch the next card. Instead we
// decrement the counts here, when the card is returned to
// the reviewer.
decrementCounts(card)
setCurrentCard(card)
card.startTimer()
} else {
discardCurrentCard()
}
if (!mHaveCounts) {
// Need to reset queues once counts are reset
TaskManager.launchCollectionTask(Reset())
}
return card
}
/** Ensures that reset is executed before the next card is selected */
override fun deferReset(undoneCard: Card?) {
haveQueues = false
mHaveCounts = false
if (undoneCard != null) {
setCurrentCard(undoneCard)
} else {
discardCurrentCard()
col.decks.update_active()
}
}
override fun reset() {
col.decks.update_active()
_updateCutoff()
resetCounts(false)
resetQueues(false)
}
fun resetCounts(cancelListener: CancelListener?) {
resetCounts(cancelListener, true)
}
fun resetCounts(checkCutoff: Boolean) {
resetCounts(null, checkCutoff)
}
override fun resetCounts() {
resetCounts(null, true)
}
/** @param checkCutoff whether we should check cutoff before resetting
*/
private fun resetCounts(cancelListener: CancelListener?, checkCutoff: Boolean) {
if (checkCutoff) {
_updateCutoff()
}
// Indicate that the counts can't be assumed to be correct since some are computed again and some not
// In theory it is useless, as anything that change counts should have set mHaveCounts to false
mHaveCounts = false
_resetLrnCount(cancelListener)
if (isCancelled(cancelListener)) {
Timber.v("Cancel computing counts of deck %s", col.decks.current().getString("name"))
return
}
_resetRevCount(cancelListener)
if (isCancelled(cancelListener)) {
Timber.v("Cancel computing counts of deck %s", col.decks.current().getString("name"))
return
}
_resetNewCount(cancelListener)
if (isCancelled(cancelListener)) {
Timber.v("Cancel computing counts of deck %s", col.decks.current().getString("name"))
return
}
mHaveCounts = true
}
/** @param checkCutoff whether we should check cutoff before resetting
*/
private fun resetQueues(checkCutoff: Boolean) {
if (checkCutoff) {
_updateCutoff()
}
_resetLrnQueue()
_resetRevQueue()
_resetNewQueue()
haveQueues = true
}
/**
* Does all actions required to answer the card. That is:
* Change its interval, due value, queue, mod time, usn, number of step left (if in learning)
* Put it in learning if required
* Log the review.
* Remove from filtered if required.
* Remove the siblings for the queue for same day spacing
* Bury siblings if required by the options
* Overridden
*/
override fun answerCard(card: Card, @BUTTON_TYPE ease: Int) {
col.log()
discardCurrentCard()
col.markReview(card)
_burySiblings(card)
_answerCard(card, ease)
_updateStats(card, "time", card.timeTaken().toLong())
card.mod = time.intTime()
card.usn = col.usn()
card.flushSched()
}
fun _answerCard(card: Card, @BUTTON_TYPE ease: Int) {
if (_previewingCard(card)) {
_answerCardPreview(card, ease)
return
}
card.incrReps()
if (card.queue == Consts.QUEUE_TYPE_NEW) {
// came from the new queue, move to learning
card.queue = Consts.QUEUE_TYPE_LRN
card.type = Consts.CARD_TYPE_LRN
// init reps to graduation
card.left = _startingLeft(card)
// update daily limit
_updateStats(card, "new")
}
if (card.queue == Consts.QUEUE_TYPE_LRN || card.queue == Consts.QUEUE_TYPE_DAY_LEARN_RELEARN) {
_answerLrnCard(card, ease)
} else if (card.queue == Consts.QUEUE_TYPE_REV) {
_answerRevCard(card, ease)
// Update daily limit
_updateStats(card, "rev")
} else {
throw RuntimeException("Invalid queue")
}
// once a card has been answered once, the original due date
// no longer applies
if (card.oDue > 0) {
card.oDue = 0
}
}
// note: when adding revlog entries in the future, make sure undo
// code deletes the entries
fun _answerCardPreview(card: Card, @BUTTON_TYPE ease: Int) {
if (ease == Consts.BUTTON_ONE) {
// Repeat after delay
card.queue = Consts.QUEUE_TYPE_PREVIEW
card.due = time.intTime() + _previewDelay(card)
mLrnCount += 1
} else if (ease == Consts.BUTTON_TWO) {
// Restore original card state and remove from filtered deck
_restorePreviewCard(card)
_removeFromFiltered(card)
} else {
// This is in place of the assert
throw RuntimeException("Invalid ease")
}
}
/** new count, lrn count, rev count. */
override fun counts(cancelListener: CancelListener?): Counts {
if (!mHaveCounts) {
resetCounts(cancelListener)
}
return Counts(mNewCount, mLrnCount, mRevCount)
}
/**
* Same as counts(), but also count `card`. In practice, we use it because `card` is in the reviewer and that is the
* number we actually want.
* Overridden: left / 1000 in V1
*/
override fun counts(card: Card): Counts {
val counts = counts()
val idx = countIdx(card)
counts.changeCount(idx, 1)
return counts
}
/**
* Which of the three numbers shown in reviewer/overview should the card be counted. 0:new, 1:rev, 2: any kind of learning.
* Overridden: V1 does not have preview
*/
override fun countIdx(card: Card): Counts.Queue {
return when (card.queue) {
Consts.QUEUE_TYPE_DAY_LEARN_RELEARN, Consts.QUEUE_TYPE_LRN, Consts.QUEUE_TYPE_PREVIEW -> LRN
Consts.QUEUE_TYPE_NEW -> NEW
Consts.QUEUE_TYPE_REV -> REV
else -> throw RuntimeException("Index " + card.queue + " does not exists.")
}
}
/** Number of buttons to show in the reviewer for `card`.
* Overridden */
override fun answerButtons(card: Card): Int {
val conf = _cardConf(card)
return if (card.isInDynamicDeck && !conf.getBoolean("resched")) {
2
} else 4
}
/**
* Rev/lrn/time daily stats *************************************************
* **********************************************
*/
protected fun _updateStats(card: Card, type: String) {
_updateStats(card, type, 1)
}
fun _updateStats(card: Card, type: String, cnt: Long) {
val key = type + "Today"
val did = card.did
val list = col.decks.parents(did).toMutableList()
list.add(col.decks.get(did))
for (g in list) {
val a = g.getJSONArray(key)
// add
a.put(1, a.getLong(1) + cnt)
col.decks.save(g)
}
}
override fun extendLimits(newc: Int, rev: Int) {
if (!BackendFactory.defaultLegacySchema) {
super.extendLimits(newc, rev)
return
}
val cur = col.decks.current()
val decks = col.decks.parents(cur.getLong("id")).toMutableList()
decks.add(cur)
for (did in col.decks.children(cur.getLong("id")).values) {
decks.add(col.decks.get(did))
}
for (g in decks) {
// add
var today = g.getJSONArray("newToday")
today.put(1, today.getInt(1) - newc)
today = g.getJSONArray("revToday")
today.put(1, today.getInt(1) - rev)
col.decks.save(g)
}
}
/**
* @param limFn Method sending a deck to the maximal number of card it can have. Normally into account both limits and cards seen today
* @param cntFn Method sending a deck to the number of card it has got to see today.
* @param cancelListener Whether the task is not useful anymore
* @return -1 if it's cancelled. Sum of the results of cntFn, limited by limFn,
*/
protected fun _walkingCount(
limFn: LimitMethod,
cntFn: CountMethod,
cancelListener: CancelListener? = null
): Int {
var tot = 0
val pcounts = HashUtil.HashMapInit<Long, Int>(col.decks.count())
// for each of the active decks
for (did in col.decks.active()) {
if (isCancelled(cancelListener)) return -1
// get the individual deck's limit
var lim = limFn.operation(col.decks.get(did))
if (lim == 0) {
continue
}
// check the parents
val parents = col.decks.parents(did)
for (p in parents) {
// add if missing
val id = p.getLong("id")
if (!pcounts.containsKey(id)) {
pcounts[id] = limFn.operation(p)
}
// take minimum of child and parent
lim = Math.min(pcounts[id]!!, lim)
}
// see how many cards we actually have
val cnt = cntFn.operation(did, lim)
// if non-zero, decrement from parents counts
for (p in parents) {
val id = p.getLong("id")
pcounts[id] = pcounts[id]!! - cnt
}
// we may also be a parent
pcounts[did] = lim - cnt
// and add to running total
tot += cnt
}
return tot
}
/*
Deck list **************************************************************** *******************************
*/
/**
* Returns [deckname, did, rev, lrn, new]
*
* Return nulls when deck task is cancelled.
*/
@KotlinCleanup("remove/set default")
private fun deckDueList(): List<DeckDueTreeNode> {
return deckDueList(null)!!
}
// Overridden
/**
* Return sorted list of all decks. */
protected open fun deckDueList(collectionTask: CancelListener?): List<DeckDueTreeNode>? {
_checkDay()
col.decks.checkIntegrity()
val allDecksSorted = col.decks.allSorted()
val lims = HashUtil.HashMapInit<String?, Array<Int>>(allDecksSorted.size)
val deckNodes = ArrayList<DeckDueTreeNode>(allDecksSorted.size)
val childMap = col.decks.childMap()
for (deck in allDecksSorted) {
if (isCancelled(collectionTask)) {
return null
}
val deckName = deck.getString("name")
val p = Decks.parent(deckName)
// new
var nlim = _deckNewLimitSingle(deck, false)
var plim: Int? = null
if (!TextUtils.isEmpty(p)) {
val parentLims = lims[Decks.normalizeName(p)]
// 'temporary for diagnosis of bug #6383'
Assert.that(
parentLims != null,
"Deck %s is supposed to have parent %s. It has not be found.",
deckName,
p
)
nlim = Math.min(nlim, parentLims!![0])
// reviews
plim = parentLims[1]
}
val _new = _newForDeck(deck.getLong("id"), nlim)
// learning
val lrn = _lrnForDeck(deck.getLong("id"))
// reviews
val rlim = _deckRevLimitSingle(deck, plim, false)
val rev = _revForDeck(deck.getLong("id"), rlim, childMap)
// save to list
deckNodes.add(
DeckDueTreeNode(
deck.getString("name"),
deck.getLong("id"),
rev,
lrn,
_new,
false,
false
)
)
// add deck as a parent
lims[Decks.normalizeName(deck.getString("name"))] = arrayOf(nlim, rlim)
}
return deckNodes
}
/** Similar to deck due tree, but ignore the number of cards.
*
* It may takes a lot of time to compute the number of card, it
* requires multiple database access by deck. Ignoring this number
* lead to the creation of a tree more quickly. */
@RustCleanup("consider updating callers to use col.deckTreeLegacy() directly, and removing this")
@Suppress("UNCHECKED_CAST")
override fun <T : AbstractDeckTreeNode> quickDeckDueTree(): List<TreeNode<T>> {
if (!BackendFactory.defaultLegacySchema) {
return super.quickDeckDueTree()
}
// Similar to deckDueList
@KotlinCleanup("simplify with map {}")
val allDecksSorted = ArrayList<DeckTreeNode>()
for (deck in col.decks.allSorted()) {
val g = DeckTreeNode(deck.getString("name"), deck.getLong("id"))
allDecksSorted.add(g)
}
// End of the similar part.
return (_groupChildren(allDecksSorted, false) as List<TreeNode<T>>)
}
@RustCleanup("once defaultLegacySchema is removed, cancelListener can be removed")
override fun deckDueTree(cancelListener: CancelListener?): List<TreeNode<DeckDueTreeNode>>? {
if (!BackendFactory.defaultLegacySchema) {
return super.deckDueTree(null)
}
_checkDay()
val allDecksSorted = deckDueList(cancelListener) ?: return null
return _groupChildren(allDecksSorted, true)
}
/**
* @return the tree with `allDecksSorted` content.
* @param allDecksSorted the set of all decks of the collection. Sorted.
* @param checkDone Whether the set of deck was checked. If false, we can't assume all decks have parents
* and that there is no duplicate. Instead, we'll ignore problems.
*/
protected fun <T : AbstractDeckTreeNode> _groupChildren(
allDecksSorted: List<T>,
checkDone: Boolean
): List<TreeNode<T>> {
return _groupChildren(allDecksSorted, 0, checkDone)
}
/**
* @return the tree structure of all decks from @descendants, starting
* at specified depth.
* @param sortedDescendants a list of decks of dept at least depth, having all
* the same first depth name elements, sorted in deck order.
* @param depth The depth of the tree we are creating
* @param checkDone whether the set of deck was checked. If
* false, we can't assume all decks have parents and that there
* is no duplicate. Instead, we'll ignore problems.
*/
protected fun <T : AbstractDeckTreeNode> _groupChildren(
sortedDescendants: List<T>,
depth: Int,
checkDone: Boolean
): List<TreeNode<T>> {
val sortedChildren: MutableList<TreeNode<T>> = ArrayList()
// group and recurse
val it = sortedDescendants.listIterator()
while (it.hasNext()) {
val child = it.next()
val head = child.getDeckNameComponent(depth)
val sortedDescendantsOfChild: MutableList<T> = ArrayList()
/* Compose the "sortedChildren" node list. The sortedChildren is a
* list of all the nodes that proceed the current one that
* contain the same at depth `depth`, except for the
* current one itself. I.e., they are subdecks that stem
* from this descendant. This is our version of python's
* itertools.groupby. */if (!checkDone && child.depth != depth) {
val deck = col.decks.get(child.did)
Timber.d(
"Deck %s (%d)'s parent is missing. Ignoring for quick display.",
deck.getString("name"),
child.did
)
continue
}
while (it.hasNext()) {
val descendantOfChild = it.next()
if (head == descendantOfChild.getDeckNameComponent(depth)) {
// Same head - add to tail of current head.
if (!checkDone && descendantOfChild.depth == depth) {
val deck = col.decks.get(descendantOfChild.did)
Timber.d(
"Deck %s (%d)'s is a duplicate name. Ignoring for quick display.",
deck.getString("name"),
descendantOfChild.did
)
continue
}
sortedDescendantsOfChild.add(descendantOfChild)
} else {
// We've iterated past this head, so step back in order to use this descendant as the
// head in the next iteration of the outer loop.
it.previous()
break
}
}
// the childrenNode set contains direct child of `child`, but not
// any descendants of the children of `child`...
val childrenNode = _groupChildren(sortedDescendantsOfChild, depth + 1, checkDone)
// Add the child nodes, and process the addition
val toAdd = TreeNode(child)
toAdd.children.addAll(childrenNode)
val childValues = childrenNode.map { it.value }
child.processChildren(col, childValues, "std" == name)
sortedChildren.add(toAdd)
}
return sortedChildren
}
/*
Getting the next card ****************************************************
*******************************************
*/
/**
* Return the next due card, or null.
* Overridden: V1 does not allow dayLearnFirst
*/
protected open fun _getCard(): Card? {
// learning card due?
var c = _getLrnCard(false)
if (c != null) {
return c
}
// new first, or time for one?
if (_timeForNewCard()) {
c = _getNewCard()
if (c != null) {
return c
}
}
// Day learning first and card due?
val dayLearnFirst = col.get_config("dayLearnFirst", false)!!
if (dayLearnFirst) {
c = _getLrnDayCard()
if (c != null) {
return c
}
}
// Card due for review?
c = _getRevCard()
if (c != null) {
return c
}
// day learning card due?
if (!dayLearnFirst) {
c = _getLrnDayCard()
if (c != null) {
return c
}
}
// New cards left?
c = _getNewCard()
return c ?: _getLrnCard(true)
// collapse or finish
}
/** similar to _getCard but only fill the queues without taking the card.
* Returns lists that may contain the next cards.
*/
protected open fun _fillNextCard(): Array<CardQueue<out Card.Cache?>> {
// learning card due?
if (_preloadLrnCard(false)) {
return arrayOf(mLrnQueue)
}
// new first, or time for one?
if (_timeForNewCard()) {
if (_fillNew()) {
return arrayOf(mLrnQueue, mNewQueue)
}
}
// Day learning first and card due?
val dayLearnFirst = col.get_config("dayLearnFirst", false)!!
if (dayLearnFirst) {
if (_fillLrnDay()) {
return arrayOf(mLrnQueue, mLrnDayQueue)
}
}
// Card due for review?
if (_fillRev()) {
return arrayOf(mLrnQueue, mRevQueue)
}
// day learning card due?
if (!dayLearnFirst) {
if (_fillLrnDay()) {
return arrayOf(mLrnQueue, mLrnDayQueue)
}
}
// New cards left?
if (_fillNew()) {
return arrayOf(mLrnQueue, mNewQueue)
}
// collapse or finish
return if (_preloadLrnCard(true)) {
arrayOf(mLrnQueue)
} else arrayOf()
}
/** pre load the potential next card. It may loads many card because, depending on the time taken, the next card may
* be a card in review or not. */
override fun preloadNextCard() {
_checkDay()
if (!mHaveCounts) {
resetCounts(false)
}
if (!haveQueues) {
resetQueues(false)
}
for (caches in _fillNextCard()) {
caches.loadFirstCard()
}
}
/**
* New cards **************************************************************** *******************************
*/
protected fun _resetNewCount(cancelListener: CancelListener? = null) {
mNewCount = _walkingCount(
LimitMethod { g: Deck -> _deckNewLimitSingle(g, true) },
CountMethod { did: Long, lim: Int -> _cntFnNew(did, lim) },
cancelListener
)
}
// Used as an argument for _walkingCount() in _resetNewCount() above
protected fun _cntFnNew(did: Long, lim: Int): Int {
return col.db.queryScalar(
"SELECT count() FROM (SELECT 1 FROM cards WHERE did = ? AND queue = " + Consts.QUEUE_TYPE_NEW + " AND id != ? LIMIT ?)",
did, currentCardId(), lim
)
}
private fun _resetNew() {
_resetNewCount()
_resetNewQueue()
}
private fun _resetNewQueue() {
mNewDids = LinkedList(col.decks.active())
mNewQueue.clear()
_updateNewCardRatio()
}
/**
* @return The id of the note currently in the reviewer. 0 if no
* such card.
*/
protected fun currentCardNid(): Long {
val currentCard = mCurrentCard
/* mCurrentCard may be set to null when the reviewer gets closed. So we copy it to be sure to avoid
NullPointerException */return if (mCurrentCard == null) {
/* This method is used to determine whether two cards are siblings. Since 0 is not a valid nid, all cards
will have a nid distinct from 0. As it is used in sql statement, it is not possible to just use a function
areSiblings()*/
0
} else currentCard!!.nid
}
/**
* @return The id of the card currently in the reviewer. 0 if no
* such card.
*/
protected fun currentCardId(): Long {
return if (mCurrentCard == null) {
/* This method is used to ensure that query don't return current card. Since 0 is not a valid nid, all cards
will have a nid distinct from 0. As it is used in sql statement, it is not possible to just use a function
areSiblings()*/
0
} else mCurrentCard!!.id
}
protected fun _fillNew(): Boolean {
return _fillNew(false)
}
private fun _fillNew(allowSibling: Boolean): Boolean {
if (!mNewQueue.isEmpty) {
return true
}
if (mHaveCounts && mNewCount == 0) {
return false
}
while (!mNewDids.isEmpty()) {
val did = mNewDids.first
val lim = Math.min(mQueueLimit, _deckNewLimit(did, true))
if (lim != 0) {
mNewQueue.clear()
val idName = if (allowSibling) "id" else "nid"
val id = if (allowSibling) currentCardId() else currentCardNid()
/* Difference with upstream: we take current card into account.
*
* When current card is answered, the card is not due anymore, so does not belong to the queue.
* Furthermore, _burySiblings ensure that the siblings of the current cards are removed from the
* queue to ensure same day spacing. We simulate this action by ensuring that those siblings are not
* filled, except if we know there are cards and we didn't find any non-sibling card. This way, the
* queue is not empty if it should not be empty (important for the conditional belows), but the
* front of the queue contains distinct card.
*/
// fill the queue with the current did
for (
cid in col.db.queryLongList(
"SELECT id FROM cards WHERE did = ? AND queue = " + Consts.QUEUE_TYPE_NEW + " AND " + idName + "!= ? ORDER BY due, ord LIMIT ?",
did,
id,
lim
)
) {
mNewQueue.add(cid)
}
if (!mNewQueue.isEmpty) {
// Note: libanki reverses mNewQueue and returns the last element in _getNewCard().
// AnkiDroid differs by leaving the queue intact and returning the *first* element
// in _getNewCard().
return true
}
}
// nothing left in the deck; move to next
mNewDids.remove()
}
if (mHaveCounts && mNewCount != 0) {
// if we didn't get a card but the count is non-zero,
// we need to check again for any cards that were
// removed from the queue but not buried
_resetNew()
return _fillNew(true)
}
return false
}
protected fun _getNewCard(): Card? {
return if (_fillNew()) {
// mNewCount -= 1; see decrementCounts()
mNewQueue.removeFirstCard()
} else null
}
private fun _updateNewCardRatio() {
if (col.get_config_int("newSpread") == Consts.NEW_CARDS_DISTRIBUTE) {
if (mNewCount != 0) {
mNewCardModulus = (mNewCount + mRevCount) / mNewCount
// if there are cards to review, ensure modulo >= 2
if (mRevCount != 0) {
mNewCardModulus = Math.max(2, mNewCardModulus)
}
return
}
}
mNewCardModulus = 0
}
/**
* @return True if it's time to display a new card when distributing.
*/
protected fun _timeForNewCard(): Boolean {
if (mHaveCounts && mNewCount == 0) {
return false
}
@NEW_CARD_ORDER val spread = col.get_config_int("newSpread")
return if (spread == Consts.NEW_CARDS_LAST) {
false
} else if (spread == Consts.NEW_CARDS_FIRST) {
true
} else if (mNewCardModulus != 0) {
// if the counter has not yet been reset, this value is
// random. This will occur only for the first card of review.
reps != 0 && reps % mNewCardModulus == 0
} else {
false
}
}
/**
*
* @param considerCurrentCard Whether current card should be counted if it is in this deck
*/
protected fun _deckNewLimit(did: Long, considerCurrentCard: Boolean): Int {
return _deckNewLimit(did, null, considerCurrentCard)
}
/**
*
* @param considerCurrentCard Whether current card should be counted if it is in this deck
*/
protected fun _deckNewLimit(did: Long, fn: LimitMethod?, considerCurrentCard: Boolean): Int {
@Suppress("NAME_SHADOWING") var fn = fn
if (fn == null) {
fn = LimitMethod { g: Deck -> _deckNewLimitSingle(g, considerCurrentCard) }
}
val decks = col.decks.parents(did).toMutableList()
decks.add(col.decks.get(did))
var lim = -1
// for the deck and each of its parents
var rem: Int
for (g in decks) {
rem = fn.operation(g)
lim = if (lim == -1) {
rem
} else {
Math.min(rem, lim)
}
}
return lim
}
/** New count for a single deck. */
fun _newForDeck(did: Long, lim: Int): Int {
@Suppress("NAME_SHADOWING") var lim = lim
if (lim == 0) {
return 0
}
lim = Math.min(lim, mReportLimit)
return col.db.queryScalar(
"SELECT count() FROM (SELECT 1 FROM cards WHERE did = ? AND queue = " + Consts.QUEUE_TYPE_NEW + " LIMIT ?)",
did, lim
)
}
/**
* Maximal number of new card still to see today in deck g. It's computed as:
* the number of new card to see by day according to the deck options
* minus the number of new cards seen today in deck d or a descendant
* plus the number of extra new cards to see today in deck d, a parent or a descendant.
*
* Limits of its ancestors are not applied.
* @param considerCurrentCard whether the current card should be taken from the limit (if it belongs to this deck)
*/
fun _deckNewLimitSingle(g: Deck, considerCurrentCard: Boolean): Int {
if (g.isDyn) {
return mDynReportLimit
}
val did = g.getLong("id")
val c = col.decks.confForDid(did)
var lim = Math.max(
0,
c.getJSONObject("new").getInt("perDay") - g.getJSONArray("newToday").getInt(1)
)
// The counts shown in the reviewer does not consider the current card. E.g. if it indicates 6 new card, it means, 6 new card including current card will be seen today.
// So currentCard does not have to be taken into consideration in this method
if (considerCurrentCard && currentCardIsInQueueWithDeck(Consts.QUEUE_TYPE_NEW, did)) {
lim--
}
return lim
}
/**
* Learning queues *********************************************************** ************************************
*/
private fun _updateLrnCutoff(force: Boolean): Boolean {
val nextCutoff = time.intTime() + col.get_config_int("collapseTime")
if (nextCutoff - mLrnCutoff > 60 || force) {
mLrnCutoff = nextCutoff
return true
}
return false
}
private fun _maybeResetLrn(force: Boolean) {
if (_updateLrnCutoff(force)) {
_resetLrn()
}
}
// Overridden: V1 has less queues
protected open fun _resetLrnCount() {
_resetLrnCount(null)
}
protected open fun _resetLrnCount(cancelListener: CancelListener?) {
_updateLrnCutoff(true)
// sub-day
mLrnCount = col.db.queryScalar(
"SELECT count() FROM cards WHERE did IN " + _deckLimit() +
" AND queue = " + Consts.QUEUE_TYPE_LRN + " AND id != ? AND due < ?",
currentCardId(),
mLrnCutoff
)
if (isCancelled(cancelListener)) return
// day
mLrnCount += col.db.queryScalar(
"SELECT count() FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_DAY_LEARN_RELEARN + " AND due <= ? AND id != ?",
mToday!!, currentCardId()
)
if (isCancelled(cancelListener)) return
// previews
mLrnCount += col.db.queryScalar(
"SELECT count() FROM cards WHERE did IN " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_PREVIEW + " AND id != ? ",
currentCardId()
)
}
// Overridden: _updateLrnCutoff not called in V1
protected fun _resetLrn() {
_resetLrnCount()
_resetLrnQueue()
}
protected open fun _resetLrnQueue() {
mLrnQueue.clear()
mLrnDayQueue.clear()
mLrnDids = col.decks.active()
}
// sub-day learning
// Overridden: a single kind of queue in V1
protected open fun _fillLrn(): Boolean {
if (mHaveCounts && mLrnCount == 0) {
return false
}
if (!mLrnQueue.isEmpty) {
return true
}
val cutoff = time.intTime() + col.get_config_long("collapseTime")
mLrnQueue.clear()
col
.db
.query(
"SELECT due, id FROM cards WHERE did IN " + _deckLimit() + " AND queue IN (" + Consts.QUEUE_TYPE_LRN + ", " + Consts.QUEUE_TYPE_PREVIEW + ") AND due < ?" +
" AND id != ? LIMIT ?",
cutoff, currentCardId(), mReportLimit
).use { cur ->
mLrnQueue.setFilled()
while (cur.moveToNext()) {
mLrnQueue.add(cur.getLong(0), cur.getLong(1))
}
// as it arrives sorted by did first, we need to sort it
mLrnQueue.sort()
return !mLrnQueue.isEmpty
}
}
// Overridden: no _maybeResetLrn in V1
protected open fun _getLrnCard(collapse: Boolean): Card? {
_maybeResetLrn(collapse && mLrnCount == 0)
if (_fillLrn()) {
var cutoff = time.intTime()
if (collapse) {
cutoff += col.get_config_int("collapseTime").toLong()
}
if (mLrnQueue.firstDue < cutoff) {
return mLrnQueue.removeFirstCard()
// mLrnCount -= 1; see decrementCounts()
}
}
return null
}
protected fun _preloadLrnCard(collapse: Boolean): Boolean {
_maybeResetLrn(collapse && mLrnCount == 0)
if (_fillLrn()) {
var cutoff = time.intTime()
if (collapse) {
cutoff += col.get_config_int("collapseTime").toLong()
}
// mLrnCount -= 1; see decrementCounts()
return mLrnQueue.firstDue < cutoff
}
return false
}
// daily learning
protected fun _fillLrnDay(): Boolean {
if (mHaveCounts && mLrnCount == 0) {
return false
}
if (!mLrnDayQueue.isEmpty) {
return true
}
while (!mLrnDids.isEmpty()) {
val did = mLrnDids.first
// fill the queue with the current did
mLrnDayQueue.clear()
/* Difference with upstream:
* Current card can't come in the queue.
*
* In standard usage, a card is not requested before
* the previous card is marked as reviewed. However,
* if we decide to query a second card sooner, we
* don't want to get the same card a second time. This
* simulate _getLrnDayCard which did remove the card
* from the queue.
*/for (
cid in col.db.queryLongList(
"SELECT id FROM cards WHERE did = ? AND queue = " + Consts.QUEUE_TYPE_DAY_LEARN_RELEARN + " AND due <= ? and id != ? LIMIT ?",
did, mToday!!, currentCardId(), mQueueLimit
)
) {
mLrnDayQueue.add(cid)
}
if (!mLrnDayQueue.isEmpty) {
// order
@KotlinCleanup(".apply { }")
val r = Random()
r.setSeed(mToday!!.toLong())
mLrnDayQueue.shuffle(r)
// is the current did empty?
if (mLrnDayQueue.size() < mQueueLimit) {
mLrnDids.remove()
}
return true
}
// nothing left in the deck; move to next
mLrnDids.remove()
}
return false
}
protected fun _getLrnDayCard(): Card? {
return if (_fillLrnDay()) {
// mLrnCount -= 1; see decrementCounts()
mLrnDayQueue.removeFirstCard()
} else null
}
// Overridden
protected open fun _answerLrnCard(card: Card, @BUTTON_TYPE ease: Int) {
val conf = _lrnConf(card)
@REVLOG_TYPE val type: Int
type =
if (card.type == Consts.CARD_TYPE_REV || card.type == Consts.CARD_TYPE_RELEARNING) {
Consts.REVLOG_RELRN
} else {
Consts.REVLOG_LRN
}
// lrnCount was decremented once when card was fetched
val lastLeft = card.left
var leaving = false
// immediate graduate?
if (ease == Consts.BUTTON_FOUR) {
_rescheduleAsRev(card, conf, true)
leaving = true
// next step?
} else if (ease == Consts.BUTTON_THREE) {
// graduation time?
if (card.left % 1000 - 1 <= 0) {
_rescheduleAsRev(card, conf, false)
leaving = true
} else {
_moveToNextStep(card, conf)
}
} else if (ease == Consts.BUTTON_TWO) {
_repeatStep(card, conf)
} else {
// move back to first step
_moveToFirstStep(card, conf)
}
_logLrn(card, ease, conf, leaving, type, lastLeft)
}
protected fun _updateRevIvlOnFail(card: Card, conf: JSONObject) {
card.lastIvl = card.ivl
card.ivl = _lapseIvl(card, conf)
}
private fun _moveToFirstStep(card: Card, conf: JSONObject): Int {
card.left = _startingLeft(card)
// relearning card?
if (card.type == Consts.CARD_TYPE_RELEARNING) {
_updateRevIvlOnFail(card, conf)
}
return _rescheduleLrnCard(card, conf)
}
private fun _moveToNextStep(card: Card, conf: JSONObject) {
// decrement real left count and recalculate left today
val left = card.left % 1000 - 1
card.left = _leftToday(conf.getJSONArray("delays"), left) * 1000 + left
_rescheduleLrnCard(card, conf)
}
private fun _repeatStep(card: Card, conf: JSONObject) {
val delay = _delayForRepeatingGrade(conf, card.left)
_rescheduleLrnCard(card, conf, delay)
}
private fun _rescheduleLrnCard(card: Card, conf: JSONObject, delay: Int? = null): Int {
// normal delay for the current step?
@Suppress("NAME_SHADOWING") var delay = delay
if (delay == null) {
delay = _delayForGrade(conf, card.left)
}
card.due = time.intTime() + delay
// due today?
if (card.due < dayCutoff) {
// Add some randomness, up to 5 minutes or 25%
val maxExtra = Math.min(300, (delay * 0.25).toInt())
val fuzz = Random().nextInt(Math.max(maxExtra, 1))
card.due = Math.min(dayCutoff - 1, card.due + fuzz)
card.queue = Consts.QUEUE_TYPE_LRN
if (card.due < time.intTime() + col.get_config_int("collapseTime")) {
mLrnCount += 1
// if the queue is not empty and there's nothing else to do, make
// sure we don't put it at the head of the queue and end up showing
// it twice in a row
if (!mLrnQueue.isEmpty && revCount() == 0 && newCount() == 0) {
val smallestDue = mLrnQueue.firstDue
card.due = Math.max(card.due, smallestDue + 1)
}
_sortIntoLrn(card.due, card.id)
}
} else {
// the card is due in one or more days, so we need to use the day learn queue
val ahead = (card.due - dayCutoff) / Stats.SECONDS_PER_DAY + 1
card.due = mToday!! + ahead
card.queue = Consts.QUEUE_TYPE_DAY_LEARN_RELEARN
}
return delay
}
protected fun _delayForGrade(conf: JSONObject, left: Int): Int {
@Suppress("NAME_SHADOWING") var left = left
left = left % 1000
return try {
val delay: Double
val delays = conf.getJSONArray("delays")
val len = delays.length()
delay = try {
delays.getDouble(len - left)
} catch (e: JSONException) {
Timber.w(e)
if (conf.getJSONArray("delays").length() > 0) {
conf.getJSONArray("delays").getDouble(0)
} else {
// user deleted final step; use dummy value
1.0
}
}
(delay * 60.0).toInt()
} catch (e: JSONException) {
throw RuntimeException(e)
}
}
private fun _delayForRepeatingGrade(conf: JSONObject, left: Int): Int {
// halfway between last and next
val delay1 = _delayForGrade(conf, left)
val delay2: Int
delay2 = if (conf.getJSONArray("delays").length() > 1) {
_delayForGrade(conf, left - 1)
} else {
delay1 * 2
}
return (delay1 + Math.max(delay1, delay2)) / 2
}
// Overridden: RELEARNING does not exists in V1
protected open fun _lrnConf(card: Card): JSONObject {
return if (card.type == Consts.CARD_TYPE_REV || card.type == Consts.CARD_TYPE_RELEARNING) {
_lapseConf(card)
} else {
_newConf(card)
}
}
// Overridden
protected open fun _rescheduleAsRev(card: Card, conf: JSONObject, early: Boolean) {
val lapse = card.type == Consts.CARD_TYPE_REV || card.type == Consts.CARD_TYPE_RELEARNING
if (lapse) {
_rescheduleGraduatingLapse(card, early)
} else {
_rescheduleNew(card, conf, early)
}
// if we were dynamic, graduating means moving back to the old deck
if (card.isInDynamicDeck) {
_removeFromFiltered(card)
}
}
private fun _rescheduleGraduatingLapse(card: Card, early: Boolean) {
if (early) {
card.ivl = card.ivl + 1
}
card.apply {
due = (mToday!! + card.ivl).toLong()
queue = Consts.QUEUE_TYPE_REV
type = Consts.CARD_TYPE_REV
}
}
// Overridden: V1 has type rev for relearning
protected open fun _startingLeft(card: Card): Int {
val conf: JSONObject
conf = if (card.type == Consts.CARD_TYPE_RELEARNING) {
_lapseConf(card)
} else {
_lrnConf(card)
}
val tot = conf.getJSONArray("delays").length()
val tod = _leftToday(conf.getJSONArray("delays"), tot)
return tot + tod * 1000
}
/** the number of steps that can be completed by the day cutoff */
protected fun _leftToday(delays: JSONArray, left: Int): Int {
return _leftToday(delays, left, 0)
}
private fun _leftToday(delays: JSONArray, left: Int, now: Long): Int {
@Suppress("NAME_SHADOWING") var now = now
if (now == 0L) {
now = time.intTime()
}
var ok = 0
val offset = Math.min(left, delays.length())
for (i in 0 until offset) {
now += (delays.getDouble(delays.length() - offset + i) * 60.0).toInt().toLong()
if (now > dayCutoff) {
break
}
ok = i
}
return ok + 1
}
protected fun _graduatingIvl(card: Card, conf: JSONObject, early: Boolean): Int {
return _graduatingIvl(card, conf, early, true)
}
private fun _graduatingIvl(card: Card, conf: JSONObject, early: Boolean, fuzz: Boolean): Int {
if (card.type == Consts.CARD_TYPE_REV || card.type == Consts.CARD_TYPE_RELEARNING) {
val bonus = if (early) 1 else 0
return card.ivl + bonus
}
var ideal: Int
val ints = conf.getJSONArray("ints")
ideal = if (!early) {
// graduate
ints.getInt(0)
} else {
// early remove
ints.getInt(1)
}
if (fuzz) {
ideal = _fuzzedIvl(ideal)
}
return ideal
}
/** Reschedule a new card that's graduated for the first time.
* Overridden: V1 does not set type and queue */
private fun _rescheduleNew(card: Card, conf: JSONObject, early: Boolean) {
card.apply {
ivl = _graduatingIvl(card, conf, early)
due = (mToday!! + card.ivl).toLong()
factor = conf.getInt("initialFactor")
type = Consts.CARD_TYPE_REV
queue = Consts.QUEUE_TYPE_REV
}
}
protected fun _logLrn(
card: Card,
@BUTTON_TYPE ease: Int,
conf: JSONObject,
leaving: Boolean,
@REVLOG_TYPE type: Int,
lastLeft: Int
) {
val lastIvl = -_delayForGrade(conf, lastLeft)
val ivl = if (leaving) card.ivl else -_delayForGrade(conf, card.left)
log(card.id, col.usn(), ease, ivl, lastIvl, card.factor, card.timeTaken(), type)
}
protected fun log(
id: Long,
usn: Int,
@BUTTON_TYPE ease: Int,
ivl: Int,
lastIvl: Int,
factor: Int,
timeTaken: Int,
@REVLOG_TYPE type: Int
) {
try {
col.db.execute(
"INSERT INTO revlog VALUES (?,?,?,?,?,?,?,?,?)",
time.intTimeMS(), id, usn, ease, ivl, lastIvl, factor, timeTaken, type
)
} catch (e: SQLiteConstraintException) {
Timber.w(e)
try {
Thread.sleep(10)
} catch (e1: InterruptedException) {
throw RuntimeException(e1)
}
log(id, usn, ease, ivl, lastIvl, factor, timeTaken, type)
}
}
// Overridden: uses left/1000 in V1
private fun _lrnForDeck(did: Long): Int {
return try {
val cnt = col.db.queryScalar(
"SELECT count() FROM (SELECT null FROM cards WHERE did = ?" +
" AND queue = " + Consts.QUEUE_TYPE_LRN + " AND due < ?" +
" LIMIT ?)",
did, time.intTime() + col.get_config_int("collapseTime"), mReportLimit
)
cnt + col.db.queryScalar(
"SELECT count() FROM (SELECT null FROM cards WHERE did = ?" +
" AND queue = " + Consts.QUEUE_TYPE_DAY_LEARN_RELEARN + " AND due <= ?" +
" LIMIT ?)",
did, mToday!!, mReportLimit
)
} catch (e: SQLException) {
throw RuntimeException(e)
}
}
/*
Reviews ****************************************************************** *****************************
*/
/**
* Maximal number of rev card still to see today in current deck. It's computed as:
* the number of rev card to see by day according to the deck options
* minus the number of rev cards seen today in this deck or a descendant
* plus the number of extra cards to see today in this deck, a parent or a descendant.
*
* Respects the limits of its ancestor. Current card is treated the same way as other cards.
* @param considerCurrentCard whether the current card should be taken from the limit (if it belongs to this deck)
*/
private fun _currentRevLimit(considerCurrentCard: Boolean): Int {
val d = col.decks.get(col.decks.selected(), false)
return _deckRevLimitSingle(d, considerCurrentCard)
}
/**
* Maximal number of rev card still to see today in deck d. It's computed as:
* the number of rev card to see by day according to the deck options
* minus the number of rev cards seen today in deck d or a descendant
* plus the number of extra cards to see today in deck d, a parent or a descendant.
*
* Respects the limits of its ancestor
* Overridden: V1 does not consider parents limit
* @param considerCurrentCard whether the current card should be taken from the limit (if it belongs to this deck)
*/
protected open fun _deckRevLimitSingle(d: Deck?, considerCurrentCard: Boolean): Int {
return _deckRevLimitSingle(d, null, considerCurrentCard)
}
/**
* Maximal number of rev card still to see today in deck d. It's computed as:
* the number of rev card to see by day according to the deck options
* minus the number of rev cards seen today in deck d or a descendant
* plus the number of extra cards to see today in deck d, a parent or a descendant.
*
* Respects the limits of its ancestor, either given as parentLimit, or through direct computation.
* @param parentLimit Limit of the parent, this is an upper bound on the limit of this deck
* @param considerCurrentCard whether the current card should be taken from the limit (if it belongs to this deck)
*/
@KotlinCleanup("remove unused parameter")
private fun _deckRevLimitSingle(
d: Deck?,
@Suppress("UNUSED_PARAMETER") parentLimit: Int?,
considerCurrentCard: Boolean
): Int {
// invalid deck selected?
if (d == null) {
return 0
}
if (d.isDyn) {
return mDynReportLimit
}
val did = d.getLong("id")
val c = col.decks.confForDid(did)
var lim = Math.max(
0,
c.getJSONObject("rev").getInt("perDay") - d.getJSONArray("revToday").getInt(1)
)
// The counts shown in the reviewer does not consider the current card. E.g. if it indicates 6 rev card, it means, 6 rev card including current card will be seen today.
// So currentCard does not have to be taken into consideration in this method
if (considerCurrentCard && currentCardIsInQueueWithDeck(Consts.QUEUE_TYPE_REV, did)) {
lim--
}
return lim
}
protected fun _revForDeck(did: Long, lim: Int, childMap: Decks.Node): Int {
@Suppress("NAME_SHADOWING") var lim = lim
val dids = col.decks.childDids(did, childMap).toMutableList()
dids.add(0, did)
lim = Math.min(lim, mReportLimit)
return col.db.queryScalar(
"SELECT count() FROM (SELECT 1 FROM cards WHERE did in " + Utils.ids2str(dids) + " AND queue = " + Consts.QUEUE_TYPE_REV + " AND due <= ? LIMIT ?)",
mToday!!, lim
)
}
// Overridden: V1 uses _walkingCount
@KotlinCleanup("see if the two versions of this function can be combined")
protected open fun _resetRevCount() {
_resetRevCount(null)
}
protected open fun _resetRevCount(cancelListener: CancelListener?) {
val lim = _currentRevLimit(true)
if (isCancelled(cancelListener)) return
mRevCount = col.db.queryScalar(
"SELECT count() FROM (SELECT id FROM cards WHERE did in " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_REV + " AND due <= ? AND id != ? LIMIT ?)",
mToday!!, currentCardId(), lim
)
}
// Overridden: V1 remove clear
protected fun _resetRev() {
_resetRevCount()
_resetRevQueue()
}
protected open fun _resetRevQueue() {
mRevQueue.clear()
}
protected fun _fillRev(): Boolean {
return _fillRev(false)
}
// Override: V1 loops over dids
protected open fun _fillRev(allowSibling: Boolean): Boolean {
if (!mRevQueue.isEmpty) {
return true
}
if (mHaveCounts && mRevCount == 0) {
return false
}
val lim = Math.min(mQueueLimit, _currentRevLimit(true))
if (lim != 0) {
mRevQueue.clear()
// fill the queue with the current did
val idName = if (allowSibling) "id" else "nid"
val id = if (allowSibling) currentCardId() else currentCardNid()
col.db.query(
"SELECT id FROM cards WHERE did in " + _deckLimit() + " AND queue = " + Consts.QUEUE_TYPE_REV + " AND due <= ? AND " + idName + " != ?" +
" ORDER BY due, random() LIMIT ?",
mToday!!, id, lim
).use { cur ->
while (cur.moveToNext()) {
mRevQueue.add(cur.getLong(0))
}
}
if (!mRevQueue.isEmpty) {
// preserve order
// Note: libanki reverses mRevQueue and returns the last element in _getRevCard().
// AnkiDroid differs by leaving the queue intact and returning the *first* element
// in _getRevCard().
return true
}
}
if (mHaveCounts && mRevCount != 0) {
// if we didn't get a card but the count is non-zero,
// we need to check again for any cards that were
// removed from the queue but not buried
_resetRev()
return _fillRev(true)
}
return false
}
protected fun _getRevCard(): Card? {
return if (_fillRev()) {
// mRevCount -= 1; see decrementCounts()
mRevQueue.removeFirstCard()
} else {
null
}
}
/**
* Answering a review card **************************************************
* *********************************************
*/
// Overridden: v1 does not deal with early
protected open fun _answerRevCard(card: Card, @BUTTON_TYPE ease: Int) {
var delay = 0
val early = card.isInDynamicDeck && card.oDue > mToday!!
val type = if (early) 3 else 1
if (ease == Consts.BUTTON_ONE) {
delay = _rescheduleLapse(card)
} else {
_rescheduleRev(card, ease, early)
}
_logRev(card, ease, delay, type)
}
// Overridden
protected open fun _rescheduleLapse(card: Card): Int {
val conf = _lapseConf(card)
card.lapses = card.lapses + 1
card.factor = Math.max(1300, card.factor - 200)
val delay: Int
val suspended = _checkLeech(card, conf) && card.queue == Consts.QUEUE_TYPE_SUSPENDED
if (conf.getJSONArray("delays").length() != 0 && !suspended) {
card.type = Consts.CARD_TYPE_RELEARNING
delay = _moveToFirstStep(card, conf)
} else {
// no relearning steps
_updateRevIvlOnFail(card, conf)
_rescheduleAsRev(card, conf, false)
// need to reset the queue after rescheduling
if (suspended) {
card.queue = Consts.QUEUE_TYPE_SUSPENDED
}
delay = 0
}
return delay
}
private fun _lapseIvl(card: Card, conf: JSONObject): Int {
return Math.max(
1,
Math.max(conf.getInt("minInt"), (card.ivl * conf.getDouble("mult")).toInt())
)
}
protected fun _rescheduleRev(card: Card, @BUTTON_TYPE ease: Int, early: Boolean) {
// update interval
card.lastIvl = card.ivl
if (early) {
_updateEarlyRevIvl(card, ease)
} else {
_updateRevIvl(card, ease)
}
// then the rest
card.factor = Math.max(1300, card.factor + FACTOR_ADDITION_VALUES[ease - 2])
card.due = (mToday!! + card.ivl).toLong()
// card leaves filtered deck
_removeFromFiltered(card)
}
protected fun _logRev(card: Card, @BUTTON_TYPE ease: Int, delay: Int, type: Int) {
log(
card.id, col.usn(), ease, if (delay != 0) -delay else card.ivl, card.lastIvl,
card.factor, card.timeTaken(), type
)
}
/*
Interval management ******************************************************
*****************************************
*/
/**
* Next interval for CARD, given EASE.
*/
protected fun _nextRevIvl(card: Card, @BUTTON_TYPE ease: Int, fuzz: Boolean): Int {
val delay = _daysLate(card)
val conf = _revConf(card)
val fct = card.factor / 1000.0
val hardFactor = conf.optDouble("hardFactor", 1.2)
val hardMin: Int
hardMin = if (hardFactor > 1) {
card.ivl
} else {
0
}
val ivl2 = _constrainedIvl(card.ivl * hardFactor, conf, hardMin.toDouble(), fuzz)
if (ease == Consts.BUTTON_TWO) {
return ivl2
}
val ivl3 = _constrainedIvl((card.ivl + delay / 2) * fct, conf, ivl2.toDouble(), fuzz)
return if (ease == Consts.BUTTON_THREE) {
ivl3
} else _constrainedIvl(
(card.ivl + delay) * fct * conf.getDouble("ease4"),
conf,
ivl3.toDouble(),
fuzz
)
}
fun _fuzzedIvl(ivl: Int): Int {
val minMax = _fuzzIvlRange(ivl)
// Anki's python uses random.randint(a, b) which returns x in [a, b] while the eq Random().nextInt(a, b)
// returns x in [0, b-a), hence the +1 diff with libanki
return Random().nextInt(minMax.second - minMax.first + 1) + minMax.first
}
protected fun _constrainedIvl(ivl: Double, conf: JSONObject, prev: Double, fuzz: Boolean): Int {
var newIvl = (ivl * conf.optDouble("ivlFct", 1.0)).toInt()
if (fuzz) {
newIvl = _fuzzedIvl(newIvl)
}
newIvl = Math.max(Math.max(newIvl.toDouble(), prev + 1), 1.0).toInt()
newIvl = Math.min(newIvl, conf.getInt("maxIvl"))
return newIvl
}
/**
* Number of days later than scheduled.
*/
protected fun _daysLate(card: Card): Long {
val due = if (card.isInDynamicDeck) card.oDue else card.due
return Math.max(0, mToday!! - due)
}
// Overridden
protected open fun _updateRevIvl(card: Card, @BUTTON_TYPE ease: Int) {
card.ivl = _nextRevIvl(card, ease, true)
}
private fun _updateEarlyRevIvl(card: Card, @BUTTON_TYPE ease: Int) {
card.ivl = _earlyReviewIvl(card, ease)
}
/** next interval for card when answered early+correctly */
private fun _earlyReviewIvl(card: Card, @BUTTON_TYPE ease: Int): Int {
if (!card.isInDynamicDeck || card.type != Consts.CARD_TYPE_REV || card.factor == 0) {
throw RuntimeException("Unexpected card parameters")
}
if (ease <= 1) {
throw RuntimeException("Ease must be greater than 1")
}
val elapsed = card.ivl - (card.oDue - mToday!!)
val conf = _revConf(card)
var easyBonus = 1.0
// early 3/4 reviews shouldn't decrease previous interval
var minNewIvl = 1.0
val factor: Double
if (ease == Consts.BUTTON_TWO) {
factor = conf.optDouble("hardFactor", 1.2)
// hard cards shouldn't have their interval decreased by more than 50%
// of the normal factor
minNewIvl = factor / 2
} else if (ease == 3) {
factor = card.factor / 1000.0
} else { // ease == 4
factor = card.factor / 1000.0
val ease4 = conf.getDouble("ease4")
// 1.3 -> 1.15
easyBonus = ease4 - (ease4 - 1) / 2
}
var ivl = Math.max(elapsed * factor, 1.0)
// cap interval decreases
ivl = Math.max(card.ivl * minNewIvl, ivl) * easyBonus
return _constrainedIvl(ivl, conf, 0.0, false)
}
/*
Dynamic deck handling ******************************************************************
*****************************
*/
override fun rebuildDyn(did: Long) {
if (!BackendFactory.defaultLegacySchema) {
super.rebuildDyn(did)
return
}
val deck = col.decks.get(did)
if (deck.isStd) {
Timber.e("error: deck is not a filtered deck")
return
}
// move any existing cards back first, then fill
emptyDyn(did)
val cnt = _fillDyn(deck)
if (cnt == 0) {
return
}
// and change to our new deck
col.decks.select(did)
}
/**
* Whether the filtered deck is empty
* Overridden
*/
private fun _fillDyn(deck: Deck): Int {
val start = -100000
var total = 0
var ids: List<Long?>
val terms = deck.getJSONArray("terms")
for (term in terms.jsonArrayIterable()) {
var search = term.getString(0)
val limit = term.getInt(1)
val order = term.getInt(2)
val orderLimit = _dynOrder(order, limit)
if (!TextUtils.isEmpty(search.trim { it <= ' ' })) {
search = String.format(Locale.US, "(%s)", search)
}
search = String.format(Locale.US, "%s -is:suspended -is:buried -deck:filtered", search)
ids = col.findCards(search, AfterSqlOrderBy(orderLimit))
if (ids.isEmpty()) {
return total
}
// move the cards over
col.log(deck.getLong("id"), ids)
_moveToDyn(deck.getLong("id"), ids, start + total)
total += ids.size
}
return total
}
override fun emptyDyn(did: Long) {
if (!BackendFactory.defaultLegacySchema) {
super.emptyDyn(did)
return
}
emptyDyn("did = $did")
}
/**
* Generates the required SQL for order by and limit clauses, for dynamic decks.
*
* @param o deck["order"]
* @param l deck["limit"]
* @return The generated SQL to be suffixed to "select ... from ... order by "
*/
protected fun _dynOrder(@DYN_PRIORITY o: Int, l: Int): String {
val t: String
t = when (o) {
Consts.DYN_OLDEST -> "c.mod"
Consts.DYN_RANDOM -> "random()"
Consts.DYN_SMALLINT -> "ivl"
Consts.DYN_BIGINT -> "ivl desc"
Consts.DYN_LAPSES -> "lapses desc"
Consts.DYN_ADDED -> "n.id"
Consts.DYN_REVADDED -> "n.id desc"
Consts.DYN_DUEPRIORITY -> String.format(
Locale.US,
"(case when queue=" + Consts.QUEUE_TYPE_REV + " and due <= %d then (ivl / cast(%d-due+0.001 as real)) else 100000+due end)",
mToday, mToday
)
Consts.DYN_DUE -> // if we don't understand the term, default to due order
"c.due"
else -> "c.due"
}
return "$t limit $l"
}
protected fun _moveToDyn(did: Long, ids: List<Long?>, start: Int) {
val deck = col.decks.get(did)
val data = ArrayList<Array<Any?>>(ids.size)
val u = col.usn()
var due = start
for (id in ids) {
data.add(
arrayOf(
did, due, u, id
)
)
due += 1
}
var queue = ""
if (!deck.getBoolean("resched")) {
queue = ", queue = " + Consts.QUEUE_TYPE_REV + ""
}
col.db.executeMany(
"UPDATE cards SET odid = did, " +
"odue = due, did = ?, due = (case when due <= 0 then due else ? end), usn = ? " + queue + " WHERE id = ?",
data
)
}
private fun _removeFromFiltered(card: Card) {
if (card.isInDynamicDeck) {
card.did = card.oDid
card.oDue = 0
card.oDid = 0
}
}
private fun _restorePreviewCard(card: Card) {
if (!card.isInDynamicDeck) {
throw RuntimeException("ODid wasn't set")
}
card.due = card.oDue
// learning and relearning cards may be seconds-based or day-based;
// other types map directly to queues
if (card.type == Consts.CARD_TYPE_LRN || card.type == Consts.CARD_TYPE_RELEARNING) {
if (card.oDue > 1000000000) {
card.queue = Consts.QUEUE_TYPE_LRN
} else {
card.queue = Consts.QUEUE_TYPE_DAY_LEARN_RELEARN
}
} else {
card.queue = card.type
}
}
/*
Leeches ****************************************************************** *****************************
*/
/** Leech handler. True if card was a leech.
* Overridden: in V1, due and did are changed */
protected open fun _checkLeech(card: Card, conf: JSONObject): Boolean {
val lf = conf.getInt("leechFails")
if (lf == 0) {
return false
}
// if over threshold or every half threshold reps after that
if (card.lapses >= lf && (card.lapses - lf) % Math.max(lf / 2, 1) == 0) {
// add a leech tag
val n = card.note()
n.addTag("leech")
n.flush()
// handle
if (conf.getInt("leechAction") == Consts.LEECH_SUSPEND) {
card.queue = Consts.QUEUE_TYPE_SUSPENDED
}
// notify UI
if (mContextReference != null) {
val context = mContextReference!!.get()
leech(card, context)
}
return true
}
return false
}
/**
* Tools ******************************************************************** ***************************
*/
// Overridden: different delays for filtered cards.
protected open fun _newConf(card: Card): JSONObject {
val conf = _cardConf(card)
if (!card.isInDynamicDeck) {
return conf.getJSONObject("new")
}
// dynamic deck; override some attributes, use original deck for others
val oconf = col.decks.confForDid(card.oDid)
return JSONObject().apply {
// original deck
put("ints", oconf.getJSONObject("new").getJSONArray("ints"))
put("initialFactor", oconf.getJSONObject("new").getInt("initialFactor"))
put("bury", oconf.getJSONObject("new").optBoolean("bury", true))
put("delays", oconf.getJSONObject("new").getJSONArray("delays"))
// overrides
put("separate", conf.getBoolean("separate"))
put("order", Consts.NEW_CARDS_DUE)
put("perDay", mReportLimit)
}
}
// Overridden: different delays for filtered cards.
protected open fun _lapseConf(card: Card): JSONObject {
val conf = _cardConf(card)
if (!card.isInDynamicDeck) {
return conf.getJSONObject("lapse")
}
// dynamic deck; override some attributes, use original deck for others
val oconf = col.decks.confForDid(card.oDid)
return JSONObject().apply {
// original deck
put("minInt", oconf.getJSONObject("lapse").getInt("minInt"))
put("leechFails", oconf.getJSONObject("lapse").getInt("leechFails"))
put("leechAction", oconf.getJSONObject("lapse").getInt("leechAction"))
put("mult", oconf.getJSONObject("lapse").getDouble("mult"))
put("delays", oconf.getJSONObject("lapse").getJSONArray("delays"))
// overrides
put("resched", conf.getBoolean("resched"))
}
}
protected fun _revConf(card: Card): JSONObject {
val conf = _cardConf(card)
return if (!card.isInDynamicDeck) {
conf.getJSONObject("rev")
} else col.decks.confForDid(card.oDid).getJSONObject("rev")
}
private fun _previewingCard(card: Card): Boolean {
val conf = _cardConf(card)
return conf.isDyn && !conf.getBoolean("resched")
}
private fun _previewDelay(card: Card): Int {
return _cardConf(card).optInt("previewDelay", 10) * 60
}
/**
* Daily cutoff ************************************************************* **********************************
* This function uses GregorianCalendar so as to be sensitive to leap years, daylight savings, etc.
*/
/* Overridden: other way to count time*/
open fun _updateCutoff() {
val oldToday = if (mToday == null) 0 else mToday!!
val timing = _timingToday()
mToday = timing.daysElapsed
dayCutoff = timing.nextDayAt
if (oldToday != mToday) {
col.log(mToday, dayCutoff)
}
// update all daily counts, but don't save decks to prevent needless conflicts. we'll save on card answer
// instead
for (deck in col.decks.all()) {
update(deck)
}
// unbury if the day has rolled over
val unburied: Int = @Suppress("USELESS_CAST") col.get_config("lastUnburied", 0 as Int)!!
if (unburied < mToday!!) {
SyncStatus.ignoreDatabaseModification { unburyCards() }
col.set_config("lastUnburied", mToday)
}
}
protected fun update(g: Deck) {
for (t in arrayOf("new", "rev", "lrn", "time")) {
val key = t + "Today"
val tToday = g.getJSONArray(key)
if (g.getJSONArray(key).getInt(0) != mToday) {
tToday.put(0, mToday!!)
tToday.put(1, 0)
}
}
}
fun _checkDay() {
// check if the day has rolled over
if (time.intTime() > dayCutoff) {
reset()
}
}
/** true if there are cards in learning, with review due the same
* day, in the selected decks. */
/* not in upstream anki. As revDue and newDue, it's used to check
* what to do when a deck is selected in deck picker. When this
* method is called, we already know that no cards is due
* immediately. It answers whether cards will be due later in the
* same deck. */
override fun hasCardsTodayAfterStudyAheadLimit(): Boolean {
return if (!BackendFactory.defaultLegacySchema) {
super.hasCardsTodayAfterStudyAheadLimit()
} else col.db.queryScalar(
"SELECT 1 FROM cards WHERE did IN " + _deckLimit() +
" AND queue = " + Consts.QUEUE_TYPE_LRN + " LIMIT 1"
) != 0
}
fun haveBuriedSiblings(): Boolean {
return haveBuriedSiblings(col.decks.active())
}
private fun haveBuriedSiblings(allDecks: List<Long>): Boolean {
// Refactored to allow querying an arbitrary deck
val sdids = Utils.ids2str(allDecks)
val cnt = col.db.queryScalar(
"select 1 from cards where queue = " + Consts.QUEUE_TYPE_SIBLING_BURIED + " and did in " + sdids + " limit 1"
)
return cnt != 0
}
fun haveManuallyBuried(): Boolean {
return haveManuallyBuried(col.decks.active())
}
private fun haveManuallyBuried(allDecks: List<Long>): Boolean {
// Refactored to allow querying an arbitrary deck
val sdids = Utils.ids2str(allDecks)
val cnt = col.db.queryScalar(
"select 1 from cards where queue = " + Consts.QUEUE_TYPE_MANUALLY_BURIED + " and did in " + sdids + " limit 1"
)
return cnt != 0
}
override fun haveBuried(): Boolean {
return if (!BackendFactory.defaultLegacySchema) {
super.haveBuried()
} else haveManuallyBuried() || haveBuriedSiblings()
}
/*
Next time reports ********************************************************
***************************************
*/
/**
* Return the next interval for CARD, in seconds.
*/
// Overridden
override fun nextIvl(card: Card, @BUTTON_TYPE ease: Int): Long {
// preview mode?
if (_previewingCard(card)) {
return if (ease == Consts.BUTTON_ONE) {
_previewDelay(card).toLong()
} else 0
}
// (re)learning?
return if (card.queue == Consts.QUEUE_TYPE_NEW || card.queue == Consts.QUEUE_TYPE_LRN || card.queue == Consts.QUEUE_TYPE_DAY_LEARN_RELEARN) {
_nextLrnIvl(card, ease)
} else if (ease == Consts.BUTTON_ONE) {
// lapse
val conf = _lapseConf(card)
if (conf.getJSONArray("delays").length() > 0) {
(conf.getJSONArray("delays").getDouble(0) * 60.0).toLong()
} else _lapseIvl(card, conf) * Stats.SECONDS_PER_DAY
} else {
// review
val early = card.isInDynamicDeck && card.oDue > mToday!!
if (early) {
_earlyReviewIvl(card, ease) * Stats.SECONDS_PER_DAY
} else {
_nextRevIvl(card, ease, false) * Stats.SECONDS_PER_DAY
}
}
}
// this isn't easily extracted from the learn code
// Overridden
protected open fun _nextLrnIvl(card: Card, @BUTTON_TYPE ease: Int): Long {
if (card.queue == Consts.QUEUE_TYPE_NEW) {
card.left = _startingLeft(card)
}
val conf = _lrnConf(card)
return if (ease == Consts.BUTTON_ONE) {
// fail
_delayForGrade(conf, conf.getJSONArray("delays").length()).toLong()
} else if (ease == Consts.BUTTON_TWO) {
_delayForRepeatingGrade(conf, card.left).toLong()
} else if (ease == Consts.BUTTON_FOUR) {
_graduatingIvl(
card,
conf,
true,
false
) * Stats.SECONDS_PER_DAY
} else { // ease == 3
val left = card.left % 1000 - 1
if (left <= 0) {
// graduate
_graduatingIvl(
card,
conf,
false,
false
) * Stats.SECONDS_PER_DAY
} else {
_delayForGrade(conf, left).toLong()
}
}
}
/*
Suspending & burying ********************************************************** ********************************
*/
/**
* learning and relearning cards may be seconds-based or day-based;
* other types map directly to queues
*
* Overridden: in V1, queue becomes type.
*/
protected open fun _restoreQueueSnippet(): String {
return """queue = (case when type in (${Consts.CARD_TYPE_LRN},${Consts.CARD_TYPE_RELEARNING}) then
(case when (case when odue then odue else due end) > 1000000000 then 1 else ${Consts.QUEUE_TYPE_DAY_LEARN_RELEARN} end)
else
type
end) """
}
/**
* Overridden: in V1 only sibling buried exits. */
protected open fun queueIsBuriedSnippet(): String {
return " queue in (" + Consts.QUEUE_TYPE_SIBLING_BURIED + ", " + Consts.QUEUE_TYPE_MANUALLY_BURIED + ") "
}
/**
* Suspend cards.
*
* Overridden: in V1 remove from dyn and lrn
*/
override fun suspendCards(ids: LongArray) {
if (!BackendFactory.defaultLegacySchema) {
super.suspendCards(ids)
return
}
col.log(*ids.toTypedArray())
col.db.execute(
"UPDATE cards SET queue = " + Consts.QUEUE_TYPE_SUSPENDED + ", mod = ?, usn = ? WHERE id IN " +
Utils.ids2str(ids),
time.intTime(), col.usn()
)
}
/**
* Unsuspend cards
*/
override fun unsuspendCards(ids: LongArray) {
if (!BackendFactory.defaultLegacySchema) {
super.unsuspendCards(ids)
return
}
col.log(*ids.toTypedArray())
col.db.execute(
"UPDATE cards SET " + _restoreQueueSnippet() + ", mod = ?, usn = ?" +
" WHERE queue = " + Consts.QUEUE_TYPE_SUSPENDED + " AND id IN " + Utils.ids2str(ids),
time.intTime(), col.usn()
)
}
// Overridden: V1 also remove from dyns and lrn
/**
* Bury all cards with id in cids. Set as manual bury if [manual]
*/
@VisibleForTesting
override fun buryCards(cids: LongArray, manual: Boolean) {
if (!BackendFactory.defaultLegacySchema) {
super.buryCards(cids, manual)
return
}
val queue =
if (manual) Consts.QUEUE_TYPE_MANUALLY_BURIED else Consts.QUEUE_TYPE_SIBLING_BURIED
col.log(*cids.toTypedArray())
col.db.execute(
"update cards set queue=?,mod=?,usn=? where id in " + Utils.ids2str(cids),
queue, time.intTime(), col.usn()
)
}
/**
* Unbury the cards of deck [did] and its descendants.
* @param type See [UnburyType]
*/
override fun unburyCardsForDeck(did: Long, type: UnburyType) {
if (!BackendFactory.defaultLegacySchema) {
super.unburyCardsForDeck(did, type)
return
}
val dids = col.decks.childDids(did, col.decks.childMap()).toMutableList()
dids.add(did)
unburyCardsForDeck(type, dids)
}
/**
* Unbury the cards of some decks.
* @param type See [UnburyType]
* @param allDecks the decks from which cards should be unburied. If None, unbury for all decks.
* Only cards directly in a deck of this lists are considered, not subdecks.
*/
fun unburyCardsForDeck(type: UnburyType, allDecks: List<Long>?) {
@Language("SQL")
val queue = when (type) {
UnburyType.ALL -> queueIsBuriedSnippet()
UnburyType.MANUAL -> "queue = " + Consts.QUEUE_TYPE_MANUALLY_BURIED
UnburyType.SIBLINGS -> "queue = " + Consts.QUEUE_TYPE_SIBLING_BURIED
}
val deckConstraint = if (allDecks == null) {
""
} else {
" and did in " + Utils.ids2str(allDecks)
}
col.log(col.db.queryLongList("select id from cards where $queue $deckConstraint"))
col.db.execute(
"update cards set mod=?,usn=?, " + _restoreQueueSnippet() + " where " + queue + deckConstraint,
time.intTime(), col.usn()
)
}
override fun unburyCards() {
unburyCardsForDeck(UnburyType.ALL, null)
}
/**
* Bury all cards for note until next session.
* @param nid The id of the targeted note.
*/
override fun buryNote(nid: Long) {
if (!BackendFactory.defaultLegacySchema) {
super.buryNote(nid)
return
}
val cids = col.db.queryLongList(
"SELECT id FROM cards WHERE nid = ? AND queue >= " + Consts.CARD_TYPE_NEW, nid
).toLongArray()
buryCards(cids)
}
/**
* Sibling spacing
* ********************
*/
protected fun _burySiblings(card: Card) {
val toBury = ArrayList<Long>()
val nconf = _newConf(card)
val buryNew = nconf.optBoolean("bury", true)
val rconf = _revConf(card)
val buryRev = rconf.optBoolean("bury", true)
col.db.query(
"select id, queue from cards where nid=? and id!=? " +
"and (queue=" + Consts.QUEUE_TYPE_NEW + " or (queue=" + Consts.QUEUE_TYPE_REV + " and due<=?))",
card.nid,
card.id,
mToday!!
).use { cur ->
while (cur.moveToNext()) {
val cid = cur.getLong(0)
val queue = cur.getInt(1)
var queue_object: SimpleCardQueue
if (queue == Consts.QUEUE_TYPE_REV) {
queue_object = mRevQueue
if (buryRev) {
toBury.add(cid)
}
} else {
queue_object = mNewQueue
if (buryNew) {
toBury.add(cid)
}
}
// even if burying disabled, we still discard to give
// same-day spacing
queue_object.remove(cid)
}
}
// then bury
if (!toBury.isEmpty()) {
buryCards(toBury.toLongArray(), false)
}
}
/*
* Resetting **************************************************************** *******************************
*/
/** Put cards at the end of the new queue. */
override fun forgetCards(ids: List<Long>) {
// Currently disabled, as this causes a breakage in some tests due to
// the AnkiDroid implementation not using nextPos to determine next position.
// if (!BackendFactory.getDefaultLegacySchema()) {
// super.forgetCards(ids);
// return;
// }
remFromDyn(ids)
col.db.execute(
"update cards set type=" + Consts.CARD_TYPE_NEW + ",queue=" + Consts.QUEUE_TYPE_NEW + ",ivl=0,due=0,odue=0,factor=" + Consts.STARTING_FACTOR +
" where id in " + Utils.ids2str(ids)
)
val pmax =
col.db.queryScalar("SELECT max(due) FROM cards WHERE type=" + Consts.CARD_TYPE_NEW + "")
// takes care of mod + usn
sortCards(ids, pmax + 1)
col.log(ids)
}
/**
* Put cards in review queue with a new interval in days (min, max).
*
* @param ids The list of card ids to be affected
* @param imin the minimum interval (inclusive)
* @param imax The maximum interval (inclusive)
*/
override fun reschedCards(ids: List<Long>, imin: Int, imax: Int) {
// Currently disabled, as this causes a breakage in the V2 tests due to
// the use of a mocked time.
// if (!BackendFactory.getDefaultLegacySchema()) {
// super.reschedCards(ids, imin, imax);
// return;
// }
val d = ArrayList<Array<Any?>>(ids.size)
val t = mToday!!
val mod = time.intTime()
val rnd = Random()
for (id in ids) {
val r = rnd.nextInt(imax - imin + 1) + imin
d.add(arrayOf(Math.max(1, r), r + t, col.usn(), mod, RESCHEDULE_FACTOR, id))
}
remFromDyn(ids)
col.db.executeMany(
"update cards set type=" + Consts.CARD_TYPE_REV + ",queue=" + Consts.QUEUE_TYPE_REV + ",ivl=?,due=?,odue=0, " +
"usn=?,mod=?,factor=? where id=?",
d
)
col.log(ids)
}
/**
* Repositioning new cards **************************************************
* *********************************************
*/
override fun sortCards(
cids: List<Long>,
start: Int,
step: Int,
shuffle: Boolean,
shift: Boolean
) {
if (!BackendFactory.defaultLegacySchema) {
super.sortCards(cids, start, step, shuffle, shift)
return
}
val scids = Utils.ids2str(cids)
val now = time.intTime()
val nids = ArrayList<Long?>(cids.size)
// List of cid from `cids` and its `nid`
val cid2nid = ArrayList<Pair<Long, Long>>(cids.size)
for (id in cids) {
val nid = col.db.queryLongScalar("SELECT nid FROM cards WHERE id = ?", id)
if (!nids.contains(nid)) {
nids.add(nid)
}
cid2nid.add(Pair(id, nid))
}
if (nids.isEmpty()) {
// no new cards
return
}
// determine nid ordering
val due = HashUtil.HashMapInit<Long?, Long>(nids.size)
if (shuffle) {
Collections.shuffle(nids)
}
for (c in nids.indices) {
due[nids[c]] = (start + c * step).toLong()
}
val high = start + step * (nids.size - 1)
// shift?
if (shift) {
val low = col.db.queryScalar(
"SELECT min(due) FROM cards WHERE due >= ? AND type = " + Consts.CARD_TYPE_NEW + " AND id NOT IN " + scids,
start
)
if (low != 0) {
val shiftBy = high - low + 1
col.db.execute(
"UPDATE cards SET mod = ?, usn = ?, due = due + ?" +
" WHERE id NOT IN " + scids + " AND due >= ? AND type = " + Consts.CARD_TYPE_NEW,
now, col.usn(), shiftBy, low
)
}
}
// reorder cards
val d = ArrayList<Array<Any?>>(cids.size)
for (pair in cid2nid) {
val cid = pair.first
val nid = pair.second
d.add(arrayOf(due[nid], now, col.usn(), cid))
}
col.db.executeMany("UPDATE cards SET due = ?, mod = ?, usn = ? WHERE id = ?", d)
}
override fun randomizeCards(did: Long) {
if (!BackendFactory.defaultLegacySchema) {
super.randomizeCards(did)
return
}
val cids: List<Long> = col.db.queryLongList(
"select id from cards where type = " + Consts.CARD_TYPE_NEW + " and did = ?",
did
)
sortCards(cids, 1, 1, true, false)
}
override fun orderCards(did: Long) {
if (!BackendFactory.defaultLegacySchema) {
super.orderCards(did)
return
}
val cids: List<Long> = col.db.queryLongList(
"SELECT id FROM cards WHERE type = " + Consts.CARD_TYPE_NEW + " AND did = ? ORDER BY nid",
did
)
sortCards(cids, 1, 1, false, false)
}
/**
* Changing scheduler versions **************************************************
* *********************************************
*/
private fun _emptyAllFiltered() {
col.db.execute(
"update cards set did = odid, queue = (case when type = " + Consts.CARD_TYPE_LRN + " then " + Consts.QUEUE_TYPE_NEW + " when type = " + Consts.CARD_TYPE_RELEARNING + " then " + Consts.QUEUE_TYPE_REV + " else type end), type = (case when type = " + Consts.CARD_TYPE_LRN + " then " + Consts.CARD_TYPE_NEW + " when type = " + Consts.CARD_TYPE_RELEARNING + " then " + Consts.CARD_TYPE_REV + " else type end), due = odue, odue = 0, odid = 0, usn = ? where odid != 0",
col.usn()
)
}
private fun _removeAllFromLearning(schedVer: Int = 2) {
// remove review cards from relearning
if (schedVer == 1) {
col.db.execute(
"update cards set due = odue, queue = " + Consts.QUEUE_TYPE_REV + ", type = " + Consts.CARD_TYPE_REV + ", mod = ?, usn = ?, odue = 0 where queue in (" + Consts.QUEUE_TYPE_LRN + "," + Consts.QUEUE_TYPE_DAY_LEARN_RELEARN + ") and type in (" + Consts.CARD_TYPE_REV + "," + Consts.CARD_TYPE_RELEARNING + ")",
time.intTime(), col.usn()
)
} else {
col.db.execute(
"update cards set due = ?+ivl, queue = " + Consts.QUEUE_TYPE_REV + ", type = " + Consts.CARD_TYPE_REV + ", mod = ?, usn = ?, odue = 0 where queue in (" + Consts.QUEUE_TYPE_LRN + "," + Consts.QUEUE_TYPE_DAY_LEARN_RELEARN + ") and type in (" + Consts.CARD_TYPE_REV + "," + Consts.CARD_TYPE_RELEARNING + ")",
mToday, time.intTime(), col.usn()
)
}
// remove new cards from learning
forgetCards(col.db.queryLongList("select id from cards where queue in (" + Consts.QUEUE_TYPE_LRN + "," + Consts.QUEUE_TYPE_DAY_LEARN_RELEARN + ")"))
}
// v1 doesn't support buried/suspended (re)learning cards
private fun _resetSuspendedLearning() {
col.db.execute(
"update cards set type = (case when type = " + Consts.CARD_TYPE_LRN + " then " + Consts.CARD_TYPE_NEW + " when type in (" + Consts.CARD_TYPE_REV + ", " + Consts.CARD_TYPE_RELEARNING + ") then " + Consts.CARD_TYPE_REV + " else type end), due = (case when odue then odue else due end), odue = 0, mod = ?, usn = ? where queue < 0",
time.intTime(), col.usn()
)
}
// no 'manually buried' queue in v1
private fun _moveManuallyBuried() {
col.db.execute(
"update cards set queue=" + Consts.QUEUE_TYPE_SIBLING_BURIED + ", mod=? where queue=" + Consts.QUEUE_TYPE_MANUALLY_BURIED,
time.intTime()
)
}
// adding 'hard' in v2 scheduler means old ease entries need shifting
// up or down
private fun _remapLearningAnswers(sql: String) {
col.db.execute("update revlog set " + sql + " and type in (" + Consts.REVLOG_LRN + ", " + Consts.REVLOG_RELRN + ")")
}
fun moveToV1() {
_emptyAllFiltered()
_removeAllFromLearning()
_moveManuallyBuried()
_resetSuspendedLearning()
_remapLearningAnswers("ease=ease-1 where ease in (" + Consts.BUTTON_THREE + "," + Consts.BUTTON_FOUR + ")")
}
fun moveToV2() {
_emptyAllFiltered()
_removeAllFromLearning(1)
_remapLearningAnswers("ease=ease+1 where ease in (" + Consts.BUTTON_TWO + "," + Consts.BUTTON_THREE + ")")
}
/*
* ***********************************************************
* The methods below are not in LibAnki.
* ***********************************************************
*/
// Overridden: In sched v1, a single type of burying exist
override fun haveBuried(did: Long): Boolean {
val all: MutableList<Long> = ArrayList(col.decks.children(did).values)
all.add(did)
return haveBuriedSiblings(all) || haveManuallyBuried(all)
}
open fun unburyCardsForDeck(did: Long) {
val all: MutableList<Long> = ArrayList(col.decks.children(did).values)
all.add(did)
unburyCardsForDeck(UnburyType.ALL, all)
}
override val name: String
get() = "std2"
override var today: Int
get() = mToday!!
set(today) {
mToday = today
}
protected fun incrReps() {
reps++
}
protected fun decrReps() {
reps--
}
/**
* Change the counts to reflect that `card` should not be counted anymore. In practice, it means that the card has
* been sent to the reviewer. Either through `getCard()` or through `undo`. Assumes that card's queue has not yet
* changed.
* Overridden */
open fun decrementCounts(discardCard: Card?) {
if (discardCard == null) {
return
}
when (discardCard.queue) {
Consts.QUEUE_TYPE_NEW -> mNewCount--
Consts.QUEUE_TYPE_LRN, Consts.QUEUE_TYPE_DAY_LEARN_RELEARN, Consts.QUEUE_TYPE_PREVIEW -> mLrnCount--
Consts.QUEUE_TYPE_REV -> mRevCount--
}
}
/**
* Sorts a card into the lrn queue LIBANKI: not in libanki
*/
protected fun _sortIntoLrn(due: Long, id: Long) {
if (!mLrnQueue.isFilled) {
// We don't want to add an element to the queue if it's not yet assumed to have its normal content.
// Adding anything is useless while the queue awaits being filled
return
}
val i = mLrnQueue.listIterator()
while (i.hasNext()) {
if (i.next().due > due) {
i.previous()
break
}
}
i.add(LrnCard(col, due, id))
}
fun leechActionSuspend(card: Card): Boolean {
val conf = _cardConf(card).getJSONObject("lapse")
return conf.getInt("leechAction") == Consts.LEECH_SUSPEND
}
override fun setContext(contextReference: WeakReference<Activity>) {
mContextReference = contextReference
}
override fun undoReview(card: Card, wasLeech: Boolean) {
// remove leech tag if it didn't have it before
if (!wasLeech && card.note().hasTag("leech")) {
card.note().delTag("leech")
card.note().flush()
}
Timber.i("Undo Review of card %d, leech: %b", card.id, wasLeech)
// write old data
card.flush(false)
val conf = _cardConf(card)
val previewing = conf.isDyn && !conf.getBoolean("resched")
if (!previewing) {
// and delete revlog entry
val last = col.db.queryLongScalar(
"SELECT id FROM revlog WHERE cid = ? ORDER BY id DESC LIMIT 1",
card.id
)
col.db.execute("DELETE FROM revlog WHERE id = $last")
}
// restore any siblings
col.db.execute(
"update cards set queue=type,mod=?,usn=? where queue=" + Consts.QUEUE_TYPE_SIBLING_BURIED + " and nid=?",
time.intTime(),
col.usn(),
card.nid
)
// and finally, update daily count
@CARD_QUEUE val n =
if (card.queue == Consts.QUEUE_TYPE_DAY_LEARN_RELEARN || card.queue == Consts.QUEUE_TYPE_PREVIEW) Consts.QUEUE_TYPE_LRN else card.queue
val type = arrayOf("new", "lrn", "rev")[n]
_updateStats(card, type, -1)
decrReps()
}
val time: Time
get() = TimeManager.time
/** Notifies the scheduler that there is no more current card. This is the case when a card is answered, when the
* scheduler is reset... #5666 */
fun discardCurrentCard() {
mCurrentCard = null
currentCardParentsDid = null
}
/**
* This imitate the action of the method answerCard, except that it does not change the state of any card.
*
* It means in particular that: + it removes the siblings of card from all queues + change the next card if required
* it also set variables, so that when querying the next card, the current card can be taken into account.
*/
fun setCurrentCard(card: Card) {
mCurrentCard = card
val did = card.did
val parents = col.decks.parents(did)
val currentCardParentsDid: MutableList<Long> = ArrayList(parents.size + 1)
for (parent in parents) {
currentCardParentsDid.add(parent.getLong("id"))
}
currentCardParentsDid.add(did)
// We set the member only once it is filled, to ensure we avoid null pointer exception if `discardCurrentCard`
// were called during `setCurrentCard`.
this.currentCardParentsDid = currentCardParentsDid
_burySiblings(card)
// if current card is next card or in the queue
mRevQueue.remove(card.id)
mNewQueue.remove(card.id)
}
protected fun currentCardIsInQueueWithDeck(@CARD_QUEUE queue: Int, did: Long): Boolean {
// mCurrentCard may be set to null when the reviewer gets closed. So we copy it to be sure to avoid NullPointerException
val currentCard = mCurrentCard
val currentCardParentsDid = currentCardParentsDid
return currentCard != null && currentCard.queue == queue && currentCardParentsDid != null && currentCardParentsDid.contains(
did
)
}
companion object {
// Not in libanki
private val FACTOR_ADDITION_VALUES = intArrayOf(-150, 0, 150)
const val RESCHEDULE_FACTOR = Consts.STARTING_FACTOR
fun _fuzzIvlRange(ivl: Int): Pair<Int, Int> {
var fuzz: Int
fuzz = if (ivl < 2) {
return Pair(1, 1)
} else if (ivl == 2) {
return Pair(2, 3)
} else if (ivl < 7) {
(ivl * 0.25).toInt()
} else if (ivl < 30) {
Math.max(2, (ivl * 0.15).toInt())
} else {
Math.max(4, (ivl * 0.05).toInt())
}
// fuzz at least a day
fuzz = Math.max(fuzz, 1)
return Pair(ivl - fuzz, ivl + fuzz)
}
}
/* The next card that will be sent to the reviewer. I.e. the result of a second call to getCard, which is not the
* current card nor a sibling.
*/
/**
* card types: 0=new, 1=lrn, 2=rev, 3=relrn
* queue types: 0=new, 1=(re)lrn, 2=rev, 3=day (re)lrn,
* 4=preview, -1=suspended, -2=sibling buried, -3=manually buried
* revlog types: 0=lrn, 1=rev, 2=relrn, 3=early review
* positive revlog intervals are in days (rev), negative in seconds (lrn)
* odue/odid store original due/did when cards moved to filtered deck
*
*/
init {
_updateCutoff()
}
@Consts.BUTTON_TYPE
override val goodNewButton: Int
get() = Consts.BUTTON_THREE
}
| gpl-3.0 | a3ea2bfd3ef3d1207d15057af5c65ecc | 36.383935 | 474 | 0.53902 | 4.22152 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/test/java/com/ichi2/libanki/ImportingTest.kt | 1 | 13376 | /*
* 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
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ichi2.anki.RobolectricTest
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class ImportingTest : RobolectricTest() {
@Test
fun empty_test() {
// A test should occurs in the file, otherwise travis rejects. This remains here until we can uncomment the real tests.
}
/****************
* Importing *
*/
/*
private void clear_tempfile(tf) {
;
" https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file ";
try {
tf.close();
os.unlink(tf.name);
} catch () {
}
}
@Test
public void test_anki2_mediadupes(){
Collection col = getCol();
// add a note that references a sound
Note n = tmp.newNote();
n.setItem("Front", "[sound:foo.mp3]");
mid = n.model().getLong("id");
col.addNote(n);
// add that sound to media directory
with open(os.path.join(col.getMedia().dir(), "foo.mp3"), "w") as note:
note.write("foo");
col.close();
// it should be imported correctly into an empty deck
Collection empty = getCol();
Anki2Importer imp = Anki2Importer(empty, col.getPath());
imp.run();
assertEqualsArrayList(new String [] {"foo.mp3"}, os.listdir(empty.getMedia().dir()));
// and importing again will not duplicate, as the file content matches
empty.remCards(empty.getDb().test_removequeryLongList("select id from cards"));
Anki2Importer imp = Anki2Importer(empty, col.getPath());
imp.run();
assertEqualsArrayList(new String [] {"foo.mp3"}, os.listdir(empty.getMedia().dir()));
Note n = empty.getNote(empty.getDb().queryLongScalar("select id from notes"));
assertThat(n.fields[0], containsString("foo.mp3"));
// if the local file content is different, and import should trigger a
// rename
empty.remCards(empty.getDb().queryLongList("select id from cards"));
with open(os.path.join(empty.getMedia().dir(), "foo.mp3"), "w") as note:
note.write("bar");
Anki2Importer imp = Anki2Importer(empty, col.getPath());
imp.run();
assertEqualsArrayList(new String [] {"foo.mp3", "foo_"+mid+".mp3"}, sorted(os.listdir(empty.getMedia().dir())));
Note n = empty.getNote(empty.getDb().queryLongScalar("select id from notes"));
assertThat(n.fields[0], containsString("_"));
// if the localized media file already exists, we rewrite the note and
// media
empty.remCards(empty.getDb().queryLongList("select id from cards"));
with open(os.path.join(empty.getMedia().dir(), "foo.mp3"), "w") as note:
note.write("bar");
Anki2Importer imp = Anki2Importer(empty, col.getPath());
imp.run();
assertEqualsArrayList(new String [] {"foo.mp3", "foo_"+mid+".mp3" }, sorted(os.listdir(empty.getMedia().dir())));
assertEqualsArrayList(new String [] {"foo.mp3", "foo_"+mid+".mp3"}, sorted(os.listdir(empty.getMedia().dir())));
Note n = empty.getNote(empty.getDb().queryLongScalar("select id from notes"));
assertThat(n.fields[0], containsString("_"));
}
@Test
public void test_apkg(){
Collection col = getCol();
String apkg = str(os.path.join(testDir, "support/media.apkg"));
AnkiPackageImporter imp = AnkiPackageImporter(col, apkg);
assertEqualsArrayList(new String [] {}, os.listdir(col.getMedia().dir()));
imp.run();
assertEqualsArrayList(new String [] {"foo.wav"}, os.listdir(col.getMedia().dir()));
// importing again should be idempotent in terms of media
col.remCards(col.getDb().queryLongList("select id from cards"));
AnkiPackageImporter imp = AnkiPackageImporter(col, apkg);
imp.run();
assertEqualsArrayList(new String [] {"foo.wav"}, os.listdir(col.getMedia().dir()));
// but if the local file has different data, it will rename
col.remCards(col.getDb().queryLongList("select id from cards"));
with open(os.path.join(col.getMedia().dir(), "foo.wav"), "w") as note:
note.write("xyz");
imp = AnkiPackageImporter(col, apkg);
imp.run();
assertEquals(2, os.listdir(col.getMedia().dir()).size());
}
@Test
public void test_anki2_diffmodel_templates(){
// different from the above as this one tests only the template text being
// changed, not the number of cards/fields
Collection dst = getCol();
// import the first version of the model
Collection col = getUpgradeDeckPath("diffmodeltemplates-1.apkg");
AnkiPackageImporter imp = AnkiPackageImporter(dst, col);
imp.dupeOnSchemaChange = true;
imp.run();
// then the version with updated template
Collection col = getUpgradeDeckPath("diffmodeltemplates-2.apkg");
imp = AnkiPackageImporter(dst, col);
imp.dupeOnSchemaChange = true;
imp.run();
// collection should contain the note we imported
assertEquals(1, dst.noteCount());
// the front template should contain the text added in the 2nd package
tlong cid = dst.findCards("")[0] // only 1 note in collection
tNote note = dst.getCard(tcid).note();
assertThat(tnote.cards().get(0).template().getString("qfmt"), containsString("Changed Front Template"));
}
@Test
public void test_anki2_updates(){
// create a new empty deck
dst = getCol();
Collection col = getUpgradeDeckPath("update1.apkg");
AnkiPackageImporter imp = AnkiPackageImporter(dst, col);
imp.run();
assertEquals(0, imp.dupes);
assertEquals(1, imp.added);
assertEquals(0, imp.updated);
// importing again should be idempotent
imp = AnkiPackageImporter(dst, col);
imp.run();
assertEquals(1, imp.dupes);
assertEquals(0, imp.added);
assertEquals(0, imp.updated);
// importing a newer note should update
assertEquals(1, dst.noteCount());
assertTrue(dst.getDb().queryLongScalar("select flds from notes").startswith("hello"));
Collection col = getUpgradeDeckPath("update2.apkg");
imp = AnkiPackageImporter(dst, col);
imp.run();
assertEquals(0, imp.dupes);
assertEquals(0, imp.added);
assertEquals(1, imp.updated);
assertEquals(1, dst.noteCount());
assertTrue(dst.getDb().queryLongScalar("select flds from notes").startswith("goodbye"));
}
@Test
public void test_csv(){
Collection col = getCol();
file = str(os.path.join(testDir, "support/text-2fields.txt"));
i = TextImporter(col, file);
i.initMapping();
i.run();
// four problems - too many & too few fields, a missing front, and a
// duplicate entry
assertEquals(5, i.log.size());
assertEquals(5, i.total);
// if we run the import again, it should update instead
i.run();
assertEquals(10, i.log.size());
assertEquals(5, i.total);
// but importing should not clobber tags if they're unmapped
Note n = col.getNote(col.getDb().queryLongScalar("select id from notes"));
n.addTag("test");
n.flush();
i.run();
n.load();
assertEqualsArrayList(new String [] {"test"}, n.tags);
// if add-only mode, count will be 0
i.importMode = 1;
i.run();
assertEquals(0, i.total);
// and if dupes mode, will reimport everything
assertEquals(5, col.cardCount());
i.importMode = 2;
i.run();
// includes repeated field
assertEquals(6, i.total);
assertEquals(11, col.cardCount());
col.close();
}
@Test
public void test_csv2(){
Collection col = getCol();
Models mm = col.getModels();
Model m = mm.current();
Note note = mm.newField("Three");
mm.addField(m, note);
mm.save(m);
Note n = col.newNote();
n.setItem("Front", "1");
n.setItem("Back", "2");
n.setItem("Three", "3");
col.addNote(n);
// an update with unmapped fields should not clobber those fields
file = str(os.path.join(testDir, "support/text-update.txt"));
TextImporter i = TextImporter(col, file);
i.initMapping();
i.run();
n.load();
assertTrue(n.setItem("Front",= "1"));
assertTrue(n.setItem("Back",= "x"));
assertTrue(n.setItem("Three",= "3"));
col.close();
}
@Test
public void test_tsv_tag_modified(){
Collection col = getCol();
Models mm = col.getModels();
Model m = mm.current();
Note note = mm.newField("Top");
mm.addField(m, note);
mm.save(m);
Note n = col.newNote();
n.setItem("Front", "1");
n.setItem("Back", "2");
n.setItem("Top", "3");
n.addTag("four");
col.addNote(n);
// https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file
with NamedTemporaryFile(mode="w", delete=false) as tf:
tf.write("1\tb\tc\n");
tf.flush();
TextImporter i = TextImporter(col, tf.name);
i.initMapping();
i.tagModified = "boom";
i.run();
clear_tempfile(tf);
n.load();
assertTrue(n.setItem("Front",= "1"));
assertTrue(n.setItem("Back",= "b"));
assertTrue(n.setItem("Top",= "c"));
assertThat(n.getTags(), containsString("four"));
assertThat(n.getTags(), containsString("boom"));
assertEquals(2, n.getTags().size());
assertEquals(1, i.updateCount);
col.close();
}
@Test
public void test_tsv_tag_multiple_tags(){
Collection col = getCol();
Models mm = col.getModels();
Model m = mm.current();
Note note = mm.newField("Top");
mm.addField(m, note);
mm.save(m);
Note n = col.newNote();
n.setItem("Front", "1");
n.setItem("Back", "2");
n.setItem("Top", "3");
n.addTag("four");
n.addTag("five");
col.addNote(n);
// https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file
with NamedTemporaryFile(mode="w", delete=false) as tf:
tf.write("1\tb\tc\n");
tf.flush();
TextImporter i = TextImporter(col, tf.name);
i.initMapping();
i.tagModified = "five six";
i.run();
clear_tempfile(tf);
n.load();
assertTrue(n.setItem("Front",= "1"));
assertTrue(n.setItem("Back",= "b"));
assertTrue(n.setItem("Top",= "c"));
assertEquals(list(sorted(new String [] {"four", "five", "six"}, list(sorted(n.getTags())))));
col.close();
}
@Test
public void test_csv_tag_only_if_modified(){
Collection col = getCol();
Models mm = col.getModels();
Model m = mm.current();
Note note = mm.newField("Left");
mm.addField(m, note);
mm.save(m);
Note n = col.newNote();
n.setItem("Front", "1");
n.setItem("Back", "2");
n.setItem("Left", "3");
col.addNote(n);
// https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file
with NamedTemporaryFile(mode="w", delete=false) as tf:
tf.write("1,2,3\n");
tf.flush();
TextImporter i = TextImporter(col, tf.name);
i.initMapping();
i.tagModified = "right";
i.run();
clear_tempfile(tf);
n.load();
assertEqualsArrayList(new String [] {}, n.tags);
assertEquals(0, i.updateCount);
col.close();
}
@pytest.mark.filterwarnings("ignore:Using or importing the ABCs")
@Test
public void test_supermemo_xml_01_unicode(){
Collection col = getCol();
String file = str(os.path.join(testDir, "support/supermemo1.xml"));
SupermemoXmlImporter i = SupermemoXmlImporter(col, file);
// i.META.logToStdOutput = true
i.run();
assertEquals(1, i.total);
long cid = col.getDb().queryLongScalar("select id from cards");
Card c = col.getCard(cid);
// Applies A Factor-to-E Factor conversion
assertEquals(2879, c.getFactor());
assertEquals(7, c.getReps());
col.close();
}
@Test
public void test_mnemo(){
Collection col = getCol();
String file = str(os.path.join(testDir, "support/mnemo.getDb()"));
MnemosyneImporter i = MnemosyneImporter(col, file);
i.run();
assertEquals(7, col.cardCount());
assertThat(col.getTags().all(), containsString("a_longer_tag"));
assertEquals(1, col.getDb().queryScalar("select count() from cards where type = 0"));
col.close()
}
*/
}
| gpl-3.0 | f97d7a994283adb9b6b537cfd5475e9f | 36.467787 | 127 | 0.613636 | 3.824993 | false | true | false | false |
pdvrieze/ProcessManager | multiplatform/src/commonMain/kotlin/nl/adaptivity/util/multiplatform/commonMultiplatform.kt | 1 | 3802 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.util.multiplatform
import kotlin.reflect.KClass
//@ExperimentalMultiplatform
//@OptionalExpectation
@Deprecated("Use 1.2.70 optional annotation", ReplaceWith("JvmStatic", "kotlin.jvm.JvmStatic"))
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
expect annotation class JvmStatic()
@Deprecated("Use 1.2.70 optional annotation", ReplaceWith("JvmWildcard", "kotlin.jvm.JvmWildcard"))
@Target(AnnotationTarget.TYPE)
@MustBeDocumented
//@ExperimentalMultiplatform
//@OptionalExpectation
expect annotation class JvmWildcard()
@Deprecated("Use 1.2.70 optional annotation", ReplaceWith("JvmField", "kotlin.jvm.JvmField"))
//@ExperimentalMultiplatform
//@OptionalExpectation
expect annotation class JvmField()
@Deprecated("Use 1.2.70 optional annotation", ReplaceWith("JvmName", "kotlin.jvm.JvmName"))
//@ExperimentalMultiplatform
//@OptionalExpectation
@Target(
AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.FILE
)
expect annotation class JvmName(val name: String)
@Deprecated("Use 1.2.70 optional annotation", ReplaceWith("JvmOverloads", "kotlin.jvm.JvmOverloads"))
//@ExperimentalMultiplatform
//@OptionalExpectation
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CONSTRUCTOR)
@MustBeDocumented
expect annotation class JvmOverloads()
@Deprecated("Use 1.2.70 optional annotation", ReplaceWith("JvmMultifileClass", "kotlin.jvm.JvmMultifileClass"))
//@ExperimentalMultiplatform
//@OptionalExpectation
@Target(AnnotationTarget.FILE)
expect annotation class JvmMultifileClass()
//@ExperimentalMultiplatform
//@OptionalExpectation
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER,
AnnotationTarget.CONSTRUCTOR
)
expect annotation class Throws(vararg val exceptionClasses: KClass<out Throwable>)
expect class URI constructor(str: String) {
fun getPath(): String
}
expect class UUID
expect fun randomUUID(): UUID
expect fun String.toUUID(): UUID
inline val URI.path get() = getPath()
expect inline fun createUri(s: String): URI
@Suppress("NOTHING_TO_INLINE")
inline fun String.toUri(): URI = createUri(this)
fun Appendable.append(d: Double) = append(d.toString())
fun Appendable.append(i: Int) = append(i.toString())
@Suppress("unused")
expect class Class<T : Any?>
expect val KClass<*>.name: String
expect fun arraycopy(src: Any, srcPos: Int, dest: Any, destPos: Int, length: Int)
expect fun <T> fill(array: Array<T>, element: T, fromIndex: Int = 0, toIndex: Int = array.size)
expect fun assert(value: Boolean, lazyMessage: () -> String)
expect fun assert(value: Boolean)
expect interface AutoCloseable {
fun close()
}
expect interface Closeable : AutoCloseable
expect interface Runnable {
fun run()
}
@Suppress("unused")
expect inline fun <reified T : Any> isTypeOf(value: Any): Boolean
expect fun Throwable.addSuppressedCompat(suppressed: Throwable): Unit
expect fun Throwable.initCauseCompat(cause: Throwable): Throwable
| lgpl-3.0 | 9ba8e46b8763bb53e9854544dee40cfd | 29.910569 | 112 | 0.773277 | 4.320455 | false | false | false | false |
aCoder2013/general | general-gossip/src/main/java/com/song/general/gossip/net/Message.kt | 1 | 666 | package com.song.general.gossip.net
import com.song.general.gossip.GossipAction
import java.io.Serializable
import java.net.SocketAddress
/**
* Created by song on 2017/8/19.
*/
class Message : Serializable {
val from: SocketAddress
var action: GossipAction
var payload: Any
var createTime: Long
constructor(from: SocketAddress, action: GossipAction, payload: Any, createTime: Long = System.currentTimeMillis()) {
this.from = from
this.action = action
this.payload = payload
this.createTime = createTime
}
companion object {
private const val serialVersionUID = 2161395957955391220L
}
}
| apache-2.0 | d67337e9326e2cc6772875bbfc9e476b | 22.785714 | 121 | 0.696697 | 4.1625 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/widget/CombinedTool.kt | 1 | 2425 | package pyxis.uzuki.live.richutilskt.widget
import android.content.Context
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.util.LruCache
import android.view.View
import pyxis.uzuki.live.richutilskt.utils.isEmpty
/**
* RichUtilsKt
* Class: CombinedTool
* Created by Pyxis on 2017-10-27.
*
* Description:
*/
fun SpannableStringBuilder.setSpan(what: Any, start: Int, end: Int) {
this.setSpan(what, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
fun SpannableStringBuilder.setFontSpan(span: TypefaceSpan?, textStyle: Int, start: Int, end: Int) {
if (span != null) {
this.setSpan(span, start, end)
} else {
when (textStyle) {
1 -> this.setSpan(StyleSpan(Typeface.BOLD), start, end)
2 -> this.setSpan(StyleSpan(Typeface.ITALIC), start, end)
3 -> this.setSpan(StyleSpan(Typeface.BOLD_ITALIC), start, end)
}
}
}
fun SpannableStringBuilder.setSizeSpan(size: Float, start: Int, end: Int) {
this.setSpan(AbsoluteSizeSpan(size.toInt()), start, end)
}
fun SpannableStringBuilder.setColorSpan(color: Int, start: Int, end: Int) {
this.setSpan(ForegroundColorSpan(color), start, end)
}
fun View.getTypefaceSpan(fontTypefaceText: String?, fontTypeface: Typeface?): TypefaceSpan? {
val fontTypefaceTextWrapped = if (fontTypefaceText == null) "" else fontTypefaceText
return if (fontTypefaceTextWrapped.isEmpty()) {
if (fontTypeface != null) TypefaceSpan(fontTypeface) else null
} else {
val typeface = FontCache.getTypefaceFromAsset(this.context, fontTypefaceTextWrapped)
TypefaceSpan(typeface)
}
}
class FontCache {
companion object {
private val sStringCache = LruCache<String, Typeface>(12)
@Synchronized
fun getTypefaceFromAsset(context: Context, name: String): Typeface? {
var typeface: Typeface? = sStringCache.get(name)
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.assets, name)
} catch (exp: Exception) {
return null
}
sStringCache.put(name, typeface)
}
return typeface
}
}
} | apache-2.0 | 69617fc2ad461fd366dcb7a02ddd44c7 | 30.506494 | 99 | 0.672577 | 4.181034 | false | false | false | false |
WindSekirun/RichUtilsKt | demo/src/main/java/pyxis/uzuki/live/richutilskt/demo/set/PermissionSet.kt | 1 | 2229 | package pyxis.uzuki.live.richutilskt.demo.set
import android.Manifest
import android.content.Context
import android.text.TextUtils
import pyxis.uzuki.live.richutilskt.demo.item.CategoryItem
import pyxis.uzuki.live.richutilskt.demo.item.ExecuteItem
import pyxis.uzuki.live.richutilskt.demo.item.generateExecuteItem
import pyxis.uzuki.live.richutilskt.utils.RPermission
import pyxis.uzuki.live.richutilskt.utils.alert
import pyxis.uzuki.live.richutilskt.utils.toast
/**
* RichUtilsKt
* Class: PermissionSet
* Created by Pyxis on 2017-11-09.
*
* Description:
*/
fun Context.getPermissionSet(): ArrayList<ExecuteItem> {
val list = arrayListOf<ExecuteItem>()
val checkPermission = generateExecuteItem(CategoryItem.PERMISSION, "checkPermission",
"check and request Permission which given.",
"RPermission.instance.checkPermission(this, array = arrays, callback = { _: Int, _: List<String> ->\n" +
"})",
"RPermission.instance.checkPermission(this, arrays, (integer, strings) -> {\n" +
"});") {
val arrays: Array<String> = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA)
RPermission.instance.checkPermission(this, array = arrays, callback = { resultCode: Int, list: List<String> ->
alert(message = "Permission result -> $resultCode / Requested Permission: ${TextUtils.join(",", list)}")
})
}
list.add(checkPermission)
val checkPermissionGranted = generateExecuteItem(CategoryItem.PERMISSION, "checkPermissionGranted",
"check permission is granted",
"RPermission.instance.checkPermissionGranted(this, arrays)",
"RPermission.instance.checkPermissionGranted(this, arrays);") {
val arrays: Array<String> = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA)
toast("WRITE/READ EXTERNAL STORAGE, CAMERA IS ${if (RPermission.instance.checkPermissionGranted(this, arrays)) "Granted" else "Not all granted"}")
}
list.add(checkPermissionGranted)
return list
} | apache-2.0 | 5f017cbc04115016e121a65bfcafc162 | 41.884615 | 154 | 0.707941 | 4.50303 | false | false | false | false |
markspit93/Github-Feed-Sample | app/src/main/kotlin/com/github/feed/sample/ui/details/DetailsActivity.kt | 1 | 3173 | package com.github.feed.sample.ui.details
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import com.github.feed.sample.R
import com.github.feed.sample.data.model.Event
import com.github.feed.sample.ext.gone
import com.github.feed.sample.ext.loadCircleImage
import com.github.feed.sample.ext.setTaskColor
import com.github.feed.sample.ui.common.BaseActivity
import com.github.feed.sample.util.ColorUtils
import com.github.feed.sample.util.DateUtils
import kotlinx.android.synthetic.main.activity_details.*
import kotlinx.android.synthetic.main.card_info.*
import kotlinx.android.synthetic.main.card_org.*
import kotlinx.android.synthetic.main.card_repo.*
import kotlinx.android.synthetic.main.toolbar.*
class DetailsActivity : BaseActivity() {
companion object {
private const val EXTRA_EVENT = "extra_event"
fun createIntent(ctx: Context, event: Event) =
Intent(ctx, DetailsActivity::class.java).apply {
putExtra(EXTRA_EVENT, event)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_details)
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowTitleEnabled(false)
val event: Event = intent.extras.getParcelable(EXTRA_EVENT)
val color = ColorUtils.getColorForType(this, event.type)
appBarLayout.setBackgroundColor(color)
toolbar.setBackgroundColor(color)
setTaskColor(color)
showInfo(event, color)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finishAfterTransition()
}
return true
}
override fun onBackPressed() {
finishAfterTransition()
}
private fun showInfo(event: Event, color: Int) {
imgAvatar.loadCircleImage(event.actor.avatar)
txtName.text = event.actor.username
txtInfoTitle.setTextColor(color)
txtInfoType.text = getString(R.string.details_info_type, event.type.removeSuffix("Event"))
txtInfoPublic.text = getString(R.string.details_info_public, getString(if (event.public) R.string.yes else R.string.no))
txtInfoDate.text = getString(R.string.details_info_date, DateUtils.formatDate(this, event.creationDate))
txtRepoTitle.setTextColor(color)
txtRepoID.text = getString(R.string.details_repo_id, event.repository.id.toString())
txtRepoName.text = getString(R.string.details_repo_name, event.repository.name)
txtRepoUrl.text = getString(R.string.details_repo_url, event.repository.url)
if (event.organization != null) {
txtOrgTitle.setTextColor(color)
txtOrgID.text = getString(R.string.details_org_id, event.organization.id.toString())
txtOrgUrl.text = getString(R.string.details_org_url, event.organization.url)
imgOrgAvatar.loadCircleImage(event.actor.avatar)
} else {
cardOrg.gone()
}
}
}
| apache-2.0 | 754f28d108ec6977dfb3a3d6718531e3 | 36.329412 | 128 | 0.708163 | 4.126138 | false | false | false | false |
hellenxu/AndroidAdvanced | Custom/app/src/main/java/six/ca/custom/loading/skeleton/SkeletonRecyclerView.kt | 1 | 884 | package six.ca.custom.loading.skeleton
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class SkeletonRecyclerView @JvmOverloads constructor(ctx: Context, attrs: AttributeSet? = null, defStyle: Int = 0):
RecyclerView(ctx, attrs, defStyle) {
private var skeletonAdapter: RecyclerView.Adapter<SkeletonViewHolder> = SkeletonAdapter(ctx)
private lateinit var dataAdapter: DataAdapter
private var inLoading = false
fun setDataAdapter (adapter: DataAdapter) {
dataAdapter = adapter
}
fun showSkeleton () {
adapter = skeletonAdapter
inLoading = true
}
fun hideSkeleton () {
adapter = dataAdapter
inLoading = false
}
class SkeletonViewHolder constructor(itemView: View): RecyclerView.ViewHolder(itemView)
}
| apache-2.0 | c83988fe4d449bf851f4481d6cf7fbd1 | 27.516129 | 115 | 0.727376 | 4.752688 | false | false | false | false |
hellenxu/AndroidAdvanced | CrashCases/app/src/main/java/six/ca/crashcases/fragment/biz/HomeViewModel.kt | 1 | 1646 | package six.ca.crashcases.fragment.biz
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import six.ca.crashcases.fragment.data.AccountType
import six.ca.crashcases.fragment.data.profile.ProfileRepository
import six.ca.crashcases.fragment.data.ResponseResult
import six.ca.crashcases.fragment.data.SingleLiveEvent
import six.ca.crashcases.fragment.manager.ProfileManager
import javax.inject.Inject
/**
* @author hellenxu
* @date 2020-10-03
* Copyright 2020 Six. All rights reserved.
*/
class HomeViewModel @Inject constructor(
private val profileRepo: ProfileRepository,
private val profileManager: ProfileManager
): ViewModel() {
private val _currentState = SingleLiveEvent<ScreenState>()
val currentState: LiveData<ScreenState>
get() = _currentState
fun retrieveProfile() {
_currentState.value = ScreenState.Loading
viewModelScope.launch {
when(val result = profileRepo.fetchProfile()) {
is ResponseResult.Success -> {
val accountType = AccountType.VIP
profileManager.accountType = accountType
profileManager.updateCurrentProfile(result.data)
_currentState.value = ScreenState.Success
}
is ResponseResult.Error -> {
_currentState.value = ScreenState.Error
}
}
}
}
}
sealed class ScreenState {
object Loading: ScreenState()
object Success: ScreenState()
object Error: ScreenState()
} | apache-2.0 | 58eace01ef84df53d7a0aa6c9633a1b4 | 30.673077 | 68 | 0.685298 | 5.095975 | false | false | false | false |
PaulWoitaschek/Voice | settings/src/main/kotlin/voice/settings/views/ResumeOnReplugRow.kt | 1 | 1449 | package voice.settings.views
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Headset
import androidx.compose.material3.Icon
import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import voice.settings.R
@Composable
internal fun ResumeOnReplugRow(
resumeOnReplug: Boolean,
toggle: () -> Unit,
) {
ListItem(
modifier = Modifier
.clickable {
toggle()
}
.fillMaxWidth(),
leadingContent = {
Icon(
imageVector = Icons.Outlined.Headset,
contentDescription = stringResource(R.string.pref_resume_on_replug),
)
},
headlineText = {
Text(
text = stringResource(R.string.pref_resume_on_replug),
style = MaterialTheme.typography.bodyLarge,
)
},
supportingText = {
Text(
text = stringResource(R.string.pref_resume_on_replug_hint),
style = MaterialTheme.typography.bodyMedium,
)
},
trailingContent = {
Switch(
checked = resumeOnReplug,
onCheckedChange = {
toggle()
},
)
},
)
}
| gpl-3.0 | 20c271dcf58e47b07e45ab795d40c755 | 25.345455 | 76 | 0.692892 | 4.338323 | false | false | false | false |
noseblowhorn/krog | src/main/kotlin/eu/fizzystuff/krog/main/Main.kt | 1 | 1338 | package eu.fizzystuff.krog.main
import com.google.inject.Guice
import com.googlecode.lanterna.screen.TerminalScreen
import com.googlecode.lanterna.terminal.DefaultTerminalFactory
import eu.fizzystuff.krog.scenes.MainScreenScene
import eu.fizzystuff.krog.scenes.visibility.VisibilityStrategy
import eu.fizzystuff.krog.model.PlayerCharacter
import eu.fizzystuff.krog.model.WorldState
import eu.fizzystuff.krog.model.dungeongenerators.EmptyCircularCaveGenerator
import eu.fizzystuff.krog.model.dungeongenerators.RandomWalkCaveGenerator
import eu.fizzystuff.krog.scenes.SceneTransitionAutomaton
fun main(args: Array<String>) {
val injector = Guice.createInjector(KrogModule());
val generator = injector.getInstance(RandomWalkCaveGenerator::class.java)
WorldState.instance.currentDungeonLevel = generator.generate(80, 22)
WorldState.instance.currentDungeonLevel.addActor(PlayerCharacter.instance)
PlayerCharacter.instance.x = WorldState.instance.currentDungeonLevel.transitionPoints.filter { x -> x.targetLevel == null }.first().x
PlayerCharacter.instance.y = WorldState.instance.currentDungeonLevel.transitionPoints.filter { x -> x.targetLevel == null }.first().y
PlayerCharacter.instance.speed = 100
val automaton = SceneTransitionAutomaton(MainScreenScene::class.java, injector)
automaton.start()
} | apache-2.0 | 6c2e19cde977cb1b21f07d8d14b05cd4 | 46.821429 | 137 | 0.822123 | 4.194357 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/MaxWidthFrameLayout.kt | 1 | 1261 | package com.pr0gramm.app.ui
import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import com.pr0gramm.app.R
import com.pr0gramm.app.util.observeChange
import com.pr0gramm.app.util.use
/**
*/
class MaxWidthFrameLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
var maxWidth: Int by observeChange(0) { requestLayout() }
init {
context.theme.obtainStyledAttributes(attrs, R.styleable.MaxWidthFrameLayout, 0, 0).use {
maxWidth = it.getDimensionPixelSize(
R.styleable.MaxWidthFrameLayout_mwfl_maxWidth, Integer.MAX_VALUE)
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val mode = MeasureSpec.getMode(widthMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
var widthSpec = widthMeasureSpec
if (width > maxWidth) {
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
widthSpec = MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST)
}
}
super.onMeasure(widthSpec, heightMeasureSpec)
}
}
| mit | ac23ea80b773690f6a7e86915dad0ca4 | 32.184211 | 96 | 0.688343 | 4.487544 | false | false | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Interactors/Helpers/LoginSharedPreferences.kt | 1 | 1877 | package com.polito.sismic.Interactors.Helpers
import android.content.Context
import com.polito.sismic.Domain.UserDetails
import com.polito.sismic.Extensions.edit
/**
* Created by Matteo on 14/08/2017.
*/
class LoginSharedPreferences {
companion object {
fun logout(context: Context) = with(context)
{
getSharedPreferences("login", Context.MODE_PRIVATE).edit {
putBoolean("logged", false)
}
}
fun isLoggedIn (context: Context) : Boolean = with(context)
{
getSharedPreferences("login", Context.MODE_PRIVATE).getBoolean("logged", false)
}
fun getLoggedUser(context: Context) : UserDetails = with(context)
{
val sp = getSharedPreferences("login", Context.MODE_PRIVATE)
UserDetails(sp.getString("name", ""),
sp.getString("address", ""),
sp.getString("email", ""),
sp.getString("phone", ""),
sp.getString("qualification", ""),
sp.getString("registration", ""))
}
fun login(userDetails: UserDetails, context: Context) = with(context)
{
getSharedPreferences("login", Context.MODE_PRIVATE).edit()
{
putString("name", userDetails.name)
putString("address", userDetails.address)
putString("email", userDetails.email)
putString("phone", userDetails.phone)
putString("qualification", userDetails.qualification)
putString("registration", userDetails.registration)
putBoolean("logged", true)
}
}
fun demoLogin (context: Context)
{
login(UserDetails("Matteo", "demo", "demo", "demo", "demo", "demo"), context)
}
}
}
| mit | 4c3053b619ab858a842cd484942bd40a | 30.813559 | 91 | 0.559403 | 5.032172 | false | false | false | false |
FHannes/intellij-community | plugins/git4idea/tests/git4idea/test/MockVcsHelper.kt | 7 | 6620 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.test
import com.intellij.ide.errorTreeView.HotfixData
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.annotate.AnnotationProvider
import com.intellij.openapi.vcs.annotate.FileAnnotation
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.CommitResultHandler
import com.intellij.openapi.vcs.changes.LocalChangeList
import com.intellij.openapi.vcs.history.VcsFileRevision
import com.intellij.openapi.vcs.history.VcsHistoryProvider
import com.intellij.openapi.vcs.history.VcsRevisionNumber
import com.intellij.openapi.vcs.merge.MergeDialogCustomizer
import com.intellij.openapi.vcs.merge.MergeProvider
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList
import com.intellij.openapi.vfs.VirtualFile
import java.awt.Component
import java.io.File
class MockVcsHelper(project: Project) : AbstractVcsHelper(project) {
@Volatile private var myCommitDialogShown: Boolean = false
@Volatile private var myMergeDialogShown: Boolean = false
@Volatile private var myMergeDelegate: () -> Unit = { throw IllegalStateException() }
@Volatile private var myCommitDelegate: (String) -> Boolean = { throw IllegalStateException() }
override fun runTransactionRunnable(vcs: AbstractVcs<*>?, runnable: TransactionRunnable?, vcsParameters: Any?): MutableList<VcsException>? {
throw UnsupportedOperationException()
}
override fun showAnnotation(annotation: FileAnnotation?, file: VirtualFile?, vcs: AbstractVcs<*>?) {
throw UnsupportedOperationException()
}
override fun showAnnotation(annotation: FileAnnotation?, file: VirtualFile?, vcs: AbstractVcs<*>?, line: Int) {
throw UnsupportedOperationException()
}
override fun showChangesBrowser(provider: CommittedChangesProvider<*, *>?, location: RepositoryLocation?, title: String?, parent: Component?) {
throw UnsupportedOperationException()
}
override fun openCommittedChangesTab(vcs: AbstractVcs<*>?, root: VirtualFile?, settings: ChangeBrowserSettings?, maxCount: Int, title: String?) {
throw UnsupportedOperationException()
}
override fun openCommittedChangesTab(provider: CommittedChangesProvider<*, *>?, location: RepositoryLocation?, settings: ChangeBrowserSettings?, maxCount: Int, title: String?) {
throw UnsupportedOperationException()
}
override fun showFileHistory(historyProvider: VcsHistoryProvider, path: FilePath, vcs: AbstractVcs<*>, repositoryPath: String?) {
throw UnsupportedOperationException()
}
override fun showFileHistory(historyProvider: VcsHistoryProvider, annotationProvider: AnnotationProvider?, path: FilePath, repositoryPath: String?, vcs: AbstractVcs<*>) {
throw UnsupportedOperationException()
}
override fun showErrors(abstractVcsExceptions: List<VcsException>, tabDisplayName: String) {
throw UnsupportedOperationException()
}
override fun showErrors(exceptionGroups: Map<HotfixData, List<VcsException>>, tabDisplayName: String) {
throw UnsupportedOperationException()
}
override fun showChangesListBrowser(changelist: CommittedChangeList, title: String) {
throw UnsupportedOperationException()
}
override fun showChangesBrowser(changelists: List<CommittedChangeList>) {
throw UnsupportedOperationException()
}
override fun showChangesBrowser(changelists: List<CommittedChangeList>, title: String) {
throw UnsupportedOperationException()
}
override fun showWhatDiffersBrowser(parent: Component?, changes: Collection<Change>, title: String) {
throw UnsupportedOperationException()
}
override fun showRollbackChangesDialog(changes: List<Change>) {
throw UnsupportedOperationException()
}
override fun selectFilesToProcess(files: List<VirtualFile>, title: String, prompt: String?, singleFileTitle: String, singleFilePromptTemplate: String, confirmationOption: VcsShowConfirmationOption): Collection<VirtualFile>? {
throw UnsupportedOperationException()
}
override fun selectFilePathsToProcess(files: List<FilePath>, title: String, prompt: String?, singleFileTitle: String, singleFilePromptTemplate: String, confirmationOption: VcsShowConfirmationOption): Collection<FilePath>? {
throw UnsupportedOperationException()
}
override fun loadAndShowCommittedChangesDetails(project: Project, revision: VcsRevisionNumber, file: VirtualFile, key: VcsKey, location: RepositoryLocation?, local: Boolean) {
throw UnsupportedOperationException()
}
override fun showMergeDialog(files: List<VirtualFile>, provider: MergeProvider, mergeDialogCustomizer: MergeDialogCustomizer): List<VirtualFile> {
myMergeDialogShown = true
myMergeDelegate()
return emptyList()
}
override fun commitChanges(changes: Collection<Change>, initialChangeList: LocalChangeList, commitMessage: String, customResultHandler: CommitResultHandler?): Boolean {
myCommitDialogShown = true
val success = myCommitDelegate(commitMessage)
if (customResultHandler != null) {
if (success) {
customResultHandler.onSuccess(commitMessage)
}
else {
customResultHandler.onFailure()
}
}
return success
}
fun mergeDialogWasShown(): Boolean {
return myMergeDialogShown
}
fun commitDialogWasShown(): Boolean {
return myCommitDialogShown
}
fun onMerge(delegate : () -> Unit) {
myMergeDelegate = delegate
}
fun onCommit(delegate : (String) -> Boolean) {
myCommitDelegate = delegate
}
@Deprecated("use onCommit") fun registerHandler(handler: CommitHandler) {
myCommitDelegate = { handler.commit(it) }
}
@Deprecated("use onMerge") fun registerHandler(handler: MergeHandler) {
myMergeDelegate = { handler.showMergeDialog() }
}
@Deprecated("use onCommit") interface CommitHandler {
fun commit(commitMessage: String): Boolean
}
@Deprecated("use onMerge") interface MergeHandler {
fun showMergeDialog()
}
}
| apache-2.0 | 3d13d292614587a181d7268b66e47eb1 | 38.404762 | 227 | 0.773112 | 4.900074 | false | false | false | false |
NextFaze/dev-fun | demo/src/main/java/com/nextfaze/devfun/demo/MainScreen.kt | 1 | 4239 | package com.nextfaze.devfun.demo
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AlertDialog
import androidx.core.view.GravityCompat
import com.google.android.material.snackbar.Snackbar
import com.nextfaze.devfun.demo.inject.ActivityInjector
import com.nextfaze.devfun.demo.kotlin.startActivity
import com.nextfaze.devfun.function.DeveloperFunction
import com.nextfaze.devfun.inject.Constructable
import com.nextfaze.devfun.invoke.view.From
import com.nextfaze.devfun.invoke.view.ValueSource
import kotlinx.android.synthetic.main.app_bar_main.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.android.synthetic.main.main_activity.*
import kotlinx.android.synthetic.main.nav_header_main.*
import javax.inject.Inject
class MainActivity : BaseActivity() {
companion object {
fun start(context: Context) = context.startActivity<MainActivity>(FLAG_ACTIVITY_CLEAR_TASK)
}
@Inject lateinit var session: Session
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
setSupportActionBar(toolbarView)
floatingActionButton.setOnClickListener {
Snackbar.make(it, "Replace with your own action!", Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
object : ActionBarDrawerToggle(this, drawerLayout, toolbarView, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
override fun onDrawerStateChanged(newState: Int) {
navHeaderName?.text = getString(R.string.name_format, session.user?.givenName, session.user?.familyName)
navHeaderEmail?.text = session.user?.email
}
}.apply {
drawerLayout.addDrawerListener(this)
syncState()
}
navigationView.setNavigationItemSelectedListener setSelected@{
when (it.itemId) {
R.id.nav_camera -> {
}
R.id.nav_gallery -> {
}
R.id.nav_slideshow -> {
}
R.id.nav_manage -> {
}
R.id.nav_share -> {
}
R.id.nav_send -> {
}
}
drawerLayout.closeDrawer(GravityCompat.START)
return@setSelected true
}
helloWorldTextView.setOnClickListener {
AlertDialog.Builder(this)
.setTitle("Test Overlay Visibility")
.setMessage("Overlays should be hidden when this dialog is visible.")
.create()
.show()
}
}
override fun onBackPressed() = when {
drawerLayout.isDrawerOpen(GravityCompat.START) -> drawerLayout.closeDrawer(GravityCompat.START)
else -> super.onBackPressed()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when {
item.itemId == R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
override fun inject(injector: ActivityInjector) = injector.inject(this)
@DeveloperFunction
@SuppressLint("SetTextI18n")
private fun doubleHelloWorld() {
helloWorldTextView.text = helloWorldTextView.text.toString() + " " + helloWorldTextView.text
}
private data class SomeType(val string: String)
@Constructable
private class CurrentSomeType : ValueSource<SomeType> {
override val value get() = SomeType("Hello World")
}
/**
* TODO This should be permitted but the instance provider system doesn't see the [From] annotation.
* TODO This should be tested from test module (along with other invoke UI behaviours).
*/
@DeveloperFunction
private fun testFromInstanceResolution(@From(CurrentSomeType::class) someType: SomeType) = showToast("someType=$someType")
}
| apache-2.0 | 0a70643966127cc07c6cc7d07cf37054 | 35.543103 | 140 | 0.671149 | 4.741611 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/util/dns.kt | 1 | 1764 | package cc.aoeiuv020.panovel.util
import android.content.Context
import cc.aoeiuv020.gson.toJson
import cc.aoeiuv020.panovel.report.Reporter
import cc.aoeiuv020.panovel.server.common.toBean
import org.xbill.DNS.*
import org.xbill.DNS.config.AndroidResolverConfigProvider
import java.net.URLDecoder
/**
* Created by AoEiuV020 on 2021.05.15-18:27:30.
*/
object DnsUtils {
fun init(ctx: Context) {
AndroidResolverConfigProvider.setContext(ctx.applicationContext)
}
/**
* 获取域名txt记录,失败直接返回空,
*/
fun getTxtList(host: String): List<String> {
val lookup = Lookup(host, Type.TXT)
lookup.setResolver(SimpleResolver())
lookup.setCache(null)
val records: Array<Record>? = lookup.run()
if (lookup.result == Lookup.SUCCESSFUL) {
return records?.flatMap { (it as? TXTRecord)?.strings ?: emptyList() } ?: emptyList()
} else {
Reporter.post("获取txt记录失败: " + lookup.errorString)
}
return emptyList()
}
/**
* txt记录解析成键值对,
*/
fun parseTxt(host: String): Map<String, String> {
return getTxtList(host)
.flatMap { query ->
query.split('&').map { entry ->
entry.split('=').let {
URLDecoder.decode(it[0], Charsets.UTF_8.name()) to URLDecoder.decode(
it[1],
Charsets.UTF_8.name()
)
}
}
}.toMap()
}
/**
* txt记录解析成对象,
*/
inline fun <reified T : Any> txtToBean(host: String): T {
return parseTxt(host).toJson().toBean()
}
} | gpl-3.0 | b64dd11d2b0fa923b65e302239a7d095 | 27.15 | 97 | 0.560427 | 3.953162 | false | true | false | false |
jraska/github-client | core-android-api/src/main/java/com/jraska/github/client/core/android/DefaultActivityCallbacks.kt | 1 | 701 | package com.jraska.github.client.core.android
import android.app.Activity
import android.app.Application
import android.os.Bundle
abstract class DefaultActivityCallbacks : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityResumed(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivityDestroyed(activity: Activity) = Unit
}
| apache-2.0 | aafaf32b6c10cd14de9ce232b5fbcf99 | 32.380952 | 88 | 0.813124 | 5.231343 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/test/groovy/graphql/NestedInputSchema.kt | 1 | 1787 | package graphql
import graphql.schema.newInputObject
import graphql.schema.newObject
import graphql.schema.newSchema
import java.util.concurrent.CompletableFuture.completedFuture
val rangeType = newInputObject {
name = "Range"
field {
name = "lowerBound"
type = GraphQLInt
}
field {
name = "upperBound"
type = GraphQLInt
}
}
val filterType = newInputObject {
name = "Filter"
field {
name = "even"
type = GraphQLBoolean
}
field {
name = "range"
type = rangeType
}
}
val rootType = newObject {
name = "Root"
field<Int> {
name = "value"
argument {
name = "initialValue"
type = GraphQLInt
defaultValue = 5
}
argument {
name = "filter"
type = filterType
}
fetcher = { environment ->
val initialValue = environment.argument<Int>("initialValue")!!
val filter = environment.argument<Map<String, Any>>("filter")!!
if (filter.containsKey("even")) {
val even = filter["even"] as Boolean
if (even && initialValue % 2 != 0) {
completedFuture<Int>(0)
} else if (!even && initialValue % 2 == 0) {
completedFuture<Int>(0)
}
} else if (filter.containsKey("range")) {
val range = filter["range"] as Map<String, Int>
if (initialValue < range["lowerBound"]!! || initialValue > range["upperBound"]!!) {
completedFuture<Int>(0)
}
}
completedFuture<Int>(initialValue)
}
}
}
val nestedSchema = newSchema {
query = rootType
} | mit | 0610aa7fefe096b7671ee31f7ba7bc32 | 24.542857 | 99 | 0.520425 | 4.790885 | false | false | false | false |
ibaton/3House | mobile/src/main/java/treehou/se/habit/ui/adapter/SitemapListAdapter.kt | 1 | 9521 | package treehou.se.habit.ui.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import se.treehou.ng.ohcommunicator.connector.models.OHServer
import se.treehou.ng.ohcommunicator.connector.models.OHSitemap
import treehou.se.habit.R
import java.util.*
class SitemapListAdapter : RecyclerView.Adapter<SitemapListAdapter.SitemapBaseHolder>() {
private val items = HashMap<OHServer, SitemapItem>()
private var sitemapSelectedListener: SitemapSelectedListener = DummySitemapSelectListener()
enum class ServerState {
STATE_SUCCESS, STATE_LOADING, STATE_ERROR, STATE_CERTIFICATE_ERROR
}
class SitemapItem(var server: OHServer) {
var state: ServerState = ServerState.STATE_LOADING
var sitemaps: MutableList<OHSitemap> = ArrayList()
fun addItem(sitemap: OHSitemap) {
sitemaps.add(sitemap)
state = ServerState.STATE_SUCCESS
}
}
open inner class SitemapBaseHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var lblServer: TextView
init {
lblServer = itemView.findViewById<View>(R.id.lbl_server) as TextView
}
}
inner class SitemapHolder(view: View) : SitemapBaseHolder(view) {
var lblName: TextView
init {
lblName = itemView.findViewById<View>(R.id.lbl_sitemap) as TextView
}
}
interface SitemapSelectedListener {
fun onSelected(server: OHServer, sitemap: OHSitemap?)
fun onErrorSelected(server: OHServer)
fun onCertificateErrorSelected(server: OHServer)
}
internal inner class DummySitemapSelectListener : SitemapSelectedListener {
override fun onSelected(server: OHServer, sitemap: OHSitemap?) {}
override fun onErrorSelected(server: OHServer) {}
override fun onCertificateErrorSelected(server: OHServer) {
}
}
inner class SitemapErrorHolder(view: View) : SitemapBaseHolder(view)
inner class SitemapCertificateErrorHolder(view: View) : SitemapBaseHolder(view)
inner class SitemapLoadHolder(view: View) : SitemapBaseHolder(view)
inner class GetResult(var item: SitemapItem, var sitemap: OHSitemap?)
override fun onCreateViewHolder(parent: ViewGroup, itemType: Int): SitemapBaseHolder {
val type = ServerState.values()[itemType]
val inflater = LayoutInflater.from(parent.context)
if (ServerState.STATE_SUCCESS == type) {
val itemView = inflater.inflate(R.layout.item_sitemap, parent, false)
return SitemapHolder(itemView)
} else if (ServerState.STATE_LOADING == type) {
val itemView = inflater.inflate(R.layout.item_sitemap_load, parent, false)
return SitemapLoadHolder(itemView)
} else if (ServerState.STATE_CERTIFICATE_ERROR == type) {
val itemView = inflater.inflate(R.layout.item_sitemap_certificate_failed, parent, false)
return SitemapCertificateErrorHolder(itemView)
} else {
val serverLoadFail = inflater.inflate(R.layout.item_sitemap_failed, parent, false)
return SitemapErrorHolder(serverLoadFail)
}
}
override fun onBindViewHolder(sitemapHolder: SitemapBaseHolder, position: Int) {
val type = ServerState.values()[getItemViewType(position)]
val item = getItem(position)
val sitemap = item!!.sitemap
val server = item.item.server
if (ServerState.STATE_SUCCESS == type) {
val holder = sitemapHolder as SitemapHolder
holder.lblName.text = sitemap?.displayName
holder.lblServer.text = server.displayName
sitemapHolder.itemView.setOnClickListener { v -> sitemapSelectedListener.onSelected(server, sitemap) }
} else if (ServerState.STATE_LOADING == type) {
val holder = sitemapHolder as SitemapLoadHolder
holder.lblServer.text = server.displayName
} else if (ServerState.STATE_ERROR == type) {
val holder = sitemapHolder as SitemapErrorHolder
holder.lblServer.text = server.displayName
holder.itemView.setOnClickListener { v -> sitemapSelectedListener.onErrorSelected(server) }
} else if (ServerState.STATE_CERTIFICATE_ERROR == type) {
val holder = sitemapHolder as SitemapCertificateErrorHolder
holder.lblServer.text = server.displayName
holder.itemView.setOnClickListener { v -> sitemapSelectedListener.onCertificateErrorSelected(server) }
}
}
override fun getItemViewType(position: Int): Int {
var count = 0
for (item in items.values) {
if (ServerState.STATE_SUCCESS == item.state) {
if (position >= count && position < count + item.sitemaps.size) {
return ServerState.STATE_SUCCESS.ordinal
}
count += item.sitemaps.size
} else if (ServerState.STATE_ERROR == item.state) {
if (count == position) {
return ServerState.STATE_ERROR.ordinal
}
count++
} else if (ServerState.STATE_CERTIFICATE_ERROR == item.state) {
if (count == position) {
return ServerState.STATE_CERTIFICATE_ERROR.ordinal
}
count++
} else if (ServerState.STATE_LOADING == item.state) {
if (count == position) {
return ServerState.STATE_LOADING.ordinal
}
count++
}
}
return ServerState.STATE_LOADING.ordinal
}
override fun getItemCount(): Int {
var count = 0
for (item in items.values) {
if (item.state == ServerState.STATE_SUCCESS) {
count += item.sitemaps.size
} else {
count++
}
}
return count
}
/**
* Returns item at a certain position
*
* @param position item to grab item for
* @return
*/
fun getItem(position: Int): GetResult? {
var result: GetResult? = null
var count = 0
for (item in items.values) {
if (ServerState.STATE_SUCCESS == item.state) {
for (sitemap in item.sitemaps) {
if (count == position) {
result = GetResult(item, sitemap)
return result
}
count++
}
} else {
if (count == position) {
result = GetResult(item, null)
break
}
count++
}
}
return result
}
fun addAll(server: OHServer, sitemapIds: List<OHSitemap>) {
for (sitemap in sitemapIds) {
add(server, sitemap)
}
}
fun add(server: OHServer, sitemap: OHSitemap) {
var item: SitemapItem? = items[server]
if (item == null) {
item = SitemapItem(server)
items.put(item.server, item)
}
item.addItem(sitemap)
notifyDataSetChanged()
}
/**
* Remove all sitemap entries from adapter.
*/
fun clear() {
items.clear()
notifyItemRangeRemoved(0, items.size - 1)
}
fun remove(sitemap: OHSitemap) {
val pos = findPosition(sitemap)
remove(sitemap, pos)
}
fun remove(sitemap: OHSitemap?, position: Int) {
val item: SitemapItem? = null // TODO items.get(serverDB.getId());
if (sitemap == null) {
return
}
item!!.sitemaps.remove(sitemap)
notifyItemRemoved(position)
}
/**
* Add listener for when sitemap item is clicked
*
* @param sitemapSelectedListener listens for click on sitemap.
*/
fun setSitemapSelectedListener(sitemapSelectedListener: SitemapSelectedListener?) {
if (sitemapSelectedListener == null) {
this.sitemapSelectedListener = DummySitemapSelectListener()
return
}
this.sitemapSelectedListener = sitemapSelectedListener
}
private fun findPosition(sitemap: OHSitemap): Int {
var count = 0
for (item in items.values) {
if (ServerState.STATE_SUCCESS == item.state) {
for (sitemapIter in item.sitemaps) {
if (sitemap === sitemapIter) {
return count
}
count++
}
} else {
count++
}
}
return -1
}
/**
* Get a sitemap item. Creates a new server item if no item exists.
*
* @param server server to get sitemap item for.
* @return
*/
private fun getItem(server: OHServer): SitemapItem {
var item: SitemapItem? = items[server]
if (item == null) {
item = SitemapItem(server)
items.put(server, item)
}
return item
}
fun setServerState(server: OHServer, state: ServerState) {
val item = getItem(server)
item.state = state
notifyDataSetChanged()
}
operator fun contains(sitemap: OHSitemap): Boolean {
return items.containsKey(sitemap.server) && items[sitemap.server]?.sitemaps!!.contains(sitemap)
}
}
| epl-1.0 | d8cdab690e3934f264c904e03ac94744 | 32.407018 | 114 | 0.597101 | 4.845293 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/platform/mixin/config/MixinConfigImportOptimizer.kt | 1 | 4465 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.config
import com.google.common.collect.Comparators
import com.google.gson.Gson
import com.intellij.json.psi.JsonArray
import com.intellij.json.psi.JsonElementGenerator
import com.intellij.json.psi.JsonFile
import com.intellij.json.psi.JsonObject
import com.intellij.json.psi.JsonProperty
import com.intellij.json.psi.JsonStringLiteral
import com.intellij.lang.ImportOptimizer
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
class MixinConfigImportOptimizer : ImportOptimizer {
/**
* Sorts a number of (qualified) class names based on their package names
* and the following rules:
*
* - Each package name is compared separately
* - Default packages come first
* - Class names are only compared if in the same package
*
* Example:
* ```
* Main
* com.demonwav.mcdev.Example
* com.demonwav.mcdev.HelloWorld
* com.demonwav.mcdev.asset.Assets
* com.demonwav.mcdev.util.ActionData
* ```
*/
private object ClassPackageComparator : Comparator<String> {
// TODO: Consider implementing with Comparator.lexicographical() (in sorting.kt)
// Different here is that the class name is considered separately,
// so that default packages come first
override fun compare(class1: String, class2: String): Int {
val parts1 = class1.split('.')
val parts2 = class2.split('.')
val end = Math.min(parts1.size - 1, parts2.size - 1)
for (i in 0 until end) {
val result = parts1[i].compareTo(parts2[i], ignoreCase = true)
if (result != 0) {
return result
}
}
if (parts1.size != parts2.size) {
// Default package always comes first
return Integer.compare(parts1.size, parts2.size)
}
// Compare class names
return parts1[end].compareTo(parts2[end], ignoreCase = true)
}
}
override fun supports(file: PsiFile) = file is JsonFile && file.fileType == MixinConfigFileType
override fun processFile(file: PsiFile): Runnable {
if (file !is JsonFile) {
return EmptyRunnable.getInstance()
}
val root = file.topLevelValue as? JsonObject ?: return EmptyRunnable.getInstance()
val mixins = processMixins(root.findProperty("mixins"))
val server = processMixins(root.findProperty("server"))
val client = processMixins(root.findProperty("client"))
if (mixins != null || server != null || client != null) {
return Task(file, mixins, server, client)
}
return EmptyRunnable.getInstance()
}
private fun processMixins(property: JsonProperty?): JsonArray? {
val mixins = property?.value as? JsonArray ?: return null
val classes = mixins.valueList.mapNotNull { (it as? JsonStringLiteral)?.value }
if (Comparators.isInStrictOrder(classes, ClassPackageComparator)) {
return null
}
// Kind of lazy here, serialize the sorted list and let IntelliJ parse it
val classesSorted = classes.toSortedSet(ClassPackageComparator)
return JsonElementGenerator(property.project).createValue(Gson().toJson(classesSorted))
}
private class Task(
private val file: JsonFile,
private val mixins: JsonArray?,
private val server: JsonArray?,
private val client: JsonArray?
) : Runnable {
override fun run() {
val manager = PsiDocumentManager.getInstance(file.project)
manager.getDocument(file)?.let { manager.commitDocument(it) }
val root = file.topLevelValue as? JsonObject ?: return
replaceProperty(root, "mixins", mixins)
replaceProperty(root, "server", server)
replaceProperty(root, "client", client)
}
private fun replaceProperty(obj: JsonObject, propertyName: String, newValue: PsiElement?) {
newValue ?: return
val property = obj.findProperty(propertyName) ?: return
property.value?.replace(newValue)
}
}
}
| mit | 9cc2f4467bb10a97c0189d045cfedba5 | 33.882813 | 99 | 0.641881 | 4.546843 | false | false | false | false |
Setekh/Gleipnir-Graphics | src/main/kotlin/eu/corvus/corax/scene/Spatial.kt | 1 | 1639 |
package eu.corvus.corax.scene
import eu.corvus.corax.scripts.Script
import org.joml.Matrix4f
/**
* Class that represent a positional space
* It can handle:
* - transforms
* - pre-render queue
*
* @author Vlad Ravenholm on 11/24/2019
*/
open class Spatial(name: String = "Spatial") : Node(name) {
val transform: Transform =
Transform()
val worldTransform: Transform =
Transform()
var alwaysCompute = false
val worldMatrix = Matrix4f()
private var shouldCompute = true
fun forceUpdate() {
children.forEach { (it as? Spatial)?.forceUpdate() }
shouldCompute = true
}
protected open fun computeWorldTransform() {
val parent = this.parent
worldTransform.set(transform)
if (parent is Spatial) { // For each child, set the update flag to shouldUpdate = true
worldTransform.mergeParentTransform(parent.worldTransform)
}
worldMatrix.identity()
.translate(worldTransform.translation)
.rotate(worldTransform.rotation)
.scale(worldTransform.scale)
shouldCompute = false
}
open fun onUpdate(tpf: Float): Boolean = false
override fun appendChild(child: Node) {
super.appendChild(child)
shouldCompute = true
}
override fun removeChild(child: Node) {
super.removeChild(child)
shouldCompute = true
}
fun update(tpf: Float) {
val shouldUpdate = onUpdate(tpf)
script?.onUpdate(tpf)
if (alwaysCompute || shouldCompute || shouldUpdate) {
computeWorldTransform()
}
}
} | bsd-3-clause | 221aa9f10b158d6a158126ab99414a3c | 22.768116 | 94 | 0.632093 | 4.41779 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/accessibility/Types.kt | 1 | 10910 | package pl.wendigo.chrome.api.accessibility
/**
* Unique accessibility node identifier.
*
* @link [Accessibility#AXNodeId](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXNodeId) type documentation.
*/
typealias AXNodeId = String
/**
* Enum of possible property types.
*
* @link [Accessibility#AXValueType](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXValueType) type documentation.
*/
@kotlinx.serialization.Serializable
enum class AXValueType {
@kotlinx.serialization.SerialName("boolean")
BOOLEAN,
@kotlinx.serialization.SerialName("tristate")
TRISTATE,
@kotlinx.serialization.SerialName("booleanOrUndefined")
BOOLEANORUNDEFINED,
@kotlinx.serialization.SerialName("idref")
IDREF,
@kotlinx.serialization.SerialName("idrefList")
IDREFLIST,
@kotlinx.serialization.SerialName("integer")
INTEGER,
@kotlinx.serialization.SerialName("node")
NODE,
@kotlinx.serialization.SerialName("nodeList")
NODELIST,
@kotlinx.serialization.SerialName("number")
NUMBER,
@kotlinx.serialization.SerialName("string")
STRING,
@kotlinx.serialization.SerialName("computedString")
COMPUTEDSTRING,
@kotlinx.serialization.SerialName("token")
TOKEN,
@kotlinx.serialization.SerialName("tokenList")
TOKENLIST,
@kotlinx.serialization.SerialName("domRelation")
DOMRELATION,
@kotlinx.serialization.SerialName("role")
ROLE,
@kotlinx.serialization.SerialName("internalRole")
INTERNALROLE,
@kotlinx.serialization.SerialName("valueUndefined")
VALUEUNDEFINED;
}
/**
* Enum of possible property sources.
*
* @link [Accessibility#AXValueSourceType](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXValueSourceType) type documentation.
*/
@kotlinx.serialization.Serializable
enum class AXValueSourceType {
@kotlinx.serialization.SerialName("attribute")
ATTRIBUTE,
@kotlinx.serialization.SerialName("implicit")
IMPLICIT,
@kotlinx.serialization.SerialName("style")
STYLE,
@kotlinx.serialization.SerialName("contents")
CONTENTS,
@kotlinx.serialization.SerialName("placeholder")
PLACEHOLDER,
@kotlinx.serialization.SerialName("relatedElement")
RELATEDELEMENT;
}
/**
* Enum of possible native property sources (as a subtype of a particular AXValueSourceType).
*
* @link [Accessibility#AXValueNativeSourceType](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXValueNativeSourceType) type documentation.
*/
@kotlinx.serialization.Serializable
enum class AXValueNativeSourceType {
@kotlinx.serialization.SerialName("figcaption")
FIGCAPTION,
@kotlinx.serialization.SerialName("label")
LABEL,
@kotlinx.serialization.SerialName("labelfor")
LABELFOR,
@kotlinx.serialization.SerialName("labelwrapped")
LABELWRAPPED,
@kotlinx.serialization.SerialName("legend")
LEGEND,
@kotlinx.serialization.SerialName("rubyannotation")
RUBYANNOTATION,
@kotlinx.serialization.SerialName("tablecaption")
TABLECAPTION,
@kotlinx.serialization.SerialName("title")
TITLE,
@kotlinx.serialization.SerialName("other")
OTHER;
}
/**
* A single source for a computed AX property.
*
* @link [Accessibility#AXValueSource](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXValueSource) type documentation.
*/
@kotlinx.serialization.Serializable
data class AXValueSource(
/**
* What type of source this is.
*/
val type: AXValueSourceType,
/**
* The value of this property source.
*/
val value: AXValue? = null,
/**
* The name of the relevant attribute, if any.
*/
val attribute: String? = null,
/**
* The value of the relevant attribute, if any.
*/
val attributeValue: AXValue? = null,
/**
* Whether this source is superseded by a higher priority source.
*/
val superseded: Boolean? = null,
/**
* The native markup source for this value, e.g. a <label> element.
*/
val nativeSource: AXValueNativeSourceType? = null,
/**
* The value, such as a node or node list, of the native source.
*/
val nativeSourceValue: AXValue? = null,
/**
* Whether the value for this property is invalid.
*/
val invalid: Boolean? = null,
/**
* Reason for the value being invalid, if it is.
*/
val invalidReason: String? = null
)
/**
*
*
* @link [Accessibility#AXRelatedNode](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXRelatedNode) type documentation.
*/
@kotlinx.serialization.Serializable
data class AXRelatedNode(
/**
* The BackendNodeId of the related DOM node.
*/
val backendDOMNodeId: pl.wendigo.chrome.api.dom.BackendNodeId,
/**
* The IDRef value provided, if any.
*/
val idref: String? = null,
/**
* The text alternative of this node in the current context.
*/
val text: String? = null
)
/**
*
*
* @link [Accessibility#AXProperty](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXProperty) type documentation.
*/
@kotlinx.serialization.Serializable
data class AXProperty(
/**
* The name of this property.
*/
val name: AXPropertyName,
/**
* The value of this property.
*/
val value: AXValue
)
/**
* A single computed AX property.
*
* @link [Accessibility#AXValue](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXValue) type documentation.
*/
@kotlinx.serialization.Serializable
data class AXValue(
/**
* The type of this value.
*/
val type: AXValueType,
/**
* The computed value of this property.
*/
val value: kotlinx.serialization.json.JsonElement? = null,
/**
* One or more related nodes, if applicable.
*/
val relatedNodes: List<AXRelatedNode>? = null,
/**
* The sources which contributed to the computation of this property.
*/
val sources: List<AXValueSource>? = null
)
/**
* Values of AXProperty name:
- from 'busy' to 'roledescription': states which apply to every AX node
- from 'live' to 'root': attributes which apply to nodes in live regions
- from 'autocomplete' to 'valuetext': attributes which apply to widgets
- from 'checked' to 'selected': states which apply to widgets
- from 'activedescendant' to 'owns' - relationships between elements other than parent/child/sibling.
*
* @link [Accessibility#AXPropertyName](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXPropertyName) type documentation.
*/
@kotlinx.serialization.Serializable
enum class AXPropertyName {
@kotlinx.serialization.SerialName("busy")
BUSY,
@kotlinx.serialization.SerialName("disabled")
DISABLED,
@kotlinx.serialization.SerialName("editable")
EDITABLE,
@kotlinx.serialization.SerialName("focusable")
FOCUSABLE,
@kotlinx.serialization.SerialName("focused")
FOCUSED,
@kotlinx.serialization.SerialName("hidden")
HIDDEN,
@kotlinx.serialization.SerialName("hiddenRoot")
HIDDENROOT,
@kotlinx.serialization.SerialName("invalid")
INVALID,
@kotlinx.serialization.SerialName("keyshortcuts")
KEYSHORTCUTS,
@kotlinx.serialization.SerialName("settable")
SETTABLE,
@kotlinx.serialization.SerialName("roledescription")
ROLEDESCRIPTION,
@kotlinx.serialization.SerialName("live")
LIVE,
@kotlinx.serialization.SerialName("atomic")
ATOMIC,
@kotlinx.serialization.SerialName("relevant")
RELEVANT,
@kotlinx.serialization.SerialName("root")
ROOT,
@kotlinx.serialization.SerialName("autocomplete")
AUTOCOMPLETE,
@kotlinx.serialization.SerialName("hasPopup")
HASPOPUP,
@kotlinx.serialization.SerialName("level")
LEVEL,
@kotlinx.serialization.SerialName("multiselectable")
MULTISELECTABLE,
@kotlinx.serialization.SerialName("orientation")
ORIENTATION,
@kotlinx.serialization.SerialName("multiline")
MULTILINE,
@kotlinx.serialization.SerialName("readonly")
READONLY,
@kotlinx.serialization.SerialName("required")
REQUIRED,
@kotlinx.serialization.SerialName("valuemin")
VALUEMIN,
@kotlinx.serialization.SerialName("valuemax")
VALUEMAX,
@kotlinx.serialization.SerialName("valuetext")
VALUETEXT,
@kotlinx.serialization.SerialName("checked")
CHECKED,
@kotlinx.serialization.SerialName("expanded")
EXPANDED,
@kotlinx.serialization.SerialName("modal")
MODAL,
@kotlinx.serialization.SerialName("pressed")
PRESSED,
@kotlinx.serialization.SerialName("selected")
SELECTED,
@kotlinx.serialization.SerialName("activedescendant")
ACTIVEDESCENDANT,
@kotlinx.serialization.SerialName("controls")
CONTROLS,
@kotlinx.serialization.SerialName("describedby")
DESCRIBEDBY,
@kotlinx.serialization.SerialName("details")
DETAILS,
@kotlinx.serialization.SerialName("errormessage")
ERRORMESSAGE,
@kotlinx.serialization.SerialName("flowto")
FLOWTO,
@kotlinx.serialization.SerialName("labelledby")
LABELLEDBY,
@kotlinx.serialization.SerialName("owns")
OWNS;
}
/**
* A node in the accessibility tree.
*
* @link [Accessibility#AXNode](https://chromedevtools.github.io/devtools-protocol/tot/Accessibility#type-AXNode) type documentation.
*/
@kotlinx.serialization.Serializable
data class AXNode(
/**
* Unique identifier for this node.
*/
val nodeId: AXNodeId,
/**
* Whether this node is ignored for accessibility
*/
val ignored: Boolean,
/**
* Collection of reasons why this node is hidden.
*/
val ignoredReasons: List<AXProperty>? = null,
/**
* This `Node`'s role, whether explicit or implicit.
*/
val role: AXValue? = null,
/**
* The accessible name for this `Node`.
*/
val name: AXValue? = null,
/**
* The accessible description for this `Node`.
*/
val description: AXValue? = null,
/**
* The value for this `Node`.
*/
val value: AXValue? = null,
/**
* All other properties
*/
val properties: List<AXProperty>? = null,
/**
* IDs for each of this node's child nodes.
*/
val childIds: List<AXNodeId>? = null,
/**
* The backend ID for the associated DOM node, if any.
*/
val backendDOMNodeId: pl.wendigo.chrome.api.dom.BackendNodeId? = null
)
| apache-2.0 | ba4697c5900c928f11dfe055de31cce6 | 23.572072 | 167 | 0.681943 | 4.250097 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/AffirmElementUI.kt | 1 | 1066 | package com.stripe.android.ui.core.elements
import androidx.annotation.RestrictTo
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.stripe.android.ui.core.R
import com.stripe.android.ui.core.paymentsColors
import com.stripe.android.uicore.text.EmbeddableImage
import com.stripe.android.uicore.text.Html
@Composable
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun AffirmElementUI() {
Html(
html = stringResource(id = R.string.affirm_buy_now_pay_later),
imageLoader = mapOf(
"affirm" to EmbeddableImage.Drawable(
R.drawable.stripe_ic_affirm_logo,
R.string.stripe_paymentsheet_payment_method_affirm
)
),
color = MaterialTheme.paymentsColors.subtitle,
style = MaterialTheme.typography.h6,
modifier = Modifier.padding(vertical = 8.dp)
)
}
| mit | a1f1f636e0aa300228cd57502049b803 | 34.533333 | 70 | 0.738274 | 4.022642 | false | false | false | false |
mihmuh/IntelliJConsole | Konsole/src/com/intellij/idekonsole/scripting/collections/impl/sequencelikeimpl.kt | 1 | 1367 | package com.intellij.idekonsole.scripting.collections.impl
import com.intellij.idekonsole.context.Context
import com.intellij.idekonsole.context.runRead
import com.intellij.idekonsole.scripting.collections.SequenceLike
import com.intellij.util.Processor
fun <T> sequenceLikeProcessor(f: (Processor<T>) -> Unit): SequenceLike<T> = object : SequenceLike<T> {
override fun forEach(action: (T) -> Unit) = f.invoke(Processor { action(it); true })
}
class SequenceSequenceLike<out T>(val sequence: Sequence<T>) : SequenceLike<T> {
var context = Context.instance()
override fun forEach(action: (T) -> Unit) {
val iterator = sequence.iterator()
var hasNext: Boolean = true
while (hasNext) {
var next: T? = null
runRead(context) {
hasNext = iterator.hasNext()
if (hasNext) {
next = iterator.next()
}
}
if (hasNext) {
action(next!!)
}
}
}
}
fun <T> SequenceLike<T>.wrapWithRead(): SequenceLike<T> {
var context = Context.instance()
return object : SequenceLike<T> {
override fun forEach(action: (T) -> Unit) {
[email protected] {
runRead(context) {
action(it)
}
}
}
}
} | gpl-3.0 | a75d0cb88c635422ed5a2248bd923afd | 30.813953 | 102 | 0.574982 | 4.11747 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/SequenceAt.kt | 1 | 2880 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * 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.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.linalg.api.ops.impl.shape.tensorops.TensorArray
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
/**
* A port of sequence_at.py from onnx tensorflow for samediff:
* https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/sequence_at.py
*
* @author Adam Gibson
*/
@PreHookRule(nodeNames = [],opNames = ["SequenceAt"],frameworkName = "onnx")
class SequenceAt : PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
val input = sd.getVariable(op.inputsToOp[0])
val position = if(op.inputsToOp.size < 2) sd.constant(-1) else {
sd.getVariable(op.inputsToOp[1])
}
//access the associated list we are writing to
val outputVar = TensorArray.itemAtIndex(sd,arrayOf(input,position),outputNames[0])
val op = sd.ops[outputVar.name()]
return mapOf(outputVar.name() to listOf(outputVar))
}
} | apache-2.0 | 231f1846bb3d0f74a8411b9eb371f598 | 42.651515 | 184 | 0.704167 | 4.155844 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sensors/services/SubscribableSensorService.kt | 2 | 3293 | // Copyright 2015-present 650 Industries. All rights reserved.
package abi44_0_0.expo.modules.sensors.services
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener2
import abi44_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi44_0_0.expo.modules.interfaces.sensors.SensorServiceSubscriptionInterface
import java.util.*
abstract class SubscribableSensorService internal constructor(reactContext: Context?) : BaseSensorService(reactContext), SensorServiceInterface {
private var mListenersCount = 0
private val mSensorEventListenerLastUpdateMap: MutableMap<SensorServiceSubscription, Long> = WeakHashMap()
// BaseService
override fun onExperienceForegrounded() {
updateObserving()
}
override fun onExperienceBackgrounded() {
updateObserving()
}
// Modules API
override fun createSubscriptionForListener(listener: SensorEventListener2): SensorServiceSubscriptionInterface {
val sensorServiceSubscription = SensorServiceSubscription(this, listener)
mSensorEventListenerLastUpdateMap[sensorServiceSubscription] = 0L
return sensorServiceSubscription
}
// SensorServiceSubscription API
fun onSubscriptionEnabledChanged(sensorServiceSubscription: SensorServiceSubscription) {
if (sensorServiceSubscription.isEnabled) {
mListenersCount += 1
} else {
mListenersCount -= 1
}
updateObserving()
}
fun removeSubscription(sensorServiceSubscription: SensorServiceSubscription) {
mSensorEventListenerLastUpdateMap.remove(sensorServiceSubscription)
}
// android.hardware.SensorEventListener2
override fun onSensorChanged(sensorEvent: SensorEvent) {
if (sensorEvent.sensor.type == sensorType) {
val currentTime = System.currentTimeMillis()
val listeners: Set<SensorServiceSubscription> = mSensorEventListenerLastUpdateMap.keys
for (sensorServiceSubscription in listeners) {
if (sensorServiceSubscription.isEnabled) {
val lastUpdate = mSensorEventListenerLastUpdateMap[sensorServiceSubscription] ?: 0L
if (currentTime - lastUpdate > sensorServiceSubscription.updateInterval) {
sensorServiceSubscription.sensorEventListener.onSensorChanged(sensorEvent)
mSensorEventListenerLastUpdateMap[sensorServiceSubscription] = currentTime
}
}
}
}
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
if (sensor.type == sensorType) {
for (subscription in mSensorEventListenerLastUpdateMap.keys) {
if (subscription.isEnabled) {
subscription.sensorEventListener.onAccuracyChanged(sensor, accuracy)
}
}
}
}
override fun onFlushCompleted(sensor: Sensor) {
if (sensor.type == sensorType) {
for (subscription in mSensorEventListenerLastUpdateMap.keys) {
if (subscription.isEnabled) {
subscription.sensorEventListener.onFlushCompleted(sensor)
}
}
}
}
// Private helpers
private fun updateObserving() {
// Start/stop observing according to the experience state
if (mListenersCount > 0 && experienceIsForegrounded) {
super.startObserving()
} else {
super.stopObserving()
}
}
}
| bsd-3-clause | 84601e9ce0405b1877974d2f66c2ebcc | 34.793478 | 145 | 0.751898 | 5.019817 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/annotator/RsDoctestAnnotatorTest.kt | 2 | 5813 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import org.rust.CheckTestmarkHit
import org.rust.ProjectDescriptor
import org.rust.WithDependencyRustProjectDescriptor
import org.rust.ide.injected.DoctestInfo
@ProjectDescriptor(WithDependencyRustProjectDescriptor::class)
class RsDoctestAnnotatorTest : RsAnnotatorTestBase(RsDoctestAnnotator::class) {
fun `test no injection 1`() = doTest("""
|/// ``` ```
|fn foo() {}
|""")
fun `test no injection 2`() = doTest("""
|/// ```
|/// ```
|fn foo() {}
|""")
fun `test single line injection`() = doTest("""
|/// ```
|///<info> <inject>let a = 0;
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test multi line injection`() = doTest("""
|/// ```
|///<info> <inject>let a = 0;
|</inject></info>///<info> <inject>let b = 0;
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test multi line injection with empty line`() = doTest("""
|/// ```
|///<info> <inject>let a = 0;
|</inject></info>///<info>
|</info>///<info> <inject>let a = 0;
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test acceptable 'lang' string`() = doTest("""
|/// ```rust, allow_fail, should_panic, no_run, test_harness, edition2018, edition2015
|///<info> <inject>let a = 0;
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test no injection with unacceptable 'lang' string`() = doTest("""
|/// ```foobar
|///let a = 0;
|/// ```
|fn foo() {}
|""")
fun `test no injection with unacceptable 'lang' string contain acceptable parts`() = doTest("""
|/// ```rust, foobar
|///let a = 0;
|/// ```
|fn foo() {}
|""")
fun `test '# ' escape`() = doTest("""
|/// ```
|///<info> # <inject>extern crate foobar;
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test '##' escape`() = doTest("""
|/// ```
|///<info> #<inject>#![allow(deprecated)]
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test '#' escape`() = doTest("""
|/// ```
|///<info> #<inject>
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test no infix in block comment`() = doTest("""
|/** ```
|<info> <inject>let a = 0;
|</inject></info> ```*/
|fn foo() {}
|""")
fun `test no infix in block comment multiline`() = doTest("""
|/** ```
|<info> <inject>let a = 0;
|</inject></info><info> <inject>let b = 0;
|</inject></info>```
|*/
|fn foo() {}
|""")
fun `test no injection in non-lib target`() = checkByText("""
/// ```
/// let a = 0;
/// ```
fn foo() {}
""", checkInfo = true)
@BatchMode
fun `test no highlighting in batch mod`() = doTest("""
|/// ```
|/// <inject>let a = 0;
|</inject>/// ```
|fn foo() {}
|""")
fun `test indented code fence`() = doTest("""
|/// foo
|/// ```
|///<info> <inject>let a = 0;
|</inject></info>///<info>
|</info>///<info> <inject>let a = 0;
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test indented code fence 2`() = doTest("""
|/// foo
|/// ```
|///<info> <inject>let a = 0;
|</inject></info>///<info> <caret>
|</info>///<info> <inject>let a = 0;
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test indented code fence 3`() = doTest("""
|/// foo
|/// ```
|///<info> <inject>let a = 0;
|</inject></info>///<info> <caret>
|</info>///<info> <inject>let a = 0;
|</inject></info>/// ```
|fn foo() {}
|""")
fun `test code fence with 4 backticks`() = doTest("""
|/// ````
|///<info> <inject>let a = 0;
|</inject></info>/// ````
|fn foo() {}
|""")
fun `test code fence with tildes`() = doTest("""
|/// ~~~
|///<info> <inject>let a = 0;
|</inject></info>/// ~~~
|fn foo() {}
|""")
fun `test incomplete code fence`() = doTest("""
|/// ```
|///<info>
|</info>///<info> <error>`</error></info>
|fn foo() {}
|""")
fun `test code before indent`() = doTest("""
|/// ```
|///<info> <inject>let a = 0;
|</inject></info>///<info> <inject>let b = 0;
|</inject></info>/// ```
|fn foo() {}
|""")
@CheckTestmarkHit(DoctestInfo.Testmarks.UnbalancedCodeFence::class)
fun `test injection broken into two parts 1`() = doTest("""
|/// ```
|///<info> <inject>let a = 0;</inject></info>
|//
|/// let b = 1;
|/// ```
|/// no injection here
|/// ```
|fn foo() {}
|""")
@CheckTestmarkHit(DoctestInfo.Testmarks.UnbalancedCodeFence::class)
fun `test injection broken into two parts 2`() = doTest("""
|/// ```
|///<info> <inject>let a = 0;</inject></info>
|fn foo() {
| //! let b = 1;
| //! ```
| //! no injection here
| //! ```
}
|""")
fun doTest(code: String) = checkByFileTree(
"//- lib.rs\n/*caret*/${code.trimMargin()}",
checkWarn = false,
checkInfo = true,
checkWeakWarn = false,
ignoreExtraHighlighting = false
)
}
| mit | 6162d5e0577b7ae4d2727923e02980bf | 26.163551 | 99 | 0.418889 | 3.816809 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/annotator/fixes/AddMutableFix.kt | 3 | 2960 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator.fixes
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.psi.ext.RsBindingModeKind.BindByReference
import org.rust.lang.core.psi.ext.RsBindingModeKind.BindByValue
import org.rust.lang.core.types.declaration
import org.rust.lang.core.types.ty.TyReference
import org.rust.lang.core.types.type
class AddMutableFix(binding: RsNamedElement) : LocalQuickFixAndIntentionActionOnPsiElement(binding) {
private val _text = "Make `${binding.name}` mutable"
override fun getFamilyName(): String = "Make mutable"
override fun getText(): String = _text
val mutable = true
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
updateMutable(project, startElement as RsNamedElement, mutable)
}
companion object {
fun createIfCompatible(expr: RsExpr): AddMutableFix? {
val declaration = expr.declaration as? RsNamedElement ?: return null
return when {
declaration is RsSelfParameter -> {
AddMutableFix(declaration)
}
declaration is RsPatBinding && declaration.kind is BindByValue
&& (declaration.isArg || expr.type !is TyReference) -> {
AddMutableFix(declaration)
}
else -> null
}
}
}
}
fun updateMutable(project: Project, binding: RsNamedElement, mutable: Boolean = true) {
when (binding) {
is RsPatBinding -> {
val parameter = binding.ancestorStrict<RsValueParameter>()
val type = parameter?.typeReference?.skipParens()
if (type is RsRefLikeType) {
val typeReference = type.typeReference ?: return
val newParameterExpr = RsPsiFactory(project)
.createValueParameter(parameter.pat?.text!!, typeReference, mutable, lifetime = type.lifetime)
parameter.replace(newParameterExpr)
return
}
val isRef = binding.kind is BindByReference
val newPatBinding = RsPsiFactory(project).createPatBinding(binding.identifier.text, mutable, isRef)
binding.replace(newPatBinding)
}
is RsSelfParameter -> {
val newSelf: RsSelfParameter = if (binding.isRef) {
RsPsiFactory(project).createSelfReference(true)
} else {
RsPsiFactory(project).createSelf(true)
}
binding.replace(newSelf)
}
}
}
| mit | 950f31be73a4929f2c914eaed4f6ebb1 | 37.947368 | 125 | 0.653716 | 4.805195 | false | false | false | false |
erokhins/KotlinCV | Utils/src/org/hanuna/math/Math.kt | 1 | 584 | package org.hanuna.math
/**
* Created by smevok on 5/11/14.
*/
public fun Int.myMod(module: Int): Int {
val java_mod = this % module
return if (java_mod >= 0)
java_mod
else
java_mod + module
}
/**
* Example:
* -1, 5 -> (mod2size = 9) -> 10 - 1 - 9 = 0
* 5, 5 -> (mod2size = 5) -> 10 - 1 - 5 = 4
*/
public fun Int.toCorrectImageNumber(size: Int): Int {
val mod2size = myMod(2 * size)
return if (mod2size < size)
mod2size
else
2 * size - 1 - mod2size
}
public fun Byte.to255Int(): Int = this.toInt() and 0xff | apache-2.0 | f220feeeb775d304e7767b1b5c25d0d9 | 19.172414 | 55 | 0.546233 | 2.834951 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/utils/CallInfo.kt | 3 | 4177 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.utils
import org.rust.ide.presentation.render
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.emptySubstitution
import org.rust.lang.core.types.inference
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyFunction
import org.rust.lang.core.types.ty.TyUnknown
import org.rust.lang.core.types.type
class CallInfo private constructor(
val methodName: String?,
val selfParameter: String?,
val parameters: List<Parameter>
) {
class Parameter(val typeRef: RsTypeReference?, val pattern: String? = null, val type: Ty? = null) {
fun renderType(): String {
return if (type != null && type !is TyUnknown) {
type.render(includeLifetimeArguments = true)
} else {
typeRef?.substAndGetText(emptySubstitution) ?: "_"
}
}
}
companion object {
fun resolve(call: RsCallExpr): CallInfo? {
val fn = (call.expr as? RsPathExpr)?.path?.reference?.resolve() ?: return null
val ty = call.expr.type as? TyFunction ?: return null
return when (fn) {
is RsFunction -> buildFunctionParameters(fn, ty)
else -> buildFunctionLike(fn, ty)
}
}
fun resolve(methodCall: RsMethodCall): CallInfo? {
val function = (methodCall.reference.resolve() as? RsFunction) ?: return null
val type = methodCall.inference?.getResolvedMethodType(methodCall) ?: return null
return buildFunctionParameters(function, type)
}
private fun buildFunctionLike(fn: RsElement, ty: TyFunction): CallInfo? {
val parameters = getFunctionLikeParameters(fn) ?: return null
return CallInfo(buildParameters(ty.paramTypes, parameters))
}
private fun getFunctionLikeParameters(element: RsElement): List<Pair<String?, RsTypeReference?>>? {
return when {
element is RsEnumVariant -> element.positionalFields.map { null to it.typeReference }
element is RsStructItem && element.isTupleStruct ->
element.tupleFields?.tupleFieldDeclList?.map { null to it.typeReference }
element is RsPatBinding -> {
val decl = element.ancestorStrict<RsLetDecl>() ?: return null
val lambda = decl.expr as? RsLambdaExpr ?: return null
lambda.valueParameters.map { (it.patText ?: "_") to it.typeReference }
}
else -> null
}
}
private fun buildFunctionParameters(function: RsFunction, ty: TyFunction): CallInfo {
val types = run {
val types = ty.paramTypes
if (function.isMethod) {
types.drop(1)
} else {
types
}
}
val parameters = function.valueParameters.map {
val pattern = it.patText ?: "_"
val type = it.typeReference
pattern to type
}
return CallInfo(function, buildParameters(types, parameters))
}
private fun buildParameters(
argumentTypes: List<Ty>,
parameters: List<Pair<String?, RsTypeReference?>>,
): List<Parameter> {
return argumentTypes.zip(parameters).map { (type, param) ->
val (name, parameterType) = param
Parameter(parameterType, name, type)
}
}
}
private constructor(fn: RsFunction, parameters: List<Parameter>) : this(
fn.name,
fn.selfParameter?.let { self ->
buildString {
if (self.isRef) append("&")
if (self.mutability.isMut) append("mut ")
append("self")
}
},
parameters
)
private constructor(parameters: List<Parameter>) : this(
null,
null,
parameters
)
}
| mit | 862c43c9d35fb8e2d84ae3626e98828e | 35.640351 | 107 | 0.576969 | 4.868298 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/TestSelectorScreen.kt | 1 | 3645 | package com.teamwizardry.librarianlib.facade.test
import com.teamwizardry.librarianlib.core.util.Client
import com.teamwizardry.librarianlib.math.Vec2d
import com.teamwizardry.librarianlib.math.clamp
import com.teamwizardry.librarianlib.core.util.vec
import com.teamwizardry.librarianlib.courier.CourierClientPlayNetworking
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking
import net.minecraft.client.gui.screen.Screen
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.text.LiteralText
import net.minecraft.util.Identifier
import java.awt.Color
import kotlin.math.max
class TestSelectorScreen(name: String, val selector: TestSelector): Screen(LiteralText(name)) {
val entries: List<SelectorEntry> = selector.entries
val itemHeight: Int = Client.textRenderer.fontHeight + 1
val indentWidth: Int = 6
val border: Int = 3
val size: Vec2d = vec(300, 20 * itemHeight)
var guiPos: Vec2d = vec(0, 0)
var scrollAmount: Double = 0.0
val scrollMax: Double get() = max(0.0, entries.size * itemHeight + size.y)
override fun init() {
super.init()
guiPos = (vec(width, height) - this.size) / 2
}
override fun render(matrixStack: MatrixStack, mouseX: Int, mouseY: Int, partialTicks: Float) {
super.render(matrixStack, mouseX, mouseY, partialTicks)
fill(matrixStack,
guiPos.xi - border, guiPos.yi - border,
guiPos.xi + size.xi + border, guiPos.yi + size.yi + border,
Color.lightGray.rgb
)
val relX = mouseX - guiPos.xi
val relY = mouseY - guiPos.yi
val scrollCount = (scrollAmount / itemHeight).toInt()
val hoveredIndex = if(relX < 0 || relX > size.x) -1 else relY / itemHeight + scrollCount
for(i in scrollCount until entries.size) {
val entry = entries[i]
if(i == hoveredIndex && entry.screen != null) {
fill(matrixStack,
guiPos.xi, guiPos.yi + i * itemHeight,
guiPos.xi + size.xi, guiPos.yi + i * itemHeight + Client.textRenderer.fontHeight,
Color.gray.rgb
)
}
Client.textRenderer.draw(
matrixStack,
entry.path.name,
guiPos.xf + indentWidth * entry.path.depth,
guiPos.yf + i * itemHeight,
Color(0, 0, 0, 0).rgb
)
}
}
override fun mouseScrolled(x: Double, y: Double, delta: Double): Boolean {
scrollAmount = (scrollAmount + delta).clamp(0.0, scrollMax)
return false
}
override fun mouseClicked(mouseX: Double, mouseY: Double, button: Int): Boolean {
val relX = (mouseX - guiPos.x).toInt()
val relY = (mouseY - guiPos.y).toInt()
val scrollCount = (scrollAmount / itemHeight).toInt()
val hoveredIndex = if(relX < 0 || relX > size.x) -1 else relY / itemHeight + scrollCount
val entry = entries.getOrNull(hoveredIndex)
val start = System.nanoTime()
val screen = entry?.create()
if(screen != null) {
logger.debug("Creating `${entry.path}` screen took ${(System.nanoTime() - start) / 1_000_000} ms")
CourierClientPlayNetworking.send(SyncSelectionPacket.type, SyncSelectionPacket(entry.path.toString()))
logger.debug("Sent path `${entry.path}` to be recorded for reopening")
Client.openScreen(screen)
}
return false
}
companion object {
private val logger = LibLibFacadeTest.logManager.makeLogger<TestSelectorScreen>()
}
}
| lgpl-3.0 | b3f48bbcc7f4ac3048e5ba7fc76155f2 | 36.193878 | 114 | 0.635665 | 4.036545 | false | true | false | false |
charleskorn/batect | app/src/main/kotlin/batect/execution/model/rules/run/WaitForContainerToBecomeHealthyStepRule.kt | 1 | 1943 | /*
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.execution.model.rules.run
import batect.config.Container
import batect.execution.model.events.ContainerCreatedEvent
import batect.execution.model.events.ContainerStartedEvent
import batect.execution.model.events.TaskEvent
import batect.execution.model.rules.TaskStepRule
import batect.execution.model.rules.TaskStepRuleEvaluationResult
import batect.execution.model.steps.WaitForContainerToBecomeHealthyStep
data class WaitForContainerToBecomeHealthyStepRule(val container: Container) : TaskStepRule() {
override fun evaluate(pastEvents: Set<TaskEvent>): TaskStepRuleEvaluationResult {
if (!containerHasStarted(pastEvents)) {
return TaskStepRuleEvaluationResult.NotReady
}
val dockerContainer = findDockerContainer(pastEvents)
return TaskStepRuleEvaluationResult.Ready(WaitForContainerToBecomeHealthyStep(container, dockerContainer))
}
private fun findDockerContainer(pastEvents: Set<TaskEvent>) =
pastEvents
.singleInstance<ContainerCreatedEvent> { it.container == container }
.dockerContainer
private fun containerHasStarted(pastEvents: Set<TaskEvent>) =
pastEvents.any { it is ContainerStartedEvent && it.container == container }
override fun toString() = "${this::class.simpleName}(container: '${container.name}')"
}
| apache-2.0 | 9e8fa8c2ce18d8a77fe6e93db377b0ab | 40.340426 | 114 | 0.766341 | 4.906566 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/os/proxies/ProxyEnvironmentVariablesProvider.kt | 1 | 3073 | /*
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.os.proxies
import batect.utils.mapToSet
import java.util.TreeSet
class ProxyEnvironmentVariablesProvider(
private val preprocessor: ProxyEnvironmentVariablePreprocessor,
private val hostEnvironmentVariables: Map<String, String>
) {
constructor(preprocessor: ProxyEnvironmentVariablePreprocessor) : this(preprocessor, System.getenv())
private val proxyEnvironmentVariablesNeedingPreprocessing = setOf("http_proxy", "https_proxy", "ftp_proxy")
.toCollection(TreeSet(String.CASE_INSENSITIVE_ORDER))
private val lowercaseProxyEnvironmentVariableNames = (proxyEnvironmentVariablesNeedingPreprocessing + "no_proxy")
private val allPossibleEnvironmentVariableNames =
lowercaseProxyEnvironmentVariableNames +
lowercaseProxyEnvironmentVariableNames.mapToSet { it.toUpperCase() }
fun getProxyEnvironmentVariables(extraNoProxyEntries: Set<String>): Map<String, String> {
val variables = allPossibleEnvironmentVariableNames
.associate { it to hostEnvironmentVariables.getMatchingCaseOrOtherCase(it) }
.filterValues { it != null }
.mapValues { (_, value) -> value!! }
.mapValues { (name, value) ->
if (name in proxyEnvironmentVariablesNeedingPreprocessing) preprocessor.process(value) else value
}
if (variables.isEmpty() || extraNoProxyEntries.isEmpty()) {
return variables
}
val noProxyVariables = mapOf(
"no_proxy" to addExtraNoProxyEntries(variables["no_proxy"], extraNoProxyEntries),
"NO_PROXY" to addExtraNoProxyEntries(variables["NO_PROXY"], extraNoProxyEntries)
)
return variables + noProxyVariables
}
private fun addExtraNoProxyEntries(existingValue: String?, extraNoProxyEntries: Set<String>): String {
val extraEntries = extraNoProxyEntries.joinToString(",")
if (existingValue == null || existingValue == "") {
return extraEntries
}
return existingValue + "," + extraEntries
}
private fun Map<String, String>.getMatchingCaseOrOtherCase(key: String): String? {
if (this.containsKey(key)) {
return this[key]
}
if (this.containsKey(key.toUpperCase())) {
return this[key.toUpperCase()]
}
if (this.containsKey(key.toLowerCase())) {
return this[key.toLowerCase()]
}
return null
}
}
| apache-2.0 | ba6925ea6e89a8b2a728c7e8d8c2cf48 | 36.024096 | 117 | 0.69053 | 5.190878 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/base/BaseFragment.kt | 1 | 3478 | package com.sedsoftware.yaptalker.presentation.base
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.arellomobile.mvp.MvpAppCompatFragment
import com.jakewharton.rxrelay2.BehaviorRelay
import com.sedsoftware.yaptalker.common.annotation.LayoutResource
import com.sedsoftware.yaptalker.common.exception.MissingAnnotationException
import com.sedsoftware.yaptalker.presentation.base.enums.lifecycle.FragmentLifecycle
import com.sedsoftware.yaptalker.presentation.delegate.MessagesDelegate
import com.sedsoftware.yaptalker.presentation.provider.ActionBarProvider
import com.sedsoftware.yaptalker.presentation.provider.NavDrawerProvider
import dagger.android.support.AndroidSupportInjection
import io.reactivex.Maybe
import javax.inject.Inject
abstract class BaseFragment : MvpAppCompatFragment() {
@Inject
lateinit var appBarProvider: ActionBarProvider
@Inject
lateinit var navDrawerProvider: NavDrawerProvider
@Inject
lateinit var messagesDelegate: MessagesDelegate
private val lifecycle: BehaviorRelay<Long> = BehaviorRelay.create()
private lateinit var backPressHandler: CanHandleBackPressed
open fun onBackPressed(): Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
AndroidSupportInjection.inject(this)
super.onCreate(savedInstanceState)
lifecycle.accept(FragmentLifecycle.CREATE)
if (activity is CanHandleBackPressed) {
backPressHandler = activity as CanHandleBackPressed
} else {
throw ClassCastException("Base activity must implement BackPressHandler interface.")
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val clazz = this::class.java
if (clazz.isAnnotationPresent(LayoutResource::class.java)) {
val layoutId = clazz.getAnnotation(LayoutResource::class.java).value
return inflater.inflate(layoutId, container, false)
} else {
throw MissingAnnotationException("$this must be annotated with @LayoutResource annotation.")
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
lifecycle.accept(FragmentLifecycle.ATTACH)
}
override fun onStart() {
super.onStart()
lifecycle.accept(FragmentLifecycle.START)
backPressHandler.setSelectedFragment(this)
}
override fun onResume() {
super.onResume()
lifecycle.accept(FragmentLifecycle.RESUME)
}
override fun onPause() {
super.onPause()
lifecycle.accept(FragmentLifecycle.PAUSE)
}
override fun onStop() {
super.onStop()
lifecycle.accept(FragmentLifecycle.STOP)
}
override fun onDestroy() {
super.onDestroy()
lifecycle.accept(FragmentLifecycle.DESTROY)
}
override fun onDetach() {
super.onDetach()
lifecycle.accept(FragmentLifecycle.DETACH)
}
protected fun event(@FragmentLifecycle.Event event: Long): Maybe<*> =
lifecycle.filter { it == event }.firstElement()
protected fun setCurrentAppbarTitle(title: String) {
appBarProvider.getCurrentActionBar()?.title = title
}
protected fun setCurrentNavDrawerItem(item: Long) {
navDrawerProvider.getCurrentDrawer().setSelection(item, false)
}
}
| apache-2.0 | 913582e2365e14eca33bfe3ff906ca51 | 32.12381 | 116 | 0.73088 | 5.167905 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/forumslist/adapter/ForumsAdapter.kt | 1 | 2305 | package com.sedsoftware.yaptalker.presentation.feature.forumslist.adapter
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.domain.device.Settings
import com.sedsoftware.yaptalker.presentation.base.adapter.YapEntityDelegateAdapter
import com.sedsoftware.yaptalker.presentation.model.DisplayedItemType
import com.sedsoftware.yaptalker.presentation.model.base.ForumModel
import java.util.ArrayList
import javax.inject.Inject
class ForumsAdapter @Inject constructor(
itemClickListener: ForumsItemClickListener,
settings: Settings
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var items: ArrayList<ForumModel>
private var delegateAdapters = SparseArrayCompat<YapEntityDelegateAdapter>()
init {
delegateAdapters.put(DisplayedItemType.FORUM, ForumsDelegateAdapter(itemClickListener, settings))
items = ArrayList()
setHasStableIds(true)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
delegateAdapters.get(viewType)!!.onCreateViewHolder(parent)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
delegateAdapters.get(getItemViewType(position))?.onBindViewHolder(holder, items[position])
with(holder.itemView) {
AnimationUtils.loadAnimation(context, R.anim.recyclerview_fade_in).apply {
startAnimation(this)
}
}
}
override fun onViewDetachedFromWindow(holder: ViewHolder) {
super.onViewDetachedFromWindow(holder)
holder.itemView.clearAnimation()
}
override fun getItemViewType(position: Int): Int =
items[position].getEntityType()
override fun getItemCount() =
items.size
override fun getItemId(position: Int) =
position.toLong()
fun addForumsListItem(item: ForumModel) {
val insertPosition = items.size
items.add(item)
notifyItemInserted(insertPosition)
}
fun clearForumsList() {
notifyItemRangeRemoved(0, items.size)
items.clear()
}
}
| apache-2.0 | 003ef5d4e205d11918acf7ef2b8eaf7b | 32.405797 | 105 | 0.745336 | 5.043764 | false | false | false | false |
thomasnield/optimized-scheduling-demo | kotlin_from_scratch_solution/src/main/kotlin/ScheduleEntities.kt | 1 | 5348 |
import java.time.LocalDateTime
/** A discrete, 15-minute chunk of time a class can be scheduled on */
data class Block(val range: ClosedRange<LocalDateTime>) {
val timeRange = range.start.toLocalTime()..range.endInclusive.toLocalTime()
/** indicates if this block is zeroed due to operating day/break constraints */
val withinOperatingDay get() = breaks.all { timeRange.start !in it } &&
timeRange.start in operatingDay &&
timeRange.endInclusive in operatingDay
val affectingSlots by lazy {
ScheduledClass.all.asSequence()
.flatMap {
it.affectingSlotsFor(this).asSequence()
}.toSet()
}
companion object {
/* All operating blocks for the entire week, broken up in 15 minute increments */
val all by lazy {
generateSequence(operatingDates.start.atStartOfDay()) { dt ->
dt.plusMinutes(15).takeIf { it.plusMinutes(15) <= operatingDates.endInclusive.atTime(23,59) }
}.map { Block(it..it.plusMinutes(15)) }
.toList()
}
/* only returns blocks within the operating times */
val allInOperatingDay by lazy {
all.filter { it.withinOperatingDay }
}
}
}
data class ScheduledClass(val id: Int,
val name: String,
val hoursLength: Double,
val recurrences: Int,
val recurrenceGapDays: Int = 2) {
/** the # of slots between each recurrence */
val gap = recurrenceGapDays * 24 * 4
/** the # of slots needed for a given occurrence */
val slotsNeededPerSession = (hoursLength * 4).toInt()
/** yields slots for this given scheduled class */
val slots by lazy {
Slot.all.asSequence().filter { it.scheduledClass == this }.toList()
}
/** yields slot groups for this scheduled class */
val recurrenceSlots by lazy {
slots.affectedWindows(slotsNeeded = slotsNeededPerSession,
gap = gap,
recurrences = recurrences,
mode = RecurrenceMode.FULL_ONLY).toList()
}
/** yields slots that affect the given block for this scheduled class */
fun affectingSlotsFor(block: Block) = recurrenceSlots.asSequence()
.filter { blk -> blk.flatMap { it }.any { it.block == block } }
.map { it.first().first() }
/** These slots should be fixed to zero **/
val slotsFixedToZero by lazy {
// broken recurrences
slots.affectedWindows(slotsNeeded = slotsNeededPerSession,
gap = gap,
recurrences = recurrences,
mode = RecurrenceMode.PARTIAL_ONLY
) .flatMap { it.asSequence() }
.flatMap { it.asSequence() }
// operating day breaks
// affected slots that cross into non-operating day
.plus(
recurrenceSlots.asSequence()
.flatMap { it.asSequence() }
.filter { slot -> slot.any { !it.block.withinOperatingDay }}
.map { it.first() }
)
.distinct()
.onEach {
it.selected = 0
}
.toList()
}
/** translates and returns the optimized start time of the class */
val start get() = slots.asSequence().filter { it.selected == 1 }.map { it.block.range.start }.min()!!
/** translates and returns the optimized end time of the class */
val end get() = start.plusMinutes((hoursLength * 60.0).toLong())
/** returns the DayOfWeeks where recurrences take place */
val daysOfWeek get() = (0..(recurrences-1)).asSequence().map { start.dayOfWeek.plus(it.toLong() * recurrenceGapDays) }.sorted()
companion object {
val all by lazy { scheduledClasses }
}
}
data class Slot(val block: Block, val scheduledClass: ScheduledClass) {
var selected: Int? = null
companion object {
val all by lazy {
Block.all.asSequence().flatMap { b ->
ScheduledClass.all.asSequence().map { Slot(b,it) }
}.toList()
}
}
}
enum class RecurrenceMode { PARTIAL_ONLY, FULL_ONLY, ALL }
fun <T> List<T>.affectedWindows(slotsNeeded: Int, gap: Int, recurrences: Int, mode: RecurrenceMode = RecurrenceMode.FULL_ONLY) =
(0..size).asSequence().map { i ->
(1..recurrences).asSequence().map { (it - 1) * gap }
.filter { it + i < size }
.map { r ->
subList(i + r, (i + r + slotsNeeded).let { if (it > size) size else it })
}
.toList()
}.filter {
when (mode) {
RecurrenceMode.ALL -> true
RecurrenceMode.FULL_ONLY -> it.size == recurrences && it.all { it.size == slotsNeeded }
RecurrenceMode.PARTIAL_ONLY -> it.size < recurrences || it.any { it.size < slotsNeeded }
}
}
fun main(args: Array<String>) {
(1..20).toList()
.affectedWindows(slotsNeeded = 4,
gap = 6,
recurrences = 3,
mode = RecurrenceMode.PARTIAL_ONLY
)
.forEach { println(it) }
} | apache-2.0 | 8284f67d10991a840f3bc7653fe0d71f | 34.423841 | 131 | 0.555161 | 4.383607 | false | false | false | false |
teobaranga/T-Tasks | t-tasks/src/main/java/com/teo/ttasks/ui/task_detail/TaskDetailPresenter.kt | 1 | 3749 | package com.teo.ttasks.ui.task_detail
import com.teo.ttasks.data.local.WidgetHelper
import com.teo.ttasks.data.model.Task
import com.teo.ttasks.data.remote.TasksHelper
import com.teo.ttasks.jobs.TaskDeleteJob
import com.teo.ttasks.ui.base.Presenter
import com.teo.ttasks.util.NotificationHelper
import io.reactivex.disposables.Disposable
import io.realm.Realm
import timber.log.Timber
internal class TaskDetailPresenter(
private val tasksHelper: TasksHelper,
private val widgetHelper: WidgetHelper,
private val notificationHelper: NotificationHelper
) : Presenter<TaskDetailView>() {
private lateinit var realm: Realm
private lateinit var taskId: String
private var taskSubscription: Disposable? = null
/** Un-managed task */
private var task: Task? = null
internal fun getTask(taskId: String) {
this.taskId = taskId
taskSubscription?.let { if (!it.isDisposed) it.dispose() }
taskSubscription = tasksHelper.getTaskAsSingle(taskId, realm)
.subscribe(
{ task ->
this.task = realm.copyFromRealm(task)
view()?.onTaskLoaded(this.task!!)
},
{
Timber.e(it, "Error while retrieving the task")
view()?.onTaskLoadError()
}
)
disposeOnUnbindView(taskSubscription!!)
}
internal fun getTaskList(taskListId: String) {
val disposable = tasksHelper.getTaskListAsSingle(taskListId, realm)
.subscribe(
{ taskList ->
view()?.onTaskListLoaded(realm.copyFromRealm(taskList))
},
{
Timber.e(it, "Error while retrieving the task list")
view()?.onTaskListLoadError()
}
)
disposeOnUnbindView(disposable)
}
/**
* Mark the task as completed if it isn't and vice versa.
* If the task is completed, the completion date is set to the current date.
*/
internal fun updateCompletionStatus() {
task!!.let {
tasksHelper.updateCompletionStatus(it, realm)
realm.executeTransaction { _ -> realm.copyToRealmOrUpdate(it) }
view()?.onTaskUpdated(it)
// Trigger a widget update
widgetHelper.updateWidgets(it.taskListId)
// Reschedule the reminder if going from completed -> active
if (!it.isCompleted) {
notificationHelper.scheduleTaskNotification(it)
}
}
}
/**
* Delete the task
*/
internal fun deleteTask() {
task?.let {
if (it.isLocalOnly) {
tasksHelper.deleteTask(it, realm)
} else {
// Mark it as deleted so it doesn't show up in the list
realm.executeTransaction { _ ->
// Make sure we're marking a managed task as deleted
realm.copyToRealmOrUpdate(it).deleted = true
}
TaskDeleteJob.schedule(it.id, it.taskListId)
}
// Trigger a widget update only if the task is marked as active
if (!it.isCompleted) {
widgetHelper.updateWidgets(it.taskListId)
}
// Cancel the notification, if present
notificationHelper.cancelTaskNotification(it.notificationId)
view()?.onTaskDeleted()
}
}
override fun bindView(view: TaskDetailView) {
super.bindView(view)
realm = Realm.getDefaultInstance()
}
override fun unbindView(view: TaskDetailView) {
super.unbindView(view)
realm.close()
}
}
| apache-2.0 | 9bc4ab8f46febb6752e61a20fe556e64 | 30.771186 | 80 | 0.58789 | 4.919948 | false | false | false | false |
Jire/Arrowhead | src/main/kotlin/org/jire/arrowhead/Source.kt | 1 | 16013 | /*
* Copyright 2016 Thomas Nappo
*
* 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.jire.arrowhead
import com.sun.jna.Memory
import com.sun.jna.Pointer
/**
* A native source which can be read from and written to with native addresses.
*/
interface Source {
/**
* Reads at the specified native address into the specified data.
*
* @param address The native address to read from.
* @param data A pointer to the data to read into.
* @param bytesToRead The amount of bytes to read.
* @return Whether or not the read was successful. (`true` indicates success, `false` indicates failure.)
*/
fun read(address: Pointer, data: Pointer, bytesToRead: Int): Boolean
/**
* Reads at the specified native address into the specified data.
*
* @param address The native address to read from.
* @param data A pointer to the data to read into.
* @param bytesToRead The amount of bytes to read.
*/
fun read(address: Long, data: Pointer, bytesToRead: Int)
= read(PointerCache[address], data, bytesToRead)
/**
* Reads at the specified native address into the specified data.
*
* @param address The native address to read from.
* @param data A pointer to the data to read into.
* @param bytesToRead The amount of bytes to read.
*/
fun read(address: Int, data: Pointer, bytesToRead: Int)
= read(address.toLong(), data, bytesToRead)
/**
* Reads at the specified native address into the specified memory.
*
* @param address The native address to read from.
* @param memory The memory to read into.
* @param bytesToRead The amount of bytes to read. (By default this is the size of the memory.)
*/
fun read(address: Long, memory: Memory, bytesToRead: Int = memory.size().toInt())
= read(address, memory as Pointer, bytesToRead)
/**
* Reads at the specified native address into the specified memory.
*
* @param address The native address to read from.
* @param memory The memory to read into.
* @param bytesToRead The amount of bytes to read. (By default this is the size of the memory.)
*/
fun read(address: Int, memory: Memory, bytesToRead: Int = memory.size().toInt())
= read(address.toLong(), memory, bytesToRead)
/**
* Reads at the specified native address into the specified struct.
*
* @param address The native address to read from.
* @param struct The struct to read into.
* @param bytesToRead The amount of bytes to read. (By default this is the size of the struct.)
*/
fun read(address: Long, struct: Struct, bytesToRead: Int = struct.size())
= read(address, struct.pointer, bytesToRead)
/**
* Reads at the specified native address into the specified struct.
*
* @param address The native address to read from.
* @param struct The struct to read into.
* @param bytesToRead The amount of bytes to read. (By default this is the size of the struct.)
*/
fun read(address: Int, struct: Struct, bytesToRead: Int = struct.size())
= read(address.toLong(), struct, bytesToRead)
/**
* Reads at the specified native address into a memory.
*
* @param address The native address to read from.
* @param bytesToRead The amount of bytes to read.
* @param fromCache Whether or not to use the memory cache for the supplied memory. (By default this is `true`.)
*/
fun read(address: Long, bytesToRead: Int, fromCache: Boolean = true): Memory? {
val memory = if (fromCache) MemoryCache[bytesToRead] else Memory(bytesToRead.toLong())
return if (read(address, memory, bytesToRead)) memory else null
}
/**
* Reads at the specified native address into a memory.
*
* @param address The native address to read from.
* @param bytesToRead The amount of bytes to read.
* @param fromCache Whether or not to use the memory cache for the supplied memory. (By default this is `true`.)
*/
fun read(address: Int, bytesToRead: Int, fromCache: Boolean = true)
= read(address.toLong(), bytesToRead, fromCache)
/**
* Reads a byte at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun byte(address: Long, offset: Long = 0) = read(address, 1)?.getByte(offset) ?: 0.toByte()
/**
* Reads a byte at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun byte(address: Int, offset: Long = 0) = byte(address.toLong(), offset)
/**
* Reads a short at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun short(address: Long, offset: Long = 0) = read(address, 2)?.getShort(offset) ?: 0
/**
* Reads a short at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun short(address: Int, offset: Long = 0) = short(address.toLong(), offset)
/**
* Reads a char at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun char(address: Long, offset: Long = 0) = read(address, 2)?.getChar(offset) ?: 0.toChar()
/**
* Reads a char at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun char(address: Int, offset: Long = 0) = char(address.toLong(), offset)
/**
* Reads an int at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun int(address: Long, offset: Long = 0) = read(address, 4)?.getInt(offset) ?: 0
/**
* Reads an int at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun int(address: Int, offset: Long = 0) = int(address.toLong(), offset)
/**
* Reads a long at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun long(address: Long, offset: Long = 0) = read(address, 8)?.getLong(offset) ?: 0
/**
* Reads a long at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun long(address: Int, offset: Long = 0) = long(address.toLong(), offset)
/**
* Reads a float at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun float(address: Long, offset: Long = 0) = read(address, 4)?.getFloat(offset) ?: 0F
/**
* Reads a float at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun float(address: Int, offset: Long = 0) = float(address.toLong(), offset)
/**
* Reads a double at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun double(address: Long, offset: Long = 0) = read(address, 8)?.getDouble(offset) ?: 0.0
/**
* Reads a double at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun double(address: Int, offset: Long = 0) = double(address.toLong(), offset)
/**
* Reads a boolean at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun boolean(address: Long, offset: Long = 0) = byte(address, offset).unsign() > 0
/**
* Reads a boolean at the specified native address, offset by the specified offset.
*
* @param address The native address to read from.
* @param offset The offset in bytes off the native address.
*/
fun boolean(address: Int, offset: Long = 0) = boolean(address.toLong(), offset)
/**
* Writes the specified memory to the specified native address.
*
* @param address The native address to write to.
* @param data A pointer to the data to write to.
*/
fun write(address: Pointer, data: Pointer, bytesToWrite: Int): Boolean
/**
* Writes the specified memory to the specified native address.
*
* @param address The native address to write to.
* @param data A pointer to the data to write to.
*/
fun write(address: Long, data: Pointer, bytesToWrite: Int)
= write(PointerCache[address], data, bytesToWrite)
/**
* Writes the specified memory to the specified native address.
*
* @param address The native address to write to.
* @param data A pointer to the data to write to.
*/
fun write(address: Int, data: Pointer, bytesToWrite: Int) = write(address.toLong(), data, bytesToWrite)
/**
* Writes the specified memory to the specified native address.
*
* @param address The native address to write to.
* @param memory The memory to write.
* @param bytesToWrite The amount of bytes to write of the memory. (By default this is the size of the memory.)
*/
fun write(address: Long, memory: Memory, bytesToWrite: Int = memory.size().toInt())
= write(address, memory as Pointer, bytesToWrite)
/**
* Writes the specified memory to the specified native address.
*
* @param address The native address to write to.
* @param memory The memory to write.
* @param bytesToWrite The amount of bytes to write of the memory. (By default this is the size of the memory.)
*/
fun write(address: Int, memory: Memory, bytesToWrite: Int = memory.size().toInt())
= write(address.toLong(), memory, bytesToWrite)
/**
* Writes the specified struct to the specified native address.
*
* @param address The native address to write to.
* @param struct The struct to write.
* @param bytesToWrite The amount of bytes to write of the struct. (By default this is the size of the struct.)
*/
fun write(address: Long, struct: Struct, bytesToWrite: Int = struct.size())
= write(address, struct.pointer, bytesToWrite)
/**
* Writes the specified struct to the specified native address.
*
* @param address The native address to write to.
* @param struct The struct to write.
* @param bytesToWrite The amount of bytes to write of the struct. (By default this is the size of the struct.)
*/
fun write(address: Int, struct: Struct, bytesToWrite: Int = struct.size())
= write(address.toLong(), struct, bytesToWrite)
/**
* Writes at the specified native address to the specified byte value.
*
* @param address The native address to write to.
* @param value The value of the byte to write.
*/
operator fun set(address: Long, value: Byte) = write(address, 1) {
setByte(0, value)
}
/**
* Writes at the specified native address to the specified byte value.
*
* @param address The native address to write to.
* @param value The value of the byte to write.
*/
operator fun set(address: Int, value: Byte) = set(address.toLong(), value)
/**
* Writes at the specified native address to the specified short value.
*
* @param address The native address to write to.
* @param value The value of the short to write.
*/
operator fun set(address: Long, value: Short) = write(address, 2) {
setShort(0, value)
}
/**
* Writes at the specified native address to the specified short value.
*
* @param address The native address to write to.
* @param value The value of the short to write.
*/
operator fun set(address: Int, value: Short) = set(address.toLong(), value)
/**
* Writes at the specified native address to the specified char value.
*
* @param address The native address to write to.
* @param value The value of the char to write.
*/
operator fun set(address: Long, value: Char) = write(address, 2) {
setChar(0, value)
}
/**
* Writes at the specified native address to the specified char value.
*
* @param address The native address to write to.
* @param value The value of the char to write.
*/
operator fun set(address: Int, value: Char) = set(address.toLong(), value)
/**
* Writes at the specified native address to the specified int value.
*
* @param address The native address to write to.
* @param value The value of the int to write.
*/
operator fun set(address: Long, value: Int) = write(address, 4) {
setInt(0, value)
}
/**
* Writes at the specified native address to the specified int value.
*
* @param address The native address to write to.
* @param value The value of the int to write.
*/
operator fun set(address: Int, value: Int) = set(address.toLong(), value)
/**
* Writes at the specified native address to the specified long value.
*
* @param address The native address to write to.
* @param value The value of the long to write.
*/
operator fun set(address: Long, value: Long) = write(address, 8) {
setLong(0, value)
}
/**
* Writes at the specified native address to the specified long value.
*
* @param address The native address to write to.
* @param value The value of the long to write.
*/
operator fun set(address: Int, value: Long) = set(address.toLong(), value)
/**
* Writes at the specified native address to the specified float value.
*
* @param address The native address to write to.
* @param value The value of the float to write.
*/
operator fun set(address: Long, value: Float) = write(address, 4) {
setFloat(0, value)
}
/**
* Writes at the specified native address to the specified float value.
*
* @param address The native address to write to.
* @param value The value of the float to write.
*/
operator fun set(address: Int, value: Float) = set(address.toLong(), value)
/**
* Writes at the specified native address to the specified double value.
*
* @param address The native address to write to.
* @param value The value of the double to write.
*/
operator fun set(address: Long, value: Double) = write(address, 8) {
setDouble(0, value)
}
/**
* Writes at the specified native address to the specified double value.
*
* @param address The native address to write to.
* @param value The value of the double to write.
*/
operator fun set(address: Int, value: Double) = set(address.toLong(), value)
/**
* Writes at the specified native address to the specified boolean value.
*
* @param address The native address to write to.
* @param value The value of the boolean to write.
*/
operator fun set(address: Long, value: Boolean) = set(address, (if (value) 1 else 0).toByte())
/**
* Writes at the specified native address to the specified boolean value.
*
* @param address The native address to write to.
* @param value The value of the boolean to write.
*/
operator fun set(address: Int, value: Boolean) = set(address.toLong(), value)
} | apache-2.0 | f6e3bc9dcae6a091b3bed0808f67ce6a | 34.273128 | 113 | 0.697246 | 3.82537 | false | true | false | false |
felipebz/sonar-plsql | zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/EmptyBlockCheck.kt | 1 | 1854 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plsqlopen.isOf
import org.sonar.plsqlopen.sslr.NullStatement
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
@Rule(priority = Priority.MINOR, tags = [Tags.UNUSED])
@ConstantRemediation("5min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class EmptyBlockCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(PlSqlGrammar.STATEMENTS_SECTION)
}
override fun visitNode(node: AstNode) {
if (context.currentScope?.isOverridingMember == true) {
return
}
val statements = node.getFirstChild(PlSqlGrammar.STATEMENTS).getChildren(PlSqlGrammar.STATEMENT)
if (statements.size == 1) {
val statement = statements[0]
if (statement.isOf<NullStatement>()) {
addIssue(statement, getLocalizedMessage())
}
}
}
}
| lgpl-3.0 | cc21705e8ec01e5bd7e7a43d2500869d | 34.653846 | 104 | 0.714671 | 4.321678 | false | false | false | false |
grueni75/GeoDiscoverer | Source/Platform/Target/Android/wear/src/main/java/com/untouchableapps/android/geodiscoverer/GDWatchFaceService.kt | 1 | 13965 | //============================================================================
// Name : GDWatchFaceService
// Author : Matthias Gruenewald
// Copyright : Copyright 2010-2022 Matthias Gruenewald
//
// This file is part of GeoDiscoverer.
//
// GeoDiscoverer 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.
//
// GeoDiscoverer 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 GeoDiscoverer. If not, see <http://www.gnu.org/licenses/>.
//
//============================================================================
package com.untouchableapps.android.geodiscoverer
import android.content.Intent
import android.view.SurfaceHolder
import androidx.wear.watchface.ComplicationSlotsManager
import androidx.wear.watchface.WatchFace
import androidx.wear.watchface.WatchFaceType
import androidx.wear.watchface.WatchState
import androidx.wear.watchface.style.CurrentUserStyleRepository
import java.lang.ref.WeakReference
import java.util.*
import com.untouchableapps.android.geodiscoverer.core.GDCore
import android.annotation.SuppressLint
import android.os.*
import android.os.Build
import android.app.ActivityManager
import android.os.PowerManager
import android.os.Vibrator
// Minimum distance between two toasts in milliseconds */
const val TOAST_DISTANCE = 5000
// All active renderers
var activeRenderers = mutableListOf<WatchFaceRenderer>()
class GDWatchFaceService : androidx.wear.watchface.WatchFaceService() {
// Managers
var powerManager: PowerManager? = null
var vibrator: Vibrator? = null
// Reference to the core object
var coreObject: GDCore? = null
// Indicates if the dialog is open
var dialogVisible = false
// Time the last toast was shown
var lastToastTimestamp: Long = 0
// Wake lock for the core
var wakeLockCore: PowerManager.WakeLock? = null
// Short vibration to give feedback to user
fun vibrate() {
vibrator?.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE))
}
// Shows a dialog
@Synchronized
fun dialog(kind: Int, message: String) {
if ((kind == Dialog.Types.WARNING)||(kind == Dialog.Types.INFO)) {
val diff: Long = SystemClock.uptimeMillis() - lastToastTimestamp
if (diff <= TOAST_DISTANCE) {
GDApplication.addMessage(
GDApplication.DEBUG_MSG, "GDApp",
"skipping dialog request <$message> because toast is still visible"
)
return
}
GDApplication.showMessageBar(
applicationContext,
message,
GDApplication.MESSAGE_BAR_DURATION_LONG
)
lastToastTimestamp = SystemClock.uptimeMillis()
} else {
val intent = Intent(this, Dialog::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION
intent.putExtra(Dialog.Extras.TEXT, message)
intent.putExtra(Dialog.Extras.KIND, kind)
startActivity(intent)
}
}
/** Shows a fatal dialog and quits the applications */
fun fatalDialog(message: String) {
dialog(Dialog.Types.FATAL, message)
}
/** Shows an error dialog without quitting the application */
fun errorDialog(message: String) {
dialog(Dialog.Types.ERROR, message)
}
/** Shows a warning dialog without quitting the application */
fun warningDialog(message: String) {
dialog(Dialog.Types.WARNING, message)
}
/** Shows an info dialog without quitting the application */
fun infoDialog(message: String) {
dialog(Dialog.Types.INFO, message)
}
// Sets the wake lock controlled by the core
@SuppressLint("Wakelock")
fun updateWakeLock() {
if (wakeLockCore==null)
return
val state = coreObject?.executeCoreCommand("getWakeLock")
if (state == "true") {
GDApplication.addMessage(GDApplication.DEBUG_MSG, "GDApp", "wake lock enabled")
if (!wakeLockCore!!.isHeld) wakeLockCore?.acquire()
} else {
GDApplication.addMessage(GDApplication.DEBUG_MSG, "GDApp", "wake lock disabled")
if (wakeLockCore!!.isHeld) wakeLockCore?.release()
}
}
// Communication with the native core
class CoreMessageHandler(GDWatchFace: GDWatchFaceService) : Handler(Looper.getMainLooper()) {
private val weakGDWatchFace: WeakReference<GDWatchFaceService> = WeakReference(GDWatchFace)
/** Called when the core has a message */
override fun handleMessage(msg: Message) {
// Abort if the object is not available anymore
val watchFaceService: GDWatchFaceService = weakGDWatchFace.get() ?: return
// Handle the message
val b: Bundle = msg.data
when (msg.what) {
0 -> {
// Extract the command
val command = b.getString("command")
val args_start = command!!.indexOf("(")
val args_end = command.lastIndexOf(")")
val commandFunction = command.substring(0, args_start)
val t = command.substring(args_start + 1, args_end)
val commandArgs: Vector<String> = Vector<String>()
var stringStarted = false
var startPos = 0
var i = 0
while (i < t.length) {
if (t.substring(i, i + 1) == "\"") {
stringStarted = !stringStarted
}
if (!stringStarted) {
if (t.substring(i, i + 1) == "," || i == t.length - 1) {
var arg: String
arg =
if (i == t.length - 1) t.substring(startPos, i + 1) else t.substring(startPos, i)
if (arg.startsWith("\"")) {
arg = arg.substring(1)
}
if (arg.endsWith("\"")) {
arg = arg.substring(0, arg.length - 1)
}
commandArgs.add(arg)
startPos = i + 1
}
}
i++
}
//GDApplication.addMessage(GDApplication.DEBUG_MSG,"GDApp","command received: " + command);
// Execute command
var commandExecuted = false
if (commandFunction == "fatalDialog") {
watchFaceService.fatalDialog(commandArgs.get(0))
commandExecuted = true
}
if (commandFunction == "errorDialog") {
watchFaceService.errorDialog(commandArgs.get(0))
commandExecuted = true
}
if (commandFunction == "warningDialog") {
watchFaceService.warningDialog(commandArgs.get(0))
commandExecuted = true
}
if (commandFunction == "infoDialog") {
watchFaceService.infoDialog(commandArgs.get(0))
commandExecuted = true
}
if (commandFunction == "createProgressDialog") {
// Create a new dialog if it does not yet exist
if (!watchFaceService.dialogVisible) {
val intent = Intent(watchFaceService, Dialog::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION
intent.putExtra(Dialog.Extras.TEXT, commandArgs.get(0))
val max: Int = commandArgs.get(1).toInt()
intent.putExtra(Dialog.Extras.MAX, max)
watchFaceService.startActivity(intent)
watchFaceService.dialogVisible = true
} else {
GDApplication.addMessage(
GDApplication.DEBUG_MSG,
"GDApp",
"skipping progress dialog request <" + commandArgs.get(0)
.toString() + "> because progress dialog is already visible"
)
}
commandExecuted = true
}
if (commandFunction == "updateProgressDialog") {
if (watchFaceService.dialogVisible) {
val intent = Intent(watchFaceService, Dialog::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION
intent.putExtra(Dialog.Extras.PROGRESS, commandArgs.get(1).toInt())
watchFaceService.startActivity(intent)
}
commandExecuted = true
}
if (commandFunction == "closeProgressDialog") {
if (watchFaceService.dialogVisible) {
val intent = Intent(watchFaceService, Dialog::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION
intent.putExtra(Dialog.Extras.CLOSE, true)
watchFaceService.startActivity(intent)
watchFaceService.dialogVisible = false
}
commandExecuted = true
}
if (commandFunction == "coreInitialized") {
commandExecuted = true
}
if (commandFunction == "earlyInitComplete") {
// Nothing to do as of now
commandExecuted = true
}
if (commandFunction == "lateInitComplete") {
// Nothing to do as of now
commandExecuted = true
}
if (commandFunction == "setSplashVisibility") {
// Nothing to do as of now
commandExecuted = true
}
if (commandFunction == "updateWakeLock") {
watchFaceService.updateWakeLock()
commandExecuted = true
}
if (commandFunction == "updateScreen") {
synchronized(activeRenderers) {
activeRenderers.forEach() {
it.forceRedraw()
}
}
commandExecuted = true
}
if (commandFunction == "restartActivity") {
if (GDApplication.coreObject != null) {
val m: Message = Message.obtain(GDApplication.coreObject.messageHandler)
m.what = GDCore.START_CORE
GDApplication.coreObject.messageHandler.sendMessage(m)
}
commandExecuted = true
}
if (commandFunction == "exitActivity") {
commandExecuted = true
}
if (commandFunction == "deactivateSwipes") {
synchronized(activeRenderers) {
activeRenderers.forEach() {
it.setTouchHandlerEnabled(false)
}
}
watchFaceService.vibrate()
commandExecuted = true
}
if (commandFunction == "ambientTransitionFinished") {
synchronized(activeRenderers) {
activeRenderers.forEach() {
it.isTransitioningToAmbient = false
}
}
commandExecuted = true
}
if (!commandExecuted) {
GDApplication.addMessage(
GDApplication.ERROR_MSG, "GDApp",
"unknown command $command received"
)
}
}
}
}
}
var coreMessageHandler = CoreMessageHandler(this)
/** Gets the vibrator in legacy way */
@Suppress("deprecation")
private fun getLegacyVibrator(): Vibrator? {
return getSystemService(VIBRATOR_SERVICE) as Vibrator;
}
// Init everything
override fun onCreate() {
super.onCreate()
// Get the core object
coreObject = GDApplication.coreObject
(application as GDApplication).setMessageHandler(coreMessageHandler)
// Get the managers
powerManager = getSystemService(POWER_SERVICE) as PowerManager
vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
(getSystemService(VIBRATOR_MANAGER_SERVICE) as VibratorManager).defaultVibrator
} else {
getLegacyVibrator()
}
// Get a wake lock
wakeLockCore = powerManager?.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "GDApp: Active core");
if (wakeLockCore==null) {
fatalDialog(getString(R.string.no_wake_lock))
return
}
// Check for OpenGL ES 2.00
val activityManager = getSystemService(ACTIVITY_SERVICE) as ActivityManager
val configurationInfo = activityManager.deviceConfigurationInfo
val supportsEs2 =
configurationInfo.reqGlEsVersion >= 0x20000 || Build.FINGERPRINT.startsWith("generic")
if (!supportsEs2) {
fatalDialog(getString(R.string.opengles20_required))
return
}
}
// Returns a new watch face
override suspend fun createWatchFace(
surfaceHolder: SurfaceHolder,
watchState: WatchState,
complicationSlotsManager: ComplicationSlotsManager,
currentUserStyleRepository: CurrentUserStyleRepository
): WatchFace {
GDApplication.addMessage(GDApplication.DEBUG_MSG,"GDApp","createWatchFace called")
// Creates class that renders the watch face.
val renderer = WatchFaceRenderer(
context = applicationContext,
coreObject = coreObject,
surfaceHolder = surfaceHolder,
watchState = watchState,
currentUserStyleRepository = currentUserStyleRepository
)
synchronized(activeRenderers) {
activeRenderers.add(renderer)
}
// Creates the watch face.
val watchFace = WatchFace(
watchFaceType = WatchFaceType.DIGITAL,
renderer = renderer
)
watchFace.setTapListener(renderer)
return watchFace
}
// Called when the service is destroyed
override fun onDestroy() {
super.onDestroy()
if ((wakeLockCore!=null)&&(wakeLockCore!!.isHeld))
wakeLockCore?.release();
(getApplication() as GDApplication).setMessageHandler(null)
if (coreObject!=null) {
if (!coreObject!!.coreStopped) {
val m: Message = Message.obtain(coreObject!!.messageHandler)
m.what = GDCore.STOP_CORE
coreObject!!.messageHandler.sendMessage(m)
}
}
}
} | gpl-3.0 | 0cb4b9943f60d18afad5141800582911 | 34.627551 | 101 | 0.623631 | 4.676825 | false | false | false | false |
jeffgbutler/mybatis-dynamic-sql | src/test/kotlin/examples/kotlin/spring/canonical/PersonDynamicSqlSupport.kt | 1 | 1705 | /*
* Copyright 2016-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 examples.kotlin.spring.canonical
import org.mybatis.dynamic.sql.SqlTable
import org.mybatis.dynamic.sql.util.kotlin.elements.column
import java.util.Date
object PersonDynamicSqlSupport {
val person = Person()
val id = person.id
val firstName = person.firstName
val lastName = person.lastName
val birthDate = person.birthDate
val employed = person.employed
val occupation = person.occupation
val addressId = person.addressId
class Person : SqlTable("Person") {
val id = column<Int>(name = "id")
val firstName = column<String>(name = "first_name")
val lastName = column(
name = "last_name",
parameterTypeConverter = lastNameConverter
)
val birthDate = column<Date>(name = "birth_date")
val employed = column(
name = "employed",
parameterTypeConverter = booleanToStringConverter
)
val occupation = column<String>(name = "occupation")
val addressId = column<Int>(name = "address_id")
}
}
| apache-2.0 | a1adcd680ea06a09169160b3853c3629 | 35.276596 | 78 | 0.673314 | 4.360614 | false | false | false | false |
skuznets0v/metro | src/main/kotlin/com/github/skuznets0v/metro/model/dto/SchemeDto.kt | 1 | 569 | package com.github.skuznets0v.metro.model.dto
import com.github.skuznets0v.metro.model.entities.Route
import com.github.skuznets0v.metro.model.entities.Station
import com.github.skuznets0v.metro.model.entities.Train
data class SchemeDto(
val urn: String = "",
val name: String = "",
val width: Int = 0,
val height: Int = 0,
val stations: List<Station> = emptyList(),
val metroLines: List<MetroLineDto> = emptyList(),
val trains: List<Train> = emptyList(),
val routes: List<Route> = emptyList()
) | mit | 9a3f600e37b34fd10008112a8f245521 | 22.75 | 57 | 0.660808 | 3.578616 | false | false | false | false |
schneppd/lab.schneppd.android2017.opengl2 | MyApplication/app/src/main/java/com/schneppd/myopenglapp/OpenGL2v1/Square.kt | 1 | 4478 | package com.schneppd.myopenglapp.OpenGL2v1
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import java.nio.ShortBuffer
import android.opengl.GLES20
/**
* Created by schneppd on 7/9/17.
*/
class Square {
companion object Static {
// This matrix member variable provides a hook to manipulate
// the coordinates of the objects that use this vertex shader
// The matrix must be included as a modifier of gl_Position.
// Note that the uMVPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
val vertexShaderCode:String = """
uniform mat4 uMVPMatrix;
attribute vec4 vPosition;
void main() {
gl_Position = uMVPMatrix * vPosition;
}"""
val fragmentShaderCode = """
precision mediump float;
uniform vec4 vColor;
void main() {
gl_FragColor = vColor;
}
"""
// number of coordinates per vertex in this array
val COORDS_PER_VERTEX = 3
val squareCoords:FloatArray = floatArrayOf(
-0.5f, 0.5f, 0.0f, // top left
-0.5f, -0.5f, 0.0f, // bottom left
0.5f, -0.5f, 0.0f, // bottom right
0.5f, 0.5f, 0.0f // top right
)
val drawOrder:ShortArray = shortArrayOf(
0, 1, 2
, 0, 2, 3
) // order to draw vertices
val vertexStride:Int = COORDS_PER_VERTEX * 4 // 4 bytes per vertex
val color:FloatArray = floatArrayOf(
0.2f, 0.709803922f, 0.898039216f, 1.0f
)
}
private var vertexBuffer: FloatBuffer
private var drawListBuffer: ShortBuffer? = null
private var mProgram: Int = 0
private var mPositionHandle: Int = 0
private var mColorHandle: Int = 0
private var mMVPMatrixHandle: Int = 0
init{
// initialize vertex byte buffer for shape coordinates
var bb:ByteBuffer = ByteBuffer.allocateDirect(
// (number of coordinate values * 4 bytes per float)
squareCoords.size * 4)
// use the device hardware's native byte order
bb.order(ByteOrder.nativeOrder())
// create a floating point buffer from the ByteBuffer
vertexBuffer = bb.asFloatBuffer()
// add the coordinates to the FloatBuffer
vertexBuffer.put(squareCoords)
// set the buffer to read the first coordinate
vertexBuffer.position(0)
// initialize byte buffer for the draw list
var dlb = ByteBuffer.allocateDirect(drawOrder.size * 2)// (# of coordinate values * 2 bytes per short)
dlb.order(ByteOrder.nativeOrder())
drawListBuffer = dlb.asShortBuffer()
drawListBuffer!!.put(drawOrder)
drawListBuffer!!.position(0)
// prepare shaders and OpenGL program
val vertexShader = CustomGLRenderer.loadShader(
GLES20.GL_VERTEX_SHADER, vertexShaderCode
)
val fragmentShader = CustomGLRenderer.loadShader(
GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode
)
mProgram = GLES20.glCreateProgram() // create empty OpenGL Program
GLES20.glAttachShader(mProgram, vertexShader) // add the vertex shader to program
GLES20.glAttachShader(mProgram, fragmentShader) // add the fragment shader to program
GLES20.glLinkProgram(mProgram) // create OpenGL program executables
}
/**
* Encapsulates the OpenGL ES instructions for drawing this shape.
*
* @param mvpMatrix - The Model View Project matrix in which to draw
* this shape.
*/
fun draw(mvpMatrix:FloatArray){
// Add program to OpenGL environment
GLES20.glUseProgram(mProgram)
// get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition")
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle)
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(
mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer)
// get handle to fragment shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor")
// Set color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0)
// get handle to shape's transformation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix")
CustomGLRenderer.checkGlError("glGetUniformLocation")
// Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0)
CustomGLRenderer.checkGlError("glUniformMatrix4fv")
// Draw the square
GLES20.glDrawElements(
GLES20.GL_TRIANGLES, drawOrder.size,
GLES20.GL_UNSIGNED_SHORT, drawListBuffer!!)
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle)
}
} | gpl-3.0 | 9119fbc85168ea0f2a0799862225a9ec | 33.453846 | 104 | 0.737159 | 3.664484 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/annotations/parameterWithPrimitiveType.kt | 2 | 1343 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
@Retention(AnnotationRetention.RUNTIME)
annotation class Ann(
val b: Byte,
val s: Short,
val i: Int,
val f: Float,
val d: Double,
val l: Long,
val c: Char,
val bool: Boolean
)
fun box(): String {
val ann = MyClass::class.java.getAnnotation(Ann::class.java)
if (ann == null) return "fail: cannot find Ann on MyClass}"
if (ann.b != 1.toByte()) return "fail: annotation parameter b should be 1, but was ${ann.b}"
if (ann.s != 1.toShort()) return "fail: annotation parameter s should be 1, but was ${ann.s}"
if (ann.i != 1) return "fail: annotation parameter i should be 1, but was ${ann.i}"
if (ann.f != 1.toFloat()) return "fail: annotation parameter f should be 1, but was ${ann.f}"
if (ann.d != 1.0) return "fail: annotation parameter d should be 1, but was ${ann.d}"
if (ann.l != 1.toLong()) return "fail: annotation parameter l should be 1, but was ${ann.l}"
if (ann.c != 'c') return "fail: annotation parameter c should be 1, but was ${ann.c}"
if (!ann.bool) return "fail: annotation parameter bool should be 1, but was ${ann.bool}"
return "OK"
}
@Ann(1, 1, 1, 1.0.toFloat(), 1.0, 1, 'c', true) class MyClass
| apache-2.0 | 1ec1a206a1875b60d684dc1564d9d256 | 40.96875 | 97 | 0.625465 | 3.374372 | false | false | false | false |
StephaneBg/SimpleNumberPicker | library/src/main/java/fr/baiget/simplenumberpicker/decimal/DecimalPickerDialog.kt | 1 | 9836 | /*
* Copyright 2017 Stéphane Baiget
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.baiget.simplenumberpicker.decimal
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.core.view.isInvisible
import androidx.fragment.app.DialogFragment
import fr.baiget.simplenumberpicker.R
import fr.baiget.simplenumberpicker.utils.color
import fr.baiget.simplenumberpicker.utils.makeSelector
import org.jetbrains.anko.colorAttr
import org.jetbrains.anko.find
import java.text.DecimalFormatSymbols
class DecimalPickerDialog : DialogFragment() {
private lateinit var dialog: AlertDialog
private lateinit var numberTextView: TextView
private lateinit var backspaceButton: ImageButton
private lateinit var decimalSeparator: String
private var reference =
DEFAULT_REFERENCE
private var relative = true
private var natural = false
private var style = R.style.SimpleNumberPickerTheme
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
assignArguments(savedInstanceState ?: arguments)
setStyle(DialogFragment.STYLE_NO_TITLE, style)
isCancelable = false
}
@SuppressLint("SetTextI18n", "InflateParams")
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val attributes =
requireContext().obtainStyledAttributes(style, R.styleable.SimpleNumberPicker)
val view = requireActivity().layoutInflater
.inflate(R.layout.snp_dialog_decimal_picker, null)
// Init number
var color = attributes.getColor(
R.styleable.SimpleNumberPicker_snpKeyColor,
requireContext().colorAttr(R.attr.colorPrimary)
)
numberTextView = view.find(R.id.tv_number)
numberTextView.setTextColor(color)
if (savedInstanceState?.containsKey(ARG_SAVED_VALUE) == true)
numberTextView.text = savedInstanceState.getString(ARG_SAVED_VALUE)
// Init backspace
color = attributes.getColor(
R.styleable.SimpleNumberPicker_snpBackspaceColor,
requireContext().colorAttr(R.attr.colorPrimary)
)
backspaceButton = view.find(R.id.key_backspace)
backspaceButton.setImageDrawable(
makeSelector(
requireContext(),
R.drawable.snp_ic_backspace_black_24dp,
color
)
)
backspaceButton.setOnClickListener {
var number = numberTextView.text.subSequence(0, numberTextView.text.length - 1)
if (1 == number.length && '-' == number[0]) number = ""
numberTextView.text = number
onNumberChanged()
}
backspaceButton.setOnLongClickListener {
numberTextView.text = ""
onNumberChanged()
true
}
// Create dialog
dialog = AlertDialog.Builder(requireContext(), theme)
.setView(view)
.setPositiveButton(android.R.string.ok) { _, _ ->
var result = numberTextView.text.toString()
if (result.isEmpty()) result = "0"
result = result.replace(',', '.')
if (result == ".") result = "0"
val number = result.toFloat()
val fragmentActivity = activity
val fragment = parentFragment
if (fragmentActivity is DecimalPickerHandler) {
fragmentActivity.onDecimalNumberPicked(reference, number)
} else if (fragment is DecimalPickerHandler) {
fragment.onDecimalNumberPicked(reference, number)
}
dismiss()
}
.setNegativeButton(android.R.string.cancel) { _, _ -> dismiss() }
.create()
// Init dialog
color = attributes.getColor(
R.styleable.SimpleNumberPicker_snpDialogBackground,
requireContext().color(android.R.color.white)
)
dialog.window?.setBackgroundDrawable(ColorDrawable(color))
// Init keys
val listener = { v: View ->
val key = v.tag as Int
val id = "${numberTextView.text}$key"
numberTextView.text = id
onNumberChanged()
}
color = attributes.getColor(
R.styleable.SimpleNumberPicker_snpKeyColor,
requireContext().colorAttr(R.attr.colorAccent)
)
val ids = resources.obtainTypedArray(R.array.snp_key_ids)
for (i in 0 until NB_KEYS) {
val key = view.find<TextView>(ids.getResourceId(i, -1))
key.tag = i
key.setOnClickListener(listener)
key.setTextColor(color)
}
// Init sign
val sign = view.find<TextView>(R.id.key_sign)
if (relative) {
sign.setTextColor(color)
sign.setOnClickListener {
val number = numberTextView.text.toString()
if (number.startsWith("-")) numberTextView.text = number.drop(1)
else numberTextView.text = "-$number"
onNumberChanged()
}
} else {
sign.isInvisible = true
}
// Init decimal separator
decimalSeparator = DecimalFormatSymbols().decimalSeparator.toString()
val separator = view.find<TextView>(R.id.key_point)
if (natural) {
separator.isInvisible = true
} else {
separator.text = decimalSeparator
separator.setTextColor(color)
separator.setOnClickListener {
if (!numberTextView.text.toString().contains(decimalSeparator)) {
numberTextView.text = "${numberTextView.text}$decimalSeparator"
onNumberChanged()
}
}
}
ids.recycle()
attributes.recycle()
return dialog
}
override fun onStart() {
super.onStart()
onNumberChanged()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
with(outState) {
putInt(ARG_REFERENCE, reference)
putBoolean(ARG_RELATIVE, relative)
putBoolean(ARG_NATURAL, natural)
putInt(ARG_STYLE, theme)
putString(ARG_SAVED_VALUE, numberTextView.text.toString())
}
}
private fun onNumberChanged() {
backspaceButton.isEnabled = 0 != numberTextView.length()
if (numberTextView.text.isEmpty()) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled = false
} else {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).isEnabled =
!(1 == numberTextView.text.length && '-' == numberTextView.text[0])
}
}
private fun assignArguments(args: Bundle?) {
if (args?.containsKey(ARG_REFERENCE) == true) reference = args.getInt(
ARG_REFERENCE
)
if (args?.containsKey(ARG_RELATIVE) == true) relative = args.getBoolean(
ARG_RELATIVE
)
if (args?.containsKey(ARG_NATURAL) == true) natural = args.getBoolean(
ARG_NATURAL
)
if (args?.containsKey(ARG_STYLE) == true) style = args.getInt(
ARG_STYLE
)
}
class Builder {
private var reference =
DEFAULT_REFERENCE
private var relative = true
private var natural = false
private var theme = R.style.SimpleNumberPickerTheme
fun setReference(reference: Int): Builder {
this.reference = reference
return this
}
fun setRelative(relative: Boolean): Builder {
this.relative = relative
return this
}
fun setNatural(natural: Boolean): Builder {
this.natural = natural
return this
}
fun setTheme(theme: Int): Builder {
this.theme = theme
return this
}
fun create(): DecimalPickerDialog =
newInstance(
reference,
relative,
natural,
theme
)
}
companion object {
private const val ARG_REFERENCE = "ARG_REFERENCE"
private const val ARG_RELATIVE = "ARG_RELATIVE"
private const val ARG_NATURAL = "ARG_NATURAL"
private const val ARG_STYLE = "ARG_STYLE"
private const val ARG_SAVED_VALUE = "ARG_SAVED_VALUE"
private const val NB_KEYS = 10
private const val DEFAULT_REFERENCE = 0
private fun newInstance(
reference: Int,
relative: Boolean,
natural: Boolean,
theme: Int
) = DecimalPickerDialog().apply {
arguments = bundleOf(
ARG_REFERENCE to reference,
ARG_RELATIVE to relative,
ARG_NATURAL to natural,
ARG_STYLE to theme
)
}
}
}
| apache-2.0 | 834333780f293b6116eeaabeca59d491 | 33.031142 | 91 | 0.605084 | 4.969682 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/source/model/SMangaExtensions.kt | 1 | 615 | package eu.kanade.tachiyomi.source.model
import data.Mangas
fun SManga.copyFrom(other: Mangas) {
if (other.author != null) {
author = other.author
}
if (other.artist != null) {
artist = other.artist
}
if (other.description != null) {
description = other.description
}
if (other.genre != null) {
genre = other.genre.joinToString(separator = ", ")
}
if (other.thumbnail_url != null) {
thumbnail_url = other.thumbnail_url
}
status = other.status.toInt()
if (!initialized) {
initialized = other.initialized
}
}
| apache-2.0 | 2e4d9234800a20128a5599d1b95e74e5 | 18.83871 | 58 | 0.588618 | 3.892405 | false | false | false | false |
k9mail/k-9 | app/k9mail/src/main/java/com/fsck/k9/backends/WebDavBackendFactory.kt | 1 | 1810 | package com.fsck.k9.backends
import com.fsck.k9.Account
import com.fsck.k9.backend.BackendFactory
import com.fsck.k9.backend.api.Backend
import com.fsck.k9.backend.webdav.WebDavBackend
import com.fsck.k9.mail.ssl.TrustManagerFactory
import com.fsck.k9.mail.store.webdav.DraftsFolderProvider
import com.fsck.k9.mail.store.webdav.SniHostSetter
import com.fsck.k9.mail.store.webdav.WebDavStore
import com.fsck.k9.mail.transport.WebDavTransport
import com.fsck.k9.mailstore.FolderRepository
import com.fsck.k9.mailstore.K9BackendStorageFactory
class WebDavBackendFactory(
private val backendStorageFactory: K9BackendStorageFactory,
private val trustManagerFactory: TrustManagerFactory,
private val sniHostSetter: SniHostSetter,
private val folderRepository: FolderRepository
) : BackendFactory {
override fun createBackend(account: Account): Backend {
val accountName = account.displayName
val backendStorage = backendStorageFactory.createBackendStorage(account)
val serverSettings = account.incomingServerSettings
val draftsFolderProvider = createDraftsFolderProvider(account)
val webDavStore = WebDavStore(trustManagerFactory, sniHostSetter, serverSettings, draftsFolderProvider)
val webDavTransport = WebDavTransport(trustManagerFactory, sniHostSetter, serverSettings, draftsFolderProvider)
return WebDavBackend(accountName, backendStorage, webDavStore, webDavTransport)
}
private fun createDraftsFolderProvider(account: Account): DraftsFolderProvider {
return DraftsFolderProvider {
val draftsFolderId = account.draftsFolderId ?: error("No Drafts folder configured")
folderRepository.getFolderServerId(account, draftsFolderId) ?: error("Couldn't find local Drafts folder")
}
}
}
| apache-2.0 | d8e35c22b4f004aa1a01bddc02a87015 | 47.918919 | 119 | 0.791713 | 4.469136 | false | false | false | false |
just-4-fun/holomorph | src/test/kotlin/just4fun/holomorph/mains/Generics.kt | 1 | 2780 | package just4fun.holomorph.mains
import just4fun.holomorph.Reflexion
import just4fun.holomorph.forms.DefaultFactory
import just4fun.holomorph.types.IntType
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.shouldEqual
class Generics: Spek() { init {
given("Generic type parameters") {
on("Generic type as property") {
class Obj(val pair: Pair<Int, String>, val triple: Triple<Boolean, Int, String>)
val sch = Reflexion(Obj::class)
val obj = sch.instanceFrom("{pair:{first:1,second:ok},triple:{first:1,second:2,third:oops}}", DefaultFactory).valueOrThrow
it("") {
shouldEqual(obj.pair.second, "ok")
shouldEqual(obj.triple.third, "oops")
}
}
on("Generic type as property type") {
class ObjA<A>(val array: Array<A>)
class Obj(val a: ObjA<Int>)
val sch = Reflexion(Obj::class)
val obj = sch.instanceFrom("{a:{array:[1, 2, 3]}}", DefaultFactory).valueOrThrow
it("") {
shouldEqual(obj.a.array.size, 3)
shouldEqual(obj.a.array[2], 3)
}
}
on("Generic type initial") {
class Obj<T>(val a:T)
val sch = Reflexion(Obj::class, IntType)
val obj = sch.instanceFrom("{a:4}", DefaultFactory).valueOrThrow
it("") {
shouldEqual(obj.a, 4)
}
}
on("Generic type initial as prop type") {
class ObjA<A>(val array: Array<A>)
class Obj<T>(val a:ObjA<T>)
val sch = Reflexion(Obj::class, IntType)
val obj = sch.instanceFrom("{a:{array:[1, 2, 3]}}", DefaultFactory).valueOrThrow
it("") {
shouldEqual(obj.a.array.size, 3)
shouldEqual(obj.a.array[2], 3)
}
}
on("Generic complex type as property type") {
class ObjA<A, B>(val list: List<Pair<A, B>>)
class Obj(val a: ObjA<Int, String>)
val sch = Reflexion(Obj::class)
val obj = sch.instanceFrom("{a:{list:[{first:1,second:ok}, {first:2,second:oops}]}}", DefaultFactory).valueOrThrow
it("") {
shouldEqual(obj.a.list.size, 2)
shouldEqual(obj.a.list[1].second, "oops")
}
}
on("Generic bound type as property type") {
class ObjA<A, B, out L: List<Pair<A, B>>>(val list: L)
class Obj(val a: ObjA<Int, String, List<Pair<Int, String>>>)
val sch = Reflexion(Obj::class)
val obj = sch.instanceFrom("{a:{list:[{first:1,second:ok}, {first:2,second:oops}]}}", DefaultFactory).valueOrThrow
it("") {
shouldEqual(obj.a.list.size, 2)
shouldEqual(obj.a.list[1].second, "oops")
}
}
on("Generic bound type as property type") {
class ObjA<A>(val a: A)
class ObjB<B>(val objA: ObjA<B>)
class Obj(val objB: ObjB<Int>)
val sch = Reflexion(Obj::class)
val obj = sch.instanceFrom("{objB:{objA:{a:1}}}", DefaultFactory).valueOrThrow
it("") {
shouldEqual(obj.objB.objA.a, 1)
}
}
// on("") {
// it("") {
//
// }
// }
}
}
} | apache-2.0 | ff643f1babf154a4eb70d6f2e2a2b397 | 28.273684 | 125 | 0.632374 | 2.836735 | false | false | false | false |
PolymerLabs/arcs | java/arcs/android/type/ParcelableType.kt | 1 | 7851 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.type
import android.os.Parcel
import android.os.Parcelable
import arcs.core.data.CollectionType
import arcs.core.data.CountType
import arcs.core.data.EntityType
import arcs.core.data.MuxType
import arcs.core.data.ReferenceType
import arcs.core.data.SingletonType
import arcs.core.data.TupleType
import arcs.core.data.TypeVariable
import arcs.core.type.Tag
import arcs.core.type.Type
/** Wrappers for [Type] classes which implements [Parcelable]. */
sealed class ParcelableType(open val actual: Type) : Parcelable {
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(actual.tag.ordinal)
// Subclasses will write the remainder.
}
override fun describeContents(): Int = 0
/** [Parcelable] variant of [arcs.core.data.CollectionType]. */
data class CollectionType(
override val actual: arcs.core.data.CollectionType<*>
) : ParcelableType(actual) {
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeType(actual.collectionType, flags)
}
companion object CREATOR : Parcelable.Creator<CollectionType> {
override fun createFromParcel(parcel: Parcel): CollectionType =
CollectionType(actual = CollectionType(requireNotNull(parcel.readType())))
override fun newArray(size: Int): Array<CollectionType?> = arrayOfNulls(size)
}
}
/** [Parcelable] variant of [arcs.core.data.CountType]. */
data class CountType(
override val actual: arcs.core.data.CountType = arcs.core.data.CountType()
) : ParcelableType(actual) {
// No need to override writeToParcel.
companion object CREATOR : Parcelable.Creator<CountType> {
override fun createFromParcel(parcel: Parcel): CountType = CountType()
override fun newArray(size: Int): Array<CountType?> = arrayOfNulls(size)
}
}
/** [Parcelable] variant of [arcs.core.data.EntityType]. */
data class EntityType(
override val actual: arcs.core.data.EntityType
) : ParcelableType(actual) {
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeSchema(actual.entitySchema, flags)
}
companion object CREATOR : Parcelable.Creator<EntityType> {
override fun createFromParcel(parcel: Parcel): EntityType =
EntityType(actual = EntityType(requireNotNull(parcel.readSchema())))
override fun newArray(size: Int): Array<EntityType?> = arrayOfNulls(size)
}
}
/** [Parcelable] variant of [arcs.core.data.MuxType]. */
data class MuxType(
override val actual: arcs.core.data.MuxType<*>
) : ParcelableType(actual) {
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeType(actual.containedType, flags)
}
companion object CREATOR : Parcelable.Creator<MuxType> {
override fun createFromParcel(parcel: Parcel): MuxType =
MuxType(actual = MuxType(requireNotNull(parcel.readType())))
override fun newArray(size: Int): Array<MuxType?> = arrayOfNulls(size)
}
}
/** [Parcelable] variant of [arcs.core.data.ReferenceType]. */
class ReferenceType(
override val actual: arcs.core.data.ReferenceType<*>
) : ParcelableType(actual) {
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeType(actual.containedType, flags)
}
companion object CREATOR : Parcelable.Creator<ReferenceType> {
override fun createFromParcel(parcel: Parcel): ReferenceType =
ReferenceType(actual = ReferenceType(requireNotNull(parcel.readType())))
override fun newArray(size: Int): Array<ReferenceType?> = arrayOfNulls(size)
}
}
/** [Parcelable] variant of [arcs.core.data.SingletonType]. */
data class SingletonType(
override val actual: arcs.core.data.SingletonType<*>
) : ParcelableType(actual) {
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeType(actual.containedType, flags)
}
companion object CREATOR : Parcelable.Creator<SingletonType> {
override fun createFromParcel(parcel: Parcel): SingletonType =
SingletonType(
actual = SingletonType(requireNotNull(parcel.readType()))
)
override fun newArray(size: Int): Array<SingletonType?> = arrayOfNulls(size)
}
}
/** [Parcelable] variant of [arcs.core.data.TupleType]. */
class TupleType(
override val actual: arcs.core.data.TupleType
) : ParcelableType(actual) {
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeInt(actual.elementTypes.size)
for (element in actual.elementTypes) {
parcel.writeType(element, flags)
}
}
companion object CREATOR : Parcelable.Creator<TupleType> {
override fun createFromParcel(parcel: Parcel): TupleType {
val elements = mutableListOf<Type>()
repeat(parcel.readInt()) {
elements.add(requireNotNull(parcel.readType()))
}
return TupleType(actual = TupleType(elements))
}
override fun newArray(size: Int): Array<TupleType?> = arrayOfNulls(size)
}
}
/** [Parcelable] variant of [arcs.core.data.TypeVariable]. */
data class TypeVariable(
override val actual: arcs.core.data.TypeVariable
) : ParcelableType(actual) {
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeString(actual.name)
}
companion object CREATOR : Parcelable.Creator<TypeVariable> {
override fun createFromParcel(parcel: Parcel) = TypeVariable(
actual = TypeVariable(requireNotNull(parcel.readString()))
)
override fun newArray(size: Int): Array<TypeVariable?> = arrayOfNulls(size)
}
}
companion object CREATOR : Parcelable.Creator<ParcelableType> {
override fun createFromParcel(parcel: Parcel): ParcelableType =
when (Tag.values()[parcel.readInt()]) {
Tag.Collection -> CollectionType.createFromParcel(parcel)
Tag.Count -> CountType.createFromParcel(parcel)
Tag.Entity -> EntityType.createFromParcel(parcel)
Tag.Mux -> MuxType.createFromParcel(parcel)
Tag.Reference -> ReferenceType.createFromParcel(parcel)
Tag.Singleton -> SingletonType.createFromParcel(parcel)
Tag.Tuple -> TupleType.createFromParcel(parcel)
Tag.TypeVariable -> TypeVariable.createFromParcel(parcel)
}
override fun newArray(size: Int): Array<ParcelableType?> = arrayOfNulls(size)
}
}
/** Converts a raw [Type] to its [ParcelableType] variant. */
fun Type.toParcelable(): ParcelableType = when (tag) {
Tag.Collection -> ParcelableType.CollectionType(this as CollectionType<*>)
Tag.Count -> ParcelableType.CountType(this as CountType)
Tag.Entity -> ParcelableType.EntityType(this as EntityType)
Tag.Mux -> ParcelableType.MuxType(this as MuxType<*>)
Tag.Reference -> ParcelableType.ReferenceType(this as ReferenceType<*>)
Tag.Singleton -> ParcelableType.SingletonType(this as SingletonType<*>)
Tag.Tuple -> ParcelableType.TupleType(this as TupleType)
Tag.TypeVariable -> ParcelableType.TypeVariable(this as TypeVariable)
}
/** Writes a [Type] to the [Parcel]. */
fun Parcel.writeType(type: Type, flags: Int) = writeTypedObject(type.toParcelable(), flags)
/** Reads a [Type] from the [Parcel]. */
fun Parcel.readType(): Type? = readTypedObject(ParcelableType)?.actual
| bsd-3-clause | 3a7293464a5a1f01bb1def3c65518012 | 36.208531 | 96 | 0.710483 | 4.368948 | false | false | false | false |
k9mail/k-9 | app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/general/LanguagePreference.kt | 1 | 1230 | package com.fsck.k9.ui.settings.general
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import androidx.core.content.res.TypedArrayUtils
import androidx.preference.ListPreference
import com.fsck.k9.ui.R
class LanguagePreference
@JvmOverloads
@SuppressLint("RestrictedApi")
constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = TypedArrayUtils.getAttr(
context,
androidx.preference.R.attr.dialogPreferenceStyle,
android.R.attr.dialogPreferenceStyle
),
defStyleRes: Int = 0
) : ListPreference(context, attrs, defStyleAttr, defStyleRes) {
init {
val supportedLanguages = context.resources.getStringArray(R.array.supported_languages).toSet()
val newEntries = mutableListOf<CharSequence>()
val newEntryValues = mutableListOf<CharSequence>()
entryValues.forEachIndexed { index, language ->
if (language in supportedLanguages) {
newEntries.add(entries[index])
newEntryValues.add(entryValues[index])
}
}
entries = newEntries.toTypedArray()
entryValues = newEntryValues.toTypedArray()
}
}
| apache-2.0 | 33df163615e00238d7e91a49f9ee9d09 | 30.538462 | 102 | 0.707317 | 4.785992 | false | false | false | false |
PolymerLabs/arcs | java/arcs/android/host/parcelables/ParcelableHandleConnection.kt | 1 | 2898 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.host.parcelables
import android.os.Parcel
import android.os.Parcelable
import arcs.android.type.readType
import arcs.android.type.writeType
import arcs.core.data.HandleMode
import arcs.core.data.Plan
import arcs.core.data.expression.deserializeExpression
import arcs.core.data.expression.serialize
/** [Parcelable] variant of [Plan.HandleConnection]. */
data class ParcelableHandleConnection(
override val actual: Plan.HandleConnection
) : ActualParcelable<Plan.HandleConnection> {
override fun writeToParcel(parcel: Parcel, flags: Int) {
// TODO(b/161819104): Avoid duplicate serialization, Handles are serialized as part of the
// Plan object.
parcel.writeHandle(actual.handle, flags)
parcel.writeType(actual.type, flags)
parcel.writeInt(actual.mode.ordinal)
parcel.writeString(actual.expression?.serialize() ?: "")
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<ParcelableHandleConnection> {
override fun createFromParcel(parcel: Parcel): ParcelableHandleConnection {
// TODO(b/161819104): Use Handle from Plan, instead of creating a new Handle object.
val handle = requireNotNull(parcel.readHandle()) {
"No Handle found in Parcel"
}
val type = requireNotNull(parcel.readType()) {
"No type found in Parcel"
}
val handleModeOrdinal = requireNotNull(parcel.readInt()) {
"No handleMode found in Parcel"
}
val handleMode = requireNotNull(HandleMode.values().getOrNull(handleModeOrdinal)) {
"HandleMode ordinal unknown value $handleModeOrdinal"
}
val expression = parcel.readString()?.ifEmpty { null }
return ParcelableHandleConnection(
Plan.HandleConnection(
handle,
handleMode,
type,
emptyList(),
expression?.deserializeExpression()
)
)
}
override fun newArray(size: Int): Array<ParcelableHandleConnection?> =
arrayOfNulls(size)
}
}
/** Wraps a [Plan.HandleConnection] as a [ParcelableHandleConnection]. */
fun Plan.HandleConnection.toParcelable(): ParcelableHandleConnection =
ParcelableHandleConnection(this)
/** Writes a [Plan.HandleConnection] to a [Parcel]. */
fun Parcel.writeHandleConnectionSpec(handleConnection: Plan.HandleConnection, flags: Int) =
writeTypedObject(handleConnection.toParcelable(), flags)
/** Reads a [Plan.HandleConnection] from a [Parcel]. */
fun Parcel.readHandleConnectionSpec(): Plan.HandleConnection? =
readTypedObject(ParcelableHandleConnection)?.actual
| bsd-3-clause | 572be8626044771362b2789011b6ca9c | 33.5 | 96 | 0.724983 | 4.585443 | false | false | false | false |
fcostaa/kotlin-rxjava-android | feature/wiki/src/main/kotlin/com/github/felipehjcosta/marvelapp/wiki/presentation/OthersCharactersViewModelInputOutput.kt | 1 | 1448 | package com.github.felipehjcosta.marvelapp.wiki.presentation
import com.felipecosta.rxaction.RxAction
import com.felipecosta.rxaction.RxCommand
import com.github.felipehjcosta.marvelapp.base.character.data.pojo.Character
import com.github.felipehjcosta.marvelapp.wiki.datamodel.OthersCharactersDataModel
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class OthersCharactersViewModelInputOutput @Inject constructor(
private val dataModel: OthersCharactersDataModel
) : OthersCharactersViewModel(), OthersCharactersViewModelInput, OthersCharactersViewModelOutput {
private val asyncLoadItemsCommand: RxAction<Any, List<Character>> = RxAction {
dataModel.getOthersCharacters()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
}
override val input: OthersCharactersViewModelInput = this
override val output: OthersCharactersViewModelOutput = this
override val loadItemsCommand: RxCommand<Any>
get() = asyncLoadItemsCommand
override val items: Observable<List<CharacterItemViewModel>>
get() = asyncLoadItemsCommand.elements.map { list ->
list.map { CharacterItemViewModel(it.id, it.name, it.thumbnail.url) }
}
override val showLoading: Observable<Boolean>
get() = asyncLoadItemsCommand.executing
}
| mit | 8ec0e89a50ec50fda5b74594cc9b3c49 | 41.588235 | 98 | 0.782459 | 4.975945 | false | false | false | false |
Hexworks/zircon | zircon.jvm.libgdx/src/main/kotlin/org/hexworks/zircon/internal/renderer/LibgdxRenderer.kt | 1 | 9133 | package org.hexworks.zircon.internal.renderer
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.zircon.api.LibgdxApplications
import org.hexworks.zircon.api.application.CursorStyle
import org.hexworks.zircon.api.application.filterByType
import org.hexworks.zircon.api.behavior.TilesetHolder
import org.hexworks.zircon.api.color.TileColor
import org.hexworks.zircon.api.data.CharacterTile
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.modifier.TileTransformModifier
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.api.tileset.Tileset
import org.hexworks.zircon.api.tileset.TilesetLoader
import org.hexworks.zircon.internal.RunTimeStats
import org.hexworks.zircon.internal.config.RuntimeConfig
import org.hexworks.zircon.internal.data.PixelPosition
import org.hexworks.zircon.internal.graphics.FastTileGraphics
import org.hexworks.zircon.internal.grid.InternalTileGrid
import org.hexworks.zircon.internal.tileset.impl.DefaultTilesetLoader
@Suppress("UNCHECKED_CAST", "UNUSED_PARAMETER")
class LibgdxRenderer(
private val grid: InternalTileGrid,
private val debug: Boolean = false
) : Renderer {
override val closedValue: Property<Boolean> = false.toProperty()
private val config = RuntimeConfig.config
private var maybeBatch: SpriteBatch? = null
private lateinit var cursorRenderer: ShapeRenderer
private val tilesetLoader: TilesetLoader<SpriteBatch> = DefaultTilesetLoader(
LibgdxApplications.DEFAULT_FACTORIES + config.tilesetLoaders.filterByType(SpriteBatch::class)
)
private var blinkOn = true
private var timeSinceLastBlink: Float = 0f
private lateinit var backgroundTexture: Texture
private var backgroundWidth: Int = 0
private var backgroundHeight: Int = 0
override fun create() {
maybeBatch = SpriteBatch().apply {
val camera = OrthographicCamera()
camera.setToOrtho(true)
projectionMatrix = camera.combined
}
cursorRenderer = ShapeRenderer()
val whitePixmap = Pixmap(grid.widthInPixels, grid.heightInPixels, Pixmap.Format.RGBA8888)
whitePixmap.setColor(Color.WHITE)
whitePixmap.fill()
backgroundTexture = Texture(whitePixmap)
backgroundWidth = whitePixmap.width / grid.width
backgroundHeight = whitePixmap.height / grid.height
whitePixmap.dispose()
}
override fun render() {
if (debug) {
RunTimeStats.addTimedStatFor("debug.render.time") {
doRender(Gdx.app.graphics.deltaTime)
}
} else doRender(Gdx.app.graphics.deltaTime)
}
override fun close() {
closedValue.value = true
maybeBatch?.let(SpriteBatch::dispose)
}
private fun doRender(delta: Float) {
handleBlink(delta)
maybeBatch?.let { batch ->
batch.begin()
val tilesToRender = mutableMapOf<Position, MutableList<Pair<Tile, TilesetResource>>>()
val renderables = grid.renderables
for (i in renderables.indices) {
val renderable = renderables[i]
if (!renderable.isHidden) {
val graphics = FastTileGraphics(
initialSize = renderable.size,
initialTileset = renderable.tileset,
initialTiles = emptyMap()
)
renderable.render(graphics)
graphics.contents().forEach { (tilePos, tile) ->
val finalPos = tilePos + renderable.position
tilesToRender.getOrPut(finalPos) { mutableListOf() }
if (tile.isOpaque) {
tilesToRender[finalPos] = mutableListOf(tile to renderable.tileset)
} else {
tilesToRender[finalPos]?.add(tile to renderable.tileset)
}
}
}
}
for ((pos, tiles) in tilesToRender) {
for ((tile, tileset) in tiles) {
renderTile(
batch = batch,
position = pos.toPixelPosition(tileset),
tile = tile,
tileset = tilesetLoader.loadTilesetFrom(tileset)
)
}
}
batch.end()
cursorRenderer.projectionMatrix = batch.projectionMatrix
if (shouldDrawCursor()) {
grid.getTileAtOrNull(grid.cursorPosition)?.let { it ->
drawCursor(cursorRenderer, it, grid.cursorPosition)
}
}
}
}
private fun renderTile(
batch: SpriteBatch,
tile: Tile,
tileset: Tileset<SpriteBatch>,
position: PixelPosition
) {
if (tile.isNotEmpty) {
var finalTile = tile
finalTile.modifiers.filterIsInstance<TileTransformModifier<CharacterTile>>().forEach { modifier ->
if (modifier.canTransform(finalTile)) {
(finalTile as? CharacterTile)?.let {
finalTile = modifier.transform(it)
}
}
}
finalTile = if (tile.isBlinking && blinkOn) {
tile.withBackgroundColor(tile.foregroundColor)
.withForegroundColor(tile.backgroundColor)
} else {
tile
}
drawBack(
tile = finalTile,
surface = batch,
position = position
)
((finalTile as? TilesetHolder)?.let {
tilesetLoader.loadTilesetFrom(it.tileset)
} ?: tileset).drawTile(
tile = finalTile,
surface = batch,
position = position
)
}
}
private fun drawBack(
tile: Tile,
surface: SpriteBatch,
position: Position
) {
val x = position.x.toFloat()
val y = position.y.toFloat()
val backSprite = Sprite(backgroundTexture)
backSprite.setSize(backgroundWidth.toFloat(), backgroundHeight.toFloat())
backSprite.setOrigin(0f, 0f)
backSprite.setOriginBasedPosition(x, y)
backSprite.flip(false, true)
backSprite.color = Color(
tile.backgroundColor.red.toFloat() / 255,
tile.backgroundColor.green.toFloat() / 255,
tile.backgroundColor.blue.toFloat() / 255,
tile.backgroundColor.alpha.toFloat() / 255
)
backSprite.draw(surface)
}
private fun handleBlink(delta: Float) {
timeSinceLastBlink += delta
if (timeSinceLastBlink > config.blinkLengthInMilliSeconds) {
blinkOn = !blinkOn
}
}
private fun drawCursor(shapeRenderer: ShapeRenderer, character: Tile, position: Position) {
val tileWidth = grid.tileset.width
val tileHeight = grid.tileset.height
val x = (position.x * tileWidth).toFloat()
val y = (position.y * tileHeight).toFloat()
val cursorColor = colorToGDXColor(config.cursorColor)
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled)
shapeRenderer.color = cursorColor
when (config.cursorStyle) {
CursorStyle.USE_CHARACTER_FOREGROUND -> {
if (blinkOn) {
shapeRenderer.color = colorToGDXColor(character.foregroundColor)
shapeRenderer.rect(x, y, tileWidth.toFloat(), tileHeight.toFloat())
}
}
CursorStyle.FIXED_BACKGROUND -> shapeRenderer.rect(x, y, tileWidth.toFloat(), tileHeight.toFloat())
CursorStyle.UNDER_BAR -> shapeRenderer.rect(x, y + tileHeight - 3, tileWidth.toFloat(), 2.0f)
CursorStyle.VERTICAL_BAR -> shapeRenderer.rect(x, y + 1, 2.0f, tileHeight - 2.0f)
}
shapeRenderer.end()
}
private fun shouldDrawCursor(): Boolean {
return grid.isCursorVisible &&
(config.isCursorBlinking.not() || config.isCursorBlinking && blinkOn)
}
private fun colorToGDXColor(color: TileColor): Color {
return Color(
color.red / 255.0f,
color.green / 255.0f,
color.blue / 255.0f,
color.alpha / 255.0f
)
}
fun TileColor.toGdxColor(): Color {
return Color(
this.red / 255.0f,
this.green / 255.0f,
this.blue / 255.0f,
this.alpha / 255.0f
)
}
}
| apache-2.0 | 4a22009a252f3b103e1bd31070c9c2ef | 37.37395 | 111 | 0.609657 | 4.737033 | false | false | false | false |
romanoid/buck | test/com/facebook/buck/multitenant/service/IndexTest.kt | 1 | 6061 | /*
* Copyright 2019-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.multitenant.service
import org.junit.Assert.assertEquals
import org.junit.Test
import java.nio.file.Paths
class IndexTest {
@Test
fun getTargetsAndDeps() {
val bt = BUILD_TARGET_PARSER
val index = Index(bt)
/*
* //java/com/facebook/buck/base:base has no deps.
*/
val changes1 = Changes(
addedBuildPackages = listOf(
BuildPackage(Paths.get("java/com/facebook/buck/base"),
setOf(
createRawRule("//java/com/facebook/buck/base:base", setOf())
))
),
modifiedBuildPackages = listOf(),
removedBuildPackages = listOf())
val commit1 = "608fd7bdf9"
index.addCommitData(commit1, changes1)
/*
* //java/com/facebook/buck/model:model depends on //java/com/facebook/buck/base:base.
*/
val changes2 = Changes(
addedBuildPackages = listOf(
BuildPackage(Paths.get("java/com/facebook/buck/model"),
setOf(
createRawRule("//java/com/facebook/buck/model:model", setOf(
"//java/com/facebook/buck/base:base"
)))
)),
modifiedBuildPackages = listOf(),
removedBuildPackages = listOf())
val commit2 = "9efba3bca1"
index.addCommitData(commit2, changes2)
/*
* //java/com/facebook/buck/util:util is introduced and
* //java/com/facebook/buck/model:model is updated to depend on it.
*/
val changes3 = Changes(
addedBuildPackages = listOf(
BuildPackage(Paths.get("java/com/facebook/buck/util"),
setOf(
createRawRule("//java/com/facebook/buck/util:util", setOf(
"//java/com/facebook/buck/base:base"
))
))
),
modifiedBuildPackages = listOf(
BuildPackage(Paths.get("java/com/facebook/buck/model"),
setOf(
createRawRule("//java/com/facebook/buck/model:model", setOf(
"//java/com/facebook/buck/base:base",
"//java/com/facebook/buck/util:util"
))
))
),
removedBuildPackages = listOf())
val commit3 = "1b522b5b47"
index.addCommitData(commit3, changes3)
/* Nothing changes! */
val changes4 = Changes(listOf(), listOf(), listOf())
val commit4 = "270c3e4c42"
index.addCommitData(commit4, changes4)
/*
* //java/com/facebook/buck/model:model is removed.
*/
val changes5 = Changes(
addedBuildPackages = listOf(),
modifiedBuildPackages = listOf(),
removedBuildPackages = listOf(Paths.get("java/com/facebook/buck/model")))
val commit5 = "c880d5b5d8"
index.addCommitData(commit5, changes5)
index.acquireReadLock().use {
assertEquals(
setOf(bt("//java/com/facebook/buck/base:base")),
index.getTargets(it, commit1).toSet())
assertEquals(
setOf(
bt("//java/com/facebook/buck/base:base"),
bt("//java/com/facebook/buck/model:model")),
index.getTargets(it, commit2).toSet())
assertEquals(
setOf(
bt("//java/com/facebook/buck/base:base"),
bt("//java/com/facebook/buck/model:model"),
bt("//java/com/facebook/buck/util:util")),
index.getTargets(it, commit3).toSet())
assertEquals(
setOf(
bt("//java/com/facebook/buck/base:base"),
bt("//java/com/facebook/buck/model:model"),
bt("//java/com/facebook/buck/util:util")),
index.getTargets(it, commit4).toSet())
assertEquals(
setOf(
bt("//java/com/facebook/buck/base:base"),
bt("//java/com/facebook/buck/util:util")),
index.getTargets(it, commit5).toSet())
assertEquals(
setOf(
bt("//java/com/facebook/buck/base:base")
),
index.getTransitiveDeps(it, commit2, bt("//java/com/facebook/buck/model:model"))
)
assertEquals(
setOf(
bt("//java/com/facebook/buck/base:base"),
bt("//java/com/facebook/buck/util:util")
),
index.getTransitiveDeps(it, commit3, bt("//java/com/facebook/buck/model:model"))
)
}
}
}
| apache-2.0 | 75524901df93fd38296bd1fb66b26642 | 41.384615 | 100 | 0.478634 | 5.029876 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/widgets/QuickStartFocusPoint.kt | 1 | 5299 | package org.wordpress.android.widgets
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import org.wordpress.android.R
import org.wordpress.android.R.styleable
/**
* Perpetually animated quick start focus point (hint)
* Consists of:
* - Initial expand animation with bounce
* 2 staggered animations on repeat:
* - Collapse
* - Expand
*/
class QuickStartFocusPoint : FrameLayout {
companion object {
const val OUTER_CIRCLE_ANIMATION_START_OFFSET_MS = 1000L
const val INNER_CIRCLE_ANIMATION_START_OFFSET_MS = OUTER_CIRCLE_ANIMATION_START_OFFSET_MS + 50L
// these must match the same values in attrs.xml
private const val SIZE_SMALL = 0
private const val SIZE_NORMAL = 1
}
constructor(context: Context) : super(context) {
initView()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initView(readSize(attrs))
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
initView(readSize(attrs))
}
private fun initView(readSize: Int = SIZE_NORMAL) {
val layout = when (readSize) {
SIZE_SMALL -> R.layout.quick_start_focus_circle_small
else -> R.layout.quick_start_focus_circle
}
View.inflate(context, layout, this)
startAnimation()
}
private fun readSize(attrs: AttributeSet): Int {
val a = context.theme.obtainStyledAttributes(
attrs,
styleable.QuickStartFocusPoint,
0, 0
)
try {
return a.getInteger(styleable.QuickStartFocusPoint_size, SIZE_NORMAL)
} finally {
a.recycle()
}
}
fun setVisibleOrGone(visible: Boolean) {
if (visible) {
this.visibility = View.VISIBLE
startAnimation()
} else {
this.visibility = View.GONE
}
}
private fun startAnimation() {
val outerCircle = findViewById<View>(R.id.quick_start_focus_outer_circle)
val innerCircle = findViewById<View>(R.id.quick_start_focus_inner_circle)
val outerCircleInitialAnimation =
AnimationUtils.loadAnimation(context, R.anim.quick_start_circle_initial_animation)
val innerCircleInitialAnimation =
AnimationUtils.loadAnimation(context, R.anim.quick_start_circle_initial_animation)
val outerCircleCollapseAnimation =
AnimationUtils.loadAnimation(context, R.anim.quick_start_circle_collapse_animation)
val innerCircleCollapseAnimation =
AnimationUtils.loadAnimation(context, R.anim.quick_start_circle_collapse_animation)
val innerCircleExpanAnimation =
AnimationUtils.loadAnimation(context, R.anim.quick_start_circle_expand_animation)
val outerCircleExpanAnimation =
AnimationUtils.loadAnimation(context, R.anim.quick_start_circle_expand_animation)
innerCircleInitialAnimation.setAnimationListener(object : AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {
outerCircleCollapseAnimation.startOffset = OUTER_CIRCLE_ANIMATION_START_OFFSET_MS
innerCircleCollapseAnimation.startOffset = INNER_CIRCLE_ANIMATION_START_OFFSET_MS
outerCircle.startAnimation(outerCircleCollapseAnimation)
innerCircle.startAnimation(innerCircleCollapseAnimation)
}
override fun onAnimationRepeat(animation: Animation) {}
})
innerCircleCollapseAnimation.setAnimationListener(object : AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {
outerCircle.startAnimation(outerCircleExpanAnimation)
innerCircle.startAnimation(innerCircleExpanAnimation)
}
override fun onAnimationRepeat(animation: Animation) {}
})
innerCircleExpanAnimation.setAnimationListener(object : AnimationListener {
override fun onAnimationStart(animation: Animation) {}
override fun onAnimationEnd(animation: Animation) {
outerCircleCollapseAnimation.startOffset = OUTER_CIRCLE_ANIMATION_START_OFFSET_MS
innerCircleCollapseAnimation.startOffset = INNER_CIRCLE_ANIMATION_START_OFFSET_MS
outerCircle.startAnimation(outerCircleCollapseAnimation)
innerCircle.startAnimation(innerCircleCollapseAnimation)
}
override fun onAnimationRepeat(animation: Animation) {}
})
outerCircleInitialAnimation.startOffset = OUTER_CIRCLE_ANIMATION_START_OFFSET_MS
outerCircle.startAnimation(outerCircleInitialAnimation)
innerCircleInitialAnimation.startOffset = INNER_CIRCLE_ANIMATION_START_OFFSET_MS
innerCircle.startAnimation(innerCircleInitialAnimation)
}
}
| gpl-2.0 | aaefbccbfcf4c22f15403cb98aede057 | 37.678832 | 105 | 0.682582 | 5.046667 | false | false | false | false |
mdaniel/intellij-community | java/testFramework/src/com/intellij/util/io/java/ClassFileBuilder.kt | 9 | 1826 | /*
* 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.util.io.java
import com.intellij.util.io.DirectoryContentBuilder
import com.intellij.util.io.java.impl.ClassFileBuilderImpl
import org.jetbrains.jps.model.java.LanguageLevel
import kotlin.reflect.KClass
/**
* Produces class-file with qualified name [name] in a place specified by [content]. If the class is not from the default package,
* the produced file will be placed in a sub-directory according to its package.
*/
inline fun DirectoryContentBuilder.classFile(name: String, content: ClassFileBuilder.() -> Unit) {
val builder = ClassFileBuilderImpl(name)
builder.content()
builder.generate(this)
}
abstract class ClassFileBuilder {
var javaVersion: LanguageLevel = LanguageLevel.JDK_1_8
var superclass: String = "java.lang.Object"
var interfaces: List<String> = emptyList()
var access: AccessModifier = AccessModifier.PUBLIC
abstract fun field(name: String, type: KClass<*>, access: AccessModifier = AccessModifier.PRIVATE)
/**
* Adds a field which type is a class with qualified name [type]
*/
abstract fun field(name: String, type: String, access: AccessModifier = AccessModifier.PRIVATE)
}
enum class AccessModifier { PRIVATE, PUBLIC, PROTECTED, PACKAGE_LOCAL } | apache-2.0 | a9ad0a2d6475ec5affe2eff88f0fd884 | 37.87234 | 130 | 0.759584 | 4.197701 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ArtifactEntityImpl.kt | 1 | 17264 | package com.intellij.workspaceModel.storage.bridgeEntities.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.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
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.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneChild
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToOneChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneChildOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToOneChildOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
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 ArtifactEntityImpl: ArtifactEntity, WorkspaceEntityBase() {
companion object {
internal val ROOTELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java, CompositePackagingElementEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
internal val CUSTOMPROPERTIES_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java, ArtifactPropertiesEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java, ArtifactOutputPackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ONE, false)
val connections = listOf<ConnectionId>(
ROOTELEMENT_CONNECTION_ID,
CUSTOMPROPERTIES_CONNECTION_ID,
ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID,
)
}
@JvmField var _name: String? = null
override val name: String
get() = _name!!
@JvmField var _artifactType: String? = null
override val artifactType: String
get() = _artifactType!!
override var includeInProjectBuild: Boolean = false
@JvmField var _outputUrl: VirtualFileUrl? = null
override val outputUrl: VirtualFileUrl?
get() = _outputUrl
override val rootElement: CompositePackagingElementEntity
get() = snapshot.extractOneToAbstractOneChild(ROOTELEMENT_CONNECTION_ID, this)!!
override val customProperties: List<ArtifactPropertiesEntity>
get() = snapshot.extractOneToManyChildren<ArtifactPropertiesEntity>(CUSTOMPROPERTIES_CONNECTION_ID, this)!!.toList()
override val artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity?
get() = snapshot.extractOneToOneChild(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ArtifactEntityData?): ModifiableWorkspaceEntityBase<ArtifactEntity>(), ArtifactEntity.Builder {
constructor(): this(ArtifactEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ArtifactEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "outputUrl", this.outputUrl)
// 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().isNameInitialized()) {
error("Field ArtifactEntity#name should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ArtifactEntity#entitySource should be initialized")
}
if (!getEntityData().isArtifactTypeInitialized()) {
error("Field ArtifactEntity#artifactType should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToAbstractOneChild<WorkspaceEntityBase>(ROOTELEMENT_CONNECTION_ID, this) == null) {
error("Field ArtifactEntity#rootElement should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, ROOTELEMENT_CONNECTION_ID)] == null) {
error("Field ArtifactEntity#rootElement should be initialized")
}
}
// Check initialization for collection with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CUSTOMPROPERTIES_CONNECTION_ID, this) == null) {
error("Field ArtifactEntity#customProperties should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] == null) {
error("Field ArtifactEntity#customProperties should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var artifactType: String
get() = getEntityData().artifactType
set(value) {
checkModificationAllowed()
getEntityData().artifactType = value
changedProperty.add("artifactType")
}
override var includeInProjectBuild: Boolean
get() = getEntityData().includeInProjectBuild
set(value) {
checkModificationAllowed()
getEntityData().includeInProjectBuild = value
changedProperty.add("includeInProjectBuild")
}
override var outputUrl: VirtualFileUrl?
get() = getEntityData().outputUrl
set(value) {
checkModificationAllowed()
getEntityData().outputUrl = value
changedProperty.add("outputUrl")
val _diff = diff
if (_diff != null) index(this, "outputUrl", value)
}
override var rootElement: CompositePackagingElementEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneChild(ROOTELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, ROOTELEMENT_CONNECTION_ID)]!! as CompositePackagingElementEntity
} else {
this.entityLinks[EntityLink(true, ROOTELEMENT_CONNECTION_ID)]!! as CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, ROOTELEMENT_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.updateOneToAbstractOneChildOfParent(ROOTELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, ROOTELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, ROOTELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("rootElement")
}
// List of non-abstract referenced types
var _customProperties: List<ArtifactPropertiesEntity>? = emptyList()
override var customProperties: List<ArtifactPropertiesEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ArtifactPropertiesEntity>(CUSTOMPROPERTIES_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] as? List<ArtifactPropertiesEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] as? List<ArtifactPropertiesEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CUSTOMPROPERTIES_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CUSTOMPROPERTIES_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CUSTOMPROPERTIES_CONNECTION_ID)] = value
}
changedProperty.add("customProperties")
}
override var artifactOutputPackagingElement: ArtifactOutputPackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToOneChild(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] as? ArtifactOutputPackagingElementEntity
} else {
this.entityLinks[EntityLink(true, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] as? ArtifactOutputPackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, ARTIFACTOUTPUTPACKAGINGELEMENT_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.updateOneToOneChildOfParent(ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(false, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(true, ARTIFACTOUTPUTPACKAGINGELEMENT_CONNECTION_ID)] = value
}
changedProperty.add("artifactOutputPackagingElement")
}
override fun getEntityData(): ArtifactEntityData = result ?: super.getEntityData() as ArtifactEntityData
override fun getEntityClass(): Class<ArtifactEntity> = ArtifactEntity::class.java
}
}
class ArtifactEntityData : WorkspaceEntityData.WithCalculablePersistentId<ArtifactEntity>() {
lateinit var name: String
lateinit var artifactType: String
var includeInProjectBuild: Boolean = false
var outputUrl: VirtualFileUrl? = null
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isArtifactTypeInitialized(): Boolean = ::artifactType.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ArtifactEntity> {
val modifiable = ArtifactEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ArtifactEntity {
val entity = ArtifactEntityImpl()
entity._name = name
entity._artifactType = artifactType
entity.includeInProjectBuild = includeInProjectBuild
entity._outputUrl = outputUrl
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun persistentId(): PersistentEntityId<*> {
return ArtifactId(name)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ArtifactEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactEntityData
if (this.name != other.name) return false
if (this.entitySource != other.entitySource) return false
if (this.artifactType != other.artifactType) return false
if (this.includeInProjectBuild != other.includeInProjectBuild) return false
if (this.outputUrl != other.outputUrl) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactEntityData
if (this.name != other.name) return false
if (this.artifactType != other.artifactType) return false
if (this.includeInProjectBuild != other.includeInProjectBuild) return false
if (this.outputUrl != other.outputUrl) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + artifactType.hashCode()
result = 31 * result + includeInProjectBuild.hashCode()
result = 31 * result + outputUrl.hashCode()
return result
}
} | apache-2.0 | 26c4fe1d727b9954ccf64c51369e2040 | 45.536388 | 246 | 0.620366 | 5.908282 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/renameConflictUtils.kt | 1 | 20768 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.psi.*
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.util.MoveRenameUsageInfo
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewUtil
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde
import org.jetbrains.kotlin.idea.base.psi.copied
import org.jetbrains.kotlin.idea.base.util.and
import org.jetbrains.kotlin.idea.base.util.restrictToKotlinSources
import org.jetbrains.kotlin.idea.highlighter.markers.resolveDeclarationWithParents
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.refactoring.explicateAsText
import org.jetbrains.kotlin.idea.refactoring.getThisLabelName
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.base.util.useScope
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.getAllAccessibleFunctions
import org.jetbrains.kotlin.idea.util.getAllAccessibleVariables
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DelegatingBindingTrace
import org.jetbrains.kotlin.resolve.OverloadChecker
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue
import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue
import org.jetbrains.kotlin.resolve.calls.results.TypeSpecificityComparator
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.error.ErrorUtils
import org.jetbrains.kotlin.utils.SmartList
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal fun ResolvedCall<*>.noReceivers() = dispatchReceiver == null && extensionReceiver == null
internal fun PsiNamedElement.renderDescription(): String {
val type = UsageViewUtil.getType(this)
if (name == null || name!!.startsWith("<")) return type
return "$type '$name'".trim()
}
internal fun PsiElement.representativeContainer(): PsiNamedElement? = when (this) {
is KtDeclaration -> containingClassOrObject
?: getStrictParentOfType<KtNamedDeclaration>()
?: JavaPsiFacade.getInstance(project).findPackage(containingKtFile.packageFqName.asString())
is PsiMember -> containingClass
else -> null
}
internal fun DeclarationDescriptor.canonicalRender(): String = DescriptorRenderer.FQ_NAMES_IN_TYPES.render(this)
internal fun checkRedeclarations(
declaration: KtNamedDeclaration,
newName: String,
result: MutableList<UsageInfo>,
resolutionFacade: ResolutionFacade = declaration.getResolutionFacade(),
descriptor: DeclarationDescriptor = declaration.unsafeResolveToDescriptor(resolutionFacade)
) {
fun DeclarationDescriptor.isTopLevelPrivate(): Boolean =
this is DeclarationDescriptorWithVisibility && visibility == DescriptorVisibilities.PRIVATE && containingDeclaration is PackageFragmentDescriptor
fun isInSameFile(d1: DeclarationDescriptor, d2: DeclarationDescriptor): Boolean =
(d1 as? DeclarationDescriptorWithSource)?.source?.getPsi()?.containingFile == (d2 as? DeclarationDescriptorWithSource)?.source
?.getPsi()?.containingFile
fun MemberScope.findSiblingsByName(): List<DeclarationDescriptor> {
val descriptorKindFilter = when (descriptor) {
is ClassifierDescriptor -> DescriptorKindFilter.CLASSIFIERS
is VariableDescriptor -> DescriptorKindFilter.VARIABLES
is FunctionDescriptor -> DescriptorKindFilter.FUNCTIONS
else -> return emptyList()
}
return getDescriptorsFiltered(descriptorKindFilter) { it.asString() == newName }.filter { it != descriptor }
}
fun getSiblingsWithNewName(): List<DeclarationDescriptor> {
val containingDescriptor = descriptor.containingDeclaration
if (descriptor is ValueParameterDescriptor) {
return (containingDescriptor as CallableDescriptor).valueParameters.filter { it.name.asString() == newName }
}
if (descriptor is TypeParameterDescriptor) {
val typeParameters = when (containingDescriptor) {
is ClassDescriptor -> containingDescriptor.declaredTypeParameters
is CallableDescriptor -> containingDescriptor.typeParameters
else -> emptyList()
}
return SmartList<DeclarationDescriptor>().apply {
typeParameters.filterTo(this) { it.name.asString() == newName }
val containingDeclaration = (containingDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() as? KtDeclaration
?: return emptyList()
val dummyVar = KtPsiFactory(containingDeclaration).createProperty("val foo: $newName")
val outerScope = containingDeclaration.getResolutionScope()
val context = dummyVar.analyzeInContext(outerScope, containingDeclaration)
addIfNotNull(context[BindingContext.VARIABLE, dummyVar]?.type?.constructor?.declarationDescriptor)
}
}
return when (containingDescriptor) {
is ClassDescriptor -> containingDescriptor.unsubstitutedMemberScope.findSiblingsByName()
is PackageFragmentDescriptor -> containingDescriptor.getMemberScope().findSiblingsByName().filter {
it != descriptor && (!(descriptor.isTopLevelPrivate() || it.isTopLevelPrivate()) || isInSameFile(descriptor, it))
}
else -> {
val block =
(descriptor as? DeclarationDescriptorWithSource)?.source?.getPsi()?.parent as? KtBlockExpression ?: return emptyList()
block.statements.mapNotNull {
if (it.name != newName) return@mapNotNull null
val isAccepted = when (descriptor) {
is ClassDescriptor -> it is KtClassOrObject
is VariableDescriptor -> it is KtProperty
is FunctionDescriptor -> it is KtNamedFunction
else -> false
}
if (!isAccepted) return@mapNotNull null
(it as? KtDeclaration)?.unsafeResolveToDescriptor()
}
}
}
}
val overloadChecker = when (descriptor) {
is PropertyDescriptor,
is FunctionDescriptor,
is ClassifierDescriptor -> {
@OptIn(FrontendInternals::class)
val typeSpecificityComparator = resolutionFacade.getFrontendService(descriptor.module, TypeSpecificityComparator::class.java)
OverloadChecker(typeSpecificityComparator)
}
else -> null
}
for (candidateDescriptor in getSiblingsWithNewName()) {
val candidate = (candidateDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() as? KtNamedDeclaration ?: continue
if (overloadChecker != null && overloadChecker.isOverloadable(descriptor, candidateDescriptor)) continue
val what = candidate.renderDescription()
val where = candidate.representativeContainer()?.renderDescription() ?: continue
val message = KotlinBundle.message("text.0.already.declared.in.1", what, where).capitalize()
result += BasicUnresolvableCollisionUsageInfo(candidate, candidate, message)
}
}
private fun LexicalScope.getRelevantDescriptors(
declaration: PsiNamedElement,
name: String
): Collection<DeclarationDescriptor> {
val nameAsName = Name.identifier(name)
return when (declaration) {
is KtProperty, is KtParameter, is PsiField -> getAllAccessibleVariables(nameAsName)
is KtNamedFunction -> getAllAccessibleFunctions(nameAsName)
is KtClassOrObject, is PsiClass -> listOfNotNull(findClassifier(nameAsName, NoLookupLocation.FROM_IDE))
else -> emptyList()
}
}
fun reportShadowing(
declaration: PsiNamedElement,
elementToBindUsageInfoTo: PsiElement,
candidateDescriptor: DeclarationDescriptor,
refElement: PsiElement,
result: MutableList<UsageInfo>
) {
val candidate = DescriptorToSourceUtilsIde.getAnyDeclaration(declaration.project, candidateDescriptor) as? PsiNamedElement ?: return
if (declaration.parent == candidate.parent) return
val message = KotlinBundle.message(
"text.0.will.be.shadowed.by.1",
declaration.renderDescription(),
candidate.renderDescription()
).capitalize()
result += BasicUnresolvableCollisionUsageInfo(refElement, elementToBindUsageInfoTo, message)
}
// todo: break into smaller functions
private fun checkUsagesRetargeting(
elementToBindUsageInfosTo: PsiElement,
declaration: PsiNamedElement,
name: String,
isNewName: Boolean,
accessibleDescriptors: Collection<DeclarationDescriptor>,
originalUsages: MutableList<UsageInfo>,
newUsages: MutableList<UsageInfo>
) {
val usageIterator = originalUsages.listIterator()
while (usageIterator.hasNext()) {
val usage = usageIterator.next()
val refElement = usage.element as? KtSimpleNameExpression ?: continue
val context = refElement.analyze(BodyResolveMode.PARTIAL)
val scope = refElement.parentsWithSelf
.filterIsInstance<KtElement>()
.mapNotNull { context[BindingContext.LEXICAL_SCOPE, it] }
.firstOrNull()
?: continue
if (scope.getRelevantDescriptors(declaration, name).isEmpty()) {
if (declaration !is KtProperty && declaration !is KtParameter) continue
if (Fe10KotlinNewDeclarationNameValidator(refElement.parent, refElement, KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE)(name)) continue
}
val psiFactory = KtPsiFactory(declaration)
val resolvedCall = refElement.getResolvedCall(context)
if (resolvedCall == null) {
val typeReference = refElement.getStrictParentOfType<KtTypeReference>() ?: continue
val referencedClass = context[BindingContext.TYPE, typeReference]?.constructor?.declarationDescriptor ?: continue
val referencedClassFqName = FqName(IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(referencedClass))
val newFqName = if (isNewName) referencedClassFqName.parent().child(Name.identifier(name)) else referencedClassFqName
val fakeVar = psiFactory.createDeclaration<KtProperty>("val __foo__: ${newFqName.asString()}")
val newContext = fakeVar.analyzeInContext(scope, refElement)
val referencedClassInNewContext = newContext[BindingContext.TYPE, fakeVar.typeReference!!]?.constructor?.declarationDescriptor
val candidateText = referencedClassInNewContext?.canonicalRender()
if (referencedClassInNewContext == null
|| ErrorUtils.isError(referencedClassInNewContext)
|| referencedClass.canonicalRender() == candidateText
|| accessibleDescriptors.any { it.canonicalRender() == candidateText }
) {
usageIterator.set(UsageInfoWithFqNameReplacement(refElement, declaration, newFqName))
} else {
reportShadowing(declaration, elementToBindUsageInfosTo, referencedClassInNewContext, refElement, newUsages)
}
continue
}
val callExpression = resolvedCall.call.callElement as? KtExpression ?: continue
val fullCallExpression = callExpression.getQualifiedExpressionForSelectorOrThis()
val qualifiedExpression = if (resolvedCall.noReceivers()) {
val resultingDescriptor = resolvedCall.resultingDescriptor
val fqName = resultingDescriptor.importableFqName
?: (resultingDescriptor as? ClassifierDescriptor)?.let {
FqName(IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(it))
}
?: continue
if (fqName.parent().isRoot) {
callExpression.copied()
} else {
psiFactory.createExpressionByPattern("${fqName.parent().asString()}.$0", callExpression)
}
} else {
resolvedCall.getExplicitReceiverValue()?.let {
fullCallExpression.copied()
} ?: resolvedCall.getImplicitReceiverValue()?.let { implicitReceiver ->
val expectedLabelName = implicitReceiver.declarationDescriptor.getThisLabelName()
val implicitReceivers = scope.getImplicitReceiversHierarchy()
val receiversWithExpectedName = implicitReceivers.filter {
it.value.type.constructor.declarationDescriptor?.getThisLabelName() == expectedLabelName
}
val canQualifyThis = receiversWithExpectedName.isEmpty()
|| receiversWithExpectedName.size == 1 && (declaration !is KtClassOrObject || expectedLabelName != name)
if (canQualifyThis) {
if (refElement.parent is KtCallableReferenceExpression) {
psiFactory.createExpressionByPattern("${implicitReceiver.explicateAsText()}::$0", callExpression)
} else {
psiFactory.createExpressionByPattern("${implicitReceiver.explicateAsText()}.$0", callExpression)
}
} else {
val defaultReceiverClassText =
implicitReceivers.firstOrNull()?.value?.type?.constructor?.declarationDescriptor?.canonicalRender()
val canInsertUnqualifiedThis = accessibleDescriptors.any { it.canonicalRender() == defaultReceiverClassText }
if (canInsertUnqualifiedThis) {
psiFactory.createExpressionByPattern("this.$0", callExpression)
} else {
callExpression.copied()
}
}
}
?: continue
}
val newCallee = if (qualifiedExpression is KtCallableReferenceExpression) {
qualifiedExpression.callableReference
} else {
qualifiedExpression.getQualifiedElementSelector() as? KtSimpleNameExpression ?: continue
}
if (isNewName) {
newCallee.getReferencedNameElement().replace(psiFactory.createNameIdentifier(name))
}
qualifiedExpression.parentSubstitute = fullCallExpression.parent
val newContext = qualifiedExpression.analyzeInContext(scope, refElement, DelegatingBindingTrace(context, ""))
val newResolvedCall = newCallee.getResolvedCall(newContext)
val candidateText = newResolvedCall?.candidateDescriptor?.getImportableDescriptor()?.canonicalRender()
if (newResolvedCall != null
&& !accessibleDescriptors.any { it.canonicalRender() == candidateText }
&& resolvedCall.candidateDescriptor.canonicalRender() != candidateText
) {
reportShadowing(declaration, elementToBindUsageInfosTo, newResolvedCall.candidateDescriptor, refElement, newUsages)
continue
}
if (fullCallExpression !is KtQualifiedExpression) {
usageIterator.set(UsageInfoWithReplacement(fullCallExpression, declaration, qualifiedExpression))
}
}
}
internal fun checkOriginalUsagesRetargeting(
declaration: KtNamedDeclaration,
newName: String,
originalUsages: MutableList<UsageInfo>,
newUsages: MutableList<UsageInfo>
) {
val accessibleDescriptors = declaration.getResolutionScope().getRelevantDescriptors(declaration, newName)
checkUsagesRetargeting(declaration, declaration, newName, true, accessibleDescriptors, originalUsages, newUsages)
}
internal fun checkNewNameUsagesRetargeting(
declaration: KtNamedDeclaration,
newName: String,
newUsages: MutableList<UsageInfo>
) {
val currentName = declaration.name ?: return
val descriptor = declaration.unsafeResolveToDescriptor()
if (declaration is KtParameter && !declaration.hasValOrVar()) {
val ownerFunction = declaration.ownerFunction
val searchScope = (if (ownerFunction is KtPrimaryConstructor) ownerFunction.containingClassOrObject else ownerFunction) ?: return
val usagesByCandidate = LinkedHashMap<PsiElement, MutableList<UsageInfo>>()
searchScope.accept(
object : KtTreeVisitorVoid() {
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
if (expression.getReferencedName() != newName) return
val ref = expression.mainReference
val candidate = ref.resolve() as? PsiNamedElement ?: return
usagesByCandidate.getOrPut(candidate) { SmartList() }.add(MoveRenameUsageInfo(ref, candidate))
}
}
)
for ((candidate, usages) in usagesByCandidate) {
checkUsagesRetargeting(candidate, declaration, currentName, false, listOf(descriptor), usages, newUsages)
usages.filterIsInstanceTo<KtResolvableCollisionUsageInfo, MutableList<UsageInfo>>(newUsages)
}
return
}
val operator = declaration.isOperator()
for (candidateDescriptor in declaration.getResolutionScope().getRelevantDescriptors(declaration, newName)) {
val candidate = DescriptorToSourceUtilsIde.getAnyDeclaration(declaration.project, candidateDescriptor) as? PsiNamedElement
?: continue
val searchParameters = KotlinReferencesSearchParameters(
candidate,
scope = candidate.useScope().restrictToKotlinSources() and declaration.useScope(),
kotlinOptions = KotlinReferencesSearchOptions(searchForOperatorConventions = operator)
)
val usages = ReferencesSearch.search(searchParameters).mapTo(SmartList<UsageInfo>()) { MoveRenameUsageInfo(it, candidate) }
checkUsagesRetargeting(candidate, declaration, currentName, false, listOf(descriptor), usages, newUsages)
usages.filterIsInstanceTo<KtResolvableCollisionUsageInfo, MutableList<UsageInfo>>(newUsages)
}
}
internal fun PsiElement?.isOperator(): Boolean {
if (this !is KtNamedFunction || !KotlinPsiHeuristics.isPossibleOperator(this)) {
return false
}
val resolveWithParents = resolveDeclarationWithParents(this as KtNamedFunction)
return resolveWithParents.overriddenDescriptors.any {
val psi = it.source.getPsi() ?: return@any false
psi !is KtElement || psi.safeAs<KtNamedFunction>()?.hasModifier(KtTokens.OPERATOR_KEYWORD) == true
}
} | apache-2.0 | 421812998851e8b0313ca373d86d0e6a | 50.408416 | 158 | 0.717402 | 5.898324 | false | false | false | false |
hermantai/samples | kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/util/APIConverters.kt | 4 | 7221 | package dev.mfazio.abl.util
import dev.mfazio.abl.api.models.*
import dev.mfazio.abl.players.*
import dev.mfazio.abl.scoreboard.ScheduledGame
import dev.mfazio.abl.scoreboard.ScheduledGameStatus
import dev.mfazio.abl.scoreboard.ScoreboardPlayerInfo
import dev.mfazio.abl.standings.TeamStanding
import dev.mfazio.abl.standings.WinLoss
import dev.mfazio.abl.teams.Division
fun List<TeamStandingApiModel>.convertToTeamStandings(originalStandings: List<TeamStanding>): List<TeamStanding> =
this.map { apiModel ->
val originalStanding =
originalStandings.firstOrNull { original -> original.teamId == apiModel.teamId }
TeamStanding(
apiModel.teamId,
originalStanding?.division ?: Division.Unknown,
apiModel.wins,
apiModel.losses,
apiModel.winsLastTen,
apiModel.streakCount,
apiModel.streakType.toWinLoss(),
apiModel.divisionGamesBack,
apiModel.leagueGamesBack
).apply { this.id = originalStanding?.id ?: 0 }
}
fun WinLossApiModel.toWinLoss() = when (this) {
WinLossApiModel.Win -> WinLoss.Win
WinLossApiModel.Loss -> WinLoss.Loss
else -> WinLoss.Unknown
}
fun List<ScheduledGameApiModel>.convertToScheduledGames(): List<ScheduledGame> =
this.map { apiModel ->
val scoreboardPlayers = apiModel.getScoreboardPlayerInfo()
ScheduledGame(
apiModel.gameId,
apiModel.gameStatus.toScheduledGameStatus(),
apiModel.gameStartTime,
apiModel.inning,
apiModel.isTopOfInning,
apiModel.outs,
apiModel.homeTeam.teamId,
"${apiModel.homeTeam.wins}-${apiModel.homeTeam.losses}",
apiModel.homeTeam.score,
apiModel.awayTeam.teamId,
"${apiModel.awayTeam.wins}-${apiModel.awayTeam.losses}",
apiModel.awayTeam.score,
scoreboardPlayers.getOrNull(0),
scoreboardPlayers.getOrNull(1),
scoreboardPlayers.getOrNull(2)
)
}
fun ScheduledGameStatusApiModel.toScheduledGameStatus() =
when (this) {
ScheduledGameStatusApiModel.Upcoming -> ScheduledGameStatus.Upcoming
ScheduledGameStatusApiModel.InProgress -> ScheduledGameStatus.InProgress
ScheduledGameStatusApiModel.Completed -> ScheduledGameStatus.Completed
else -> ScheduledGameStatus.Unknown
}
fun ScheduledGameApiModel.getScoreboardPlayerInfo(): List<ScoreboardPlayerInfo?> =
when (this.gameStatus) {
ScheduledGameStatusApiModel.Completed -> {
val homeTeamWon = this.homeTeam.score > this.awayTeam.score
listOf(
(if (homeTeamWon) this.homeTeam.pitcherOfRecord else this.awayTeam.pitcherOfRecord)?.convertPitcherToScoreboardPlayerInfo(),
(if (homeTeamWon) this.awayTeam.pitcherOfRecord else this.homeTeam.pitcherOfRecord)?.convertPitcherToScoreboardPlayerInfo(),
(if (homeTeamWon) this.homeTeam.savingPitcher else this.awayTeam.savingPitcher)?.convertCloserToScoreboardPlayerInfo()
)
}
ScheduledGameStatusApiModel.InProgress -> listOf(
(if (this.isTopOfInning) this.homeTeam.currentPitcher else this.awayTeam.currentPitcher)?.convertPitcherToScoreboardPlayerInfo(),
(if (this.isTopOfInning) this.awayTeam.currentBatter else this.homeTeam.currentBatter)?.convertCurrentBatterToScoreboardPlayerInfo()
)
ScheduledGameStatusApiModel.Upcoming -> listOf(
this.awayTeam.startingPitcher?.convertPitcherToScoreboardPlayerInfo(),
this.homeTeam.startingPitcher?.convertPitcherToScoreboardPlayerInfo()
)
else -> emptyList()
}
fun ScheduledGamePitcherApiModel.convertPitcherToScoreboardPlayerInfo() =
ScoreboardPlayerInfo(this.playerName, "${this.wins}-${this.losses}, ${this.era}")
fun ScheduledGamePitcherApiModel.convertCloserToScoreboardPlayerInfo() =
ScoreboardPlayerInfo(this.playerName, this.saves.toString())
fun ScheduledGameBatterApiModel.convertCurrentBatterToScoreboardPlayerInfo() =
ScoreboardPlayerInfo(
this.playerName,
"${this.hitsToday}-${this.atBatsToday}, ${this.battingAverage}"
)
fun PlayerApiModel.convertToPlayer() = Player(
this.playerId,
this.teamId,
this.firstName,
this.lastName,
this.number,
this.bats.toHand(),
this.throws.toHand(),
this.position.toPosition(),
this.boxScoreLastName ?: this.lastName
)
fun List<PlayerApiModel>.convertToPlayers() = this.map(PlayerApiModel::convertToPlayer)
fun HandApiModel.toHand() = when (this) {
HandApiModel.Left -> Hand.Left
HandApiModel.Right -> Hand.Right
else -> Hand.Unknown
}
fun PositionApiModel.toPosition() =
Position.values().firstOrNull { it.shortName == this.shortName } ?: Position.Unknown
fun List<BatterBoxScoreItemApiModel>.convertToBattersAndStats() =
this.associate { apiModel ->
apiModel.convertToBatterAndStats()
}.let { statsMap ->
Pair(statsMap.keys.toList(), statsMap.values.toList())
}
fun BatterBoxScoreItemApiModel.convertToBatterAndStats() =
Player(
this.playerId,
this.teamId,
this.firstName,
this.lastName,
this.number,
this.bats.toHand(),
this.throws.toHand(),
this.position.toPosition(),
this.boxScoreLastName
) to PlayerStats(
this.playerId,
batterStats = BatterStats(
this.games,
this.plateAppearances,
this.atBats,
this.runs,
this.hits,
this.doubles,
this.triples,
this.homeRuns,
this.rbi,
this.strikeouts,
this.baseOnBalls,
this.hitByPitch,
this.stolenBases,
this.caughtStealing,
this.gidp,
this.sacrificeHits,
this.sacrificeFlies,
this.errors,
this.passedBalls
)
)
fun List<PitcherBoxScoreItemApiModel>.convertToPitchersAndStats() =
this.associate { apiModel ->
apiModel.convertToPitcherAndStats()
}.let { statsMap ->
Pair(statsMap.keys.toList(), statsMap.values.toList())
}
fun PitcherBoxScoreItemApiModel.convertToPitcherAndStats() =
Player(
this.playerId,
this.teamId,
this.firstName,
this.lastName,
this.number,
this.bats.toHand(),
this.throws.toHand(),
this.position.toPosition(),
this.boxScoreLastName
) to PlayerStats(
this.playerId,
pitcherStats = PitcherStats(
this.games,
this.gamesStarted,
this.outs,
this.hits,
this.doubles,
this.triples,
this.homeRuns,
this.runs,
this.earnedRuns,
this.baseOnBalls,
this.hitByPitches,
this.strikeouts,
this.errors,
this.wildPitches,
this.battersFaced,
this.wins,
this.losses,
this.saves,
this.blownSaves,
this.holds
)
) | apache-2.0 | 654b70c470abe69590f2c993a60c3424 | 34.058252 | 144 | 0.65171 | 4.65871 | false | false | false | false |
JetBrains/teamcity-nuget-support | nuget-feed/src/jetbrains/buildServer/nuget/feed/server/index/impl/NuGetBuildMetadataProviderImpl.kt | 1 | 8127 | package jetbrains.buildServer.nuget.feed.server.index.impl
import com.intellij.openapi.diagnostic.Logger
import jetbrains.buildServer.nuget.common.FeedConstants
import jetbrains.buildServer.nuget.common.PackageLoadException
import jetbrains.buildServer.nuget.common.index.*
import jetbrains.buildServer.nuget.feedReader.NuGetPackageAttributes
import jetbrains.buildServer.serverSide.SBuild
import jetbrains.buildServer.serverSide.ServerResponsibility
import jetbrains.buildServer.serverSide.artifacts.BuildArtifact
import jetbrains.buildServer.serverSide.artifacts.BuildArtifactsViewMode
import jetbrains.buildServer.serverSide.impl.LogUtil
import jetbrains.buildServer.util.FileUtil
import java.io.File
import java.io.IOException
import java.util.*
class NuGetBuildMetadataProviderImpl(private val myPackageAnalyzer: PackageAnalyzer,
private val myServerResponsibility: ServerResponsibility) : NuGetBuildMetadataProvider {
override fun getPackagesMetadata(build: SBuild): Metadata {
var metadata: Metadata = readBuildMetadata(build)
when (metadata.state) {
MetadataState.IsAbsent -> metadata = Metadata(MetadataState.Synchronized, indexBuildPackages(build))
MetadataState.Unsynchronized -> metadata = Metadata(MetadataState.Unsynchronized, indexBuildPackages(build))
MetadataState.Synchronized -> return metadata
}
if (myServerResponsibility.isResponsibleForBuild(build)) {
try {
writeBuildMetadata(build, metadata)
} catch (e: Throwable) {
LOG.warnAndDebugDetails("Failed to write packages list for build ${LogUtil.describe(build)}", e)
}
}
return metadata
}
private fun indexBuildPackages(build: SBuild): Collection<NuGetPackageData> {
val nugetArtifacts = HashSet<BuildArtifact>()
val artifacts = build.getArtifacts(BuildArtifactsViewMode.VIEW_ALL)
visitArtifacts(artifacts.rootArtifact, nugetArtifacts)
return nugetArtifacts.mapNotNull {
LOG.info("Indexing NuGet package from artifact ${it.relativePath} of build ${LogUtil.describe(build)}")
try {
generateMetadataForPackage(build, it)
} catch (e: PackageLoadException) {
LOG.warnAndDebugDetails("Failed to read NuGet package $it", e)
null
} catch (e: Exception) {
LOG.warnAndDebugDetails("Unexpected error while indexing NuGet package $it", e)
null
}
}
}
private fun writeBuildMetadata(build: SBuild, metadata: Metadata) {
if (metadata.packages.isNotEmpty()) {
val packages = metadata.packages.mapNotNull {
it.metadata[PackageConstants.TEAMCITY_ARTIFACT_RELPATH]?.let { path ->
NuGetPackageData(path, it.metadata)
}
}
//Thread.sleep(20000)
val packageFile = File(build.artifactsDirectory, PackageConstants.PACKAGES_FILE_PATH)
FileUtil.createDir(packageFile.parentFile)
LOG.debug("Writing list of NuGet packages into $packageFile file")
packageFile.outputStream().use {
NuGetPackagesUtil.writePackages(NuGetPackagesList(packages), it)
}
}
}
private fun readBuildMetadata(build: SBuild): Metadata {
val artifacts = build.getArtifacts(BuildArtifactsViewMode.VIEW_ALL)
val tempPackagesArtifact = artifacts.getArtifact(PackageConstants.TEMP_PACKAGES_FILE_PATH)
if (tempPackagesArtifact != null) {
if (myServerResponsibility.isResponsibleForBuild(build)) {
LOG.debug("Renaming temporary packages.json file to reqular one")
deletePackageFile(build)
FileUtil.renameFileNameOnly(File(build.artifactsDirectory, PackageConstants.TEMP_PACKAGES_FILE_PATH), PackageConstants.PACKAGES_LIST_NAME)
}
}
val artifact = artifacts.getArtifact(PackageConstants.PACKAGES_FILE_PATH)
if (artifact != null) {
try {
val metadata = artifact.inputStream.use {
NuGetPackagesUtil
.readPackages(it)
?.let {
list -> list.packages.map {
packageInfo -> NuGetPackageData(packageInfo.key, packageInfo.value )
}
}
?.let { packages ->
Metadata(MetadataState.Synchronized, packages)
}
?: Metadata(MetadataState.Synchronized)
}
val hasAnyUnavailablePackages =
metadata.packages.asSequence()
.map { pack -> pack.metadata[PackageConstants.TEAMCITY_ARTIFACT_RELPATH] }
.filterNotNull()
.filter {
val packageArtifact = artifacts.findArtifact(it)
LOG.debug("Checking artifact by path: '${packageArtifact.relativePath}', isAvailable: ${packageArtifact.isAvailable}, isAccessible: ${packageArtifact.isAccessible}")
!packageArtifact.isAvailable || !packageArtifact.isAccessible
}
.any()
if (hasAnyUnavailablePackages) {
deletePackageFile(build)
return Metadata(MetadataState.Unsynchronized)
}
return metadata
} catch (e: Exception) {
LOG.warnAndDebugDetails("Failed to read NuGet packages list for build ${LogUtil.describe(build)}", e)
}
deletePackageFile(build)
}
return Metadata(MetadataState.IsAbsent)
}
private fun deletePackageFile(build: SBuild) {
if (myServerResponsibility.isResponsibleForBuild(build)) {
FileUtil.delete(File(build.artifactsDirectory, PackageConstants.PACKAGES_FILE_PATH))
}
}
private fun generateMetadataForPackage(build: SBuild, artifact: BuildArtifact): NuGetPackageData {
val metadata = try {
artifact.inputStream.use {
myPackageAnalyzer.analyzePackage(it)
}
} catch (e: IOException) {
throw PackageLoadException("Failed to read build artifact data", e)
}
metadata[NuGetPackageAttributes.PACKAGE_SIZE] = artifact.size.toString()
metadata[PackageConstants.TEAMCITY_ARTIFACT_RELPATH] = artifact.relativePath
metadata[PackageConstants.TEAMCITY_BUILD_TYPE_ID] = build.buildTypeId
try {
artifact.inputStream.use {
metadata[NuGetPackageAttributes.PACKAGE_HASH] = myPackageAnalyzer.getSha512Hash(it)
metadata[NuGetPackageAttributes.PACKAGE_HASH_ALGORITHM] = PackageAnalyzer.SHA512
}
} catch (e: IOException) {
throw PackageLoadException("Failed to calculate package hash", e)
}
val finishDate = build.finishDate
val created = ODataDataFormat.formatDate(finishDate ?: Date())
metadata[NuGetPackageAttributes.CREATED] = created
metadata[NuGetPackageAttributes.LAST_UPDATED] = created
metadata[NuGetPackageAttributes.PUBLISHED] = created
return NuGetPackageData(artifact.relativePath, metadata)
}
private fun visitArtifacts(artifact: BuildArtifact, packages: MutableSet<BuildArtifact>) {
if (!artifact.isDirectory) {
if (FeedConstants.PACKAGE_FILE_NAME_FILTER.accept(artifact.name)) {
packages.add(artifact)
}
return
}
for (children in artifact.children) {
visitArtifacts(children, packages)
}
}
companion object {
private val LOG = Logger.getInstance(NuGetBuildMetadataProviderImpl::class.java.name)
}
}
| apache-2.0 | e8045a6a2c5ad009abdef33e2bda2670 | 42.459893 | 193 | 0.627538 | 5.137168 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.