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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JetBrains/intellij-community | platform/platform-impl/src/com/intellij/openapi/progress/impl/PlatformTaskSupport.kt | 1 | 11163 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.progress.impl
import com.intellij.concurrency.currentThreadContext
import com.intellij.concurrency.resetThreadContext
import com.intellij.ide.IdeEventQueue
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.application.impl.RawSwingDispatcher
import com.intellij.openapi.application.impl.inModalContext
import com.intellij.openapi.application.impl.onEdtInNonAnyModality
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.*
import com.intellij.openapi.progress.util.AbstractProgressIndicatorExBase
import com.intellij.openapi.progress.util.ProgressDialogUI
import com.intellij.openapi.progress.util.ProgressIndicatorBase
import com.intellij.openapi.progress.util.ProgressIndicatorWithDelayedPresentation.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS
import com.intellij.openapi.progress.util.createDialogWrapper
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.impl.DialogWrapperPeerImpl.isHeadlessEnv
import com.intellij.openapi.util.EmptyRunnable
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.NlsContexts.ProgressTitle
import com.intellij.openapi.wm.ex.IdeFrameEx
import com.intellij.openapi.wm.ex.ProgressIndicatorEx
import com.intellij.openapi.wm.ex.StatusBarEx
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.util.awaitCancellation
import com.intellij.util.flow.throttle
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import java.awt.AWTEvent
import java.awt.Component
import java.awt.Container
import java.awt.EventQueue
import javax.swing.SwingUtilities
internal class PlatformTaskSupport : TaskSupport {
override fun taskCancellationNonCancellableInternal(): TaskCancellation.NonCancellable = NonCancellableTaskCancellation
override fun taskCancellationCancellableInternal(): TaskCancellation.Cancellable = defaultCancellable
override fun modalTaskOwner(component: Component): ModalTaskOwner = ComponentModalTaskOwner(component)
override fun modalTaskOwner(project: Project): ModalTaskOwner = ProjectModalTaskOwner(project)
override suspend fun <T> withBackgroundProgressIndicatorInternal(
project: Project,
title: @ProgressTitle String,
cancellation: TaskCancellation,
action: suspend CoroutineScope.() -> T
): T = coroutineScope {
val sink = FlowProgressSink()
val showIndicatorJob = showIndicator(project, taskInfo(title, cancellation), sink.stateFlow)
try {
withContext(sink.asContextElement(), action)
}
finally {
showIndicatorJob.cancel()
}
}
override suspend fun <T> withModalProgressIndicatorInternal(
owner: ModalTaskOwner,
title: @ProgressTitle String,
cancellation: TaskCancellation,
action: suspend CoroutineScope.() -> T,
): T = onEdtInNonAnyModality {
val descriptor = ModalIndicatorDescriptor(owner, title, cancellation)
runBlockingModalInternal(cs = this, descriptor, action)
}
override fun <T> runBlockingModalInternal(
owner: ModalTaskOwner,
title: @ProgressTitle String,
cancellation: TaskCancellation,
action: suspend CoroutineScope.() -> T,
): T = ensureCurrentJobAllowingOrphan {
val descriptor = ModalIndicatorDescriptor(owner, title, cancellation)
val scope = CoroutineScope(currentThreadContext())
runBlockingModalInternal(cs = scope, descriptor, action)
}
private fun <T> runBlockingModalInternal(
cs: CoroutineScope,
descriptor: ModalIndicatorDescriptor,
action: suspend CoroutineScope.() -> T,
): T = resetThreadContext().use {
inModalContext(cs.coroutineContext.job) { newModalityState ->
val deferredDialog = CompletableDeferred<DialogWrapper>()
val mainJob = cs.async(Dispatchers.Default + newModalityState.asContextElement()) {
withModalIndicator(descriptor, deferredDialog, action)
}
mainJob.invokeOnCompletion {
// Unblock `getNextEvent()` in case it's blocked.
SwingUtilities.invokeLater(EmptyRunnable.INSTANCE)
}
IdeEventQueue.getInstance().pumpEventsForHierarchy(
exitCondition = mainJob::isCompleted,
modalComponent = deferredDialog::modalComponent,
)
@OptIn(ExperimentalCoroutinesApi::class)
mainJob.getCompleted()
}
}
}
private fun CoroutineScope.showIndicator(
project: Project,
taskInfo: TaskInfo,
stateFlow: Flow<ProgressState>,
): Job {
return launch(Dispatchers.IO) {
delay(DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS.toLong())
val indicator = coroutineCancellingIndicator([email protected]) // cancel the parent job from UI
indicator.start()
try {
val indicatorAdded = withContext(Dispatchers.EDT) {
showIndicatorInUI(project, taskInfo, indicator)
}
if (indicatorAdded) {
indicator.updateFromSink(stateFlow)
}
}
finally {
indicator.stop()
indicator.finish(taskInfo)
}
}
}
/**
* @return an indicator which cancels the given [job] when it's cancelled
*/
private fun coroutineCancellingIndicator(job: Job): ProgressIndicatorEx {
val indicator = ProgressIndicatorBase()
indicator.addStateDelegate(object : AbstractProgressIndicatorExBase() {
override fun cancel() {
job.cancel()
super.cancel()
}
})
return indicator
}
/**
* Asynchronously updates the indicator [text][ProgressIndicator.setText],
* [text2][ProgressIndicator.setText2], and [fraction][ProgressIndicator.setFraction] from the [stateFlow].
*/
private suspend fun ProgressIndicatorEx.updateFromSink(stateFlow: Flow<ProgressState>): Nothing {
stateFlow.collect { state: ProgressState ->
text = state.text
text2 = state.details
if (state.fraction >= 0.0) {
// first fraction update makes the indicator determinate
isIndeterminate = false
fraction = state.fraction
}
}
error("collect call must be cancelled")
}
private fun showIndicatorInUI(project: Project, taskInfo: TaskInfo, indicator: ProgressIndicatorEx): Boolean {
val frameEx: IdeFrameEx = WindowManagerEx.getInstanceEx().findFrameHelper(project) ?: return false
val statusBar = frameEx.statusBar as? StatusBarEx ?: return false
statusBar.addProgress(indicator, taskInfo)
return true
}
private fun taskInfo(title: @ProgressTitle String, cancellation: TaskCancellation): TaskInfo = object : TaskInfo {
override fun getTitle(): String = title
override fun isCancellable(): Boolean = cancellation is CancellableTaskCancellation
override fun getCancelText(): String? = (cancellation as? CancellableTaskCancellation)?.buttonText
override fun getCancelTooltipText(): String? = (cancellation as? CancellableTaskCancellation)?.tooltipText
}
private suspend fun <T> withModalIndicator(
descriptor: ModalIndicatorDescriptor,
deferredDialog: CompletableDeferred<DialogWrapper>?,
action: suspend CoroutineScope.() -> T,
): T = coroutineScope {
val sink = FlowProgressSink()
val showIndicatorJob = showModalIndicator(descriptor, sink.stateFlow, deferredDialog)
try {
withContext(sink.asContextElement(), action)
}
finally {
showIndicatorJob.cancel()
}
}
private class ModalIndicatorDescriptor(
val owner: ModalTaskOwner,
val title: @ProgressTitle String,
val cancellation: TaskCancellation,
)
@OptIn(IntellijInternalApi::class)
private fun CoroutineScope.showModalIndicator(
descriptor: ModalIndicatorDescriptor,
stateFlow: Flow<ProgressState>,
deferredDialog: CompletableDeferred<DialogWrapper>?,
): Job = launch(Dispatchers.IO) {
if (isHeadlessEnv()) {
return@launch
}
delay(DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS.toLong())
val mainJob = [email protected]
// Use Dispatchers.EDT to avoid showing the dialog on top of another unrelated modal dialog (e.g. MessageDialogBuilder.YesNoCancel)
withContext(Dispatchers.EDT) {
val window = ownerWindow(descriptor.owner)
if (window == null) {
logger<PlatformTaskSupport>().error("Cannot show progress dialog because owner window is not found")
return@withContext
}
val ui = ProgressDialogUI()
ui.initCancellation(descriptor.cancellation) {
mainJob.cancel("button cancel")
}
ui.backgroundButton.isVisible = false
ui.updateTitle(descriptor.title)
launch {
ui.updateFromSink(stateFlow)
}
val dialog = createDialogWrapper(
panel = ui.panel,
window = window,
writeAction = false,
project = (descriptor.owner as? ProjectModalTaskOwner)?.project,
cancelAction = {
if (descriptor.cancellation is CancellableTaskCancellation) {
mainJob.cancel("dialog cancel")
}
},
)
awaitCancellation {
dialog.close(DialogWrapper.OK_EXIT_CODE)
}
// 1. If the dialog is heavy (= spins an inner event loop):
// show() returns after dialog was closed
// => following withContext() will resume with CancellationException
// => don't complete deferredDialog
// 2. If the dialog is glass pane based (= without inner event loop):
// show() returns immediately
// => complete deferredDialog to process component inputs events in processEventQueueConsumingUnrelatedInputEvents
dialog.show()
// 'Light' popup is shown in glass pane,
// glass pane is 'activating' (becomes visible) in 'SwingUtilities.invokeLater' call (see IdeGlassPaneImp.addImpl),
// requesting focus to cancel button until that time has no effect, as it's not showing
// => re-dispatch via 'SwingUtilities.invokeLater'
withContext(RawSwingDispatcher) {
val focusComponent = ui.cancelButton
val previousFocusOwner = SwingUtilities.getWindowAncestor(focusComponent)?.mostRecentFocusOwner
focusComponent.requestFocusInWindow()
if (previousFocusOwner != null) {
awaitCancellation {
previousFocusOwner.requestFocusInWindow()
}
}
deferredDialog?.complete(dialog)
}
}
}
private suspend fun ProgressDialogUI.updateFromSink(stateFlow: Flow<ProgressState>): Nothing {
stateFlow
.throttle(50)
.flowOn(Dispatchers.IO)
.collect {
updateProgress(it)
}
error("collect call must be cancelled")
}
private fun Deferred<DialogWrapper>.modalComponent(): Container? {
if (!isCompleted) {
return null
}
@OptIn(ExperimentalCoroutinesApi::class)
val dialogWrapper = getCompleted()
if (dialogWrapper.isDisposed) {
return null
}
return dialogWrapper.contentPane
}
private fun IdeEventQueue.pumpEventsForHierarchy(
exitCondition: () -> Boolean,
modalComponent: () -> Component?,
) {
assert(EventQueue.isDispatchThread())
while (!exitCondition()) {
val event: AWTEvent = nextEvent
val consumed = IdeEventQueue.consumeUnrelatedEvent(modalComponent(), event)
if (!consumed) {
dispatchEvent(event)
}
}
}
| apache-2.0 | a185bd8a74ca792dfcbf06e1506d11b4 | 35.361564 | 133 | 0.750963 | 4.674623 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/y2021/Day12.kt | 1 | 863 | package com.nibado.projects.advent.y2021
import com.nibado.projects.advent.*
import com.nibado.projects.advent.graph.Graph
object Day12 : Day {
private val graph = resourceLines(2021, 12).map { it.split('-').let { (a, b) -> Cave(a) to Cave(b) } }
.let { Graph<Cave, Int>().addAll(it, 0, true) }
override fun part1() = graph.paths(Cave("start"), Cave("end")) { node, visited ->
node.key.big || visited.getOrDefault(node, 0) < 1 }.size
override fun part2() = graph.paths(Cave("start"), Cave("end")) { node, visited ->
when {
node.key.id == "start" -> false
node.key.big -> true
else -> visited.getOrDefault(node, 0) < if (visited.any { (node, count) -> !node.key.big && count >= 2 }) 1 else 2
} }.size
data class Cave(val id: String, val big: Boolean = id.uppercase() == id)
} | mit | c8995f9f7d5f39e4aa6ac68488b1d8e7 | 40.142857 | 126 | 0.594438 | 3.268939 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/js/src/Dispatchers.kt | 1 | 1529 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlin.coroutines.*
public actual object Dispatchers {
public actual val Default: CoroutineDispatcher = createDefaultDispatcher()
public actual val Main: MainCoroutineDispatcher
get() = injectedMainDispatcher ?: mainDispatcher
public actual val Unconfined: CoroutineDispatcher = kotlinx.coroutines.Unconfined
private val mainDispatcher = JsMainDispatcher(Default, false)
private var injectedMainDispatcher: MainCoroutineDispatcher? = null
@PublishedApi
internal fun injectMain(dispatcher: MainCoroutineDispatcher) {
injectedMainDispatcher = dispatcher
}
@PublishedApi
internal fun resetInjectedMain() {
injectedMainDispatcher = null
}
}
private class JsMainDispatcher(
val delegate: CoroutineDispatcher,
private val invokeImmediately: Boolean
) : MainCoroutineDispatcher() {
override val immediate: MainCoroutineDispatcher =
if (invokeImmediately) this else JsMainDispatcher(delegate, true)
override fun isDispatchNeeded(context: CoroutineContext): Boolean = !invokeImmediately
override fun dispatch(context: CoroutineContext, block: Runnable) = delegate.dispatch(context, block)
override fun dispatchYield(context: CoroutineContext, block: Runnable) = delegate.dispatchYield(context, block)
override fun toString(): String = toStringInternalImpl() ?: delegate.toString()
}
| apache-2.0 | f1ccbf793ab3ebb5db9b2a1eb6a8c137 | 38.205128 | 115 | 0.763898 | 5.346154 | false | false | false | false |
hzsweers/RxLifecycle | rxlifecycle-kotlin/src/main/java/com/trello/rxlifecycle/kotlin/rxlifecycle.kt | 1 | 2149 | /**
* 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.trello.rxlifecycle.kotlin
import android.view.View
import com.trello.rxlifecycle.LifecycleProvider
import com.trello.rxlifecycle.android.RxLifecycleAndroid
import rx.Completable
import rx.Observable
import rx.Single
fun <T, E> Observable<T>.bindToLifecycle(provider: LifecycleProvider<E>): Observable<T>
= this.compose<T>(provider.bindToLifecycle<T>())
fun <T, E> Observable<T>.bindUntilEvent(provider: LifecycleProvider<E>, event: E): Observable<T>
= this.compose<T>(provider.bindUntilEvent(event))
fun <T> Observable<T>.bindToLifecycle(view: View): Observable<T>
= this.compose<T>(RxLifecycleAndroid.bindView(view))
fun <E> Completable.bindToLifecycle(provider: LifecycleProvider<E>): Completable
= this.compose(provider.bindToLifecycle<Completable>().forCompletable())
fun <E> Completable.bindUntilEvent(provider: LifecycleProvider<E>, event: E): Completable
= this.compose(provider.bindUntilEvent<Completable>(event).forCompletable())
fun Completable.bindToLifecycle(view: View): Completable
= this.compose(RxLifecycleAndroid.bindView<Completable>(view).forCompletable())
fun <T, E> Single<T>.bindToLifecycle(provider: LifecycleProvider<E>): Single<T>
= this.compose(provider.bindToLifecycle<T>().forSingle<T>())
fun <T, E> Single<T>.bindUntilEvent(provider: LifecycleProvider<E>, event: E): Single<T>
= this.compose(provider.bindUntilEvent<T>(event).forSingle<T>())
fun <T> Single<T>.bindToLifecycle(view: View): Single<T>
= this.compose(RxLifecycleAndroid.bindView<T>(view).forSingle<T>()) | apache-2.0 | bc0ed8d1a6aa82f918368375068d75c5 | 42.877551 | 96 | 0.74872 | 3.994424 | false | false | false | false |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/text/MatchResult.kt | 2 | 5816 | /*
* Copyright 2010-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 kotlin.text
import kotlin.text.regex.*
/**
* Represents a collection of captured groups in a single match of a regular expression.
*
* This collection has size of `groupCount + 1` where `groupCount` is the count of groups in the regular expression.
* Groups are indexed from 1 to `groupCount` and group with the index 0 corresponds to the entire match.
*
* An element of the collection at the particular index can be `null`,
* if the corresponding group in the regular expression is optional and
* there was no match captured by that group.
*/
// TODO: Add MatchGroup
interface MatchGroupCollection : Collection<MatchGroup?> {
/** Returns a group with the specified [index].
*
* @return An instance of [MatchGroup] if the group with the specified [index] was matched or `null` otherwise.
*
* Groups are indexed from 1 to the count of groups in the regular expression. A group with the index 0
* corresponds to the entire match.
*/
operator fun get(index: Int): MatchGroup?
}
/**
* Extends [MatchGroupCollection] by introducing a way to get matched groups by name, when regex supports it.
*/
@SinceKotlin("1.1") interface MatchNamedGroupCollection : MatchGroupCollection {
/**
* Returns a named group with the specified [name].
* @return An instance of [MatchGroup] if the group with the specified [name] was matched or `null` otherwise.
*/
operator fun get(name: String): MatchGroup?
}
/**
* Represents the results from a single regular expression match.
*/
interface MatchResult {
/** The range of indices in the original string where match was captured. */
val range: IntRange
/** The substring from the input string captured by this match. */
val value: String
/**
* A collection of groups matched by the regular expression.
*
* This collection has size of `groupCount + 1` where `groupCount` is the count of groups in the regular expression.
* Groups are indexed from 1 to `groupCount` and group with the index 0 corresponds to the entire match.
*/
val groups: MatchGroupCollection
/**
* A list of matched indexed group values.
*
* This list has size of `groupCount + 1` where `groupCount` is the count of groups in the regular expression.
* Groups are indexed from 1 to `groupCount` and group with the index 0 corresponds to the entire match.
*
* If the group in the regular expression is optional and there were no match captured by that group,
* corresponding item in [groupValues] is an empty string.
*
* @sample: samples.text.Regexps.matchDestructuringToGroupValues
*/
val groupValues: List<String>
/**
* An instance of [MatchResult.Destructured] wrapper providing components for destructuring assignment of group values.
*
* component1 corresponds to the value of the first group, component2 — of the second, and so on.
*
* @sample: samples.text.Regexps.matchDestructuring
*/
val destructured: Destructured get() = Destructured(this)
/** Returns a new [MatchResult] with the results for the next match, starting at the position
* at which the last match ended (at the character after the last matched character).
*/
fun next(): MatchResult?
/**
* Provides components for destructuring assignment of group values.
*
* [component1] corresponds to the value of the first group, [component2] — of the second, and so on.
*
* If the group in the regular expression is optional and there were no match captured by that group,
* corresponding component value is an empty string.
*
* @sample: samples.text.Regexps.matchDestructuringToGroupValues
*/
class Destructured internal constructor(val match: MatchResult) {
@kotlin.internal.InlineOnly operator inline fun component1(): String = match.groupValues[1]
@kotlin.internal.InlineOnly operator inline fun component2(): String = match.groupValues[2]
@kotlin.internal.InlineOnly operator inline fun component3(): String = match.groupValues[3]
@kotlin.internal.InlineOnly operator inline fun component4(): String = match.groupValues[4]
@kotlin.internal.InlineOnly operator inline fun component5(): String = match.groupValues[5]
@kotlin.internal.InlineOnly operator inline fun component6(): String = match.groupValues[6]
@kotlin.internal.InlineOnly operator inline fun component7(): String = match.groupValues[7]
@kotlin.internal.InlineOnly operator inline fun component8(): String = match.groupValues[8]
@kotlin.internal.InlineOnly operator inline fun component9(): String = match.groupValues[9]
@kotlin.internal.InlineOnly operator inline fun component10(): String = match.groupValues[10]
/**
* Returns destructured group values as a list of strings.
* First value in the returned list corresponds to the value of the first group, and so on.
*
* @sample: samples.text.Regexps.matchDestructuringToGroupValues
*/
fun toList(): List<String> = match.groupValues.subList(1, match.groupValues.size)
}
}
| apache-2.0 | b007f6893ad5ab6574681422a6c179cf | 44.76378 | 123 | 0.707846 | 4.488031 | false | false | false | false |
AndroidX/androidx | room/room-compiler/src/main/kotlin/androidx/room/solver/query/result/MultimapQueryResultAdapter.kt | 3 | 7153 | /*
* 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.room.solver.query.result
import androidx.room.compiler.codegen.CodeLanguage
import androidx.room.compiler.codegen.XClassName
import androidx.room.compiler.codegen.XCodeBlock
import androidx.room.compiler.processing.XType
import androidx.room.ext.CollectionTypeNames
import androidx.room.ext.CommonTypeNames
import androidx.room.ext.implementsEqualsAndHashcode
import androidx.room.parser.ParsedQuery
import androidx.room.processor.Context
import androidx.room.processor.ProcessorErrors
import androidx.room.processor.ProcessorErrors.AmbiguousColumnLocation.ENTITY
import androidx.room.processor.ProcessorErrors.AmbiguousColumnLocation.MAP_INFO
import androidx.room.processor.ProcessorErrors.AmbiguousColumnLocation.POJO
import androidx.room.solver.types.CursorValueReader
import androidx.room.vo.ColumnIndexVar
import androidx.room.vo.MapInfo
import androidx.room.vo.Warning
/**
* Abstract class for Map and Multimap result adapters.
*/
abstract class MultimapQueryResultAdapter(
context: Context,
parsedQuery: ParsedQuery,
rowAdapters: List<RowAdapter>,
) : QueryResultAdapter(rowAdapters) {
abstract val keyTypeArg: XType
abstract val valueTypeArg: XType
// List of duplicate columns in the query result. Note that if the query result info is not
// available then we use the adapter mappings to determine if there are duplicate columns.
// The latter approach might yield false positive (i.e. two POJOs that want the same column)
// but the resolver will still produce correct results based on the result columns at runtime.
val duplicateColumns: Set<String>
init {
val resultColumns =
parsedQuery.resultInfo?.columns?.map { it.name } ?: mappings.flatMap { it.usedColumns }
duplicateColumns = buildSet {
val visitedColumns = mutableSetOf<String>()
resultColumns.forEach {
// When Set.add() returns false the column is already visited and therefore a dupe.
if (!visitedColumns.add(it)) {
add(it)
}
}
}
if (parsedQuery.resultInfo != null && duplicateColumns.isNotEmpty()) {
// If there are duplicate columns and one of the result object is for a single column
// then we should warn the user to disambiguate in the query projections since the
// current AmbiguousColumnResolver will choose the first matching column. Only show
// this warning if the query has been analyzed or else we risk false positives.
mappings.filter {
it.usedColumns.size == 1 && duplicateColumns.contains(it.usedColumns.first())
}.forEach {
val ambiguousColumnName = it.usedColumns.first()
val (location, objectTypeName) = when (it) {
is SingleNamedColumnRowAdapter.SingleNamedColumnRowMapping ->
MAP_INFO to null
is PojoRowAdapter.PojoMapping ->
POJO to it.pojo.typeName
is EntityRowAdapter.EntityMapping ->
ENTITY to it.entity.typeName
else -> error("Unknown mapping type: $it")
}
context.logger.w(
Warning.AMBIGUOUS_COLUMN_IN_RESULT,
ProcessorErrors.ambiguousColumn(
columnName = ambiguousColumnName,
location = location,
typeName = objectTypeName?.toString(context.codeLanguage)
)
)
}
}
}
enum class MapType(val className: XClassName) {
DEFAULT(CommonTypeNames.MUTABLE_MAP),
ARRAY_MAP(CollectionTypeNames.ARRAY_MAP),
LONG_SPARSE(CollectionTypeNames.LONG_SPARSE_ARRAY),
INT_SPARSE(CollectionTypeNames.INT_SPARSE_ARRAY);
companion object {
fun MapType.isSparseArray() = this == LONG_SPARSE || this == INT_SPARSE
}
}
enum class CollectionValueType(val className: XClassName) {
LIST(CommonTypeNames.MUTABLE_LIST),
SET(CommonTypeNames.MUTABLE_SET)
}
companion object {
/**
* Checks if the @MapInfo annotation is needed for clarification regarding the return type
* of a Dao method.
*/
fun validateMapTypeArgs(
context: Context,
keyTypeArg: XType,
valueTypeArg: XType,
keyReader: CursorValueReader?,
valueReader: CursorValueReader?,
mapInfo: MapInfo?,
) {
if (!keyTypeArg.implementsEqualsAndHashcode()) {
context.logger.w(
Warning.DOES_NOT_IMPLEMENT_EQUALS_HASHCODE,
ProcessorErrors.classMustImplementEqualsAndHashCode(
keyTypeArg.asTypeName().toString(context.codeLanguage)
)
)
}
val hasKeyColumnName = mapInfo?.keyColumnName?.isNotEmpty() ?: false
if (!hasKeyColumnName && keyReader != null) {
context.logger.e(
ProcessorErrors.keyMayNeedMapInfo(
keyTypeArg.asTypeName().toString(context.codeLanguage)
)
)
}
val hasValueColumnName = mapInfo?.valueColumnName?.isNotEmpty() ?: false
if (!hasValueColumnName && valueReader != null) {
context.logger.e(
ProcessorErrors.valueMayNeedMapInfo(
valueTypeArg.asTypeName().toString(context.codeLanguage)
)
)
}
}
}
/**
* Generates a code expression that verifies if all matched fields are null.
*/
fun getColumnNullCheckCode(
language: CodeLanguage,
cursorVarName: String,
indexVars: List<ColumnIndexVar>
) = XCodeBlock.builder(language).apply {
val space = when (language) {
CodeLanguage.JAVA -> "%W"
CodeLanguage.KOTLIN -> " "
}
val conditions = indexVars.map {
XCodeBlock.of(
language,
"%L.isNull(%L)",
cursorVarName,
it.indexVar
)
}
val placeholders = conditions.joinToString(separator = "$space&&$space") { "%L" }
add(placeholders, *conditions.toTypedArray())
}.build()
}
| apache-2.0 | eebc5d6b49570f882d8a50312bb2fcd7 | 38.738889 | 99 | 0.622256 | 5.105639 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dump/paths/indexedFilePaths.kt | 10 | 3097 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing.diagnostic.dump.paths
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.impl.FilePropertyPusher
import com.intellij.openapi.util.io.FileTooBigException
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Base64
import com.intellij.util.indexing.FileBasedIndex
import com.intellij.util.indexing.FileContentImpl
import com.intellij.util.indexing.IndexedHashesSupport
import com.intellij.util.indexing.SubstitutedFileType
object IndexedFilePaths {
const val TOO_LARGE_FILE = "<TOO LARGE>"
const val FAILED_TO_LOAD = "<FAILED TO LOAD: %s>"
fun createIndexedFilePath(fileOrDir: VirtualFile, project: Project): IndexedFilePath {
val fileId = FileBasedIndex.getFileId(fileOrDir)
val fileUrl = fileOrDir.url
val fileType = if (fileOrDir.isDirectory) null else fileOrDir.fileType.name
val substitutedFileType = if (fileOrDir.isDirectory) {
null
}
else {
runReadAction {
SubstitutedFileType.substituteFileType(fileOrDir, fileOrDir.fileType, project).name.takeIf { it != fileType }
}
}
val (contentHash, indexedHash) = try {
val fileContent = FileContentImpl.createByFile(fileOrDir) as FileContentImpl
runReadAction {
val contentHash = IndexedHashesSupport.getBinaryContentHash(fileContent.content)
val indexedHash = IndexedHashesSupport.calculateIndexedHash(fileContent, contentHash)
Base64.encode(contentHash) to Base64.encode(indexedHash)
}
}
catch (e: FileTooBigException) {
TOO_LARGE_FILE to TOO_LARGE_FILE
}
catch (e: Throwable) {
val msg = FAILED_TO_LOAD.format(e.message)
msg to msg
}
val fileSize = if (fileOrDir.isDirectory) null else fileOrDir.length
val portableFilePath = PortableFilePaths.getPortableFilePath(fileOrDir, project)
val allPusherValues = dumpFilePropertyPusherValues(fileOrDir, project).mapValues { it.value?.toString() ?: "<null-value>" }
return IndexedFilePath(
fileId,
fileType,
substitutedFileType,
fileSize,
fileUrl,
portableFilePath,
allPusherValues,
indexedHash,
contentHash
)
}
private fun dumpFilePropertyPusherValues(file: VirtualFile, project: Project): Map<String, Any?> {
val map = hashMapOf<String, Any?>()
FilePropertyPusher.EP_NAME.forEachExtensionSafe { pusher ->
if (file.isDirectory && pusher.acceptsDirectory(file, project)
|| !file.isDirectory && pusher.acceptsFile(file, project)
) {
map[pusher.pusherName] = pusher.getImmediateValue(project, file)
}
}
return map
}
private val FilePropertyPusher<*>.pusherName: String
get() = javaClass.name
.removePrefix("com.")
.removePrefix("intellij.")
.removePrefix("jetbrains.")
.replace("util.", "")
.replace("impl.", "")
} | apache-2.0 | 6faf5d3289044eb12c03be1ca043e80f | 35.880952 | 140 | 0.719406 | 4.325419 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt | 1 | 23281 | package info.nightscout.androidaps.queue
import android.content.Context
import android.content.Intent
import android.os.SystemClock
import android.text.Spanned
import androidx.appcompat.app.AppCompatActivity
import dagger.Lazy
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.BolusProgressHelperActivity
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.dialogs.BolusProgressDialog
import info.nightscout.androidaps.events.EventBolusRequested
import info.nightscout.androidaps.events.EventNewBasalProfile
import info.nightscout.androidaps.events.EventProfileNeedsUpdate
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker
import info.nightscout.androidaps.queue.commands.CustomCommand
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.queue.commands.*
import info.nightscout.androidaps.queue.commands.Command.CommandType
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.buildHelper.BuildHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by mike on 08.11.2017.
*
*
* DATA FLOW:
* ---------
*
*
* (request) - > ConfigBuilder.getCommandQueue().bolus(...)
*
*
* app no longer waits for result but passes Callback
*
*
* request is added to queue, if another request of the same type already exists in queue, it's removed prior adding
* but if request of the same type is currently executed (probably important only for bolus which is running long time), new request is declined
* new QueueThread is created and started if current if finished
* CommandReadStatus is added automatically before command if queue is empty
*
*
* biggest change is we don't need exec pump commands in Handler because it's finished immediately
* command queueing if not realized by stacking in different Handlers and threads anymore but by internal queue with better control
*
*
* QueueThread calls ConfigBuilder#connect which is passed to getActivePump().connect
* connect should be executed on background and return immediately. afterwards isConnecting() is expected to be true
*
*
* while isConnecting() == true GUI is updated by posting connection progress
*
*
* if connect is successful: isConnected() becomes true, isConnecting() becomes false
* CommandQueue starts calling execute() of commands. execute() is expected to be blocking (return after finish).
* callback with result is called after finish automatically
* if connect failed: isConnected() becomes false, isConnecting() becomes false
* connect() is called again
*
*
* when queue is empty, disconnect is called
*/
@Singleton
class CommandQueue @Inject constructor(
private val injector: HasAndroidInjector,
val aapsLogger: AAPSLogger,
val rxBus: RxBusWrapper,
val resourceHelper: ResourceHelper,
val constraintChecker: ConstraintChecker,
val profileFunction: ProfileFunction,
val activePlugin: Lazy<ActivePluginProvider>,
val context: Context,
val sp: SP,
private val buildHelper: BuildHelper,
val fabricPrivacy: FabricPrivacy
) : CommandQueueProvider {
private val disposable = CompositeDisposable()
private val queue = LinkedList<Command>()
private var thread: QueueThread? = null
var performing: Command? = null
init {
disposable.add(rxBus
.toObservable(EventProfileNeedsUpdate::class.java)
.observeOn(Schedulers.io())
.subscribe({
aapsLogger.debug(LTag.PROFILE, "onProfileSwitch")
profileFunction.getProfile()?.let {
setProfile(it, object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(context, ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.boluserror)
i.putExtra("status", result.comment)
i.putExtra("title", resourceHelper.gs(R.string.failedupdatebasalprofile))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
}
if (result.enacted) rxBus.send(EventNewBasalProfile())
}
})
}
}) { exception: Throwable -> fabricPrivacy.logException(exception) }
)
}
private fun executingNowError(): PumpEnactResult =
PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.executingrightnow))
override fun isRunning(type: CommandType): Boolean = performing?.commandType == type
@Synchronized
private fun removeAll(type: CommandType) {
synchronized(queue) {
for (i in queue.indices.reversed()) {
if (queue[i].commandType == type) {
queue.removeAt(i)
}
}
}
}
@Suppress("SameParameterValue")
@Synchronized
private fun isLastScheduled(type: CommandType): Boolean {
synchronized(queue) {
if (queue.size > 0 && queue[queue.size - 1].commandType == type) {
return true
}
}
return false
}
@Synchronized
private fun add(command: Command) {
aapsLogger.debug(LTag.PUMPQUEUE, "Adding: " + command.javaClass.simpleName + " - " + command.status())
synchronized(queue) { queue.add(command) }
}
@Synchronized
override fun pickup() {
synchronized(queue) { performing = queue.poll() }
}
@Synchronized
override fun clear() {
performing = null
synchronized(queue) {
for (i in queue.indices) {
queue[i].cancel()
}
queue.clear()
}
}
override fun size(): Int = queue.size
override fun performing(): Command? = performing
override fun resetPerforming() {
performing = null
}
// After new command added to the queue
// start thread again if not already running
@Synchronized
private fun notifyAboutNewCommand() {
while (thread != null && thread!!.state != Thread.State.TERMINATED && thread!!.waitingForDisconnect) {
aapsLogger.debug(LTag.PUMPQUEUE, "Waiting for previous thread finish")
SystemClock.sleep(500)
}
if (thread == null || thread!!.state == Thread.State.TERMINATED) {
thread = QueueThread(this, context, aapsLogger, rxBus, activePlugin.get(), resourceHelper, sp)
thread!!.start()
aapsLogger.debug(LTag.PUMPQUEUE, "Starting new thread")
} else {
aapsLogger.debug(LTag.PUMPQUEUE, "Thread is already running")
}
}
override fun independentConnect(reason: String, callback: Callback?) {
aapsLogger.debug(LTag.PUMPQUEUE, "Starting new queue")
val tempCommandQueue = CommandQueue(injector, aapsLogger, rxBus, resourceHelper, constraintChecker, profileFunction, activePlugin, context, sp, buildHelper, fabricPrivacy)
tempCommandQueue.readStatus(reason, callback)
}
@Synchronized
override fun bolusInQueue(): Boolean {
if (isRunning(CommandType.BOLUS)) return true
synchronized(queue) {
for (i in queue.indices) {
if (queue[i].commandType == CommandType.BOLUS) {
return true
}
}
}
return false
}
// returns true if command is queued
@Synchronized
override fun bolus(detailedBolusInfo: DetailedBolusInfo, callback: Callback?): Boolean {
var type = if (detailedBolusInfo.isSMB) CommandType.SMB_BOLUS else CommandType.BOLUS
if (type == CommandType.SMB_BOLUS) {
if (isRunning(CommandType.BOLUS) || isRunning(CommandType.SMB_BOLUS) || bolusInQueue()) {
aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting SMB since a bolus is queue/running")
return false
}
if (detailedBolusInfo.lastKnownBolusTime < activePlugin.get().activeTreatments.lastBolusTime) {
aapsLogger.debug(LTag.PUMPQUEUE, "Rejecting bolus, another bolus was issued since request time")
return false
}
removeAll(CommandType.SMB_BOLUS)
}
if (type == CommandType.BOLUS && detailedBolusInfo.carbs > 0 && detailedBolusInfo.insulin == 0.0) {
type = CommandType.CARBS_ONLY_TREATMENT
//Carbs only can be added in parallel as they can be "in the future".
} else {
if (isRunning(type)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished boluses
removeAll(type)
}
// apply constraints
detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(Constraint(detailedBolusInfo.insulin)).value()
detailedBolusInfo.carbs = constraintChecker.applyCarbsConstraints(Constraint(detailedBolusInfo.carbs.toInt())).value().toDouble()
// add new command to queue
if (detailedBolusInfo.isSMB) {
add(CommandSMBBolus(injector, detailedBolusInfo, callback))
} else {
add(CommandBolus(injector, detailedBolusInfo, callback, type))
if (type == CommandType.BOLUS) { // Bring up bolus progress dialog (start here, so the dialog is shown when the bolus is requested,
// not when the Bolus command is starting. The command closes the dialog upon completion).
showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context)
// Notify Wear about upcoming bolus
rxBus.send(EventBolusRequested(detailedBolusInfo.insulin))
}
}
notifyAboutNewCommand()
return true
}
override fun stopPump(callback: Callback?) {
add(CommandStopPump(injector, callback))
notifyAboutNewCommand()
}
override fun startPump(callback: Callback?) {
add(CommandStartPump(injector, callback))
notifyAboutNewCommand()
}
override fun setTBROverNotification(callback: Callback?, enable: Boolean) {
add(CommandInsightSetTBROverNotification(injector, enable, callback))
notifyAboutNewCommand()
}
@Synchronized
override fun cancelAllBoluses() {
if (!isRunning(CommandType.BOLUS)) {
rxBus.send(EventDismissBolusProgressIfRunning(PumpEnactResult(injector).success(true).enacted(false)))
}
removeAll(CommandType.BOLUS)
removeAll(CommandType.SMB_BOLUS)
Thread(Runnable { activePlugin.get().activePump.stopBolusDelivering() }).run()
}
// returns true if command is queued
override fun tempBasalAbsolute(absoluteRate: Double, durationInMinutes: Int, enforceNew: Boolean, profile: Profile, callback: Callback?): Boolean {
if (!enforceNew && isRunning(CommandType.TEMPBASAL)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAll(CommandType.TEMPBASAL)
val rateAfterConstraints = constraintChecker.applyBasalConstraints(Constraint(absoluteRate), profile).value()
// add new command to queue
add(CommandTempBasalAbsolute(injector, rateAfterConstraints, durationInMinutes, enforceNew, profile, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun tempBasalPercent(percent: Int, durationInMinutes: Int, enforceNew: Boolean, profile: Profile, callback: Callback?): Boolean {
if (!enforceNew && isRunning(CommandType.TEMPBASAL)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAll(CommandType.TEMPBASAL)
val percentAfterConstraints = constraintChecker.applyBasalPercentConstraints(Constraint(percent), profile).value()
// add new command to queue
add(CommandTempBasalPercent(injector, percentAfterConstraints, durationInMinutes, enforceNew, profile, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun extendedBolus(insulin: Double, durationInMinutes: Int, callback: Callback?): Boolean {
if (isRunning(CommandType.EXTENDEDBOLUS)) {
callback?.result(executingNowError())?.run()
return false
}
val rateAfterConstraints = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value()
// remove all unfinished
removeAll(CommandType.EXTENDEDBOLUS)
// add new command to queue
add(CommandExtendedBolus(injector, rateAfterConstraints, durationInMinutes, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun cancelTempBasal(enforceNew: Boolean, callback: Callback?): Boolean {
if (!enforceNew && isRunning(CommandType.TEMPBASAL)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAll(CommandType.TEMPBASAL)
// add new command to queue
add(CommandCancelTempBasal(injector, enforceNew, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun cancelExtended(callback: Callback?): Boolean {
if (isRunning(CommandType.EXTENDEDBOLUS)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAll(CommandType.EXTENDEDBOLUS)
// add new command to queue
add(CommandCancelExtendedBolus(injector, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun setProfile(profile: Profile, callback: Callback?): Boolean {
if (isThisProfileSet(profile)) {
aapsLogger.debug(LTag.PUMPQUEUE, "Correct profile already set")
callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run()
return false
}
/* this is breaking setting of profile at all if not engineering mode
if (!buildHelper.isEngineeringModeOrRelease()) {
val notification = Notification(Notification.NOT_ENG_MODE_OR_RELEASE, resourceHelper.gs(R.string.not_eng_mode_or_release), Notification.URGENT)
rxBus.send(EventNewNotification(notification))
callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.not_eng_mode_or_release)))?.run()
return false
}
*/
// Compare with pump limits
val basalValues = profile.basalValues
for (basalValue in basalValues) {
if (basalValue.value < activePlugin.get().activePump.pumpDescription.basalMinimumRate) {
val notification = Notification(Notification.BASAL_VALUE_BELOW_MINIMUM, resourceHelper.gs(R.string.basalvaluebelowminimum), Notification.URGENT)
rxBus.send(EventNewNotification(notification))
callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.basalvaluebelowminimum)))?.run()
return false
}
}
rxBus.send(EventDismissNotification(Notification.BASAL_VALUE_BELOW_MINIMUM))
// remove all unfinished
removeAll(CommandType.BASAL_PROFILE)
// add new command to queue
add(CommandSetProfile(injector, profile, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun readStatus(reason: String, callback: Callback?): Boolean {
if (isLastScheduled(CommandType.READSTATUS)) {
aapsLogger.debug(LTag.PUMPQUEUE, "READSTATUS $reason ignored as duplicated")
callback?.result(executingNowError())?.run()
return false
}
// add new command to queue
add(CommandReadStatus(injector, reason, callback))
notifyAboutNewCommand()
return true
}
@Synchronized
override fun statusInQueue(): Boolean {
if (isRunning(CommandType.READSTATUS)) return true
synchronized(queue) {
for (i in queue.indices) {
if (queue[i].commandType == CommandType.READSTATUS) {
return true
}
}
}
return false
}
// returns true if command is queued
override fun loadHistory(type: Byte, callback: Callback?): Boolean {
if (isRunning(CommandType.LOAD_HISTORY)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAll(CommandType.LOAD_HISTORY)
// add new command to queue
add(CommandLoadHistory(injector, type, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun setUserOptions(callback: Callback?): Boolean {
if (isRunning(CommandType.SET_USER_SETTINGS)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAll(CommandType.SET_USER_SETTINGS)
// add new command to queue
add(CommandSetUserSettings(injector, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun loadTDDs(callback: Callback?): Boolean {
if (isRunning(CommandType.LOAD_HISTORY)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAll(CommandType.LOAD_HISTORY)
// add new command to queue
add(CommandLoadTDDs(injector, callback))
notifyAboutNewCommand()
return true
}
// returns true if command is queued
override fun loadEvents(callback: Callback?): Boolean {
if (isRunning(CommandType.LOAD_EVENTS)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAll(CommandType.LOAD_EVENTS)
// add new command to queue
add(CommandLoadEvents(injector, callback))
notifyAboutNewCommand()
return true
}
override fun customCommand(customCommand: CustomCommand, callback: Callback?): Boolean {
if (isCustomCommandInQueue(customCommand.javaClass)) {
callback?.result(executingNowError())?.run()
return false
}
// remove all unfinished
removeAllCustomCommands(customCommand.javaClass)
// add new command to queue
add(CommandCustomCommand(injector, customCommand, callback))
notifyAboutNewCommand()
return true
}
@Synchronized
override fun isCustomCommandInQueue(customCommandType: Class<out CustomCommand>): Boolean {
if(isCustomCommandRunning(customCommandType)) {
return true
}
synchronized(queue) {
for (i in queue.indices) {
val command = queue[i]
if (command is CommandCustomCommand && customCommandType.isInstance(command.customCommand)) {
return true
}
}
}
return false
}
override fun isCustomCommandRunning(customCommandType: Class<out CustomCommand>): Boolean {
val performing = this.performing
if (performing is CommandCustomCommand && customCommandType.isInstance(performing.customCommand)) {
return true
}
return false
}
@Synchronized
private fun removeAllCustomCommands(targetType: Class<out CustomCommand>) {
synchronized(queue) {
for (i in queue.indices.reversed()) {
val command = queue[i]
if (command is CustomCommand && targetType.isInstance(command.commandType)) {
queue.removeAt(i)
}
}
}
}
override fun spannedStatus(): Spanned {
var s = ""
var line = 0
val perf = performing
if (perf != null) {
s += "<b>" + perf.status() + "</b>"
line++
}
synchronized(queue) {
for (i in queue.indices) {
if (line != 0) s += "<br>"
s += queue[i].status()
line++
}
}
return HtmlHelper.fromHtml(s)
}
override fun isThisProfileSet(profile: Profile): Boolean {
val activePump = activePlugin.get().activePump
val current = profileFunction.getProfile()
return if (current != null) {
val result = activePump.isThisProfileSet(profile)
if (!result) {
aapsLogger.debug(LTag.PUMPQUEUE, "Current profile: $current")
aapsLogger.debug(LTag.PUMPQUEUE, "New profile: $profile")
}
result
} else true
}
private fun showBolusProgressDialog(insulin: Double, ctx: Context?) {
if (ctx != null) {
val bolusProgressDialog = BolusProgressDialog()
bolusProgressDialog.setInsulin(insulin)
bolusProgressDialog.show((ctx as AppCompatActivity).supportFragmentManager, "BolusProgress")
} else {
val i = Intent()
i.putExtra("insulin", insulin)
i.setClass(context, BolusProgressHelperActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
}
}
} | agpl-3.0 | 85167d898d9c20f512aac32120d6d047 | 39.072289 | 179 | 0.654439 | 5.062187 | false | false | false | false |
Flank/flank | test_runner/src/test/kotlin/ftl/reports/HtmlErrorReportTest.kt | 1 | 2715 | package ftl.reports
import ftl.api.JUnitTest
import ftl.client.junit.parseAllSuitesXml
import ftl.client.junit.parseOneSuiteXml
import ftl.client.xml.JUnitXmlTest
import ftl.domain.junit.merge
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class HtmlErrorReportTest {
@Test
fun `reactJson androidPassXml`() {
val results = parseOneSuiteXml(JUnitXmlTest.androidPassXml).testsuites!!.process()
assertTrue(results.isEmpty())
}
@Test
fun `reactJson androidFailXml`() {
val results: List<HtmlErrorReport.Group> = parseOneSuiteXml(JUnitXmlTest.androidFailXml).testsuites!!.process()
val group = results.first()
assertEquals(1, results.size)
assertEquals("com.example.app.ExampleUiTest#testFails", group.label)
assertEquals(1, group.items.size)
val item = group.items.first()
assertEquals("junit.framework.AssertionFailedError: expected:<true> but was:<false>", item.label)
assertEquals("", item.url)
}
@Test
fun `reactJson androidFailXml merged`() {
// 4 tests - 2 pass, 2 fail. we should have 2 failures in the report
val mergedXml: JUnitTest.Result = parseOneSuiteXml(JUnitXmlTest.androidFailXml)
mergedXml.merge(mergedXml)
assertEquals(4, mergedXml.testsuites?.first()?.testcases?.size)
val results: List<HtmlErrorReport.Group> = mergedXml.testsuites!!.process()
val group = results.first()
assertEquals(1, results.size)
assertEquals("com.example.app.ExampleUiTest#testFails", group.label)
assertEquals(2, group.items.size)
group.items.forEach { item ->
assertEquals("junit.framework.AssertionFailedError: expected:<true> but was:<false>", item.label)
assertEquals("", item.url)
}
}
@Test
fun `reactJson iosPassXml`() {
val results = parseAllSuitesXml(JUnitXmlTest.iosPassXml).testsuites!!.process()
assertTrue(results.isEmpty())
}
@Test
fun `reactJson iosFailXml`() {
val results = parseAllSuitesXml(JUnitXmlTest.iosFailXml).testsuites!!.process()
val group = results.first()
assertEquals(1, results.size)
assertEquals("EarlGreyExampleSwiftTests EarlGreyExampleSwiftTests#testBasicSelectionAndAction()", group.label)
assertEquals(1, group.items.size)
val item = group.items.first()
assertEquals(
"Exception: NoMatchingElementException, failed: caught \"EarlGreyInternalTestInterruptException\", \"Immediately halt execution of testcase\"null",
item.label
)
assertEquals("", item.url)
}
}
| apache-2.0 | 50e0d0d4f5b4ad742cd9b94b56775a11 | 32.9375 | 159 | 0.684346 | 4.248826 | false | true | false | false |
meltwater/rabbit-puppy | src/main/kotlin/com/meltwater/puppy/rest/RestRequestBuilder.kt | 2 | 2223 | package com.meltwater.puppy.rest
import com.google.common.net.UrlEscapers
import org.glassfish.jersey.client.JerseyClientBuilder
import org.glassfish.jersey.client.JerseyInvocation
import org.glassfish.jersey.client.JerseyWebTarget
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature
import org.slf4j.LoggerFactory
import java.util.*
import java.util.Optional.empty
class RestRequestBuilder(var host: String, var auth: Pair<String, String>) {
private val log = LoggerFactory.getLogger(RestRequestBuilder::class.java)
private val client = JerseyClientBuilder.createClient()
private val escaper = UrlEscapers.urlPathSegmentEscaper()
private var authNext: Optional<Pair<String, String>> = empty()
private var headers = HashMap<String, String>()
fun nextWithAuthentication(authUser: String, authPass: String): RestRequestBuilder {
authNext = Optional.of(Pair(authUser, authPass))
return this
}
fun withHeader(header: String, value: String): RestRequestBuilder {
headers.put(header, value)
return this
}
fun request(path: String): JerseyInvocation.Builder {
val url = hostAnd(path)
log.trace("Building request to $url")
return addProperties(client.target(url)).request()
}
fun request(path: String, routeParams: Map<String, String>): JerseyInvocation.Builder {
var p: String = path
for (entry in routeParams.entries) {
p = p.replace("{${entry.key}}", escaper.escape(entry.value))
}
return request(p)
}
fun getAuthUser(): String = auth.first
fun getAuthPass(): String = auth.second
private fun addProperties(target: JerseyWebTarget): JerseyWebTarget {
for (entry in headers.entries) {
target.property(entry.key, entry.value)
}
if (authNext.isPresent) {
target.register(HttpAuthenticationFeature.basic(authNext.get().first, authNext.get().second))
authNext = empty()
} else {
target.register(HttpAuthenticationFeature.basic(auth.first, auth.second))
}
return target
}
private fun hostAnd(path: String): String = host + path
}
| mit | 9a6e06fbdbb8c2c5cb7d193aabd2f995 | 34.285714 | 105 | 0.693207 | 4.202268 | false | false | false | false |
siosio/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesTableModel.kt | 2 | 1318 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.util.ui.ColumnInfo
import com.intellij.util.ui.ListTableModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
internal class PackagesTableModel(
var onlyStable: Boolean,
vararg val columns: ColumnInfo<PackagesTableItem<*>, *>
) : ListTableModel<PackagesTableItem<*>>(*columns) {
override fun getRowCount() = items.size
override fun getColumnCount() = columns.size
override fun getColumnClass(columnIndex: Int): Class<out Any> = columns[columnIndex].javaClass
fun replaceItemMatching(packageModel: PackageModel, itemProducer: (PackagesTableItem<*>) -> PackagesTableItem<*>) {
val newItems = mutableListOf<PackagesTableItem<*>>()
newItems.addAll(items.takeWhile { it.packageModel != packageModel })
if (newItems.size == items.size) {
logDebug("PackagesTableModel#replaceItem()") { "Could not replace with model ${packageModel.identifier}: not found" }
return
}
newItems.add(itemProducer(items[newItems.size]))
newItems.addAll(items.subList(newItems.size, items.size - 1))
items = newItems
}
}
| apache-2.0 | d04762534ef32ba134b46fe3d5ab255a | 46.071429 | 129 | 0.734446 | 4.827839 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/fixers/KotlinMissingIfBranchFixer.kt | 1 | 1958 | // 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.editor.fixers
import com.intellij.lang.SmartEnterProcessorWithFixers
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.editor.KotlinSmartEnterHandler
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtIfExpression
class KotlinMissingIfBranchFixer : SmartEnterProcessorWithFixers.Fixer<KotlinSmartEnterHandler>() {
override fun apply(editor: Editor, processor: KotlinSmartEnterHandler, element: PsiElement) {
if (element !is KtIfExpression) return
val document = editor.document
val elseBranch = element.`else`
val elseKeyword = element.elseKeyword
if (elseKeyword != null) {
if (elseBranch == null || elseBranch !is KtBlockExpression && elseBranch.startLine(document) > elseKeyword.startLine(document)) {
document.insertString(elseKeyword.range.end, "{}")
return
}
}
val thenBranch = element.then
if (thenBranch is KtBlockExpression) return
val rParen = element.rightParenthesis ?: return
var transformingOneLiner = false
if (thenBranch != null && thenBranch.startLine(document) == element.startLine(document)) {
if (element.condition != null) return
transformingOneLiner = true
}
val probablyNextStatementParsedAsThen = elseKeyword == null && elseBranch == null && !transformingOneLiner
if (thenBranch == null || probablyNextStatementParsedAsThen) {
document.insertString(rParen.range.end, "{}")
} else {
document.insertString(rParen.range.end, "{")
document.insertString(thenBranch.range.end + 1, "}")
}
}
}
| apache-2.0 | dbf4017491a70ed7f63ed79a3bc8f5cb | 40.659574 | 158 | 0.690501 | 4.870647 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpConflictsUtils.kt | 1 | 12133 | // 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.pullUp
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.RefactoringBundle
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.getChildrenToAnalyze
import org.jetbrains.kotlin.idea.refactoring.memberInfo.resolveToDescriptorWrapperAware
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.ParameterNameRenderingPolicy
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor
import org.jetbrains.kotlin.util.findCallableMemberBySignature
fun checkConflicts(
project: Project,
sourceClass: KtClassOrObject,
targetClass: PsiNamedElement,
memberInfos: List<KotlinMemberInfo>,
onShowConflicts: () -> Unit = {},
onAccept: () -> Unit
) {
val conflicts = MultiMap<PsiElement, String>()
val pullUpData = KotlinPullUpData(sourceClass,
targetClass,
memberInfos.mapNotNull { it.member })
with(pullUpData) {
for (memberInfo in memberInfos) {
val member = memberInfo.member
val memberDescriptor = member.resolveToDescriptorWrapperAware(resolutionFacade)
checkClashWithSuperDeclaration(member, memberDescriptor, conflicts)
checkAccidentalOverrides(member, memberDescriptor, conflicts)
checkInnerClassToInterface(member, memberDescriptor, conflicts)
checkVisibility(memberInfo, memberDescriptor, conflicts)
}
}
checkVisibilityInAbstractedMembers(memberInfos, pullUpData.resolutionFacade, conflicts)
project.checkConflictsInteractively(conflicts, onShowConflicts, onAccept)
}
internal fun checkVisibilityInAbstractedMembers(
memberInfos: List<KotlinMemberInfo>,
resolutionFacade: ResolutionFacade,
conflicts: MultiMap<PsiElement, String>
) {
val membersToMove = ArrayList<KtNamedDeclaration>()
val membersToAbstract = ArrayList<KtNamedDeclaration>()
for (memberInfo in memberInfos) {
val member = memberInfo.member ?: continue
(if (memberInfo.isToAbstract) membersToAbstract else membersToMove).add(member)
}
for (member in membersToAbstract) {
val memberDescriptor = member.resolveToDescriptorWrapperAware(resolutionFacade)
member.forEachDescendantOfType<KtSimpleNameExpression> {
val target = it.mainReference.resolve() as? KtNamedDeclaration ?: return@forEachDescendantOfType
if (!willBeMoved(target, membersToMove)) return@forEachDescendantOfType
if (target.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
val targetDescriptor = target.resolveToDescriptorWrapperAware(resolutionFacade)
val memberText = memberDescriptor.renderForConflicts()
val targetText = targetDescriptor.renderForConflicts()
val message = KotlinBundle.message("text.0.uses.1.which.will.not.be.accessible.from.subclass", memberText, targetText)
conflicts.putValue(target, message.capitalize())
}
}
}
}
internal fun willBeMoved(element: PsiElement, membersToMove: Collection<KtNamedDeclaration>) =
element.parentsWithSelf.any { it in membersToMove }
internal fun willBeUsedInSourceClass(
member: PsiElement,
sourceClass: KtClassOrObject,
membersToMove: Collection<KtNamedDeclaration>
): Boolean {
return !ReferencesSearch
.search(member, LocalSearchScope(sourceClass), false)
.all { willBeMoved(it.element, membersToMove) }
}
private val CALLABLE_RENDERER = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.withOptions {
parameterNameRenderingPolicy = ParameterNameRenderingPolicy.NONE
modifiers = emptySet()
startFromName = false
}
fun DeclarationDescriptor.renderForConflicts(): String {
return when (this) {
is ClassDescriptor -> "${DescriptorRenderer.getClassifierKindPrefix(this)} " +
IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(this)
is FunctionDescriptor -> KotlinBundle.message("text.function.in.ticks.0", CALLABLE_RENDERER.render(this))
is PropertyDescriptor -> KotlinBundle.message("text.property.in.ticks.0", CALLABLE_RENDERER.render(this))
is PackageFragmentDescriptor -> fqName.asString()
is PackageViewDescriptor -> fqName.asString()
else -> ""
}
}
internal fun KotlinPullUpData.getClashingMemberInTargetClass(memberDescriptor: CallableMemberDescriptor): CallableMemberDescriptor? {
val memberInSuper = memberDescriptor.substitute(sourceToTargetClassSubstitutor) ?: return null
return targetClassDescriptor.findCallableMemberBySignature(memberInSuper as CallableMemberDescriptor)
}
private fun KotlinPullUpData.checkClashWithSuperDeclaration(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
val message = KotlinBundle.message(
"text.class.0.already.contains.member.1",
targetClassDescriptor.renderForConflicts(),
memberDescriptor.renderForConflicts()
)
if (member is KtParameter) {
if (((targetClass as? KtClass)?.primaryConstructorParameters ?: emptyList()).any { it.name == member.name }) {
conflicts.putValue(member, message.capitalize())
}
return
}
if (memberDescriptor !is CallableMemberDescriptor) return
val clashingSuper = getClashingMemberInTargetClass(memberDescriptor) ?: return
if (clashingSuper.modality == Modality.ABSTRACT) return
if (clashingSuper.kind != CallableMemberDescriptor.Kind.DECLARATION) return
conflicts.putValue(member, message.capitalize())
}
private fun PsiClass.isSourceOrTarget(data: KotlinPullUpData): Boolean {
var element = unwrapped
if (element is KtObjectDeclaration && element.isCompanion()) element = element.containingClassOrObject
return element == data.sourceClass || element == data.targetClass
}
private fun KotlinPullUpData.checkAccidentalOverrides(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
if (memberDescriptor is CallableDescriptor && !member.hasModifier(KtTokens.PRIVATE_KEYWORD)) {
val memberDescriptorInTargetClass = memberDescriptor.substitute(sourceToTargetClassSubstitutor)
if (memberDescriptorInTargetClass != null) {
val sequence = HierarchySearchRequest<PsiElement>(targetClass, targetClass.useScope)
.searchInheritors()
.asSequence()
.filterNot { it.isSourceOrTarget(this) }
.mapNotNull { it.unwrapped as? KtClassOrObject }
for (it in sequence) {
val subClassDescriptor = it.resolveToDescriptorWrapperAware(resolutionFacade) as ClassDescriptor
val substitutor = getTypeSubstitutor(
targetClassDescriptor.defaultType,
subClassDescriptor.defaultType
) ?: TypeSubstitutor.EMPTY
val memberDescriptorInSubClass = memberDescriptorInTargetClass.substitute(substitutor) as? CallableMemberDescriptor
val clashingMemberDescriptor = memberDescriptorInSubClass?.let {
subClassDescriptor.findCallableMemberBySignature(it)
} ?: continue
val clashingMember = clashingMemberDescriptor.source.getPsi() ?: continue
val message = KotlinBundle.message(
"text.member.0.in.super.class.will.clash.with.existing.member.of.1",
memberDescriptor.renderForConflicts(),
it.resolveToDescriptorWrapperAware(resolutionFacade).renderForConflicts()
)
conflicts.putValue(clashingMember, message.capitalize())
}
}
}
}
private fun KotlinPullUpData.checkInnerClassToInterface(
member: KtNamedDeclaration,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
if (isInterfaceTarget && memberDescriptor is ClassDescriptor && memberDescriptor.isInner) {
val message = KotlinBundle.message("text.inner.class.0.cannot.be.moved.to.intefrace", memberDescriptor.renderForConflicts())
conflicts.putValue(member, message.capitalize())
}
}
private fun KotlinPullUpData.checkVisibility(
memberInfo: KotlinMemberInfo,
memberDescriptor: DeclarationDescriptor,
conflicts: MultiMap<PsiElement, String>
) {
fun reportConflictIfAny(targetDescriptor: DeclarationDescriptor) {
if (targetDescriptor in memberDescriptors.values) return
val target = (targetDescriptor as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return
if (targetDescriptor is DeclarationDescriptorWithVisibility
&& !DescriptorVisibilities.isVisibleIgnoringReceiver(targetDescriptor, targetClassDescriptor)
) {
val message = RefactoringBundle.message(
"0.uses.1.which.is.not.accessible.from.the.superclass",
memberDescriptor.renderForConflicts(),
targetDescriptor.renderForConflicts()
)
conflicts.putValue(target, message.capitalize())
}
}
val member = memberInfo.member
val childrenToCheck = memberInfo.getChildrenToAnalyze()
if (memberInfo.isToAbstract && member is KtCallableDeclaration) {
if (member.typeReference == null) {
(memberDescriptor as CallableDescriptor).returnType?.let { returnType ->
val typeInTargetClass = sourceToTargetClassSubstitutor.substitute(returnType, Variance.INVARIANT)
val descriptorToCheck = typeInTargetClass?.constructor?.declarationDescriptor as? ClassDescriptor
if (descriptorToCheck != null) {
reportConflictIfAny(descriptorToCheck)
}
}
}
}
childrenToCheck.forEach { children ->
children.accept(
object : KtTreeVisitorVoid() {
override fun visitReferenceExpression(expression: KtReferenceExpression) {
super.visitReferenceExpression(expression)
val context = resolutionFacade.analyze(expression)
expression.references
.flatMap { (it as? KtReference)?.resolveToDescriptors(context) ?: emptyList() }
.forEach(::reportConflictIfAny)
}
}
)
}
}
| apache-2.0 | d535fab95da2c4c64bd99b5a23fc74f2 | 44.441948 | 158 | 0.724718 | 5.50749 | false | false | false | false |
PeteGabriel/Yamda | app/src/main/java/com/dev/moviedb/mvvm/extensions/Context.kt | 1 | 1580 | package com.dev.moviedb.mvvm.extensions
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
/**
* Utility class that provides methods to verify the existence of connectivity.
*
* Yamda 1.0.0
*/
/**
* Get network info.
*
* @return An instance of NetworkInfo
*/
fun Context.getNetworkInfo(): NetworkInfo =
(this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo
/**
* Checks if exists an internet connectivity according with the user preferences.
*
* @return True if was found a valid connection.
*/
fun Context.isConnected(connType: Long): Boolean {
if (connType == ConnectivityManager.TYPE_MOBILE.toLong())
return this.isConnectedToMobile()
return if (connType == ConnectivityManager.TYPE_WIFI.toLong()) this.isConnectedToWifi() else this.isConnected()
}
/**
* Check for any connectivity
*
* @return True if is connected false otherwise.
*/
fun Context.isConnected(): Boolean = this.getNetworkInfo().isConnected
/**
* Check for connectivity to a Wifi network
*
* @return True if is connected to wifi.
*/
fun Context.isConnectedToWifi(): Boolean {
val info = this.getNetworkInfo()
return info.isConnected && info.type == ConnectivityManager.TYPE_WIFI
}
/**
* Check for any connectivity to a mobile network
*
* @return True if is connected to a mobile data connection.
*/
fun Context.isConnectedToMobile(): Boolean {
val info = this.getNetworkInfo()
return info.isConnected && info.type == ConnectivityManager.TYPE_MOBILE
}
| gpl-3.0 | 545e51a6b222bef7c01f85f9e7b5c5b4 | 25.333333 | 115 | 0.736076 | 4.247312 | false | false | false | false |
jwren/intellij-community | plugins/evaluation-plugin/src/com/intellij/cce/evaluation/step/SetupStatsCollectorStep.kt | 1 | 7013 | package com.intellij.cce.evaluation.step
import com.intellij.cce.evaluation.features.CCEContextFeatureProvider
import com.intellij.cce.evaluation.features.CCEElementFeatureProvider
import com.intellij.cce.evaluation.UndoableEvaluationStep
import com.intellij.cce.workspace.EvaluationWorkspace
import com.intellij.codeInsight.completion.ml.ContextFeatureProvider
import com.intellij.codeInsight.completion.ml.ElementFeatureProvider
import com.intellij.completion.ml.experiment.ExperimentInfo
import com.intellij.completion.ml.experiment.ExperimentStatus
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.Language
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.stats.completion.sender.StatisticSender
import com.intellij.stats.completion.storage.FilePathProvider
import com.intellij.stats.completion.storage.UniqueFilesProvider
import java.io.File
import java.nio.file.Paths
import java.util.*
class SetupStatsCollectorStep(private val project: Project,
private val experimentGroup: Int?,
private val logLocationAndTextItem: Boolean,
private val isHeadless: Boolean) : UndoableEvaluationStep {
companion object {
private val LOG = Logger.getInstance(SetupStatsCollectorStep::class.java)
private const val SEND_LOGS_REGISTRY = "completion.stats.send.logs"
private const val STATS_COLLECTOR_ID = "com.intellij.stats.completion"
private const val COLLECT_LOGS_HEADLESS_KEY = "completion.evaluation.headless"
fun statsCollectorLogsDirectory(): String = Paths.get(PathManager.getSystemPath(), "completion-stats-data").toString()
fun deleteLogs() {
val logsDirectory = File(statsCollectorLogsDirectory())
if (logsDirectory.exists()) {
logsDirectory.deleteRecursively()
}
}
fun isStatsCollectorEnabled(): Boolean = PluginManagerCore.getPlugin(PluginId.getId(STATS_COLLECTOR_ID))?.isEnabled ?: false
}
val serviceManager = ApplicationManager.getApplication() as ComponentManagerImpl
val initFileProvider: FilePathProvider? = serviceManager.getService(FilePathProvider::class.java)
val initStatisticSender: StatisticSender? = serviceManager.getService(StatisticSender::class.java)
val initExperimentStatus: ExperimentStatus? = serviceManager.getService(ExperimentStatus::class.java)
private var initSendLogsValue = false
private var initCollectLogsInHeadlessValue = false
private lateinit var elementFeatureProvider: CCEElementFeatureProvider
private lateinit var contextFeatureProvider: CCEContextFeatureProvider
override val name: String = "Setup Stats Collector step"
override val description: String = "Configure plugin Stats Collector if needed"
override fun start(workspace: EvaluationWorkspace): EvaluationWorkspace? {
if (!isStatsCollectorEnabled()) {
println("Stats Collector plugin isn't installed. Install it, if you want to save completion logs or features.")
return null
}
deleteLogs()
val filesProvider = object : UniqueFilesProvider("chunk", PathManager.getSystemPath(), "completion-stats-data", 10) {
override fun cleanupOldFiles() = Unit
}
val statisticSender = object : StatisticSender {
override fun sendStatsData(url: String) = Unit
}
try {
initSendLogsValue = Registry.`is`(SEND_LOGS_REGISTRY)
Registry.get(SEND_LOGS_REGISTRY).setValue(false)
} catch (e: MissingResourceException) {
LOG.warn("No registry for not sending logs", e)
}
if (isHeadless) {
initCollectLogsInHeadlessValue = java.lang.Boolean.getBoolean(COLLECT_LOGS_HEADLESS_KEY)
System.setProperty(COLLECT_LOGS_HEADLESS_KEY, "true")
}
val experimentStatus = object : ExperimentStatus {
// it allows to collect logs from all sessions (need a more explicit solution in stats-collector)
override fun forLanguage(language: Language): ExperimentInfo =
ExperimentInfo(true, version = experimentGroup ?: 0, shouldRank = false, shouldShowArrows = false, shouldCalculateFeatures = true)
// it allows to ignore experiment info during ranking
override fun isDisabled(): Boolean = true
override fun disable() = Unit
}
serviceManager.replaceRegularServiceInstance(FilePathProvider::class.java, filesProvider)
serviceManager.replaceRegularServiceInstance(StatisticSender::class.java, statisticSender)
serviceManager.replaceRegularServiceInstance(ExperimentStatus::class.java, experimentStatus)
LOG.runAndLogException { registerFeatureProvidersIfNeeded() }
return workspace
}
override fun undoStep(): UndoableEvaluationStep.UndoStep {
return object : UndoableEvaluationStep.UndoStep {
override val name: String = "Undo setup Stats Collector step"
override val description: String = "Return default behaviour of Stats Collector plugin"
override fun start(workspace: EvaluationWorkspace): EvaluationWorkspace {
if (initFileProvider != null)
serviceManager.replaceRegularServiceInstance(FilePathProvider::class.java, initFileProvider)
if (initStatisticSender != null)
serviceManager.replaceRegularServiceInstance(StatisticSender::class.java, initStatisticSender)
if (initExperimentStatus != null)
serviceManager.replaceRegularServiceInstance(ExperimentStatus::class.java, initExperimentStatus)
try {
Registry.get(SEND_LOGS_REGISTRY).setValue(initSendLogsValue)
}
catch (e: MissingResourceException) {
LOG.warn("No registry for not sending logs", e)
}
if (isHeadless) {
System.setProperty(COLLECT_LOGS_HEADLESS_KEY, initCollectLogsInHeadlessValue.toString())
}
LOG.runAndLogException { unregisterFeatureProviders() }
return workspace
}
}
}
@Suppress("UnstableApiUsage")
private fun registerFeatureProvidersIfNeeded() {
contextFeatureProvider = CCEContextFeatureProvider(logLocationAndTextItem)
ContextFeatureProvider.EP_NAME.addExplicitExtension(Language.ANY, contextFeatureProvider)
if (!logLocationAndTextItem) return
elementFeatureProvider = CCEElementFeatureProvider()
ElementFeatureProvider.EP_NAME.addExplicitExtension(Language.ANY, elementFeatureProvider)
}
@Suppress("UnstableApiUsage")
private fun unregisterFeatureProviders() {
ContextFeatureProvider.EP_NAME.removeExplicitExtension(Language.ANY, contextFeatureProvider)
if (!logLocationAndTextItem) return
ElementFeatureProvider.EP_NAME.removeExplicitExtension(Language.ANY, elementFeatureProvider)
}
} | apache-2.0 | eb1d468800ca5943a959170a19149586 | 48.744681 | 138 | 0.769286 | 4.956184 | false | false | false | false |
allotria/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/configuration/ui/PackageSearchGeneralConfigurable.kt | 1 | 3958 | package com.jetbrains.packagesearch.intellij.plugin.configuration.ui
import com.intellij.openapi.options.SearchableConfigurable
import com.intellij.openapi.project.Project
import com.intellij.ui.RelativeFont
import com.intellij.ui.TitledSeparator
import com.intellij.ui.components.ActionLink
import com.intellij.util.ui.FormBuilder
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ConfigurableContributor
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.event.ChangeListener
class PackageSearchGeneralConfigurable(project: Project) : SearchableConfigurable {
companion object {
const val ID = "preferences.packagesearch.PackageSearchGeneralConfigurable"
}
override fun getId(): String = ID
override fun getDisplayName(): String = PackageSearchBundle.message("packagesearch.configuration.title")
private val extensions = ConfigurableContributor.extensionsForProject(project)
.sortedBy { it.javaClass.simpleName }
.map { it.createDriver() }
private var modified: Boolean = false
private val configuration = PackageSearchGeneralConfiguration.getInstance(project)
private val checkboxFieldChangeListener = ChangeListener { modified = true }
private val builder = FormBuilder.createFormBuilder()
private val refreshProjectEditor =
JCheckBox(PackageSearchBundle.message("packagesearch.configuration.refresh.project"))
.apply {
addChangeListener(checkboxFieldChangeListener)
}
private val allowCheckForPackageUpgradesEditor =
JCheckBox(PackageSearchBundle.message("packagesearch.configuration.allow.check.upgrades"))
.apply {
addChangeListener(checkboxFieldChangeListener)
}
override fun createComponent(): JComponent? {
// Extensions
extensions.forEach {
it.contributeUserInterface(builder)
}
// General options
builder.addComponent(
TitledSeparator(PackageSearchBundle.message("packagesearch.configuration.general")),
0
)
// Refresh project?
builder.addComponent(refreshProjectEditor)
// Allow checking for package upgrades?
builder.addComponent(allowCheckForPackageUpgradesEditor)
builder.addComponent(
RelativeFont.TINY.install(
JLabel(PackageSearchBundle.message("packagesearch.configuration.allow.check.upgrades.extrainfo"))
)
)
// Reset defaults
builder.addComponent(JLabel())
builder.addComponent(ActionLink(PackageSearchBundle.message("packagesearch.configuration.restore.defaults")) {
restoreDefaults()
})
builder.addComponentFillVertically(JPanel(), 0)
return builder.panel
}
override fun isModified() = modified || extensions.any { it.isModified() }
override fun reset() {
extensions.forEach {
it.reset()
}
refreshProjectEditor.isSelected = configuration.refreshProject
allowCheckForPackageUpgradesEditor.isSelected = configuration.allowCheckForPackageUpgrades
modified = false
}
private fun restoreDefaults() {
extensions.forEach {
it.restoreDefaults()
}
refreshProjectEditor.isSelected = true
allowCheckForPackageUpgradesEditor.isSelected = true
modified = true
}
override fun apply() {
extensions.forEach {
it.apply()
}
configuration.refreshProject = refreshProjectEditor.isSelected
configuration.allowCheckForPackageUpgrades = allowCheckForPackageUpgradesEditor.isSelected
}
}
| apache-2.0 | e08ace55174d7d478e733abe6526bb38 | 32.82906 | 118 | 0.716018 | 5.670487 | false | true | false | false |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/SecurityDialog.kt | 1 | 4523 | package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import androidx.biometric.auth.AuthPromptHost
import androidx.fragment.app.FragmentActivity
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.adapters.PasswordTypesAdapter
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.*
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.views.MyDialogViewPager
import kotlinx.android.synthetic.main.dialog_security.view.*
class SecurityDialog(
private val activity: Activity,
private val requiredHash: String,
private val showTabIndex: Int,
private val callback: (hash: String, type: Int, success: Boolean) -> Unit
) : HashListener {
private var dialog: AlertDialog? = null
private val view = LayoutInflater.from(activity).inflate(R.layout.dialog_security, null)
private var tabsAdapter: PasswordTypesAdapter
private var viewPager: MyDialogViewPager
init {
view.apply {
viewPager = findViewById(R.id.dialog_tab_view_pager)
viewPager.offscreenPageLimit = 2
tabsAdapter = PasswordTypesAdapter(
context = context,
requiredHash = requiredHash,
hashListener = this@SecurityDialog,
scrollView = dialog_scrollview,
biometricPromptHost = AuthPromptHost(activity as FragmentActivity),
showBiometricIdTab = shouldShowBiometricIdTab(),
showBiometricAuthentication = showTabIndex == PROTECTION_FINGERPRINT && isRPlus()
)
viewPager.adapter = tabsAdapter
viewPager.onPageChangeListener {
dialog_tab_layout.getTabAt(it)?.select()
}
viewPager.onGlobalLayout {
updateTabVisibility()
}
if (showTabIndex == SHOW_ALL_TABS) {
val textColor = context.getProperTextColor()
if (shouldShowBiometricIdTab()) {
val tabTitle = if (isRPlus()) R.string.biometrics else R.string.fingerprint
dialog_tab_layout.addTab(dialog_tab_layout.newTab().setText(tabTitle), PROTECTION_FINGERPRINT)
}
if (activity.baseConfig.isUsingSystemTheme) {
dialog_tab_layout.setBackgroundColor(activity.resources.getColor(R.color.you_dialog_background_color))
} else {
dialog_tab_layout.setBackgroundColor(context.getProperBackgroundColor())
}
dialog_tab_layout.setTabTextColors(textColor, textColor)
dialog_tab_layout.setSelectedTabIndicatorColor(context.getProperPrimaryColor())
dialog_tab_layout.onTabSelectionChanged(tabSelectedAction = {
viewPager.currentItem = when {
it.text.toString().equals(resources.getString(R.string.pattern), true) -> PROTECTION_PATTERN
it.text.toString().equals(resources.getString(R.string.pin), true) -> PROTECTION_PIN
else -> PROTECTION_FINGERPRINT
}
updateTabVisibility()
})
} else {
dialog_tab_layout.beGone()
viewPager.currentItem = showTabIndex
viewPager.allowSwiping = false
}
}
activity.getAlertDialogBuilder()
.setOnCancelListener { onCancelFail() }
.setNegativeButton(R.string.cancel) { _, _ -> onCancelFail() }
.apply {
activity.setupDialogStuff(view, this) { alertDialog ->
dialog = alertDialog
}
}
}
private fun onCancelFail() {
callback("", 0, false)
dialog?.dismiss()
}
override fun receivedHash(hash: String, type: Int) {
callback(hash, type, true)
if (!activity.isFinishing) {
dialog?.dismiss()
}
}
private fun updateTabVisibility() {
for (i in 0..2) {
tabsAdapter.isTabVisible(i, viewPager.currentItem == i)
}
}
private fun shouldShowBiometricIdTab(): Boolean {
return if (isRPlus()) {
activity.isBiometricIdAvailable()
} else {
activity.isFingerPrintSensorAvailable()
}
}
}
| gpl-3.0 | f6f689a4e0731f831fdd3c9e9e2184d2 | 38.330435 | 122 | 0.619279 | 5.198851 | false | false | false | false |
androidx/androidx | metrics/metrics-performance/src/main/java/androidx/metrics/performance/JankStats.kt | 3 | 9186 | /*
* 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.metrics.performance
import android.os.Build
import android.view.View
import android.view.Window
import androidx.annotation.RestrictTo
import androidx.annotation.UiThread
import java.lang.IllegalStateException
/**
* This class is used to both accumulate and report information about UI "jank" (runtime
* performance problems) in an application.
*
* There are three major components at work in JankStats:
*
* **Identifying Jank**: This library uses internal heuristics to determine when
* jank has occurred, and uses that information to know when to issue jank reports so
* that developers have information on those problems to help analyze and fix the issues.
*
* **Providing UI Context**: To make the jank reports more useful and actionable,
* the system provides a mechanism to help track the current state of the UI and user.
* This information is provided whenever reports are logged, so that developers can
* understand not only when problems occurred, but what the user was doing at the time,
* to help identify problem areas in the application that can then be addressed. Some
* of this state is provided automatically, and internally, by various AndroidX libraries.
* But developers are encouraged to provide their own app-specific state as well. See
* [PerformanceMetricsState] for more information on logging this state information.
*
* **Reporting Results**: On every frame, the JankStats client is notified via a listener
* with information about that frame, including how long the frame took to
* complete, whether it was considered jank, and what the UI context was during that frame.
* Clients are encouraged to aggregate and upload the data as they see fit for analysis that
* can help debug overall performance problems.
*
* Note that the behavior of JankStats varies according to API level, because it is dependent
* upon underlying capabilities in the platform to determine frame timing information.
* Below API level 16, JankStats does nothing, because there is no way to derive dependable
* frame timing data. Starting at API level 16, JankStats uses rough frame timing information
* that can at least provide estimates of how long frames should have taken, compared to how
* long they actually took. Starting with API level 24, frame durations are more dependable,
* using platform timing APIs that are available in that release. And starting in API level
* 31, there is even more underlying platform information which helps provide more accurate
* timing still. On all of these releases (starting with API level 16), the base functionality
* of JankStats should at least provide useful information about performance problems, along
* with the state of the application during those frames, but the timing data will be necessarily
* more accurate for later releases, as described above.
*/
@Suppress("SingletonConstructor")
class JankStats private constructor(
window: Window,
private val frameListener: OnFrameListener
) {
private val holder: PerformanceMetricsState.Holder
/**
* JankStats uses the platform FrameMetrics API internally when it is available to track frame
* timings. It turns this data into "jank" metrics. Prior to API 24, it uses other mechanisms
* to derive frame durations (not as dependable as FrameMetrics, but better than nothing).
*
* Because of this platform version limitation, most of the functionality of
* JankStats is in the impl class, which is instantiated when necessary
* based on the runtime OS version. The JankStats API is basically a think wrapper around
* the implementations in these classes.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
internal val implementation: JankStatsBaseImpl
init {
val decorView: View? = window.peekDecorView()
if (decorView == null) {
throw IllegalStateException(
"window.peekDecorView() is null: " +
"JankStats can only be created with a Window that has a non-null DecorView"
)
}
holder = PerformanceMetricsState.create(decorView)
implementation =
when {
Build.VERSION.SDK_INT >= 31 -> {
JankStatsApi31Impl(this, decorView, window)
}
Build.VERSION.SDK_INT >= 26 -> {
JankStatsApi26Impl(this, decorView, window)
}
Build.VERSION.SDK_INT >= 24 -> {
JankStatsApi24Impl(this, decorView, window)
}
Build.VERSION.SDK_INT >= 22 -> {
JankStatsApi22Impl(this, decorView)
}
Build.VERSION.SDK_INT >= 16 -> {
JankStatsApi16Impl(this, decorView)
}
else -> {
JankStatsBaseImpl(this)
}
}
implementation.setupFrameTimer(true)
}
/**
* Whether this JankStats instance is enabled for tracking and reporting jank data.
* Enabling tracking causes JankStats to listen to system frame-timing information and
* record data on a per-frame basis that can later be reported to the JankStats listener.
* Tracking is enabled by default at creation time.
*/
var isTrackingEnabled: Boolean = true
/**
* Enabling tracking causes JankStats to listen to system frame-timing information and
* record data on a per-frame basis that can later be reported to the JankStats listener.
* Tracking is enabled by default at creation time.
*/
@UiThread
set(value) {
implementation.setupFrameTimer(value)
field = value
}
/**
* This multiplier is used to determine when frames are exhibiting jank.
*
* The factor is multiplied by the current refresh rate to calculate a frame
* duration beyond which frames are considered, and reported, as having jank.
* For example, an app wishing to ignore smaller-duration jank events should
* increase the multiplier. Setting the value to 0, while not recommended for
* production usage, causes all frames to be regarded as jank, which can be
* used in tests to verify correct instrumentation behavior.
*
* By default, the multiplier is 2.
*/
var jankHeuristicMultiplier: Float = 2.0f
set(value) {
// reset calculated value to force recalculation based on new heuristic
JankStatsBaseImpl.frameDuration = -1
field = value
}
/**
* Called internally (by Impl classes) with the frame data, which is passed onto the client.
*/
internal fun logFrameData(volatileFrameData: FrameData) {
frameListener.onFrame(volatileFrameData)
}
companion object {
/**
* Creates a new JankStats object and starts tracking jank metrics for the given
* window.
* @see isTrackingEnabled
* @throws IllegalStateException `window` must be active, with a non-null DecorView. See
* [Window.peekDecorView].
*/
@JvmStatic
@UiThread
@Suppress("ExecutorRegistration")
fun createAndTrack(window: Window, frameListener: OnFrameListener): JankStats {
return JankStats(window, frameListener)
}
}
/**
* This interface should be implemented to receive per-frame callbacks with jank data.
*
* Internally, the [FrameData] objected passed to [OnFrameListener.onFrame] is
* reused and populated with new data on every frame. This means that listeners
* implementing [OnFrameListener] cannot depend on the data received in that
* structure over time and should consider the [FrameData] object **obsolete when control
* returns from the listener**. Clients wishing to retain data from this call should **copy
* the data elsewhere before returning**.
*/
fun interface OnFrameListener {
/**
* The implementation of this method will be called on every frame when an
* OnFrameListener is set on this JankStats object.
*
* The FrameData object **will be modified internally after returning from the listener**;
* any data that needs to be retained should be copied before returning.
*
* @param volatileFrameData The data for the most recent frame.
*/
fun onFrame(
volatileFrameData: FrameData
)
}
} | apache-2.0 | 6e45a5ae97d76252a8b49d50b74449ed | 44.935 | 98 | 0.687459 | 5.022417 | false | false | false | false |
androidx/androidx | graphics/graphics-core/src/androidTest/java/androidx/graphics/lowlatency/FrontBufferedRendererTestActivity.kt | 3 | 1277 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.graphics.lowlatency
import android.app.Activity
import android.os.Bundle
import android.view.SurfaceView
import android.view.ViewGroup
class FrontBufferedRendererTestActivity : Activity() {
private lateinit var mSurfaceView: SurfaceView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val surfaceView = SurfaceView(this).also { mSurfaceView = it }
setContentView(surfaceView, ViewGroup.LayoutParams(WIDTH, HEIGHT))
}
fun getSurfaceView(): SurfaceView = mSurfaceView
companion object {
const val WIDTH = 100
const val HEIGHT = 100
}
} | apache-2.0 | 89862b6ec799c6eec477836775ad7c1c | 30.95 | 75 | 0.736883 | 4.626812 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/my/MyStoriesRepository.kt | 1 | 2537 | package org.thoughtcrime.securesms.stories.my
import android.content.Context
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.thoughtcrime.securesms.conversation.ConversationMessage
import org.thoughtcrime.securesms.database.DatabaseObserver
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.model.MessageRecord
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.sms.MessageSender
class MyStoriesRepository(context: Context) {
private val context = context.applicationContext
fun resend(story: MessageRecord): Completable {
return Completable.fromAction {
MessageSender.resend(context, story)
}.subscribeOn(Schedulers.io())
}
fun getMyStories(): Observable<List<MyStoriesState.DistributionSet>> {
return Observable.create { emitter ->
fun refresh() {
val storiesMap = mutableMapOf<Recipient, List<MessageRecord>>()
SignalDatabase.mms.getAllOutgoingStories(true, -1).use {
for (messageRecord in it) {
val currentList = storiesMap[messageRecord.recipient] ?: emptyList()
storiesMap[messageRecord.recipient] = (currentList + messageRecord)
}
}
emitter.onNext(storiesMap.toSortedMap(MyStoryBiasComparator()).map { (r, m) -> createDistributionSet(r, m) })
}
val observer = DatabaseObserver.Observer {
refresh()
}
ApplicationDependencies.getDatabaseObserver().registerConversationListObserver(observer)
emitter.setCancellable {
ApplicationDependencies.getDatabaseObserver().unregisterObserver(observer)
}
refresh()
}
}
private fun createDistributionSet(recipient: Recipient, messageRecords: List<MessageRecord>): MyStoriesState.DistributionSet {
return MyStoriesState.DistributionSet(
label = recipient.getDisplayName(context),
stories = messageRecords.map {
ConversationMessage.ConversationMessageFactory.createWithUnresolvedData(context, it)
}
)
}
/**
* Biases "My Story" to the top of the list.
*/
class MyStoryBiasComparator : Comparator<Recipient> {
override fun compare(o1: Recipient, o2: Recipient): Int {
return when {
o1 == o2 -> 0
o1.isMyStory -> -1
o2.isMyStory -> 1
else -> -1
}
}
}
}
| gpl-3.0 | 557666fb3dae42f4d7108d1b77df8f3b | 33.283784 | 128 | 0.72566 | 4.715613 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/repl/KtScratchReplExecutor.kt | 4 | 8964 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.scratch.repl
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.execution.target.TargetProgressIndicator
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.cli.common.repl.replInputAsXml
import org.jetbrains.kotlin.cli.common.repl.replNormalizeLineBreaks
import org.jetbrains.kotlin.cli.common.repl.replRemoveLineBreaksInTheEnd
import org.jetbrains.kotlin.cli.common.repl.replUnescapeLineBreaks
import org.jetbrains.kotlin.console.KotlinConsoleKeeper
import org.jetbrains.kotlin.console.actions.logError
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.scratch.*
import org.jetbrains.kotlin.idea.scratch.output.ScratchOutput
import org.jetbrains.kotlin.idea.scratch.output.ScratchOutputType
import org.w3c.dom.Element
import org.xml.sax.InputSource
import java.io.ByteArrayInputStream
import java.nio.charset.Charset
import javax.xml.parsers.DocumentBuilderFactory
class KtScratchReplExecutor(file: ScratchFile) : SequentialScratchExecutor(file) {
private val history: ReplHistory = ReplHistory()
@Volatile
private var osProcessHandler: OSProcessHandler? = null
override fun startExecution() {
val module = file.module
val (environmentRequest, cmdLine) = KotlinConsoleKeeper.createReplCommandLine(file.project, module)
val environment = environmentRequest.prepareEnvironment(TargetProgressIndicator.EMPTY)
val commandPresentation = cmdLine.getCommandPresentation(environment)
LOG.printDebugMessage("Execute REPL: $commandPresentation")
osProcessHandler = ReplOSProcessHandler(environment.createProcess(cmdLine, EmptyProgressIndicator()), commandPresentation)
osProcessHandler?.startNotify()
}
override fun stopExecution(callback: (() -> Unit)?) {
val processHandler = osProcessHandler
if (processHandler == null) {
callback?.invoke()
return
}
try {
if (callback != null) {
processHandler.addProcessListener(object : ProcessAdapter() {
override fun processTerminated(event: ProcessEvent) {
callback()
}
})
}
sendCommandToProcess(":quit")
} catch (e: Exception) {
errorOccurs(KotlinJvmBundle.message("couldn.t.stop.repl.process"), e, false)
processHandler.destroyProcess()
clearState()
}
}
// There should be some kind of more wise synchronization cause this method is called from non-UI thread (process handler thread)
// and actually there could be side effects in handlers
private fun clearState() {
history.clear()
osProcessHandler = null
handler.onFinish(file)
}
override fun executeStatement(expression: ScratchExpression) {
if (needProcessToStart()) {
startExecution()
}
history.addEntry(expression)
try {
sendCommandToProcess(runReadAction { expression.element.text })
} catch (e: Throwable) {
errorOccurs(KotlinJvmBundle.message("couldn.t.execute.statement.0", expression.element.text), e, true)
}
}
override fun needProcessToStart(): Boolean {
return osProcessHandler == null
}
private fun sendCommandToProcess(command: String) {
LOG.printDebugMessage("Send to REPL: $command")
val processInputOS = osProcessHandler?.processInput ?: return logError(this::class.java, "<p>Broken execute stream</p>")
val charset = osProcessHandler?.charset ?: Charsets.UTF_8
val xmlRes = command.replInputAsXml()
val bytes = ("$xmlRes\n").toByteArray(charset)
processInputOS.write(bytes)
processInputOS.flush()
}
private class ReplHistory {
private var entries = arrayListOf<ScratchExpression>()
private var processedEntriesCount: Int = 0
fun addEntry(entry: ScratchExpression) {
entries.add(entry)
}
fun lastUnprocessedEntry(): ScratchExpression? {
return entries.takeIf { processedEntriesCount < entries.size }?.get(processedEntriesCount)
}
fun lastProcessedEntry(): ScratchExpression? {
if (processedEntriesCount < 1) return null
val lastProcessedEntryIndex = processedEntriesCount - 1
return entries.takeIf { lastProcessedEntryIndex < entries.size }?.get(lastProcessedEntryIndex)
}
fun entryProcessed() {
processedEntriesCount++
}
fun clear() {
entries = arrayListOf()
processedEntriesCount = 0
}
fun isAllProcessed() = entries.size == processedEntriesCount
}
private inner class ReplOSProcessHandler(process: Process, commandLine: String) : OSProcessHandler(process, commandLine) {
private val factory = DocumentBuilderFactory.newInstance()
override fun notifyTextAvailable(text: String, outputType: Key<*>) {
if (text.startsWith("warning: classpath entry points to a non-existent location")) return
when (outputType) {
ProcessOutputTypes.STDOUT -> handleReplMessage(text)
ProcessOutputTypes.STDERR -> errorOccurs(text)
}
}
override fun notifyProcessTerminated(exitCode: Int) {
// Do state cleaning before notification otherwise KtScratchFileEditorWithPreview.dispose
// would try to stop process again (after stop in tests 'stopReplProcess`)
// via `stopExecution` (because handler is not null) with next exception:
//
// Caused by: com.intellij.testFramework.TestLogger$TestLoggerAssertionError: The pipe is being closed
// at com.intellij.testFramework.TestLogger.error(TestLogger.java:40)
// at com.intellij.openapi.diagnostic.Logger.error(Logger.java:170)
// at org.jetbrains.kotlin.idea.scratch.ScratchExecutor.errorOccurs(ScratchExecutor.kt:50)
// at org.jetbrains.kotlin.idea.scratch.repl.KtScratchReplExecutor.stopExecution(KtScratchReplExecutor.kt:61)
// at org.jetbrains.kotlin.idea.scratch.SequentialScratchExecutor.stopExecution$default(ScratchExecutor.kt:90)
clearState()
super.notifyProcessTerminated(exitCode)
}
private fun strToSource(s: String, encoding: Charset = Charsets.UTF_8) = InputSource(ByteArrayInputStream(s.toByteArray(encoding)))
private fun handleReplMessage(text: String) {
if (text.isBlank()) return
val output = try {
factory.newDocumentBuilder().parse(strToSource(text))
} catch (e: Exception) {
return handler.error(file, "Couldn't parse REPL output: $text")
}
val root = output.firstChild as Element
val outputType = root.getAttribute("type")
val content = root.textContent.replUnescapeLineBreaks().replNormalizeLineBreaks().replRemoveLineBreaksInTheEnd()
LOG.printDebugMessage("REPL output: $outputType $content")
if (outputType in setOf("SUCCESS", "COMPILE_ERROR", "INTERNAL_ERROR", "RUNTIME_ERROR", "READLINE_END")) {
history.entryProcessed()
if (history.isAllProcessed()) {
handler.onFinish(file)
}
}
val result = parseReplOutput(content, outputType)
if (result != null) {
val lastExpression = if (outputType == "USER_OUTPUT") {
// success command is printed after user output
history.lastUnprocessedEntry()
} else {
history.lastProcessedEntry()
}
if (lastExpression != null) {
handler.handle(file, lastExpression, result)
}
}
}
private fun parseReplOutput(text: String, outputType: String): ScratchOutput? = when (outputType) {
"USER_OUTPUT" -> ScratchOutput(text, ScratchOutputType.OUTPUT)
"REPL_RESULT" -> ScratchOutput(text, ScratchOutputType.RESULT)
"REPL_INCOMPLETE",
"INTERNAL_ERROR",
"COMPILE_ERROR",
"RUNTIME_ERROR",
-> ScratchOutput(text, ScratchOutputType.ERROR)
else -> null
}
}
}
| apache-2.0 | a951c4aed3f3d3500d5911e3740a2fbf | 40.119266 | 158 | 0.662651 | 5.013423 | false | false | false | false |
GunoH/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffKeys.kt | 7 | 682 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.diff.tools.combined
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.openapi.util.Key
val COMBINED_DIFF_VIEWER = DataKey.create<CombinedDiffViewer>("combined_diff_viewer")
val COMBINED_DIFF_VIEWER_KEY = Key.create<CombinedDiffViewer>("combined_diff_viewer")
val COMBINED_DIFF_MAIN_UI = Key.create<CombinedDiffMainUI>("combined_diff_main_ui")
val COMBINED_DIFF_MODEL = Key.create<CombinedDiffModel>("combined_diff_model")
val COMBINED_DIFF_SCROLL_TO_BLOCK = Key.create<CombinedBlockId>("combined_diff_scroll_to_block")
| apache-2.0 | db11d71e0c3562abde756ce35482e727 | 61 | 120 | 0.802053 | 3.533679 | false | false | false | false |
SDS-Studios/ScoreKeeper | app/src/main/java/io/github/sdsstudios/ScoreKeeper/Sortable.kt | 1 | 1477 | package io.github.sdsstudios.ScoreKeeper
import android.app.Activity
import android.view.Menu
import android.view.MenuItem
import java.util.*
/**
* Created by sethsch1 on 23/01/18.
*/
interface Sortable {
companion object {
const val A_Z = "a_z"
const val Z_A = "z_a"
const val ITEM_ID = 99
fun addMenuItem(activity: Activity, sortable: Sortable, menu: Menu) {
val onItemClickListener = MenuItem.OnMenuItemClickListener {
SortPopupMenu(activity, activity.findViewById(ITEM_ID), sortable).show()
true
}
menu.add(0, ITEM_ID, 0, R.string.action_sort)
.setIcon(R.drawable.ic_sort_white_24dp)
.setOnMenuItemClickListener(onItemClickListener)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS)
}
}
var sortMethod: String
fun invalidate()
fun sort(list: List<SortByString>) {
when (sortMethod) {
A_Z -> sortAtoZ(list)
Z_A -> sortZtoA(list)
}
invalidate()
}
private fun sortAtoZ(list: List<SortByString>) {
Collections.sort(list, { o1, o2 ->
o1.stringToSort.compareTo(o2.stringToSort, ignoreCase = true)
})
}
private fun sortZtoA(list: List<SortByString>) {
Collections.sort(list, { o1, o2 ->
o2.stringToSort.compareTo(o1.stringToSort, ignoreCase = true)
})
}
} | gpl-3.0 | aa9ed462c774b1667a5ea7ce5ee96e43 | 25.392857 | 88 | 0.589709 | 3.938667 | false | false | false | false |
GunoH/intellij-community | plugins/git-features-trainer/src/training/git/lesson/GitCommitLesson.kt | 2 | 14495 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.git.lesson
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsNotificationIdsHolder
import com.intellij.openapi.vcs.changes.ChangeListChange
import com.intellij.openapi.vcs.changes.ChangesViewWorkflowManager
import com.intellij.openapi.vcs.changes.ui.ChangesListView
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.JBOptionButton
import com.intellij.util.DocumentUtil
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.tree.TreeUtil
import com.intellij.vcs.commit.AbstractCommitWorkflowHandler
import com.intellij.vcs.commit.CommitActionsPanel
import com.intellij.vcs.commit.CommitOptionsPanel
import com.intellij.vcs.commit.restoreState
import com.intellij.vcs.log.ui.frame.VcsLogChangesBrowser
import com.intellij.vcs.log.ui.table.VcsLogGraphTable
import git4idea.i18n.GitBundle
import org.assertj.swing.core.MouseButton
import org.assertj.swing.data.TableCell
import org.assertj.swing.fixture.JCheckBoxFixture
import org.assertj.swing.fixture.JTableFixture
import training.dsl.*
import training.git.GitLessonsBundle
import training.git.GitLessonsUtil.highlightSubsequentCommitsInGitLog
import training.git.GitLessonsUtil.openCommitWindowText
import training.git.GitLessonsUtil.resetGitLogWindow
import training.git.GitLessonsUtil.restoreCommitWindowStateInformer
import training.git.GitLessonsUtil.showWarningIfCommitWindowClosed
import training.git.GitLessonsUtil.showWarningIfGitWindowClosed
import training.git.GitLessonsUtil.showWarningIfModalCommitEnabled
import training.git.GitLessonsUtil.showWarningIfStagingAreaEnabled
import training.git.GitLessonsUtil.triggerOnNotification
import training.project.ProjectUtils
import training.ui.LearningUiHighlightingManager
import training.ui.LearningUiUtil.findComponentWithTimeout
import java.awt.Point
import java.awt.Rectangle
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import javax.swing.JCheckBox
import javax.swing.JTree
import javax.swing.KeyStroke
import javax.swing.tree.TreePath
class GitCommitLesson : GitLesson("Git.Commit", GitLessonsBundle.message("git.commit.lesson.name")) {
override val sampleFilePath = "git/puss_in_boots.yml"
override val branchName = "feature"
private val firstFileName = "simple_cat.yml"
private val secondFileName = "puss_in_boots.yml"
private val firstFileAddition = """
|
| - play:
| condition: boring
| actions: [ run after favourite plush mouse ]""".trimMargin()
private val secondFileAddition = """
|
| - play:
| condition: boring
| actions: [ run after mice or own tail ]""".trimMargin()
override val testScriptProperties = TaskTestContext.TestScriptProperties(duration = 60)
override val lessonContent: LessonContext.() -> Unit = {
prepareRuntimeTask {
modifyFiles()
}
showWarningIfModalCommitEnabled()
showWarningIfStagingAreaEnabled()
task {
openCommitWindowText(GitLessonsBundle.message("git.commit.open.commit.window"))
stateCheck {
ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.COMMIT)?.isVisible == true
}
test { actions("CheckinProject") }
}
prepareRuntimeTask {
val lastCommitMessage = "Add facts about playing cats"
VcsConfiguration.getInstance(project).apply {
REFORMAT_BEFORE_PROJECT_COMMIT = false
LAST_COMMIT_MESSAGE = lastCommitMessage
setRecentMessages(listOf(lastCommitMessage))
}
val commitWorkflowHandler: AbstractCommitWorkflowHandler<*, *> = ChangesViewWorkflowManager.getInstance(project).commitWorkflowHandler
?: return@prepareRuntimeTask
commitWorkflowHandler.workflow.commitOptions.restoreState()
commitWorkflowHandler.setCommitMessage(lastCommitMessage)
}
task {
triggerUI().componentPart l@{ ui: ChangesListView ->
val path = TreeUtil.treePathTraverser(ui).find { it.getPathComponent(it.pathCount - 1).toString().contains(firstFileName) }
?: return@l null
val rect = ui.getPathBounds(path) ?: return@l null
Rectangle(rect.x, rect.y, 20, rect.height)
}
}
val commitWindowName = VcsBundle.message("commit.dialog.configurable")
task {
text(GitLessonsBundle.message("git.commit.choose.files", strong(commitWindowName), strong(firstFileName)))
text(GitLessonsBundle.message("git.commit.choose.files.balloon"),
LearningBalloonConfig(Balloon.Position.below, 300, cornerToPointerDistance = 55))
highlightVcsChange(firstFileName)
triggerOnOneChangeIncluded(secondFileName)
showWarningIfCommitWindowClosed(restoreTaskWhenResolved = true)
test {
clickChangeElement(firstFileName)
}
}
task {
triggerAndFullHighlight { usePulsation = true }.component { ui: ActionButton ->
ActionManager.getInstance().getId(ui.action) == "ChangesView.ShowCommitOptions"
}
}
lateinit var showOptionsTaskId: TaskContext.TaskId
task {
showOptionsTaskId = taskId
text(GitLessonsBundle.message("git.commit.open.before.commit.options", icon(AllIcons.General.Gear)))
text(GitLessonsBundle.message("git.commit.open.options.tooltip", strong(commitWindowName)),
LearningBalloonConfig(Balloon.Position.above, 0))
triggerUI().component { _: CommitOptionsPanel -> true }
showWarningIfCommitWindowClosed(restoreTaskWhenResolved = true)
test {
ideFrame {
actionButton(ActionsBundle.actionText("ChangesView.ShowCommitOptions")).click()
}
}
}
val reformatCodeButtonText = VcsBundle.message("checkbox.checkin.options.reformat.code").dropMnemonic()
task {
triggerAndFullHighlight().component { ui: JBCheckBox ->
ui.text?.contains(reformatCodeButtonText) == true
}
}
task {
val analyzeOptionText = VcsBundle.message("before.checkin.standard.options.check.smells").dropMnemonic()
text(GitLessonsBundle.message("git.commit.analyze.code.explanation", strong(analyzeOptionText)))
text(GitLessonsBundle.message("git.commit.enable.reformat.code", strong(reformatCodeButtonText)))
triggerUI().component { ui: JBCheckBox ->
ui.text?.contains(reformatCodeButtonText) == true && ui.isSelected
}
restoreByUi(showOptionsTaskId)
test {
ideFrame {
val checkBox = findComponentWithTimeout(defaultTimeout) { ui: JBCheckBox -> ui.text?.contains(reformatCodeButtonText) == true }
JCheckBoxFixture(robot, checkBox).check()
}
}
}
task {
text(GitLessonsBundle.message("git.commit.close.commit.options", LessonUtil.rawKeyStroke(KeyEvent.VK_ESCAPE)))
stateCheck {
previous.ui?.isShowing != true
}
test { invokeActionViaShortcut("ESCAPE") }
}
val commitButtonText = GitBundle.message("commit.action.name").dropMnemonic()
task {
text(GitLessonsBundle.message("git.commit.perform.commit", strong(commitButtonText)))
triggerAndFullHighlight { usePulsation = true }.component { ui: JBOptionButton ->
ui.text?.contains(commitButtonText) == true
}
triggerOnNotification { it.displayId == VcsNotificationIdsHolder.COMMIT_FINISHED }
showWarningIfCommitWindowClosed()
test {
ideFrame {
button { b: JBOptionButton -> b.text == commitButtonText }.click()
}
}
}
task("ActivateVersionControlToolWindow") {
before {
LearningUiHighlightingManager.clearHighlights()
}
text(GitLessonsBundle.message("git.commit.open.git.window", action(it)))
stateCheck {
val toolWindowManager = ToolWindowManager.getInstance(project)
toolWindowManager.getToolWindow(ToolWindowId.VCS)?.isVisible == true
}
test { actions(it) }
}
resetGitLogWindow()
task {
text(GitLessonsBundle.message("git.commit.select.top.commit"))
triggerOnTopCommitSelected()
showWarningIfGitWindowClosed()
test {
ideFrame {
val table: VcsLogGraphTable = findComponentWithTimeout(defaultTimeout)
JTableFixture(robot, table).click(TableCell.row(0).column(1), MouseButton.LEFT_BUTTON)
}
}
}
task {
text(GitLessonsBundle.message("git.commit.committed.file.explanation"))
triggerAndBorderHighlight { usePulsation = true }.component { _: VcsLogChangesBrowser -> true }
proceedLink()
showWarningIfGitWindowClosed()
}
task {
before { LearningUiHighlightingManager.clearHighlights() }
val amendCheckboxText = VcsBundle.message("checkbox.amend").dropMnemonic()
text(GitLessonsBundle.message("git.commit.select.amend.checkbox",
strong(amendCheckboxText),
LessonUtil.rawKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.ALT_DOWN_MASK)),
strong(commitWindowName)))
triggerAndFullHighlight { usePulsation = true }.component { ui: JBCheckBox ->
ui.text?.contains(amendCheckboxText) == true
}
triggerUI().component { ui: JBCheckBox ->
ui.text?.contains(amendCheckboxText) == true && ui.isSelected
}
showWarningIfCommitWindowClosed()
test {
ideFrame {
val checkBox = findComponentWithTimeout(defaultTimeout) { ui: JBCheckBox -> ui.text?.contains(amendCheckboxText) == true }
JCheckBoxFixture(robot, checkBox).check()
}
}
}
task {
text(GitLessonsBundle.message("git.commit.select.file"))
highlightVcsChange(firstFileName)
triggerOnOneChangeIncluded(firstFileName)
showWarningIfCommitWindowClosed()
test {
clickChangeElement(firstFileName)
}
}
task {
val amendButtonText = VcsBundle.message("amend.action.name", commitButtonText)
text(GitLessonsBundle.message("git.commit.amend.commit", strong(amendButtonText)))
triggerAndFullHighlight().component { ui: JBOptionButton ->
UIUtil.getParentOfType(CommitActionsPanel::class.java, ui) != null
}
triggerOnNotification { it.displayId == VcsNotificationIdsHolder.COMMIT_FINISHED }
showWarningIfCommitWindowClosed()
test {
ideFrame {
button { b: JBOptionButton -> UIUtil.getParentOfType(CommitActionsPanel::class.java, b) != null }.click()
}
}
}
task {
text(GitLessonsBundle.message("git.commit.select.top.commit.again"))
triggerOnTopCommitSelected()
showWarningIfGitWindowClosed()
test {
ideFrame {
val table: VcsLogGraphTable = findComponentWithTimeout(defaultTimeout)
JTableFixture(robot, table).click(TableCell.row(0).column(1), MouseButton.LEFT_BUTTON)
}
}
}
text(GitLessonsBundle.message("git.commit.two.committed.files.explanation"))
restoreCommitWindowStateInformer()
}
private fun TaskContext.highlightVcsChange(changeFileName: String, highlightBorder: Boolean = true) {
triggerAndBorderHighlight().treeItem { _: JTree, path: TreePath ->
path.pathCount > 2 && path.getPathComponent(2).toString().contains(changeFileName)
}
}
private fun TaskContext.triggerOnOneChangeIncluded(changeFileName: String) {
triggerUI().component l@{ ui: ChangesListView ->
val includedChanges = ui.includedSet
if (includedChanges.size != 1) return@l false
val change = includedChanges.first() as? ChangeListChange ?: return@l false
change.virtualFile?.name == changeFileName
}
}
private fun TaskContext.triggerOnTopCommitSelected() {
highlightSubsequentCommitsInGitLog(0)
triggerUI().component { ui: VcsLogGraphTable ->
ui.isCellSelected(0, 1)
}
}
private fun TaskRuntimeContext.modifyFiles() = invokeLater {
DocumentUtil.writeInRunUndoTransparentAction {
val projectRoot = ProjectUtils.getCurrentLearningProjectRoot()
appendToFile(projectRoot, firstFileName, firstFileAddition)
appendToFile(projectRoot, secondFileName, secondFileAddition)
PsiDocumentManager.getInstance(project).commitAllDocuments()
}
}
private fun appendToFile(projectRoot: VirtualFile, fileName: String, text: String) {
val file = VfsUtil.collectChildrenRecursively(projectRoot).find { it.name == fileName }
?: error("Failed to find ${fileName} in project root: ${projectRoot}")
file.refresh(false, false)
val document = FileDocumentManager.getInstance().getDocument(file)!! // it's not directory or binary file and it isn't large
document.insertString(document.textLength, text)
FileDocumentManager.getInstance().saveDocument(document)
}
private fun TaskTestContext.clickChangeElement(partOfText: String) {
val checkPath: (TreePath) -> Boolean = { p -> p.getPathComponent(p.pathCount - 1).toString().contains(partOfText) }
ideFrame {
val fixture = jTree(checkPath = checkPath)
val tree = fixture.target()
val pathRect = invokeAndWaitIfNeeded {
val path = TreeUtil.treePathTraverser(tree).find(checkPath)
tree.getPathBounds(path)
} ?: error("Failed to find path with text '$partOfText'")
val offset = JCheckBox().preferredSize.width / 2
robot.click(tree, Point(pathRect.x + offset, pathRect.y + offset))
}
}
override val helpLinks: Map<String, String>
get() = mapOf(
Pair(GitLessonsBundle.message("git.commit.help.link"),
LessonUtil.getHelpLink("commit-and-push-changes.html")),
)
} | apache-2.0 | fd6c620b8f1df0f26aa928bb4a27b287 | 39.605042 | 140 | 0.718938 | 5.01037 | false | false | false | false |
GunoH/intellij-community | java/idea-ui/testSrc/com/intellij/openapi/roots/ui/configuration/libraryEditor/JavaLibraryRootsDetectionTest.kt | 7 | 3032 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.roots.ui.configuration.libraryEditor
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.roots.NativeLibraryOrderRootType
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.libraries.ui.impl.LibraryRootsDetectorImpl
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.impl.jar.JarFileSystemImpl
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.util.io.DirectoryContentBuilder
import com.intellij.util.io.directoryContent
import com.intellij.util.io.generateInVirtualTempDir
class JavaLibraryRootsDetectionTest : LightPlatformTestCase() {
fun `test JAR with classes`() {
assertRootType(OrderRootType.CLASSES, false) {
zip("classes.jar") {
file("A.class")
}
}
}
fun `test directory with classes`() {
assertRootType(OrderRootType.CLASSES, false) {
dir("classes") {
file("A.class")
}
}
}
fun `test directory with sources`() {
assertRootType(OrderRootType.SOURCES, false) {
dir("src") {
file("A.java", "class A {}")
}
}
}
fun `test JAR directory`() {
assertRootType(OrderRootType.CLASSES, true) {
dir("lib") {
zip("a.jar") {
file("A.class")
}
}
}
}
fun `test sources zip directory`() {
assertRootType(OrderRootType.SOURCES, true) {
dir("lib") {
zip("src.zip") {
file("A.java", "class A {}")
}
}
}
}
fun `test native library`() {
assertRootType(NativeLibraryOrderRootType.getInstance(), false) {
dir("lib") {
file("a.dll")
}
}
}
fun `test native library in JAR`() {
assertRootType(OrderRootType.CLASSES, false) {
zip("a.jar") {
file("a.dll")
}
}
}
private fun assertRootType(expectedType: OrderRootType, jarDirectory: Boolean, content: DirectoryContentBuilder.() -> Unit) {
val dir = directoryContent(content).generateInVirtualTempDir()
val detector = LibraryRootsDetectorImpl(DefaultLibraryRootsComponentDescriptor().rootDetectors)
val root = assertOneElement(dir.children.flatMap { file ->
val rootFile = if (FileTypeRegistry.getInstance().isFileOfType(file, ArchiveFileType.INSTANCE)) JarFileSystem.getInstance().getJarRootForLocalFile(file)!! else file
detector.detectRoots(rootFile, EmptyProgressIndicator())
})
val type = assertOneElement(root.types)
assertEquals(expectedType, type.type)
assertEquals(jarDirectory, type.isJarDirectory)
}
override fun tearDown() {
try {
JarFileSystemImpl.cleanupForNextTest()
}
catch (e: Throwable) {
addSuppressedException(e)
}
finally {
super.tearDown()
}
}
} | apache-2.0 | 5d4fdb018998b546ffb82f0ef87cc0a2 | 29.029703 | 170 | 0.687995 | 4.400581 | false | true | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/comparison/classMembersOnlyChanged/membersFlagsChanged/new.kt | 5 | 2719 | package test
abstract class A {
abstract val abstractFlagAddedVal: String
val abstractFlagRemovedVal: String = ""
abstract val abstractFlagUnchangedVal: String
abstract fun abstractFlagAddedFun()
fun abstractFlagRemovedFun() {}
abstract fun abstractFlagUnchangedFun()
final val finalFlagAddedVal = ""
val finalFlagRemovedVal = ""
final val finalFlagUnchangedVal = ""
final fun finalFlagAddedFun() {}
fun finalFlagRemovedFun() {}
final fun finalFlagUnchangedFun() {}
@Suppress("INAPPLICABLE_INFIX_MODIFIER")
infix fun infixFlagAddedFun() {}
fun infixFlagRemovedFun() {}
@Suppress("INAPPLICABLE_INFIX_MODIFIER")
infix fun infixFlagUnchangedFun() {}
inline fun inlineFlagAddedFun() {}
fun inlineFlagRemovedFun() {}
inline fun inlineFlagUnchangedFun() {}
internal val internalFlagAddedVal = ""
val internalFlagRemovedVal = ""
internal val internalFlagUnchangedVal = ""
internal fun internalFlagAddedFun() {}
fun internalFlagRemovedFun() {}
internal fun internalFlagUnchangedFun() {}
lateinit var lateinitFlagAddedVal: String
var lateinitFlagRemovedVal: String = ""
lateinit var lateinitFlagUnchangedVal: String
open val openFlagAddedVal = ""
val openFlagRemovedVal = ""
open val openFlagUnchangedVal = ""
open fun openFlagAddedFun() {}
fun openFlagRemovedFun() {}
open fun openFlagUnchangedFun() {}
@Suppress("INAPPLICABLE_OPERATOR_MODIFIER")
operator fun operatorFlagAddedFun() {}
fun operatorFlagRemovedFun() {}
@Suppress("INAPPLICABLE_OPERATOR_MODIFIER")
operator fun operatorFlagUnchangedFun() {}
private val privateFlagAddedVal = ""
val privateFlagRemovedVal = ""
private val privateFlagUnchangedVal = ""
private fun privateFlagAddedFun() {}
fun privateFlagRemovedFun() {}
private fun privateFlagUnchangedFun() {}
protected val protectedFlagAddedVal = ""
val protectedFlagRemovedVal = ""
protected val protectedFlagUnchangedVal = ""
protected fun protectedFlagAddedFun() {}
fun protectedFlagRemovedFun() {}
protected fun protectedFlagUnchangedFun() {}
public val publicFlagAddedVal = ""
val publicFlagRemovedVal = ""
public val publicFlagUnchangedVal = ""
public fun publicFlagAddedFun() {}
fun publicFlagRemovedFun() {}
public fun publicFlagUnchangedFun() {}
tailrec fun tailrecFlagAddedFun() {}
fun tailrecFlagRemovedFun() {}
tailrec fun tailrecFlagUnchangedFun() {}
val noFlagsUnchangedVal = ""
fun noFlagsUnchangedFun() {}
}
object O {
const val constFlagAddedVal = ""
val constFlagRemovedVal = ""
const val constFlagUnchangedVal = ""
} | apache-2.0 | b5756ac2e22a29a1790efd764948f1cd | 31 | 49 | 0.711659 | 5.044527 | false | false | false | false |
spring-cloud/spring-cloud-contract | specs/spring-cloud-contract-spec-kotlin/src/main/kotlin/org/springframework/cloud/contract/spec/internal/ResponseBodyMatchersDsl.kt | 1 | 1209 | /*
* Copyright 2019-2020 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 org.springframework.cloud.contract.spec.internal
/**
* Additional matchers for the response or output message part.
*
* @author Tim Ysewyn
* @since 2.2.0
*/
class ResponseBodyMatchersDsl : BodyMatchersDsl() {
val byType
get() = MatchingTypeValue(MatchingType.TYPE)
val byNull
get() = MatchingTypeValue(MatchingType.NULL)
fun byCommand(execute: String) = MatchingTypeValue().apply {
type = MatchingType.COMMAND
value = ExecutionProperty(execute)
}
override fun get() = configureBodyMatchers(ResponseBodyMatchers())
} | apache-2.0 | cf367befe01efa8b523f0d720a9ad785 | 29.25 | 75 | 0.72043 | 4.183391 | false | false | false | false |
jwren/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/references/OneToOne.kt | 2 | 5940 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.references
import com.intellij.workspaceModel.storage.impl.*
import com.intellij.workspaceModel.storage.impl.ConnectionId.ConnectionType.ONE_TO_ONE
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class OneToOneParent private constructor() {
class Nullable<Parent : WorkspaceEntityBase, Child : WorkspaceEntityBase>(
private val childClass: Class<Child>,
private val isParentInChildNullable: Boolean,
) : ReadOnlyProperty<Parent, Child?> {
private var connectionId: ConnectionId? = null
override fun getValue(thisRef: Parent, property: KProperty<*>): Child? {
if (connectionId == null) {
connectionId = ConnectionId.create(thisRef.javaClass, childClass, ONE_TO_ONE, isParentInChildNullable)
}
return thisRef.snapshot.extractOneToOneChild(connectionId!!, thisRef.id)
}
}
}
class OneToOneChild private constructor() {
class NotNull<Child : WorkspaceEntityBase, Parent : WorkspaceEntityBase>(
private val parentClass: Class<Parent>,
) : ReadOnlyProperty<Child, Parent> {
private var connectionId: ConnectionId? = null
override fun getValue(thisRef: Child, property: KProperty<*>): Parent {
if (connectionId == null) {
connectionId = ConnectionId.create(parentClass, thisRef.javaClass, ONE_TO_ONE, false)
}
return thisRef.snapshot.extractOneToOneParent(connectionId!!, thisRef.id)!!
}
}
class Nullable<Child : WorkspaceEntityBase, Parent : WorkspaceEntityBase>(
private val parentClass: Class<Parent>
) : ReadOnlyProperty<Child, Parent?> {
private var connectionId: ConnectionId? = null
override fun getValue(thisRef: Child, property: KProperty<*>): Parent? {
if (connectionId == null) {
connectionId = ConnectionId.create(parentClass, thisRef.javaClass, ONE_TO_ONE, true)
}
return thisRef.snapshot.extractOneToOneParent(connectionId!!, thisRef.id)
}
}
}
// TODO: 08.02.2021 It may cause issues if we'll attach two children to the same parent
class MutableOneToOneParent private constructor() {
class Nullable<Parent : WorkspaceEntityBase, Child : WorkspaceEntityBase, ModifParent : ModifiableWorkspaceEntityBase<Parent>>(
private val parentClass: Class<Parent>,
private val childClass: Class<Child>,
private val isParentInChildNullable: Boolean,
) : ReadWriteProperty<ModifParent, Child?> {
private var connectionId: ConnectionId? = null
override fun getValue(thisRef: ModifParent, property: KProperty<*>): Child? {
if (connectionId == null) {
connectionId = ConnectionId.create(parentClass, childClass, ONE_TO_ONE, isParentInChildNullable)
}
return (thisRef.diff as WorkspaceEntityStorageBuilderImpl).extractOneToOneChild(connectionId!!, thisRef.id)!!
}
override fun setValue(thisRef: ModifParent, property: KProperty<*>, value: Child?) {
if (!thisRef.modifiable.get()) {
throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!")
}
if (connectionId == null) {
connectionId = ConnectionId.create(parentClass, childClass, ONE_TO_ONE, isParentInChildNullable)
}
(thisRef.diff as WorkspaceEntityStorageBuilderImpl).updateOneToOneChildOfParent(connectionId!!, thisRef.id, value?.id?.asChild())
}
}
}
class MutableOneToOneChild private constructor() {
class NotNull<Parent : WorkspaceEntityBase, Child : WorkspaceEntityBase, ModifChild : ModifiableWorkspaceEntityBase<Child>>(
private val childClass: Class<Child>,
private val parentClass: Class<Parent>,
) : ReadWriteProperty<ModifChild, Parent> {
private var connectionId: ConnectionId? = null
override fun getValue(thisRef: ModifChild, property: KProperty<*>): Parent {
if (connectionId == null) {
connectionId = ConnectionId.create(parentClass, childClass, ONE_TO_ONE, false)
}
return (thisRef.diff as WorkspaceEntityStorageBuilderImpl).extractOneToOneParent(connectionId!!, thisRef.id)!!
}
override fun setValue(thisRef: ModifChild, property: KProperty<*>, value: Parent) {
if (!thisRef.modifiable.get()) {
throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!")
}
if (connectionId == null) {
connectionId = ConnectionId.create(parentClass, childClass, ONE_TO_ONE, false)
}
(thisRef.diff as WorkspaceEntityStorageBuilderImpl).updateOneToOneParentOfChild(connectionId!!, thisRef.id, value)
}
}
class Nullable<Parent : WorkspaceEntityBase, Child : WorkspaceEntityBase, ModifChild : ModifiableWorkspaceEntityBase<Child>>(
private val childClass: Class<Child>,
private val parentClass: Class<Parent>,
) : ReadWriteProperty<ModifChild, Parent?> {
private var connectionId: ConnectionId? = null
override fun getValue(thisRef: ModifChild, property: KProperty<*>): Parent? {
if (connectionId == null) {
connectionId = ConnectionId.create(parentClass, childClass, ONE_TO_ONE, true)
}
return (thisRef.diff as WorkspaceEntityStorageBuilderImpl).extractOneToOneParent(connectionId!!, thisRef.id)
}
override fun setValue(thisRef: ModifChild, property: KProperty<*>, value: Parent?) {
if (!thisRef.modifiable.get()) {
throw IllegalStateException("Modifications are allowed inside 'addEntity' and 'modifyEntity' methods only!")
}
if (connectionId == null) {
connectionId = ConnectionId.create(parentClass, childClass, ONE_TO_ONE, true)
}
(thisRef.diff as WorkspaceEntityStorageBuilderImpl).updateOneToOneParentOfChild(connectionId!!, thisRef.id, value)
}
}
}
| apache-2.0 | 825dd2c6ca37d9acde05c9caf92d8217 | 44.343511 | 140 | 0.728956 | 4.991597 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/java/src/service/project/wizard/GradleJavaNewProjectWizardData.kt | 1 | 1873 | // 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.plugins.gradle.service.project.wizard
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.openapi.util.Key
interface GradleJavaNewProjectWizardData : GradleNewProjectWizardData {
companion object {
@JvmStatic val KEY = Key.create<GradleJavaNewProjectWizardData>(GradleJavaNewProjectWizardData::class.java.name)
@JvmStatic val NewProjectWizardStep.gradleData get() = data.getUserData(KEY)!!
@JvmStatic val NewProjectWizardStep.sdkProperty get() = gradleData.sdkProperty
@JvmStatic val NewProjectWizardStep.useKotlinDslProperty get() = gradleData.useKotlinDslProperty
@JvmStatic val NewProjectWizardStep.parentProperty get() = gradleData.parentProperty
@JvmStatic val NewProjectWizardStep.groupIdProperty get() = gradleData.groupIdProperty
@JvmStatic val NewProjectWizardStep.artifactIdProperty get() = gradleData.artifactIdProperty
@JvmStatic var NewProjectWizardStep.sdk get() = gradleData.sdk; set(it) { gradleData.sdk = it }
@JvmStatic var NewProjectWizardStep.useKotlinDsl get() = gradleData.useKotlinDsl; set(it) { gradleData.useKotlinDsl = it }
@JvmStatic var NewProjectWizardStep.parent get() = gradleData.parent; set(it) { gradleData.parent = it }
@JvmStatic var NewProjectWizardStep.parentData get() = gradleData.parentData; set(it) { gradleData.parentData = it }
@JvmStatic var NewProjectWizardStep.groupId get() = gradleData.groupId; set(it) { gradleData.groupId = it }
@JvmStatic var NewProjectWizardStep.artifactId get() = gradleData.artifactId; set(it) { gradleData.artifactId = it }
@JvmStatic var NewProjectWizardStep.version get() = gradleData.version; set(it) { gradleData.version = it }
}
} | apache-2.0 | 0308f2f66248e7db51462b67f0ad8189 | 71.076923 | 158 | 0.785905 | 4.647643 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/util/testProject.kt | 1 | 1779 | // 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.perf.util
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.impl.ProjectLoadingErrorsHeadlessNotifier
import org.jetbrains.kotlin.idea.testFramework.ProjectOpenAction
import java.io.File
class ExternalProject(val path: String, val openWith: ProjectOpenAction) {
companion object {
val KOTLIN_PROJECT_PATH = run {
val path = System.getProperty("performanceProjects", "kotlin")
if (File(path).exists()) path else "../$path"
}
val KOTLIN_GRADLE = ExternalProject(KOTLIN_PROJECT_PATH, ProjectOpenAction.GRADLE_PROJECT)
val KOTLIN_JPS = ExternalProject(KOTLIN_PROJECT_PATH, ProjectOpenAction.EXISTING_IDEA_PROJECT)
// not intended for using in unit tests, only for local verification
val KOTLIN_AUTO = ExternalProject(KOTLIN_PROJECT_PATH, autoOpenAction(KOTLIN_PROJECT_PATH))
fun autoOpenAction(path: String): ProjectOpenAction {
return when {
exists(path, "build.gradle") || exists(path, "build.gradle.kts") -> ProjectOpenAction.GRADLE_PROJECT
exists(path, ".idea", "modules.xml") -> ProjectOpenAction.EXISTING_IDEA_PROJECT
else -> ProjectOpenAction.GRADLE_PROJECT
}
}
fun autoOpenProject(path: String): ExternalProject = ExternalProject(path, autoOpenAction(path))
}
}
internal fun Disposable.registerLoadingErrorsHeadlessNotifier() {
ProjectLoadingErrorsHeadlessNotifier.setErrorHandler(this) { description ->
throw RuntimeException(description.description)
}
}
| apache-2.0 | 07e16e328035f8a5ac48371d0e3a0160 | 43.475 | 158 | 0.714446 | 4.756684 | false | false | false | false |
android/compose-samples | Owl/app/src/main/java/com/example/owl/ui/common/OutlinedAvatar.kt | 1 | 2660 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.owl.ui.common
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.owl.ui.theme.BlueTheme
import com.example.owl.ui.utils.NetworkImage
@Composable
fun OutlinedAvatar(
url: String,
modifier: Modifier = Modifier,
outlineSize: Dp = 3.dp,
outlineColor: Color = MaterialTheme.colors.surface
) {
Box(
modifier = modifier.background(
color = outlineColor,
shape = CircleShape
)
) {
NetworkImage(
url = url,
contentDescription = null,
modifier = Modifier
.padding(outlineSize)
.fillMaxSize()
.clip(CircleShape)
)
}
}
@Preview(
name = "Outlined Avatar",
widthDp = 40,
heightDp = 40
)
@Composable
private fun OutlinedAvatarPreview() {
BlueTheme {
OutlinedAvatar(url = "")
}
}
| apache-2.0 | a6f96878e3164a409da482a2b3cacc99 | 30.294118 | 75 | 0.716541 | 4.242424 | false | false | false | false |
dariopellegrini/Spike | spike/src/main/java/com/dariopellegrini/spike/Builder.kt | 1 | 3659 | package com.dariopellegrini.spike
import com.dariopellegrini.spike.multipart.SpikeMultipartEntity
import com.dariopellegrini.spike.network.SpikeMethod
import com.dariopellegrini.spike.response.SpikeErrorResponse
import com.dariopellegrini.spike.response.SpikeSuccessResponse
/**
* Created by Dario on 10/12/2018.
* Dario Pellegrini Brescia
*/
class TargetBuilder() {
var baseURL: String = ""
var path: String = ""
var method: SpikeMethod = SpikeMethod.GET
var headers: Map<String, String>? = null
var parameters: Map<String, Any>? = null
var multipartEntities: List<SpikeMultipartEntity>? = null
var successClosure: ((String, Map<String, String>?) -> Any?)? = null
var errorClosure: ((String, Map<String, String>?) -> Any?)? = null
var sampleHeaders: Map<String, String>? = null
var sampleResult: String? = null
val target: TargetType
get() = object : TargetType {
override val baseURL = [email protected]
override val path = [email protected]
override val method: SpikeMethod = [email protected]
override val headers: Map<String, String>? = [email protected]
override val parameters: Map<String, Any>? = [email protected]
override val multipartEntities: List<SpikeMultipartEntity>? = [email protected]
override val successClosure: ((String, Map<String, String>?) -> Any?)? = [email protected]
override val errorClosure: ((String, Map<String, String>?) -> Any?)? = [email protected]
override val sampleHeaders: Map<String, String>? = [email protected]
override val sampleResult: String? = [email protected]
}
}
// Builder functions
fun buildTarget(closure: TargetBuilder.() -> Unit): TargetType {
val targetBuilder = TargetBuilder()
targetBuilder.closure()
return targetBuilder.target
}
// SpikeProvider extensions
suspend fun <T> SpikeProvider<TargetType>.buildRequest(closure: TargetBuilder.() -> Unit): SpikeSuccessResponse<T> {
val targetBuilder = TargetBuilder()
targetBuilder.closure()
return this.suspendingRequest<T>(targetBuilder.target)
}
suspend fun SpikeProvider<TargetType>.buildAnyRequest(closure: TargetBuilder.() -> Unit): SpikeSuccessResponse<Any> {
val targetBuilder = TargetBuilder()
targetBuilder.closure()
return this.suspendingRequest(targetBuilder.target)
}
// Suspendable functions with global SpikeProvider
suspend fun requestAny(closure: TargetBuilder.() -> Unit): SpikeSuccessResponse<Any> {
val provider = SpikeProvider<TargetType>()
return provider.buildAnyRequest(closure)
}
suspend fun <T>request(closure: TargetBuilder.() -> Unit): SpikeSuccessResponse<T> {
val provider = SpikeProvider<TargetType>()
return provider.buildRequest(closure)
}
// Functions with callback with global SpikeProvider
fun requestAny(closure: TargetBuilder.() -> Unit, onSuccess: (SpikeSuccessResponse<Any>) -> Unit, onError: (SpikeErrorResponse<Any>) -> Unit) {
val targetBuilder = TargetBuilder()
targetBuilder.closure()
val provider = SpikeProvider<TargetType>()
provider.request(targetBuilder.target, onSuccess, onError)
}
fun <S, E>request(closure: TargetBuilder.() -> Unit, onSuccess: (SpikeSuccessResponse<S>) -> Unit, onError: (SpikeErrorResponse<E>) -> Unit) {
val targetBuilder = TargetBuilder()
targetBuilder.closure()
val provider = SpikeProvider<TargetType>()
provider.requestTypesafe<S, E>(targetBuilder.target, onSuccess, onError)
}
| mit | eae2245991dae1752591746804d4672b | 42.559524 | 143 | 0.725335 | 4.284543 | false | false | false | false |
bhubie/Expander | app/src/main/kotlin/com/wanderfar/expander/DynamicValue/DynamicValueDrawableSpan.kt | 1 | 3328 | /*
* Expander: Text Expansion Application
* Copyright (C) 2016 Brett Huber
*
* 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.wanderfar.expander.DynamicValue
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.text.style.DynamicDrawableSpan
import java.lang.ref.WeakReference
class DynamicValueDrawableSpan(verticalAlignment: Int) : DynamicDrawableSpan(verticalAlignment) {
private var mContext: Context? = null
private var mResourceId: Int = 0
private var mSize: Int = 0
private var mTextSize: Int = 0
private var mHeight: Int = 0
private var mWidth: Int = 0
private var mTop: Int = 0
private var mXPos: Float = 0.0f
private var mYpos: Float = 0.0f
lateinit private var mDrawable: Drawable
private var mDrawableRef: WeakReference<Drawable>? = null
lateinit private var mText: String
constructor(context: Context, resourceId: Int, size: Int, alignment: Int, textSize: Int, text: String, xPos: Float, yPos: Float): this(alignment) {
mContext = context
mResourceId = resourceId
mWidth; mHeight; mSize = size
mTextSize = textSize
mText = text
mXPos = xPos
mYpos = yPos
}
override fun getDrawable(): Drawable {
try {
//mDrawable = mContext?.resources?.getDrawable(mResourceId) as Drawable
mDrawable = TextDrawableCustom(mText, mSize, mXPos, mYpos) as Drawable
mHeight = mSize
val paint = Paint()
paint.textSize = (mTextSize * .80).toFloat()
mWidth = paint.measureText(mText + " ").toInt()
mTop = (mTextSize - mHeight) / 2
mDrawable.setBounds(0, mTop, mWidth, mTop + mHeight)
} catch (e: Exception) {
// swallow
}
return mDrawable
}
override fun draw(canvas: Canvas, text: CharSequence, start: Int, end: Int, x: Float, top: Int, y: Int, bottom: Int, paint: Paint) {
//super.draw(canvas, text, start, end, x, top, y, bottom, paint);
val b = getCachedDrawable()
canvas.save()
var transY = bottom - b!!.bounds.bottom
if (mVerticalAlignment === ALIGN_BASELINE) {
transY = top + (bottom - top) / 2 - (b.bounds.bottom - b.bounds.top) / 2 - mTop
}
canvas.translate(x, transY.toFloat())
b.draw(canvas)
canvas.restore()
}
private fun getCachedDrawable(): Drawable? {
if (mDrawableRef == null || mDrawableRef!!.get() == null) {
mDrawableRef = WeakReference<Drawable>(drawable)
}
return mDrawableRef!!.get()
}
} | gpl-3.0 | 46708e51c88f848a3dfdb9ac75c6125e | 31.637255 | 152 | 0.652644 | 4.261204 | false | false | false | false |
cmcpasserby/MayaCharm | src/main/kotlin/mayacomms/MayaCommandInterface.kt | 1 | 2455 | package mayacomms
import resources.MayaNotifications
import resources.PythonStrings
import com.intellij.notification.Notifications
import com.intellij.openapi.application.PathManager
import com.intellij.util.io.createDirectories
import com.intellij.util.io.exists
import java.io.*
import java.net.Socket
import java.nio.file.Paths
const val LOG_FILENAME_STRING: String = "/mayalog%s.txt"
class MayaCommandInterface(private val port: Int) {
private val logFileName: String = String.format(LOG_FILENAME_STRING, port)
private fun writeFile(text: String): File? {
var tempFile: File? = null
val bw: BufferedWriter
try {
tempFile = File.createTempFile("MayaCharmTemp", ".py") ?: return null
if (!tempFile.exists()) {
tempFile.createNewFile()
}
bw = BufferedWriter(FileWriter(tempFile))
bw.write(PythonStrings.UTF8_ENCODING_STR.message)
bw.newLine()
bw.write(text)
bw.close()
tempFile.deleteOnExit()
} catch (e: IOException) {
Notifications.Bus.notify(MayaNotifications.FILE_FAIL)
e.printStackTrace()
}
return tempFile
}
private fun sendToPort(message: File) {
var client: Socket? = null
try {
client = Socket("localhost", port)
val outString = PythonStrings.EXECFILE.format(message.toString().replace("\\", "/"))
client.outputStream.write(outString.toByteArray())
} catch (e: IOException) {
Notifications.Bus.notify(MayaNotifications.CONNECTION_REFUSED)
e.printStackTrace()
} finally {
client?.close()
}
}
fun sendCodeToMaya(message: String) {
val file = writeFile(message)
sendToPort(file!!)
}
fun sendFileToMaya(path: String) {
val file = File(path)
sendToPort(file)
}
fun connectMayaLog() {
val mayaLogPath = Paths.get(PathManager.getPluginTempPath()).let {
if (!it.exists()) it.createDirectories()
Paths.get(it.toString() + logFileName)
}
File(mayaLogPath.toString()).also {
if (!it.exists()) it.createNewFile()
}
val message = PythonStrings.CLOSE_LOG.message +
System.lineSeparator() + PythonStrings.OPEN_LOG.format(mayaLogPath)
sendCodeToMaya(message)
}
}
| mit | 10d69c0947a0aa55fb26983fea1624df | 29.308642 | 96 | 0.617515 | 4.383929 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/webrtc/ui/WebPermissionFragment.kt | 1 | 2993 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.webrtc.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import dagger.hilt.android.AndroidEntryPoint
import jp.hazuki.yuzubrowser.core.utility.utils.ui
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.webrtc.WebPermissionsDao
import jp.hazuki.yuzubrowser.legacy.webrtc.WebRtcPermission
import jp.hazuki.yuzubrowser.legacy.webrtc.core.WebPermissions
import jp.hazuki.yuzubrowser.ui.widget.recycler.DividerItemDecoration
import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener
import javax.inject.Inject
@AndroidEntryPoint
class WebPermissionFragment : Fragment(), OnRecyclerListener, WebPermissionsEditDialog.OnPermissionEditedListener {
@Inject
internal lateinit var webPermissionsDao: WebPermissionsDao
private lateinit var adapter: WebPermissionAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.recycler_view, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val activity = activity ?: return
adapter = WebPermissionAdapter(activity, this)
ui {
adapter.addAll(webPermissionsDao.getList())
adapter.notifyDataSetChanged()
}
view.findViewById<RecyclerView>(R.id.recyclerView).run {
layoutManager = LinearLayoutManager(activity)
addItemDecoration(DividerItemDecoration(activity))
adapter = [email protected]
}
}
override fun onRecyclerItemClicked(v: View, position: Int) {
val permissions = adapter[position]
WebPermissionsEditDialog(position, permissions)
.show(childFragmentManager, "edit")
}
override fun onPermissionEdited(position: Int, permissions: WebPermissions) {
adapter[position] = permissions
adapter.notifyItemChanged(position)
ui {
webPermissionsDao.update(permissions)
}
WebRtcPermission.clearCache()
}
override fun onRecyclerItemLongClicked(v: View, position: Int) = false
}
| apache-2.0 | 9514f2f18d33f6758330c8bb5fd88360 | 35.5 | 116 | 0.749415 | 4.743265 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/database/table/RPKTicketTable.kt | 1 | 10118 | /*
* Copyright 2018 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.moderation.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.database.jooq.rpkit.Tables.RPKIT_TICKET
import com.rpkit.moderation.bukkit.ticket.RPKTicket
import com.rpkit.moderation.bukkit.ticket.RPKTicketImpl
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import org.bukkit.Location
import org.ehcache.config.builders.CacheConfigurationBuilder
import org.ehcache.config.builders.ResourcePoolsBuilder
import org.jooq.impl.DSL.constraint
import org.jooq.impl.SQLDataType
import java.sql.Timestamp
class RPKTicketTable(database: Database, private val plugin: RPKModerationBukkit): Table<RPKTicket>(database, RPKTicket::class) {
private val cache = if (plugin.config.getBoolean("caching.rpkit_ticket.id.enabled")) {
database.cacheManager.createCache("rpk-moderation-bukkit.rpkit_ticket.id", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKTicket::class.java,
ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_ticket.id.size"))))
} else {
null
}
override fun create() {
database.create.createTableIfNotExists(RPKIT_TICKET)
.column(RPKIT_TICKET.ID, SQLDataType.INTEGER.identity(true))
.column(RPKIT_TICKET.REASON, SQLDataType.VARCHAR.length(1024))
.column(RPKIT_TICKET.ISSUER_ID, SQLDataType.INTEGER)
.column(RPKIT_TICKET.RESOLVER_ID, SQLDataType.INTEGER)
.column(RPKIT_TICKET.WORLD, SQLDataType.VARCHAR.length(256))
.column(RPKIT_TICKET.X, SQLDataType.DOUBLE)
.column(RPKIT_TICKET.Y, SQLDataType.DOUBLE)
.column(RPKIT_TICKET.Z, SQLDataType.DOUBLE)
.column(RPKIT_TICKET.YAW, SQLDataType.DOUBLE)
.column(RPKIT_TICKET.PITCH, SQLDataType.DOUBLE)
.column(RPKIT_TICKET.OPEN_DATE, SQLDataType.TIMESTAMP)
.column(RPKIT_TICKET.CLOSE_DATE, SQLDataType.TIMESTAMP)
.column(RPKIT_TICKET.CLOSED, SQLDataType.TINYINT.length(1))
.constraints(
constraint("pk_rpkit_ticket").primaryKey(RPKIT_TICKET.ID)
)
.execute()
}
override fun applyMigrations() {
if (database.getTableVersion(this) == null) {
database.setTableVersion(this, "1.5.2")
}
if (database.getTableVersion(this) == "1.5.0") {
database.create
.alterTable(RPKIT_TICKET)
.alterColumn(RPKIT_TICKET.ID)
.set(SQLDataType.INTEGER.identity(true))
.execute()
database.setTableVersion(this, "1.5.2")
}
}
override fun insert(entity: RPKTicket): Int {
database.create
.insertInto(
RPKIT_TICKET,
RPKIT_TICKET.REASON,
RPKIT_TICKET.ISSUER_ID,
RPKIT_TICKET.RESOLVER_ID,
RPKIT_TICKET.WORLD,
RPKIT_TICKET.X,
RPKIT_TICKET.Y,
RPKIT_TICKET.Z,
RPKIT_TICKET.YAW,
RPKIT_TICKET.PITCH,
RPKIT_TICKET.OPEN_DATE,
RPKIT_TICKET.CLOSE_DATE,
RPKIT_TICKET.CLOSED
)
.values(
entity.reason,
entity.issuer.id,
entity.resolver?.id,
entity.location?.world?.name,
entity.location?.x,
entity.location?.y,
entity.location?.z,
entity.location?.yaw?.toDouble(),
entity.location?.pitch?.toDouble(),
Timestamp.valueOf(entity.openDate),
if (entity.closeDate == null) null else Timestamp.valueOf(entity.closeDate),
if (entity.isClosed) 1.toByte() else 0.toByte()
)
.execute()
val id = database.create.lastID().toInt()
entity.id = id
cache?.put(id, entity)
return id
}
override fun update(entity: RPKTicket) {
database.create
.update(RPKIT_TICKET)
.set(RPKIT_TICKET.REASON, entity.reason)
.set(RPKIT_TICKET.ISSUER_ID, entity.issuer.id)
.set(RPKIT_TICKET.RESOLVER_ID, entity.resolver?.id)
.set(RPKIT_TICKET.WORLD, entity.location?.world?.name)
.set(RPKIT_TICKET.X, entity.location?.x)
.set(RPKIT_TICKET.Y, entity.location?.y)
.set(RPKIT_TICKET.Z, entity.location?.z)
.set(RPKIT_TICKET.YAW, entity.location?.yaw?.toDouble())
.set(RPKIT_TICKET.PITCH, entity.location?.pitch?.toDouble())
.set(RPKIT_TICKET.OPEN_DATE, Timestamp.valueOf(entity.openDate))
.set(RPKIT_TICKET.CLOSE_DATE, if (entity.closeDate == null) null else Timestamp.valueOf(entity.closeDate))
.set(RPKIT_TICKET.CLOSED, if (entity.isClosed) 1.toByte() else 0.toByte())
.where(RPKIT_TICKET.ID.eq(entity.id))
.execute()
cache?.put(entity.id, entity)
}
override fun get(id: Int): RPKTicket? {
if (cache?.containsKey(id) == true) {
return cache[id]
} else {
val result = database.create
.select(
RPKIT_TICKET.REASON,
RPKIT_TICKET.ISSUER_ID,
RPKIT_TICKET.RESOLVER_ID,
RPKIT_TICKET.WORLD,
RPKIT_TICKET.X,
RPKIT_TICKET.Y,
RPKIT_TICKET.Z,
RPKIT_TICKET.YAW,
RPKIT_TICKET.PITCH,
RPKIT_TICKET.OPEN_DATE,
RPKIT_TICKET.CLOSE_DATE,
RPKIT_TICKET.CLOSED
)
.from(RPKIT_TICKET)
.where(RPKIT_TICKET.ID.eq(id))
.fetchOne() ?: return null
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val issuerId = result[RPKIT_TICKET.ISSUER_ID]
val issuer = if (issuerId == null) null else profileProvider.getProfile(issuerId)
val resolverId = result[RPKIT_TICKET.RESOLVER_ID]
val resolver = if (resolverId == null) null else profileProvider.getProfile(resolverId)
val worldName = result[RPKIT_TICKET.WORLD]
val world = if (worldName == null) null else plugin.server.getWorld(worldName)
val x = result[RPKIT_TICKET.X]
val y = result[RPKIT_TICKET.Y]
val z = result[RPKIT_TICKET.Z]
val yaw = result[RPKIT_TICKET.YAW]
val pitch = result[RPKIT_TICKET.PITCH]
if (issuer != null) {
val ticket = RPKTicketImpl(
id,
result[RPKIT_TICKET.REASON],
issuer,
resolver,
if (world == null || x == null || y == null || z == null || yaw == null || pitch == null) {
null
} else {
Location(
world,
x,
y,
z,
yaw.toFloat(),
pitch.toFloat()
)
},
result[RPKIT_TICKET.OPEN_DATE].toLocalDateTime(),
result[RPKIT_TICKET.CLOSE_DATE]?.toLocalDateTime(),
result[RPKIT_TICKET.CLOSED] == 1.toByte()
)
cache?.put(id, ticket)
return ticket
} else {
database.create
.deleteFrom(RPKIT_TICKET)
.where(RPKIT_TICKET.ID.eq(id))
.execute()
cache?.remove(id)
return null
}
}
}
override fun delete(entity: RPKTicket) {
database.create
.deleteFrom(RPKIT_TICKET)
.where(RPKIT_TICKET.ID.eq(entity.id))
.execute()
cache?.remove(entity.id)
}
fun getOpenTickets(): List<RPKTicket> {
val results = database.create
.select(RPKIT_TICKET.ID)
.from(RPKIT_TICKET)
.where(RPKIT_TICKET.CLOSED.eq(0.toByte()))
.fetch()
return results.map { get(it[RPKIT_TICKET.ID]) }.filterNotNull()
}
fun getClosedTickets(): List<RPKTicket> {
val results = database.create
.select(RPKIT_TICKET.ID)
.from(RPKIT_TICKET)
.where(RPKIT_TICKET.CLOSED.eq(1.toByte()))
.fetch()
return results.map { get(it[RPKIT_TICKET.ID]) }.filterNotNull()
}
} | apache-2.0 | 923bfc7c963a80b57c07a96230b38e51 | 42.616379 | 129 | 0.526883 | 4.834209 | false | false | false | false |
AlmasB/Zephyria | src/main/kotlin/com/almasb/zeph/gameplay/Gameplay.kt | 1 | 5032 | package com.almasb.zeph.gameplay
import com.almasb.fxgl.core.Updatable
import com.almasb.fxgl.dsl.getUIFactoryService
import javafx.beans.property.ReadOnlyBooleanProperty
import javafx.beans.property.ReadOnlyBooleanWrapper
import javafx.beans.property.ReadOnlyIntegerProperty
import javafx.beans.property.ReadOnlyIntegerWrapper
import javafx.scene.Parent
import javafx.scene.paint.Color
import javafx.scene.text.Text
import java.util.concurrent.CopyOnWriteArrayList
/**
* Represents an in-game clock for gameplay purposes, such as day/night systems.
* For example, certain quests appear at a certain time of day, or some NPCs may only be around at night.
*
* @author Almas Baimagambetov ([email protected])
*/
class Clock(
/**
* Number of real-time seconds in 24 in-game hours.
*/
secondsIn24h: Int) : Updatable {
private var seconds = 0.0
private val gameDayProp = ReadOnlyIntegerWrapper()
private val gameHourProp = ReadOnlyIntegerWrapper()
private val gameMinuteProp = ReadOnlyIntegerWrapper()
fun gameDayProperty(): ReadOnlyIntegerProperty {
return gameDayProp.readOnlyProperty
}
fun gameHourProperty(): ReadOnlyIntegerProperty {
return gameHourProp.readOnlyProperty
}
fun gameMinuteProperty(): ReadOnlyIntegerProperty {
return gameMinuteProp.readOnlyProperty
}
/**
* The range is [0..MAX_INT]
*/
val gameDay: Int
get() = gameDayProp.value
/**
* The range is [0..23].
*/
val gameHour: Int
get() = gameHourProp.value
/**
* The range is [0..59].
*/
val gameMinute: Int
get() = gameMinuteProp.value
/**
* The range is [0, 59].
*/
var gameSecond = 0
private set
/**
* 24 * 3600 / real seconds in 24h.
*/
private val toGameSeconds = 86400.0 / secondsIn24h
var dayTimeStart = 8
var nightTimeStart = 20
private val isDayTime = ReadOnlyBooleanWrapper(false)
fun dayProperty(): ReadOnlyBooleanProperty {
return isDayTime.readOnlyProperty
}
val isDay: Boolean
get() = isDayTime.value
val isNight: Boolean
get() = !isDay
private val actions = CopyOnWriteArrayList<ClockAction>()
private fun updateActions() {
actions.filter { it.dayToRun == gameDay && (gameHour > it.hour || (gameHour == it.hour && gameMinute >= it.minute)) }
.forEach {
if (!it.isIndefinite) {
it.isDone = true
} else {
it.dayToRun++
}
it.action.run()
}
actions.removeIf { it.isDone }
}
/**
* Runs [action] once when at the clock [hour] or past it.
*/
fun runOnceAtHour(hour: Int, action: Runnable) {
runAt(hour, minute = 0, action)
}
/**
* Runs [action] indefinitely when at the clock [hour]:[minute] or past it.
*/
fun runAt(hour: Int, minute: Int, action: Runnable) {
actions.add(ClockAction(hour, minute, action, isIndefinite = true))
}
/**
* Runs [action] once when at the clock [hour]:[minute] or past it.
*/
fun runOnceAt(hour: Int, minute: Int, action: Runnable) {
actions.add(ClockAction(hour, minute, action))
}
override fun onUpdate(tpf: Double) {
seconds += tpf
var totalGameSeconds = seconds * toGameSeconds
if (totalGameSeconds > 86400) {
seconds = 0.0
totalGameSeconds = 0.0
// new day
gameDayProp.value++
}
gameHourProp.value = totalGameSeconds.toInt() / 3600
gameMinuteProp.value = (totalGameSeconds.toInt() / 60) % 60
gameSecond = totalGameSeconds.toInt() % 60
isDayTime.value = gameHourProp.value in dayTimeStart until nightTimeStart
updateActions()
}
private data class ClockAction(
var hour: Int,
var minute: Int,
var action: Runnable,
var isIndefinite: Boolean = false,
var isDone: Boolean = false,
/**
* Keeps track of the day on which to run next.
*/
var dayToRun: Int = 0
)
}
abstract class ClockView(val clock: Clock) : Parent()
/**
* Basic clock view in hh:mm format
*/
open class TextClockView(clock: Clock) : ClockView(clock) {
private val text = getUIFactoryService().newText("", Color.BLACK, 16.0)
init {
children += text
clock.gameHourProperty().addListener { observable, oldValue, newValue ->
updateView()
}
clock.gameMinuteProperty().addListener { observable, oldValue, newValue ->
updateView()
}
}
private fun updateView() {
val hour = "${clock.gameHourProperty().value}".padStart(2, '0')
val min = "${clock.gameMinuteProperty().value}".padStart(2, '0')
text.text = "$hour:$min"
}
} | gpl-2.0 | a01b101057bd35d614e9fbee27b054ba | 25.489474 | 125 | 0.605922 | 4.375652 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/sql/NullableImpact.kt | 1 | 4271 | package org.evomaster.core.search.impact.impactinfocollection.sql
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.optional.NullableGene
import org.evomaster.core.search.impact.impactinfocollection.*
import org.evomaster.core.search.impact.impactinfocollection.value.numeric.BinaryGeneImpact
/**
* created by manzh on 2019-09-29
*/
class NullableImpact(sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo,
val presentImpact : BinaryGeneImpact = BinaryGeneImpact("isPresent"),
val geneImpact: GeneImpact) : GeneImpact(sharedImpactInfo, specificImpactInfo){
constructor(id : String, sqlnullGene: NullableGene) : this(SharedImpactInfo(id), SpecificImpactInfo(), geneImpact = ImpactUtils.createGeneImpact(sqlnullGene.gene, id))
override fun copy(): NullableImpact {
return NullableImpact(
shared.copy(),
specific.copy(),
presentImpact = presentImpact.copy(),
geneImpact = geneImpact.copy())
}
override fun clone(): NullableImpact {
return NullableImpact(
shared.clone(),specific.clone(), presentImpact.clone(), geneImpact.clone()
)
}
override fun countImpactWithMutatedGeneWithContext(gc: MutatedGeneWithContext,noImpactTargets : Set<Int>, impactTargets: Set<Int>, improvedTargets: Set<Int>, onlyManipulation: Boolean) {
countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene)
if (gc.current !is NullableGene){
throw IllegalStateException("gc.current (${gc.current::class.java.simpleName}) should be SqlNullable")
}
if (gc.previous != null && gc.previous !is NullableGene){
throw IllegalStateException("gc.previous (${gc.previous::class.java.simpleName}) should be SqlNullable")
}
if (gc.previous == null || (gc.previous as NullableGene).isPresent != gc.current.isPresent){
presentImpact.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = gc.numOfMutatedGene)
if (gc.current.isPresent)
presentImpact.trueValue.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
else
presentImpact.falseValue.countImpactAndPerformance(noImpactTargets = noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation, num = 1)
if (gc.previous != null) {
return
}
}
if (gc.previous == null && impactTargets.isNotEmpty()) return
if (gc.current.isPresent){
val mutatedGeneWithContext = MutatedGeneWithContext(
previous = if (gc.previous == null) null else (gc.previous as NullableGene).gene,
current = gc.current.gene,
numOfMutatedGene = gc.numOfMutatedGene
)
geneImpact.countImpactWithMutatedGeneWithContext(mutatedGeneWithContext, noImpactTargets= noImpactTargets, impactTargets = impactTargets, improvedTargets = improvedTargets, onlyManipulation = onlyManipulation)
}
}
override fun validate(gene: Gene): Boolean = gene is NullableGene
override fun flatViewInnerImpact(): Map<String, Impact> {
return mutableMapOf("${getId()}-${geneImpact.getId()}" to geneImpact)
.plus("${getId()}-${presentImpact.getId()}" to presentImpact)
.plus(presentImpact.flatViewInnerImpact().plus(geneImpact.flatViewInnerImpact()).map { "${getId()}-${it.key}" to it.value })
}
override fun innerImpacts(): List<Impact> {
return listOf(presentImpact, geneImpact)
}
override fun syncImpact(previous: Gene?, current: Gene) {
check(previous,current)
geneImpact.syncImpact((previous as NullableGene).gene, (current as NullableGene).gene)
}
} | lgpl-3.0 | 9e11d943c2980e4c8aadf27783dbc74c | 50.46988 | 221 | 0.69328 | 5.253383 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/settings/AccountFragment.kt | 1 | 5462 | /*
* Copyright (C) 2004-2019 Savoir-faire Linux Inc.
*
* Author: AmirHossein Naghshzan <[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 cx.ring.settings
import android.app.Activity
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver.OnScrollChangedListener
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import cx.ring.R
import cx.ring.account.AccountEditionFragment
import cx.ring.account.JamiAccountSummaryFragment
import cx.ring.client.HomeActivity
import cx.ring.databinding.FragAccountBinding
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import net.jami.model.Account
import net.jami.services.AccountService
import javax.inject.Inject
@AndroidEntryPoint
class AccountFragment : Fragment(), OnScrollChangedListener {
private var mBinding: FragAccountBinding? = null
private val mDisposable = CompositeDisposable()
@Inject
lateinit var mAccountService: AccountService
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return FragAccountBinding.inflate(inflater, container, false).apply {
scrollview.viewTreeObserver.addOnScrollChangedListener(this@AccountFragment)
settingsChangePassword.setOnClickListener { (parentFragment as JamiAccountSummaryFragment).onPasswordChangeAsked() }
settingsExport.setOnClickListener { (parentFragment as JamiAccountSummaryFragment).onClickExport() }
mBinding = this
}.root
}
override fun onDestroyView() {
super.onDestroyView()
mBinding = null
mDisposable.clear()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setHasOptionsMenu(true)
val accountId = requireArguments().getString(AccountEditionFragment.ACCOUNT_ID_KEY)!!
mDisposable.add(mAccountService.getAccountSingle(accountId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ account: Account ->
mBinding?.let { binding ->
binding.settingsChangePassword.visibility = if (account.hasManager()) View.GONE else View.VISIBLE
binding.settingsExport.visibility = if (account.hasManager()) View.GONE else View.VISIBLE
binding.systemChangePasswordTitle.setText(if (account.hasPassword()) R.string.account_password_change else R.string.account_password_set)
binding.settingsDeleteAccount.setOnClickListener { createDeleteDialog(account.accountId).show() }
binding.settingsBlackList.setOnClickListener {
val summaryFragment = parentFragment as JamiAccountSummaryFragment?
summaryFragment?.goToBlackList(account.accountId)
}
}
}) {
val summaryFragment = parentFragment as JamiAccountSummaryFragment?
summaryFragment?.popBackStack()
})
}
override fun onScrollChanged() {
mBinding?.let { binding ->
val activity: Activity? = activity
if (activity is HomeActivity)
activity.setToolbarElevation(binding.scrollview.canScrollVertically(SCROLL_DIRECTION_UP))
}
}
private fun createDeleteDialog(accountId: String): AlertDialog {
val alertDialog = MaterialAlertDialogBuilder(requireContext())
.setMessage(R.string.account_delete_dialog_message)
.setTitle(R.string.account_delete_dialog_title)
.setPositiveButton(R.string.menu_delete) { dialog: DialogInterface?, whichButton: Int ->
mAccountService.removeAccount(accountId)
if (activity is HomeActivity)
(activity as HomeActivity).goToHome()
}
.setNegativeButton(android.R.string.cancel, null)
.create()
activity?.let { activity -> alertDialog.setOwnerActivity(activity) }
return alertDialog
}
companion object {
val TAG = AccountFragment::class.simpleName!!
private const val SCROLL_DIRECTION_UP = -1
fun newInstance(accountId: String): AccountFragment {
val bundle = Bundle()
bundle.putString(AccountEditionFragment.ACCOUNT_ID_KEY, accountId)
val accountFragment = AccountFragment()
accountFragment.arguments = bundle
return accountFragment
}
}
} | gpl-3.0 | 9e2499c32f0b3f148b41f5978c3f0c51 | 43.778689 | 157 | 0.703772 | 5.043398 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/api/comment/UpdateCommentEndpoint.kt | 1 | 2821 | package me.proxer.library.api.comment
import me.proxer.library.ProxerCall
import me.proxer.library.api.Endpoint
import me.proxer.library.enums.UserMediaProgress
import me.proxer.library.util.ProxerUtils
/**
* Endpoint for updating or creating a comment.
*
* If the id is passed an update will performed (requiring that a comment with that id exists).
* If the entryId is passed a new comment for the associated [me.proxer.library.entity.info.Entry] will be
* created (requiring that no comment exists yet).
*
* Comments are also used for persisting the current state of the user related to the entry. Thus, at least the progress
* is required for creating a new comment. Most of the time, the update method should be called, because (empty)
* comments get created automatically when the user sets a bookmark.
*
* This Endpoint is used for both the /create and /update apis.
*
* @author Ruben Gees
*/
class UpdateCommentEndpoint internal constructor(
private val internalApi: InternalApi,
private val id: String?,
private val entryId: String?
) : Endpoint<Unit> {
private var rating: Int? = null
private var episode: Int? = null
private var mediaProgress: UserMediaProgress? = null
private var comment: String? = null
init {
require(id.isNullOrBlank().not() || entryId.isNullOrBlank().not()) {
"You must pass either an id or an entryId."
}
}
/**
* Sets the rating for the comment. Must be between 0 and 10, while 0 means no rating is given by the user.
*/
fun rating(rating: Int?): UpdateCommentEndpoint {
require(rating == null || rating in 0..10) {
"The rating must be between 0 and 10."
}
return this.apply { this.rating = rating }
}
/**
* Sets the episode the user is currently at.
*/
fun episode(episode: Int?): UpdateCommentEndpoint {
return this.apply { this.episode = episode }
}
/**
* Sets the overall progress of the user.
*/
fun progress(mediaProgress: UserMediaProgress?): UpdateCommentEndpoint {
return this.apply { this.mediaProgress = mediaProgress }
}
/**
* Sets the content of the comment. May contain BBCode tags and can be empty.
*/
fun comment(comment: String?): UpdateCommentEndpoint {
return this.apply { this.comment = comment }
}
override fun build(): ProxerCall<Unit> {
val apiMediaProgress = mediaProgress?.let { ProxerUtils.getSafeApiEnumName(it).toInt() }
return when {
id != null -> internalApi.update(id, rating, episode, apiMediaProgress, comment)
entryId != null -> internalApi.create(entryId, rating, episode, apiMediaProgress, comment)
else -> error("id and entryId are null")
}
}
}
| gpl-3.0 | 21a01d8ce657869320001f113c07afb8 | 33.82716 | 120 | 0.671393 | 4.366873 | false | false | false | false |
Deanveloper/KBukkit | src/main/kotlin/com/deanveloper/kbukkit/player/CustomPlayer.kt | 1 | 2922 | package com.deanveloper.kbukkit.player
import com.deanveloper.kbukkit.util.Players
import com.deanveloper.kbukkit.util.registerEvents
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.plugin.Plugin
import java.util.*
/**
* API for custom players through delegation.
* In order to implement, make sure your
* companion object extends CustomPlayerCompanion and
* provides the type of your class.
*
* @author Dean B <[email protected]>
*/
open class CustomPlayer protected constructor(var bukkitPlayer: Player) : Player by bukkitPlayer {
// companion object : CustomPlayerCompanion<CustomPlayer>(::CustomPlayer, plugin)
}
/**
* This class, while not required, provides utility in your
* CustomPlayer implementation's companion object.
*
* Usage -> companion object : CustomPlayerCompanion<YourImpl>(::YourImpl)
*/
open class CustomPlayerCompanion<T : CustomPlayer>(val factory: (Player) -> T, plugin: Plugin) : Listener {
protected val idMap = mutableMapOf<UUID, T>()
protected val nameMap = mutableMapOf<String, T>()
init {
this.registerEvents(plugin)
}
/**
* Fetches the CustomPlayer instance.
*
* @return the CustomPlayer instance for this bukkitPlayer
*/
operator fun get(bPlayer: Player): T {
if (bPlayer.uniqueId in idMap) {
val player = idMap[bPlayer.uniqueId]!!
if (player.bukkitPlayer !== bPlayer) {
return update(bPlayer)
}
return player
} else {
return update(bPlayer)
}
}
/**
* Fetches the CustomPlayer instance from a UUID.
*
* @return the CustomPlayer associated with the UUID, null if the player is not online.
*/
operator fun get(index: UUID): T? {
val player = Players[index]
return if(player === null) null else this[player]
}
/**
* Fetches the CustomPlayer instance from a name.
*
* @return the CustomPlayer associated with the name, null if the player is not online.
*/
@Deprecated("Names are not guaranteed to be unique.", ReplaceWith("get(id)"))
operator fun get(index: String): T? {
val player = Players[index]
return if(player === null) null else this[player]
}
protected fun update(bPlayer: Player): T {
val player = idMap[bPlayer.uniqueId] ?: factory(bPlayer)
player.bukkitPlayer = bPlayer
idMap[bPlayer.uniqueId] = player
nameMap[bPlayer.name] = player
return player
}
@EventHandler
fun onJoin(e: PlayerJoinEvent) {
update(e.player)
}
@EventHandler
fun onLeave(e: PlayerQuitEvent) {
idMap.remove(e.player.uniqueId)
nameMap.remove(e.player.name)
}
} | mit | daacb7938d2f1aaea2ad2a9164c32742 | 28.23 | 107 | 0.664613 | 4.234783 | false | false | false | false |
JohnnyShieh/RxFlux | todo/src/main/java/com/johnny/rxfluxtodo/TodoActivity.kt | 1 | 3436 | package com.johnny.rxfluxtodo
/*
* Copyright (C) 2017 Johnny Shieh 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 android.os.Bundle
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.snackbar.Snackbar
import com.johnny.rxflux.RxFlux
import com.johnny.rxfluxtodo.todo.TodoActionCreator
import com.johnny.rxfluxtodo.todo.TodoStore
import kotlinx.android.synthetic.main.activity_main.*
/**
* description
*
* @author Johnny Shieh ([email protected])
* @version 1.0
*
* Created on 2017/3/28
*/
class TodoActivity : AppCompatActivity() {
private lateinit var mAdapter: TodoRecyclerAdapter
private lateinit var mActionCreator: TodoActionCreator
private lateinit var mTodoStore: TodoStore
private val inputText: String
get() = edtInput.text.toString()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
RxFlux.enableRxFluxLog(true)
setContentView(R.layout.activity_main)
initDependencies()
setupView()
}
private fun initDependencies() {
mActionCreator = TodoActionCreator()
mTodoStore = ViewModelProviders.of(this).get(TodoStore::class.java)
}
private fun setupView() {
btnAddTodo.setOnClickListener {
addTodo()
resetMainInput()
}
chkAllComplete.setOnClickListener { checkAll() }
btnClearCompleted.setOnClickListener {
clearCompleted()
resetMainCheck()
}
rvTodo.layoutManager = LinearLayoutManager(this)
mAdapter = TodoRecyclerAdapter(mActionCreator)
rvTodo.adapter = mAdapter
mTodoStore.todoList.observe(
this,
Observer { mAdapter.setItems(mTodoStore.todoList.value!!) })
mTodoStore.canUndo.observe(this, Observer { canUndo ->
if (canUndo == true) {
val snackbar = Snackbar.make(vContainer, "Element deleted", Snackbar.LENGTH_LONG)
snackbar.setAction("Undo") { mActionCreator.undoDestroy() }
snackbar.show()
}
})
}
private fun addTodo() {
if (validateInput()) {
mActionCreator.create(inputText)
}
}
private fun checkAll() {
mActionCreator.toggleCompleteAll()
}
private fun clearCompleted() {
mActionCreator.destroyCompleted()
}
private fun resetMainInput() {
edtInput.setText("")
}
private fun resetMainCheck() {
if (chkAllComplete.isChecked) {
chkAllComplete.isChecked = false
}
}
private fun validateInput(): Boolean {
return !TextUtils.isEmpty(inputText)
}
}
| apache-2.0 | 33640f9b36241bcc69a6b88f5320a0df | 28.62069 | 97 | 0.67695 | 4.550993 | false | false | false | false |
hwki/SimpleBitcoinWidget | bitcoin/src/main/java/com/brentpanther/bitcoinwidget/WidgetApplication.kt | 1 | 1629 | package com.brentpanther.bitcoinwidget
import android.app.Application
import android.appwidget.AppWidgetManager
import android.content.ComponentName
import android.content.Intent
import android.content.IntentFilter
import android.content.res.Resources
import com.brentpanther.bitcoinwidget.receiver.WidgetBroadcastReceiver
class WidgetApplication : Application() {
fun <T : WidgetProvider> getWidgetIds(className: Class<T>): IntArray {
val name = ComponentName(this, className)
return AppWidgetManager.getInstance(this).getAppWidgetIds(name)
}
val widgetIds: IntArray
get() {
return widgetProviders.map { getWidgetIds(it).toList() }.flatten().toIntArray()
}
val widgetProviders = listOf(WidgetProvider::class.java, ValueWidgetProvider::class.java)
fun getWidgetType(widgetId: Int): WidgetType {
val widgetInfo = AppWidgetManager.getInstance(this).getAppWidgetInfo(widgetId)
?: return WidgetType.PRICE
return when (widgetInfo.provider.className) {
WidgetProvider::class.qualifiedName -> WidgetType.PRICE
ValueWidgetProvider::class.qualifiedName -> WidgetType.VALUE
else -> throw IllegalArgumentException()
}
}
override fun onCreate() {
super.onCreate()
instance = this
registerReceiver(WidgetBroadcastReceiver(), IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED))
}
companion object {
lateinit var instance: WidgetApplication
private set
fun Int.dpToPx() = this * Resources.getSystem().displayMetrics.density
}
} | mit | 0fe4c88a699139d9309033fe82419af1 | 32.958333 | 102 | 0.712093 | 5.090625 | false | false | false | false |
Doist/TodoistPojos | src/main/java/com/todoist/pojo/Workspace.kt | 1 | 1483 | package com.todoist.pojo
open class Workspace(
id: String,
open var name: String,
open var description: String?,
open var logoBig: String?,
open var logoMedium: String?,
open var logoSmall: String?,
open var logoS640: String?,
open var isInviteOnlyDefault: Boolean,
open var defaultCollaboratorRole: Collaborator.Role,
open var createdAt: Long,
open var isCollapsed: Boolean,
isDeleted: Boolean,
) : Model(id, isDeleted) {
sealed class Role(protected open val key: String) {
object Admin : Role("ADMIN")
object Member : Role("MEMBER")
object Guest : Role("GUEST")
data class Unknown(override val key: String) : Role(key)
object Invalid : Role("INVALID")
override fun toString() = key
companion object {
fun get(typeKey: String?): Role {
val upperCasedKey = typeKey?.uppercase()
return when {
upperCasedKey.isNullOrEmpty() -> Invalid
upperCasedKey == Admin.key -> Admin
upperCasedKey == Member.key -> Member
upperCasedKey == Guest.key -> Guest
else -> Unknown(typeKey)
}
}
}
}
companion object {
fun sanitizeName(name: String): String =
Sanitizers.WORKSPACE_NAME_INVALID_PATTERN.matcher(name.trim())
.replaceAll(Sanitizers.REPLACEMENT)
}
}
| mit | fa10244773705cad5a5c489ac860e8e9 | 29.265306 | 74 | 0.58058 | 4.72293 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/hide/CharacterHideCommand.kt | 1 | 4182 | /*
* Copyright 2022 Ren 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.command.character.hide
import com.rpkit.characters.bukkit.RPKCharactersBukkit
import com.rpkit.characters.bukkit.character.RPKCharacterService
import com.rpkit.characters.bukkit.character.field.HideableCharacterCardField
import com.rpkit.characters.bukkit.character.field.RPKCharacterCardFieldService
import com.rpkit.characters.bukkit.command.result.NoCharacterSelfFailure
import com.rpkit.core.command.RPKCommandExecutor
import com.rpkit.core.command.result.*
import com.rpkit.core.command.sender.RPKCommandSender
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.command.result.NotAPlayerFailure
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.completedFuture
/**
* Character hide command.
* Parent command for commands to hide different character card fields.
*/
class CharacterHideCommand(private val plugin: RPKCharactersBukkit) : RPKCommandExecutor {
override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<out CommandResult> {
if (args.isEmpty()) {
sender.sendMessage(plugin.messages.characterHideUsage)
return completedFuture(IncorrectUsageFailure())
}
if (sender !is RPKMinecraftProfile) {
sender.sendMessage(plugin.messages.notFromConsole)
return completedFuture(NotAPlayerFailure())
}
val fieldName = args.joinToString(" ")
val characterCardFieldService = Services[RPKCharacterCardFieldService::class.java]
if (characterCardFieldService == null) {
sender.sendMessage(plugin.messages.noCharacterCardFieldService)
return completedFuture(MissingServiceFailure(RPKCharacterCardFieldService::class.java))
}
val characterService= Services[RPKCharacterService::class.java]
if (characterService == null) {
sender.sendMessage(plugin.messages.noCharacterService)
return completedFuture(MissingServiceFailure(RPKCharacterService::class.java))
}
val field = characterCardFieldService.characterCardFields
.filterIsInstance<HideableCharacterCardField>()
.firstOrNull { it.name == fieldName }
if (field == null) {
sender.sendMessage(plugin.messages.characterHideInvalidField
.withParameters(
fields = characterCardFieldService.characterCardFields
.filterIsInstance<HideableCharacterCardField>()
)
)
return completedFuture(InvalidFieldFailure())
}
if (!sender.hasPermission("rpkit.characters.command.character.hide.${field.name}")) {
sender.sendMessage(plugin.messages.noPermissionCharacterHide.withParameters(field = field))
return completedFuture(NoPermissionFailure("rpkit.characters.command.character.hide.${field.name}"))
}
val character = characterService.getPreloadedActiveCharacter(sender)
if (character == null) {
sender.sendMessage(plugin.messages.noCharacter)
return completedFuture(NoCharacterSelfFailure())
}
return field.setHidden(character, true).thenApply {
sender.sendMessage(plugin.messages.characterHideValid.withParameters(field = field))
character.showCharacterCard(sender)
return@thenApply CommandSuccess
}
}
class InvalidFieldFailure : CommandFailure()
}
| apache-2.0 | b707b4d01faf880b971b22c5e618a5a5 | 45.988764 | 117 | 0.726925 | 5.150246 | false | false | false | false |
j-selby/kotgb | core/src/main/kotlin/net/jselby/kotgb/hw/ram/providers/Cartridge.kt | 1 | 6612 | package net.jselby.kotgb.hw.ram.providers
import net.jselby.kotgb.hw.ram.RAMProvider
import net.jselby.kotgb.utils.arrayToString
import net.jselby.kotgb.utils.toHex
/**
* A cartridge is where a game's ROM/other optional hardware is
* accessed from. This contains metadata, assets as well as the
* game itself.
*/
class Cartridge(val logger : (String) -> (Unit), val fileName : String, val memory : ByteArray) : RAMProvider() {
val name : String
get() = arrayToString(memory.copyOfRange(0x134, 0x134 + 16))
val type : CartridgeType
get() = CartridgeType.getById(memory[0x0147].toInt())!!
val romSize : Int
get() = romSizes[memory[0x148].toInt()]!!
val ramSize : Int
get() = ramSizes[memory[0x149].toInt()]!!
val romBankCount : Int
get() = romSize / (16 * 1024)
val ram : ByteArray
private var currentBank = 1
private var memoryMode = 0
init {
logger("Cartridge id: ${toHex(memory[0x0147].toInt())}")
logger ("Loaded cartridge \"$name\" of type $type") // info
if (romSize != memory.size) {
logger ("Incorrect file size for what was declared by ROM (declared $romSize bytes != file ${memory.size} bytes)") // warn
}
logger ("ROM size of $romSize bytes ($romBankCount banks)") // debug
ram = ByteArray(ramSize)
logger ("Allocation of Cartridge RAM (size ${ram.size} bytes) successful") // debug
}
override fun getByte(pointer: Long): Byte {
when(type) {
CartridgeType.ROM_ONLY -> {
return memory[pointer.toInt()]
}
CartridgeType.ROM_MBC1_RAM_BATT,
CartridgeType.ROM_MBC2_BATT,
CartridgeType.ROM_MBC3_RAM_BATT,
CartridgeType.ROM_MBC5_RAM_BATT,
CartridgeType.ROM_MBC1 -> {
if ((0x4000 .. 0x7FFF).contains(pointer)) {
if (currentBank == 0) {
logger ( "MBC: Attempted to read ROM bank 0 from high ROM!" ) // warn
return 0xFF.toByte()
}
// Make sure that it is in bounds
if (pointer.toInt() + (currentBank - 1) * 0x4000 >= memory.size) {
return 0xFF.toByte()
}
return memory[pointer.toInt() + (currentBank - 1) * 0x4000]
} else if ((0x0000 .. 0x3FFF).contains(pointer)) {
return memory[pointer.toInt()]
} else {
error("Unknown cart read: ${toHex(pointer, 4)}")
}
}
else -> {
error("Unimplemented cartridge read for $type")
}
}
}
override fun setByte(pointer: Long, value: Byte) {
when(type) {
CartridgeType.ROM_ONLY -> {
logger ( "Attempted to write to ROM only cartridge @ ${toHex(pointer)} = ${toHex(value)}. Ignoring." ) // warn
}
CartridgeType.ROM_MBC1_RAM_BATT,
CartridgeType.ROM_MBC5_RAM_BATT,
CartridgeType.ROM_MBC2_BATT,
CartridgeType.ROM_MBC1 -> {
if ((0x2000 .. 0x3FFF).contains(pointer)) {
currentBank = value.toInt() and 0b11111
if (currentBank < 1) {
currentBank = 1
}
} else if ((0x6000 .. 0x7FFF).contains(pointer)) {
logger ("MBC1: Switching memory models is not supported!") // warn
} else if ((0x0000 .. 0x1FFF).contains(pointer)) {
if (value.toInt() and 0x1111 == 0b1010) {
logger ( "STUB: Activating ROM bank: $pointer" ) // warn
} else {
logger ( "STUB: Disabling ROM bank: $pointer" ) // warn
}
} else {
logger ( "Attempted to write to ROM+MBC1 cartridge @ ${toHex(pointer)} = ${toHex(value)}." ) // warn
}
}
CartridgeType.ROM_MBC3_RAM_BATT -> {
if ((0x2000 .. 0x3FFF).contains(pointer)) {
currentBank = value.toInt() and 0b1111111
if (currentBank < 1) {
currentBank = 1
}
} else {
logger ("Attempted to write to ROM+MBC3+RAM+BATT cartridge @ ${toHex(pointer)} = ${toHex(value)}.") // warn
}
}
// TODO: Other cartridge types
else -> {
throw UnsupportedOperationException("Writing to cartridge @ ${toHex(pointer)} = ${toHex(value)}")
}
}
}
override fun getAbsoluteRange() = 0L .. (0x8000L - 1)
fun isBatteryAssured() = when(type) {
CartridgeType.ROM_ONLY,
CartridgeType.ROM_MBC1 -> false
CartridgeType.ROM_MBC1_RAM_BATT,
CartridgeType.ROM_MBC2_BATT,
CartridgeType.ROM_MBC3_RAM_BATT,
CartridgeType.ROM_MBC5_RAM_BATT -> true
}
}
/**6
* The type of a Cartridge.
*/
enum class CartridgeType(val id: Int) {
ROM_ONLY(0x00),
ROM_MBC1(0x01),
ROM_MBC1_RAM_BATT(0x03),
ROM_MBC2_BATT(0x06),
ROM_MBC3_RAM_BATT(0x13),
ROM_MBC5_RAM_BATT(0x1B);
companion object {
fun getById(id : Int): CartridgeType? {
for (value in values()) {
if (value.id == id) {
return value
}
}
// TODO: Fix this lack of logging
//logger("Failed to identify cartridge type: ${toHex(id, 2)}")
return null
}
}
}
private val romSizes = mapOf(
Pair(0, 32 * 1024), // 32 Kbyte
Pair(1, 64 * 1024), // 64 Kbyte
Pair(2, 128 * 1024), // 128 Kbyte
Pair(3, 256 * 1024), // 256 Kbyte
Pair(4, 512 * 1024), // 512 Kbyte
Pair(5, 1 * 1024 * 1024), // 1 Mbyte
Pair(6, 2 * 1024 * 1024), // 2 Mbyte
Pair(0x52, (1.1 * 1024 * 1024).toInt()), // 1.1 Mbyte
Pair(0x53, (1.2 * 1024 * 1024).toInt()), // 1.2 Mbyte
Pair(0x54, (1.5 * 1024 * 1024).toInt()) // 1.5 Mbyte
)
private val ramSizes = mapOf(
Pair(0, 0), // ROM only
Pair(1, 2 * 1024), // 2 Kbyte
Pair(2, 8 * 1024), // 8 Kbyte
Pair(3, 32 * 1024), // 32 Kbyte
Pair(4, 128 * 1024) // 128 Kbyte
) | mit | 444c4bec7ece00296976a92a17f6e421 | 35.944134 | 134 | 0.497731 | 3.758954 | false | false | false | false |
ethauvin/kobalt | src/test/kotlin/com/beust/kobalt/internal/InstallTest.kt | 2 | 1993 | package com.beust.kobalt.internal
import com.beust.kobalt.BaseTest
import com.beust.kobalt.BuildFile
import com.beust.kobalt.ProjectFile
import com.beust.kobalt.ProjectInfo
import com.beust.kobalt.app.BuildFileCompiler
import com.google.inject.Inject
import org.assertj.core.api.Assertions.assertThat
import org.testng.annotations.Test
import java.io.File
class InstallTest @Inject constructor(compilerFactory: BuildFileCompiler.IFactory) : BaseTest(compilerFactory) {
@Test(description = "Test that copy() and include() work properly")
fun shouldInstall() {
val from = from("testFile")
val to = to("installed")
val inc = include("a", "deployed2", "glob(\"**/*\")")
val install = """
install {
copy($from, $to)
$inc
}
""".trimIndent()
val bf = BuildFile(listOf("com.beust.kobalt.plugin.packaging.*"), install)
val testFileContent = "This should be in the file\n"
val cContent = "Nested file\n"
val files = listOf(ProjectFile("testFile", testFileContent),
ProjectFile("a/b/c", cContent))
val result = launchProject(ProjectInfo(bf, files), arrayOf("install"))
assertFile(result, "installed/testFile", testFileContent)
assertFile(result, "deployed2/b/c", cContent)
}
private fun toPath(s: String) = "\"\${project.directory}/$s\""
private fun from(path: String) = "from(" + toPath(path) + ")"
private fun to(path: String) = "to(" + toPath(path) + ")"
private fun include(s1: String, s2: String, s3: String) = "include(from(" + toPath(s1) + "), " +
"to(" + toPath(s2) + "), " + s3 + ")"
private fun assertFile(lpr: LaunchProjectResult, path: String, content: String) {
File(lpr.projectDescription.file.absolutePath, path).let { file ->
assertThat(file).exists()
assertThat(file.readText()).isEqualTo(content)
}
}
}
| apache-2.0 | ef3f98598eb69b1f8251e62499f26acf | 38.86 | 112 | 0.627697 | 3.946535 | false | true | false | false |
RichoDemus/kotlin-test | src/main/kotlin/demo/extension_functions/ExtensionFunctions.kt | 1 | 1205 | package demo.extension_functions
private fun Int.double(): Int = this * 2
// ----------------------------------------
private fun (() -> Unit).andHello() {
this()
println("Hello, world!")
}
private fun greet() {
println("Hey there!")
}
private fun greetAndHello() {
::greet.andHello()
}
private fun ((str: String) -> Unit).wat(arg: String) {
this(arg)
println("$arg is weird")
}
private fun methodThatTakesString(arg: String) {
println("Got the string $arg")
}
// ----------------------------------------
private fun String.addName() = "$this and Richo "
private fun String.separate() = this.split(" ")
private fun List<String>.join() = this.reduce { left, right -> "$left - $right" }
// ----------------------------------------
private fun <T, Y> T.map(func: (T) -> Y): Y = func.invoke(this)
// ----------------------------------------
fun main(args: Array<String>) {
println("2 doubled is ${2.double()}")
greetAndHello()
::methodThatTakesString.wat("geez")
println("First word".addName().separate().join())
println("hello".map { str -> str.toUpperCase() })
val message = 1.map { number -> "Your number is $number" }
println(message)
}
| apache-2.0 | 8271d41f0d8e6304869893ff1090b61a | 24.104167 | 81 | 0.538589 | 3.742236 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/util/ColorTransparentPixelsTask.kt | 1 | 3717 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor.util
import javafx.embed.swing.SwingFXUtils
import javafx.scene.image.Image
import javafx.scene.image.WritableImage
import javafx.scene.paint.Color
import java.io.File
import javax.imageio.ImageIO
private data class PixelWeight(val dx: Int, val dy: Int, val weight: Double)
private val orthWeight = 1.0
private val diagWeight = 0.5
private val weights = listOf(
PixelWeight(-1, 0, orthWeight),
PixelWeight(1, 0, orthWeight),
PixelWeight(0, -1, orthWeight),
PixelWeight(0, 1, orthWeight),
PixelWeight(-1, -1, diagWeight),
PixelWeight(1, -1, diagWeight),
PixelWeight(-1, 1, diagWeight),
PixelWeight(1, 1, diagWeight)
)
/**
* Changes the RGB values for transparent pixels, so that they match the RGB values of neighbouring pixels.
* A transparent pixel can have any RGB values, and still look the same (transparent!). However, due to the
* way that OpenGL renders images, the RGB values of these transparent pixel can "leak" into opaque pixels.
* This usually manifests as a white border around objects (especially when rotated). It is usually white,
* because many graphics programs set the RGB values to white for transparent pixels.
* This function fixes the problem by changing the RGB values of transparent pixels, so that they are a weighted
* average of the neighbouring RGB values.
*/
fun colorTransparentPixels(file: File) {
val image = Image(file.inputStream())
val width = image.width.toInt()
val height = image.height.toInt()
val reader = image.pixelReader
val dest = WritableImage(width, height)
val writer = dest.pixelWriter
fun averageColor(ox: Int, oy: Int): Color {
var rsum = 0.0
var gsum = 0.0
var bsum = 0.0
var divider = 0.0
weights.forEach { (dx, dy, weight) ->
val x = ox + dx
val y = oy + dy
if (x >= 0 && x < width && y >= 0 && y < height) {
val neighbour = reader.getColor(x, y)
val scale = weight * neighbour.opacity
rsum += neighbour.red * scale
gsum += neighbour.green * scale
bsum += neighbour.blue * scale
divider += scale
}
}
if (rsum > 0) {
return Color(rsum / divider, gsum / divider, bsum / divider, 0.0)
} else {
return Color.TRANSPARENT
}
}
for (y in 0..height - 1) {
for (x in 0..width - 1) {
val sourceColor = reader.getColor(x, y)
if (sourceColor.opacity == 0.0) {
// Transparent, so use the rgb values from surrounding pixels
writer.setColor(x, y, averageColor(x, y))
} else {
// At least slightly opaque, therefore just copy the color
writer.setColor(x, y, sourceColor)
}
}
}
val bufferedImage = SwingFXUtils.fromFXImage(image, null)
ImageIO.write(bufferedImage, "png", file)
}
| gpl-3.0 | 72cff7c4f57a4c447736e4a72326d804 | 35.087379 | 112 | 0.646758 | 4.098126 | false | false | false | false |
robedmo/vlc-android | vlc-android/src/org/videolan/vlc/gui/video/DisplayManager.kt | 1 | 6799 | package org.videolan.vlc.gui.video
import android.annotation.TargetApi
import android.app.Activity
import android.app.Presentation
import android.content.Context
import android.content.DialogInterface
import android.graphics.PixelFormat
import android.media.MediaRouter
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.Display
import android.view.SurfaceView
import android.view.WindowManager
import android.widget.FrameLayout
import org.videolan.libvlc.RendererItem
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.vlc.BuildConfig
import org.videolan.vlc.R
import org.videolan.vlc.RendererDelegate
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
class DisplayManager(private val activity: Activity, cloneMode: Boolean) : RendererDelegate.RendererPlayer {
enum class DisplayType { PRIMARY, PRESENTATION, RENDERER }
val displayType: DisplayType
// Presentation
private val mediaRouter: MediaRouter? by lazy { if (AndroidUtil.isJellyBeanMR1OrLater) activity.applicationContext.getSystemService(Context.MEDIA_ROUTER_SERVICE) as MediaRouter else null }
private var mediaRouterCallback: MediaRouter.SimpleCallback? = null
var presentation: SecondaryDisplay? = null
private var presentationDisplayId = -1
///Renderers
private var rendererItem: RendererItem? = null
val isPrimary: Boolean
get() = displayType == DisplayType.PRIMARY
val isOnRenderer: Boolean
get() = displayType == DisplayType.RENDERER
/**
* Listens for when presentations are dismissed.
*/
private val mOnDismissListener = DialogInterface.OnDismissListener { dialog ->
if (dialog == presentation) {
if (BuildConfig.DEBUG) Log.i(TAG, "Presentation was dismissed.")
presentation = null
presentationDisplayId = -1
}
}
init {
presentation = if (AndroidUtil.isJellyBeanMR1OrLater) createPresentation(cloneMode) else null
rendererItem = RendererDelegate.selectedRenderer
displayType = getCurrentType()
RendererDelegate.addPlayerListener(this)
}
companion object {
private val TAG = "VLC/DisplayManager"
}
fun release() {
if (displayType == DisplayType.PRESENTATION) {
presentation?.dismiss()
presentation = null
}
}
private fun updateDisplayType() {
if (getCurrentType() != displayType && activity is VideoPlayerActivity) activity.recreate()
}
private fun getCurrentType() = when {
presentationDisplayId != -1 -> DisplayType.PRESENTATION
rendererItem !== null -> DisplayType.RENDERER
else -> DisplayType.PRIMARY
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private fun createPresentation(cloneMode: Boolean): SecondaryDisplay? {
if (mediaRouter === null || cloneMode) return null
// Get the current route and its presentation display.
val route = mediaRouter?.getSelectedRoute(MediaRouter.ROUTE_TYPE_LIVE_VIDEO)
val presentationDisplay = route?.presentationDisplay
if (presentationDisplay !== null) {
// Show a new presentation if possible.
if (BuildConfig.DEBUG) Log.i(TAG, "Showing presentation on display: " + presentationDisplay)
val presentation = SecondaryDisplay(activity, presentationDisplay)
presentation.setOnDismissListener(mOnDismissListener)
try {
presentation.show()
presentationDisplayId = presentationDisplay.displayId
return presentation
} catch (ex: WindowManager.InvalidDisplayException) {
if (BuildConfig.DEBUG) Log.w(TAG, "Couldn't show presentation! Display was removed in " + "the meantime.", ex)
}
} else if (BuildConfig.DEBUG) Log.i(TAG, "No secondary display detected")
return null
}
/**
* Add or remove MediaRouter callbacks. This is provided for version targeting.
*
* @param add true to add, false to remove
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
fun mediaRouterAddCallback(add: Boolean) {
if (!AndroidUtil.isJellyBeanMR1OrLater || mediaRouter === null
|| add == (mediaRouterCallback !== null))
return
if (add) {
mediaRouterCallback = object : MediaRouter.SimpleCallback() {
override fun onRoutePresentationDisplayChanged(
router: MediaRouter, info: MediaRouter.RouteInfo) {
if (BuildConfig.DEBUG) Log.d(TAG, "onRoutePresentationDisplayChanged: info=" + info)
val newDisplayId = info.presentationDisplay?.displayId ?: -1
if (newDisplayId == presentationDisplayId) return
presentationDisplayId = newDisplayId
if (presentationDisplayId != -1) removePresentation() else updateDisplayType()
}
}
mediaRouter?.addCallback(MediaRouter.ROUTE_TYPE_LIVE_VIDEO, mediaRouterCallback)
} else {
mediaRouter?.removeCallback(mediaRouterCallback)
mediaRouterCallback = null
}
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private fun removePresentation() {
if (mediaRouter === null) return
// Dismiss the current presentation if the display has changed.
if (BuildConfig.DEBUG) Log.i(TAG, "Dismissing presentation because the current route no longer " + "has a presentation display.")
presentation?.dismiss()
presentation = null
updateDisplayType()
}
override fun onRendererChanged(renderer: RendererItem?) {
rendererItem = renderer
updateDisplayType()
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
class SecondaryDisplay(context: Context, display: Display) : Presentation(context, display) {
lateinit var surfaceView: SurfaceView
lateinit var subtitlesSurfaceView: SurfaceView
lateinit var surfaceFrame: FrameLayout
companion object {
val TAG = "VLC/SecondaryDisplay"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.player_remote)
surfaceView = findViewById(R.id.remote_player_surface)
subtitlesSurfaceView = findViewById(R.id.remote_subtitles_surface)
surfaceFrame = findViewById(R.id.remote_player_surface_frame)
subtitlesSurfaceView.setZOrderMediaOverlay(true)
subtitlesSurfaceView.holder.setFormat(PixelFormat.TRANSLUCENT)
if (BuildConfig.DEBUG) Log.i(TAG, "Secondary display created")
}
}
}
| gpl-2.0 | 247cb5dbbace896e504f410773490204 | 38.994118 | 192 | 0.676717 | 4.977306 | false | false | false | false |
darakeon/dfm | android/Lib/src/test/kotlin/com/darakeon/dfm/lib/api/entities/moves/DetailTest.kt | 1 | 852 | package com.darakeon.dfm.lib.api.entities.moves
import com.darakeon.dfm.testutils.BaseTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
class DetailTest: BaseTest() {
@Test
fun equals() {
val detail1 = Detail("desc", 1, 1.0)
val detail2 = Detail("desc", 1, 1.0)
assertEquals(detail1, detail2)
}
@Test
fun notEqualsBecauseOfDescription() {
val detail1 = Detail("desc", 1, 1.0)
val detail2 = Detail("desc_diff", 1, 1.0)
assertNotEquals(detail1, detail2)
}
@Test
fun notEqualsBecauseOfAmount() {
val detail1 = Detail("desc", 1, 1.0)
val detail2 = Detail("desc", 2, 1.0)
assertNotEquals(detail1, detail2)
}
@Test
fun notEqualsBecauseOfValue() {
val detail1 = Detail("desc", 1, 1.0)
val detail2 = Detail("desc", 1, 2.0)
assertNotEquals(detail1, detail2)
}
}
| gpl-3.0 | 4d54c9febbe9594a56233f2c0624fe40 | 20.3 | 47 | 0.699531 | 2.897959 | false | true | false | false |
chrsep/Kingfish | app/src/main/java/com/directdev/portal/models/FinanceModel.kt | 1 | 924 | package com.directdev.portal.models
import com.squareup.moshi.Json
import io.realm.RealmObject
open class FinanceModel(
@Json(name = "applied_amt")
open var paymentAmount: String = "N/A", //".0000"
@Json(name = "descr")
open var description: String = "N/A", //"Variable Tuition Fee"
@Json(name = "due_dt")
open var dueDate: String = "N/A", //"2016-09-28 00:00:00.000"
@Json(name = "item_amt")
open var chargeAmount: String = "N/A", //"5405000.0000"
@Json(name = "item_effective_dt")
open var postedDate: String = "N/A", //"2016-04-21 00:00:00.000"
@Json(name = "item_term")
open var term: String = "N/A", //"2016, Odd Semester"
@Json(name = "item_type")
open var type: String = "N/A", //"100020013050"
@Json(name = "item_type_cd")
open var typeId: String = "N/A" //"C"
) : RealmObject()
| gpl-3.0 | 4137151c71549ea00e74f944611937c9 | 29.8 | 72 | 0.570346 | 3.197232 | false | false | false | false |
ZhuoKeTeam/JueDiQiuSheng | app/src/main/java/cc/zkteam/juediqiusheng/module/category/Test.kt | 1 | 1889 | package cc.zkteam.juediqiusheng.module.category
/**
* Created by renxuelong on 17-10-27.
* Description:
*/
class Test {
fun main(args: Array<String>) {
// 变量
var x = 5
x += 1
// 常量
val a: Int = 1
val b = 2
val c: Int
c = 3
// 字符串
val sl = "a is $a"
// 条件
if (a > b) {
} else if (a < b) {
} else {
}
// 字符串
println("a=$a,b=$b,c=$c")
}
// 函数
fun sum(a: Int, b: Int): Int {
return a + b
}
// 表达式作为函数体
fun sum1(a: Int, b: Int) = a + b
// 定义返回值可空
fun parseInt(str: String): Int? {
return str.toIntOrNull()
}
fun printProduct(arg1: Any, arg2: String) {
// is 判断
if (arg1 is String) {
arg1.length
}
// 集合定义
val items = listOf("apple", "orange", "kiwi")
// 循环 in
for (i in items) {
}
for (index in items.indices) {
}
var index = 0
while (index < items.size) {
index += 1
}
val x = 10
for (x in 0..items.size) {
}
// in 判断
if (x in 0..items.size) {
}
// 步进
for (x in 1..items.size step 2) {
}
for (x in items.size downTo 0 step 2) {
}
// when 循环
when {
"orange" in items -> println("")
"apple" in items -> println("")
}
// 可能为空
val file: String? = null
// 如果不为空则执行
val length = file?.length
// 如果不为空执行。。。否则。。。
val length1 = file?.length ?: 10
// 如果为空则执行
val length2 = file?:10
}
} | bsd-3-clause | 56f1cda0600cd33d73e6b864ab2221a3 | 14.781818 | 53 | 0.402305 | 3.456175 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/meta/AboutActivity.kt | 1 | 2321 | package com.ghstudios.android.features.meta
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ghstudios.android.GenericActivity
import com.ghstudios.android.components.IconLabelTextCell
import com.ghstudios.android.components.TitleBarCell
import com.ghstudios.android.mhgendatabase.BuildConfig
import com.ghstudios.android.mhgendatabase.R
import com.ghstudios.android.mhgendatabase.databinding.FragmentAboutBinding
class AboutActivity : GenericActivity() {
override fun getSelectedSection() = 0
override fun createFragment(): androidx.fragment.app.Fragment {
return AboutFragment()
}
}
class AboutFragment : Fragment() {
private lateinit var binding: FragmentAboutBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
activity?.title = getString(R.string.about)
binding = FragmentAboutBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Set version string
val versionName = BuildConfig.VERSION_NAME
val titlebar = view.findViewById<TitleBarCell>(R.id.title)
titlebar.setAltTitleText(getString(R.string.about_version, versionName))
// Make the links clickable
activateLinks(binding.aboutLayout)
}
/**
* Recursive function to find all IconLabelTextCell entries and activate the links
* in tags or labels. Works recursively.
*/
private fun activateLinks(viewGroup: ViewGroup) {
for (i in 0..viewGroup.childCount) {
val child = viewGroup.getChildAt(i)
if (child is IconLabelTextCell) {
child.setOnClickListener {
val href = child.tag as? String
if (!href.isNullOrBlank()) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(href))
startActivity(intent)
}
}
} else if (child is ViewGroup) {
activateLinks(child) // recursive call
}
}
}
}
| mit | fcb59c6230e2ab7bbc1e68d647cd3c37 | 35.265625 | 116 | 0.682034 | 4.896624 | false | false | false | false |
jiangkang/KTools | app/src/main/java/com/jiangkang/ktools/widget/ThemeActivity.kt | 1 | 1321 | package com.jiangkang.ktools.widget
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jiangkang.ktools.R
import com.jiangkang.ktools.widget.TextAdapter.onItemClickListener
import com.jiangkang.tools.utils.ToastUtils
class ThemeActivity : AppCompatActivity() {
private val mRcTheme: RecyclerView by lazy { findViewById<RecyclerView>(R.id.rc_theme) }
private var mAdapter: TextAdapter? = null
private var mThemeList: List<String> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_theme)
initViews()
loadData()
bindDataToView()
}
private fun bindDataToView() {
mAdapter = TextAdapter(this, mThemeList)
mAdapter!!.setOnItemClickListener(object : onItemClickListener {
override fun onClick(holder: TextAdapter.ViewHolder?, position: Int) {
ToastUtils.showShortToast(position.toString())
}
})
mRcTheme.adapter = mAdapter
}
private fun loadData() {
}
private fun initViews() {
mRcTheme.layoutManager = LinearLayoutManager(this)
}
} | mit | 5cc2f70b58f5eccc1b52d14bef53666d | 29.744186 | 92 | 0.712339 | 4.892593 | false | false | false | false |
alxnns1/MobHunter | src/main/kotlin/com/alxnns1/mobhunter/item/MHConsumable.kt | 1 | 2142 | package com.alxnns1.mobhunter.item
import net.minecraft.advancements.CriteriaTriggers
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.ServerPlayerEntity
import net.minecraft.item.Item
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.item.UseAction
import net.minecraft.potion.EffectInstance
import net.minecraft.stats.Stats
import net.minecraft.util.ActionResult
import net.minecraft.util.DrinkHelper
import net.minecraft.util.Hand
import net.minecraft.world.World
class MHConsumable(properties: Properties, private val colour: Int, potionEffects: () -> Array<EffectInstance>) : Item(properties), MHITintItem {
private val potionEffects: Array<EffectInstance> by lazy(potionEffects)
override fun onItemUseFinish(stack: ItemStack, worldIn: World, entityLiving: LivingEntity): ItemStack? {
val playerEntity = if (entityLiving is PlayerEntity) entityLiving else null
if (playerEntity is ServerPlayerEntity) {
CriteriaTriggers.CONSUME_ITEM.trigger(playerEntity, stack)
}
if (!worldIn.isRemote) {
for (effectInstance in potionEffects) {
if (effectInstance.potion.isInstant) {
effectInstance.potion.affectEntity(playerEntity, playerEntity, entityLiving, effectInstance.amplifier, 1.0)
} else {
entityLiving.addPotionEffect(EffectInstance(effectInstance))
}
}
}
if (playerEntity != null) {
playerEntity.addStat(Stats.ITEM_USED[this])
if (!playerEntity.abilities.isCreativeMode) {
stack.shrink(1)
}
}
if (playerEntity == null || !playerEntity.abilities.isCreativeMode) {
if (stack.isEmpty) {
return ItemStack(Items.GLASS_BOTTLE)
}
playerEntity?.inventory?.addItemStackToInventory(ItemStack(Items.GLASS_BOTTLE))
}
return stack
}
override fun getUseDuration(stack: ItemStack?) = 32
override fun getUseAction(stack: ItemStack) = UseAction.DRINK
override fun onItemRightClick(worldIn: World, playerIn: PlayerEntity, handIn: Hand): ActionResult<ItemStack> =
DrinkHelper.startDrinking(worldIn, playerIn, handIn)
override fun getColour() = colour
} | gpl-2.0 | 0b088758908e37898a313c3f53684189 | 35.948276 | 145 | 0.782913 | 3.757895 | false | false | false | false |
nlefler/Glucloser | Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/dataSource/PumpDataFactory.kt | 1 | 1043 | package com.nlefler.glucloser.a.dataSource
import android.util.Log
import com.nlefler.glucloser.a.dataSource.sync.cairo.CairoServices
import com.nlefler.glucloser.a.dataSource.sync.cairo.services.CairoPumpService
import com.nlefler.glucloser.a.models.BolusPattern
import com.nlefler.glucloser.a.models.SensorReading
import rx.Observable
import java.util.*
import javax.inject.Inject
/**
* Created by nathan on 3/26/16.
*/
public class PumpDataFactory @Inject constructor(userServices: CairoServices) {
private val LOG_TAG = "PumpDataFactory"
private val pumpService = userServices.pumpService()
fun currentCarbRatios(uuid: String): Observable<BolusPattern> {
return pumpService.currentBolusPattern()
}
fun sensorReadingsAfter(date: Date): Observable<SensorReading> {
val cal = Calendar.getInstance()
cal.time = date
cal.add(Calendar.HOUR, 2)
val endDate = cal.time
return pumpService.cgmReadingsBetween(CairoPumpService.CGMReadingsBetweenBody(date, endDate))
}
}
| gpl-2.0 | 5169934db6e9a4cc6035f8a9722d55b4 | 31.59375 | 101 | 0.75743 | 3.906367 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/multiblocks/MainBlockComponent.kt | 2 | 1963 | package com.cout970.magneticraft.systems.multiblocks
import com.cout970.magneticraft.misc.i18n
import com.cout970.magneticraft.misc.prettyFormat
import com.cout970.magneticraft.misc.vector.plus
import net.minecraft.block.Block
import net.minecraft.block.state.IBlockState
import net.minecraft.item.ItemStack
import net.minecraft.util.math.BlockPos
import net.minecraft.util.text.ITextComponent
/**
* Created by cout970 on 20/08/2016.
*/
class MainBlockComponent(
val block: Block,
val getter: (context: MultiblockContext, activate: Boolean) -> IBlockState
) : IMultiblockComponent {
override fun checkBlock(relativePos: BlockPos, context: MultiblockContext): List<ITextComponent> {
val pos = context.center + relativePos
val state = context.world.getBlockState(pos)
if (state.block != block) {
val keyStr = "text.magneticraft.multiblock.invalid_block"
val vecStr = "[%d, %d, %d]".format(pos.x, pos.y, pos.z)
return listOf(keyStr.i18n(vecStr, state.prettyFormat(), block.localizedName))
}
return emptyList()
}
override fun getBlockData(relativePos: BlockPos, context: MultiblockContext): BlockData {
val pos = context.center + relativePos
val state = context.world.getBlockState(pos)
return BlockData(state, pos)
}
override fun activateBlock(relativePos: BlockPos, context: MultiblockContext) {
val pos = context.center + relativePos
context.world.setBlockState(pos, getter(context, true))
super.activateBlock(relativePos, context)
}
override fun deactivateBlock(relativePos: BlockPos, context: MultiblockContext) {
super.deactivateBlock(relativePos, context)
val pos = context.center + relativePos
context.world.setBlockState(pos, getter(context, false))
}
override fun getBlueprintBlocks(multiblock: Multiblock, blockPos: BlockPos): List<ItemStack> = listOf()
} | gpl-2.0 | 7b27c79965d89e105bf3ddb861eef4b2 | 38.28 | 107 | 0.718798 | 4.158898 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/integration-testing/src/main/kotlin/org/gradle/gradlebuild/test/integrationtests/DistributionTestingPlugin.kt | 1 | 6010 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.gradlebuild.test.integrationtests
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.file.Directory
import org.gradle.api.file.ProjectLayout
import org.gradle.api.invocation.Gradle
import org.gradle.api.plugins.BasePluginConvention
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.tasks.Sync
import org.gradle.kotlin.dsl.*
import accessors.base
import org.gradle.api.file.FileCollection
import org.gradle.api.model.ObjectFactory
import org.gradle.gradlebuild.packaging.ShadedJar
import org.gradle.gradlebuild.testing.integrationtests.cleanup.CleanUpDaemons
import org.gradle.internal.classloader.ClasspathHasher
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.kotlin.dsl.support.serviceOf
import kotlin.collections.set
import java.io.File
class DistributionTestingPlugin : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
tasks.withType<DistributionTest>().configureEach {
dependsOn(":toolingApi:toolingApiShadedJar")
dependsOn(":cleanUpCaches")
finalizedBy(":cleanUpDaemons")
shouldRunAfter("test")
setJvmArgsOfTestJvm()
setSystemPropertiesOfTestJVM(project)
configureGradleTestEnvironment(rootProject.providers, rootProject.layout, rootProject.base, rootProject.objects)
addSetUpAndTearDownActions(gradle)
}
}
private
fun DistributionTest.addSetUpAndTearDownActions(gradle: Gradle) {
lateinit var daemonListener: Any
// TODO Why don't we register with the test listener of the test task
// We would not need to do late configuration and need to add a global listener
// We now add multiple global listeners stepping on each other
doFirst {
// TODO Refactor to not reach into tasks of another project
val cleanUpDaemons: CleanUpDaemons by gradle.rootProject.tasks
daemonListener = cleanUpDaemons.newDaemonListener()
gradle.addListener(daemonListener)
}
// TODO Remove once we go to task specific listeners.
doLast {
gradle.removeListener(daemonListener)
}
}
private
fun DistributionTest.configureGradleTestEnvironment(providers: ProviderFactory, layout: ProjectLayout, basePluginConvention: BasePluginConvention, objects: ObjectFactory) {
val projectDirectory = layout.projectDirectory
// TODO: Replace this with something in the Gradle API to make this transition easier
fun dirWorkaround(directory: () -> File): Provider<Directory> = objects.directoryProperty().also {
it.set(projectDirectory.dir(providers.provider { directory().absolutePath }))
}
gradleInstallationForTest.apply {
val intTestImage: Sync by project.tasks
gradleUserHomeDir.set(projectDirectory.dir("intTestHomeDir"))
gradleGeneratedApiJarCacheDir.set(providers.provider {
projectDirectory.dir("intTestHomeDir/generatedApiJars/${project.version}/${project.name}-$classpathHash")
})
daemonRegistry.set(layout.buildDirectory.dir("daemon"))
gradleHomeDir.set(dirWorkaround { intTestImage.destinationDir })
toolingApiShadedJarDir.set(dirWorkaround {
// TODO Refactor to not reach into tasks of another project
val toolingApiShadedJar: ShadedJar by project.rootProject.project(":toolingApi").tasks
toolingApiShadedJar.jarFile.get().asFile.parentFile
})
}
libsRepository.dir.set(projectDirectory.dir("build/repo"))
binaryDistributions.apply {
distsDir.set(layout.buildDirectory.dir(basePluginConvention.distsDirName))
distZipVersion = project.version.toString()
}
}
private
val DistributionTest.classpathHash
get() = project.classPathHashOf(classpath)
private
fun Project.classPathHashOf(files: FileCollection) =
serviceOf<ClasspathHasher>().hash(DefaultClassPath.of(files))
private
fun DistributionTest.setJvmArgsOfTestJvm() {
jvmArgs("-Xmx512m", "-XX:+HeapDumpOnOutOfMemoryError")
if (!javaVersion.isJava8Compatible) {
jvmArgs("-XX:MaxPermSize=768m")
}
}
private
fun DistributionTest.setSystemPropertiesOfTestJVM(project: Project) {
// use -PtestVersions=all or -PtestVersions=1.2,1.3…
val integTestVersionsSysProp = "org.gradle.integtest.versions"
if (project.hasProperty("testVersions")) {
systemProperties[integTestVersionsSysProp] = project.property("testVersions")
} else {
if (integTestVersionsSysProp !in systemProperties) {
if (project.findProperty("testPartialVersions") == true) {
systemProperties[integTestVersionsSysProp] = "partial"
}
if (project.findProperty("testAllVersions") == true) {
systemProperties[integTestVersionsSysProp] = "all"
}
if (integTestVersionsSysProp !in systemProperties) {
systemProperties[integTestVersionsSysProp] = "default"
}
}
}
}
}
| apache-2.0 | 1cf40ce80fec296c59ac8f1f582b5b3a | 39.053333 | 176 | 0.693742 | 4.745656 | false | true | false | false |
spark/photon-tinker-android | meshui/src/main/java/io/particle/mesh/ui/controlpanel/ControlPanelCellularDataLimitFragment.kt | 1 | 4732 | package io.particle.mesh.ui.controlpanel
import android.R.color
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.fragment.app.FragmentActivity
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import io.particle.android.common.easyDiffUtilCallback
import io.particle.mesh.setup.flow.FlowRunnerUiListener
import io.particle.mesh.setup.utils.safeToast
import io.particle.mesh.ui.R
import io.particle.mesh.ui.TitleBarOptions
import io.particle.mesh.ui.controlpanel.DataLimitAdapter.DataLimitHolder
import io.particle.mesh.ui.inflateFragment
import io.particle.mesh.ui.inflateRow
import kotlinx.android.synthetic.main.controlpanel_row_data_limit.view.*
import kotlinx.android.synthetic.main.fragment_control_panel_cellular_data_limit.*
import kotlin.math.roundToInt
class ControlPanelCellularDataLimitFragment : BaseControlPanelFragment() {
override val titleBarOptions = TitleBarOptions(
R.string.p_controlpanel_datalimit_title,
showBackButton = true
)
private val limits: List<Int> = listOf(1, 2, 3, 5, 10, 20, 50, 100, 200, 500)
private lateinit var adapter: DataLimitAdapter
private var selectedLimit: Int? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return container?.inflateFragment(R.layout.fragment_control_panel_cellular_data_limit)
}
override fun onFragmentReady(activity: FragmentActivity, flowUiListener: FlowRunnerUiListener) {
super.onFragmentReady(activity, flowUiListener)
adapter = DataLimitAdapter(::onDataLimitItemClicked, activity)
adapter.currentDataLimit = flowUiListener.targetDevice.sim?.monthlyDataRateLimitInMBs
adapter.currentDataUsage = flowUiListener.targetDevice.dataUsedInMB?.roundToInt()
limits_list.adapter = adapter
adapter.submitList(limits)
action_change_data_limit.setOnClickListener { onChangeLimitClicked() }
}
private fun onDataLimitItemClicked(item: Int) {
selectedLimit = item
action_change_data_limit.isEnabled = true
}
private fun onChangeLimitClicked() {
flowUiListener?.cellular?.updateNewSelectedDataLimit(selectedLimit!!)
// FIXME: this is a hack. Look for a cleaner approach
if (flowUiListener?.cellular?.popOwnBackStackOnSelectingDataLimit == true) {
findNavController().popBackStack()
}
}
}
private class DataLimitAdapter(
private val itemClickedCallback: (Int) -> Unit,
private val everythingNeedsAContext: Context
) : ListAdapter<Int, DataLimitHolder>(
easyDiffUtilCallback { item: Int -> item }
) {
class DataLimitHolder(val root: View) : ViewHolder(root) {
val limitValue: TextView = root.limit_value
val checkbox: ImageView = root.selected_checkmark
}
var currentDataLimit: Int? = null
var currentDataUsage: Int? = null
var selectedDataLimit: Int? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DataLimitHolder {
return DataLimitHolder(parent.inflateRow(R.layout.controlpanel_row_data_limit))
}
override fun onBindViewHolder(holder: DataLimitHolder, position: Int) {
val item = getItem(position)
@SuppressLint("SetTextI18n")
holder.limitValue.text = "${item}MB"
when (item) {
currentDataLimit -> {
holder.checkbox.isVisible = true
holder.checkbox.setImageResource(R.drawable.ic_check_gray_24dp)
}
selectedDataLimit -> {
holder.checkbox.isVisible = true
holder.checkbox.setImageResource(R.drawable.ic_check_cyan_24dp)
}
else -> holder.checkbox.isVisible = false
}
val enableItem = item > (currentDataUsage?: 0)
holder.root.isEnabled = enableItem
val textColor = ContextCompat.getColor(
everythingNeedsAContext,
if (enableItem) color.black else R.color.p_faded_gray
)
holder.limitValue.setTextColor(textColor)
holder.root.setOnClickListener { onItemClicked(item) }
}
private fun onItemClicked(item: Int) {
selectedDataLimit = item
notifyDataSetChanged()
itemClickedCallback(item)
}
}
| apache-2.0 | a91af94b6d97d1d6107a24fd1969d413 | 34.051852 | 100 | 0.71978 | 4.580833 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/utils/IntentUtils.kt | 1 | 3484 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.utils
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.LabeledIntent
import android.os.Build
import android.os.Parcelable
import mozilla.components.support.utils.ext.queryIntentActivitiesCompat
object IntentUtils {
/**
* Since Android 12 we need to set PendingIntent mutability explicitly, but Android 6 can be the minimum version
* This additional requirement improves your app's security.
* FLAG_IMMUTABLE -> Flag indicating that the created PendingIntent should be immutable.
*/
val defaultIntentPendingFlags
get() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE
} else {
0 // No flags. Default behavior.
}
/**
* Method for creating an intent chooser but without the current app
*/
fun getIntentChooser(
context: Context,
intent: Intent,
chooserTitle: CharSequence? = null,
): Intent {
val chooserIntent: Intent
val resolveInfos = context.packageManager.queryIntentActivitiesCompat(intent, 0).toHashSet()
val excludedComponentNames = resolveInfos
.map { it.activityInfo }
.filter { it.packageName == context.packageName }
.map { ComponentName(it.packageName, it.name) }
// Starting with Android N we can use Intent.EXTRA_EXCLUDE_COMPONENTS to exclude components
// other way we are constrained to use Intent.EXTRA_INITIAL_INTENTS.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
chooserIntent = Intent.createChooser(intent, chooserTitle)
.putExtra(Intent.EXTRA_EXCLUDE_COMPONENTS, excludedComponentNames.toTypedArray())
} else {
var targetIntents = resolveInfos
.filterNot { it.activityInfo.packageName == context.packageName }
.map { resolveInfo ->
val activityInfo = resolveInfo.activityInfo
val targetIntent = Intent(intent).apply {
component = ComponentName(activityInfo.packageName, activityInfo.name)
}
LabeledIntent(
targetIntent,
activityInfo.packageName,
resolveInfo.labelRes,
resolveInfo.icon,
)
}
// Sometimes on Android M and below an empty chooser is displayed, problem reported also here
// https://issuetracker.google.com/issues/37085761
// To fix that we are creating a chooser with an empty intent
chooserIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent.createChooser(Intent(), chooserTitle)
} else {
targetIntents = targetIntents.toMutableList()
Intent.createChooser(targetIntents.removeAt(0), chooserTitle)
}
chooserIntent.putExtra(
Intent.EXTRA_INITIAL_INTENTS,
targetIntents.toTypedArray<Parcelable>(),
)
}
return chooserIntent
}
}
| mpl-2.0 | bd53c8edcec01bd3c0bb1a36202fe471 | 41.487805 | 116 | 0.627727 | 5.223388 | false | false | false | false |
Caellian/Math | src/main/kotlin/hr/caellian/math/vector/Vector.kt | 1 | 2851 | package hr.caellian.math.vector
import hr.caellian.math.internal.BufferConstructor
import hr.caellian.math.internal.DataWrapper
import hr.caellian.math.internal.Replicable
import hr.caellian.math.internal.TypeErasable
import hr.caellian.math.matrix.Matrix
import java.util.*
/**
* Generic Vector trait defined for stable code infrastructure and consistency.
* Most basic Vector variables and functions can be found here.
*
* @tparam T vector data type.
* @author Caellian
*/
abstract class Vector<T : Any> : Replicable<Vector<T>>, DataWrapper<Vector<T>, Array<T>>, TypeErasable<T>, Iterable<T>, BufferConstructor {
/**
* Size of this vector.
*/
val size: Int
get() = wrapped.size
/**
* @param index element return
*
* @return vector element at [index] position.
*/
operator fun get(index: Int): T = wrapped[index]
/**
* Vertical matrix containing data of this vector.
*/
abstract val verticalMatrix: Matrix<T>
/**
* Horizontal matrix containing data of this vector.
*/
abstract val horizontalMatrix: Matrix<T>
/**
* Returns an iterator over the elements of this object.
*/
override fun iterator() = VectorIterator(this)
/**
* Returns array containing vector data.
* Default implementation:
* <code>
* Array(size) { wrapped[it] }
* </code>
*
* @return array containing data of this vector.
*/
abstract fun toArray(): Array<T>
/**
* @return true if this vector is equal to other vector.
*/
override fun equals(other: Any?): Boolean {
if (other == null) {
return false
}
if (this === other) {
return true
}
if (other !is Vector<*>) {
return false
}
return wrapped contentDeepEquals other.wrapped
}
/**
* Vector hashcode depends on vector data and will change if vector data is modified!
*
* @return hashcode of this vector.
*/
override fun hashCode(): Int = Arrays.hashCode(wrapped)
/**
* @return string representation of this vector.
*/
override fun toString(): String = "(${wrapped.joinToString(", ")})"
/**
* Custom vector iterator class.
*
* @since 3.0.0
*/
class VectorIterator<T: Any>(private val parent: Vector<T>): Iterator<T> {
var pos = 0
/**
* Returns `true` if the iteration has more elements.
*/
override fun hasNext() = pos < parent.size
/**
* Returns the next element in the iteration.
*/
override fun next() = parent.wrapped[pos++]
/**
* Resets the iterator allowing it to be used again to reduce garbage.
*/
fun reset() {
pos = 0
}
}
} | mit | cdefcc65ea90cf508ba247f2d8d20439 | 24.927273 | 139 | 0.593827 | 4.359327 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/preferences/PreferenceAdapter.kt | 1 | 5283 | /*
* Copyright 2021, Lawnchair
*
* 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 app.lawnchair.preferences
import androidx.compose.runtime.*
import androidx.compose.ui.platform.LocalContext
import app.lawnchair.preferences2.IdpPreference
import app.lawnchair.preferences2.asState
import app.lawnchair.preferences2.firstBlocking
import com.android.launcher3.InvariantDeviceProfile
import com.patrykmichalik.opto.domain.Preference
import kotlinx.coroutines.launch
import kotlin.reflect.KProperty
interface PreferenceAdapter<T> {
val state: State<T>
fun onChange(newValue: T)
operator fun getValue(thisObj: Any?, property: KProperty<*>): T = state.value
operator fun setValue(thisObj: Any?, property: KProperty<*>, newValue: T) {
onChange(newValue)
}
}
private class MutableStatePreferenceAdapter<T>(
private val mutableState: MutableState<T>
) : PreferenceAdapter<T> {
override val state = mutableState
override fun onChange(newValue: T) {
mutableState.value = newValue
}
}
class PreferenceAdapterImpl<T>(
private val get: () -> T,
private val set: (T) -> Unit
) : PreferenceAdapter<T>, PreferenceChangeListener {
private val stateInternal = mutableStateOf(get())
override val state: State<T> get() = stateInternal
override fun onChange(newValue: T) {
set(newValue)
stateInternal.value = newValue
}
override fun onPreferenceChange() {
stateInternal.value = get()
}
}
private class StatePreferenceAdapter<T>(
override val state: State<T>,
private val set: (T) -> Unit
) : PreferenceAdapter<T> {
override fun onChange(newValue: T) {
set(newValue)
}
}
@Composable
fun BasePreferenceManager.IdpIntPref.getAdapter(): PreferenceAdapter<Int> {
val context = LocalContext.current
val idp = remember { InvariantDeviceProfile.INSTANCE.get(context) }
val defaultGrid = idp.closestProfile
return getAdapter(
this,
{ get(defaultGrid) },
{ newValue -> set(newValue, defaultGrid) }
)
}
@Composable
fun <T> PrefEntry<T>.getAdapter() = getAdapter(this, ::get, ::set)
@Composable
fun <T> PrefEntry<T>.getState() = getAdapter().state
@Composable
fun <T> PrefEntry<T>.observeAsState() = getAdapter().state
@Composable
private fun <P, T> getAdapter(
pref: PrefEntry<P>,
get: () -> T,
set: (T) -> Unit
): PreferenceAdapter<T> {
val adapter = remember { PreferenceAdapterImpl(get, set) }
DisposableEffect(pref) {
pref.addListener(adapter)
onDispose { pref.removeListener(adapter) }
}
return adapter
}
@Composable
fun <T> Preference<T, *, *>.getAdapter(): PreferenceAdapter<T> {
return createStateAdapter(state = asState(), set = this::set)
}
@Composable
fun IdpPreference.getAdapter(): PreferenceAdapter<Int> {
val context = LocalContext.current
val idp = remember { InvariantDeviceProfile.INSTANCE.get(context) }
val defaultGrid = idp.closestProfile
val state = get(defaultGrid).collectAsState(initial = firstBlocking(defaultGrid))
return createStateAdapter(state = state, set = { set(it, defaultGrid) })
}
@Composable
private fun <T> createStateAdapter(
state: State<T>,
set: suspend (T) -> Unit
) : PreferenceAdapter<T> {
val scope = rememberCoroutineScope()
return remember {
StatePreferenceAdapter(state) {
scope.launch { set(it) }
}
}
}
@Composable
fun <T, R> rememberTransformAdapter(
adapter: PreferenceAdapter<T>,
transformGet: (T) -> R,
transformSet: (R) -> T
): PreferenceAdapter<R> = remember(adapter) {
TransformPreferenceAdapter(adapter, transformGet, transformSet)
}
@Composable
fun <T> MutableState<T>.asPreferenceAdapter(): PreferenceAdapter<T> {
return remember(this) { MutableStatePreferenceAdapter(this) }
}
private class TransformPreferenceAdapter<T, R>(
private val parent: PreferenceAdapter<T>,
private val transformGet: (T) -> R,
private val transformSet: (R) -> T
) : PreferenceAdapter<R> {
override val state = derivedStateOf { transformGet(parent.state.value) }
override fun onChange(newValue: R) {
parent.onChange(transformSet(newValue))
}
}
@Composable
fun <T> customPreferenceAdapter(value: T, onValueChange: (T) -> Unit): PreferenceAdapter<T> {
val state = remember { mutableStateOf(value) }
state.value = value
return object : PreferenceAdapter<T> {
override val state = state
override fun onChange(newValue: T) {
onValueChange(newValue)
}
}
}
@Composable
operator fun PreferenceAdapter<Boolean>.not(): PreferenceAdapter<Boolean> {
return rememberTransformAdapter(adapter = this, transformGet = { !it }, transformSet = { !it })
}
| gpl-3.0 | d0c0116c3b3b1872a713dbef9ca3e3e3 | 28.513966 | 99 | 0.700738 | 4.01139 | false | false | false | false |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/logViewer/TimberEntryItemView.kt | 1 | 1278 | package com.garpr.android.features.logViewer
import android.content.Context
import android.util.AttributeSet
import android.util.SparseIntArray
import android.widget.LinearLayout
import com.garpr.android.R
import com.garpr.android.extensions.clear
import com.garpr.android.extensions.getAttrColor
import com.garpr.android.misc.Timber
import kotlinx.android.synthetic.main.item_timber_entry.view.*
class TimberEntryItemView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : LinearLayout(context, attrs) {
private val colors = SparseIntArray()
fun setContent(content: Timber.Entry) {
tagAndMessage.text = resources.getString(R.string.tag_and_message, content.tag,
content.msg)
if (content.stackTrace.isNullOrBlank()) {
stackTrace.clear()
stackTrace.visibility = GONE
} else {
stackTrace.text = content.stackTrace
stackTrace.visibility = VISIBLE
}
var color = colors.get(content.color, -1)
if (color == -1) {
color = context.getAttrColor(content.color)
colors.put(content.color, color)
}
tagAndMessage.setTextColor(color)
stackTrace.setTextColor(color)
}
}
| unlicense | 785fa8167314a5de9944d153215c2bc6 | 28.72093 | 87 | 0.683099 | 4.391753 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/core/stubs/index/RsNamedElementIndex.kt | 2 | 1717 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.stubs.index
import com.intellij.openapi.project.Project
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.stubs.StringStubIndexExtension
import com.intellij.psi.stubs.StubIndexKey
import org.rust.cargo.project.workspace.PackageOrigin
import org.rust.lang.core.psi.RsTraitItem
import org.rust.lang.core.psi.ext.RsNamedElement
import org.rust.lang.core.psi.ext.containingCargoPackage
import org.rust.lang.core.resolve.STD_DERIVABLE_TRAITS
import org.rust.lang.core.stubs.RsFileStub
import org.rust.lang.utils.findWithCache
import org.rust.lang.utils.getElements
class RsNamedElementIndex : StringStubIndexExtension<RsNamedElement>() {
override fun getVersion(): Int = RsFileStub.Type.stubVersion
override fun getKey(): StubIndexKey<String, RsNamedElement> = KEY
companion object {
val KEY: StubIndexKey<String, RsNamedElement> =
StubIndexKey.createIndexKey("org.rust.lang.core.stubs.index.RustNamedElementIndex")
fun findDerivableTraits(project: Project, target: String): Collection<RsTraitItem> =
findWithCache(project, target) {
val stdTrait = STD_DERIVABLE_TRAITS[target]
getElements(KEY, target, project, GlobalSearchScope.allScope(project))
.mapNotNull { it as? RsTraitItem }
.filter { e ->
if (stdTrait == null) return@filter true
e.containingCargoPackage?.origin == PackageOrigin.STDLIB && e.containingMod.modName == stdTrait.modName
}
}
}
}
| mit | fcff7c1a4d67bfd0b1b85921f72c5304 | 41.925 | 127 | 0.709377 | 4.380102 | false | false | false | false |
Fitbit/MvRx | todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/data/Task.kt | 1 | 505 | package com.airbnb.mvrx.todomvrx.data
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.UUID
@Entity(tableName = "tasks")
data class Task @JvmOverloads constructor(
@ColumnInfo(name = "title") var title: String = "",
@ColumnInfo(name = "description") var description: String = "",
@PrimaryKey @ColumnInfo(name = "id") var id: String = UUID.randomUUID().toString(),
@ColumnInfo(name = "complete") var complete: Boolean = false
)
| apache-2.0 | d47cdc9f44cfbb6f821a82cfcc4ed4cb | 35.071429 | 87 | 0.728713 | 3.945313 | false | false | false | false |
jtransc/jtransc | jtransc-gen-cpp/src/com/jtransc/gen/cpp/CppTarget.kt | 1 | 46002 | package com.jtransc.gen.cpp
import com.jtransc.ConfigOutputFile
import com.jtransc.ConfigTargetDirectory
import com.jtransc.annotation.*
import com.jtransc.ast.*
import com.jtransc.ast.feature.method.*
import com.jtransc.error.invalidOp
import com.jtransc.gen.GenTargetDescriptor
import com.jtransc.gen.TargetBuildTarget
import com.jtransc.gen.common.*
import com.jtransc.gen.cpp.libs.Libs
import com.jtransc.injector.Injector
import com.jtransc.injector.Singleton
import com.jtransc.io.ProcessResult2
import com.jtransc.plugin.finalizer.descendantList
import com.jtransc.text.Indenter
import com.jtransc.text.quote
import com.jtransc.text.toCommentString
import com.jtransc.text.uquote
import com.jtransc.vfs.ExecOptions
import com.jtransc.vfs.LocalVfs
import com.jtransc.vfs.LocalVfsEnsureDirs
import com.jtransc.vfs.SyncVfsFile
import java.io.File
import java.util.*
const val CHECK_ARRAYS = true
const val TRACING = false
const val TRACING_JUST_ENTER = false
data class ConfigCppOutput(val cppOutput: SyncVfsFile)
// @TODO: http://en.cppreference.com/w/cpp/language/eval_order
// @TODO: Use std::array to ensure it is deleted
class CppTarget : GenTargetDescriptor() {
override val name = "cpp"
override val outputExtension = "bin"
override val extraLibraries = listOf<String>()
override val extraClasses = listOf<String>()
override val runningAvailable: Boolean = true
override fun getGenerator(injector: Injector): CommonGenerator {
val settings = injector.get<AstBuildSettings>()
val configTargetDirectory = injector.get<ConfigTargetDirectory>()
val configOutputFile = injector.get<ConfigOutputFile>()
val targetFolder = LocalVfsEnsureDirs(File("${configTargetDirectory.targetDirectory}/jtransc-cpp"))
injector.mapInstance(CommonGenFolders(settings.assets.map { LocalVfs(it) }))
injector.mapInstance(ConfigTargetFolder(targetFolder))
injector.mapInstance(ConfigSrcFolder(targetFolder))
injector.mapInstance(ConfigOutputFile2(targetFolder[configOutputFile.outputFileBaseName].realfile))
return injector.get<CppGenerator>()
}
override val buildTargets: List<TargetBuildTarget> = listOf(
TargetBuildTarget("cpp", "cpp", "program.cpp", minimizeNames = false),
TargetBuildTarget("plainCpp", "cpp", "program.cpp", minimizeNames = false)
)
override fun getTargetByExtension(ext: String): String? = when (ext) {
"exe" -> "cpp"
"bin" -> "cpp"
else -> null
}
}
@Singleton
class CppGenerator(injector: Injector) : CommonGenerator(injector) {
override val TARGET_NAME: String = "CPP"
override val SINGLE_FILE: Boolean = true
override val GENERATE_LINE_NUMBERS = false
override val ARRAY_SUPPORT_SHORTCUTS = false
override val ARRAY_OPEN_SYMBOL = "{"
override val ARRAY_CLOSE_SYMBOL = "}"
// override val methodFeaturesWithTraps = setOf(SwitchFeature::class.java, UndeterministicParameterEvaluationFeature::class.java)
// override val methodFeatures = methodFeaturesWithTraps + setOf(GotosFeature::class.java)
override val methodFeaturesWithTraps = setOf(OptimizeFeature::class.java, SwitchFeature::class.java, SimdFeature::class.java, UndeterministicParameterEvaluationFeature::class.java)
override val methodFeatures = (methodFeaturesWithTraps + GotosFeature::class.java)
override val keywords = setOf(
"alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel", "atomic_commit", "atomic_noexcept", "auto",
"bitand", "bitor", "bool", "break",
"case", "catch", "char", "char16_t", "char32_t", "class", "compl", "concept", "const", "constexpr", "const_cast", "continue",
"decltype", "default", "delete", "do", "double", "dynamic_cast",
"else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend",
"goto", "if", "import", "inline", "int", "long",
"module", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr",
"operator", "or", "or_eq", "private", "protected", "public",
"register", "reinterpret_cast", "requires", "return",
"short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "synchronized",
"template", "this", "thread_local", "__GC_thread_local", "throw", "true", "try", "typedef", "typeid", "typename",
"union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while",
"xor", "xor_eq", "override", "final", "transaction_safe", "transaction_safe_dynamic",
// Macro
"if", "elif", "else", "endif", "defined", "ifdef", "ifndef",
"define", "undef", "include", "line", "error", "pragma", "_Pragma"
)
override val stringPoolType = StringPool.Type.GLOBAL
override val staticAccessOperator: String = "::"
override val instanceAccessOperator: String = "->"
override val allTargetLibraries by lazy { Libs.libs + super.allTargetLibraries }
override val allTargetDefines by lazy { Libs.extraDefines + super.allTargetDefines }
//override fun copyFilesExtra(output: SyncVfsFile) {
// output["CMakeLists.txt"] = Indenter {
// line("cmake_minimum_required(VERSION 2.8.9)")
// line("project (program)")
// line("add_executable(program program.cpp)")
// }
//}
override fun compile(): ProcessResult2 {
Libs.installIfRequired(program.resourcesVfs)
return super.compile()
}
//override fun escapedConstant(v: Any?): String = when (v) {
// null -> "((p_java_lang_Object)(null))"
// else -> super.escapedConstant(v)
//}
//override val AstType.nativeDefaultString: String get() = this.nativeDefault?.escapedConstant ?: "NULL"
override fun genCompilerCommand(programFile: File, debug: Boolean, libs: List<String>): List<String> {
return CppCompiler.genCommand(
//programFile = File(configOutputFile.output),
programFile = configTargetFolder.targetFolder[configOutputFile.output].realfile,
debug = settings.debug,
libs = allTargetLibraries,
includeFolders = Libs.includeFolders.map { it.absolutePath },
libsFolders = Libs.libFolders.map { it.absolutePath },
defines = allTargetDefines,
extraVars = extraVars
)
}
override fun run(redirect: Boolean, args: List<String>): ProcessResult2 {
val cmakeFolder = if (debugVersion) "Debug" else "Release"
//val names = listOf("bin/$cmakeFolder/program.exe", "bin/$cmakeFolder/program", "bin/$cmakeFolder/a", "bin/$cmakeFolder/a.out", "program", "a.exe", "a", "a.out")
val names = listOf("$cmakeFolder/program.exe", "$cmakeFolder/program", "$cmakeFolder/a", "$cmakeFolder/a.out", "program", "a.exe", "a", "a.out")
val outFile = names.map { configTargetFolder.targetFolder[it] }.firstOrNull { it.exists } ?: invalidOp("Not generated output file $names")
val result = LocalVfs(File(configTargetFolder.targetFolder.realpathOS)).exec(listOf(outFile.realpathOS) + args, options = ExecOptions(passthru = redirect, sysexec = false, fixLineEndings = true, fixencoding = false))
return ProcessResult2(result)
}
override val allowAssignItself = true
val lastClassId = program.classes.map { it.classId }.maxOrNull() ?: 0
fun generateTypeTableHeader() = Indenter {
line("struct TYPE_INFO", after2 = ";") {
line("const size_t size;")
line("const int32_t* subtypes;")
}
line("struct TYPE_TABLE { static const int32_t count; static const TYPE_INFO TABLE[$lastClassId]; };")
line("const TYPE_INFO TABLE_INFO_NULL = {1, new int32_t[1]{0}};")
}
fun generateTypeTableFooter() = Indenter {
val objectClassId = program["java.lang.Object".fqname].classId
for (clazz in ordereredClassesMustGenerate) {
val ids = clazz.getAllRelatedTypesIdsWith0AtEnd()
line("const TYPE_INFO ${clazz.cppName}::TABLE_INFO = { ${ids.size - 1}, new int32_t[${ids.size}]{${ids.joinToString(", ")}} };")
}
line("const int32_t TYPE_TABLE::count = $lastClassId;")
line("const TYPE_INFO TYPE_TABLE::TABLE[$lastClassId] =", after2 = ";") {
val classesById = program.classes.map { it.classId to it }.toMap()
@Suppress("LoopToCallChain")
for (n in 0 until lastClassId) {
val clazz = classesById[n]
if (clazz != null && clazz.mustGenerate) {
line("${clazz.cppName}::TABLE_INFO,")
} else if (n == 1) { // Special case for the array base class, which is also an object
line("{ 1, new int32_t[1]{$objectClassId} },")
} else {
line("TABLE_INFO_NULL,")
}
}
}
}
fun generateCppCtorMap() = Indenter {
line("typedef JAVA_OBJECT* (*ctor_func)(void);")
//line("const int32_t TYPE_TABLE::count = $lastClassId;")
line("static ctor_func CTOR_TABLE[$lastClassId] =", after2 = ";") {
val classesById = program.classes.map { it.classId to it }.toMap()
@Suppress("LoopToCallChain")
for (n in 0 until lastClassId) {
val clazz = classesById[n]
if (clazz != null && !clazz.mustGenerate) {
println("$n:" + clazz)
}
if (clazz != null && clazz.mustGenerate && !clazz.isAbstract && !clazz.isInterface) {
line("[](){return (JAVA_OBJECT*)(__GC_ALLOC<${clazz.cppName}>());},")
} else if (clazz != null && clazz.mustGenerate && (clazz.isAbstract || clazz.isInterface)) {
line("[](){ std::cerr << \"Class id \" << $n << \" refers to abstract class or interface!\"; abort(); return (JAVA_OBJECT*)(NULL);},")
} else if (n == 1) {
line("[](){ std::cerr << \"Class id \" << $n << \" refers to array base class!\"; abort(); return (JAVA_OBJECT*)(NULL);},")
} else {
line("[](){ std::cerr << \"Class id \" << $n << \" referred to a null clazz at compile time!\"; abort(); return (JAVA_OBJECT*)(NULL);},")
}
}
}
}
val ordereredClasses = Unit.let {
val childrenMap = hashMapOf<AstClass, ArrayList<AstClass>>()
for (current in program.classes) {
val parent = current.parentClass
if (parent != null) {
val list = childrenMap.getOrPut(parent) { arrayListOf() }
list += current
}
}
val out = LinkedHashSet<AstClass>()
fun explore(classes: List<AstClass>) {
if (classes.isNotEmpty()) {
for (clazz in classes) out += clazz
explore(classes.flatMap { childrenMap[it] ?: arrayListOf() }.filter { it !in out })
}
}
val roots = program.classes.filter { it.parentClass == null }
explore(roots)
out.toList()
}
val ordereredClassesMustGenerate by lazy { ordereredClasses.filter { it.mustGenerate } }
var prefixTempId = 0
val bodyPrefixes = arrayListOf<String>()
override fun resetLocalsPrefix() {
prefixTempId = 0
bodyPrefixes.clear()
}
override fun genLocalsPrefix(): Indenter = indent {
line(super.genLocalsPrefix())
for (prefix in bodyPrefixes) line(prefix)
}
val JAVA_LANG_STRING_FQ = AstType.REF("java.lang.String")
override fun genBodyTrapsPrefix(): Indenter = indent { line("p_java_lang_Object J__exception__ = (p_java_lang_Object)nullptr;") }
override fun genStmTryCatch(stm: AstStm.TRY_CATCH): Indenter = Indenter {
line("try") {
line(stm.trystm.genStm())
}
line("catch (p_java_lang_Object J__i__exception__)") {
line("J__exception__ = J__i__exception__;")
line(stm.catch.genStm())
}
}
fun Indenter.condWrapper(cond: String, callback: Indenter.() -> Unit) {
if (cond.isNotEmpty()) {
if (cond.startsWith("!")) line("#ifndef ${cond.substring(1)}") else line("#ifdef $cond")
indent {
callback()
}
line("#endif")
} else {
callback()
}
}
val StringInPool.cppName get() = "STRINGLIT[$id]"
override fun writeClasses(output: SyncVfsFile) {
val arrayTypes = listOf(
"JA_B" to "int8_t",
"JA_Z" to "int8_t",
"JA_S" to "int16_t",
"JA_C" to "uint16_t",
"JA_I" to "int32_t",
"JA_J" to "int64_t",
"JA_F" to "float",
"JA_D" to "double",
"JA_L" to "p_java_lang_Object"
)
this.params["CPP_LIB_FOLDERS"] = Libs.libFolders
this.params["CPP_INCLUDE_FOLDERS"] = Libs.includeFolders
this.params["CPP_LIBS"] = allTargetLibraries
this.params["CPP_INCLUDES"] = targetIncludes
this.params["CPP_DEFINES"] = allTargetDefines
this.params["CPP_GLOBAL_POINTERS"] = ordereredClasses.flatMap { it.fields.filter { it.isStatic } }.map { "&${it.containingClass.ref.targetName}::${it.ref.targetName}" }
val mainClassFq = program.entrypoint
entryPointClass = FqName(mainClassFq.fqname)
entryPointFilePath = entryPointClass.targetFilePath
val CLASS_REFERENCES = Indenter {
// {{ CLASS_REFERENCES }}
for (clazz in ordereredClassesMustGenerate) {
line(writeClassRef(clazz))
}
for (clazz in ordereredClassesMustGenerate) {
line(writeClassRefPtr(clazz))
}
}
val TYPE_TABLE_HEADERS = Indenter {
// {{ TYPE_TABLE_HEADERS }}
line(generateTypeTableHeader())
}
val ARRAY_TYPES = Indenter {
// {{ ARRAY_TYPES }}
for (name in arrayTypes.map { it.first }) line("struct $name;")
for (name in arrayTypes.map { it.first }) line("typedef $name* p_$name;")
}
val ARRAY_HEADERS_PRE = Indenter {
// {{ ARRAY_HEADERS }}
for (clazz in ordereredClasses.filter { !it.isNative }.filter { it.fqname == "java.lang.Object" }) {
line(writeClassHeader(clazz))
}
}
val ARRAY_HEADERS_POST = Indenter {
// {{ ARRAY_HEADERS }}
for (clazz in ordereredClasses.filter { !it.isNative }.filter { it.fqname != "java.lang.Object" }) {
line(writeClassHeader(clazz))
}
}
val impls = Indenter {
for (clazz in ordereredClasses.filter { !it.isNative }) {
if (clazz.implCode != null) {
line(clazz.implCode!!)
} else {
line(writeClassImpl(clazz))
}
}
}
val STRINGS = Indenter {
val globalStrings = getGlobalStrings()
val maxGlobalStrings = globalStrings.map { it.id }.maxOrNull()?.plus(1) ?: 0
line("__GC_thread_local static void* STRINGS_START = nullptr;")
line("__GC_thread_local static ${JAVA_LANG_STRING_FQ.targetNameRef} STRINGLIT[$maxGlobalStrings] = {0};")
line("__GC_thread_local static void* STRINGS_END = nullptr;")
line("void N::initStringPool()", after2 = ";") {
for (gs in globalStrings) {
line("""N_ADD_STRING(${gs.cppName}, L${gs.str.uquote()}, ${gs.str.length});""")
}
}
}
val CLASSES_IMPL = Indenter { line(impls) }
val CPP_CTOR_MAP = Indenter { line(generateCppCtorMap()) }
val TYPE_TABLE_FOOTER = Indenter { line(generateTypeTableFooter()) }
val MAIN = Indenter { line(writeMain()) }
this.params["CLASS_REFERENCES"] = CLASS_REFERENCES.toString()
this.params["TYPE_TABLE_HEADERS"] = TYPE_TABLE_HEADERS.toString()
this.params["ARRAY_TYPES"] = ARRAY_TYPES.toString()
this.params["ARRAY_HEADERS_PRE"] = ARRAY_HEADERS_PRE.toString()
this.params["ARRAY_HEADERS_POST"] = ARRAY_HEADERS_POST.toString()
this.params["CLASSES_IMPL"] = CLASSES_IMPL.toString()
this.params["CPP_CTOR_MAP"] = CPP_CTOR_MAP.toString()
this.params["STRINGS"] = STRINGS.toString()
this.params["TYPE_TABLE_FOOTER"] = TYPE_TABLE_FOOTER.toString()
this.params["MAIN"] = MAIN.toString()
val HEADER = Indenter {
// {{ HEADER }}
val resourcesVfs = program.resourcesVfs
for (clazz in program.classes) {
for (includes in clazz.annotationsList.getTypedList(JTranscAddHeaderList::value).filter { it.target == "cpp" }) {
condWrapper(includes.cond) {
for (header in includes.value) line(header)
}
}
for (files in clazz.annotationsList.getTypedList(JTranscAddFileList::value).filter { it.target == "cpp" }.filter { it.prepend.isNotEmpty() }) {
line(gen(resourcesVfs[files.prepend].readString(), process = files.process))
}
}
}
this.params["HEADER"] = HEADER.toString()
val classesIndenter = Indenter {
if (settings.debug) {
line("#define DEBUG 1")
} else {
line("#define RELEASE 1")
}
if (TRACING_JUST_ENTER) line("#define TRACING_JUST_ENTER")
if (TRACING) line("#define TRACING")
line(gen(program.resourcesVfs["cpp/Base.cpp"].readString(), extra = [email protected]))
}
output[outputFile] = classesIndenter.toString()
injector.mapInstance(ConfigCppOutput(output[outputFile]))
println(output[outputFile].realpathOS)
copyFiles(output)
}
val AstClass.cppName: String get() = this.name.targetName
val AstClass.cppNameRefCast: String get() = this.name.targetNameRef
override val FqName.targetNameRef: String get() = "p_" + this.targetName
val AstType.REF.cppName: String get() = this.name.targetName
fun writeMain(): Indenter = Indenter {
line("void N::staticInit()") {
line(genStaticConstructorsSorted())
}
line("int main(int argc, char *argv[])") {
line("""TRACE_REGISTER("::main");""")
line("__GC_REGISTER_THREAD();")
line("try") {
line("N::startup();")
val callMain = buildMethod(program[AstMethodRef(program.entrypoint, "main", AstType.METHOD(AstType.VOID, listOf(ARRAY(AstType.STRING))))]!!, static = true)
line("$callMain(N::strArray(argc, argv));")
}
line("catch (char const *s)") {
line("""std::cout << "ERROR char const*: '" << s << "'\n";""")
}
line("catch (wchar_t const *s)") {
line("""std::wcout << L"ERROR wchar_t const*: '" << s << L"'\n";""")
}
line("catch (std::wstring s)") {
line("""std::wcout << L"ERROR std::wstring: '" << s << L"'\n";""")
}
line("catch (java_lang_Object *s)") {
line("""std::wcout << L"${"java.lang.Throwable".fqname.targetName}:" << N::istr2(s) << L"\n";""")
}
//}
//line("catch (p_java_lang_Object s)") {
// val toStringMethod = program["java.lang.Object".fqname].getMethodWithoutOverrides("toString")!!.targetName
// line("""std::wcout << L"ERROR p_java_lang_Object " << N::istr2(s->$toStringMethod()) << L"\n";""")
//}
//line("catch (...)") {
// line("""std::wcout << L"ERROR unhandled unknown exception\n";""")
//}
line("return 0;")
}
}
fun writeClassRef(clazz: AstClass): Indenter = Indenter {
setCurrentClass(clazz)
line("struct ${clazz.cppName};")
}
fun writeClassRefPtr(clazz: AstClass): Indenter = Indenter {
setCurrentClass(clazz)
line("typedef ${clazz.cppName}* ${clazz.cppNameRefCast};")
}
fun writeClassHeader(clazz: AstClass): Indenter = Indenter {
setCurrentClass(clazz)
val directImplementing = clazz.allInterfacesInAncestors - (clazz.parentClass?.allInterfacesInAncestors ?: listOf())
val directExtendingAndImplementing = (clazz.parentClassList + directImplementing)
val parts = if (clazz.isInterface) {
""
//"public java_lang_Object"
} else if (clazz.fqname == "java.lang.Object") {
"public java_lang_ObjectBase"
} else {
directExtendingAndImplementing.map { "public ${it.cppName}" }.joinToString(", ")
}
line("struct ${clazz.cppName}${if (parts.isNotEmpty()) " : $parts " else " "} { public:")
indent {
if (!clazz.isInterface) {
line("std::wstring __GC_Name() { return L${clazz.cppName.quote()}; }")
line("virtual void __GC_Trace(__GCVisitor* visitor)") {
val parentClass = clazz.parentClass
if (parentClass != null) {
line("${parentClass.cppName}::__GC_Trace(visitor);")
}
for (field in clazz.fieldsInstance) {
if (field.type.isNotPrimitive()) {
line("visitor->Trace(${field.targetName});")
}
}
}
}
for (memberCond in clazz.nativeMembers) {
condWrapper(memberCond.cond) {
for (member in memberCond.members) {
line(member.replace("###", "").template("native members"))
}
}
}
if (clazz.fqname == "java.lang.Object") {
line("int32_t __JT__CLASS_ID;")
//line("SOBJ sptr() { return shared_from_this(); };")
}
for (field in clazz.fields) {
val normalStatic = if (field.isStatic) "__GC_thread_local static " else ""
val add = ""
val btype = field.type.targetNameRef
val type = if (btype == "SOBJ" && field.isWeak) "WOBJ" else btype
line("$normalStatic$type ${field.targetName}$add;")
}
val decl = if (clazz.parentClass != null) {
"${clazz.cppName}(int __JT__CLASS_ID = ${clazz.classId}) : ${clazz.parentClass?.cppName}(__JT__CLASS_ID)"
} else {
"${clazz.cppName}(int __JT__CLASS_ID = ${clazz.classId})"
}
line(decl) {
if (!clazz.isInterface) {
if (clazz.parentClass == null) {
line("this->__JT__CLASS_ID = __JT__CLASS_ID;")
}
for (field in clazz.fields.filter { !it.isStatic }) {
val cst = if (field.hasConstantValue) field.constantValue.escapedConstant else "0"
line("this->${field.targetName} = $cst;")
}
}
}
if (!clazz.isInterface) {
line("virtual void* __getInterface(int classId)") {
if (clazz.allInterfacesInAncestors.isNotEmpty()) {
line("switch (classId)") {
for (ifc in clazz.allInterfacesInAncestors) {
line("case ${ifc.classId}: return (void*)(${ifc.ref.targetNameRefCast})this;")
}
}
}
line("return nullptr;")
}
}
for (method in clazz.methods) {
val type = method.methodType
val argsString = type.args.map { it.type.targetNameRef + " " + it.name }.joinToString(", ")
val zero = if (clazz.isInterface && !method.isStatic) " = 0" else ""
val inlineNone = if (method.isInline) "inline " else ""
val virtualStatic = when {
method.isStatic -> "static "
method.isInstanceInit -> ""
else -> "virtual "
}
line("$inlineNone$virtualStatic${method.returnTypeWithThis.targetNameRef} ${method.targetName}($argsString)$zero;")
}
for (parentMethod in directImplementing.flatMap { it.methods }) {
val type = parentMethod.methodType
val returnStr = if (type.retVoid) "" else "return "
val argsString = type.args.map { it.type.targetNameRef + " " + it.name }.joinToString(", ")
val argsCallString = type.args.map { it.name }.joinToString(", ")
val callingMethod = clazz.getMethodInAncestors(parentMethod.ref.withoutClass)
if (callingMethod != null) {
line("virtual ${parentMethod.returnTypeWithThis.targetNameRef} ${parentMethod.targetName}($argsString) { $returnStr this->${callingMethod.targetName}($argsCallString); }")
}
}
line("static bool SI_once;")
line("static void SI();")
val ids = (clazz.thisAndAncestors + clazz.allInterfacesInAncestors).distinct().map { it.classId }.filterNotNull() + listOf(-1)
line("static const TYPE_INFO TABLE_INFO;")
//line("static ${clazz.cppName} *GET(java_lang_Object *obj);")
//line("static ${clazz.cppName} *GET_npe(java_lang_Object *obj, const wchar_t *location);")
}
line("};")
/*line("${clazz.cppName} *${clazz.cppName}::GET(java_lang_Object *obj)") {
line("return dynamic_cast<${clazz.cppName}*>(obj);")
}
line("${clazz.cppName} *${clazz.cppName}::GET_npe(java_lang_Object *obj, const wchar_t *location)") {
line("return dynamic_cast<${clazz.cppName}*>(obj);")
}*/
}
@Suppress("LoopToCallChain")
fun writeClassImpl(clazz: AstClass): Indenter = Indenter {
setCurrentClass(clazz)
for (field in clazz.fields) line(writeField(field))
for (method in clazz.methods) {
if (!clazz.isInterface || method.isStatic) {
try {
line(writeMethod(method))
} catch (e: Throwable) {
throw RuntimeException("Couldn't generate method $method for class $clazz due to ${e.message}", e)
}
}
}
for (memberCond in clazz.nativeMembers) {
condWrapper(memberCond.cond) {
for (member in memberCond.members) {
if (member.startsWith("static ")) {
line(member.replace("###", "${clazz.cppName}::").replace("static ", "").template("native members 2"))
}
}
}
}
line("void ${clazz.cppName}::SI() {")
indent {
line("""TRACE_REGISTER("${clazz.cppName}::SI");""")
for (field in clazz.fields.filter { it.isStatic }) {
val cst = if (field.hasConstantValue) field.constantValue.escapedConstant else field.type.nativeDefaultString
line("${clazz.cppName}::${field.targetName} = $cst;")
}
for (field in clazz.fields.filter { it.isStatic }) {
if (field.type.isNotPrimitive()) {
val fieldFullName = "${clazz.cppName}::${field.targetName}"
line("__GC_ADD_ROOT_NAMED(${fieldFullName.quote()}, &$fieldFullName);")
}
}
val sim = clazz.staticInitMethod
if (sim != null) {
line("${sim.targetName}();")
}
}
line("};")
}
fun writeField(field: AstField): Indenter = Indenter {
val clazz = field.containingClass
if (field.isStatic) {
line("__GC_thread_local ${field.type.targetNameRef} ${clazz.cppName}::${field.targetName} = ${field.type.nativeDefaultString};")
}
}
fun writeMethod(method: AstMethod): Indenter = Indenter {
val clazz = method.containingClass
val type = method.methodType
val argsString = type.args.map { it.type.targetNameRef + " " + it.name }.joinToString(", ")
line("${method.returnTypeWithThis.targetNameRef} ${clazz.cppName}::${method.targetName}($argsString)") {
if (method.name == "finalize") {
//line("""std::cout << "myfinalizer\n"; """);
}
if (!method.isStatic) {
//line("""SOBJ _this(this);""")
}
line("#ifdef TRACING")
line("""const wchar_t *FUNCTION_NAME = L"${method.containingClass.name}::${method.name}::${method.desc}";""")
line("""TRACE_REGISTER(FUNCTION_NAME);""")
line("#endif")
setCurrentMethod(method)
val body = method.body
fun genJavaBody() = Indenter {
if (body != null) {
line([email protected](method, body))
} else {
line("throw \"Empty BODY : ${method.containingClass.name}::${method.name}::${method.desc}\";")
}
}
val bodies = method.getNativeBodies("cpp")
val nonDefaultBodies = bodies.filterKeys { it != "" }
val defaultBody = bodies[""] ?: genJavaBody()
if (nonDefaultBodies.isNotEmpty()) {
for ((cond, nbody) in nonDefaultBodies) {
if (cond.startsWith("!")) line("#ifndef ${cond.substring(1)}") else line("#ifdef $cond")
indent {
line(nbody)
}
}
line("#else")
indent {
line(defaultBody)
}
line("#endif")
} else if (method.isNative && bodies.isEmpty() && method.name.startsWith("dooFoo")) {
line(genJniMethod(method))
} else {
line(defaultBody)
}
if (method.methodVoidReturnThis) line("return this;")
}
}
fun genJniMethod(method: AstMethod) = Indenter {
//if (method.isOverloaded) {
// mangledJniFunctionName = JniUtils.mangleLongJavaMethod(method);
//} else {
//val mangledJniFunctionName = JniUtils.mangleShortJavaMethod(method);
//}
val sb = StringBuilder(30)
for (i in method.methodType.args.indices) {
val arg = method.methodType.args[i]
sb.append(", ") // This seperates the arguments that are _always_ passed to jni from the other arguments
sb.append(toNativeType(arg.type))
}
val nativeParameterString = sb.toString()
var standardJniArgumentString = "JNIEnv*"
if (method.isStatic) standardJniArgumentString += ", jclass"
else standardJniArgumentString += ", jobject"
line("typedef ${toNativeType(method.methodType.ret)} (JNICALL *func_ptr_t)(${standardJniArgumentString + nativeParameterString});")
line("static void* nativePointer = nullptr;")
//{% CLASS ${method.containingClass.fqname} %}
line("func_ptr_t fptr = (func_ptr_t)DYN::jtvmResolveNative(N::resolveClass(L\"${method.containingClass.fqname}\"), \"${JniUtils.mangleShortJavaMethod(method)}\", \"${JniUtils.mangleLongJavaMethod(method)}\", &nativePointer);")
fun genJavaToJniCast(arg: AstType): String {
if (arg is AstType.REF) {
return "(${referenceToNativeType(arg)})"
} else if (arg is AstType.ARRAY) {
return "(${arrayToNativeType(arg)})"
} else {
return "";
}
}
fun genJniToJavaCast(arg: AstType): String {
return "(${arg.targetNameRef})"
}
val sb2 = StringBuilder(30)
for (i in method.methodType.args.indices) {
val arg = method.methodType.args[i].type
sb2.append(", ${genJavaToJniCast(arg)}p${i}")
}
line("return ${genJniToJavaCast(method.actualRetType)}fptr(N::getJniEnv(), NULL $sb2);")
//line("JNI: \"Empty BODY : ${method.containingClass.name}::${method.name}::${method.desc}\";")
}
private fun toNativeType(type: AstType): String {
when (type) {
is AstType.BOOL -> return "jboolean"
is AstType.BYTE -> return "jbyte"
is AstType.CHAR -> return "jchar"
is AstType.SHORT -> return "jshort"
is AstType.INT -> return "jint"
is AstType.LONG -> return "jlong"
is AstType.FLOAT -> return "jfloat"
is AstType.DOUBLE -> return "jdouble"
is AstType.REF -> return referenceToNativeType(type)
is AstType.ARRAY -> return arrayToNativeType(type)
AstType.VOID -> return "void"
else -> throw Exception("Encountered unrecognized type for JNI: ${type}")
}
}
private fun arrayToNativeType(type: AstType.ARRAY): String {
val arrayType = type.element
when (arrayType) {
is AstType.BOOL -> return "jbooleanArray"
is AstType.BYTE -> return "jbyteArray"
is AstType.CHAR -> return "jcharArray"
is AstType.SHORT -> return "jshortArray"
is AstType.INT -> return "jintArray"
is AstType.LONG -> return "jlongArray"
is AstType.FLOAT -> return "jfloatArray"
is AstType.DOUBLE -> return "jdoubleArray"
else -> return "jobjectArray"
}
}
private fun referenceToNativeType(type: AstType.REF): String {
val throwableClass = program.get("java.lang.Throwable".fqname.ref)
fun isThrowable(type: AstType.REF): Boolean {
val clazz = program.get(type)
if (clazz == throwableClass) return true
if (clazz == null) throw RuntimeException("Couldn't generate jni call because the class for reference ${clazz} is null")
return clazz.parentClassList.contains(throwableClass)
}
when {
type == AstType.STRING -> return "jstring"
type == AstType.CLASS -> return "jclass"
isThrowable(type) -> return "jthrowable"
else -> return "jobject"
}
}
override fun processCallArg(e: AstExpr, str: String, targetType: AstType) = doArgCast(targetType, str)
override fun genNew(className: String, commaArgs: String): String {
return "__GC_ALLOC<$className>($commaArgs)"
}
override val AstType.nativeDefaultString: String
get() {
if (this is AstType.REF) {
val clazz = program[this]!!
if (clazz.isNative) {
val nativeInfo = clazz.nativeNameInfo
if (nativeInfo != null && nativeInfo.defaultValue.isNotEmpty()) {
return nativeInfo.defaultValue
}
}
}
return this.nativeDefault.escapedConstant
}
override val AstLocal.decl: String get() = "${this.type.targetNameRef} ${this.targetName} = (${this.type.targetNameRef})${this.type.nativeDefaultString};"
override fun genExprArrayLength(e: AstExpr.ARRAY_LENGTH): String = "((JA_0*)${e.array.genNotNull()})->length"
override fun N_AGET_T(arrayType: AstType.ARRAY, elementType: AstType, array: String, index: String): String {
val getMethod = if (context.useUnsafeArrays) "get" else "fastGet"
return doCast(arrayType, array) + "->$getMethod($index)"
}
override fun N_ASET_T(arrayType: AstType.ARRAY, elementType: AstType, array: String, index: String, value: String): String {
val setMethod = if (context.useUnsafeArrays) "set" else "fastSet"
return doCast(arrayType, array) + "->$setMethod($index, $value)" + ";"
}
private fun doCast(target: AstType, expr: String, from: AstType? = null, npe: Boolean = true): String {
if (target is AstType.REF) {
return getPtr(program[target]!!, expr, npe = npe)
} else {
return "((${target.targetNameRefCast})($expr))"
}
}
private fun doArgCast(target: AstType, expr: String, from: AstType? = null): String {
return "((${target.targetNameRef})($expr))"
}
private fun getPtr(clazz: AstClass, objStr: String, npe: Boolean = true): String {
// http://www.cplusplus.com/doc/tutorial/typecasting/
if (objStr == "null" || objStr == "nullptr") {
return "(${clazz.cppNameRefCast})(nullptr)"
}
if (clazz.isInterface) {
if (npe) {
return "(dynamic_cast<${clazz.cppNameRefCast}>(N_ENSURE_NPE($objStr)))"
} else {
return "(dynamic_cast<${clazz.cppNameRefCast}>($objStr))"
}
} else {
if (clazz.name.targetName == JAVA_LANG_OBJECT) {
return "((p_java_lang_Object)($objStr))"
//return "($objStr)"
//return "(dynamic_cast<${clazz.cppNameRef}>(N_ENSURE_NPE($objStr)))"
} else {
if (npe) {
return "(static_cast<${clazz.cppNameRefCast}>(N_ENSURE_NPE($objStr)))"
} else {
return "(static_cast<${clazz.cppNameRefCast}>($objStr))"
}
}
//return "(static_cast<${clazz.cppNameRef}>(N_ENSURE_NPE($objStr)))"
//return "((${clazz.cppNameRef})(N_ENSURE_NPE($objStr)))"
}
}
private fun isThisOrThisWithCast(e: AstExpr): Boolean {
return when (e) {
is AstExpr.THIS -> true
is AstExpr.CAST -> if (e.to == this.mutableBody.method.containingClass.astType) {
isThisOrThisWithCast(e.subject.value)
} else {
false
}
else -> false
}
}
override fun genExprCallBaseInstance(e2: AstExpr.CALL_INSTANCE, clazz: AstType.REF, refMethodClass: AstClass, method: AstMethodRef, methodAccess: String, args: List<String>, isNativeCall: Boolean): String {
//return "((${refMethodClass.cppName}*)(${e2.obj.genNotNull()}.get()))$methodAccess(${args.joinToString(", ")})"
if (isThisOrThisWithCast(e2.obj.value)) {
return "this$methodAccess(${args.joinToString(", ")})"
} else {
val objStr = e2.obj.genNotNull()
return "${getPtr(refMethodClass, objStr)}$methodAccess(${args.joinToString(", ")})"
}
}
override fun genExprCallBaseSuper(e2: AstExpr.CALL_SUPER, clazz: AstType.REF, refMethodClass: AstClass, method: AstMethodRef, methodAccess: String, args: List<String>, isNativeCall: Boolean): String {
val superMethod = refMethodClass[method.withoutClass] ?: invalidOp("Can't find super for method : $method")
return "${refMethodClass.ref.cppName}::${superMethod.targetName}(${args.joinToString(", ")})"
}
override fun genExprThis(e: AstExpr.THIS): String = genExprThis()
fun genExprThis(): String = "this" //->sptr()"
override fun genExprMethodClass(e: AstExpr.INVOKE_DYNAMIC_METHOD): String = "N::dummyMethodClass()"
override val AstType.targetNameRef: String
get() {
if (this is AstType.Reference) {
if (this is AstType.REF) {
val clazz = program[this]!!
val nativeName = clazz.nativeName
if (nativeName != null) {
return nativeName
}
}
return "p_java_lang_Object"
} else {
return getTypeTargetName(this, ref = true)
}
}
val AstType.targetNameRefCast: String get() = getTypeTargetName(this, ref = true)
//override val AstType.targetNameRefBounds: String get() {
// return if (this is AstType.Reference) {
// "p_java_lang_Object"
// } else {
// getTypeTargetName(this, ref = true)
// }
//}
override fun genBody2WithFeatures(method: AstMethod, body: AstBody): Indenter = Indenter {
if (method.isSynchronized) {
//line("SynchronizedMethodLocker __locker(" + getMonitorLockedObjectExpr(method).genExpr() + ");")
line("" + getMonitorLockedObjectExpr(method).genExpr() + ";")
}
line(genBody2WithFeatures2(method, body))
}
override fun N_i2b(str: String) = "((int8_t)($str))"
override fun N_i2c(str: String) = "((uint16_t)($str))"
override fun N_i2s(str: String) = "((int16_t)($str))"
override fun N_f2i(str: String) = "N::f2i($str)"
override fun N_d2i(str: String) = "N::d2i($str)"
override fun N_i2f(str: String) = "((float)($str))"
override fun N_i2d(str: String) = "((double)($str))"
override fun N_j2f(str: String) = "((float)($str))"
override fun N_j2d(str: String) = "((double)($str))"
//override fun N_i(str: String) = "((int32_t)($str))"
override fun N_i(str: String) = str
override fun N_idiv(l: String, r: String) = N_func("idiv", "$l, $r")
override fun N_irem(l: String, r: String) = N_func("irem", "$l, $r")
override fun N_ishl(l: String, r: String) = N_func("ishl", "$l, $r")
override fun N_ishr(l: String, r: String) = N_func("ishr", "$l, $r")
override fun N_iushr(l: String, r: String) = N_func("iushr", "$l, $r")
override fun N_ishl_cst(l: String, r: Int) = N_func("ishl_cst", "$l, $r")
override fun N_ishr_cst(l: String, r: Int) = N_func("ishr_cst", "$l, $r")
override fun N_iushr_cst(l: String, r: Int) = N_func("iushr_cst", "$l, $r")
override fun N_lshl_cst(l: String, r: Int) = N_func("lshl_cst", "$l, $r")
override fun N_lshr_cst(l: String, r: Int) = N_func("lshr_cst", "$l, $r")
override fun N_lushr_cst(l: String, r: Int) = N_func("lushr_cst", "$l, $r")
override fun N_frem(l: String, r: String) = "::fmod($l, $r)"
override fun N_drem(l: String, r: String) = "::fmod($l, $r)"
override fun N_lneg(str: String) = "(-($str))"
override fun N_linv(str: String) = "(~($str))"
override fun N_ladd(l: String, r: String) = "(($l) + ($r))"
override fun N_lsub(l: String, r: String) = "(($l) - ($r))"
override fun N_lmul(l: String, r: String) = "(($l) * ($r))"
override fun N_ldiv(l: String, r: String) = "N::ldiv($l, $r)"
override fun N_lrem(l: String, r: String) = "N::lrem($l, $r)"
override fun N_lshl(l: String, r: String) = N_func("lshl", "$l, $r")
override fun N_lshr(l: String, r: String) = N_func("lshr", "$l, $r")
override fun N_lushr(l: String, r: String) = N_func("lushr", "$l, $r")
override fun N_lor(l: String, r: String) = "(($l) | ($r))"
override fun N_lxor(l: String, r: String) = "(($l) ^ ($r))"
override fun N_land(l: String, r: String) = "(($l) & ($r))"
override fun N_obj_eq(l: String, r: String) = "(($l) == ($r))"
override fun N_obj_ne(l: String, r: String) = "(($l) != ($r))"
override fun genStmSetFieldStaticActual(stm: AstStm.SET_FIELD_STATIC, left: String, field: AstFieldRef, right: String): Indenter = indent {
line("${__GC_SET_FIELD_ANY(stm.field.type)}($left, (${field.type.targetNameRef})($right));")
}
override fun genStmReturnVoid(stm: AstStm.RETURN_VOID, last: Boolean): Indenter = Indenter {
line(if (context.method.methodVoidReturnThis) "return " + genExprThis() + ";" else "return;")
}
override fun genStmReturnValue(stm: AstStm.RETURN, last: Boolean): Indenter = Indenter {
line("return (${context.method.returnTypeWithThis.targetNameRef})${stm.retval.genExpr()};")
}
override fun N_is(a: String, b: AstType.Reference): String = when (b) {
is AstType.REF -> {
val clazz = program[b.name]
val ids = clazz.getAllRelatedTypes() + clazz.descendantList.toSet()
//if (!clazz.isInterface && clazz.isFinal && ids.size <= 7) {
if (!clazz.isInterface && ids.size <= 7) {
N_func("isFast", "($a), ${ids.map { it.classId }.joinToString(", ")}")
} else {
N_func("is", "($a), ${clazz.classId}")
}
}
is AstType.ARRAY -> N_func("isArray", "($a), L${b.mangle().quote()}")
else -> N_func("isUnknown", """$a, "Unsupported $b"""")
}
override fun genExprFieldInstanceAccess(e: AstExpr.FIELD_INSTANCE_ACCESS): String {
if (isThisOrThisWithCast(e.expr.value)) {
return buildInstanceField("this", fixField(e.field))
} else {
return buildInstanceField(doCast(e.field.containingTypeRef, e.expr.genNotNull()), fixField(e.field))
}
}
override fun actualSetField(stm: AstStm.SET_FIELD_INSTANCE, left: String, right: String): String {
val left1 = if (stm.left.value is AstExpr.THIS) {
"this"
} else {
doCast(stm.field.containingTypeRef, stm.left.genNotNull())
}
val left2 = buildInstanceField(left1, fixField(stm.field))
val right2 = "(${stm.field.type.targetNameRef})((${stm.field.type.targetNameRef})(" + stm.expr.genExpr() + "))"
return "${__GC_SET_FIELD_ANY(stm.field.type)}((__GC*)($left1), $left2, $right2);"
}
fun __GC_SET_FIELD_ANY(type: AstType): String {
if (type is AstType.REF) {
if (program[type]!!.nativeNameInfo != null) return "__GC_SET_FIELD"
}
return if (type.isPrimitive()) "__GC_SET_FIELD" else "__GC_SET_FIELD_OBJ"
}
//fun __GC_SET_FIELD_ANY(type: AstType): String = "__GC_SET_FIELD"
override fun actualSetLocal(stm: AstStm.SET_LOCAL, localName: String, exprStr: String): String {
return "$localName = (${stm.local.type.targetNameRef})($exprStr);"
}
override fun genExprIntArrayLit(e: AstExpr.INTARRAY_LITERAL): String {
val ints = e.values.joinToString(",")
if (e.values.size <= 4) {
return "JA_I::fromArgValues($ints)"
} else {
val id = prefixTempId++
val tempname = "arraylit_$id"
bodyPrefixes += "int32_t $tempname[] = {$ints};"
return "JA_I::fromVector($tempname, ${e.values.size})"
}
}
//override fun genExprObjectArrayLit(e: AstExpr.OBJECTARRAY_LITERAL): String {
// noImpl("C++ genExprStringArrayLit")
//}
override fun createArraySingle(e: AstExpr.NEW_ARRAY, desc: String): String {
return if (e.type.elementType !is AstType.Primitive) {
"__GC_ALLOC_$ObjectArrayType(${e.counts[0].genExpr()}, L\"$desc\")"
} else {
"__GC_ALLOC_${e.type.targetName}(${e.counts[0].genExpr()})"
}
}
override fun createArrayMultisure(e: AstExpr.NEW_ARRAY, desc: String): String {
return "$ObjectArrayType${staticAccessOperator}createMultiSure(L\"$desc\", { ${e.counts.map { it.genExpr() }.joinToString(", ")} } )"
}
override fun genStmRawTry(trap: AstTrap): Indenter = Indenter {
//line("try {")
//_indent()
}
override fun genStmRawCatch(trap: AstTrap): Indenter = Indenter {
//_unindent()
//line("} catch (SOBJ e) {")
//indent {
// line("if (N::is(e, ${getClassId(trap.exception.name)})) goto ${trap.handler.name};")
// line("throw e;")
//}
//line("}")
}
override fun genStmSetArrayLiterals(stm: AstStm.SET_ARRAY_LITERALS) = Indenter {
val values = stm.values.map { it.genExpr() }
line("") {
line("const ${stm.array.type.elementType.targetNameRef} ARRAY_LITERAL[${values.size}] = { ${values.joinToString(", ")} };")
line(doCast(stm.array.type, stm.array.genExpr()) + "->setArray(${stm.startIndex}, ${values.size}, ARRAY_LITERAL);")
}
}
//override val MethodRef.targetName: String get() {
// return getClassNameAllocator(ref.containingClass).allocate(ref) {
// val astMethod = program[ref]!!
// val containingClass = astMethod.containingClass
//
// val prefix = if (containingClass.isInterface) "I_" else if (astMethod.isStatic) "S_" else "M_"
// val prefix2 = if (containingClass.isInterface || ref.isClassOrInstanceInit) "${containingClass.name.targetName}_" else ""
//
// "$prefix$prefix2${super.targetName}_" + normalizeName(astMethod.methodType.mangle())
// }
//}
override fun access(name: String, static: Boolean, field: Boolean): String = if (static) "::$name" else "->$name"
override val NullType = "p_java_lang_Object"
override val VoidType = "void"
override val BoolType = "int8_t"
override val IntType = "int32_t"
override val ShortType = "int16_t"
override val CharType = "uint16_t"
override val ByteType = "int8_t"
override val FloatType = "float"
override val DoubleType = "double"
override val LongType = "int64_t"
override val BaseArrayTypeRef = "p_JA_0"
override val BoolArrayTypeRef = "p_JA_Z"
override val ByteArrayTypeRef = "p_JA_B"
override val CharArrayTypeRef = "p_JA_C"
override val ShortArrayTypeRef = "p_JA_S"
override val IntArrayTypeRef = "p_JA_I"
override val LongArrayTypeRef = "p_JA_J"
override val FloatArrayTypeRef = "p_JA_F"
override val DoubleArrayTypeRef = "p_JA_D"
override val ObjectArrayTypeRef = "p_JA_L"
//override val FieldRef.targetName: String get() {
// val fieldRef = this
// val ref = fieldRef.ref
// return getClassNameAllocator(ref.containingClass).allocate(ref) { "F_" + normalizeName(ref.name + "_" + ref.type.mangle()) }
//}
override val DoubleNegativeInfinityString = "-N::INFINITY_DOUBLE"
override val DoublePositiveInfinityString = "N::INFINITY_DOUBLE"
override val DoubleNanString = "N::NAN_DOUBLE"
override val FloatNegativeInfinityString = "-N::INFINITY_FLOAT"
override val FloatPositiveInfinityString = "N::INFINITY_FLOAT"
override val FloatNanString = "N::NAN_FLOAT"
override val String.escapeString: String get() = "STRINGLIT[${allocString(currentClass, this)}]${this.toCommentString()}"
override val AstType.escapeType: String get() = N_func("resolveClass", "L${this.mangle().uquote()}")
override fun pquote(str: String): String = "L" + str.uquote()
override fun N_lnew(value: Long): String {
if (value == Long.MIN_VALUE) {
//return "(int64_t)(0x8000000000000000L"
return "(int64_t)(-${Long.MAX_VALUE}LL - 1)"
} else {
return "(int64_t)(${value}LL)"
}
}
override val FieldRef.targetName: String get() = getNativeName(this)
override val MethodRef.targetNameBase: String
get() {
val method = this
return getClassNameAllocator(method.ref.containingClass).allocate(method.ref) {
val astMethod = program[method.ref]!!
val containingClass = astMethod.containingClass
val prefix = if (containingClass.isInterface) "I_" else if (astMethod.isStatic) "S_" else "M_"
val prefix2 = if (containingClass.isInterface || method.ref.isClassOrInstanceInit) {
//getClassFqNameForCalling(containingClass.name) + "_"
containingClass.name.fqname + "_"
} else {
""
}
val suffix = "_${astMethod.name}${astMethod.desc}"
//"$prefix$prefix2" + super.getNativeName(method) + "$suffix"
"$prefix$prefix2$suffix"
}
}
fun getNativeName(field: FieldRef): String {
val clazz = field.ref.getClass(program)
val actualField = clazz[field.ref]
return getClassNameAllocator(actualField.ref.containingClass).allocate(actualField.ref) { "F_" + normalizeName(actualField.ref.name + "_" + clazz.fqname + "_" + actualField.ref.type.mangle(), NameKind.FIELD) }
}
override val AstMethodRef.objectToCache: Any get() = this
override fun buildStaticInit(clazzName: FqName): String? = null
override fun escapedConstant(v: Any?, place: ConstantPlace): String = when (v) {
null -> "nullptr"
else -> super.escapedConstant(v, place)
}
override fun genExprCastChecked(e: String, from: AstType.Reference, to: AstType.Reference): String {
if (from == to) return e;
if (from is AstType.NULL) return e
if (from is AstType.Reference && to is AstType.REF) {
val toCls = program[to]!!
if (toCls.isInterface) {
return "(N::CC_CHECK_UNTYPED($e, ${toCls.classId}))"
//return e
} else {
return "(N::CC_CHECK_CLASS<${getTypeTargetName(to, ref = true)}>($e, ${toCls.classId}))"
//return e
}
//}
}
return "(N::CC_CHECK_GENERIC<${getTypeTargetName(to, ref = true)}>($e))"
//return e
}
override fun genStmMonitorEnter(stm: AstStm.MONITOR_ENTER) = Indenter("N::monitorEnter(" + stm.expr.genExpr() + ");")
override fun genStmMonitorExit(stm: AstStm.MONITOR_EXIT) = Indenter("N::monitorExit(" + stm.expr.genExpr() + ");")
}
| apache-2.0 | 29fbd3cd6a57b072a546281be5eb6012 | 36.460912 | 228 | 0.665928 | 3.220752 | false | false | false | false |
ItsPriyesh/chroma | chroma/src/main/kotlin/me/priyesh/chroma/chroma.kt | 1 | 884 | package me.priyesh.chroma
import android.content.Context
import android.graphics.Color
import android.util.DisplayMetrics
import android.view.WindowManager
internal fun screenDimensions(context: Context): DisplayMetrics {
val manager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val metrics = DisplayMetrics()
manager.defaultDisplay.getMetrics(metrics)
return metrics
}
internal fun orientation(context: Context) = context.resources.configuration.orientation
internal infix fun Int.percentOf(n: Int): Int = (n * (this / 100.0)).toInt()
fun hue(color: Int): Int = hsv(color, 0)
fun saturation(color: Int): Int = hsv(color, 1, 100)
fun value(color: Int): Int = hsv(color, 2, 100)
private fun hsv(color: Int, index: Int, multiplier: Int = 1): Int {
val hsv = FloatArray(3)
Color.colorToHSV(color, hsv)
return (hsv[index] * multiplier).toInt()
} | apache-2.0 | 588e5e49630759ddc2c3706eaf89a160 | 31.777778 | 88 | 0.754525 | 3.698745 | false | false | false | false |
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/ui/fragments/StickerFragment.kt | 1 | 10160 | package nl.ecci.hamers.ui.fragments
import android.Manifest
import android.app.AlertDialog
import android.content.pm.PackageManager
import android.location.Location
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.Toast
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationListener
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.Marker
import com.google.android.gms.maps.model.MarkerOptions
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_sticker.*
import nl.ecci.hamers.R
import nl.ecci.hamers.data.GetCallback
import nl.ecci.hamers.data.Loader
import nl.ecci.hamers.models.Sticker
import nl.ecci.hamers.utils.PermissionUtils
import nl.ecci.hamers.utils.Utils
import org.json.JSONException
import org.json.JSONObject
import java.util.*
class StickerFragment : HamersFragment(),
OnMapReadyCallback,
GoogleMap.OnMarkerDragListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
GoogleMap.OnMarkerClickListener {
private val dataSet = ArrayList<Sticker>()
private lateinit var fusedLocationClient: FusedLocationProviderClient
private var mGoogleApiClient: GoogleApiClient? = null
private var mapView: MapView? = null
private var mMap: GoogleMap? = null
private var mLocationRequest: LocationRequest? = null
private var mCurrLocationMarker: Marker? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity!!.application)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_sticker, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Gets the MapView from the XML layout and creates it
mapView = stickers_map as MapView
mapView?.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PermissionUtils.checkLocationPermission(activity)
}
fusedLocationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let { onLocationChanged(location) }
}
hamers_fab.setOnClickListener {
postLocationDialog()
}
// Gets to GoogleMap from the MapView and does initialization stuff
mapView?.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
mMap?.uiSettings?.isMyLocationButtonEnabled = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient()
mMap?.isMyLocationEnabled = true
}
} else {
buildGoogleApiClient()
mMap?.isMyLocationEnabled = true
}
addMarkers()
mMap?.setOnMarkerClickListener(this)
mMap?.setOnMarkerDragListener(this)
}
override fun onMarkerClick(marker: Marker?): Boolean {
marker?.showInfoWindow()
return false
}
private fun onRefresh() {
Loader.getData(requireContext(), Loader.STICKERURL, -1, object : GetCallback {
override fun onSuccess(response: String) {
populateMap().execute(dataSet)
}
}, null)
}
private fun addMarkers() {
for (sticker in dataSet) {
mMap?.addMarker(MarkerOptions()
.position(LatLng(sticker.lat.toDouble(), sticker.lon.toDouble()))
.title(sticker.notes))
}
}
override fun onResume() {
mapView?.onResume()
super.onResume()
onRefresh()
activity?.title = resources.getString(R.string.navigation_item_stickers)
val params = hamers_fab.layoutParams as CoordinatorLayout.LayoutParams
params.anchorId = stickers_map.id
hamers_fab.layoutParams = params
}
override fun onPause() {
super.onPause()
mapView?.onPause()
}
override fun onDestroy() {
super.onDestroy()
mapView?.onDestroy()
}
override fun onLowMemory() {
super.onLowMemory()
mapView?.onLowMemory()
}
private fun postLocationDialog() {
val alert = AlertDialog.Builder(activity)
.setTitle(R.string.sticker_post_title)
.setMessage(R.string.sticker_post_message)
val input = EditText(activity)
input.setSingleLine()
input.setHint(R.string.sticker_post_note)
val container = FrameLayout(activity!!)
container.addView(input)
val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
params.marginStart = resources.getDimensionPixelSize(R.dimen.dialog_margin)
params.marginEnd = resources.getDimensionPixelSize(R.dimen.dialog_margin)
input.layoutParams = params
alert.setView(container)
alert.setPositiveButton(android.R.string.yes) { _, _ ->
postSticker(input.text.toString())
}
alert.setNegativeButton(android.R.string.no) { _, _ ->
// Do nothing.
}
// Only show dialog if permissions are given
if (PermissionUtils.checkLocationPermission(activity)) {
alert.show()
} else {
Toast.makeText(activity, R.string.sticker_no_permission, Toast.LENGTH_LONG).show()
}
}
private fun postSticker(notes: String) {
val body = JSONObject()
val lat = mCurrLocationMarker?.position?.latitude
val lon = mCurrLocationMarker?.position?.longitude
if (lat != null && lon != null) {
try {
body.put("lat", lat.toString())
body.put("lon", lon.toString())
body.put("notes", notes)
Loader.postOrPatchData(requireContext(), Loader.STICKERURL, body, Utils.notFound, null)
} catch (ignored: JSONException) {
}
} else {
Toast.makeText(activity, R.string.generic_error, Toast.LENGTH_SHORT).show()
}
}
private fun buildGoogleApiClient() {
mGoogleApiClient = GoogleApiClient.Builder(requireContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build()
mGoogleApiClient?.connect()
}
override fun onLocationChanged(location: Location) {
val latLng = LatLng(location.latitude, location.longitude)
if (mCurrLocationMarker == null) {
val markerOptions = MarkerOptions()
markerOptions.draggable(true)
markerOptions.position(latLng)
markerOptions.title("Je locatie")
markerOptions.icon(BitmapDescriptorFactory.defaultMarker())
mCurrLocationMarker = mMap?.addMarker(markerOptions)
}
// Move mMap camera
mMap?.moveCamera(CameraUpdateFactory.newLatLng(latLng))
mMap?.animateCamera(CameraUpdateFactory.zoomTo(11F))
// Stop location updates
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this)
}
override fun onConnected(bundle: Bundle?) {
if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this)
}
}
override fun onConnectionSuspended(i: Int) {
// Nothing
}
override fun onConnectionFailed(p0: ConnectionResult) {
// Nothing
}
override fun onMarkerDragStart(marker: Marker) {
// Nothing
}
override fun onMarkerDrag(p0: Marker) {
// Nothing
}
override fun onMarkerDragEnd(marker: Marker) {
mCurrLocationMarker?.position = marker.position
}
private inner class populateMap : AsyncTask<ArrayList<Sticker>, Void, ArrayList<Sticker>>() {
@SafeVarargs
override fun doInBackground(vararg param: ArrayList<Sticker>): ArrayList<Sticker> {
val gson = GsonBuilder().create()
val type = object : TypeToken<ArrayList<Sticker>>() {
}.type
return gson.fromJson<ArrayList<Sticker>>(prefs?.getString(Loader.STICKERURL, null), type)
}
override fun onPostExecute(result: ArrayList<Sticker>) {
if (result.isNotEmpty()) {
dataSet.clear()
dataSet.addAll(result)
addMarkers()
}
}
}
}
| gpl-3.0 | 95c4d1da3cc75be1c27e795070f4e51c | 34.649123 | 159 | 0.673425 | 4.953681 | false | false | false | false |
jonnyhsia/storybook | app/src/main/java/com/jonnyhsia/storybook/kit/UIKit.kt | 1 | 1710 | package com.jonnyhsia.storybook.kit
import android.app.Activity
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.annotation.ColorInt
import android.support.v4.app.Fragment
import android.support.v4.graphics.drawable.DrawableCompat
import android.util.TypedValue
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.jonnyhsia.storybook.app.App
/**
* UI 工具集
*/
object UIKit {
fun sp2px(sp: Int): Float = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, sp.toFloat(), App.INSTANCE.resources.displayMetrics)
fun dp2px(dp: Int): Float = dp2px(dp.toFloat())
fun dp2px(dp: Float): Float = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dp, App.INSTANCE.resources.displayMetrics)
fun tintDrawable(drawable: Drawable, colors: Int): Drawable {
val wrappedDrawable = DrawableCompat.wrap(drawable).mutate()
DrawableCompat.setTint(wrappedDrawable, colors)
return wrappedDrawable
}
}
fun Drawable.tint(@ColorInt tintColor: Int): Drawable? {
val wrappedDrawable = DrawableCompat.wrap(this).mutate()
DrawableCompat.setTint(wrappedDrawable, tintColor)
return wrappedDrawable
}
/**
* 隐藏键盘
*/
fun Activity.hideKeyboard() {
val focusedView = currentFocus as? EditText ?: return
focusedView.hideKeyboard()
}
fun Fragment.hideKeyboard() {
activity?.hideKeyboard()
}
fun EditText.hideKeyboard() {
val imm = context.getSystemService(
Context.INPUT_METHOD_SERVICE) as? InputMethodManager
if (imm != null && imm.isActive) {
imm.hideSoftInputFromWindow(applicationWindowToken, 0)
}
} | apache-2.0 | f38a1b6ee7fd528cc5b6ec557bcf580f | 28.258621 | 92 | 0.738208 | 4.208437 | false | false | false | false |
daneko/android-inapp-library | library/src/main/kotlin/com/github/daneko/android/iab/PlayMarketConnection.kt | 1 | 3832 | package com.github.daneko.android.iab
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.support.annotation.VisibleForTesting
import com.android.vending.billing.IInAppBillingService
import com.github.daneko.android.iab.exception.IabException
import com.github.daneko.android.iab.model.GooglePlayResponse
import com.github.daneko.android.iab.model.IabItemType
import fj.data.Option
import org.slf4j.LoggerFactory
import rx.Observable
import rx.subjects.BehaviorSubject
/**
*
*/
@VisibleForTesting
internal open class PlayMarketConnection(val context: Context) : ServiceConnection {
companion object {
private val log = LoggerFactory.getLogger(PlayMarketConnection::class.java)
private val intentAction = "com.android.vending.billing.InAppBillingService.BIND"
private val marketPackage = "com.android.vending"
private fun create(context: Context): Option<PlayMarketConnection> {
val connection = PlayMarketConnection(context)
return Option.iif(connection.connectionOpen(Context.BIND_AUTO_CREATE), connection)
}
fun connect(context: Context, packageName: String): Observable<PlayMarketConnection> =
fromValidation(PlayMarketConnection.create(context).toValidation(IabException("connect fail"))).
flatMap { connection ->
connection.checkBillingSupportWithError(packageName).
all { it.isSuccess }.map { connection }.
doOnUnsubscribe { log.trace("unsubscribe connection observable") }.
doOnUnsubscribe { connection.connectionClose() }
}
}
private val subject: BehaviorSubject<IInAppBillingService> = BehaviorSubject.create()
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
log.trace("onServiceConnected name: $name, service: $service")
subject.onNext(IInAppBillingService.Stub.asInterface(service))
}
override fun onServiceDisconnected(name: ComponentName?) {
log.trace("onServiceDisconnected name: $name")
subject.onCompleted()
}
private fun connectionOpen(/* @BindServiceFlags */ flags: Int): Boolean {
log.trace("do Bind")
val intent = Intent(intentAction)
intent.setPackage(marketPackage)
return Option.iif(context.packageManager.queryIntentServices(intent, 0).isNotEmpty(), flags).
map { context.bindService(intent, this@PlayMarketConnection, it) }.orSome(false)
}
private fun connectionClose() {
log.trace("do close")
context.unbindService(this)
}
open fun <T> action(f: (IInAppBillingService) -> T): Observable<T> {
return subject.asObservable().take(1).map(f)
}
/**
* wrap {@link IInAppBillingService#isBillingSupported }
*/
private fun checkBillingSupport(packageName: String): Observable<GooglePlayResponse> {
log.trace("#checkBillingSupport: target package name : $packageName")
return Observable.from(IabItemType.values().map { it.typeName }).
flatMap { typeName ->
action {
GooglePlayResponse.create(
it.isBillingSupported(IabConstant.TARGET_VERSION, packageName, typeName))
}
}
}
/**
* if response is not {@link GooglePlayResponse#OK}, return Observable#onError
*/
fun checkBillingSupportWithError(packageName: String): Observable<GooglePlayResponse> =
checkBillingSupport(packageName).flatMap { checkGooglePlayResponse(it) }
}
| mit | 3ab5a8d035b57ab62e639e2313a85532 | 40.204301 | 112 | 0.675104 | 4.900256 | false | false | false | false |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt | 1 | 3452 | package eu.kanade.tachiyomi.data.preference
import android.content.Context
import eu.kanade.tachiyomi.R
/**
* This class stores the keys for the preferences in the application. Most of them are defined
* in the file "keys.xml". By using this class we can define preferences in one place and get them
* referenced here.
*/
class PreferenceKeys(context: Context) {
val rotation = context.getString(R.string.pref_rotation_type_key)
val enableTransitions = context.getString(R.string.pref_enable_transitions_key)
val showPageNumber = context.getString(R.string.pref_show_page_number_key)
val hideStatusBar = context.getString(R.string.pref_hide_status_bar_key)
val keepScreenOn = context.getString(R.string.pref_keep_screen_on_key)
val customBrightness = context.getString(R.string.pref_custom_brightness_key)
val customBrightnessValue = context.getString(R.string.pref_custom_brightness_value_key)
val defaultViewer = context.getString(R.string.pref_default_viewer_key)
val imageScaleType = context.getString(R.string.pref_image_scale_type_key)
val imageDecoder = context.getString(R.string.pref_image_decoder_key)
val zoomStart = context.getString(R.string.pref_zoom_start_key)
val readerTheme = context.getString(R.string.pref_reader_theme_key)
val readWithTapping = context.getString(R.string.pref_read_with_tapping_key)
val readWithVolumeKeys = context.getString(R.string.pref_read_with_volume_keys_key)
val portraitColumns = context.getString(R.string.pref_library_columns_portrait_key)
val landscapeColumns = context.getString(R.string.pref_library_columns_landscape_key)
val updateOnlyNonCompleted = context.getString(R.string.pref_update_only_non_completed_key)
val autoUpdateMangaSync = context.getString(R.string.pref_auto_update_manga_sync_key)
val askUpdateMangaSync = context.getString(R.string.pref_ask_update_manga_sync_key)
val lastUsedCatalogueSource = context.getString(R.string.pref_last_catalogue_source_key)
val seamlessMode = context.getString(R.string.pref_seamless_mode_key)
val catalogueAsList = context.getString(R.string.pref_display_catalogue_as_list)
val enabledLanguages = context.getString(R.string.pref_source_languages)
val downloadsDirectory = context.getString(R.string.pref_download_directory_key)
val downloadThreads = context.getString(R.string.pref_download_slots_key)
val downloadOnlyOverWifi = context.getString(R.string.pref_download_only_over_wifi_key)
val removeAfterRead = context.getString(R.string.pref_remove_after_read_key)
val removeAfterReadPrevious = context.getString(R.string.pref_remove_after_read_previous_key)
val removeAfterMarkedAsRead = context.getString(R.string.pref_remove_after_marked_as_read_key)
val updateOnlyWhenCharging = context.getString(R.string.pref_update_only_when_charging_key)
val libraryUpdateInterval = context.getString(R.string.pref_library_update_interval_key)
val filterDownloaded = context.getString(R.string.pref_filter_downloaded_key)
val filterUnread = context.getString(R.string.pref_filter_unread_key)
fun sourceUsername(sourceId: Int) = "pref_source_username_$sourceId"
fun sourcePassword(sourceId: Int) = "pref_source_password_$sourceId"
fun syncUsername(syncId: Int) = "pref_mangasync_username_$syncId"
fun syncPassword(syncId: Int) = "pref_mangasync_password_$syncId"
}
| apache-2.0 | b2fefe0e8042766430ba89ecf8b4ae67 | 38.678161 | 98 | 0.771437 | 3.744035 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/core/routing/ParserState.kt | 1 | 4485 | package io.javalin.core.routing
private enum class ParserState {
NORMAL,
INSIDE_SLASH_IGNORING_BRACKETS,
INSIDE_SLASH_ACCEPTING_BRACKETS
}
private val allDelimiters = setOf('{', '}', '<', '>')
private val adjacentViolations = listOf("*{", "*<", "}*", ">*")
internal fun convertSegment(segment: String, rawPath: String): PathSegment {
val bracketsCount by lazy { segment.count { it in allDelimiters } }
val wildcardCount by lazy { segment.count { it == '*' } }
return when {
bracketsCount % 2 != 0 -> throw MissingBracketsException(segment, rawPath)
adjacentViolations.any { it in segment } -> throw WildcardBracketAdjacentException(segment, rawPath)
segment == "*" -> PathSegment.Wildcard // a wildcard segment
bracketsCount == 0 && wildcardCount == 0 -> createNormal(segment) // a normal segment, no params or wildcards
bracketsCount == 2 && segment.isEnclosedBy('{', '}') -> createSlashIgnoringParam(segment.stripEnclosing('{', '}')) // simple path param (no slashes)
bracketsCount == 2 && segment.isEnclosedBy('<', '>') -> createSlashAcceptingParam(segment.stripEnclosing('<', '>')) // simple path param (slashes)
else -> parseAsPathSegment(segment, rawPath) // complicated path segment, need to parse
}
}
private fun parseAsPathSegment(segment: String, rawPath: String): PathSegment {
var state: ParserState = ParserState.NORMAL
val pathNameAccumulator = mutableListOf<Char>()
fun mapSingleChar(char: Char): PathSegment? = when (state) {
ParserState.NORMAL -> when (char) {
'*' -> PathSegment.Wildcard
'{' -> {
state = ParserState.INSIDE_SLASH_IGNORING_BRACKETS
null
}
'<' -> {
state = ParserState.INSIDE_SLASH_ACCEPTING_BRACKETS
null
}
'}', '>' -> throw MissingBracketsException(
segment,
rawPath
) // cannot start with a closing delimiter
else -> createNormal(char.toString()) // the single characters will be merged later
}
ParserState.INSIDE_SLASH_IGNORING_BRACKETS -> when (char) {
'}' -> {
state = ParserState.NORMAL
val name = pathNameAccumulator.joinToString(separator = "")
pathNameAccumulator.clear()
createSlashIgnoringParam(name)
}
'{', '<', '>' -> throw MissingBracketsException(
segment,
rawPath
) // cannot start another variable inside a variable
// wildcard is also okay inside a variable name
else -> {
pathNameAccumulator += char
null
}
}
ParserState.INSIDE_SLASH_ACCEPTING_BRACKETS -> when (char) {
'>' -> {
state = ParserState.NORMAL
val name = pathNameAccumulator.joinToString(separator = "")
pathNameAccumulator.clear()
createSlashAcceptingParam(name)
}
'{', '}', '<' -> throw MissingBracketsException(
segment,
rawPath
) // cannot start another variable inside a variable
// wildcard is also okay inside a variable name
else -> {
pathNameAccumulator += char
null
}
}
}
return segment.map(::mapSingleChar)
.filterNotNull()
.fold(PathSegment.MultipleSegments(emptyList())) { acc, pathSegment ->
val lastAddition = acc.innerSegments.lastOrNull()
when {
lastAddition == null -> PathSegment.MultipleSegments(listOf(pathSegment))
lastAddition is PathSegment.Wildcard && pathSegment is PathSegment.Wildcard -> acc
lastAddition is PathSegment.Normal && pathSegment is PathSegment.Normal -> PathSegment.MultipleSegments(
acc.innerSegments.dropLast(1) + createNormal(lastAddition.content + pathSegment.content)
)
else -> PathSegment.MultipleSegments(acc.innerSegments + pathSegment)
}
}
}
private fun String.isEnclosedBy(prefix: Char, suffix: Char) = this.startsWith(prefix) && this.endsWith(suffix)
private fun String.stripEnclosing(prefix: Char, suffix: Char) = this.removePrefix(prefix.toString()).removeSuffix(suffix.toString())
| apache-2.0 | 1a62f2e49ff8693709ef76085545945d | 44.765306 | 156 | 0.59175 | 4.901639 | false | false | false | false |
Samourai-Wallet/samourai-wallet-android | app/src/main/java/com/samourai/wallet/send/batch/ReviewFragment.kt | 1 | 8453 | package com.samourai.wallet.send.batch;
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.google.android.material.button.MaterialButton
import com.google.android.material.slider.Slider
import com.samourai.wallet.R
import com.samourai.wallet.send.FeeUtil
import com.samourai.wallet.send.SuggestedFee
import com.samourai.wallet.util.FormatsUtil
import com.samourai.wallet.util.PrefsUtil
import java.math.BigInteger
import java.text.DecimalFormat
class ReviewFragment : Fragment() {
private val FEE_LOW = 0
private val FEE_NORMAL = 1
private val FEE_PRIORITY = 2
private var FEE_TYPE = FEE_LOW
private var feeLow: Long = 0L
private var feeMed: Long = 0L
private var feeHigh: Long = 0
private val decimalFormatSatPerByte = DecimalFormat("##")
private lateinit var feeSeekBar: Slider
private lateinit var tvSelectedFeeRateLayman: TextView
private lateinit var tvEstimatedBlockWait: TextView
private lateinit var tvTotalFee: TextView
private lateinit var tvSelectedFeeRate: TextView
private var sendButtonBatch: MaterialButton? = null;
private var onFeeChangeListener: (() -> Unit)? = null
private var onClickListener: (View.OnClickListener)? = null
init {
decimalFormatSatPerByte.isDecimalSeparatorAlwaysShown = false
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
feeSeekBar = view.findViewById(R.id.fee_seekbar)
tvSelectedFeeRate = view.findViewById(R.id.selected_fee_rate)
tvSelectedFeeRateLayman = view.findViewById(R.id.selected_fee_rate_in_layman)
tvEstimatedBlockWait = view.findViewById(R.id.est_block_time)
sendButtonBatch = view.findViewById(R.id.sendButtonBatch)
tvTotalFee = view.findViewById(R.id.total_fee)
sendButtonBatch?.setOnClickListener { onClickListener?.onClick(it) }
setUpFee()
}
fun getSendButton(): MaterialButton? {
return sendButtonBatch;
}
fun enableSendButton(enable:Boolean){
if(isAdded){
sendButtonBatch?.isEnabled = enable
if(enable){
sendButtonBatch?.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.green_ui_2))
}else{
sendButtonBatch?.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.disabled_grey))
}
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.batch_spend_review, container, false)
}
private fun setUpFee() {
FEE_TYPE = PrefsUtil.getInstance(requireContext()).getValue(PrefsUtil.CURRENT_FEE_TYPE, FEE_NORMAL)
feeLow = FeeUtil.getInstance().lowFee.defaultPerKB.toLong() / 1000L
feeMed = FeeUtil.getInstance().normalFee.defaultPerKB.toLong() / 1000L
feeHigh = FeeUtil.getInstance().highFee.defaultPerKB.toLong() / 1000L
val high = feeHigh.toFloat() / 2 + feeHigh.toFloat()
val feeHighSliderValue = (high * 10000).toInt()
val feeMedSliderValue = (feeMed * 10000).toInt()
feeSeekBar.valueTo = (feeHighSliderValue - 10000).toFloat()
feeSeekBar.valueFrom = 1F
feeSeekBar.setLabelFormatter {
"${tvSelectedFeeRate.text}"
}
if (feeLow == feeMed && feeMed == feeHigh) {
feeLow = (feeMed.toDouble() * 0.85).toLong()
feeHigh = (feeMed.toDouble() * 1.15).toLong()
val lo_sf = SuggestedFee()
lo_sf.defaultPerKB = BigInteger.valueOf(feeLow * 1000L)
FeeUtil.getInstance().lowFee = lo_sf
val hi_sf = SuggestedFee()
hi_sf.defaultPerKB = BigInteger.valueOf(feeHigh * 1000L)
FeeUtil.getInstance().highFee = hi_sf
} else if (feeLow == feeMed || feeMed == feeMed) {
feeMed = (feeLow + feeHigh) / 2L
val mi_sf = SuggestedFee()
mi_sf.defaultPerKB = BigInteger.valueOf(feeHigh * 1000L)
FeeUtil.getInstance().normalFee = mi_sf
} else {
}
if (feeLow < 1L) {
feeLow = 1L
val lo_sf = SuggestedFee()
lo_sf.defaultPerKB = BigInteger.valueOf(feeLow * 1000L)
FeeUtil.getInstance().lowFee = lo_sf
}
if (feeMed < 1L) {
feeMed = 1L
val mi_sf = SuggestedFee()
mi_sf.defaultPerKB = BigInteger.valueOf(feeMed * 1000L)
FeeUtil.getInstance().normalFee = mi_sf
}
if (feeHigh < 1L) {
feeHigh = 1L
val hi_sf = SuggestedFee()
hi_sf.defaultPerKB = BigInteger.valueOf(feeHigh * 1000L)
FeeUtil.getInstance().highFee = hi_sf
}
// tvEstimatedBlockWait.setText("6 blocks");
tvSelectedFeeRateLayman.text = getString(R.string.normal)
FeeUtil.getInstance().sanitizeFee()
tvSelectedFeeRate.text = ("${feeMed} sats/b")
feeSeekBar.value = (feeMedSliderValue - 10000 + 1).toFloat()
setFeeLabels()
feeSeekBar.addOnChangeListener(Slider.OnChangeListener { slider, i, fromUser ->
var value = (i.toDouble() + 10000) / 10000.toDouble()
if (value == 0.0) {
value = 1.0
}
var pct = 0.0
var nbBlocks = 6
if (value <= feeLow.toDouble()) {
pct = feeLow.toDouble() / value
nbBlocks = Math.ceil(pct * 24.0).toInt()
} else if (value >= feeHigh.toDouble()) {
pct = feeHigh.toDouble() / value
nbBlocks = Math.ceil(pct * 2.0).toInt()
if (nbBlocks < 1) {
nbBlocks = 1
}
} else {
pct = feeMed.toDouble() / value
nbBlocks = Math.ceil(pct * 6.0).toInt()
}
var blocks = "$nbBlocks blocks"
if (nbBlocks > 50) {
blocks = "50+ blocks"
}
tvEstimatedBlockWait.text = blocks
setFee(value)
setFeeLabels()
})
when (FEE_TYPE) {
FEE_LOW -> {
FeeUtil.getInstance().suggestedFee = FeeUtil.getInstance().lowFee
FeeUtil.getInstance().sanitizeFee()
}
FEE_PRIORITY -> {
FeeUtil.getInstance().suggestedFee = FeeUtil.getInstance().highFee
FeeUtil.getInstance().sanitizeFee()
}
else -> {
FeeUtil.getInstance().suggestedFee = FeeUtil.getInstance().normalFee
FeeUtil.getInstance().sanitizeFee()
}
}
setFee(((feeMedSliderValue-10000) /10000).toDouble())
}
private fun setFeeLabels() {
val sliderValue: Float = feeSeekBar.value / feeSeekBar.valueTo
val sliderInPercentage = sliderValue * 100
if (sliderInPercentage < 33) {
tvSelectedFeeRateLayman.setText(R.string.low)
} else if (sliderInPercentage > 33 && sliderInPercentage < 66) {
tvSelectedFeeRateLayman.setText(R.string.normal)
} else if (sliderInPercentage > 66) {
tvSelectedFeeRateLayman.setText(R.string.urgent)
}
}
private fun setFee(fee: Double) {
val suggestedFee = SuggestedFee()
suggestedFee.isStressed = false
suggestedFee.isOK = true
suggestedFee.defaultPerKB = BigInteger.valueOf((fee * 1000.0).toLong())
FeeUtil.getInstance().suggestedFee = suggestedFee
this.onFeeChangeListener?.invoke()
}
fun setOnFeeChangeListener(onFeeChangeListener: (() -> Unit)) {
this.onFeeChangeListener = onFeeChangeListener
}
fun setTotalMinerFees(fee: BigInteger?) {
if (isAdded) {
tvTotalFee.text = "${FormatsUtil.getBTCDecimalFormat(fee?.toLong())} BTC"
}
}
fun setOnClickListener(onClickListener: View.OnClickListener) {
this.onClickListener = onClickListener
}
fun setFeeRate(value: Double) {
if (isAdded)
tvSelectedFeeRate.text = "${decimalFormatSatPerByte.format(value)} sat/b"
}
}
| unlicense | 3225b11db487384f661219d6232ff976 | 38.316279 | 115 | 0.616468 | 4.207566 | false | false | false | false |
youkai-app/Youkai | app/src/main/kotlin/app/youkai/ui/feature/login/LoginState.kt | 1 | 2100 | package app.youkai.ui.feature.login
import android.os.Bundle
import com.hannesdorfmann.mosby.mvp.viewstate.RestorableViewState
class LoginState : RestorableViewState<LoginView> {
var error: String? = null
var usernameEnabled = true
var passwordEnabled = true
var buttonEnabled = true
var progressVisible = false
var isLoading = false
override fun apply(view: LoginView, retained: Boolean) {
if (error != null) {
view.showError(error!!)
}
view.enableUsername(usernameEnabled)
view.enablePassword(passwordEnabled)
view.enableButton(buttonEnabled)
view.showProgress(progressVisible)
if (isLoading) view.doLogin()
}
override fun restoreInstanceState(bundle: Bundle?): RestorableViewState<LoginView> {
val state = LoginState()
if (bundle != null) {
state.error = bundle.getString(KEY_ERROR)
state.usernameEnabled = bundle.getBoolean(KEY_USERNAME_ENABLED)
state.passwordEnabled = bundle.getBoolean(KEY_PASSWORD_ENABLED)
state.buttonEnabled = bundle.getBoolean(KEY_BUTTON_ENABLED)
state.progressVisible = bundle.getBoolean(KEY_PROGRESS_VISIBLE)
state.isLoading = bundle.getBoolean(KEY_IS_LOADING)
}
return state
}
override fun saveInstanceState(bundle: Bundle) {
bundle.putString(KEY_ERROR, error)
bundle.putBoolean(KEY_USERNAME_ENABLED, usernameEnabled)
bundle.putBoolean(KEY_PASSWORD_ENABLED, passwordEnabled)
bundle.putBoolean(KEY_BUTTON_ENABLED, buttonEnabled)
bundle.putBoolean(KEY_PROGRESS_VISIBLE, progressVisible)
bundle.putBoolean(KEY_IS_LOADING, isLoading)
}
companion object {
private val KEY_ERROR = "error"
private val KEY_USERNAME_ENABLED = "username_enabled"
private val KEY_PASSWORD_ENABLED = "password_enabled"
private val KEY_BUTTON_ENABLED = "button_enabled"
private val KEY_PROGRESS_VISIBLE = "progress_visible"
private val KEY_IS_LOADING = "is_loading"
}
} | gpl-3.0 | 71e92f10f6f6beb117992431a12396e2 | 37.2 | 88 | 0.680476 | 4.449153 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/MeasurementConsumersService.kt | 1 | 10972 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.api.v2alpha
import io.grpc.Status
import io.grpc.StatusException
import org.wfanet.measurement.api.Version
import org.wfanet.measurement.api.accountFromCurrentContext
import org.wfanet.measurement.api.v2alpha.AccountKey
import org.wfanet.measurement.api.v2alpha.AddMeasurementConsumerOwnerRequest
import org.wfanet.measurement.api.v2alpha.CreateMeasurementConsumerRequest
import org.wfanet.measurement.api.v2alpha.DataProviderPrincipal
import org.wfanet.measurement.api.v2alpha.GetMeasurementConsumerRequest
import org.wfanet.measurement.api.v2alpha.MeasurementConsumer
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerCertificateKey
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerPrincipal
import org.wfanet.measurement.api.v2alpha.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineImplBase as MeasurementConsumersCoroutineService
import org.wfanet.measurement.api.v2alpha.MeasurementPrincipal
import org.wfanet.measurement.api.v2alpha.RemoveMeasurementConsumerOwnerRequest
import org.wfanet.measurement.api.v2alpha.measurementConsumer
import org.wfanet.measurement.api.v2alpha.principalFromCurrentContext
import org.wfanet.measurement.api.v2alpha.signedData
import org.wfanet.measurement.common.crypto.hashSha256
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.common.grpc.grpcRequire
import org.wfanet.measurement.common.grpc.grpcRequireNotNull
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.identity.externalIdToApiId
import org.wfanet.measurement.internal.kingdom.MeasurementConsumer as InternalMeasurementConsumer
import org.wfanet.measurement.internal.kingdom.MeasurementConsumerKt.details
import org.wfanet.measurement.internal.kingdom.MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineStub as InternalMeasurementConsumersCoroutineStub
import org.wfanet.measurement.internal.kingdom.addMeasurementConsumerOwnerRequest
import org.wfanet.measurement.internal.kingdom.createMeasurementConsumerRequest
import org.wfanet.measurement.internal.kingdom.getMeasurementConsumerRequest
import org.wfanet.measurement.internal.kingdom.measurementConsumer as internalMeasurementConsumer
import org.wfanet.measurement.internal.kingdom.removeMeasurementConsumerOwnerRequest
private val API_VERSION = Version.V2_ALPHA
class MeasurementConsumersService(
private val internalClient: InternalMeasurementConsumersCoroutineStub
) : MeasurementConsumersCoroutineService() {
override suspend fun createMeasurementConsumer(
request: CreateMeasurementConsumerRequest
): MeasurementConsumer {
val account = accountFromCurrentContext
val measurementConsumer = request.measurementConsumer
grpcRequire(!measurementConsumer.publicKey.data.isEmpty) { "public_key.data is missing" }
grpcRequire(!measurementConsumer.publicKey.signature.isEmpty) {
"public_key.signature is missing"
}
grpcRequire(measurementConsumer.measurementConsumerCreationToken.isNotBlank()) {
"Measurement Consumer creation token is unspecified"
}
val createRequest = createMeasurementConsumerRequest {
this.measurementConsumer = internalMeasurementConsumer {
certificate = parseCertificateDer(measurementConsumer.certificateDer)
details = details {
apiVersion = API_VERSION.string
publicKey = measurementConsumer.publicKey.data
publicKeySignature = measurementConsumer.publicKey.signature
}
}
externalAccountId = account.externalAccountId
measurementConsumerCreationTokenHash =
hashSha256(apiIdToExternalId(measurementConsumer.measurementConsumerCreationToken))
}
val internalMeasurementConsumer =
try {
internalClient.createMeasurementConsumer(createRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.INVALID_ARGUMENT ->
failGrpc(Status.INVALID_ARGUMENT, ex) { "Required field unspecified or invalid." }
Status.Code.PERMISSION_DENIED ->
failGrpc(Status.PERMISSION_DENIED, ex) {
"Measurement Consumer creation token is not valid."
}
Status.Code.FAILED_PRECONDITION ->
failGrpc(Status.FAILED_PRECONDITION, ex) { "Account not found or inactivated." }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return internalMeasurementConsumer.toMeasurementConsumer()
}
override suspend fun getMeasurementConsumer(
request: GetMeasurementConsumerRequest
): MeasurementConsumer {
val principal: MeasurementPrincipal = principalFromCurrentContext
val key: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(request.name)) {
"Resource name unspecified or invalid"
}
val externalMeasurementConsumerId = apiIdToExternalId(key.measurementConsumerId)
when (principal) {
is DataProviderPrincipal -> {}
is MeasurementConsumerPrincipal -> {
if (
apiIdToExternalId(principal.resourceKey.measurementConsumerId) !=
externalMeasurementConsumerId
) {
failGrpc(Status.PERMISSION_DENIED) { "Cannot get another MeasurementConsumer" }
}
}
else -> {
failGrpc(Status.PERMISSION_DENIED) {
"Caller does not have permission to get MeasurementConsumers"
}
}
}
val getRequest = getMeasurementConsumerRequest {
this.externalMeasurementConsumerId = externalMeasurementConsumerId
}
val internalResponse =
try {
internalClient.getMeasurementConsumer(getRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.NOT_FOUND ->
failGrpc(Status.NOT_FOUND, ex) { "MeasurementConsumer not found" }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return internalResponse.toMeasurementConsumer()
}
override suspend fun addMeasurementConsumerOwner(
request: AddMeasurementConsumerOwnerRequest
): MeasurementConsumer {
val account = accountFromCurrentContext
val measurementConsumerKey: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(request.name)) {
"Resource name unspecified or invalid"
}
val externalMeasurementConsumerId =
apiIdToExternalId(measurementConsumerKey.measurementConsumerId)
if (!account.externalOwnedMeasurementConsumerIdsList.contains(externalMeasurementConsumerId)) {
failGrpc(Status.PERMISSION_DENIED) { "Account doesn't own MeasurementConsumer" }
}
val accountKey: AccountKey =
grpcRequireNotNull(AccountKey.fromName(request.account)) { "Account unspecified or invalid" }
val internalAddMeasurementConsumerOwnerRequest = addMeasurementConsumerOwnerRequest {
this.externalMeasurementConsumerId = externalMeasurementConsumerId
externalAccountId = apiIdToExternalId(accountKey.accountId)
}
val internalMeasurementConsumer =
try {
internalClient.addMeasurementConsumerOwner(internalAddMeasurementConsumerOwnerRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.FAILED_PRECONDITION ->
failGrpc(Status.FAILED_PRECONDITION, ex) { "Account not found." }
Status.Code.NOT_FOUND ->
failGrpc(Status.NOT_FOUND, ex) { "MeasurementConsumer not found." }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return internalMeasurementConsumer.toMeasurementConsumer()
}
override suspend fun removeMeasurementConsumerOwner(
request: RemoveMeasurementConsumerOwnerRequest
): MeasurementConsumer {
val account = accountFromCurrentContext
val measurementConsumerKey: MeasurementConsumerKey =
grpcRequireNotNull(MeasurementConsumerKey.fromName(request.name)) {
"Resource name unspecified or invalid"
}
val externalMeasurementConsumerId =
apiIdToExternalId(measurementConsumerKey.measurementConsumerId)
if (!account.externalOwnedMeasurementConsumerIdsList.contains(externalMeasurementConsumerId)) {
failGrpc(Status.PERMISSION_DENIED) { "Account doesn't own MeasurementConsumer" }
}
val accountKey: AccountKey =
grpcRequireNotNull(AccountKey.fromName(request.account)) { "Account unspecified or invalid" }
val internalRemoveMeasurementConsumerOwnerRequest = removeMeasurementConsumerOwnerRequest {
this.externalMeasurementConsumerId = externalMeasurementConsumerId
externalAccountId = apiIdToExternalId(accountKey.accountId)
}
val internalMeasurementConsumer =
try {
internalClient.removeMeasurementConsumerOwner(internalRemoveMeasurementConsumerOwnerRequest)
} catch (ex: StatusException) {
when (ex.status.code) {
Status.Code.FAILED_PRECONDITION ->
failGrpc(Status.FAILED_PRECONDITION, ex) {
"Account not found or Account doesn't own the MeasurementConsumer."
}
Status.Code.NOT_FOUND ->
failGrpc(Status.NOT_FOUND, ex) { "MeasurementConsumer not found." }
else -> failGrpc(Status.UNKNOWN, ex) { "Unknown exception." }
}
}
return internalMeasurementConsumer.toMeasurementConsumer()
}
}
private fun InternalMeasurementConsumer.toMeasurementConsumer(): MeasurementConsumer {
check(Version.fromString(details.apiVersion) == API_VERSION) {
"Incompatible API version ${details.apiVersion}"
}
val internalMeasurementConsumer = this
val measurementConsumerId: String = externalIdToApiId(externalMeasurementConsumerId)
val certificateId: String = externalIdToApiId(certificate.externalCertificateId)
return measurementConsumer {
name = MeasurementConsumerKey(measurementConsumerId).toName()
certificate = MeasurementConsumerCertificateKey(measurementConsumerId, certificateId).toName()
certificateDer = internalMeasurementConsumer.certificate.details.x509Der
publicKey = signedData {
data = internalMeasurementConsumer.details.publicKey
signature = internalMeasurementConsumer.details.publicKeySignature
}
}
}
| apache-2.0 | 98c0a4e411d6d8dcbfe329bc7c2f2f03 | 42.713147 | 152 | 0.764856 | 5.275 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/poll/text/TextPollOptionView.kt | 1 | 16535 | package io.rover.sdk.experiences.ui.blocks.poll.text
import android.animation.AnimatorSet
import android.animation.TimeInterpolator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Typeface
import androidx.core.view.ViewCompat
import androidx.appcompat.widget.AppCompatTextView
import android.text.TextUtils
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import io.rover.sdk.core.data.domain.FontWeight
import io.rover.sdk.core.data.domain.TextPollOption
import io.rover.sdk.experiences.data.mapToFont
import io.rover.sdk.experiences.platform.create
import io.rover.sdk.experiences.platform.setBackgroundWithoutPaddingChange
import io.rover.sdk.experiences.platform.setupLinearLayoutParams
import io.rover.sdk.experiences.platform.setupRelativeLayoutParams
import io.rover.sdk.experiences.platform.textPollProgressBar
import io.rover.sdk.experiences.platform.textView
import io.rover.sdk.experiences.ui.asAndroidColor
import io.rover.sdk.experiences.ui.blocks.concerns.background.BackgroundColorDrawableWrapper
import io.rover.sdk.experiences.ui.blocks.poll.PollBorderView
import io.rover.sdk.experiences.ui.blocks.poll.RoundRect
import io.rover.sdk.experiences.ui.dpAsPx
/**
* Custom view that is "externally bound", the "bind" methods on this class are externally called
* as opposed to other views which subscribe to a ViewModel. This means that this view and the views
* that interact with it operate in a more MVP type approach than the other MVVM-esque views.
*/
internal class TextOptionView(context: Context?) : RelativeLayout(context) {
private val optionTextView = textView {
id = ViewCompat.generateViewId()
ellipsize = TextUtils.TruncateAt.END
maxLines = 1
setLineSpacing(0f, 1.0f)
includeFontPadding = false
gravity = Gravity.CENTER_VERTICAL
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
val marginInPixels = 16.dpAsPx(resources.displayMetrics)
setupRelativeLayoutParams(
width = ViewGroup.LayoutParams.WRAP_CONTENT, height = ViewGroup.LayoutParams.MATCH_PARENT,
leftMargin = marginInPixels, rightMargin = marginInPixels
) {
addRule(ALIGN_PARENT_START)
}
}
private val voteIndicatorView = textView {
visibility = View.GONE
maxLines = 1
gravity = Gravity.CENTER_VERTICAL
textAlignment = View.TEXT_ALIGNMENT_TEXT_START
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
val marginInPixels = 8.dpAsPx(resources.displayMetrics)
setupRelativeLayoutParams(
width = LayoutParams.WRAP_CONTENT,
height = LayoutParams.MATCH_PARENT,
leftMargin = marginInPixels
) {
addRule(END_OF, optionTextView.id)
}
}
private val textPollProgressBar = textPollProgressBar {
visibility = View.GONE
}
private val votePercentageText = textView {
id = ViewCompat.generateViewId()
visibility = View.GONE
maxLines = 1
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
setLineSpacing(0f, 1.0f)
includeFontPadding = false
gravity = Gravity.CENTER_VERTICAL
textAlignment = View.TEXT_ALIGNMENT_TEXT_END
val marginInDp = 16.dpAsPx(resources.displayMetrics)
setupRelativeLayoutParams(
width = LayoutParams.WRAP_CONTENT, height = LayoutParams.MATCH_PARENT,
leftMargin = marginInDp, rightMargin = marginInDp
) {
addRule(ALIGN_PARENT_RIGHT)
}
}
private val borderView = PollBorderView(this.context).apply {
setupRelativeLayoutParams(width = ViewGroup.LayoutParams.MATCH_PARENT, height = ViewGroup.LayoutParams.MATCH_PARENT)
}
private var roundRect: RoundRect? = null
set(value) {
field = value
value?.borderRadius?.let {
clipPath = Path().apply {
addRoundRect(value.rectF, value.borderRadius, value.borderRadius, Path.Direction.CW)
}
}
}
private var optionPaints: OptionPaints = OptionPaints()
// used to set starting point for update animations
private var currentVote = 0
var backgroundImage: BackgroundColorDrawableWrapper? = null
set(value) {
field = value
value?.let {
mainLayout.setBackgroundWithoutPaddingChange(it)
}
}
companion object {
private const val RESULTS_TEXT_SCALE_FACTOR = 1.05f
private const val RESULT_FILL_PROGRESS_DURATION = 1000L
private const val ALPHA_DURATION = 750L
private const val RESULT_FILL_ALPHA_DURATION = 50L
}
private val mainLayout = RelativeLayout(context)
init {
mainLayout.addView(textPollProgressBar)
mainLayout.addView(optionTextView)
mainLayout.addView(votePercentageText)
mainLayout.addView(voteIndicatorView)
addView(mainLayout)
addView(borderView)
}
fun setContentDescription(optionIndex: Int) {
contentDescription = "${optionTextView.text}. Option $optionIndex"
}
fun initializeOptionViewLayout(optionStyle: TextPollOption) {
val optionStyleHeight = optionStyle.height.dpAsPx(resources.displayMetrics)
val optionMarginHeight = optionStyle.topMargin.dpAsPx(resources.displayMetrics)
val borderWidth = optionStyle.border.width.dpAsPx(resources.displayMetrics)
val totalBorderWidth = borderWidth * 2
gravity = Gravity.CENTER_VERTICAL
alpha = optionStyle.opacity.toFloat()
setBackgroundColor(Color.TRANSPARENT)
setupLinearLayoutParams(
width = ViewGroup.LayoutParams.MATCH_PARENT,
height = optionStyleHeight + totalBorderWidth,
topMargin = optionMarginHeight
)
mainLayout.setupRelativeLayoutParams {
width = LayoutParams.MATCH_PARENT
height = optionStyleHeight
marginStart = borderWidth
marginEnd = borderWidth
topMargin = borderWidth
bottomMargin = borderWidth
}
initializeViewStyle(optionStyle)
}
fun bindOptionView(option: TextPollOption) {
optionTextView.run {
setLineSpacing(0f, 1.0f)
includeFontPadding = false
text = option.text.rawValue
textSize = option.text.font.size.toFloat()
setTextColor(option.text.color.asAndroidColor())
val font = option.text.font.weight.mapToFont()
typeface = Typeface.create(font.fontFamily, font.fontStyle)
}
}
private fun initializeViewStyle(optionStyle: TextPollOption) {
val adjustedBorderRadius = if (optionStyle.border.radius.toFloat() > optionStyle.height.toFloat() / 2) {
optionStyle.height / 2
} else {
optionStyle.border.radius
}
val adjustedOptionStyle = optionStyle.copy(border = optionStyle.border.copy(radius = adjustedBorderRadius))
val borderRadius = adjustedOptionStyle.border.radius.dpAsPx(resources.displayMetrics).toFloat()
val borderStrokeWidth = adjustedOptionStyle.border.width.dpAsPx(resources.displayMetrics).toFloat()
val fillPaint = Paint().create(adjustedOptionStyle.background.color.asAndroidColor(), Paint.Style.FILL)
val resultPaint = Paint().create(adjustedOptionStyle.resultFillColor.asAndroidColor(), Paint.Style.FILL)
optionPaints = OptionPaints(fillPaint, resultPaint)
val rect = RectF(0f, 0f, width.toFloat(), height.toFloat())
roundRect = RoundRect(rect, borderRadius, borderStrokeWidth)
borderView.border = adjustedOptionStyle.border
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
roundRect = roundRect?.copy(rectF = RectF(0f, 0f, width.toFloat(), height.toFloat()))
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
roundRect?.rectF?.let {
if (backgroundImage == null) canvas.drawRoundRect(it, roundRect!!.borderRadius, roundRect!!.borderRadius, optionPaints.fillPaint)
}
}
private var clipPath: Path? = null
override fun draw(canvas: Canvas?) {
clipPath?.let { canvas?.clipPath(it) }
super.draw(canvas)
}
fun goToResultsState(votingShare: Int, isSelectedOption: Boolean, optionStyle: TextPollOption, shouldAnimate: Boolean, optionWidth: Float?, maxVotingShare: Int) {
bindVotePercentageText(votingShare, optionStyle)
votePercentageText.visibility = View.VISIBLE
bindVoteIndicatorText(optionStyle)
if (isSelectedOption) voteIndicatorView.visibility = View.VISIBLE
val borderWidth = optionStyle.border.width.dpAsPx(resources.displayMetrics)
val totalBorderWidth = borderWidth * 2
val viewHeight = optionStyle.height.dpAsPx(resources.displayMetrics) + totalBorderWidth
val viewWidth = (optionWidth?.dpAsPx(resources.displayMetrics))?.minus(totalBorderWidth) ?: mainLayout.width
textPollProgressBar.viewHeight = viewHeight.toFloat()
textPollProgressBar.visibility = View.VISIBLE
textPollProgressBar.fillPaint = optionPaints.resultPaint
optionTextView.run {
gravity = Gravity.CENTER_VERTICAL
val marginInPixels = 16.dpAsPx(resources.displayMetrics)
text = optionStyle.text.rawValue
setupRelativeLayoutParams(
width = LayoutParams.WRAP_CONTENT,
height = LayoutParams.MATCH_PARENT,
leftMargin = marginInPixels
) {
addRule(ALIGN_PARENT_LEFT)
}
val widthOfOtherViews =
calculateWidthWithoutOptionText(voteIndicatorView, votePercentageText, isSelectedOption, maxVotingShare)
maxWidth = viewWidth - widthOfOtherViews
}
isClickable = false
contentDescription = if (isSelectedOption) {
"Your vote ${optionStyle.text.rawValue}, $votingShare percent"
} else {
"${optionStyle.text.rawValue}, $votingShare percent"
}
if (shouldAnimate) {
performResultsAnimation(votingShare, (optionStyle.resultFillColor.alpha * 255).toInt(), viewWidth.toFloat())
} else {
immediatelyGoToResultsState(votingShare, (optionStyle.resultFillColor.alpha * 255).toInt(), viewWidth.toFloat(), viewHeight.toFloat())
}
}
private fun immediatelyGoToResultsState(votingShare: Int, resultFillAlpha: Int, viewWidth: Float, viewHeight: Float) {
currentVote = votingShare
textPollProgressBar.viewHeight = viewHeight
textPollProgressBar.barValue = viewWidth / 100 * votingShare
textPollProgressBar.visibility = View.VISIBLE
votePercentageText.alpha = 1f
optionPaints.resultPaint.alpha = resultFillAlpha
voteIndicatorView.alpha = 1f
votePercentageText.text = "$votingShare%"
}
private val easeInEaseOutInterpolator = TimeInterpolator { input ->
val inputSquared = input * input
inputSquared / (2.0f * (inputSquared - input) + 1.0f)
}
private fun performResultsAnimation(votingShare: Int, resultFillAlpha: Int, viewWidth: Float) {
currentVote = votingShare
voteIndicatorView.alpha = 1f
val adjustedViewWidth = viewWidth / 100
val alphaAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
duration = ALPHA_DURATION
addUpdateListener {
votePercentageText.alpha = it.animatedFraction
}
}
val resultFillAlphaAnimator = ValueAnimator.ofInt(0, resultFillAlpha).apply {
duration = RESULT_FILL_ALPHA_DURATION
addUpdateListener {
optionPaints.resultPaint.alpha = (it.animatedValue as Int)
}
}
val resultsAnimation = ValueAnimator.ofFloat(0f, votingShare.toFloat()).apply {
duration = RESULT_FILL_PROGRESS_DURATION
addUpdateListener {
val animatedValue = it.animatedValue as Float
votePercentageText.text = "${animatedValue.toInt()}%"
textPollProgressBar.barValue = adjustedViewWidth * animatedValue
}
}
AnimatorSet().apply { playTogether(alphaAnimator, resultFillAlphaAnimator, resultsAnimation)
interpolator = easeInEaseOutInterpolator
}.start()
}
fun updateResults(votingShare: Int) {
val resultProgressFillAnimator = ValueAnimator.ofFloat(currentVote.toFloat(), votingShare.toFloat()).apply {
duration = RESULT_FILL_PROGRESS_DURATION
addUpdateListener {
val animatedValue = it.animatedValue as Float
votePercentageText.text = "${animatedValue.toInt()}%"
textPollProgressBar.barValue = mainLayout.width.toFloat() / 100 * animatedValue
}
interpolator = easeInEaseOutInterpolator
}
resultProgressFillAnimator.start()
currentVote = votingShare
}
private fun calculateWidthWithoutOptionText(
voteIndicatorView: AppCompatTextView,
votePercentageText: AppCompatTextView,
isSelectedOption: Boolean,
maxVotingShare: Int
): Int {
voteIndicatorView.measure(0, 0)
val previousText = votePercentageText.text
votePercentageText.text = if(maxVotingShare == 100) "100%" else "88%"
votePercentageText.measure(0, 0)
votePercentageText.text = previousText
val voteIndicatorWidth =
if (isSelectedOption) voteIndicatorView.measuredWidth + (voteIndicatorView.layoutParams as MarginLayoutParams).marginStart else 0
val votePercentageMargins =
(votePercentageText.layoutParams as MarginLayoutParams).marginEnd + (votePercentageText.layoutParams as MarginLayoutParams).marginStart
val votePercentageWidth = votePercentageText.measuredWidth + votePercentageMargins
val optionEndMargin = (optionTextView.layoutParams as MarginLayoutParams).marginStart
return voteIndicatorWidth + optionEndMargin + votePercentageWidth
}
private fun bindVotePercentageText(
votingShare: Int,
optionStyle: TextPollOption
) {
votePercentageText.run {
textSize = (optionStyle.text.font.size * RESULTS_TEXT_SCALE_FACTOR)
votePercentageText.text = "$votingShare%"
setLineSpacing(0f, 1.0f)
includeFontPadding = false
setTextColor(optionStyle.text.color.asAndroidColor())
val font = optionStyle.text.font.weight.getIncreasedFontWeight().mapToFont()
typeface = Typeface.create(font.fontFamily, font.fontStyle)
}
}
private fun FontWeight.getIncreasedFontWeight(): FontWeight {
return FontWeight.values().getOrElse(this.ordinal + 2) { FontWeight.Black }
}
private fun bindVoteIndicatorText(optionStyle: TextPollOption) {
voteIndicatorView.run {
text = "\u2022"
textSize = optionStyle.text.font.size.toFloat()
setLineSpacing(0f, 1.0f)
includeFontPadding = false
setTextColor(optionStyle.text.color.asAndroidColor())
val font = optionStyle.text.font.weight.mapToFont()
typeface = Typeface.create(font.fontFamily, font.fontStyle)
}
}
}
private data class OptionPaints(
val fillPaint: Paint = Paint(),
val resultPaint: Paint = Paint()
)
private data class ResultRect(var left: Float, var top: Float, var right: Float, var bottom: Float)
internal class TextPollProgressBar(context: Context?) : View(context) {
var viewHeight: Float? = null
var barValue = 0f
set(value) {
field = value
resultRect.right = value
invalidate()
}
var fillPaint = Paint()
private var resultRect: ResultRect = ResultRect(0f, 0f, 0f, 0f)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawRect(0f, 0f, resultRect.right, viewHeight ?: 0f, fillPaint)
}
}
| apache-2.0 | 7bc5959272f6c4ffca3c4019a9f554c3 | 37.814554 | 166 | 0.681887 | 4.754169 | false | false | false | false |
MaKToff/Codename_Ghost | core/src/com/cypress/CGHelpers/AssetLoader.kt | 1 | 8701 | package com.cypress.CGHelpers
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.audio.Sound
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.cypress.GameObjects.Bullet
import java.util.*
/** Loads assets of project. */
public class AssetLoader {
public val manager = AssetManager()
public val levelsBG = Array(9, { LinkedList<Texture?>() })
public val levelsFP = Array<Texture?>(9, { null } )
public val gunNames = arrayOf("uzi", "shotgun", "assaultRiffle", "plasmagun",
"lasergun", "minigun", "rocketLauncher")
public val ammoNames = Array(7, {i -> gunNames[i] + "_ammo"})
public val bulletsList = LinkedList<Bullet>()
public val maxCapacity = arrayOf(30, 8, 45, 25, 50, 100, 1)
public val bulletDamage = arrayOf(10, 20, 15, 25, 20, 15, 40)
public val rateOfFire = arrayOf(20, 50, 13, 35, 15, 7, 90)
public val levelsMusic = Array<Music?>(9, { null })
public val shot = Array<Sound?>(7, { null })
public val reload = Array<Sound?>(7, { null })
public val happy = Array<Sound?>(3, { null })
public val eats = Array<Sound?>(4, { null })
public val neutral = Array<Sound?>(3, { null })
public var musicOn = true
public var language = "english"
public var zoom = 1.25f
public var godMode = false
public var logo : Texture? = null
public var main : Texture? = null
public var buttons : Texture? = null
public var settings : Texture? = null
public var about : Texture? = null
public var player : Texture? = null
public var guns : Texture? = null
public var bullets : Texture? = null
public var levels : Texture? = null
public var warrior : Texture? = null
public var items : Texture? = null
public var effects : Texture? = null
public var activeMusic : Music? = null
public var mainTheme : Music? = null
public var gameOver : Music? = null
public var snow : Music? = null
public var fan : Sound? = null
public var explosion : Sound? = null
companion object {
private var _instance : AssetLoader = AssetLoader()
fun getInstance() : AssetLoader = _instance
}
/** Loads main resources to AssetManager. */
public fun load() {
// loading of images
val textureLoadList = arrayOf("logo", "main", "buttons", "settings", "about", "player",
"guns", "bullets", "levels", "warrior", "items", "effects")
for (t in textureLoadList) manager.load("data/images/" + t + ".png", Texture::class.java)
// loading of music and sounds
manager.load("data/sounds/music/MainTheme.ogg", Music::class.java)
manager.load("data/sounds/music/GameOver.ogg", Music::class.java)
val soundLoadList = arrayOf("uzi", "shotgun", "assaultRiffle", "plasmagun", "lasergun",
"minigun", "rocketLauncher")
for (s in soundLoadList) {
manager.load("data/sounds/weapons/" + s + ".ogg", Sound::class.java)
manager.load("data/sounds/weapons/" + s + "_reload.ogg", Sound::class.java)
}
manager.load("data/sounds/weapons/explosion.ogg", Sound::class.java)
val voiceLoadList = arrayOf("yeah1", "yeah2", "yeah3", "yum1", "yum2", "yum3", "yum4",
"neutral1", "neutral2", "neutral3")
for (v in voiceLoadList) manager.load("data/sounds/player/" + v + ".ogg", Sound::class.java)
manager.finishLoading()
logo = manager.get("data/images/logo.png")
main = manager.get("data/images/main.png")
buttons = manager.get("data/images/buttons.png")
settings = manager.get("data/images/settings.png")
about = manager.get("data/images/about.png")
player = manager.get("data/images/player.png")
guns = manager.get("data/images/guns.png")
bullets = manager.get("data/images/bullets.png")
levels = manager.get("data/images/levels.png")
warrior = manager.get("data/images/warrior.png")
items = manager.get("data/images/items.png")
effects = manager.get("data/images/effects.png")
mainTheme = manager.get("data/sounds/music/MainTheme.ogg")
gameOver = manager.get("data/sounds/music/GameOver.ogg")
explosion = manager.get("data/sounds/weapons/explosion.ogg")
for (i in 0 .. 6) shot[i] = manager.get("data/sounds/weapons/" + gunNames[i] + ".ogg")
for (i in 0 .. 6) reload[i] = manager.get("data/sounds/weapons/" + gunNames[i] + "_reload.ogg")
for (i in 0 .. 2) happy[i] = manager.get("data/sounds/player/yeah" + (i + 1) + ".ogg")
for (i in 0 .. 3) eats[i] = manager.get("data/sounds/player/yum" + (i + 1) + ".ogg")
for (i in 0 .. 2) neutral[i] = manager.get("data/sounds/player/neutral" + (i + 1) + ".ogg")
}
/** Generates font with given parameters. */
public fun generateFont(fileName : String, size : Int, color : Color) : BitmapFont {
val generator = FreeTypeFontGenerator(Gdx.files.internal("data/fonts/" + fileName))
var parameter = FreeTypeFontGenerator.FreeTypeFontParameter()
parameter.size = size
parameter.color = color
val RUSSIAN_CHARACTERS = "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"
val ENGLISH_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
val DIGITS_AND_SYMBOLS = "0123456789`~!@#$%^&*()-_+=[]{}?/\\,.<>'|:;,\"®©∞"
parameter.characters = RUSSIAN_CHARACTERS + ENGLISH_CHARACTERS + DIGITS_AND_SYMBOLS
val font = generator.generateFont(parameter)
generator.dispose()
return font
}
/** Returns image button style with given parameters. */
fun getImageButtonStyle(x1 : Int, y1 : Int, x2 : Int, y2 : Int, height : Int, width : Int,
checkedRequired : Boolean) : ImageButton.ImageButtonStyle {
// skin for button
val skin = Skin()
skin.add("button-up", TextureRegion(buttons, x1, y1, height, width))
skin.add("button-down", TextureRegion(buttons, x2, y2, height, width))
val style = ImageButton.ImageButtonStyle()
style.up = skin.getDrawable("button-up")
style.down = skin.getDrawable("button-down")
if (checkedRequired) style.checked = skin.getDrawable("button-down")
return style
}
/** Returns text button style with given parameters. */
fun getTextButtonStyle(x1 : Int, y1 : Int, x2 : Int, y2 : Int, height : Int, width : Int,
font : BitmapFont) : TextButton.TextButtonStyle {
// skin for button
val skin = Skin()
skin.add("button-up", TextureRegion(buttons, x1, y1, height, width))
skin.add("button-down", TextureRegion(buttons, x2, y2, height, width))
val style = TextButton.TextButtonStyle()
style.font = font
style.up = skin.getDrawable("button-up")
style.down = skin.getDrawable("button-down")
return style
}
/** Loads resources of level 1 to AssetManager. */
public fun loadLevel1() {
// loading of images
val textureLoadList = arrayOf("background.png", "background2.png", "firstplan.png")
for (t in textureLoadList) manager.load("data/images/level1/" + t, Texture::class.java)
// loading of music and sounds
manager.load("data/sounds/music/Level1.ogg", Music::class.java)
manager.load("data/sounds/world/snow.ogg", Music::class.java)
manager.load("data/sounds/world/fan.ogg", Sound::class.java)
manager.finishLoading()
for (i in 0 .. 1) levelsBG[1].add(manager.get("data/images/level1/" + textureLoadList[i]))
levelsFP[1] = (manager.get("data/images/level1/firstplan.png"))
levelsMusic[1] = manager.get("data/sounds/music/Level1.ogg")
snow = manager.get("data/sounds/world/snow.ogg")
fan = manager.get("data/sounds/world/fan.ogg")
}
} | apache-2.0 | 6ec6a10f9642ec1753ed55db3debbcd7 | 45.913043 | 104 | 0.620206 | 3.632576 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/ui/navigation/NavigationView.kt | 1 | 5284 | package io.rover.sdk.experiences.ui.navigation
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.transition.Slide
import androidx.transition.TransitionManager
import androidx.transition.TransitionSet
import android.util.AttributeSet
import android.util.LruCache
import android.view.Gravity
import android.view.View
import android.widget.FrameLayout
import io.rover.sdk.core.streams.androidLifecycleDispose
import io.rover.sdk.core.streams.subscribe
import io.rover.sdk.experiences.platform.whenNotNull
import io.rover.sdk.experiences.ui.concerns.ViewModelBinding
import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView
import io.rover.sdk.experiences.ui.layout.screen.ScreenView
import io.rover.sdk.experiences.ui.layout.screen.ScreenViewModelInterface
/**
* Navigation behaviour between screens of an Experience.
*/
internal class NavigationView : FrameLayout, MeasuredBindableView<NavigationViewModelInterface> {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
// TODO: implement an onCreate and if inEditMode() display a "Rover Experience" text view.
/**
* The current view, stored so we can yield an android state parcelable and thus enable
* state restore.
*/
private var activeView: ScreenView? = null
private val viewCache: LruCache<ScreenViewModelInterface, ScreenView> = object : LruCache<ScreenViewModelInterface, ScreenView>(3) {
override fun entryRemoved(evicted: Boolean, key: ScreenViewModelInterface?, oldValue: ScreenView?, newValue: ScreenView?) {
removeView(oldValue)
}
}
private fun getViewForScreenViewModel(screenViewModel: ScreenViewModelInterface): ScreenView {
return viewCache[screenViewModel] ?: ScreenView(
context
).apply {
[email protected](this)
this.visibility = View.GONE
viewCache.put(screenViewModel, this)
this.viewModelBinding = MeasuredBindableView.Binding(screenViewModel)
}
}
override var viewModelBinding: MeasuredBindableView.Binding<NavigationViewModelInterface>? by ViewModelBinding { binding, subscriptionCallback ->
val viewModel = binding?.viewModel
viewModel?.screen?.androidLifecycleDispose(this)?.subscribe({ screenUpdate ->
if (!screenUpdate.animate) {
val newView = getViewForScreenViewModel(screenUpdate.screenViewModel)
activeView?.visibility = GONE
newView.visibility = VISIBLE
activeView = newView
} else {
if (screenUpdate.backwards) {
val newView = getViewForScreenViewModel(screenUpdate.screenViewModel)
newView.bringToFront()
newView.visibility = GONE
val set = TransitionSet().apply {
addTransition(
Slide(
Gravity.START
).addTarget(newView)
)
activeView.whenNotNull { activeView ->
addTransition(
Slide(
Gravity.END
).addTarget(activeView)
)
}
}
TransitionManager.beginDelayedTransition(this, set)
activeView.whenNotNull {
it.visibility = GONE
}
newView.visibility = VISIBLE
activeView = newView
} else {
// forwards
val newView = getViewForScreenViewModel(screenUpdate.screenViewModel)
newView.bringToFront()
newView.visibility = GONE
val set = TransitionSet().apply {
activeView.whenNotNull { activeView ->
addTransition(
Slide(
Gravity.START
).addTarget(activeView)
)
}
addTransition(
Slide(
Gravity.END
).addTarget(newView)
)
}
TransitionManager.beginDelayedTransition(this, set)
newView.visibility = VISIBLE
activeView.whenNotNull { it.visibility = GONE }
activeView = newView
}
}
}, { error -> throw error }, { subscription -> subscriptionCallback(subscription) })
viewModel?.start()
}
}
| apache-2.0 | ed4a515b5edcc27185eac9dee02f1c3c | 41.272 | 149 | 0.58592 | 5.95045 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/stored/library/items/StoredItemAccess.kt | 1 | 5790 | package com.lasthopesoftware.bluewater.client.stored.library.items
import android.content.Context
import com.lasthopesoftware.bluewater.client.browsing.items.IItem
import com.lasthopesoftware.bluewater.client.browsing.items.Item
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItem.ItemType
import com.lasthopesoftware.bluewater.repository.InsertBuilder.Companion.fromTable
import com.lasthopesoftware.bluewater.repository.RepositoryAccessHelper
import com.lasthopesoftware.bluewater.repository.fetch
import com.lasthopesoftware.bluewater.repository.fetchFirst
import com.lasthopesoftware.resources.executors.ThreadPools
import com.namehillsoftware.handoff.promises.Promise
import com.namehillsoftware.handoff.promises.queued.MessageWriter
import com.namehillsoftware.handoff.promises.queued.QueuedPromise
class StoredItemAccess(private val context: Context) : IStoredItemAccess {
override fun toggleSync(libraryId: LibraryId, item: IItem, enable: Boolean) {
val inferredItem = inferItem(item)
if (enable) enableItemSync(libraryId, inferredItem, StoredItemHelpers.getListType(inferredItem))
else disableItemSync(libraryId, inferredItem, StoredItemHelpers.getListType(inferredItem))
}
override fun isItemMarkedForSync(libraryId: LibraryId, item: IItem): Promise<Boolean> =
QueuedPromise(MessageWriter{
RepositoryAccessHelper(context).use { repositoryAccessHelper ->
val inferredItem = inferItem(item)
isItemMarkedForSync(
repositoryAccessHelper,
libraryId,
inferredItem,
StoredItemHelpers.getListType(inferredItem)
)
}
}, ThreadPools.databaseTableExecutor<StoredItem>())
override fun disableAllLibraryItems(libraryId: LibraryId): Promise<Unit> =
QueuedPromise(MessageWriter{
RepositoryAccessHelper(context).use { repositoryAccessHelper ->
repositoryAccessHelper.beginTransaction().use { closeableTransaction ->
repositoryAccessHelper
.mapSql("DELETE FROM ${StoredItem.tableName} WHERE ${StoredItem.libraryIdColumnName} = @${StoredItem.libraryIdColumnName}")
.addParameter(StoredItem.libraryIdColumnName, libraryId.id)
.execute()
closeableTransaction.setTransactionSuccessful()
}
}
}, ThreadPools.databaseTableExecutor<StoredItem>())
private fun enableItemSync(libraryId: LibraryId, item: IItem, itemType: ItemType) {
QueuedPromise(MessageWriter{
RepositoryAccessHelper(context).use { repositoryAccessHelper ->
if (isItemMarkedForSync(repositoryAccessHelper, libraryId, item, itemType)) return@MessageWriter
repositoryAccessHelper.beginTransaction().use { closeableTransaction ->
repositoryAccessHelper
.mapSql(storedItemInsertSql)
.addParameter(StoredItem.libraryIdColumnName, libraryId.id)
.addParameter(StoredItem.serviceIdColumnName, item.key)
.addParameter(StoredItem.itemTypeColumnName, itemType)
.execute()
closeableTransaction.setTransactionSuccessful()
}
}
}, ThreadPools.databaseTableExecutor<StoredItem>())
}
private fun disableItemSync(libraryId: LibraryId, item: IItem, itemType: ItemType) {
QueuedPromise(MessageWriter{
RepositoryAccessHelper(context).use { repositoryAccessHelper ->
repositoryAccessHelper.beginTransaction().use { closeableTransaction ->
repositoryAccessHelper
.mapSql("""
DELETE FROM ${StoredItem.tableName}
WHERE ${StoredItem.serviceIdColumnName} = @${StoredItem.serviceIdColumnName}
AND ${StoredItem.libraryIdColumnName} = @${StoredItem.libraryIdColumnName}
AND ${StoredItem.itemTypeColumnName} = @${StoredItem.itemTypeColumnName}""")
.addParameter(StoredItem.serviceIdColumnName, item.key)
.addParameter(StoredItem.libraryIdColumnName, libraryId.id)
.addParameter(StoredItem.itemTypeColumnName, itemType)
.execute()
closeableTransaction.setTransactionSuccessful()
}
}
}, ThreadPools.databaseTableExecutor<StoredItem>())
}
override fun promiseStoredItems(libraryId: LibraryId): Promise<Collection<StoredItem>> =
QueuedPromise(MessageWriter{
RepositoryAccessHelper(context).use { repositoryAccessHelper ->
repositoryAccessHelper
.mapSql("SELECT * FROM ${StoredItem.tableName} WHERE ${StoredItem.libraryIdColumnName} = @${StoredItem.libraryIdColumnName}")
.addParameter(StoredItem.libraryIdColumnName, libraryId.id)
.fetch()
}
}, ThreadPools.databaseTableExecutor<StoredItem>())
companion object {
private val storedItemInsertSql by lazy {
fromTable(StoredItem.tableName)
.addColumn(StoredItem.libraryIdColumnName)
.addColumn(StoredItem.serviceIdColumnName)
.addColumn(StoredItem.itemTypeColumnName)
.build()
}
private fun isItemMarkedForSync(helper: RepositoryAccessHelper, libraryId: LibraryId, item: IItem, itemType: ItemType): Boolean {
return getStoredItem(helper, libraryId, item, itemType) != null
}
private fun getStoredItem(helper: RepositoryAccessHelper, libraryId: LibraryId, item: IItem, itemType: ItemType): StoredItem? {
return helper.mapSql("""
SELECT * FROM ${StoredItem.tableName}
WHERE ${StoredItem.serviceIdColumnName} = @${StoredItem.serviceIdColumnName}
AND ${StoredItem.libraryIdColumnName} = @${StoredItem.libraryIdColumnName}
AND ${StoredItem.itemTypeColumnName} = @${StoredItem.itemTypeColumnName}""")
.addParameter(StoredItem.serviceIdColumnName, item.key)
.addParameter(StoredItem.libraryIdColumnName, libraryId.id)
.addParameter(StoredItem.itemTypeColumnName, itemType)
.fetchFirst()
}
private fun inferItem(item: IItem): IItem {
if (item is Item) {
val playlist = item.playlist
if (playlist != null) return playlist
}
return item
}
}
}
| lgpl-3.0 | dea3429581a6f092adfa969f6b4d2e6a | 43.538462 | 131 | 0.779275 | 4.509346 | false | false | false | false |
danwime/eazyajax | core/src/me/danwi/ezajax/middleware/InvokeChecker.kt | 1 | 964 | package me.danwi.ezajax.middleware
import me.danwi.ezajax.container.Current
import me.danwi.ezajax.container.container
import me.danwi.ezajax.util.EzError
/**
* 调用中间件
* Created by demon on 2017/2/14.
*/
val InvokeChecker = {
val req = Current.request
val res = Current.response
val matchResult = Regex("\\/ezajax\\/(\\S+)\\/(\\S+)\\.ac").find(req.requestURI)
if (matchResult != null) {
val moduleName = (matchResult.groups[1] ?: throw EzError(-2, "调用路径解析错误")).value
val methodName = (matchResult.groups[2] ?: throw EzError(-2, "调用路径解析错误")).value
Current.module = container[moduleName] ?: throw EzError(-2, "模块 $moduleName 找不到")
Current.method = Current.module.methods[methodName] ?: throw EzError(-2, "方法 $moduleName.$methodName 找不到")
true
} else {
res.error(-2, "非法的请求路径:${req.requestURI}")
false
}
}
| apache-2.0 | a0c7bcac52bb67259b5d9ee8988169ad | 33.153846 | 114 | 0.649775 | 3.376426 | false | false | false | false |
ahmedeltaher/MVP-Sample | app/src/main/java/com/task/data/remote/dto/NewsModel.kt | 1 | 1007 | package com.task.data.remote.dto
import com.google.gson.annotations.SerializedName
/**
* we define all the variables as @var, because it might happen that backend send some values as
* null
*/
/**
* you can convert your json to kotlin data class in easy simple way, by using
* @(JSON To Kotlin Class) plugin in android studio, you can install the plugin as any other
* plugin and then use it, for more details check here:
* https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass-
*/
data class NewsModel(@SerializedName("status") var status: String? = null,
@SerializedName("copyright") var copyright: String? = null,
@SerializedName("section") var section: String? = null,
@SerializedName("last_updated") var lastUpdated: String? = null,
@SerializedName("num_results") var numResults: Long? = null,
@SerializedName("results") var newsItems: List<NewsItem>? = null)
| apache-2.0 | 130caef20d806b519cf5edabfd95db03 | 49.35 | 96 | 0.670308 | 4.340517 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/find/qidiantu/list/QidiantuListPresenter.kt | 1 | 9920 | @file:Suppress("DEPRECATION")
package cc.aoeiuv020.panovel.find.qidiantu.list
import android.annotation.SuppressLint
import android.content.Context
import androidx.annotation.MainThread
import androidx.annotation.WorkerThread
import cc.aoeiuv020.anull.notNull
import cc.aoeiuv020.base.jar.absHref
import cc.aoeiuv020.encrypt.hex
import cc.aoeiuv020.irondb.Database
import cc.aoeiuv020.irondb.Iron
import cc.aoeiuv020.irondb.read
import cc.aoeiuv020.irondb.write
import cc.aoeiuv020.okhttp.OkHttpUtils
import cc.aoeiuv020.okhttp.string
import cc.aoeiuv020.panovel.Presenter
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.CacheManager
import cc.aoeiuv020.panovel.data.DataManager
import cc.aoeiuv020.panovel.report.Reporter
import cc.aoeiuv020.panovel.settings.LocationSettings
import cc.aoeiuv020.regex.pick
import org.jetbrains.anko.*
import org.jsoup.Jsoup
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
@Suppress("SameParameterValue")
class QidiantuListPresenter : Presenter<QidiantuListActivity>(), AnkoLogger {
private var requesting = false
private lateinit var baseUrl: String
private val executorService: ExecutorService = Executors.newSingleThreadExecutor()
private var currentWorker: Future<Unit>? = null
private val maxRetry = 5
private lateinit var keyCache: String
@SuppressLint("SimpleDateFormat")
private lateinit var root: Database
fun start(ctx: Context, url: String) {
debug { "start," }
this.baseUrl = url
keyCache = url.toByteArray().hex()
root = initCacheLocation(ctx)
loadCache()
}
fun refresh() {
debug { "refresh," }
if (requesting) {
stop()
}
request()
}
fun stop() {
val future = currentWorker ?: return
requesting = false
future.cancel(true)
}
@MainThread
private fun request() {
requesting = true
currentWorker = view?.doAsync({ t ->
if (t is InterruptedException) {
info { "stopped" }
return@doAsync
}
requesting = false
view?.runOnUiThread {
showFailed("获取小说列表失败", t)
}
}, executorService) {
val ret = mutableListOf<Item>()
val head = mutableListOf<Post>()
var title = ""
var code = -1
var retry = 0
while (requesting && code != 200 && ret.isEmpty() && retry < maxRetry) {
retry++
val response = OkHttpUtils.get(baseUrl).execute()
code = response.code()
if (code != 200) {
uiThread {
showProgress(retry)
}
Thread.sleep(200)
continue
}
OkHttpUtils.get(baseUrl).string()
val html = response.body().notNull().string()
val root = Jsoup.parse(html, baseUrl)
try {
title = root.selectFirst("div.panel-heading > h1").text().removePrefix("起点新书上架首订")
} catch (e: Exception) {
error({ "解析标题失败" }, e)
}
try {
root.select("div.panel-heading > a").forEach {
head.add(Post(it.text(), it.absHref()))
}
} catch (e: Exception) {
error({ "解析头部链接失败" }, e)
}
val nameList = try {
root.select("#shouding_table > thead > tr > th").map { it.text() }
} catch (e: Exception) {
throw IllegalStateException("解析小说列表标头", e)
}
try {
root.select("#shouding_table > tbody > tr")
?.takeIf { it.isNotEmpty() }.notNull()
} catch (e: Exception) {
throw IllegalStateException("解析小说列表失败", e)
}.mapNotNull { tr ->
val realOrder = mapOf(
"order" to "#",
"name" to "书名",
"type" to "分类",
"author" to "作者",
"level" to "等级",
"fans" to "粉丝",
"collection" to "收藏",
"firstOrder" to "首订",
"ratio" to "收订比",
"words" to "字数",
"dateAdded" to "首V时刻"
).mapValues { (_, value) ->
nameList.indexOfFirst { it.contains(value) }
}
val children = tr.children()
if (children.size == 1 && children.first().text().contains("无新书上架")) {
return@mapNotNull null
}
val (name, url) = try {
children[realOrder["name"].notNull("name")].child(0).run {
Pair(text(), absHref())
}
} catch (e: Exception) {
throw IllegalStateException("解析书名失败", e)
}
val author = try {
children[realOrder["author"].notNull("author")].text()
} catch (e: Exception) {
throw IllegalStateException("解析作者名失败", e)
}
val itemOrder = listOf(
"level",
"type",
"words",
"collection",
"firstOrder",
"ratio",
"dateAdded"
)
val info = itemOrder.map {
val index = realOrder[it]
try {
val value: String =
children[(index?.takeIf { i -> i != -1 }).notNull(it)].text() ?: ""
if (it == "type") {
value.pick("\\[([^\\]]*)\\]").first().toString()
} else {
value
}
} catch (e: Exception) {
error({ "解析信息失败: $index" }, e)
""
}
}
ret.add(
Item(
url, name, author,
info[0], info[1], info[2],
info[3], info[4], info[5],
info[6]
)
)
}
}
saveCache(ret, head, title)
uiThread {
showResult(ret, head, title)
}
}
}
@MainThread
private fun loadCache() {
currentWorker = view?.doAsync({ t ->
if (t is InterruptedException) {
info { "stopped" }
return@doAsync
}
view?.runOnUiThread {
showFailed("加载小说列表缓存失败", t)
}
}, executorService) {
val data = root.read<List<Item>>(keyCache) ?: run {
uiThread {
request()
}
return@doAsync
}
val head = root.read<List<Post>>(keyCache + "head") ?: listOf()
val title = root.read<String>(keyCache + "title") ?: ""
uiThread {
showResult(data, head, title)
}
}
}
@WorkerThread
private fun saveCache(data: List<Item>, head: List<Post>, title: String) {
root.write(keyCache, data)
root.write(keyCache + "head", head)
root.write(keyCache + "title", title)
}
private fun initCacheLocation(ctx: Context): Database = try {
Iron.db(File(LocationSettings.cacheLocation))
} catch (e: Exception) {
Reporter.post("初始化缓存目录<${LocationSettings.cacheLocation}>失败,", e)
ctx.toast(
ctx.getString(
R.string.tip_init_cache_failed_place_holder,
LocationSettings.cacheLocation
)
)
// 失败一次就改成默认的,以免反复失败,
LocationSettings.cacheLocation = ctx.cacheDir.resolve(CacheManager.NAME_FOLDER).absolutePath
Iron.db(File(LocationSettings.cacheLocation))
}.sub("Qidiantu")
private fun showResult(data: List<Item>, head: List<Post>, title: String) {
view?.showResult(data, head, title)
}
private fun showProgress(retry: Int) {
view?.showProgress(retry, maxRetry)
}
private fun showFailed(message: String, t: Throwable) {
error(message, t)
view?.showError(message, t)
}
fun browse() {
view?.innerBrowse(baseUrl)
}
fun open(item: Item, bookId: String) {
debug { "open <$item>," }
view?.doAsync({ e ->
val message = "打开地址<$item>失败,"
Reporter.post(message, e)
error(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
val novelManager = DataManager.query("起点中文", item.author, item.name, bookId)
val novel = novelManager.novel
uiThread {
view?.openNovelDetail(novel)
}
}
}
} | gpl-3.0 | 9a6ebd4e7dd8f3020d75d01fbe8a7d0b | 34.050909 | 102 | 0.470533 | 4.816592 | false | false | false | false |
cloose/luftbild4p3d | src/main/kotlin/org/luftbild4p3d/bing/PixelCoordinates.kt | 1 | 845 | package org.luftbild4p3d.bing
fun Int.clippedTo(minValue: Double, maxValue: Double) = Math.min(Math.max(this.toDouble(), minValue), maxValue)
data class PixelCoordinates(val x: Int, val y: Int, val levelOfDetail: LevelOfDetail) {
fun toTile(): Tile {
val x = Math.floor(x.toDouble() / Tile.SIZE).toInt()
val y = Math.floor(y.toDouble() / Tile.SIZE).toInt()
return Tile(x, y, levelOfDetail)
}
fun toWgs84Coordinates(): Wgs84Coordinates {
val mapSize = Tile.SIZE shl levelOfDetail.bingLOD
val x = (x.clippedTo(0.0, mapSize - 1.0) / mapSize) - 0.5
val y = 0.5 - (y.clippedTo(0.0, mapSize - 1.0) / mapSize)
var latitude = 90 - 360 * Math.atan(Math.exp(-y * 2 * Math.PI)) / Math.PI
var longitude = 360 * x
return Wgs84Coordinates(latitude, longitude)
}
} | gpl-3.0 | 7bfda029783716535b1f9fd851fbe386 | 32.84 | 111 | 0.630769 | 3.188679 | false | false | false | false |
rcgroot/open-gpstracker-ng | studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/control/ControlBindingAdapters.kt | 1 | 2897 | package nl.sogeti.android.gpstracker.ng.features.control
import androidx.databinding.BindingAdapter
import com.google.android.material.floatingactionbutton.FloatingActionButton
import android.view.View
import android.view.ViewGroup
import nl.sogeti.android.gpstracker.ng.features.databinding.CommonBindingAdapters
import nl.sogeti.android.gpstracker.service.integration.ServiceConstants.*
import nl.sogeti.android.opengpstrack.ng.features.R
class ControlBindingAdapters : CommonBindingAdapters() {
@BindingAdapter("state")
fun setState(container: ViewGroup, state: Int) {
val left = container.getChildAt(0) as FloatingActionButton
val right = container.getChildAt(1) as FloatingActionButton
cancelAnimations(left, right)
if (state == STATE_STOPPED) {
right.setImageResource(R.drawable.ic_navigation_black_24dp)
right.contentDescription = container.context.getString(R.string.control_record)
showOnlyRightButton(left, right)
} else if (state == STATE_LOGGING) {
left.setImageResource(R.drawable.ic_stop_black_24dp)
left.contentDescription = container.context.getString(R.string.control_stop)
right.setImageResource(R.drawable.ic_pause_black_24dp)
right.contentDescription = container.context.getString(R.string.control_pause)
showAllButtons(left, right)
} else if (state == STATE_PAUSED) {
right.setImageResource(R.drawable.ic_navigation_black_24dp)
right.contentDescription = container.context.getString(R.string.control_resume)
left.setImageResource(R.drawable.ic_stop_black_24dp)
left.contentDescription = container.context.getString(R.string.control_stop)
showAllButtons(left, right)
} else {
// state == STATE_UNKNOWN and illegal states
showNoButtons(left, right)
}
}
private fun showNoButtons(left: FloatingActionButton, right: FloatingActionButton) {
left.animate()
.alpha(0F)
right.animate()
.alpha(0F)
}
private fun showAllButtons(left: FloatingActionButton, right: FloatingActionButton) {
left.animate()
.alpha(1F)
right.animate()
.alpha(1F)
}
private fun showOnlyRightButton(left: FloatingActionButton, right: FloatingActionButton) {
left.animate()
.alpha(0F)
right.animate()
.alpha(1F)
}
private fun cancelAnimations(left: FloatingActionButton, right: FloatingActionButton) {
left.animate().cancel()
right.animate().cancel()
}
}
private val View.visible: Boolean
get() {
return this.visibility == View.VISIBLE
}
private val View.invisible: Boolean
get() {
return this.visibility != View.VISIBLE
}
| gpl-3.0 | c73e8170e728bc3f288f769501573f4b | 37.626667 | 94 | 0.673455 | 4.519501 | false | false | false | false |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/custom/MyBottomNavigationView.kt | 1 | 984 | package com.pickth.gachi.view.custom
import android.content.Context
import android.support.design.internal.BottomNavigationMenuView
import android.support.design.widget.BottomNavigationView
import android.util.AttributeSet
/**
* Created by yonghoon on 2017-07-20.
* Mail : [email protected]
*/
class MyBottomNavigationView(context: Context, attrs: AttributeSet): BottomNavigationView(context, attrs) {
init {
centerMenuIcon()
}
private fun centerMenuIcon() {
val menuView: BottomNavigationMenuView = getChildAt(0) as BottomNavigationMenuView
menuView::class.java.getDeclaredField("mShiftingMode").apply {
isAccessible = true
setBoolean(menuView, false)
isAccessible = false
}
// if(menuView != null) {
// for(i in 0..menuView.childCount-1) {
// val menuItemView = menuView.getChildAt(i) as BottomNavigationItemView
//
// }
// }
}
} | apache-2.0 | ea20e069900a97bbc79148ae34402530 | 27.970588 | 107 | 0.669715 | 4.278261 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/AppVersion.kt | 4 | 2714 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC 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.
*
* BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.os.Parcel
import android.os.Parcelable
data class AppVersion(
var appName: String? = null,
var versionNum: Int = 0,
var platform: String? = null,
var planClass: String? = null,
var apiVersion: String? = null,
var avgNoOfCPUs: Double = 0.0,
var maxNoOfCPUs: Double = 0.0,
var gpuRam: Double = 0.0,
var app: App? = null,
var project: Project? = null
) : Parcelable {
internal constructor(appName: String?, versionNum: Int) : this(appName) {
this.versionNum = versionNum
}
private constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readInt(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readDouble(),
parcel.readDouble(),
parcel.readDouble(),
parcel.readValue(App::class.java.classLoader) as App?,
parcel.readValue(Project::class.java.classLoader) as Project?
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(appName)
dest.writeInt(versionNum)
dest.writeString(platform)
dest.writeString(planClass)
dest.writeString(apiVersion)
dest.writeDouble(avgNoOfCPUs)
dest.writeDouble(maxNoOfCPUs)
dest.writeDouble(gpuRam)
dest.writeValue(app)
dest.writeValue(project)
}
object Fields {
const val APP_NAME = "app_name"
const val VERSION_NUM = "version_num"
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<AppVersion> = object : Parcelable.Creator<AppVersion> {
override fun createFromParcel(parcel: Parcel) = AppVersion(parcel)
override fun newArray(size: Int) = arrayOfNulls<AppVersion>(size)
}
}
}
| lgpl-3.0 | 89b5d98d44f7e52d973cced55eea9dd1 | 32.506173 | 95 | 0.646279 | 4.294304 | false | false | false | false |
LarsKrogJensen/graphql-kotlin | src/main/kotlin/graphql/execution/ValuesResolver.kt | 1 | 7422 | package graphql.execution
import graphql.GraphQLException
import graphql.language.Argument
import graphql.language.ObjectValue
import graphql.language.VariableDefinition
import graphql.language.VariableReference
import graphql.schema.GraphQLInputObjectField
import graphql.schema.GraphQLNonNull
import graphql.schema.GraphQLScalarType
import graphql.schema.GraphQLType
import graphql.language.*
import graphql.schema.*
import java.util.*
class ValuesResolver {
fun getVariableValues(schema: GraphQLSchema,
variableDefinitions: List<VariableDefinition>,
inputs: Map<String, Any>): Map<String, Any?> {
val result = LinkedHashMap<String, Any?>()
for (variableDefinition in variableDefinitions) {
result.put(variableDefinition.name, variableValue(schema, variableDefinition, inputs[variableDefinition.name]))
}
return result
}
fun argumentValues(argumentTypes: List<GraphQLArgument>,
arguments: List<Argument>,
variables: Map<String, Any?>): Map<String, Any?> {
val result = LinkedHashMap<String, Any?>()
val argumentMap = argumentMap(arguments)
for (fieldArgument in argumentTypes) {
val argument = argumentMap[fieldArgument.name]
val value = if (argument != null) {
coerceValueAst(fieldArgument.type, argument.value, variables)
} else {
fieldArgument.defaultValue
}
result.put(fieldArgument.name, value)
}
return result
}
private fun argumentMap(arguments: List<Argument>): Map<String, Argument> {
val result = LinkedHashMap<String, Argument>()
for (argument in arguments) {
result.put(argument.name, argument)
}
return result
}
private fun variableValue(schema: GraphQLSchema,
variableDefinition: VariableDefinition,
inputValue: Any?): Any? {
val type = TypeFromAST.getTypeFromAST(schema, variableDefinition.type)
if (!isValid(type, inputValue)) {
throw GraphQLException("Invalid value for type")
}
if (inputValue == null && variableDefinition.defaultValue != null) {
return coerceValueAst(type, variableDefinition.defaultValue, emptyMap())
}
return coerceValue(type, inputValue)
}
private fun isValid(type: GraphQLType?, inputValue: Any?): Boolean {
return true
}
private fun coerceValue(graphQLType: GraphQLType?, value: Any?): Any? {
if (graphQLType is GraphQLNonNull) {
return coerceValue(graphQLType.wrappedType, value) ?: throw GraphQLException("Null value for NonNull type " + graphQLType)
}
if (value == null) return null
if (graphQLType is GraphQLScalarType) {
return coerceValueForScalar(graphQLType, value)
} else if (graphQLType is GraphQLEnumType) {
return coerceValueForEnum(graphQLType, value)
} else if (graphQLType is GraphQLList) {
return coerceValueForList(graphQLType, value)
} else if (graphQLType is GraphQLInputObjectType) {
return coerceValueForInputObjectType(graphQLType, value as Map<String, Any>)
} else {
throw GraphQLException("unknown type " + graphQLType)
}
}
private fun coerceValueForInputObjectType(inputObjectType: GraphQLInputObjectType, input: Map<String, Any>): Any {
return inputObjectType.fields
.filter { input.containsKey(it.name) || alwaysHasValue(it) }
.associateBy({ it.name }, { coerceValue(it.type, input[it.name]) ?: it.defaultValue })
}
private fun alwaysHasValue(inputField: GraphQLInputObjectField): Boolean {
return inputField.defaultValue != null || inputField.type is GraphQLNonNull
}
private fun coerceValueForScalar(graphQLScalarType: GraphQLScalarType, value: Any): Any? {
return graphQLScalarType.coercing.parseValue(value)
}
private fun coerceValueForEnum(graphQLEnumType: GraphQLEnumType, value: Any): Any? {
return graphQLEnumType.coercing.parseValue(value)
}
private fun coerceValueForList(graphQLList: GraphQLList, value: Any): List<*> {
if (value is Iterable<*>) {
return value.map { coerceValue(graphQLList.wrappedType, it) }
} else {
return listOf(coerceValue(graphQLList.wrappedType, value))
}
}
private fun coerceValueAst(type: GraphQLType?,
inputValue: Value?,
variables: Map<String, Any?>): Any? {
if (inputValue is VariableReference) {
return variables[inputValue.name]
}
if (type is GraphQLScalarType) {
return type.coercing.parseLiteral(inputValue)
}
if (type is GraphQLNonNull) {
return coerceValueAst(type.wrappedType, inputValue, variables)
}
if (type is GraphQLInputObjectType) {
return coerceValueAstForInputObject(type, inputValue as ObjectValue, variables)
}
if (type is GraphQLEnumType) {
return type.coercing.parseLiteral(inputValue)
}
if (type is GraphQLList) {
return coerceValueAstForList(type, inputValue, variables)
}
return null
}
private fun coerceValueAstForList(graphQLList: GraphQLList, value: Value?, variables: Map<String, Any?>): Any {
if (value is ArrayValue) {
return value.values.map { coerceValueAst(graphQLList.wrappedType, it, variables) }
} else {
return listOf(coerceValueAst(graphQLList.wrappedType, value, variables))
}
}
private fun coerceValueAstForInputObject(type: GraphQLInputObjectType,
inputValue: ObjectValue,
variables: Map<String, Any?>): Any {
val result = LinkedHashMap<String, Any?>()
val inputValueFieldsByName = mapObjectValueFieldsByName(inputValue)
for (inputTypeField in type.fields) {
if (inputValueFieldsByName.containsKey(inputTypeField.name)) {
inputValueFieldsByName[inputTypeField.name]?.let { (name, value) ->
val fieldValue = coerceValueAst(inputTypeField.type, value, variables) ?: inputTypeField.defaultValue
result.put(name, fieldValue)
}
} else if (inputTypeField.defaultValue != null) {
result.put(inputTypeField.name, inputTypeField.defaultValue)
} else if (inputTypeField.type is GraphQLNonNull) {
// Possibly overkill; an object literal with a missing non null field shouldn't pass validation
throw GraphQLException("Null value for NonNull type " + inputTypeField.type)
}
}
return result
}
private fun mapObjectValueFieldsByName(inputValue: ObjectValue): Map<String, ObjectField> {
val inputValueFieldsByName = LinkedHashMap<String, ObjectField>()
for (objectField in inputValue.objectFields) {
inputValueFieldsByName.put(objectField.name, objectField)
}
return inputValueFieldsByName
}
}
| mit | 5afa9e8ed2bce4cdb96d39a38d62d814 | 38.269841 | 134 | 0.637833 | 4.981208 | false | false | false | false |
pushtorefresh/storio | storio-sqlite-annotations-processor/src/main/kotlin/com/pushtorefresh/storio3/sqlite/annotations/processor/generate/TableGenerator.kt | 2 | 4939 | package com.pushtorefresh.storio3.sqlite.annotations.processor.generate
import com.pushtorefresh.storio3.common.annotations.processor.generate.Common.INDENT
import com.pushtorefresh.storio3.common.annotations.processor.generate.Generator
import com.pushtorefresh.storio3.common.annotations.processor.toUpperSnakeCase
import com.pushtorefresh.storio3.sqlite.annotations.processor.introspection.StorIOSQLiteColumnMeta
import com.pushtorefresh.storio3.sqlite.annotations.processor.introspection.StorIOSQLiteTypeMeta
import com.squareup.javapoet.*
import javax.lang.model.element.Modifier.*
private const val ANDROID_NON_NULL_ANNOTATION = "android.support.annotation.NonNull"
private const val DB_PARAM = "db"
private const val OLD_VERSION_PARAM = "oldVersion"
object TableGenerator : Generator<StorIOSQLiteTypeMeta> {
private val sqliteDatabase = ClassName.get("android.database.sqlite", "SQLiteDatabase")
override fun generateJavaFile(typeMeta: StorIOSQLiteTypeMeta): JavaFile {
val tableSpec = TypeSpec.classBuilder("${typeMeta.simpleName}Table")
.addModifiers(PUBLIC, FINAL)
.addMethod(generatePrivateConstructor())
.addFields(generateFields(typeMeta.storIOType.table, typeMeta.columns.values))
.addMethod(generateCreateMethod(typeMeta.storIOType.table, typeMeta.columns.values))
.addMethod(generateUpdateMethod(typeMeta.storIOType.table, typeMeta.columns.values))
.build()
return JavaFile.builder(typeMeta.packageName, tableSpec)
.indent(INDENT)
.build()
}
private fun generateFields(table: String, columns: Collection<StorIOSQLiteColumnMeta>): Iterable<FieldSpec> {
val list = mutableListOf<FieldSpec>()
list += FieldSpec.builder(String::class.java, "NAME")
.initializer("\$S", table)
.addModifiers(PUBLIC, STATIC, FINAL)
.build()
columns.forEach { column ->
list += FieldSpec.builder(String::class.java, "${column.elementName.toUpperSnakeCase()}_COLUMN")
.initializer("\$S", column.storIOColumn.name)
.addModifiers(PUBLIC, STATIC, FINAL)
.build()
}
return list
}
private fun generateCreateMethod(table: String, columns: Collection<StorIOSQLiteColumnMeta>): MethodSpec {
val builder = StringBuilder()
builder.append("CREATE TABLE $table (")
val primaryKeys = columns.filter { it.storIOColumn.key }.toList()
columns.forEachIndexed { index, column ->
builder.append("${column.storIOColumn.name} ${column.javaType.sqliteType}")
if (column.isNotNull()) builder.append(" NOT NULL")
if (column.storIOColumn.key && primaryKeys.size == 1) builder.append(" PRIMARY KEY")
if (index != columns.size - 1) builder.append(",\n")
}
if (primaryKeys.size > 1) {
builder.append(",\nPRIMARY KEY(")
primaryKeys.forEachIndexed { index, key ->
builder.append(key.storIOColumn.name)
if (index != primaryKeys.size - 1) builder.append(", ")
}
builder.append(")")
}
builder.append(");")
return MethodSpec.methodBuilder("createTable")
.addModifiers(PUBLIC, STATIC)
.addParameter(ParameterSpec.builder(sqliteDatabase, DB_PARAM).build())
.addStatement("$DB_PARAM.execSQL(\$S)", builder.toString())
.build()
}
private fun generateUpdateMethod(table: String, columns: Collection<StorIOSQLiteColumnMeta>): MethodSpec {
val builder = MethodSpec.methodBuilder("updateTable")
.addModifiers(PUBLIC, STATIC)
.addParameter(ParameterSpec.builder(sqliteDatabase, DB_PARAM).build())
.addParameter(ParameterSpec.builder(TypeName.INT, OLD_VERSION_PARAM).build())
val columnsToUpdate = columns
.filter { it.storIOColumn.version > 1 }
.sortedBy { it.storIOColumn.version }
columnsToUpdate.forEach { column ->
builder.beginControlFlow("if ($OLD_VERSION_PARAM < ${column.storIOColumn.version})")
builder.addCode("$DB_PARAM.execSQL(\$S);\n", "ALTER TABLE $table ADD COLUMN ${column.storIOColumn.name} ${column.javaType.sqliteType}${if (column.isNotNull()) " NOT NULL" else ""}")
builder.endControlFlow()
}
return builder.build()
}
private fun generatePrivateConstructor() = MethodSpec.constructorBuilder().addModifiers(PRIVATE).build()
private fun StorIOSQLiteColumnMeta.isNotNull(): Boolean {
this.element.annotationMirrors.forEach {
if (it.annotationType.toString() == ANDROID_NON_NULL_ANNOTATION) return true
}
return false
}
} | apache-2.0 | a740c5157bbf1fc4636d45ce9678c276 | 43.909091 | 193 | 0.654383 | 4.78122 | false | false | false | false |
android/health-samples | health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/component/NotSupportedMessage.kt | 1 | 2761 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.healthconnectsample.presentation.component
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import com.example.healthconnectsample.R
import com.example.healthconnectsample.data.MIN_SUPPORTED_SDK
import com.example.healthconnectsample.presentation.theme.HealthConnectTheme
/**
* Welcome text shown when the app first starts, where the device is not running a sufficient
* Android version for Health Connect to be used.
*/
@Composable
fun NotSupportedMessage() {
val tag = stringResource(R.string.not_supported_tag)
val url = stringResource(R.string.not_supported_url)
val handler = LocalUriHandler.current
val notSupportedText = stringResource(
id = R.string.not_supported_description,
MIN_SUPPORTED_SDK
)
val notSupportedLinkText = stringResource(R.string.not_supported_link_text)
val unavailableText = buildAnnotatedString {
withStyle(style = SpanStyle(color = MaterialTheme.colors.onBackground)) {
append(notSupportedText)
append("\n\n")
}
pushStringAnnotation(tag = tag, annotation = url)
withStyle(style = SpanStyle(color = MaterialTheme.colors.primary)) {
append(notSupportedLinkText)
}
}
ClickableText(
text = unavailableText,
style = TextStyle(textAlign = TextAlign.Justify)
) { offset ->
unavailableText.getStringAnnotations(tag = tag, start = offset, end = offset)
.firstOrNull()?.let {
handler.openUri(it.item)
}
}
}
@Preview
@Composable
fun NotSupportedMessagePreview() {
HealthConnectTheme {
NotSupportedMessage()
}
}
| apache-2.0 | 9d750829ba798c650948484b038d31f2 | 35.328947 | 93 | 0.736327 | 4.4176 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/ContainerizedBrowser.kt | 1 | 2162 | package pl.wendigo.chrome
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.testcontainers.utility.DockerImageName
import pl.wendigo.chrome.api.ProtocolDomains
import pl.wendigo.chrome.protocol.ProtocolConnection
import pl.wendigo.chrome.targets.Manager
internal class ContainerizedBrowser private constructor(
private val container: HeadlessChromeContainer,
browserInfo: BrowserInfo,
options: Options,
connection: ProtocolConnection,
manager: Manager
) : pl.wendigo.chrome.Browser(browserInfo, options, connection, manager) {
override fun close() {
super.close()
logger.info("Stopping container {}", container.containerId)
container.close()
}
override fun toString(): String {
return "ContainerizedBrowser(container=${container.dockerImageName}[${container.containerId}])"
}
companion object {
private val logger: Logger = LoggerFactory.getLogger(ContainerizedBrowser::class.java)
/**
* Creates new Browser instance by connecting to remote chrome debugger.
*/
internal fun connect(dockerImageName: DockerImageName, options: Options): Browser {
logger.info("Creating new headless Chrome instance from image {}", dockerImageName)
val container = HeadlessChromeContainer(dockerImageName)
container.start()
logger.info("Started container {}", container.containerId)
logger.info("Debugger is available on http://{}", container.getBrowserEndpoint())
val info = fetchInfo(container.getBrowserEndpoint())
val connection = ProtocolConnection.open(info.webSocketDebuggerUrl, options.eventsBufferSize)
val protocol = ProtocolDomains(connection)
return ContainerizedBrowser(
container,
info,
options,
connection,
Manager(
info.webSocketDebuggerUrl,
options.multiplexConnections,
options.eventsBufferSize,
protocol
)
)
}
}
}
| apache-2.0 | 370e651270595ae98254c54f32ef193e | 33.870968 | 105 | 0.654487 | 5.351485 | false | false | false | false |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/model/ShippingInformation.kt | 1 | 846 | package com.stripe.android.model
import com.stripe.android.core.model.StripeModel
import kotlinx.parcelize.Parcelize
/**
* Model representing a shipping address object
*/
@Parcelize
data class ShippingInformation constructor(
val address: Address? = null,
val name: String? = null,
val phone: String? = null
) : StripeModel, StripeParamsModel {
override fun toParamMap(): Map<String, Any> {
return listOf(
PARAM_NAME to name,
PARAM_PHONE to phone,
PARAM_ADDRESS to address?.toParamMap()
)
.mapNotNull { (first, second) -> second?.let { Pair(first, it) } }
.toMap()
}
companion object {
private const val PARAM_ADDRESS = "address"
private const val PARAM_NAME = "name"
private const val PARAM_PHONE = "phone"
}
}
| mit | 773f82c74ba1b054b2b6df6e7ece16ab | 26.290323 | 78 | 0.630024 | 4.208955 | false | false | false | false |
eggeral/3d-playground | src/main/kotlin/glmatrix/Mat2.kt | 1 | 9163 | package glmatrix
import kotlin.js.Math
class Mat2() : GlMatrix() {
private val matrix: Array<Double> = arrayOf(1.0, 0.0, 0.0, 1.0)
constructor(m00: Double, m01: Double, m10: Double, m11: Double) : this() {
matrix[0] = m00
matrix[1] = m01
matrix[2] = m10
matrix[3] = m11
}
operator fun get(index: Int): Double {
return matrix[index]
}
operator fun set(index: Int, value: Double) {
matrix[index] = value
}
/**
* Creates a new mat2 initialized with values from an existing matrix
*/
fun clone(): Mat2 {
return Mat2(
this.matrix[0],
this.matrix[1],
this.matrix[2],
this.matrix[3])
}
/**
* Set a mat2 to the identity matrix
*/
fun identity(): Mat2 {
this.matrix[0] = 1.0
this.matrix[1] = 0.0
this.matrix[2] = 0.0
this.matrix[3] = 1.0
return this
}
/**
* Adds summand matrix to this
*/
fun add(summand: Mat2): Mat2 {
this.matrix[0] += summand[0]
this.matrix[1] += summand[1]
this.matrix[2] += summand[2]
this.matrix[3] += summand[3]
return this
}
/**
* Adds summand matrix with + operator
*/
operator fun plus(summand: Mat2): Mat2 {
return clone().add(summand)
}
/**
* Subtracts subtrahend matrix from this
*/
fun subtract(subtrahend: Mat2): Mat2 {
this.matrix[0] -= subtrahend[0]
this.matrix[1] -= subtrahend[1]
this.matrix[2] -= subtrahend[2]
this.matrix[3] -= subtrahend[3]
return this
}
/**
* Subtracts subtrahend matrix with - operator
*/
operator fun minus(subtrahend: Mat2): Mat2 {
return clone().subtract(subtrahend)
}
/**
* Multiplies multiplier matrix with this
*/
fun multiply(multiplier: Mat2): Mat2 {
val a0 = this.matrix[0]
val a1 = this.matrix[1]
val a2 = this.matrix[2]
val a3 = this.matrix[3]
this.matrix[0] = a0 * multiplier[0] + a2 * multiplier[1]
this.matrix[1] = a1 * multiplier[0] + a3 * multiplier[1]
this.matrix[2] = a0 * multiplier[2] + a2 * multiplier[3]
this.matrix[3] = a1 * multiplier[2] + a3 * multiplier[3]
return this
}
/**
* Multiplies multiplier matrix with * operator
*/
operator fun times(multiplier: Mat2): Mat2 {
return multiplier.clone().multiply(this)
}
/**
* Transpose the values of source Mat2 to this
*
* @param {Mat2} source the source matrix
*/
fun transpose(source: Mat2): Mat2 {
// If we are transposing ourselves we can skip source few steps but have to cache
// some values
if (this === source) {
val a1 = source[1]
this.matrix[1] = source[2]
this.matrix[2] = a1
} else {
this.matrix[0] = source[0]
this.matrix[1] = source[2]
this.matrix[2] = source[1]
this.matrix[3] = source[3]
}
return this
}
/**
* Inverts Mat2
*/
fun invert(): Mat2 {
val a0 = this.matrix[0]
val a1 = this.matrix[1]
val a2 = this.matrix[2]
val a3 = this.matrix[3]
// Calculate the determinant
var det = a0 * a3 - a2 * a1
if (det < 0) {
return Mat2()
}
det = 1.0 / det
this.matrix[0] = a3 * det
this.matrix[1] = -a1 * det
this.matrix[2] = -a2 * det
this.matrix[3] = a0 * det
return this
}
/**
* Calculates the adjugate of Mat2
*/
fun adjoint(): Mat2 {
// Caching this.matrix value is nessecary if out == source
val a0 = this.matrix[0]
this.matrix[0] = this.matrix[3]
this.matrix[1] = -this.matrix[1]
this.matrix[2] = -this.matrix[2]
this.matrix[3] = a0
return this
}
/**
* Calculates the determinant of Mat2
*/
fun determinant(): Double {
return this.matrix[0] * this.matrix[3] - this.matrix[2] * this.matrix[1]
}
/**
* Rotates Mat2 by the given angle
*
* @param {Double} angleInRad the angle to rotate the matrix by
*/
fun rotate(angleInRad: Double): Mat2 {
val a0 = this.matrix[0]
val a1 = this.matrix[1]
val a2 = this.matrix[2]
val a3 = this.matrix[3]
val s = Math.sin(angleInRad)
val c = Math.cos(angleInRad)
this.matrix[0] = a0 * c + a2 * s
this.matrix[1] = a1 * c + a3 * s
this.matrix[2] = a0 * -s + a2 * c
this.matrix[3] = a1 * -s + a3 * c
return this
}
/**
* Scales the Mat2 by the dimensions in the given Vec2
*
* @param {Vec2} vec2ToScaleBy the Vec2 to scale the matrix by
**/
fun scale(vec2ToScaleBy: Vec2): Mat2 {
val a0 = this.matrix[0]
val a1 = this.matrix[1]
val a2 = this.matrix[2]
val a3 = this.matrix[3]
val v0 = vec2ToScaleBy[0]
val v1 = vec2ToScaleBy[1]
this.matrix[0] = a0 * v0
this.matrix[1] = a1 * v0
this.matrix[2] = a2 * v1
this.matrix[3] = a3 * v1
return this
}
/**
* Scales the Mat2 by the dimensions in the given Vec2
*
* @param {Array<Double>} vec2ToScaleBy the Vec2 to scale the matrix by
**/
fun scale(vec2ToScaleBy: Array<Double>): Mat2 {
val a0 = this.matrix[0]
val a1 = this.matrix[1]
val a2 = this.matrix[2]
val a3 = this.matrix[3]
val v0 = vec2ToScaleBy[0]
val v1 = vec2ToScaleBy[1]
this.matrix[0] = a0 * v0
this.matrix[1] = a1 * v0
this.matrix[2] = a2 * v1
this.matrix[3] = a3 * v1
return this
}
/**
* Creates a matrix from a given angle
*
* @param {Double} angleToRotateByInRad the angle to rotate the matrix by
*/
fun fromRotation(angleToRotateByInRad: Double): Mat2 {
val s = Math.sin(angleToRotateByInRad)
val c = Math.cos(angleToRotateByInRad)
this.matrix[0] = c
this.matrix[1] = s
this.matrix[2] = -s
this.matrix[3] = c
return this
}
/**
* Creates a matrix from a vector scaling
*
* @param {Vec2} scalingVec2 Scaling vector
*/
fun fromScaling(scalingVec2: Vec2): Mat2 {
this.matrix[0] = scalingVec2[0]
this.matrix[1] = 0.0
this.matrix[2] = 0.0
this.matrix[3] = scalingVec2[1]
return this
}
/**
* Creates a matrix from a vector scaling
*
* @param {Array<Double>} scalingVec2 Scaling vector
*/
fun fromScaling(scalingVec2: Array<Double>): Mat2 {
this.matrix[0] = scalingVec2[0]
this.matrix[1] = 0.0
this.matrix[2] = 0.0
this.matrix[3] = scalingVec2[1]
return this
}
/**
* Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix
* @param {Mat2} L the lower triangular matrix
* @param {Mat2} D the diagonal matrix
* @param {Mat2} U the upper triangular matrix
* @param {Mat2} a the input matrix to factorize
*/
fun LDU(lowerTriangularMatrix: Mat2, diagonalMatrix: Mat2, upperTriangularMatrix: Mat2, matrixToFactorize: Mat2): Triple<Mat2, Mat2, Mat2> {
lowerTriangularMatrix[2] = matrixToFactorize[2] / matrixToFactorize[0]
upperTriangularMatrix[0] = matrixToFactorize[0]
upperTriangularMatrix[1] = matrixToFactorize[1]
upperTriangularMatrix[3] = matrixToFactorize[3] - lowerTriangularMatrix[2] * upperTriangularMatrix[1]
return Triple(lowerTriangularMatrix, diagonalMatrix, upperTriangularMatrix)
}
/**
* Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
*/
fun exactEquals(matrix: Mat2): Boolean {
return this.matrix[0] == matrix[0] && this.matrix[1] == matrix[1] && this.matrix[2] == matrix[2] && this.matrix[3] == matrix[3]
}
/**
* Returns whether or not the matrices have approximately the same elements in the same position.
*/
fun equals(matrix: Mat2): Boolean {
val a0 = this.matrix[0]
val a1 = this.matrix[1]
val a2 = this.matrix[2]
val a3 = this.matrix[3]
val b0 = matrix[0]
val b1 = matrix[1]
val b2 = matrix[2]
val b3 = matrix[3]
return (Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) &&
Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)))
}
/**
* Returns a string representation of a Mat2
*/
override fun toString(): String {
return "Mat2(${this.matrix[0]}, ${this.matrix[1]}, ${this.matrix[2]}, ${this.matrix[3]})"
}
} | apache-2.0 | 97eb3bd6f19fb8533850fb2042fafe3c | 28.466238 | 144 | 0.548619 | 3.36875 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/PermissionPolicyList.kt | 1 | 492 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Represents a list of [PermissionPolicy].
*
* @param total the number of policies in the list returned in [data]
* @param data the actual list of [PermissionPolicies][PermissionPolicy]
*/
@JsonClass(generateAdapter = true)
data class PermissionPolicyList(
@Json(name = "total")
val total: Int? = null,
@Json(name = "data")
val data: List<PermissionPolicy>? = null
)
| mit | dbed4a6766c591a4cabf243bbdeb0988 | 24.894737 | 72 | 0.719512 | 3.727273 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/medialibrary/albums/AlbumUtils.kt | 2 | 2821 | package abi44_0_0.expo.modules.medialibrary.albums
import android.content.Context
import android.os.Bundle
import android.provider.MediaStore
import android.provider.MediaStore.MediaColumns
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.medialibrary.ERROR_UNABLE_TO_LOAD
import abi44_0_0.expo.modules.medialibrary.ERROR_UNABLE_TO_LOAD_PERMISSION
import abi44_0_0.expo.modules.medialibrary.EXTERNAL_CONTENT_URI
import abi44_0_0.expo.modules.medialibrary.MediaLibraryUtils.queryPlaceholdersFor
import java.lang.IllegalArgumentException
/**
* Queries for assets filtered by given `selection`.
* Resolves `promise` with [Bundle] of kind: `Array<{ id, title, assetCount }>`
*/
fun queryAlbum(
context: Context,
selection: String?,
selectionArgs: Array<String>?,
promise: Promise
) {
val projection = arrayOf(MediaColumns.BUCKET_ID, MediaColumns.BUCKET_DISPLAY_NAME)
val order = MediaColumns.BUCKET_DISPLAY_NAME
try {
context.contentResolver.query(
EXTERNAL_CONTENT_URI,
projection,
selection,
selectionArgs,
order
).use { albumsCursor ->
if (albumsCursor == null) {
promise.reject(ERROR_UNABLE_TO_LOAD, "Could not get album. Query is incorrect.")
return
}
if (!albumsCursor.moveToNext()) {
promise.resolve(null)
return
}
val bucketIdIndex = albumsCursor.getColumnIndex(MediaColumns.BUCKET_ID)
val bucketDisplayNameIndex = albumsCursor.getColumnIndex(MediaColumns.BUCKET_DISPLAY_NAME)
val result = Bundle().apply {
putString("id", albumsCursor.getString(bucketIdIndex))
putString("title", albumsCursor.getString(bucketDisplayNameIndex))
putInt("assetCount", albumsCursor.count)
}
promise.resolve(result)
}
} catch (e: SecurityException) {
promise.reject(
ERROR_UNABLE_TO_LOAD_PERMISSION,
"Could not get albums: need READ_EXTERNAL_STORAGE permission.", e
)
} catch (e: IllegalArgumentException) {
promise.reject(ERROR_UNABLE_TO_LOAD, "Could not get album.", e)
}
}
/**
* Returns flat list of asset IDs (`_ID` column) for given album IDs (`BUCKET_ID` column)
*/
fun getAssetsInAlbums(context: Context, vararg albumIds: String?): List<String> {
val assetIds = mutableListOf<String>()
val selection = "${MediaColumns.BUCKET_ID} IN (${queryPlaceholdersFor(albumIds)} )"
val projection = arrayOf(MediaColumns._ID)
context.contentResolver.query(
EXTERNAL_CONTENT_URI,
projection,
selection,
albumIds,
null
).use { assetCursor ->
if (assetCursor == null) {
return assetIds
}
while (assetCursor.moveToNext()) {
val id = assetCursor.getString(assetCursor.getColumnIndex(MediaStore.Images.Media._ID))
assetIds.add(id)
}
}
return assetIds
}
| bsd-3-clause | e2a694b497097a4c006523d46f1c00cb | 32.583333 | 96 | 0.709677 | 3.973239 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/etcetera/src/main/kotlin/com/teamwizardry/librarianlib/etcetera/Raycaster.kt | 1 | 23181 | package com.teamwizardry.librarianlib.etcetera
import com.teamwizardry.librarianlib.core.util.mixinCast
import com.teamwizardry.librarianlib.etcetera.mixin.WorldEntityLookupMixin
import net.minecraft.block.BlockState
import net.minecraft.block.ShapeContext
import net.minecraft.entity.Entity
import net.minecraft.fluid.FluidState
import net.minecraft.util.TypeFilter
import net.minecraft.util.math.Box
import net.minecraft.util.math.BlockPos
import net.minecraft.util.shape.VoxelShape
import net.minecraft.util.shape.VoxelShapes
import net.minecraft.world.World
import java.util.function.Function
import java.util.function.Predicate
/**
* A class designed to efficiently raytrace collisions with the world. This class uses custom raytracing code to
* reduce the number short-lived objects created and to improve the performance of long rays.
*/
public class Raycaster {
/**
* The type of hit that occurred, if any.
*/
public var hitType: HitType = HitType.NONE
private set
/**
* The X component of the impacted block's position, or 0 if no impact occurred.
*/
public var blockX: Int = 0
private set
/**
* The Y component of the impacted block's position, or 0 if no impact occurred.
*/
public var blockY: Int = 0
private set
/**
* The Z component of the impacted block's position, or 0 if no impact occurred.
*/
public var blockZ: Int = 0
private set
/**
* The entity that was hit
*/
public var entity: Entity? = null
private set
/**
* The fraction along the raycast that an impact occurred, or 1.0 if no impact occurred
*/
public var fraction: Double = 0.0
private set
/**
* The depth of the hit. This is the distance from the entrance to the exit point, expressed as a multiple of the
* ray's length, or zero if no impact occurred.
*/
public var depth: Double = 0.0
private set
/**
* The hit position, or the end position if no hit occurred. Computed as `start + (end - start) * fraction`
*/
public val hitX: Double
get() = startX + (endX - startX) * fraction
/**
* The hit position, or the end position if no hit occurred. Computed as `start + (end - start) * fraction`
*/
public val hitY: Double
get() = startY + (endY - startY) * fraction
/**
* The hit position, or the end position if no hit occurred. Computed as `start + (end - start) * fraction`
*/
public val hitZ: Double
get() = startZ + (endZ - startZ) * fraction
/**
* The X component of the impacted face's normal, or 0.0 if no impact occurred
*/
public var normalX: Double = 0.0
private set
/**
* The Y component of the impacted face's normal, or 0.0 if no impact occurred
*/
public var normalY: Double = 0.0
private set
/**
* The Z component of the impacted face's normal, or 0.0 if no impact occurred
*/
public var normalZ: Double = 0.0
private set
/**
* The configured start position
*/
public var startX: Double = 0.0
private set
/**
* The configured start position
*/
public var startY: Double = 0.0
private set
/**
* The configured start position
*/
public var startZ: Double = 0.0
private set
/**
* The configured end position
*/
public var endX: Double = 0.0
private set
/**
* The configured end position
*/
public var endY: Double = 0.0
private set
/**
* The configured end position
*/
public var endZ: Double = 0.0
private set
/**
* Cast the ray through the passed world, colliding with blocks using the specified mode, ignoring fluid and
* entities.
*
* The result of the raycast is made available as properties of this raycaster. It is ***vitally*** important that
* you call [reset] once you're done with the result to prepare for the next raycast.
*
* @param shapeContext The context to use when getting block shapes. Generally [ShapeContext.of(entity)][ShapeContext.of].
* Defaults to [ShapeContext.absent] if null
*
* @see hitType
* @see blockX
* @see blockY
* @see blockZ
* @see entity
* @see fraction
* @see depth
* @see hitX
* @see hitY
* @see hitZ
* @see normalX
* @see normalY
* @see normalZ
*/
public fun cast(
world: World,
blockMode: BlockMode,
shapeContext: ShapeContext?,
startX: Double, startY: Double, startZ: Double,
endX: Double, endY: Double, endZ: Double
) {
val request = RaycastRequest(world, startX, startY, startZ, endX, endY, endZ)
.withBlockMode(blockMode)
if (shapeContext != null) {
request.withShapeContext(shapeContext)
}
cast(request)
}
/**
* Cast the ray through the passed world, colliding with blocks and fluids using the specified modes, and colliding
* with entities according to the specified filter, if present. Passing null for both [entityFilter] and
* [entityPredicate] will ignore entities.
*
* The result of the raycast is made available as properties of this raycaster. It is ***vitally*** important that
* you call [reset] once you're done with the result to prepare for the next raycast and avoid leaking [entity].
*
* @param blockMode The type of collisions to make with solid blocks
* @param fluidMode The type of collisions to make with fluids
* @param shapeContext The context to use when getting block shapes. Generally [ShapeContext.of(entity)][ShapeContext.of].
* Defaults to [ShapeContext.absent] if null
* @param entityFilter If non-null, a filter dictating which entity types to collide against. Using this will result
* in better performance than using an equivalent [entityPredicate]
* @param entityPredicate If non-null, a predicate dictating which entities to collide against.
*
* @see hitType
* @see blockX
* @see blockY
* @see blockZ
* @see entity
* @see fraction
* @see depth
* @see hitX
* @see hitY
* @see hitZ
* @see normalX
* @see normalY
* @see normalZ
*/
public fun cast(
world: World,
blockMode: BlockMode,
fluidMode: FluidMode,
shapeContext: ShapeContext?,
entityFilter: TypeFilter<Entity, Entity>?,
entityPredicate: Predicate<Entity>?,
startX: Double, startY: Double, startZ: Double,
endX: Double, endY: Double, endZ: Double
) {
val request = RaycastRequest(world, startX, startY, startZ, endX, endY, endZ)
.withBlockMode(blockMode)
.withFluidMode(fluidMode)
if (shapeContext != null) {
request.withShapeContext(shapeContext)
}
if (entityFilter != null || entityPredicate != null) {
request.withEntities(entityFilter, entityPredicate)
}
return cast(request)
}
/**
* Cast the ray through the configured world, colliding with blocks and fluids using the configured modes, and
* colliding with entities according to the specified filter, if enabled.
*
* The result of the raycast is made available as properties of this raycaster. It is ***vitally*** important that
* you call [reset] once you're done with the result to prepare for the next raycast and avoid leaking [entity].
*
* @see hitType
* @see blockX
* @see blockY
* @see blockZ
* @see entity
* @see fraction
* @see depth
* @see hitX
* @see hitY
* @see hitZ
* @see normalX
* @see normalY
* @see normalZ
*/
public fun cast(request: RaycastRequest) {
reset()
this.startX = request.startX
this.startY = request.startY
this.startZ = request.startZ
this.endX = request.endX
this.endY = request.endY
this.endZ = request.endZ
invVelX = 1.0 / (endX - startX)
invVelY = 1.0 / (endY - startY)
invVelZ = 1.0 / (endZ - startZ)
if (request.blockMode != BlockMode.NONE || request.fluidMode != FluidMode.NONE) {
castBlocks(
request.world,
request.shapeContext,
request.blockMode,
request.fluidMode,
request.blockOverride,
request.fluidOverride
)
}
if (request.castEntities) {
castEntities(request.world, request.entityFilter, request.entityPredicate)
}
}
/**
* Resets the state
*/
public fun reset() {
hitType = HitType.NONE
fraction = 1.0
depth = 0.0
normalX = 0.0
normalY = 0.0
normalZ = 0.0
blockX = 0
blockY = 0
blockZ = 0
entity = null
startX = 0.0
startY = 0.0
startZ = 0.0
endX = 0.0
endY = 0.0
endZ = 0.0
invVelX = 0.0
invVelY = 0.0
invVelZ = 0.0
raycaster.reset()
}
public class RaycastRequest(
public val world: World,
public val startX: Double, public val startY: Double, public val startZ: Double,
public val endX: Double, public val endY: Double, public val endZ: Double
) {
public var shapeContext: ShapeContext = ShapeContext.absent()
public var blockMode: BlockMode = BlockMode.NONE
public var fluidMode: FluidMode = FluidMode.NONE
public var castEntities: Boolean = false
public var entityFilter: TypeFilter<Entity, Entity>? = null
public var entityPredicate: Predicate<Entity>? = null
public var blockOverride: ShapeOverride<BlockState>? = null
public var fluidOverride: ShapeOverride<FluidState>? = null
/**
* Sets the shape context. Generally [ShapeContext.of(entity)][ShapeContext.of].
*
* The default shape context is [ShapeContext.absent]
*/
public fun withShapeContext(context: ShapeContext): RaycastRequest = apply { this.shapeContext = context }
/**
* Sets the shape context using [ShapeContext.of(entity)][ShapeContext.of].
*/
public fun withEntityContext(entity: Entity): RaycastRequest = withShapeContext(ShapeContext.of(entity))
/**
* Sets the type of collisions to make with blocks.
*
* The default block mode is [BlockMode.NONE]
*/
public fun withBlockMode(mode: BlockMode): RaycastRequest = apply { this.blockMode = mode }
/**
* Sets the block shape override callback. This will take effect even when [blockMode] is [BlockMode.NONE].
*
* The function receives a BlockState parameter and returns a nullable [VoxelShape]. A null return value falls
* back to the default behavior according to the [blockMode]. To ignore a block return
* [VoxelShapes.empty()][VoxelShapes.empty].
*/
public fun withBlockOverride(blockOverride: ShapeOverride<BlockState>): RaycastRequest = apply {
this.blockOverride = blockOverride
}
/**
* Sets the type of collisions to make with fluids.
*
* The default fluid mode is [FluidMode.NONE]
*/
public fun withFluidMode(mode: FluidMode): RaycastRequest = apply { this.fluidMode = mode }
/**
* Sets the fluid shape override callback. This will take effect even when [fluidMode] is [FluidMode.NONE].
*
* The function receives a FluidState parameter and returns a nullable [VoxelShape]. A null return value falls
* back to the default behavior according to the [fluidMode]. To ignore a fluid return
* [VoxelShapes.empty()][VoxelShapes.empty].
*/
public fun withFluidOverride(fluidOverride: ShapeOverride<FluidState>): RaycastRequest = apply {
this.fluidOverride = fluidOverride
}
/**
* Enables entity raycasting and sets the entity filter/predicate. Setting both the filter and the predicate to
* null will cast against all entities.
*
* @param entityFilter If non-null, a filter dictating which entity types to collide against. Using this will
* result in better performance than using an equivalent [entityPredicate]
* @param entityPredicate If non-null, a predicate dictating which entities to collide against.
*/
public fun withEntities(
entityFilter: TypeFilter<Entity, Entity>?,
entityPredicate: Predicate<Entity>?
): RaycastRequest = apply {
this.castEntities = true
this.entityFilter = entityFilter
this.entityPredicate = entityPredicate
}
}
public fun interface ShapeOverride<T> {
/**
* Returns the shape for the given state or returns null to fall back to the default behavior. To ignore a block
* return [VoxelShapes.empty].
*
* If you modify [pos] (which you should if you need a [BlockPos], to minimize object allocations), you *must*
* return it to its original value before returning from this function.
*/
public fun getShape(state: T, world: World, pos: BlockPos.Mutable): VoxelShape?
}
public enum class BlockMode {
/**
* Ignore blocks
*/
NONE,
/**
* Use the collision shape of the block
*/
COLLISION,
/**
* Use the visual shape of the block (like when checking what block to click on)
*/
VISUAL;
}
public enum class FluidMode {
/**
* Ignore fluids
*/
NONE,
/**
* Only return hits on source blocks (like when using a bucket)
*/
SOURCE,
/**
* Return hits on any fluid
*/
ANY;
}
public enum class HitType {
/**
* No hit occurred
*/
NONE,
/**
* The ray hit a block
*/
BLOCK,
/**
* The ray hit a fluid
*/
FLUID,
/**
* The ray hit an entity
*/
ENTITY;
}
// v============================ Implementation ===========================v
// Note: Because each hit test is reusing the same `DirectRaycaster`, tests will only succeed if they are closer
// than the closest hit so far. This allows us to trivially cast against multiple types of object.
private val intersectingIterator = IntersectingBlocksIterator()
private val raycaster = DirectRaycaster()
private val boundingBoxSegmenter = RayBoundingBoxSegmenter()
// v-------------------------------- Blocks -------------------------------v
private val mutablePos = BlockPos.Mutable()
private var invVelX: Double = 0.0
private var invVelY: Double = 0.0
private var invVelZ: Double = 0.0
/**
* The implementation of block raycasting.
*/
private fun castBlocks(
world: World,
shapeContext: ShapeContext,
blockMode: BlockMode,
fluidMode: FluidMode,
blockOverride: ShapeOverride<BlockState>?,
fluidOverride: ShapeOverride<FluidState>?
) {
// Only blocks the ray directly passes through are checked.
intersectingIterator.reset(
startX, startY, startZ,
endX, endY, endZ
)
for (block in intersectingIterator) {
if (
castBlock(
world, shapeContext, blockMode,
fluidMode, blockOverride, fluidOverride,
block.x, block.y, block.z
)
) {
break // short-circuit at the first hit since we iterate near to far
}
}
}
/**
* Cast the ray through the passed block.
* @return true if the block was hit
*/
private fun castBlock(
world: World,
shapeContext: ShapeContext,
blockMode: BlockMode,
fluidMode: FluidMode,
blockOverride: ShapeOverride<BlockState>?,
fluidOverride: ShapeOverride<FluidState>?,
blockX: Int,
blockY: Int,
blockZ: Int
): Boolean {
mutablePos.set(blockX, blockY, blockZ)
val blockShape = when (blockMode) {
BlockMode.NONE -> {
// if `blockOverride` is null `world.getBlockState()` is never executed
blockOverride?.getShape(world.getBlockState(mutablePos), world, mutablePos)
}
BlockMode.COLLISION -> {
val state = world.getBlockState(mutablePos)
blockOverride?.getShape(state, world, mutablePos)
?: state.getCollisionShape(world, mutablePos, shapeContext)
}
BlockMode.VISUAL -> {
val state = world.getBlockState(mutablePos)
blockOverride?.getShape(state, world, mutablePos)
?: state.getOutlineShape(world, mutablePos, shapeContext)
}
}
val hitBlock = if(blockShape != null) {
castShape(blockX, blockY, blockZ, blockShape)
} else {
false
}
if (hitBlock) {
entity = null
this.blockX = blockX
this.blockY = blockY
this.blockZ = blockZ
hitType = HitType.BLOCK
}
val fluidShape = when (fluidMode) {
FluidMode.NONE -> {
fluidOverride?.getShape(world.getFluidState(mutablePos), world, mutablePos)
}
FluidMode.SOURCE -> {
val state = world.getFluidState(mutablePos)
fluidOverride?.getShape(state, world, mutablePos)
?: (if (state.isStill) state.getShape(world, mutablePos) else null)
}
FluidMode.ANY -> {
val state = world.getFluidState(mutablePos)
fluidOverride?.getShape(state, world, mutablePos)
?: state.getShape(world, mutablePos)
}
}
val hitFluid = if(fluidShape != null) {
castShape(blockX, blockY, blockZ, fluidShape)
} else {
false
}
if (hitFluid) {
entity = null
this.blockX = blockX
this.blockY = blockY
this.blockZ = blockZ
hitType = HitType.FLUID
}
return hitBlock || hitFluid
}
/**
* The ray start relative to the block currently being tested. Used by [boxConsumer]
*/
private var relativeStartX: Double = 0.0
private var relativeStartY: Double = 0.0
private var relativeStartZ: Double = 0.0
/**
* This is reset to false before each shape is tested, and is set to true if any of the boxes sent to [boxConsumer]
* resulted in a hit.
*
* [VoxelShape.forEachBox] just passes each box to the function, so we need somewhere external to track whether
* there was a hit.
*/
private var didHitShape = false
/**
* [VoxelShape.forEachBox] expects a [VoxelShapes.ILineConsumer]. While I could make the raycaster implement that
* interface, it would only serve to clutter the API.
*/
private val boxConsumer = VoxelShapes.BoxConsumer { minX, minY, minZ, maxX, maxY, maxZ ->
val raycaster = raycaster
if (raycaster.cast(
true,
minX, minY, minZ,
maxX, maxY, maxZ,
relativeStartX, relativeStartY, relativeStartZ,
invVelX, invVelY, invVelZ
)
) {
fraction = raycaster.distance
depth = raycaster.depth
normalX = raycaster.normalX
normalY = raycaster.normalY
normalZ = raycaster.normalZ
didHitShape = true
}
}
/**
* Cast the ray through the passed shape.
*/
private fun castShape(blockX: Int, blockY: Int, blockZ: Int, shape: VoxelShape): Boolean {
if (shape === VoxelShapes.empty())
return false
// the bounding boxes that get fed to [boxConsumer] are all relative to the block (they aren't in absolute world
// coordinates), so we have to transform the start point to be relative to the block.
relativeStartX = startX - blockX
relativeStartY = startY - blockY
relativeStartZ = startZ - blockZ
didHitShape = false
shape.forEachBox(boxConsumer)
return didHitShape
}
// v------------------------------- Entities ------------------------------v
/**
* The implementation of entity raycasting. This checks against entities on a per-chunk basis
*/
private fun castEntities(
world: World,
entityFilter: TypeFilter<Entity, Entity>?,
entityPredicate: Predicate<Entity>?
) {
boundingBoxSegmenter.reset(startX, startY, startZ, endX, endY, endZ, 32.0)
val lookup = mixinCast<WorldEntityLookupMixin>(world).callGetEntityLookup()
if (entityFilter == null) {
for (segment in boundingBoxSegmenter) {
lookup.forEachIntersects(
Box(
segment.minX, segment.minY, segment.minZ,
segment.maxX, segment.maxY, segment.maxZ
)
) {
if (entityPredicate == null || entityPredicate.test(it)) {
castEntity(it)
}
}
}
} else {
for (segment in boundingBoxSegmenter) {
lookup.forEachIntersects(
entityFilter,
Box(
segment.minX, segment.minY, segment.minZ,
segment.maxX, segment.maxY, segment.maxZ
)
) {
if (entityPredicate == null || entityPredicate.test(it)) {
castEntity(it)
}
}
}
}
}
/**
* Cast against a single entity
*/
private fun castEntity(entity: Entity) {
val box = entity.boundingBox
if (raycaster.cast(
true,
box.minX, box.minY, box.minZ,
box.maxX, box.maxY, box.maxZ,
startX, startY, startZ,
invVelX, invVelY, invVelZ
)
) {
fraction = raycaster.distance
depth = raycaster.depth
normalX = raycaster.normalX
normalY = raycaster.normalY
normalZ = raycaster.normalZ
blockX = 0
blockY = 0
blockZ = 0
this.entity = entity
hitType = HitType.ENTITY
}
}
}
| lgpl-3.0 | bf97e3db03036878ec862b73213a03f0 | 32.16309 | 126 | 0.581597 | 4.490701 | false | false | false | false |
TakWolf/Android-HeaderAndFooterRecyclerView | app/src/main/java/com/takwolf/android/demo/hfrecyclerview/ui/activity/GridVerticalActivity.kt | 1 | 1931 | package com.takwolf.android.demo.hfrecyclerview.ui.activity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.takwolf.android.demo.hfrecyclerview.R
import com.takwolf.android.demo.hfrecyclerview.databinding.ActivityRecyclerViewBinding
import com.takwolf.android.demo.hfrecyclerview.ui.adapter.GridVerticalAdapter
import com.takwolf.android.demo.hfrecyclerview.ui.adapter.GridVerticalSpanSizeLookup
import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotoDeleteListener
import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotosSwapListener
import com.takwolf.android.demo.hfrecyclerview.vm.SingleListViewModel
import com.takwolf.android.demo.hfrecyclerview.vm.holder.setupView
class GridVerticalActivity : AppCompatActivity() {
private val viewModel: SingleListViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityRecyclerViewBinding.inflate(layoutInflater)
binding.toolbar.setTitle(R.string.grid_vertical)
binding.toolbar.setNavigationOnClickListener {
finish()
}
binding.recyclerView.layoutManager = GridLayoutManager(this, 2).apply {
spanSizeLookup = GridVerticalSpanSizeLookup(this, binding.recyclerView.proxyAdapter)
}
viewModel.extraHolder.setupVertical(layoutInflater, binding.recyclerView, binding.hfDashboard)
val adapter = GridVerticalAdapter(layoutInflater).apply {
onPhotosSwapListener = OnPhotosSwapListener(viewModel.photosHolder)
onPhotoDeleteListener = OnPhotoDeleteListener(viewModel.photosHolder)
}
binding.recyclerView.adapter = adapter
viewModel.photosHolder.setupView(this, adapter)
setContentView(binding.root)
}
}
| apache-2.0 | f298ee61b790d7eff8c9b691b914066d | 46.097561 | 102 | 0.790264 | 4.901015 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/database/CdsDatabase.kt | 1 | 3779 | package org.thoughtcrime.securesms.database
import android.content.ContentValues
import android.content.Context
import androidx.core.content.contentValuesOf
import org.signal.core.util.SqlUtil
import org.signal.core.util.delete
import org.signal.core.util.logging.Log
import org.signal.core.util.requireNonNullString
import org.signal.core.util.select
import org.signal.core.util.withinTransaction
/**
* Keeps track of the numbers we've previously queried CDS for.
*
* This is important for rate-limiting: our rate-limiting strategy hinges on keeping
* an accurate history of numbers we've queried so that we're only "charged" for
* querying new numbers.
*/
class CdsDatabase(context: Context, databaseHelper: SignalDatabase) : Database(context, databaseHelper) {
companion object {
private val TAG = Log.tag(CdsDatabase::class.java)
const val TABLE_NAME = "cds"
private const val ID = "_id"
const val E164 = "e164"
private const val LAST_SEEN_AT = "last_seen_at"
const val CREATE_TABLE = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY,
$E164 TEXT NOT NULL UNIQUE ON CONFLICT IGNORE,
$LAST_SEEN_AT INTEGER DEFAULT 0
)
"""
}
fun getAllE164s(): Set<String> {
val e164s: MutableSet<String> = mutableSetOf()
readableDatabase
.select(E164)
.from(TABLE_NAME)
.run()
.use { cursor ->
while (cursor.moveToNext()) {
e164s += cursor.requireNonNullString(E164)
}
}
return e164s
}
/**
* Saves the set of e164s used after a full refresh.
* @param fullE164s All of the e164s used in the last CDS query (previous and new).
* @param seenE164s The E164s that were seen in either the system contacts or recipients table. This is different from [fullE164s] in that [fullE164s]
* includes every number we've ever seen, even if it's not in our contacts anymore.
*/
fun updateAfterFullCdsQuery(fullE164s: Set<String>, seenE164s: Set<String>) {
val lastSeen = System.currentTimeMillis()
writableDatabase.withinTransaction { db ->
val existingE164s: Set<String> = getAllE164s()
val removedE164s: Set<String> = existingE164s - fullE164s
val addedE164s: Set<String> = fullE164s - existingE164s
if (removedE164s.isNotEmpty()) {
SqlUtil.buildCollectionQuery(E164, removedE164s)
.forEach { db.delete(TABLE_NAME, it.where, it.whereArgs) }
}
if (addedE164s.isNotEmpty()) {
val insertValues: List<ContentValues> = addedE164s.map { contentValuesOf(E164 to it) }
SqlUtil.buildBulkInsert(TABLE_NAME, arrayOf(E164), insertValues)
.forEach { db.execSQL(it.where, it.whereArgs) }
}
if (seenE164s.isNotEmpty()) {
val contentValues = contentValuesOf(LAST_SEEN_AT to lastSeen)
SqlUtil.buildCollectionQuery(E164, seenE164s)
.forEach { query -> db.update(TABLE_NAME, contentValues, query.where, query.whereArgs) }
}
}
}
/**
* Updates after a partial CDS query. Will not insert new entries. Instead, this will simply update the lastSeen timestamp of any entry we already have.
* @param seenE164s The newly-added E164s that we hadn't previously queried for.
*/
fun updateAfterPartialCdsQuery(seenE164s: Set<String>) {
val lastSeen = System.currentTimeMillis()
writableDatabase.withinTransaction { db ->
val contentValues = contentValuesOf(LAST_SEEN_AT to lastSeen)
SqlUtil.buildCollectionQuery(E164, seenE164s)
.forEach { query -> db.update(TABLE_NAME, contentValues, query.where, query.whereArgs) }
}
}
/**
* Wipes the entire table.
*/
fun clearAll() {
writableDatabase
.delete(TABLE_NAME)
.run()
}
}
| gpl-3.0 | dddb513eec8c091249b705c41fcf1bb8 | 32.442478 | 154 | 0.68616 | 3.824899 | false | false | false | false |
bsmr-java/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/Generator.kt | 1 | 17923 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.*
import java.lang.Math.max
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.nio.ByteBuffer
import java.nio.file.*
import java.nio.file.attribute.FileTime
import java.util.*
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
import java.util.function.BiPredicate
/*
A template will be generated in the following cases:
- The target Java source does not exist.
- The source template has a later timestamp than the target.
- Any file in the source package has later timestamp than the target.
- Any file in the generator itself has later timestamp than the target. (implies re-generation of all templates)
Example template: /src/main/kotlin/org/lwjgl/opengl/templates/ARB_imaging.kt
- Generator source -> /src/main/kotlin/org/lwjgl/generator/
- Source package -> /src/main/kotlin/org/lwjgl/opengl/
- Source template -> /src/main/kotlin/org/lwjgl/opengl/templates/ARB_imaging.kt
- Target source (Java) -> modules/core/src/generated/java/org/lwjgl/opengl/ARBImaging.java
- Target source (C) -> modules/core/src/generated/c/opengl/org_lwjgl_opengl_ARBImaging.c
*/
enum class Binding(val key: String, val packageName: String) {
BGFX("binding.bgfx", "org.lwjgl.bgfx"),
EGL("binding.egl", "org.lwjgl.egl"),
GLFW("binding.glfw", "org.lwjgl.glfw"),
JAWT("binding.jawt", "org.lwjgl.system.jawt"),
JEMALLOC("binding.jemalloc", "org.lwjgl.system.jemalloc"),
LMDB("binding.lmdb", "org.lwjgl.util.lmdb"),
NANOVG("binding.nanovg", "org.lwjgl.nanovg"),
NFD("binding.nfd", "org.lwjgl.util.nfd"),
NUKLEAR("binding.nuklear", "org.lwjgl.nuklear"),
OPENAL("binding.openal", "org.lwjgl.openal"),
OPENCL("binding.opencl", "org.lwjgl.opencl"),
OPENGL("binding.opengl", "org.lwjgl.opengl"),
OPENGLES("binding.opengles", "org.lwjgl.opengles"),
OVR("binding.ovr", "org.lwjgl.ovr"),
PAR("binding.par", "org.lwjgl.util.par"),
SSE("binding.sse", "org.lwjgl.util.simd"),
STB("binding.stb", "org.lwjgl.stb"),
TINYFD("binding.tinyfd", "org.lwjgl.util.tinyfd"),
VULKAN("binding.vulkan", "org.lwjgl.vulkan"),
XXHASH("binding.xxhash", "org.lwjgl.util.xxhash");
companion object {
val CHECKS = !System.getProperty("binding.DISABLE_CHECKS", "false").toBoolean()
}
val enabled: Boolean
get() = System.getProperty(key, "false").toBoolean()
}
fun dependsOn(binding: Binding, init: () -> NativeClass): NativeClass? = if ( binding.enabled ) init() else null
fun main(args: Array<String>) {
if ( args.size < 2 )
throw IllegalArgumentException("The code Generator requires 2 paths as arguments: a) the template source path and b) the generation target path")
val validateDirectory = { name: String, path: String ->
if ( !Files.isDirectory(Paths.get(path)) )
throw IllegalArgumentException("Invalid $name path: $path")
}
validateDirectory("template source", args[0])
validateDirectory("generation target", args[1])
generate(args[0], args[1]) {
// We discover templates reflectively.
// For a package passed to the generate function, we
// search for a <package>.templates.TemplatesPackage class file
// and run any public static methods that return a NativeClass object.
// Note: For a Kotlin package X.Y.Z, <Z>Package is the class Kotlin generates that contains
// all top-level functions/properties in that package. Example:
// org.lwjgl.opengl -> org.lwjgl.opengl.OpenglPackage (the first letter is capitalized)
val pool = ForkJoinPool.commonPool()
// Generate bindings
val bindingsSystem = arrayOf(
"org.lwjgl.system",
"org.lwjgl.system.dyncall",
"org.lwjgl.system.jemalloc",
"org.lwjgl.system.libc",
"org.lwjgl.system.linux",
"org.lwjgl.system.macosx",
"org.lwjgl.system.windows"
)
val bindingsModular = Binding.values().asSequence()
try {
val errors = AtomicInteger()
CountDownLatch(bindingsSystem.size + bindingsModular.count()).let { latch ->
fun generate(packageName: String, binding: Binding? = null) {
pool.submit {
try {
this.generate(packageName, binding)
} catch(t: Throwable) {
errors.incrementAndGet()
t.printStackTrace()
}
latch.countDown()
}
}
bindingsSystem.forEach { generate(it) }
bindingsModular.forEach { generate(it.packageName, it) }
latch.await()
}
if ( errors.get() != 0 )
throw RuntimeException("Generation failed")
// Generate utility classes. These are auto-registered during the process above.
CountDownLatch(4).let { latch ->
fun submit(work: () -> Unit) {
pool.submit {
try {
work()
} catch(t: Throwable) {
errors.incrementAndGet()
t.printStackTrace()
}
latch.countDown()
}
}
submit { generate("struct", Generator.structs) }
submit { generate("callback", Generator.callbacks) }
submit { generate("custom class", Generator.customClasses) }
submit { generate(JNI) }
latch.await()
}
if ( errors.get() != 0 )
throw RuntimeException("Generation failed")
} finally {
pool.shutdown()
}
}
}
private fun generate(
srcPath: String,
trgPath: String,
generate: Generator.() -> Unit
) {
Generator(srcPath, trgPath).generate()
}
class Generator(
val srcPath: String,
val trgPath: String
) {
companion object {
// package -> #name -> class#prefix_name
internal val tokens = ConcurrentHashMap<String, MutableMap<String, String>>()
// package -> #name() -> class#prefix_name()
internal val functions = ConcurrentHashMap<String, MutableMap<String, String>>()
internal val structs = ConcurrentLinkedQueue<Struct>()
internal val callbacks = ConcurrentLinkedQueue<CallbackFunction>()
internal val customClasses = ConcurrentLinkedQueue<GeneratorTarget>()
internal val tlsImport = ConcurrentLinkedQueue<String>()
internal val tlsState = ConcurrentLinkedQueue<String>()
/** Registers a struct definition. */
fun register(struct: Struct): Struct {
structs.add(struct)
return struct
}
/** Registers a callback function. */
fun register(callback: CallbackFunction) {
callbacks.add(callback)
}
/** Registers a custom class. */
fun <T : GeneratorTarget> register(customClass: T): T {
customClasses.add(customClass)
return customClass
}
fun registerLibraryInit(packageName: String, className: String, libraryName: String, setupAllocator: Boolean = false) {
Generator.register(object : GeneratorTargetNative(packageName, className) {
init {
access = Access.INTERNAL
documentation = "Initializes the $libraryName shared library."
javaImport("org.lwjgl.system.*")
if ( setupAllocator )
javaImport("static org.lwjgl.system.MemoryUtil.*")
nativeDirective("""#define LWJGL_MALLOC_LIB $nativeFileNameJNI
#include "lwjgl_malloc.h"""")
}
override fun PrintWriter.generateJava() {
generateJavaPreamble()
println(
"""${access.modifier}final class $className {
static {
String libName = Platform.mapLibraryNameBundled("lwjgl_$libraryName");
Library.loadSystem(libName);${if ( setupAllocator ) """
MemoryAllocator allocator = getAllocator();
setupMalloc(
allocator.getMalloc(),
allocator.getCalloc(),
allocator.getRealloc(),
allocator.getFree(),
allocator.getAlignedAlloc(),
allocator.getAlignedFree()
);""" else ""}
}
private $className() {
}
static void initialize() {
// intentionally empty to trigger static initializer
}${if ( setupAllocator ) """
private static native void setupMalloc(
long malloc,
long calloc,
long realloc,
long free,
long aligned_alloc,
long aligned_free
);""" else ""}
}""")
}
override val skipNative: Boolean
get() = !setupAllocator
override fun PrintWriter.generateNative() {
generateNativePreamble()
}
})
}
/** Registers state that will be added to `org.lwjgl.system.ThreadLocalState`. */
fun registerTLS(import: String, state: String) {
tlsImport.add(import)
tlsState.add(state)
}
init {
Generator.register(object : GeneratorTarget("org.lwjgl.system", "ThreadLocalState") {
override fun PrintWriter.generateJava() {
print(HEADER)
println("package $packageName;\n")
Generator.tlsImport.toSortedSet().forEach {
javaImport(it)
}
preamble.printJava(this)
println("""/** Thread-local state used internally by LWJGL. */
public final class $className implements Runnable {
Runnable target;
public final MemoryStack stack;
""")
Generator.tlsState.toSortedSet().forEach {
println("\t$it")
}
println("""
$className() {
stack = MemoryStack.create();
}
@Override
public void run() {
if ( target != null )
target.run();
}
}""")
}
})
}
}
private val GENERATOR_LAST_MODIFIED = sequenceOf(
Paths.get("modules/generator/src/main/kotlin").lastModified(),
Paths.get("config/build-bindings.xml").lastModified
).fold(0L, ::max)
private fun methodFilter(method: Method, javaClass: Class<*>) =
// static
method.modifiers and Modifier.STATIC != 0 &&
// returns NativeClass
method.returnType === javaClass &&
// has no arguments
method.parameterTypes.size == 0
private fun apply(packagePath: String, packageName: String, consume: Sequence<Method>.() -> Unit) {
val packageDirectory = Paths.get(packagePath)
if ( !Files.isDirectory(packageDirectory) )
throw IllegalStateException()
Files.list(packageDirectory)
.filter { KOTLIN_PATH_MATCHER.matches(it) }
.sorted(Comparator.naturalOrder())
.forEach {
try {
Class
.forName("$packageName.${it.fileName.toString().substringBeforeLast('.').upperCaseFirst}Kt")
.methods
.asSequence()
.consume()
} catch (e: ClassNotFoundException) {
// ignore
}
}
}
internal fun generate(packageName: String, binding: Binding? = null) {
val packagePath = "$srcPath/${packageName.replace('.', '/')}"
val packageLastModified = Paths.get(packagePath).lastModified(maxDepth = 1)
packageLastModifiedMap[packageName] = packageLastModified
if ( binding?.enabled == false )
return
// Find and run configuration methods
//runConfiguration(packagePath, packageName)
apply(packagePath, packageName) {
this
.filter { methodFilter(it, Void.TYPE) }
.forEach { it.invoke(null) }
}
// Find the template methods
val templates = TreeSet<Method> { o1, o2 -> o1.name.compareTo(o2.name) }
apply("$packagePath/templates", "$packageName.templates") {
this.filterTo(templates) {
methodFilter(it, NativeClass::class.java)
}
}
if ( templates.isEmpty() ) {
println("*WARNING* No templates found in $packageName.templates package.")
return
}
// Get classes with bodies and register tokens/functions
val packageTokens = HashMap<String, String>()
val packageFunctions = HashMap<String, String>()
val duplicateTokens = HashSet<String>()
val duplicateFunctions = HashSet<String>()
val classes = ArrayList<NativeClass>()
for (template in templates) {
val nativeClass = template.invoke(null) as NativeClass? ?: continue
if ( nativeClass.packageName != packageName )
throw IllegalStateException("NativeClass ${nativeClass.className} has invalid package [${nativeClass.packageName}]. Should be: [$packageName]")
if ( nativeClass.hasBody ) {
classes.add(nativeClass)
// Register tokens/functions for javadoc link references
nativeClass.registerLinks(
packageTokens,
duplicateTokens,
packageFunctions,
duplicateFunctions
)
}
}
packageTokens.keys.removeAll(duplicateTokens)
packageFunctions.keys.removeAll(duplicateFunctions)
tokens.put(packageName, packageTokens)
functions.put(packageName, packageFunctions)
// Generate the template code
classes.forEach {
it.registerFunctions()
generate(it, max(packageLastModified, GENERATOR_LAST_MODIFIED))
}
}
private fun generate(nativeClass: NativeClass, packageLastModified: Long) {
val packagePath = nativeClass.packageName.replace('.', '/')
val outputJava = Paths.get("$trgPath/java/$packagePath/${nativeClass.className}.java")
val lmt = max(nativeClass.getLastModified("$srcPath/$packagePath/templates"), packageLastModified)
if ( lmt < outputJava.lastModified ) {
//println("SKIPPED: ${nativeClass.packageName}.${nativeClass.className}")
return
}
//println("GENERATING: ${nativeClass.packageName}.${nativeClass.className}")
generateOutput(nativeClass, outputJava, lmt) {
it.generateJava()
}
if ( !nativeClass.skipNative ) {
generateNative(nativeClass) {
generateOutput(nativeClass, it) {
it.generateNative()
}
}
} else
nativeClass.nativeDirectivesWarning()
}
internal fun <T : GeneratorTarget> generate(typeName: String, targets: Iterable<T>) {
targets.forEach {
try {
generate(it)
} catch (e: Exception) {
throw RuntimeException("Uncaught exception while generating $typeName: ${it.packageName}.${it.className}", e)
}
}
}
internal fun generate(target: GeneratorTarget) {
val packagePath = target.packageName.replace('.', '/')
val outputJava = Paths.get("$trgPath/java/$packagePath/${target.className}.java")
val lmt = if ( target.sourceFile == null ) null else max(
target.getLastModified("$srcPath/$packagePath"),
max(packageLastModifiedMap[target.packageName]!!, GENERATOR_LAST_MODIFIED)
)
if ( lmt != null && lmt < outputJava.lastModified ) {
//println("SKIPPED: ${target.packageName}.${target.className}")
return
}
//println("GENERATING: ${target.packageName}.${target.className}")
generateOutput(target, outputJava, lmt) {
it.generateJava()
}
if ( target is GeneratorTargetNative && !target.skipNative ) {
generateNative(target) {
generateOutput(target, it) {
it.generateNative()
}
}
}
}
private fun generateNative(target: GeneratorTargetNative, generate: (Path) -> Unit) {
var subPackagePath = target.packageName.substring("org.lwjgl.".length).replace('.', '/')
if ( !target.nativeSubPath.isEmpty() )
subPackagePath = "$subPackagePath/${target.nativeSubPath}"
generate(Paths.get("$trgPath/c/$subPackagePath/${target.nativeFileName}.c"))
}
}
// File management
private val packageLastModifiedMap: MutableMap<String, Long> = ConcurrentHashMap()
internal val Path.lastModified: Long get() = if ( Files.isRegularFile(this) )
Files.getLastModifiedTime(this).toMillis()
else
0L
private val KOTLIN_PATH_MATCHER = FileSystems.getDefault().getPathMatcher("glob:**/*.kt")
internal fun Path.lastModified(
maxDepth: Int = Int.MAX_VALUE,
glob: String? = null,
matcher: PathMatcher = if ( glob == null ) KOTLIN_PATH_MATCHER else FileSystems.getDefault().getPathMatcher("glob:$glob")
): Long {
if ( !Files.isDirectory(this) )
throw IllegalStateException()
return Files
.find(this, maxDepth, BiPredicate { path, attribs -> matcher.matches(path) })
.mapToLong { it.lastModified }
.reduce(0L, Math::max)
}
private fun ensurePath(path: Path) {
val parent = path.parent ?: throw IllegalArgumentException("The given path has no parent directory.")
if ( !Files.isDirectory(parent) ) {
println("\tMKDIR: $parent")
Files.createDirectories(parent)
}
}
private fun readFile(file: Path) = Files.newByteChannel(file).use {
val bytesTotal = it.size().toInt()
val buffer = ByteBuffer.allocateDirect(bytesTotal)
var bytesRead = 0
do {
bytesRead += it.read(buffer)
} while ( bytesRead < bytesTotal )
buffer.flip()
buffer
}
private class LWJGLWriter(out: Writer) : PrintWriter(out) {
override fun println() = print('\n')
}
private fun <T> generateOutput(
target: T,
file: Path,
/** If not null, the file timestamp will be updated if no change occured since last generation. */
lmt: Long? = null,
generate: T.(PrintWriter) -> Unit
) {
// TODO: Add error handling
ensurePath(file)
if ( Files.isRegularFile(file) ) {
// Generate in-memory
val baos = ByteArrayOutputStream(4 * 1024)
LWJGLWriter(OutputStreamWriter(baos, Charsets.UTF_8)).use {
target.generate(it)
}
// Compare the existing file content with the generated content.
val before = readFile(file)
val after = baos.toByteArray()
fun somethingChanged(before: ByteBuffer, after: ByteArray): Boolean {
if ( before.remaining() != after.size )
return true
for (i in 0..before.limit() - 1) {
if ( before.get(i) != after[i] )
return true
}
return false
}
if ( somethingChanged(before, after) ) {
println("\tUPDATING: $file")
// Overwrite
Files.newOutputStream(file).use {
it.write(after)
}
} else if ( lmt != null ) {
// Update the file timestamp
Files.setLastModifiedTime(file, FileTime.fromMillis(lmt + 1))
}
} else {
println("\tWRITING: $file")
LWJGLWriter(Files.newBufferedWriter(file, Charsets.UTF_8)).use {
target.generate(it)
}
}
}
/** Returns true if the array was empty. */
internal inline fun <T> Array<out T>.forEachWithMore(apply: (T, Boolean) -> Unit): Boolean {
for (i in 0..this.lastIndex)
apply(this[i], 0 < i)
return this.size == 0
}
/** Returns true if the collection was empty. */
internal fun <T> Collection<T>.forEachWithMore(moreOverride: Boolean = false, apply: (T, Boolean) -> Unit): Boolean = this.asSequence().forEachWithMore(moreOverride, apply)
/** Returns true if the sequence was empty. */
internal fun <T> Sequence<T>.forEachWithMore(moreOverride: Boolean = false, apply: (T, Boolean) -> Unit): Boolean {
var more = moreOverride
for (item in this) {
apply(item, more)
if ( !more )
more = true
}
return more
}
/** Returns the string with the first letter uppercase. */
internal val String.upperCaseFirst: String
get() = if ( this.length <= 1 )
this.toUpperCase()
else
"${Character.toUpperCase(this[0])}${this.substring(1)}" | bsd-3-clause | a10bf3b8c9ea6ec6900e0cf1fddca062 | 27.909677 | 172 | 0.696033 | 3.61278 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/ui/view/bbcode/prototype/ImagePrototype.kt | 1 | 5342 | package me.proxer.app.ui.view.bbcode.prototype
import android.app.Activity
import android.graphics.drawable.Drawable
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.view.ViewCompat
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.target.Target
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.sizeDp
import com.uber.autodispose.android.ViewScopeProvider
import com.uber.autodispose.autoDisposable
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.ui.ImageDetailActivity
import me.proxer.app.ui.view.bbcode.BBArgs
import me.proxer.app.ui.view.bbcode.BBCodeView
import me.proxer.app.ui.view.bbcode.BBTree
import me.proxer.app.ui.view.bbcode.BBUtils
import me.proxer.app.ui.view.bbcode.prototype.BBPrototype.Companion.REGEX_OPTIONS
import me.proxer.app.util.extension.iconColor
import me.proxer.app.util.extension.logErrors
import me.proxer.app.util.extension.proxyIfRequired
import me.proxer.app.util.extension.toPrefixedUrlOrNull
import me.proxer.app.util.wrapper.SimpleGlideRequestListener
import okhttp3.HttpUrl
/**
* @author Ruben Gees
*/
object ImagePrototype : AutoClosingPrototype {
const val HEIGHT_MAP_ARGUMENT = "dimension_map"
private const val WIDTH_ARGUMENT = "width"
private val widthAttributeRegex = Regex("(?:size)? *= *(.+?)( |$)", REGEX_OPTIONS)
override val startRegex = Regex(" *img *=? *\"?.*?\"?( .*?)?", REGEX_OPTIONS)
override val endRegex = Regex("/ *img *", REGEX_OPTIONS)
override fun construct(code: String, parent: BBTree): BBTree {
val width = BBUtils.cutAttribute(code, widthAttributeRegex)?.toIntOrNull()
return BBTree(this, parent, args = BBArgs(custom = *arrayOf(WIDTH_ARGUMENT to width)))
}
override fun makeViews(parent: BBCodeView, children: List<BBTree>, args: BBArgs): List<View> {
val childViews = children.flatMap { it.makeViews(parent, args) }
val url = (childViews.firstOrNull() as? TextView)?.text.toString().trim()
val proxyUrl = url.toPrefixedUrlOrNull()?.proxyIfRequired()
@Suppress("UNCHECKED_CAST")
val heightMap = args[HEIGHT_MAP_ARGUMENT] as MutableMap<String, Int>?
val width = args[WIDTH_ARGUMENT] as Int? ?: MATCH_PARENT
val height = proxyUrl?.let { heightMap?.get(it.toString()) } ?: WRAP_CONTENT
return listOf(AppCompatImageView(parent.context).also { view: ImageView ->
ViewCompat.setTransitionName(view, "bb_image_$proxyUrl")
view.layoutParams = ViewGroup.MarginLayoutParams(width, height)
args.glide?.let { loadImage(it, view, proxyUrl, heightMap) }
(parent.context as? Activity)?.let { context ->
view.clicks()
.autoDisposable(ViewScopeProvider.from(parent))
.subscribe {
if (view.getTag(R.id.error_tag) == true) {
view.tag = null
args.glide?.let { loadImage(it, view, proxyUrl, heightMap) }
} else if (view.drawable != null && proxyUrl != null) {
ImageDetailActivity.navigateTo(context, proxyUrl, view)
}
}
}
})
}
private fun loadImage(
glide: GlideRequests,
view: ImageView,
url: HttpUrl?,
heightMap: MutableMap<String, Int>?
) = glide
.load(url.toString())
.centerInside()
.listener(object : SimpleGlideRequestListener<Drawable?> {
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable?>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
if (resource is Drawable && model is String) {
heightMap?.put(model, resource.intrinsicHeight)
}
if (target is ImageViewTarget && target.view.layoutParams.height <= 0) {
findHost(target.view)?.heightChanges?.onNext(Unit)
}
return false
}
override fun onLoadFailed(error: GlideException?): Boolean {
view.setTag(R.id.error_tag, true)
return false
}
})
.error(
IconicsDrawable(view.context, CommunityMaterial.Icon.cmd_refresh)
.iconColor(view.context)
.sizeDp(32)
)
.logErrors()
.into(view)
private fun findHost(view: View): BBCodeView? {
var current = view.parent
while (current !is BBCodeView && current is ViewGroup) {
current = current.parent
}
return current as? BBCodeView
}
}
| gpl-3.0 | ef5213bf839bfb9782d5a601fba4df4e | 36.356643 | 98 | 0.646574 | 4.481544 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.