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
f-droid/fdroidclient
libs/index/src/commonMain/kotlin/org/fdroid/index/v1/IndexV1.kt
1
1698
package org.fdroid.index.v1 import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import org.fdroid.index.DEFAULT_LOCALE import org.fdroid.index.v2.AntiFeatureV2 import org.fdroid.index.v2.CategoryV2 import org.fdroid.index.v2.FileV2 import org.fdroid.index.v2.MirrorV2 import org.fdroid.index.v2.ReleaseChannelV2 import org.fdroid.index.v2.RepoV2 @Serializable public data class IndexV1( val repo: RepoV1, val requests: Requests = Requests(emptyList(), emptyList()), val apps: List<AppV1> = emptyList(), val packages: Map<String, List<PackageV1>> = emptyMap(), ) @Serializable public data class RepoV1( val timestamp: Long, val version: Int, @SerialName("maxage") val maxAge: Int? = null, // missing in izzy repo val name: String, val icon: String, val address: String, val description: String, val mirrors: List<String> = emptyList(), // missing in izzy repo ) { public fun toRepoV2( locale: String = DEFAULT_LOCALE, antiFeatures: Map<String, AntiFeatureV2>, categories: Map<String, CategoryV2>, releaseChannels: Map<String, ReleaseChannelV2>, ): RepoV2 = RepoV2( name = mapOf(locale to name), icon = mapOf(locale to FileV2("/icons/$icon")), address = address, webBaseUrl = null, description = mapOf(locale to description), mirrors = mirrors.map { MirrorV2(it) }, timestamp = timestamp, antiFeatures = antiFeatures, categories = categories, releaseChannels = releaseChannels, ) } @Serializable public data class Requests( val install: List<String>, val uninstall: List<String>, )
gpl-3.0
c65f41e33681b00b41a928a7891bac25
29.321429
68
0.687279
3.731868
false
false
false
false
google/horologist
compose-layout/src/main/java/com/google/android/horologist/compose/rotaryinput/Rotary.kt
1
39926
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.compose.rotaryinput import android.view.ViewConfiguration import androidx.compose.animation.core.AnimationState import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.SpringSpec import androidx.compose.animation.core.animateTo import androidx.compose.animation.core.copy import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.ScrollableDefaults import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.input.rotary.onRotaryScrollEvent import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.util.fastSumBy import androidx.wear.compose.material.ScalingLazyListState import com.google.android.horologist.compose.navscaffold.ExperimentalHorologistComposeLayoutApi import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.transformLatest import kotlin.math.abs import kotlin.math.sign private const val DEBUG = false /** * Debug logging that can be enabled. */ private inline fun debugLog(generateMsg: () -> String) { if (DEBUG) { println("RotaryScroll: ${generateMsg()}") } } /** * A modifier which connects rotary events with scrollable. * This modifier supports fling. * * Fling algorithm: * - A scroll with RSB/ Bezel happens. * - If this is a first rotary event after the threshold ( by default 200ms), a new scroll * session starts by resetting all necessary parameters * - A delta value is added into VelocityTracker and a new speed is calculated. * - If the current speed is bigger than the previous one, this value is remembered as * a latest fling speed with a timestamp * - After each scroll event a fling countdown starts ( by default 70ms) which * resets if new scroll event is received * - If fling countdown is finished - it means that the finger was probably raised from RSB, there will be no other events and probably * this is the last event during this session. After it a fling is triggered. * - Fling is stopped when a new scroll event happens * * The screen containing the scrollable item should request the focus * by calling [requestFocus] method * * ``` * LaunchedEffect(Unit) { * focusRequester.requestFocus() * } * ``` * @param focusRequester Requests the focus for rotary input * @param scrollableState Scrollable state which will be scrolled while receiving rotary events * @param flingBehavior Logic describing fling behavior. * @param rotaryHaptics Class which will handle haptic feedback */ @ExperimentalHorologistComposeLayoutApi @Suppress("ComposableModifierFactory") @Composable public fun Modifier.rotaryWithFling( focusRequester: FocusRequester, scrollableState: ScrollableState, flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(), rotaryHaptics: RotaryHapticFeedback = rememberRotaryHapticFeedback() ): Modifier = rotaryHandler( rotaryScrollHandler = RotaryDefaults.rememberFlingHandler(scrollableState, flingBehavior), rotaryHaptics = rotaryHaptics ) .focusRequester(focusRequester) .focusable() /** * A modifier which connects rotary events with scrollable. * This modifier only supports scroll without fling or snap. * The screen containing the scrollable item should request the focus * by calling [requestFocus] method * * ``` * LaunchedEffect(Unit) { * focusRequester.requestFocus() * } * ``` * @param focusRequester Requests the focus for rotary input * @param scrollableState Scrollable state which will be scrolled while receiving rotary events * @param rotaryHaptics Class which will handle haptic feedback */ @ExperimentalHorologistComposeLayoutApi @Suppress("ComposableModifierFactory") @Composable public fun Modifier.rotaryWithScroll( focusRequester: FocusRequester, scrollableState: ScrollableState, rotaryHaptics: RotaryHapticFeedback = rememberRotaryHapticFeedback() ): Modifier = rotaryHandler( rotaryScrollHandler = RotaryDefaults.rememberFlingHandler(scrollableState, null), rotaryHaptics = rotaryHaptics ) .focusRequester(focusRequester) .focusable() /** * A modifier which connects rotary events with scrollable. * This modifier supports snap. * * The screen containing the scrollable item should request the focus * by calling [requestFocus] method * * ``` * LaunchedEffect(Unit) { * focusRequester.requestFocus() * } * ``` * @param focusRequester Requests the focus for rotary input * @param rotaryScrollAdapter A connection between scrollable objects and rotary events * @param rotaryHaptics Class which will handle haptic feedback */ @ExperimentalHorologistComposeLayoutApi @Suppress("ComposableModifierFactory") @Composable public fun Modifier.rotaryWithSnap( focusRequester: FocusRequester, rotaryScrollAdapter: RotaryScrollAdapter, rotaryHaptics: RotaryHapticFeedback = rememberRotaryHapticFeedback() ): Modifier = rotaryHandler( rotaryScrollHandler = RotaryDefaults.rememberSnapHandler(rotaryScrollAdapter), rotaryHaptics = rotaryHaptics ) .focusRequester(focusRequester) .focusable() /** * An extension function for creating [RotaryScrollAdapter] from [ScalingLazyListState] */ @ExperimentalHorologistComposeLayoutApi public fun ScalingLazyListState.toRotaryScrollAdapter(): RotaryScrollAdapter = ScalingLazyColumnRotaryScrollAdapter(this) /** * An implementation of rotary scroll adapter for [ScalingLazyColumn] */ @ExperimentalHorologistComposeLayoutApi public class ScalingLazyColumnRotaryScrollAdapter( override val scrollableState: ScalingLazyListState ) : RotaryScrollAdapter { /** * Calculates an average height of an item by taking an average from visible items height. */ override fun averageItemSize(): Float { val visibleItems = scrollableState.layoutInfo.visibleItemsInfo return (visibleItems.fastSumBy { it.unadjustedSize } / visibleItems.size).toFloat() } /** * Current (centred) item index */ override fun currentItemIndex(): Int = scrollableState.centerItemIndex /** * An offset from the item centre */ override fun currentItemOffset(): Float = scrollableState.centerItemScrollOffset.toFloat() } /** * An adapter which connects scrollableState to Rotary */ @ExperimentalHorologistComposeLayoutApi public interface RotaryScrollAdapter { /** * A scrollable state. Used for performing scroll when Rotary events received */ @ExperimentalHorologistComposeLayoutApi public val scrollableState: ScrollableState /** * Average size of an item. Used for estimating the scrollable distance */ @ExperimentalHorologistComposeLayoutApi public fun averageItemSize(): Float /** * A current item index. Used for scrolling */ @ExperimentalHorologistComposeLayoutApi public fun currentItemIndex(): Int /** * An offset from the centre or the border of the current item. */ @ExperimentalHorologistComposeLayoutApi public fun currentItemOffset(): Float } /** * Defaults for rotary modifiers */ @ExperimentalHorologistComposeLayoutApi public object RotaryDefaults { /** * Handles scroll with fling. * @param scrollableState Scrollable state which will be scrolled while receiving rotary events * @param flingBehavior Logic describing Fling behavior. If null - fling will not happen * @param isLowRes Whether the input is Low-res (a bezel) or high-res(a crown/rsb) */ @ExperimentalHorologistComposeLayoutApi @Composable public fun rememberFlingHandler( scrollableState: ScrollableState, flingBehavior: FlingBehavior? = null, isLowRes: Boolean = isLowResInput() ): RotaryScrollHandler { val viewConfiguration = ViewConfiguration.get(LocalContext.current) return remember(scrollableState, flingBehavior, isLowRes) { debugLog { "isLowRes : $isLowRes" } fun rotaryFlingBehavior() = flingBehavior?.run { DefaultRotaryFlingBehavior( scrollableState, flingBehavior, viewConfiguration, flingTimeframe = if (isLowRes) lowResFlingTimeframe else highResFlingTimeframe ) } fun scrollBehavior() = AnimationScrollBehavior(scrollableState) if (isLowRes) { LowResRotaryScrollHandler( rotaryFlingBehaviorFactory = { rotaryFlingBehavior() }, scrollBehaviorFactory = { scrollBehavior() } ) } else { HighResRotaryScrollHandler( rotaryFlingBehaviorFactory = { rotaryFlingBehavior() }, scrollBehaviorFactory = { scrollBehavior() } ) } } } /** * Handles scroll with snap * @param rotaryScrollAdapter A connection between scrollable objects and rotary events * @param snapParameters Snap parameters */ @ExperimentalHorologistComposeLayoutApi @Composable public fun rememberSnapHandler( rotaryScrollAdapter: RotaryScrollAdapter, snapParameters: SnapParameters = snapParametersDefault() ): RotaryScrollHandler { return remember(rotaryScrollAdapter, snapParameters) { RotaryScrollSnapHandler( snapBehaviourFactory = { DefaultSnapBehavior(rotaryScrollAdapter, snapParameters) }, scrollBehaviourFactory = { AnimationScrollBehavior(rotaryScrollAdapter.scrollableState) } ) } } /** * Returns default [SnapParameters] */ @ExperimentalHorologistComposeLayoutApi public fun snapParametersDefault(): SnapParameters = SnapParameters(snapOffset = 0) @ExperimentalHorologistComposeLayoutApi @Composable private fun isLowResInput(): Boolean = LocalContext.current.packageManager .hasSystemFeature("android.hardware.rotaryencoder.lowres") private val lowResFlingTimeframe: Long = 100L private val highResFlingTimeframe: Long = 30L } /** * Parameters used for snapping * * @param snapOffset an optional offset to be applied when snapping the item. After the snap the * snapped items offset will be [snapOffset]. */ public class SnapParameters(public val snapOffset: Int) { /** * Returns a snapping offset in [Dp] */ @Composable public fun snapOffsetDp(): Dp { return with(LocalDensity.current) { snapOffset.toDp() } } } /** * An interface for handling scroll events */ @ExperimentalHorologistComposeLayoutApi public interface RotaryScrollHandler { /** * Handles scrolling events * @param coroutineScope A scope for performing async actions * @param event A scrollable event from rotary input, containing scrollable delta and timestamp * @param rotaryHaptics */ @ExperimentalHorologistComposeLayoutApi public suspend fun handleScrollEvent( coroutineScope: CoroutineScope, event: TimestampedDelta, rotaryHaptics: RotaryHapticFeedback ) } /** * An interface for scrolling behavior */ @ExperimentalHorologistComposeLayoutApi public interface RotaryScrollBehavior { /** * Handles scroll event to [targetValue] */ @ExperimentalHorologistComposeLayoutApi public suspend fun handleEvent(targetValue: Float) } /** * Default implementation of [RotaryFlingBehavior] */ @ExperimentalHorologistComposeLayoutApi public class DefaultRotaryFlingBehavior( private val scrollableState: ScrollableState, private val flingBehavior: FlingBehavior, viewConfiguration: ViewConfiguration, private val flingTimeframe: Long ) : RotaryFlingBehavior { // A time range during which the fling is valid. // For simplicity it's twice as long as [flingTimeframe] private val timeRangeToFling = flingTimeframe * 2 // A default fling factor for making fling slower private val flingScaleFactor = 0.7f private var previousVelocity = 0f private val rotaryVelocityTracker = RotaryVelocityTracker() private val minFlingSpeed = viewConfiguration.scaledMinimumFlingVelocity.toFloat() private val maxFlingSpeed = viewConfiguration.scaledMaximumFlingVelocity.toFloat() private var latestEventTimestamp: Long = 0 private var flingVelocity: Float = 0f private var flingTimestamp: Long = 0 @ExperimentalHorologistComposeLayoutApi override fun startFlingTracking(timestamp: Long) { rotaryVelocityTracker.start(timestamp) latestEventTimestamp = timestamp previousVelocity = 0f } @ExperimentalHorologistComposeLayoutApi override fun observeEvent(timestamp: Long, delta: Float) { rotaryVelocityTracker.move(timestamp, delta) latestEventTimestamp = timestamp } @ExperimentalHorologistComposeLayoutApi override suspend fun trackFling(beforeFling: () -> Unit) { val currentVelocity = rotaryVelocityTracker.velocity debugLog { "currentVelocity: $currentVelocity" } if (abs(currentVelocity) >= abs(previousVelocity)) { flingTimestamp = latestEventTimestamp flingVelocity = currentVelocity * flingScaleFactor } previousVelocity = currentVelocity // Waiting for a fixed amount of time before checking the fling delay(flingTimeframe) // For making a fling 2 criteria should be met: // 1) no more than // `rangeToFling` ms should pass between last fling detection // and the time of last motion event // 2) flingVelocity should exceed the minFlingSpeed debugLog { "Check fling: flingVelocity: $flingVelocity " + "minFlingSpeed: $minFlingSpeed, maxFlingSpeed: $maxFlingSpeed" } if (latestEventTimestamp - flingTimestamp < timeRangeToFling && abs(flingVelocity) > minFlingSpeed ) { // Stops scrollAnimationCoroutine because a fling will be performed beforeFling() val velocity = flingVelocity.coerceIn(-maxFlingSpeed, maxFlingSpeed) scrollableState.scroll(MutatePriority.UserInput) { with(flingBehavior) { debugLog { "Flinging with velocity $velocity" } performFling(velocity) } } } } } /** * An interface for flinging with rotary */ @ExperimentalHorologistComposeLayoutApi public interface RotaryFlingBehavior { /** * Observing new event within a fling tracking session with new timestamp and delta */ @ExperimentalHorologistComposeLayoutApi public fun observeEvent(timestamp: Long, delta: Float) /** * Performing fling if necessary and calling [beforeFling] lambda before it is triggered */ @ExperimentalHorologistComposeLayoutApi public suspend fun trackFling(beforeFling: () -> Unit) /** * Starts a new fling tracking session * with specified timestamp */ @ExperimentalHorologistComposeLayoutApi public fun startFlingTracking(timestamp: Long) } /** * An interface for snapping with rotary */ @ExperimentalHorologistComposeLayoutApi public interface RotarySnapBehavior { /** * Preparing snapping. This method should be called before [startSnappingSession] is called. * * Snapping is done for current + [moveForElements] items. * * If [sequentialSnap] is true, items are summed up together. * For example, if [prepareSnapForItems] is called with * [moveForElements] = 2, 3, 5 -> then the snapping will happen to current + 10 items * * If [sequentialSnap] is false, then [moveForElements] are not summed up together. */ public fun prepareSnapForItems(moveForElements: Int, sequentialSnap: Boolean) /** * Performs snapping to the specified in [prepareSnapForItems] element * If [toClosestItem] is true - then the snapping will happen to the closest item only. * If it's set to false - then it'll snap to the element specified * in [prepareSnapForItems] method. */ @ExperimentalHorologistComposeLayoutApi public suspend fun startSnappingSession(toClosestItem: Boolean) /** * A threshold after which snapping happens. * There can be 2 thresholds - before snap and during snap (while snap is happening ). * During-snap threshold is usually longer than before-snap so that * the list will not scroll too fast. */ @ExperimentalHorologistComposeLayoutApi public fun snapThreshold(duringSnap: Boolean): Float } /** * A rotary event object which contains a [timestamp] of the rotary event and a scrolled [delta]. */ @ExperimentalHorologistComposeLayoutApi public data class TimestampedDelta(val timestamp: Long, val delta: Float) /** Animation implementation of [RotaryScrollBehavior]. * This class does a smooth animation when the scroll by N pixels is done. * This animation works well on Rsb(high-res) and Bezel(low-res) devices. */ @ExperimentalHorologistComposeLayoutApi public class AnimationScrollBehavior( private val scrollableState: ScrollableState ) : RotaryScrollBehavior { private var sequentialAnimation = false private var scrollAnimation = AnimationState(0f) private var prevPosition = 0f @ExperimentalHorologistComposeLayoutApi override suspend fun handleEvent(targetValue: Float) { scrollableState.scroll(MutatePriority.UserInput) { debugLog { "ScrollAnimation value before start: ${scrollAnimation.value}" } scrollAnimation.animateTo( targetValue, animationSpec = spring(), sequentialAnimation = sequentialAnimation ) { val delta = value - prevPosition debugLog { "Animated by $delta, value: $value" } scrollBy(delta) prevPosition = value sequentialAnimation = value != this.targetValue } } } } /** * An animated implementation of [RotarySnapBehavior]. Uses animateScrollToItem * method for snapping to the Nth item */ @ExperimentalHorologistComposeLayoutApi public class DefaultSnapBehavior( private val rotaryScrollAdapter: RotaryScrollAdapter, private val snapParameters: SnapParameters ) : RotarySnapBehavior { private var snapTarget: Int = 0 private var sequentialSnap: Boolean = false private var anim = AnimationState(0f) private var expectedDistance = 0f private val defaultStiffness = 200f private var snapTargetUpdated = true @ExperimentalHorologistComposeLayoutApi override fun prepareSnapForItems(moveForElements: Int, sequentialSnap: Boolean) { this.sequentialSnap = sequentialSnap if (sequentialSnap) { snapTarget += moveForElements } else { snapTarget = rotaryScrollAdapter.currentItemIndex() + moveForElements } snapTargetUpdated = true } @ExperimentalHorologistComposeLayoutApi override suspend fun startSnappingSession(toClosestItem: Boolean) { if (toClosestItem) { snapToClosestItem() } else { snapToAnotherItem() } } @ExperimentalHorologistComposeLayoutApi override fun snapThreshold(duringSnap: Boolean): Float { val averageSize = rotaryScrollAdapter.averageItemSize() // it just looks better if it takes more scroll to trigger a snap second time. return (if (duringSnap) averageSize * 0.7f else averageSize * 0.3f) .coerceIn(50f..400f) // 30 percent of the average height } private suspend fun snapToClosestItem() { // Snapping to the closest item by using performFling method with 0 speed rotaryScrollAdapter.scrollableState.scroll(MutatePriority.UserInput) { debugLog { "snap to closest item" } var prevPosition = 0f AnimationState(0f).animateTo( targetValue = -rotaryScrollAdapter.currentItemOffset(), animationSpec = tween(durationMillis = 100, easing = FastOutSlowInEasing) ) { val animDelta = value - prevPosition scrollBy(animDelta) prevPosition = value } snapTarget = rotaryScrollAdapter.currentItemIndex() } } private suspend fun snapToAnotherItem() { if (sequentialSnap) { anim = anim.copy(0f) } else { anim = AnimationState(0f) } debugLog { "snapTarget $snapTarget" } rotaryScrollAdapter.scrollableState.scroll(MutatePriority.UserInput) { // If snapTargetUpdated is true - then the target was updated so we // need to do snap again while (snapTargetUpdated) { snapTargetUpdated = false var latestCenterItem: Int var continueFirstScroll = true while (continueFirstScroll) { latestCenterItem = rotaryScrollAdapter.currentItemIndex() anim = anim.copy(0f) expectedDistance = expectedDistanceTo(snapTarget, snapParameters.snapOffset) debugLog { "expectedDistance = $expectedDistance, " + "scrollableState.centerItemScrollOffset " + "${rotaryScrollAdapter.currentItemOffset()}" } continueFirstScroll = false var prevPosition = 0f anim.animateTo( expectedDistance, animationSpec = SpringSpec( stiffness = defaultStiffness, visibilityThreshold = 0.1f ), sequentialAnimation = (anim.velocity != 0f) ) { val animDelta = value - prevPosition debugLog { "First animation, value:$value, velocity:$velocity, " + "animDelta:$animDelta" } // Exit animation if snap target was updated if (snapTargetUpdated) cancelAnimation() scrollBy(animDelta) prevPosition = value if (latestCenterItem != rotaryScrollAdapter.currentItemIndex()) { continueFirstScroll = true cancelAnimation() return@animateTo } debugLog { "centerItemIndex = ${rotaryScrollAdapter.currentItemIndex()}" } if (rotaryScrollAdapter.currentItemIndex() == snapTarget) { debugLog { "Target is visible. Cancelling first animation" } debugLog { "scrollableState.centerItemScrollOffset " + "${rotaryScrollAdapter.currentItemOffset()}" } expectedDistance = -rotaryScrollAdapter.currentItemOffset() continueFirstScroll = false cancelAnimation() return@animateTo } } } // Exit animation if snap target was updated if (snapTargetUpdated) continue anim = anim.copy(0f) var prevPosition = 0f anim.animateTo( expectedDistance, animationSpec = SpringSpec( stiffness = defaultStiffness, visibilityThreshold = 0.1f ), sequentialAnimation = (anim.velocity != 0f) ) { // Exit animation if snap target was updated if (snapTargetUpdated) cancelAnimation() val animDelta = value - prevPosition debugLog { "Final animation. velocity:$velocity, animDelta:$animDelta" } scrollBy(animDelta) prevPosition = value } } } } private fun expectedDistanceTo(index: Int, targetScrollOffset: Int): Float { val averageSize = rotaryScrollAdapter.averageItemSize() val indexesDiff = index - rotaryScrollAdapter.currentItemIndex() debugLog { "Average size $averageSize" } return (averageSize * indexesDiff) + targetScrollOffset - rotaryScrollAdapter.currentItemOffset() } } /** * A modifier which handles rotary events. * It accepts ScrollHandler as the input - a class where main logic about how * scroll should be handled is lying */ @ExperimentalHorologistComposeLayoutApi @OptIn(ExperimentalComposeUiApi::class) public fun Modifier.rotaryHandler( rotaryScrollHandler: RotaryScrollHandler, batchTimeframe: Long = 0L, rotaryHaptics: RotaryHapticFeedback ): Modifier = composed { val channel = rememberTimestampChannel() val eventsFlow = remember(channel) { channel.receiveAsFlow() } composed { LaunchedEffect(eventsFlow) { eventsFlow // TODO: batching causes additional delays. // Do we really need to do this on this level? .batchRequestsWithinTimeframe(batchTimeframe) .collectLatest { debugLog { "Scroll event received: " + "delta:${it.delta}, timestamp:${it.timestamp}" } rotaryScrollHandler.handleScrollEvent(this, it, rotaryHaptics) } } this .onRotaryScrollEvent { channel.trySend( TimestampedDelta( it.uptimeMillis, it.verticalScrollPixels ) ) true } } } /** * Batching requests for scrolling events. This function combines all events together * (except first) within specified timeframe. Should help with performance on high-res devices. */ @ExperimentalHorologistComposeLayoutApi @OptIn(ExperimentalCoroutinesApi::class) public fun Flow<TimestampedDelta>.batchRequestsWithinTimeframe(timeframe: Long): Flow<TimestampedDelta> { var delta = 0f var lastTimestamp = -timeframe return if (timeframe == 0L) { this } else { this.transformLatest { delta += it.delta debugLog { "Batching requests. delta:$delta" } if (lastTimestamp + timeframe <= it.timestamp) { lastTimestamp = it.timestamp debugLog { "No events before, delta= $delta" } emit(TimestampedDelta(it.timestamp, delta)) } else { delay(timeframe) debugLog { "After delay, delta= $delta" } if (delta > 0f) { emit(TimestampedDelta(it.timestamp, delta)) } } delta = 0f } } } /** * A scroll handler for RSB(high-res) without snapping and with or without fling * A list is scrolled by the number of pixels received from the rotary device. * * This class is a little bit different from LowResScrollHandler class - it has a filtering * for events which are coming with wrong sign ( this happens to rsb devices, * especially at the end of the scroll) * * This scroll handler supports fling. It can be set with [RotaryFlingBehavior]. */ @OptIn(ExperimentalHorologistComposeLayoutApi::class) internal class HighResRotaryScrollHandler( private val rotaryFlingBehaviorFactory: () -> RotaryFlingBehavior?, private val scrollBehaviorFactory: () -> RotaryScrollBehavior, private val hapticsThreshold: Long = 50 ) : RotaryScrollHandler { // This constant is specific for high-res devices. Because that input values // can sometimes come with different sign, we have to filter them in this threshold private val gestureThresholdTime = 200L private var scrollJob: Job = CompletableDeferred<Unit>() private var flingJob: Job = CompletableDeferred<Unit>() private var previousScrollEventTime = 0L private var rotaryScrollDistance = 0f private var rotaryFlingBehavior: RotaryFlingBehavior? = rotaryFlingBehaviorFactory() private var scrollBehavior: RotaryScrollBehavior = scrollBehaviorFactory() private var prevHapticsPosition = 0f private var currScrollPosition = 0f override suspend fun handleScrollEvent( coroutineScope: CoroutineScope, event: TimestampedDelta, rotaryHaptics: RotaryHapticFeedback ) { val time = event.timestamp if (isNewScrollEvent(time)) { debugLog { "New scroll event" } resetTracking(time) rotaryScrollDistance = event.delta } else { // Filter out opposite axis values from end of scroll, also some values // at the start of motion which sometimes appear with a different sign if (isOppositeValueAfterScroll(event.delta)) { debugLog { "Opposite value after scroll. Filtering:${event.delta}" } return } rotaryScrollDistance += event.delta rotaryFlingBehavior?.observeEvent(event.timestamp, event.delta) } scrollJob.cancel() flingJob.cancel() handleHaptic(rotaryHaptics, event.delta) debugLog { "Rotary scroll distance: $rotaryScrollDistance" } previousScrollEventTime = time scrollJob = coroutineScope.async { scrollBehavior.handleEvent(rotaryScrollDistance) } flingJob = coroutineScope.async { rotaryFlingBehavior?.trackFling( beforeFling = { debugLog { "Calling before fling section" } scrollJob.cancel() scrollBehavior = scrollBehaviorFactory() } ) } } private fun isOppositeValueAfterScroll(delta: Float): Boolean = sign(rotaryScrollDistance) * sign(delta) == -1f && (abs(delta) < abs(rotaryScrollDistance)) private fun isNewScrollEvent(timestamp: Long): Boolean { val timeDelta = timestamp - previousScrollEventTime return previousScrollEventTime == 0L || timeDelta > gestureThresholdTime } private fun resetTracking(timestamp: Long) { scrollBehavior = scrollBehaviorFactory() rotaryFlingBehavior = rotaryFlingBehaviorFactory() rotaryFlingBehavior?.startFlingTracking(timestamp) } private fun handleHaptic(rotaryHaptics: RotaryHapticFeedback, scrollDelta: Float) { currScrollPosition += scrollDelta val diff = abs(currScrollPosition - prevHapticsPosition) if (diff >= hapticsThreshold) { rotaryHaptics.performHapticFeedback(RotaryHapticsType.ScrollTick) prevHapticsPosition = currScrollPosition } } } /** * A scroll handler for Bezel(low-res) without snapping. * This scroll handler supports fling. It can be set with RotaryFlingBehavior. */ @OptIn(ExperimentalHorologistComposeLayoutApi::class) internal class LowResRotaryScrollHandler( private val rotaryFlingBehaviorFactory: () -> RotaryFlingBehavior?, private val scrollBehaviorFactory: () -> RotaryScrollBehavior ) : RotaryScrollHandler { private val gestureThresholdTime = 200L private var previousScrollEventTime = 0L private var rotaryScrollDistance = 0f private var scrollJob: Job = CompletableDeferred<Unit>() private var flingJob: Job = CompletableDeferred<Unit>() private var rotaryFlingBehavior: RotaryFlingBehavior? = rotaryFlingBehaviorFactory() private var scrollBehavior: RotaryScrollBehavior = scrollBehaviorFactory() override suspend fun handleScrollEvent( coroutineScope: CoroutineScope, event: TimestampedDelta, rotaryHaptics: RotaryHapticFeedback ) { val time = event.timestamp if (isNewScrollEvent(time)) { resetTracking(time) rotaryScrollDistance = event.delta } else { rotaryFlingBehavior?.observeEvent(event.timestamp, event.delta) rotaryScrollDistance += event.delta } scrollJob.cancel() flingJob.cancel() rotaryHaptics.performHapticFeedback(RotaryHapticsType.ScrollItemFocus) debugLog { "Rotary scroll distance: $rotaryScrollDistance" } previousScrollEventTime = time scrollJob = coroutineScope.async { scrollBehavior.handleEvent(rotaryScrollDistance) } flingJob = coroutineScope.async { rotaryFlingBehavior?.trackFling( beforeFling = { debugLog { "Calling before fling section" } scrollJob.cancel() scrollBehavior = scrollBehaviorFactory() } ) } } private fun isNewScrollEvent(timestamp: Long): Boolean { val timeDelta = timestamp - previousScrollEventTime return previousScrollEventTime == 0L || timeDelta > gestureThresholdTime } private fun resetTracking(timestamp: Long) { scrollBehavior = scrollBehaviorFactory() debugLog { "Velocity tracker reset" } rotaryFlingBehavior = rotaryFlingBehaviorFactory() rotaryFlingBehavior?.startFlingTracking(timestamp) } } /** * A scroll handler for RSB(high-res) with snapping and without fling * Snapping happens after a threshold is reached ( set in [RotarySnapBehavior]) * * This scroll handler doesn't support fling. */ @OptIn(ExperimentalHorologistComposeLayoutApi::class) internal class RotaryScrollSnapHandler( val snapBehaviourFactory: () -> RotarySnapBehavior, val scrollBehaviourFactory: () -> RotaryScrollBehavior ) : RotaryScrollHandler { // This constant is specific for high-res devices. Because that input values // can sometimes come with different sign, we have to filter them in this threshold val gestureThresholdTime = 200L val snapDelay = 100L var scrollJob: Job = CompletableDeferred<Unit>() var snapJob: Job = CompletableDeferred<Unit>() var previousScrollEventTime = 0L var rotaryScrollDistance = 0f var scrollInProgress = false var snapBehaviour = snapBehaviourFactory() var scrollBehaviour = scrollBehaviourFactory() override suspend fun handleScrollEvent( coroutineScope: CoroutineScope, event: TimestampedDelta, rotaryHaptics: RotaryHapticFeedback ) { val time = event.timestamp if (isNewScrollEvent(time)) { debugLog { "New scroll event" } resetTracking() snapJob.cancel() snapBehaviour = snapBehaviourFactory() scrollBehaviour = scrollBehaviourFactory() rotaryScrollDistance = event.delta } else { // Filter out opposite axis values from end of scroll, also some values // at the start of motion which sometimes appear with a different sign if (isOppositeValueAfterScroll(event.delta)) { debugLog { "Opposite value after scroll. Filtering:${event.delta}" } return } rotaryScrollDistance += event.delta } debugLog { "Rotary scroll distance: $rotaryScrollDistance" } previousScrollEventTime = time if (abs(rotaryScrollDistance) > snapBehaviour.snapThreshold(snapJob.isActive)) { debugLog { "Snap threshold reached" } scrollInProgress = false scrollBehaviour = scrollBehaviourFactory() scrollJob.cancel() val snapDistance = sign(rotaryScrollDistance).toInt() rotaryHaptics.performHapticFeedback(RotaryHapticsType.ScrollItemFocus) val sequentialSnap = snapJob.isActive debugLog { "Prepare snap: snapDistance:$snapDistance, " + "sequentialSnap: $sequentialSnap" } snapBehaviour.prepareSnapForItems(snapDistance, sequentialSnap) if (!snapJob.isActive) { snapJob.cancel() snapJob = coroutineScope.async { debugLog { "Snap started" } try { snapBehaviour.startSnappingSession(false) } finally { debugLog { "Snap called finally" } } } } rotaryScrollDistance = 0f } else { if (!snapJob.isActive) { scrollJob.cancel() debugLog { "Scrolling for ${event.delta} px" } scrollJob = coroutineScope.async { scrollBehaviour.handleEvent(rotaryScrollDistance) } delay(snapDelay) scrollInProgress = false scrollBehaviour = scrollBehaviourFactory() snapBehaviour.prepareSnapForItems(0, false) snapBehaviour.startSnappingSession(true) } } } private fun isOppositeValueAfterScroll(delta: Float): Boolean = sign(rotaryScrollDistance) * sign(delta) == -1f && (abs(delta) < abs(rotaryScrollDistance)) private fun isNewScrollEvent(timestamp: Long): Boolean { val timeDelta = timestamp - previousScrollEventTime return previousScrollEventTime == 0L || timeDelta > gestureThresholdTime } private fun resetTracking() { scrollInProgress = true } } @OptIn(ExperimentalHorologistComposeLayoutApi::class) @Composable private fun rememberTimestampChannel() = remember { Channel<TimestampedDelta>(capacity = Channel.CONFLATED) }
apache-2.0
88c4acd86562482c7b03b4e243d0c955
36.037106
135
0.665682
5.169753
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/ui/preferences/HomeScreenGridPreferences.kt
1
4185
package app.lawnchair.ui.preferences import android.content.res.Configuration import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.material.MaterialTheme import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.navigation.NavGraphBuilder import app.lawnchair.preferences.asPreferenceAdapter import app.lawnchair.preferences.getAdapter import app.lawnchair.preferences.preferenceManager import app.lawnchair.ui.preferences.components.GridOverridesPreview import app.lawnchair.ui.preferences.components.PreferenceGroup import app.lawnchair.ui.preferences.components.PreferenceLayout import app.lawnchair.ui.preferences.components.SliderPreference import com.android.launcher3.LauncherAppState import com.android.launcher3.R fun NavGraphBuilder.homeScreenGridGraph(route: String) { preferenceGraph(route, { HomeScreenGridPreferences() }) } @Composable fun HomeScreenGridPreferences() { val isPortrait = LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT val scrollState = rememberScrollState() PreferenceLayout( label = stringResource(id = R.string.home_screen_grid), scrollState = if (isPortrait) null else scrollState ) { val prefs = preferenceManager() val columnsAdapter = prefs.workspaceColumns.getAdapter() val rowsAdapter = prefs.workspaceRows.getAdapter() val originalColumns = remember { columnsAdapter.state.value } val originalRows = remember { rowsAdapter.state.value } val columns = rememberSaveable { mutableStateOf(originalColumns) } val rows = rememberSaveable { mutableStateOf(originalRows) } if (isPortrait) { GridOverridesPreview( modifier = Modifier .padding(top = 8.dp) .weight(1f) .align(Alignment.CenterHorizontally) .clip(MaterialTheme.shapes.large) ) { numColumns = columns.value numRows = rows.value } } PreferenceGroup { SliderPreference( label = stringResource(id = R.string.columns), adapter = columns.asPreferenceAdapter(), step = 1, valueRange = 3..10, ) SliderPreference( label = stringResource(id = R.string.rows), adapter = rows.asPreferenceAdapter(), step = 1, valueRange = 3..10, ) } val navController = LocalNavController.current val context = LocalContext.current val applyOverrides = { prefs.batchEdit { columnsAdapter.onChange(columns.value) rowsAdapter.onChange(rows.value) } LauncherAppState.getIDP(context).onPreferencesChanged(context) navController.popBackStack() } Box( modifier = Modifier .fillMaxWidth() .padding(top = 8.dp) .padding(horizontal = 16.dp) ) { Button( onClick = { applyOverrides() }, modifier = Modifier .align(Alignment.CenterEnd) .fillMaxWidth(), enabled = columns.value != originalColumns || rows.value != originalRows ) { Text(text = stringResource(id = R.string.apply_grid)) } } } }
gpl-3.0
315192ff1e7417dbb0be1fe051b3ff90
37.045455
97
0.663321
5.072727
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/allapps/SearchResultIconRow.kt
1
4466
package app.lawnchair.allapps import android.content.Context import android.text.TextUtils import android.util.AttributeSet import android.view.View import android.widget.LinearLayout import android.widget.TextView import androidx.core.view.ViewCompat import androidx.core.view.isVisible import app.lawnchair.allapps.SearchResultView.Companion.FLAG_HIDE_SUBTITLE import app.lawnchair.search.SearchTargetCompat import com.android.app.search.LayoutType import com.android.launcher3.R import com.android.launcher3.touch.ItemClickHandler import com.android.launcher3.views.BubbleTextHolder class SearchResultIconRow(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs), SearchResultView, BubbleTextHolder { private var isSmall = false private lateinit var icon: SearchResultIcon private lateinit var title: TextView private lateinit var subtitle: TextView private var delimiter: View? = null private lateinit var shortcutIcons: Array<SearchResultIcon> private var boundId = "" private var flags = 0 override fun onFinishInflate() { super.onFinishInflate() isSmall = id == R.id.search_result_small_icon_row icon = ViewCompat.requireViewById(this, R.id.icon) icon.importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO val iconSize = icon.iconSize icon.layoutParams.apply { width = iconSize height = iconSize } icon.setTextVisibility(false) title = ViewCompat.requireViewById(this, R.id.title) subtitle = ViewCompat.requireViewById(this, R.id.subtitle) subtitle.isVisible = false delimiter = findViewById(R.id.delimiter) setOnClickListener(icon) shortcutIcons = listOf( R.id.shortcut_0, R.id.shortcut_1, R.id.shortcut_2, ) .mapNotNull { findViewById<SearchResultIcon>(it) } .toTypedArray() shortcutIcons.forEach { it.setTextVisibility(false) it.layoutParams.apply { width = icon.iconSize height = icon.iconSize } } } override val isQuickLaunch get() = icon.isQuickLaunch override val titleText get() = icon.titleText override fun launch(): Boolean { ItemClickHandler.INSTANCE.onClick(this) return true } override fun bind(target: SearchTargetCompat, shortcuts: List<SearchTargetCompat>) { if (boundId == target.id) return boundId = target.id flags = getFlags(target.extras) icon.bind(target) { title.text = it.title tag = it } bindShortcuts(shortcuts) var showDelimiter = true if (isSmall) { val textRows = ViewCompat.requireViewById<LinearLayout>(this, R.id.text_rows) if (target.layoutType == LayoutType.HORIZONTAL_MEDIUM_TEXT) { showDelimiter = false layoutParams.height = resources.getDimensionPixelSize(R.dimen.search_result_row_medium_height) textRows.orientation = VERTICAL subtitle.setPadding(0, 0, 0, 0) } else { layoutParams.height = resources.getDimensionPixelSize(R.dimen.search_result_small_row_height) textRows.orientation = HORIZONTAL val subtitleStartPadding = resources.getDimensionPixelSize(R.dimen.search_result_subtitle_padding_start) subtitle.setPaddingRelative(subtitleStartPadding, 0, 0, 0) } } setSubtitleText(target.searchAction?.subtitle, showDelimiter) } private fun setSubtitleText(subtitleText: CharSequence?, showDelimiter: Boolean) { if (TextUtils.isEmpty(subtitleText) || icon.hasFlag(FLAG_HIDE_SUBTITLE)) { subtitle.isVisible = false delimiter?.isVisible = false } else { subtitle.text = subtitleText subtitle.isVisible = true delimiter?.isVisible = showDelimiter } } private fun bindShortcuts(shortcuts: List<SearchTargetCompat>) { shortcutIcons.forEachIndexed { index, icon -> if (index < shortcuts.size) { icon.isVisible = true icon.bind(shortcuts[index], emptyList()) } else { icon.isVisible = false } } } override fun getBubbleText() = icon }
gpl-3.0
a88370c1d51522aabeff8199a9052f7e
35.308943
120
0.649127
4.751064
false
false
false
false
fython/PackageTracker
mobile/src/main/kotlin/info/papdt/express/helper/ui/items/CategoryItemViewBinder.kt
1
1886
package info.papdt.express.helper.ui.items import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.localbroadcastmanager.content.LocalBroadcastManager import info.papdt.express.helper.R import info.papdt.express.helper.event.EventIntents import info.papdt.express.helper.model.Category import info.papdt.express.helper.model.MaterialIcon import info.papdt.express.helper.ui.adapter.ItemViewHolder import me.drakeet.multitype.ItemViewBinder class CategoryItemViewBinder(private val layoutResource: Int) : ItemViewBinder<Category, CategoryItemViewBinder.ViewHolder>() { override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder { return ViewHolder(inflater.inflate(layoutResource, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, item: Category) { holder.bind(item) } class ViewHolder(itemView: View) : ItemViewHolder<Category>(itemView) { private val iconTextView: TextView = itemView.findViewById(R.id.icon_text_view) private val titleView: TextView = itemView.findViewById(R.id.title_view) init { iconTextView.typeface = MaterialIcon.iconTypeface itemView.setOnClickListener { LocalBroadcastManager.getInstance(it.context) .sendBroadcast(EventIntents .notifyItemOnClick(CategoryItemViewBinder::class, item)) } } override fun onBind(item: Category) { if (item.title.isEmpty()) { titleView.setText(R.string.choose_category_dialog_unclassified) iconTextView.text = "" } else { titleView.text = item.title iconTextView.text = item.iconCode } } } }
gpl-3.0
975bcb71c4c828c2b837c2501d4f2f03
34.603774
94
0.69088
4.898701
false
false
false
false
CarrotCodes/Warren
src/main/kotlin/chat/willow/warren/state/ChannelsStateHelper.kt
1
2611
package chat.willow.warren.state import chat.willow.kale.helper.CaseMapping import chat.willow.kale.irc.prefix.Prefix fun generateUsersFromNicks(nicks: List<String>, mappingState: CaseMappingState = CaseMappingState(CaseMapping.RFC1459)): ChannelUsersState { return generateUsersFromPrefixes(prefixes = nicks.map { Prefix(nick = it) }) } fun generateUsersFromPrefixes(prefixes: List<Prefix>, mappingState: CaseMappingState = CaseMappingState(CaseMapping.RFC1459)): ChannelUsersState { val users = ChannelUsersState(mappingState) for (prefix in prefixes) { users += ChannelUserState(prefix) } return users } fun generateUsersWithModes(vararg nicks: Pair<String, Set<Char>>, mappingState: CaseMappingState): ChannelUsersState { val users = ChannelUsersState(mappingState) for ((nick, modes) in nicks) { users += generateUser(nick, modes) } return users } fun generateUser(nick: String, modes: Set<Char>): ChannelUserState { return ChannelUserState(Prefix(nick = nick), modes = modes.toMutableSet()) } fun generateUser(nick: String, account: String? = null, awayMessage: String? = null): ChannelUserState { return ChannelUserState(Prefix(nick = nick), account = account, awayMessage = awayMessage) } fun generateChannelUsersState(vararg users: ChannelUserState, mappingState: CaseMappingState = CaseMappingState(CaseMapping.RFC1459)): ChannelUsersState { val channelUsers = ChannelUsersState(mappingState) for (user in users) { channelUsers += user } return channelUsers } fun emptyChannelsState(mappingState: CaseMappingState): ChannelsState { return ChannelsState(joining = JoiningChannelsState(mappingState), joined = JoinedChannelsState(mappingState)) } fun channelsStateWith(joined: Collection<ChannelState>, mappingState: CaseMappingState): ChannelsState { val joinedChannels = JoinedChannelsState(mappingState) joinedChannels += joined return ChannelsState(joining = JoiningChannelsState(mappingState), joined = joinedChannels) } fun joiningChannelsStateWith(joining: Collection<JoiningChannelState>, mappingState: CaseMappingState): ChannelsState { val joiningChannels = JoiningChannelsState(mappingState) joiningChannels += joining return ChannelsState(joining = joiningChannels, joined = JoinedChannelsState(mappingState)) } fun emptyChannel(name: String, mappingState: CaseMappingState = CaseMappingState(mapping = CaseMapping.RFC1459)): ChannelState { return ChannelState(name = name, users = generateUsersFromNicks(nicks = listOf(), mappingState = mappingState)) }
isc
f1b71f5a2f07757c45dcbd909dc46da3
36.314286
154
0.772118
4.687612
false
false
false
false
edvin/tornadofx-idea-plugin
src/main/kotlin/no/tornado/tornadofx/idea/editors/ViewEditor.kt
1
3454
package no.tornado.tornadofx.idea.editors import com.intellij.codeHighlighting.BackgroundEditorHighlighter import com.intellij.ide.structureView.StructureViewBuilder import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorLocation import com.intellij.openapi.fileEditor.FileEditorState import com.intellij.openapi.fileEditor.FileEditorStateLevel import com.intellij.openapi.project.Project import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.util.PsiTreeUtil import javafx.application.Platform import javafx.embed.swing.JFXPanel import javafx.scene.Scene import javafx.scene.layout.StackPane import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil import org.jetbrains.kotlin.idea.core.util.* import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtClass import java.beans.PropertyChangeListener import javax.swing.JComponent class ViewEditor(val project: Project, val myFile: VirtualFile) : FileEditor { private val panel = JFXPanel() private val wrapper = StackPane() override fun getFile() = myFile init { // val psiFile = file.toPsiFile(project)!! // val ktClass = PsiTreeUtil.findChildOfType(psiFile, KtClass::class.java)!! // val psiFacade = JavaPsiFacade.getInstance(project) Platform.setImplicitExit(false) createHierarchy() panel.scene = Scene(wrapper) } private fun createHierarchy() { val psiFile = file.toPsiFile(project)!! val ktClass = PsiTreeUtil.findChildOfType(psiFile, KtClass::class.java)!! //val psiFacade = JavaPsiFacade.getInstance(project) val root = ktClass.getProperties().find { it.name == "root" } val rootType = QuickFixUtil.getDeclarationReturnType(root)!! println(rootType) for (child in root!!.children) { println("Child: $child") if (child is KtCallExpression) { println("Reference element: " + child.reference?.element?.firstChild) println("Args: " + child.lambdaArguments) } } } override fun <T : Any?> putUserData(key: Key<T>, value: T?) { } override fun <T : Any?> getUserData(key: Key<T>): T? { return null } override fun dispose() { } override fun getName(): String { return "View Editor" } override fun getStructureViewBuilder(): StructureViewBuilder? { return null } override fun setState(state: FileEditorState) { } override fun getComponent(): JComponent { return panel } override fun getPreferredFocusedComponent(): JComponent? { return null } override fun deselectNotify() { } override fun getBackgroundHighlighter(): BackgroundEditorHighlighter? { return null } override fun isValid(): Boolean { return true } override fun isModified(): Boolean { return false } override fun addPropertyChangeListener(listener: PropertyChangeListener) { } override fun getState(level: FileEditorStateLevel): FileEditorState { return FileEditorState { _, _ -> true } } override fun selectNotify() { } override fun getCurrentLocation(): FileEditorLocation? { return null } override fun removePropertyChangeListener(listener: PropertyChangeListener) { } }
apache-2.0
79b428442fbcf205f3c3d341332e0379
28.033613
85
0.694557
4.783934
false
false
false
false
chrisbanes/tivi
ui/popular/src/main/java/app/tivi/home/popular/Popular.kt
1
1553
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.home.popular import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import androidx.hilt.navigation.compose.hiltViewModel import androidx.paging.compose.collectAsLazyPagingItems import app.tivi.common.compose.EntryGrid import app.tivi.common.ui.resources.R as UiR @Composable fun PopularShows( openShowDetails: (showId: Long) -> Unit, navigateUp: () -> Unit ) { PopularShows( viewModel = hiltViewModel(), openShowDetails = openShowDetails, navigateUp = navigateUp ) } @Composable internal fun PopularShows( viewModel: PopularShowsViewModel, openShowDetails: (showId: Long) -> Unit, navigateUp: () -> Unit ) { EntryGrid( lazyPagingItems = viewModel.pagedList.collectAsLazyPagingItems(), title = stringResource(UiR.string.discover_popular_title), onOpenShowDetails = openShowDetails, onNavigateUp = navigateUp ) }
apache-2.0
3a93d32d1ca33e28c7a49a652f94b503
30.06
75
0.732131
4.36236
false
false
false
false
KotlinBy/awesome-kotlin
src/main/kotlin/link/kotlin/scripts/utils/HttpClient.kt
1
2427
package link.kotlin.scripts.utils import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.CancellationException import kotlinx.coroutines.cancelFutureOnCancellation import kotlinx.coroutines.suspendCancellableCoroutine import org.apache.http.HttpResponse import org.apache.http.client.methods.HttpUriRequest import org.apache.http.concurrent.FutureCallback import org.apache.http.impl.cookie.IgnoreSpecProvider import org.apache.http.impl.nio.client.HttpAsyncClients import org.apache.http.nio.client.HttpAsyncClient import kotlin.concurrent.thread interface HttpClient { suspend fun execute(request: HttpUriRequest): HttpResponse companion object } fun HttpResponse.body(): String { return entity.content.reader().readText() } private class DefaultHttpClient( private val client: HttpAsyncClient ) : HttpClient { override suspend fun execute(request: HttpUriRequest): HttpResponse { return client.execute(request) } } private suspend fun HttpAsyncClient.execute(request: HttpUriRequest): HttpResponse { return suspendCancellableCoroutine { cont: CancellableContinuation<HttpResponse> -> val future = this.execute(request, object : FutureCallback<HttpResponse> { override fun completed(result: HttpResponse) { cont.resumeWith(Result.success(result)) } override fun cancelled() { if (cont.isCancelled) return cont.resumeWith(Result.failure(CancellationException("Cancelled"))) } override fun failed(ex: Exception) { cont.resumeWith(Result.failure(ex)) } }) cont.cancelFutureOnCancellation(future) Unit } } fun HttpClient.Companion.default(): HttpClient { val ua = "Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:74.0) Gecko/20100101 Firefox/74.0" val asyncClient = HttpAsyncClients.custom() .setUserAgent(ua) .setMaxConnPerRoute(10) .setMaxConnTotal(100) .setDefaultCookieSpecRegistry { IgnoreSpecProvider() } .build() Runtime.getRuntime().addShutdownHook(thread(start = false) { logger<HttpClient>().info("HttpClient Shutdown called...") asyncClient.close() logger<HttpClient>().info("HttpClient Shutdown done...") }) asyncClient.start() return DefaultHttpClient( client = asyncClient ) }
apache-2.0
c80130ad1f6a476b6d485bb04d4377cb
30.934211
91
0.707046
4.730994
false
false
false
false
herbeth1u/VNDB-Android
app/src/main/java/com/booboot/vndbandroid/dao/RelationDao.kt
1
624
package com.booboot.vndbandroid.dao import com.booboot.vndbandroid.model.vndb.Relation import io.objectbox.annotation.Entity import io.objectbox.annotation.Id @Entity class RelationDao() { @Id(assignable = true) var id: Long = 0 var relation: String = "" var title: String = "" var original: String? = null var official: Boolean = true constructor(item: Relation) : this() { id = item.id relation = item.relation title = item.title original = item.original official = item.official } fun toBo() = Relation(id, relation, title, original, official) }
gpl-3.0
167d3da5fc7107970e3eec201625a133
25.041667
66
0.663462
4
false
false
false
false
jpmoreto/play-with-robots
android/lib/src/main/java/jpm/lib/maps/KDTreeAbs.kt
1
8948
package jpm.lib.maps import jpm.lib.math.Vector2D import jpm.lib.math.nearZero /** * Created by jm on 17/03/17. * * http://www.dcc.fc.up.pt/~pribeiro/aulas/taa1415/rangesearch.pdf */ object KDTreeAbs { enum class SplitAxis(val i: Int) { XAxis(0), YAxis(1) } val dirLabels = arrayOf("T_R", "B_L") val TOP_OR_RIGHT = 0 val BOTTOM_OR_LEFT = 1 val otherChild = arrayOf(1,0) var thresholdPos = 0.9 var thresholdNeg = 1.0 - thresholdPos fun setThreshold(threshold: Double) { thresholdPos = threshold thresholdNeg = 1.0 - threshold } val maxChildren = 2 abstract class Node<T : Node<T, V, N>, V : Vector2D<V, N>, N : Number>(override val center: V, val splitAxis: SplitAxis, val xDim: N, val yDim: N = xDim) : Tree<T, V, N> { override fun visitAll(visit: (node: T) -> Unit) { visit(this as T) for (child in children) child?.visitAll(visit) } override fun visitAllDepthFirst(visit: (node: T) -> Unit) { for (child in children) child?.visitAll(visit) visit(this as T) } override fun size(): Int { var s = 1 for (child in children) { if (child != null) s += child.size() } return s } override fun occupied(p: V): Double = getPoint(p).occupied() override fun free(p: V): Double = getPoint(p).free() override fun free(): Double = 1.0 - occupied() internal var samplesPositive = 0 internal var samplesNegative = 0 override var isLeaf = true protected fun setOccupied() { if (samplesPositive < Int.MAX_VALUE) ++samplesPositive else if (samplesNegative > 0) --samplesNegative } protected fun setFree() { if (samplesNegative < Int.MAX_VALUE) ++samplesNegative else if (samplesPositive > 0) --samplesPositive } protected fun meanOccupied(): Double { var occupied = 0.0 var count = 0.0 for (child in children) { if (child != null) { occupied += child.occupied() count += 1.0 } } if (count == 0.0) return 0.5 else return (occupied + 0.5 * (maxChildren - count)) / maxChildren } override fun occupied(): Double { if (isLeaf) { if (samplesPositive > samplesNegative) return samplesPositive / (samplesPositive.toDouble() + samplesNegative) else if (samplesPositive < samplesNegative) return 1.0 - samplesNegative / (samplesPositive.toDouble() + samplesNegative) else return 0.5 } return meanOccupied() } protected fun tryDeleteChild() { if(nearZero(children[0]!!.occupied() - 0.5, 1E-10) && nearZero(children[1]!!.occupied() - 0.5, 1E-10)) { isLeaf = true samplesNegative = 0 samplesPositive = 0 } } protected fun tryMergeChildren() { fun deleteAllChildren() { children[0] = null children[1] = null isLeaf = true } var numberOfOccupied = 0 var numberOfFree = 0 for (child in children) { if (child!!.isLeaf) { if (child.occupied() >= thresholdPos) ++numberOfOccupied if (child.free() >= thresholdPos) ++numberOfFree } else break } if (numberOfOccupied == maxChildren || numberOfFree == maxChildren) { var positives = 0 var negatives = 0 for (child in children) { var toSubtractNeg = 0 var toSubtractPos = 0 if (positives < Int.MAX_VALUE - child!!.samplesPositive) { positives += child.samplesPositive } else { toSubtractNeg = child.samplesPositive + (positives - Int.MAX_VALUE) positives = Int.MAX_VALUE } if (negatives < Int.MAX_VALUE - child.samplesNegative) { negatives += child.samplesNegative } else { toSubtractPos = child.samplesNegative + (negatives - Int.MAX_VALUE) negatives = Int.MAX_VALUE } negatives -= toSubtractNeg if (negatives < 0) negatives = 0 positives -= toSubtractPos if (positives < 0) positives = 0 } samplesPositive = positives samplesNegative = negatives deleteAllChildren() } } override fun setFree(p: V) { if (canSplit()) { if (samplesPositive > 0 || samplesNegative > 0) { if (samplesPositive < samplesNegative) { setFree() } else { getOrCreateChild(p).setFree(p) split() } } else { val child = getOrCreateChild(p) child.setFree(p) tryMergeChildren() if (child.isLeaf && nearZero(child.occupied() - 0.5, 1E-10)) tryDeleteChild() } } else setFree() } override fun setOccupied(p: V) { if (canSplit()) { if (samplesPositive > 0 || samplesNegative > 0) { if (samplesPositive > samplesNegative) { setOccupied() } else { getOrCreateChild(p).setOccupied(p) split() } } else { val child = getOrCreateChild(p) child.setOccupied(p) if (child.isLeaf) { tryMergeChildren() if(nearZero(child.occupied() - 0.5, 1E-10)) tryDeleteChild() } } } else setOccupied() } fun setOccupied(x: N, y: N) { if (canSplit()) { if (samplesPositive > 0 || samplesNegative > 0) { if (samplesPositive > samplesNegative) { setOccupied() } else { getOrCreateChild(x,y).setOccupied(x,y) split() } } else { val child = getOrCreateChild(x,y) child.setOccupied(x,y) if (child.isLeaf) { tryMergeChildren() if(nearZero(child.occupied() - 0.5, 1E-10)) tryDeleteChild() } } } else setOccupied() } protected abstract fun getOrCreateChild(p: V): T protected abstract fun getOrCreateChild(x: N, y: N): T protected abstract fun canSplit(): Boolean protected abstract fun split() abstract val children: Array<T?> protected abstract val halfDim: N override fun toString(): String = toString("") private fun toString(spacing: String): String { fun toStringChild(pos: Int, s: String): String { if (children[pos] != null) return "\n$s${dirLabels[pos]} -> " + children[pos]!!.toString(s + " ") return "" } var res = "Node($center,$splitAxis,$xDim,$yDim,$samplesPositive,$samplesNegative,$isLeaf, ${occupied()})" if (isLeaf) return res res += toStringChild(TOP_OR_RIGHT, spacing + " ") res += toStringChild(BOTTOM_OR_LEFT, spacing + " ") return res } override fun toStringLeaf(): String { fun toStringChild(pos: Int): String { if (children[pos] != null) return children[pos]!!.toStringLeaf() else return "" } if (isLeaf) return "\nNode($center,$splitAxis,$xDim,$yDim,$samplesPositive,$samplesNegative,$isLeaf, ${occupied()})" return toStringChild(TOP_OR_RIGHT) + toStringChild(BOTTOM_OR_LEFT) } override fun toStringNode(): String = "Node($center,$splitAxis,$xDim,$yDim,$samplesPositive,$samplesNegative,$isLeaf, ${occupied()})" } }
mit
fdaf06cbdd92bc9d9f2db5bd677699fb
31.900735
175
0.471055
4.772267
false
false
false
false
alashow/music-android
modules/base/src/main/java/tm/alashow/base/util/extensions/CollectionExtensions.kt
1
875
/* * Copyright (C) 2019, Alashov Berkeli * All rights reserved. */ package tm.alashow.base.util.extensions import java.util.* fun <K, V> Map<K, V>.findKeys(target: V) = filterValues { it == target }.keys fun <K, V> Map<K, V>.findFirstKey(target: V) = findKeys(target).first() fun <K, V> Map<K, Set<V>>.getOrEmpty(key: K) = getOrElse(key, { emptySet() }) inline fun <T> Iterable<T>.sumByFloat(selector: (T) -> Float): Float { var sum = 0.0f for (element in this) { sum += selector(element) } return sum } fun <T> List<T>.toStack() = Stack<T>().also { stack -> forEach { stack.push(it) } } fun <T> Stack<T>.popOrNull() = when (isEmpty()) { true -> null else -> pop() } fun <T> List<T>.swap(from: Int, to: Int): List<T> { val new = toMutableList() val element = new.removeAt(from) new.add(to, element) return new }
apache-2.0
14f099c8155caa4cfa2dfbfc3c79651c
22.648649
77
0.604571
2.906977
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/AbstractFlashcardViewer.kt
1
109335
/**************************************************************************************** * Copyright (c) 2011 Kostas Spyropoulos <[email protected]> * * Copyright (c) 2014 Bruno Romero de Azevedo <[email protected]> * * Copyright (c) 2014–15 Roland Sieker <[email protected]> * * Copyright (c) 2015 Timothy Rae <[email protected]> * * Copyright (c) 2016 Mark Carter <[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/>. * ****************************************************************************************/ // TODO: implement own menu? http://www.codeproject.com/Articles/173121/Android-Menus-My-Way package com.ichi2.anki import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.* import android.content.res.Configuration import android.content.res.Resources import android.graphics.Color import android.media.MediaPlayer import android.net.Uri import android.os.* import android.text.TextUtils import android.view.* import android.view.GestureDetector.SimpleOnGestureListener import android.view.View.OnTouchListener import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputMethodManager import android.webkit.* import android.webkit.WebView.HitTestResult import android.widget.* import androidx.annotation.CheckResult import androidx.annotation.IdRes import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting import androidx.core.view.isVisible import androidx.webkit.WebViewAssetLoader import anki.collection.OpChanges import com.afollestad.materialdialogs.MaterialDialog import com.drakeet.drawer.FullDraggableContainer import com.google.android.material.snackbar.Snackbar import com.ichi2.anim.ActivityTransitionAnimation import com.ichi2.anim.ActivityTransitionAnimation.getInverseTransition import com.ichi2.anki.CollectionManager.withCol import com.ichi2.anki.UIUtils.showThemedToast import com.ichi2.anki.cardviewer.* import com.ichi2.anki.cardviewer.CardHtml.Companion.legacyGetTtsTags import com.ichi2.anki.cardviewer.HtmlGenerator.Companion.createInstance import com.ichi2.anki.cardviewer.SoundPlayer.CardSoundConfig import com.ichi2.anki.cardviewer.SoundPlayer.CardSoundConfig.Companion.create import com.ichi2.anki.cardviewer.TypeAnswer.Companion.createInstance import com.ichi2.anki.dialogs.tags.TagsDialog import com.ichi2.anki.dialogs.tags.TagsDialogFactory import com.ichi2.anki.dialogs.tags.TagsDialogListener import com.ichi2.anki.receiver.SdCardReceiver import com.ichi2.anki.reviewer.* import com.ichi2.anki.reviewer.AutomaticAnswer.AutomaticallyAnswered import com.ichi2.anki.reviewer.FullScreenMode.Companion.DEFAULT import com.ichi2.anki.reviewer.FullScreenMode.Companion.fromPreference import com.ichi2.anki.reviewer.ReviewerUi.ControlBlock import com.ichi2.anki.servicelayer.AnkiMethod import com.ichi2.anki.servicelayer.LanguageHintService.applyLanguageHint import com.ichi2.anki.servicelayer.NoteService.isMarked import com.ichi2.anki.servicelayer.SchedulerService.* import com.ichi2.anki.servicelayer.TaskListenerBuilder import com.ichi2.anki.servicelayer.Undo import com.ichi2.anki.snackbar.SnackbarBuilder import com.ichi2.anki.snackbar.showSnackbar import com.ichi2.annotations.NeedsTest import com.ichi2.async.TaskListener import com.ichi2.async.updateCard import com.ichi2.compat.CompatHelper.Companion.compat import com.ichi2.libanki.* import com.ichi2.libanki.Collection import com.ichi2.libanki.Consts.BUTTON_TYPE import com.ichi2.libanki.Sound.SoundSide import com.ichi2.libanki.sched.AbstractSched import com.ichi2.libanki.sched.SchedV2 import com.ichi2.themes.Themes import com.ichi2.themes.Themes.getResFromAttr import com.ichi2.ui.FixedEditText import com.ichi2.utils.AdaptionUtil.hasWebBrowser import com.ichi2.utils.AndroidUiUtils.isRunningOnTv import com.ichi2.utils.AssetHelper.guessMimeType import com.ichi2.utils.BlocksSchemaUpgrade import com.ichi2.utils.ClipboardUtil.getText import com.ichi2.utils.Computation import com.ichi2.utils.HandlerUtils.executeFunctionWithDelay import com.ichi2.utils.HandlerUtils.newHandler import com.ichi2.utils.HashUtil.HashSetInit import com.ichi2.utils.KotlinCleanup import com.ichi2.utils.WebViewDebugging.initializeDebugging import com.ichi2.utils.iconAttr import kotlinx.coroutines.Job import net.ankiweb.rsdroid.BackendFactory import net.ankiweb.rsdroid.RustCleanup import timber.log.Timber import java.io.* import java.lang.ref.WeakReference import java.net.URLDecoder import java.util.* import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReadWriteLock import java.util.concurrent.locks.ReentrantReadWriteLock import java.util.function.Consumer import java.util.function.Function import java.util.function.Supplier import kotlin.math.abs @KotlinCleanup("lots to deal with") abstract class AbstractFlashcardViewer : NavigationDrawerActivity(), ReviewerUi, ViewerCommand.CommandProcessor, TagsDialogListener, WhiteboardMultiTouchMethods, AutomaticallyAnswered, OnPageFinishedCallback, ChangeManager.Subscriber { private var mTtsInitialized = false private var mReplayOnTtsInit = false private var mAnkiDroidJsAPI: AnkiDroidJsAPI? = null /** * Broadcast that informs us when the sd card is about to be unmounted */ private var mUnmountReceiver: BroadcastReceiver? = null private var mTagsDialogFactory: TagsDialogFactory? = null /** * Variables to hold preferences */ @KotlinCleanup("internal for AnkiDroidJsApi") internal var prefShowTopbar = false protected var fullscreenMode = DEFAULT private set private var mRelativeButtonSize = 0 private var mDoubleScrolling = false private var mScrollingButtons = false private var mGesturesEnabled = false private var mLargeAnswerButtons = false private var mAnswerButtonsPosition: String? = "bottom" private var mDoubleTapTimeInterval = DEFAULT_DOUBLE_TAP_TIME_INTERVAL // Android WebView var automaticAnswer = AutomaticAnswer.defaultInstance(this) protected var typeAnswer: TypeAnswer? = null /** Generates HTML content */ private var mHtmlGenerator: HtmlGenerator? = null // Default short animation duration, provided by Android framework private var shortAnimDuration = 0 private var mBackButtonPressedToReturn = false // Preferences from the collection private var mShowNextReviewTime = false private var mIsSelecting = false private var mTouchStarted = false private var mInAnswer = false private var mAnswerSoundsAdded = false /** * Variables to hold layout objects that we need to update or handle events for */ var webView: WebView? = null private set private var mCardFrame: FrameLayout? = null private var mTouchLayer: FrameLayout? = null protected var answerField: FixedEditText? = null protected var flipCardLayout: LinearLayout? = null private var easeButtonsLayout: LinearLayout? = null @KotlinCleanup("internal for AnkiDroidJsApi") internal var easeButton1: EaseButton? = null @KotlinCleanup("internal for AnkiDroidJsApi") internal var easeButton2: EaseButton? = null @KotlinCleanup("internal for AnkiDroidJsApi") internal var easeButton3: EaseButton? = null @KotlinCleanup("internal for AnkiDroidJsApi") internal var easeButton4: EaseButton? = null protected var topBarLayout: RelativeLayout? = null private val mClipboard: ClipboardManager? = null private var mPreviousAnswerIndicator: PreviousAnswerIndicator? = null /** set when [currentCard] is */ private var mCardSoundConfig: CardSoundConfig? = null private var mCurrentEase = 0 private var mInitialFlipCardHeight = 0 private var mButtonHeightSet = false /** * A record of the last time the "show answer" or ease buttons were pressed. We keep track * of this time to ignore accidental button presses. */ @VisibleForTesting protected var lastClickTime: Long = 0 /** * Swipe Detection */ var gestureDetector: GestureDetector? = null private set private lateinit var mGestureDetectorImpl: MyGestureDetector private var mIsXScrolling = false private var mIsYScrolling = false /** * Gesture Allocation */ protected val mGestureProcessor = GestureProcessor(this) @get:VisibleForTesting var cardContent: String? = null private set private var mBaseUrl: String? = null private var mViewerUrl: String? = null private var mAssetLoader: WebViewAssetLoader? = null private val mFadeDuration = 300 @KotlinCleanup("made internal for tests") @VisibleForTesting(otherwise = VisibleForTesting.PROTECTED) internal var sched: AbstractSched? = null protected val mSoundPlayer = Sound() /** * Time taken to play all medias in mSoundPlayer * This is 0 if we have "Read card" enabled, as we can't calculate the duration. */ private var mUseTimerDynamicMS: Long = 0 /** Reference to the parent of the cardFrame to allow regeneration of the cardFrame in case of crash */ private var mCardFrameParent: ViewGroup? = null /** Lock to allow thread-safe regeneration of mCard */ private val mCardLock: ReadWriteLock = ReentrantReadWriteLock() /** whether controls are currently blocked, and how long we expect them to be */ override var controlBlocked = ControlBlock.SLOW /** Preference: Whether the user wants press back twice to return to the main screen" */ private var mExitViaDoubleTapBack = false @VisibleForTesting val mOnRenderProcessGoneDelegate = OnRenderProcessGoneDelegate(this) protected val mTTS = TTS() // ---------------------------------------------------------------------------- // LISTENERS // ---------------------------------------------------------------------------- private val mLongClickHandler = newHandler() private val mLongClickTestRunnable = Runnable { Timber.i("AbstractFlashcardViewer:: onEmulatedLongClick") compat.vibrate(AnkiDroidApp.instance.applicationContext, 50) mLongClickHandler.postDelayed(mStartLongClickAction, 300) } private val mStartLongClickAction = Runnable { mGestureProcessor.onLongTap() } // Handler for the "show answer" button private val mFlipCardListener = View.OnClickListener { Timber.i("AbstractFlashcardViewer:: Show answer button pressed") // Ignore what is most likely an accidental double-tap. if (elapsedRealTime - lastClickTime < mDoubleTapTimeInterval) { return@OnClickListener } lastClickTime = elapsedRealTime automaticAnswer.onShowAnswer() displayCardAnswer() } init { ChangeManager.subscribe(this) } // Event handler for eases (answer buttons) inner class SelectEaseHandler : View.OnClickListener, OnTouchListener { private var mPrevCard: Card? = null private var mHasBeenTouched = false private var mTouchX = 0f private var mTouchY = 0f override fun onTouch(view: View, event: MotionEvent): Boolean { if (event.action == MotionEvent.ACTION_DOWN) { // Save states when button pressed mPrevCard = currentCard mHasBeenTouched = true // We will need to check if a touch is followed by a click // Since onTouch always come before onClick, we should check if // the touch is going to be a click by storing the start coordinates // and comparing with the end coordinates of the touch mTouchX = event.rawX mTouchY = event.rawY } else if (event.action == MotionEvent.ACTION_UP) { val diffX = abs(event.rawX - mTouchX) val diffY = abs(event.rawY - mTouchY) // If a click is not coming then we reset the touch if (diffX > Companion.CLICK_ACTION_THRESHOLD || diffY > Companion.CLICK_ACTION_THRESHOLD) { mHasBeenTouched = false } } return false } override fun onClick(view: View) { // Try to perform intended action only if the button has been pressed for current card, // or if the button was not touched, if (mPrevCard === currentCard || !mHasBeenTouched) { // Only perform if the click was not an accidental double-tap if (elapsedRealTime - lastClickTime >= mDoubleTapTimeInterval) { // For whatever reason, performClick does not return a visual feedback anymore if (!mHasBeenTouched) { view.isPressed = true } lastClickTime = elapsedRealTime automaticAnswer.onSelectEase() when (view.id) { R.id.flashcard_layout_ease1 -> { Timber.i("AbstractFlashcardViewer:: EASE_1 pressed") answerCard(Consts.BUTTON_ONE) } R.id.flashcard_layout_ease2 -> { Timber.i("AbstractFlashcardViewer:: EASE_2 pressed") answerCard(Consts.BUTTON_TWO) } R.id.flashcard_layout_ease3 -> { Timber.i("AbstractFlashcardViewer:: EASE_3 pressed") answerCard(Consts.BUTTON_THREE) } R.id.flashcard_layout_ease4 -> { Timber.i("AbstractFlashcardViewer:: EASE_4 pressed") answerCard(Consts.BUTTON_FOUR) } else -> mCurrentEase = 0 } if (!mHasBeenTouched) { view.isPressed = false } } } // We will have to reset the touch after every onClick event // Do not return early without considering this mHasBeenTouched = false } } private val mEaseHandler = SelectEaseHandler() @get:VisibleForTesting protected open val elapsedRealTime: Long get() = SystemClock.elapsedRealtime() private val mGestureListener = OnTouchListener { _, event -> if (gestureDetector!!.onTouchEvent(event)) { return@OnTouchListener true } if (!mGestureDetectorImpl.eventCanBeSentToWebView(event)) { return@OnTouchListener false } // Gesture listener is added before mCard is set processCardAction { cardWebView: WebView? -> if (cardWebView == null) return@processCardAction cardWebView.dispatchTouchEvent(event) } false } // This is intentionally package-private as it removes the need for synthetic accessors @SuppressLint("CheckResult") fun processCardAction(cardConsumer: Consumer<WebView?>) { processCardFunction { cardWebView: WebView? -> cardConsumer.accept(cardWebView) true } } @CheckResult private fun <T> processCardFunction(cardFunction: Function<WebView?, T>): T { val readLock = mCardLock.readLock() return try { readLock.lock() cardFunction.apply(webView) } finally { readLock.unlock() } } suspend fun saveEditedCard() { val updatedCard: Card = withProgress { withCol { updateCard(this, editorCard!!, true, canAccessScheduler()) } } onCardUpdated(updatedCard) } private fun onCardUpdated(result: Card) { if (currentCard !== result) { /* * Before updating currentCard, we check whether it is changing or not. If the current card changes, * then we need to display it as a new card, without showing the answer. */ displayAnswer = false } currentCard = result launchCatchingTask { withCol { sched.counts() // Ensure counts are recomputed if necessary, to know queue to look for sched.preloadNextCard() } } if (currentCard == null) { // If the card is null means that there are no more cards scheduled for review. showProgressBar() closeReviewer(RESULT_NO_MORE_CARDS, true) } onCardEdited(currentCard!!) if (displayAnswer) { mSoundPlayer.resetSounds() // load sounds from scratch, to expose any edit changes mAnswerSoundsAdded = false // causes answer sounds to be reloaded generateQuestionSoundList() // questions must be intentionally regenerated displayCardAnswer() } else { displayCardQuestion() } hideProgressBar() } /** Operation after a card has been updated due to being edited. Called before display[Question/Answer] */ protected open fun onCardEdited(card: Card) { // intentionally blank } /** Invoked by [CardViewerWebClient.onPageFinished] */ override fun onPageFinished() { // intentionally blank } internal inner class NextCardHandler<Result : Computation<NextCard<*>>?> : TaskListener<Unit, Result>() { override fun onPreExecute() { dealWithTimeBox() } private fun dealWithTimeBox() { val elapsed = col.timeboxReached() if (elapsed != null) { val nCards = elapsed.second val nMins = elapsed.first / 60 val mins = resources.getQuantityString(R.plurals.in_minutes, nMins, nMins) val timeboxMessage = resources.getQuantityString(R.plurals.timebox_reached, nCards, nCards, mins) MaterialDialog(this@AbstractFlashcardViewer).show { title(R.string.timebox_reached_title) message(text = timeboxMessage) positiveButton(R.string.dialog_continue) { col.startTimebox() } negativeButton(R.string.close) { finishWithAnimation(ActivityTransitionAnimation.Direction.END) } cancelable(true) setOnCancelListener { col.startTimebox() } } } } override fun onPostExecute(result: Result) { if (sched == null) { // TODO: proper testing for restored activity finishWithoutAnimation() return } val displaySuccess = result!!.succeeded() if (!displaySuccess) { // RuntimeException occurred on answering cards closeReviewer(DeckPicker.RESULT_DB_ERROR, false) return } val nextCardAndResult = result.value if (nextCardAndResult.hasNoMoreCards()) { closeReviewer(RESULT_NO_MORE_CARDS, true) // When launched with a shortcut, we want to display a message when finishing if (intent.getBooleanExtra(EXTRA_STARTED_WITH_SHORTCUT, false)) { showThemedToast(baseContext, R.string.studyoptions_congrats_finished, false) } return } currentCard = nextCardAndResult.nextScheduledCard() // Start reviewing next card hideProgressBar() unblockControls() [email protected]() // set the correct mark/unmark icon on action bar refreshActionBar() focusDefaultLayout() } } private fun focusDefaultLayout() { if (!isRunningOnTv(this)) { findViewById<View>(R.id.root_layout).requestFocus() } else { val flip = findViewById<View>(R.id.answer_options_layout) ?: return Timber.d("Requesting focus for flip button") flip.requestFocus() } } protected fun answerCardHandler(quick: Boolean): TaskListenerBuilder<Unit, Computation<NextCard<*>>?> { return nextCardHandler<Computation<NextCard<*>>?>() .alsoExecuteBefore { blockControls(quick) } } open val answerButtonCount: Int get() = col.sched.answerButtons(currentCard!!) // ---------------------------------------------------------------------------- // ANDROID METHODS // ---------------------------------------------------------------------------- override fun onCreate(savedInstanceState: Bundle?) { Timber.d("onCreate()") restorePreferences() mTagsDialogFactory = TagsDialogFactory(this).attachToActivity<TagsDialogFactory>(this) super.onCreate(savedInstanceState) setContentView(getContentViewAttr(fullscreenMode)) // Make ACTION_PROCESS_TEXT for in-app searching possible on > Android 4.0 delegate.isHandleNativeActionModesEnabled = true val mainView = findViewById<View>(android.R.id.content) initNavigationDrawer(mainView) mPreviousAnswerIndicator = PreviousAnswerIndicator(findViewById(R.id.chosen_answer)) shortAnimDuration = resources.getInteger(android.R.integer.config_shortAnimTime) mGestureDetectorImpl = LinkDetectingGestureDetector() } protected open fun getContentViewAttr(fullscreenMode: FullScreenMode): Int { return R.layout.reviewer } @get:VisibleForTesting(otherwise = VisibleForTesting.PROTECTED) val isFullscreen: Boolean get() = !supportActionBar!!.isShowing override fun onConfigurationChanged(newConfig: Configuration) { // called when screen rotated, etc, since recreating the Webview is too expensive super.onConfigurationChanged(newConfig) refreshActionBar() } protected abstract fun setTitle() // Finish initializing the activity after the collection has been correctly loaded public override fun onCollectionLoaded(col: Collection) { super.onCollectionLoaded(col) sched = col.sched val mediaDir = col.media.dir() mBaseUrl = Utils.getBaseUrl(mediaDir) mViewerUrl = mBaseUrl + "__viewer__.html" mAssetLoader = WebViewAssetLoader.Builder() .addPathHandler("/") { path: String -> try { val file = File(mediaDir, path) val inputStream = FileInputStream(file) val mimeType = guessMimeType(path) val headers = HashMap<String, String>() headers["Access-Control-Allow-Origin"] = "*" val response = WebResourceResponse(mimeType, null, inputStream) response.responseHeaders = headers return@addPathHandler response } catch (e: Exception) { Timber.w(e, "Error trying to open path in asset loader") } null } .build() registerExternalStorageListener() restoreCollectionPreferences(col) initLayout() setTitle() mHtmlGenerator = createInstance(this, typeAnswer!!, mBaseUrl!!) // Initialize text-to-speech. This is an asynchronous operation. mTTS.initialize(this, ReadTextListener()) updateActionBar() invalidateOptionsMenu() } // Saves deck each time Reviewer activity loses focus override fun onPause() { super.onPause() Timber.d("onPause()") automaticAnswer.disable() mLongClickHandler.removeCallbacks(mLongClickTestRunnable) mLongClickHandler.removeCallbacks(mStartLongClickAction) mSoundPlayer.stopSounds() // Prevent loss of data in Cookies CookieManager.getInstance().flush() } override fun onResume() { super.onResume() // Set the context for the Sound manager mSoundPlayer.setContext(WeakReference(this)) automaticAnswer.enable() // Reset the activity title setTitle() updateActionBar() selectNavigationItem(-1) } override fun onDestroy() { super.onDestroy() // Tells the scheduler there is no more current cards. 0 is // not a valid id. if (sched != null && sched is SchedV2) { (sched!! as SchedV2).discardCurrentCard() } Timber.d("onDestroy()") mTTS.releaseTts(this) if (mUnmountReceiver != null) { unregisterReceiver(mUnmountReceiver) } // WebView.destroy() should be called after the end of use // http://developer.android.com/reference/android/webkit/WebView.html#destroy() if (mCardFrame != null) { mCardFrame!!.removeAllViews() } destroyWebView(webView) // OK to do without a lock } override fun onBackPressed() { if (isDrawerOpen) { super.onBackPressed() } else { Timber.i("Back key pressed") if (!mExitViaDoubleTapBack || mBackButtonPressedToReturn) { closeReviewer(RESULT_DEFAULT, false) } else { showSnackbar(R.string.back_pressed_once_reviewer, Snackbar.LENGTH_SHORT) } mBackButtonPressedToReturn = true executeFunctionWithDelay(Consts.SHORT_TOAST_DURATION) { mBackButtonPressedToReturn = false } } } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { return if (processCardFunction { cardWebView: WebView? -> processHardwareButtonScroll(keyCode, cardWebView) }) { true } else super.onKeyDown(keyCode, event) } public override val currentCardId: CardId? get() = currentCard?.id private fun processHardwareButtonScroll(keyCode: Int, card: WebView?): Boolean { if (keyCode == KeyEvent.KEYCODE_PAGE_UP) { card!!.pageUp(false) if (mDoubleScrolling) { card.pageUp(false) } return true } if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) { card!!.pageDown(false) if (mDoubleScrolling) { card.pageDown(false) } return true } if (mScrollingButtons && keyCode == KeyEvent.KEYCODE_PICTSYMBOLS) { card!!.pageUp(false) if (mDoubleScrolling) { card.pageUp(false) } return true } if (mScrollingButtons && keyCode == KeyEvent.KEYCODE_SWITCH_CHARSET) { card!!.pageDown(false) if (mDoubleScrolling) { card.pageDown(false) } return true } return false } override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean { if (answerFieldIsFocused()) { return super.onKeyUp(keyCode, event) } if (!displayAnswer) { if (keyCode == KeyEvent.KEYCODE_SPACE || keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) { displayCardAnswer() return true } } return super.onKeyUp(keyCode, event) } protected open fun answerFieldIsFocused(): Boolean { return answerField != null && answerField!!.isFocused } protected fun clipboardHasText(): Boolean { return !TextUtils.isEmpty(getText(mClipboard)) } /** * Returns the text stored in the clipboard or the empty string if the clipboard is empty or contains something that * cannot be converted to text. * * @return the text in clipboard or the empty string. */ private fun clipboardGetText(): CharSequence { val text = getText(mClipboard) return text ?: "" } @Suppress("deprecation") // super.onActivityResult public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == DeckPicker.RESULT_DB_ERROR) { closeReviewer(DeckPicker.RESULT_DB_ERROR, false) } if (resultCode == DeckPicker.RESULT_MEDIA_EJECTED) { finishNoStorageAvailable() } /* Reset the schedule and reload the latest card off the top of the stack if required. The card could have been rescheduled, the deck could have changed, or a change of note type could have lead to the card being deleted */ val reloadRequired = data?.getBooleanExtra("reloadRequired", false) == true if (reloadRequired) { performReload() } if (requestCode == EDIT_CURRENT_CARD) { if (resultCode == RESULT_OK) { // content of note was changed so update the note and current card Timber.i("AbstractFlashcardViewer:: Saving card...") launchCatchingTask { saveEditedCard() } onEditedNoteChanged() } else if (resultCode == RESULT_CANCELED && !reloadRequired) { // nothing was changed by the note editor so just redraw the card redrawCard() } } else if (requestCode == DECK_OPTIONS && resultCode == RESULT_OK) { performReload() } } /** * Whether the class should use collection.getSched() when performing tasks. * The aim of this method is to completely distinguish FlashcardViewer from Reviewer * * This is partially implemented, the end goal is that the FlashcardViewer will not have any coupling to getSched * * Currently, this is used for note edits - in a reviewing context, this should show the next card. * In a previewing context, the card should not change. */ open fun canAccessScheduler(): Boolean { return false } protected open fun onEditedNoteChanged() {} /** An action which may invalidate the current list of cards has been performed */ protected abstract fun performReload() // ---------------------------------------------------------------------------- // CUSTOM METHODS // ---------------------------------------------------------------------------- // Get the did of the parent deck (ignoring any subdecks) protected val parentDid: DeckId get() = col.decks.selected() private fun redrawCard() { // #3654 We can call this from ActivityResult, which could mean that the card content hasn't yet been set // if the activity was destroyed. In this case, just wait until onCollectionLoaded callback succeeds. if (hasLoadedCardContent()) { fillFlashcard() } else { Timber.i("Skipping card redraw - card still initialising.") } } /** Whether the callback to onCollectionLoaded has loaded card content */ private fun hasLoadedCardContent(): Boolean { return cardContent != null } /** * Show/dismiss dialog when sd card is ejected/remounted (collection is saved by SdCardReceiver) */ private fun registerExternalStorageListener() { if (mUnmountReceiver == null) { mUnmountReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == SdCardReceiver.MEDIA_EJECT) { finishWithoutAnimation() } } } val iFilter = IntentFilter() iFilter.addAction(SdCardReceiver.MEDIA_EJECT) registerReceiver(mUnmountReceiver, iFilter) } } open fun undo(): Job? { if (isUndoAvailable) { val undoneAction = col.undoName(resources) val message = getString(R.string.undo_succeeded, undoneAction) fun legacyUndo() { Undo().runWithHandler( answerCardHandler(false) .alsoExecuteAfter { showSnackbarAboveAnswerButtons(message, Snackbar.LENGTH_SHORT) } ) } if (BackendFactory.defaultLegacySchema) { legacyUndo() } else { return launchCatchingTask { if (!backendUndoAndShowPopup(findViewById(R.id.flip_card))) { legacyUndo() } } } } return null } private fun finishNoStorageAvailable() { [email protected](DeckPicker.RESULT_MEDIA_EJECTED) finishWithoutAnimation() } @NeedsTest("Starting animation from swipe is inverse to the finishing one") protected open fun editCard(fromGesture: Gesture? = null) { if (currentCard == null) { // This should never occurs. It means the review button was pressed while there is no more card in the reviewer. return } val editCard = Intent(this@AbstractFlashcardViewer, NoteEditor::class.java) val animation = getAnimationTransitionFromGesture(fromGesture) editCard.putExtra(NoteEditor.EXTRA_CALLER, NoteEditor.CALLER_REVIEWER_EDIT) editCard.putExtra(FINISH_ANIMATION_EXTRA, getInverseTransition(animation) as Parcelable) editorCard = currentCard startActivityForResultWithAnimation(editCard, EDIT_CURRENT_CARD, animation) } fun generateQuestionSoundList() { val tags = Sound.extractTagsFromLegacyContent(currentCard!!.qSimple()) mSoundPlayer.addSounds(mBaseUrl!!, tags, SoundSide.QUESTION) } protected fun showDeleteNoteDialog() { MaterialDialog(this).show { title(R.string.delete_card_title) iconAttr(R.attr.dialogErrorIcon) message( text = resources.getString( R.string.delete_note_message, Utils.stripHTML(currentCard!!.q(true)) ) ) positiveButton(R.string.dialog_positive_delete) { Timber.i( "AbstractFlashcardViewer:: OK button pressed to delete note %d", currentCard!!.nid ) mSoundPlayer.stopSounds() deleteNoteWithoutConfirmation() } negativeButton(R.string.dialog_cancel) } } /** Consumers should use [.showDeleteNoteDialog] */ private fun deleteNoteWithoutConfirmation() { dismiss(DeleteNote(currentCard!!)) { showSnackbarWithUndoButton(R.string.deleted_note) } } private fun showSnackbarWithUndoButton( @StringRes textResource: Int, duration: Int = Snackbar.LENGTH_SHORT ) { showSnackbarAboveAnswerButtons(textResource, duration) { setAction(R.string.undo) { undo() } } } private fun getRecommendedEase(easy: Boolean): Int { return try { when (answerButtonCount) { 2 -> EASE_2 3 -> if (easy) EASE_3 else EASE_2 4 -> if (easy) EASE_4 else EASE_3 else -> 0 } } catch (e: RuntimeException) { CrashReportService.sendExceptionReport(e, "AbstractReviewer-getRecommendedEase") closeReviewer(DeckPicker.RESULT_DB_ERROR, true) 0 } } open fun answerCard(@BUTTON_TYPE ease: Int) { launchCatchingTask { if (mInAnswer) { return@launchCatchingTask } mIsSelecting = false val buttonNumber = col.sched.answerButtons(currentCard!!) // Detect invalid ease for current card (e.g. by using keyboard shortcut or gesture). if (buttonNumber < ease) { return@launchCatchingTask } // Temporarily sets the answer indicator dots appearing below the toolbar mPreviousAnswerIndicator!!.displayAnswerIndicator(ease, buttonNumber) mSoundPlayer.stopSounds() mCurrentEase = ease val oldCard = currentCard!! val newCard = withCol { Timber.i("Answering card %d", oldCard.id) col.sched.answerCard(oldCard, ease) Timber.i("Obtaining next card") sched.card?.apply { render_output(reload = true) } } // TODO: this handling code is unnecessarily complex, and would be easier to follow // if written imperatively val handler = answerCardHandler(true) handler.before?.run() handler.after?.accept(Computation.ok(NextCard.withNoResult(newCard))) } } // Set the content view to the one provided and initialize accessors. @KotlinCleanup("Move a lot of these to onCreate()") protected open fun initLayout() { topBarLayout = findViewById(R.id.top_bar) mCardFrame = findViewById(R.id.flashcard) mCardFrameParent = mCardFrame!!.parent as ViewGroup mTouchLayer = findViewById<FrameLayout>(R.id.touch_layer).apply { setOnTouchListener(mGestureListener) } mCardFrame!!.removeAllViews() // Initialize swipe gestureDetector = GestureDetector(this, mGestureDetectorImpl) easeButtonsLayout = findViewById(R.id.ease_buttons) easeButton1 = EaseButton(EASE_1, findViewById(R.id.flashcard_layout_ease1), findViewById(R.id.ease1), findViewById(R.id.nextTime1)).apply { setListeners(mEaseHandler) } easeButton2 = EaseButton(EASE_2, findViewById(R.id.flashcard_layout_ease2), findViewById(R.id.ease2), findViewById(R.id.nextTime2)).apply { setListeners(mEaseHandler) } easeButton3 = EaseButton(EASE_3, findViewById(R.id.flashcard_layout_ease3), findViewById(R.id.ease3), findViewById(R.id.nextTime3)).apply { setListeners(mEaseHandler) } easeButton4 = EaseButton(EASE_4, findViewById(R.id.flashcard_layout_ease4), findViewById(R.id.ease4), findViewById(R.id.nextTime4)).apply { setListeners(mEaseHandler) } if (!mShowNextReviewTime) { easeButton1!!.hideNextReviewTime() easeButton2!!.hideNextReviewTime() easeButton3!!.hideNextReviewTime() easeButton4!!.hideNextReviewTime() } val flipCard = findViewById<Button>(R.id.flip_card) flipCardLayout = findViewById<LinearLayout>(R.id.flashcard_layout_flip).apply { setOnClickListener(mFlipCardListener) } if (animationEnabled()) { flipCard.setBackgroundResource(getResFromAttr(this, R.attr.hardButtonRippleRef)) } if (!mButtonHeightSet && mRelativeButtonSize != 100) { val params = flipCardLayout!!.layoutParams params.height = params.height * mRelativeButtonSize / 100 easeButton1!!.setButtonScale(mRelativeButtonSize) easeButton2!!.setButtonScale(mRelativeButtonSize) easeButton3!!.setButtonScale(mRelativeButtonSize) easeButton4!!.setButtonScale(mRelativeButtonSize) mButtonHeightSet = true } mInitialFlipCardHeight = flipCardLayout!!.layoutParams.height if (mLargeAnswerButtons) { val params = flipCardLayout!!.layoutParams params.height = mInitialFlipCardHeight * 2 } answerField = findViewById(R.id.answer_field) initControls() // Position answer buttons val answerButtonsPosition = AnkiDroidApp.getSharedPrefs(this).getString( getString(R.string.answer_buttons_position_preference), "bottom" ) mAnswerButtonsPosition = answerButtonsPosition val answerArea = findViewById<LinearLayout>(R.id.bottom_area_layout) val answerAreaParams = answerArea.layoutParams as RelativeLayout.LayoutParams val whiteboardContainer = findViewById<FrameLayout>(R.id.whiteboard) val whiteboardContainerParams = whiteboardContainer.layoutParams as RelativeLayout.LayoutParams val flashcardContainerParams = mCardFrame!!.layoutParams as RelativeLayout.LayoutParams val touchLayerContainerParams = mTouchLayer!!.layoutParams as RelativeLayout.LayoutParams when (answerButtonsPosition) { "top" -> { whiteboardContainerParams.addRule(RelativeLayout.BELOW, R.id.bottom_area_layout) flashcardContainerParams.addRule(RelativeLayout.BELOW, R.id.bottom_area_layout) touchLayerContainerParams.addRule(RelativeLayout.BELOW, R.id.bottom_area_layout) answerAreaParams.addRule(RelativeLayout.BELOW, R.id.mic_tool_bar_layer) answerArea.removeView(answerField) answerArea.addView(answerField, 1) } "bottom", "none" -> { whiteboardContainerParams.addRule(RelativeLayout.ABOVE, R.id.bottom_area_layout) whiteboardContainerParams.addRule(RelativeLayout.BELOW, R.id.mic_tool_bar_layer) flashcardContainerParams.addRule(RelativeLayout.ABOVE, R.id.bottom_area_layout) flashcardContainerParams.addRule(RelativeLayout.BELOW, R.id.mic_tool_bar_layer) touchLayerContainerParams.addRule(RelativeLayout.ABOVE, R.id.bottom_area_layout) touchLayerContainerParams.addRule(RelativeLayout.BELOW, R.id.mic_tool_bar_layer) answerAreaParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) } else -> Timber.w("Unknown answerButtonsPosition: %s", answerButtonsPosition) } answerArea.visibility = if (answerButtonsPosition == "none") View.GONE else View.VISIBLE answerArea.layoutParams = answerAreaParams whiteboardContainer.layoutParams = whiteboardContainerParams mCardFrame!!.layoutParams = flashcardContainerParams mTouchLayer!!.layoutParams = touchLayerContainerParams } @SuppressLint("SetJavaScriptEnabled") // they request we review carefully because of XSS security, we have protected open fun createWebView(): WebView { val webView: WebView = MyWebView(this) webView.scrollBarStyle = View.SCROLLBARS_OUTSIDE_OVERLAY webView.settings.displayZoomControls = false webView.settings.builtInZoomControls = true webView.settings.setSupportZoom(true) // Start at the most zoomed-out level webView.settings.loadWithOverviewMode = true webView.settings.javaScriptEnabled = true webView.webChromeClient = AnkiDroidWebChromeClient() // This setting toggles file system access within WebView // The default configuration is already true in apps targeting API <= 29 // Hence, this setting is only useful for apps targeting API >= 30 webView.settings.allowFileAccess = true // Problems with focus and input tags is the reason we keep the old type answer mechanism for old Androids. webView.isFocusableInTouchMode = typeAnswer!!.useInputTag webView.isScrollbarFadingEnabled = true Timber.d("Focusable = %s, Focusable in touch mode = %s", webView.isFocusable, webView.isFocusableInTouchMode) webView.webViewClient = CardViewerWebClient(mAssetLoader, this) // Set transparent color to prevent flashing white when night mode enabled webView.setBackgroundColor(Color.argb(1, 0, 0, 0)) // Javascript interface for calling AnkiDroid functions in webview, see card.js mAnkiDroidJsAPI = javaScriptFunction() webView.addJavascriptInterface(mAnkiDroidJsAPI!!, "AnkiDroidJS") // enable dom storage so that sessionStorage & localStorage can be used in webview webView.settings.domStorageEnabled = true return webView } /** If a card is displaying the question, flip it, otherwise answer it */ private fun flipOrAnswerCard(cardOrdinal: Int) { if (!displayAnswer) { displayCardAnswer() return } performClickWithVisualFeedback(cardOrdinal) } // #5780 - Users could OOM the WebView Renderer. This triggers the same symptoms @VisibleForTesting fun crashWebViewRenderer() { loadUrlInViewer("chrome://crash") } /** Used to set the "javascript:" URIs for IPC */ private fun loadUrlInViewer(url: String) { processCardAction { cardWebView: WebView? -> cardWebView!!.loadUrl(url) } } private fun <T : View?> inflateNewView(@IdRes id: Int): T { val layoutId = getContentViewAttr(fullscreenMode) val content = LayoutInflater.from(this@AbstractFlashcardViewer).inflate(layoutId, null, false) as ViewGroup val ret: T = content.findViewById(id) (ret!!.parent as ViewGroup).removeView(ret) // detach the view from its parent content.removeAllViews() return ret } private fun destroyWebView(webView: WebView?) { try { if (webView != null) { webView.stopLoading() webView.webChromeClient = null webView.destroy() } } catch (npe: NullPointerException) { Timber.e(npe, "WebView became null on destruction") } } protected fun shouldShowNextReviewTime(): Boolean { return mShowNextReviewTime } protected open fun displayAnswerBottomBar() { flipCardLayout!!.isClickable = false easeButtonsLayout!!.visibility = View.VISIBLE if (mLargeAnswerButtons) { easeButtonsLayout!!.orientation = LinearLayout.VERTICAL easeButtonsLayout!!.removeAllViewsInLayout() easeButton1!!.detachFromParent() easeButton2!!.detachFromParent() easeButton3!!.detachFromParent() easeButton4!!.detachFromParent() val row1 = LinearLayout(baseContext) row1.orientation = LinearLayout.HORIZONTAL val row2 = LinearLayout(baseContext) row2.orientation = LinearLayout.HORIZONTAL when (answerButtonCount) { 2 -> { easeButton1!!.height = mInitialFlipCardHeight * 2 easeButton2!!.height = mInitialFlipCardHeight * 2 easeButton1!!.addTo(row2) easeButton2!!.addTo(row2) easeButtonsLayout!!.addView(row2) } 3 -> { easeButton3!!.addTo(row1) easeButton1!!.addTo(row2) easeButton2!!.addTo(row2) val params: ViewGroup.LayoutParams params = LinearLayout.LayoutParams(Resources.getSystem().displayMetrics.widthPixels / 2, easeButton4!!.height) params.marginStart = Resources.getSystem().displayMetrics.widthPixels / 2 row1.layoutParams = params easeButtonsLayout!!.addView(row1) easeButtonsLayout!!.addView(row2) } else -> { easeButton2!!.addTo(row1) easeButton4!!.addTo(row1) easeButton1!!.addTo(row2) easeButton3!!.addTo(row2) easeButtonsLayout!!.addView(row1) easeButtonsLayout!!.addView(row2) } } } val after = Runnable { flipCardLayout!!.visibility = View.GONE } // hide "Show Answer" button if (animationDisabled()) { after.run() } else { flipCardLayout!!.alpha = 1f flipCardLayout!!.animate().alpha(0f).setDuration(shortAnimDuration.toLong()).withEndAction(after) } } protected open fun hideEaseButtons() { val after = Runnable { actualHideEaseButtons() } val easeButtonsVisible = easeButtonsLayout!!.visibility == View.VISIBLE flipCardLayout!!.isClickable = true flipCardLayout!!.visibility = View.VISIBLE if (animationDisabled() || !easeButtonsVisible) { after.run() } else { flipCardLayout!!.alpha = 0f flipCardLayout!!.animate().alpha(1f).setDuration(shortAnimDuration.toLong()).withEndAction(after) } focusAnswerCompletionField() } private fun actualHideEaseButtons() { easeButtonsLayout!!.visibility = View.GONE easeButton1!!.hide() easeButton2!!.hide() easeButton3!!.hide() easeButton4!!.hide() } /** * Focuses the appropriate field for an answer * And allows keyboard shortcuts to go to the default handlers. */ private fun focusAnswerCompletionField() { // This does not handle mUseInputTag (the WebView contains an input field with a typable answer). // In this case, the user can use touch to focus the field if necessary. if (typeAnswer!!.autoFocusEditText()) { answerField!!.focusWithKeyboard() } else { flipCardLayout!!.requestFocus() } } protected open fun switchTopBarVisibility(visible: Int) { mPreviousAnswerIndicator!!.setVisibility(visible) } protected open fun initControls() { mCardFrame!!.visibility = View.VISIBLE mPreviousAnswerIndicator!!.setVisibility(View.VISIBLE) flipCardLayout!!.visibility = View.VISIBLE answerField!!.visibility = if (typeAnswer!!.validForEditText()) View.VISIBLE else View.GONE answerField!!.setOnEditorActionListener { _, actionId: Int, _ -> if (actionId == EditorInfo.IME_ACTION_DONE) { displayCardAnswer() return@setOnEditorActionListener true } false } answerField!!.setOnKeyListener { _, keyCode: Int, event: KeyEvent -> if (event.action == KeyEvent.ACTION_UP && (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER) ) { displayCardAnswer() return@setOnKeyListener true } false } } protected open fun restorePreferences(): SharedPreferences { val preferences = AnkiDroidApp.getSharedPrefs(baseContext) typeAnswer = createInstance(preferences) // mDeckFilename = preferences.getString("deckFilename", ""); fullscreenMode = fromPreference(preferences) mRelativeButtonSize = preferences.getInt("answerButtonSize", 100) mTTS.enabled = preferences.getBoolean("tts", false) mScrollingButtons = preferences.getBoolean("scrolling_buttons", false) mDoubleScrolling = preferences.getBoolean("double_scrolling", false) prefShowTopbar = preferences.getBoolean("showTopbar", true) mLargeAnswerButtons = preferences.getBoolean("showLargeAnswerButtons", false) mDoubleTapTimeInterval = preferences.getInt(DOUBLE_TAP_TIME_INTERVAL, DEFAULT_DOUBLE_TAP_TIME_INTERVAL) mExitViaDoubleTapBack = preferences.getBoolean("exitViaDoubleTapBack", false) mGesturesEnabled = preferences.getBoolean(GestureProcessor.PREF_KEY, false) if (mGesturesEnabled) { mGestureProcessor.init(preferences) } if (preferences.getBoolean("keepScreenOn", false)) { this.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } return preferences } protected open fun restoreCollectionPreferences(col: Collection) { // These are preferences we pull out of the collection instead of SharedPreferences try { mShowNextReviewTime = col.get_config_boolean("estTimes") val preferences = AnkiDroidApp.getSharedPrefs(baseContext) automaticAnswer = AutomaticAnswer.createInstance(this, preferences, col) } catch (ex: Exception) { Timber.w(ex) onCollectionLoadError() } } private fun setInterface() { if (currentCard == null) { return } recreateWebView() } protected open fun recreateWebView() { if (webView == null) { webView = createWebView() initializeDebugging(AnkiDroidApp.getSharedPrefs(this)) mCardFrame!!.addView(webView) mGestureDetectorImpl.onWebViewCreated(webView!!) } if (webView!!.visibility != View.VISIBLE) { webView!!.visibility = View.VISIBLE } } /** A new card has been loaded into the Viewer, or the question has been re-shown */ protected open fun updateForNewCard() { updateActionBar() // Clean answer field if (typeAnswer!!.validForEditText()) { answerField!!.setText("") } } protected open fun updateActionBar() { updateDeckName() } private fun updateDeckName() { if (currentCard == null) return val actionBar = supportActionBar if (actionBar != null) { val title = Decks.basename(col.decks.get(currentCard!!.did).getString("name")) actionBar.title = title } if (!prefShowTopbar) { topBarLayout!!.visibility = View.GONE } } override fun automaticShowQuestion(action: AutomaticAnswerAction) { // Assume hitting the "Again" button when auto next question easeButton1!!.performSafeClick() } override fun automaticShowAnswer() { if (flipCardLayout!!.isEnabled && flipCardLayout!!.visibility == View.VISIBLE) { flipCardLayout!!.performClick() } } internal inner class ReadTextListener : ReadText.ReadTextListener { override fun onDone(playedSide: SoundSide?) { Timber.d("done reading text") if (playedSide == SoundSide.QUESTION) { automaticAnswer.scheduleAutomaticDisplayAnswer() } else if (playedSide == SoundSide.ANSWER) { automaticAnswer.scheduleAutomaticDisplayQuestion() } } } open fun displayCardQuestion() { displayCardQuestion(false) // js api initialisation / reset mAnkiDroidJsAPI!!.init() } private fun displayCardQuestion(reload: Boolean) { Timber.d("displayCardQuestion()") displayAnswer = false mBackButtonPressedToReturn = false setInterface() typeAnswer!!.input = "" typeAnswer!!.updateInfo(currentCard!!, resources) if (!currentCard!!.isEmpty && typeAnswer!!.validForEditText()) { // Show text entry based on if the user wants to write the answer answerField!!.visibility = View.VISIBLE answerField!!.applyLanguageHint(typeAnswer!!.languageHint) } else { answerField!!.visibility = View.GONE } val content = mHtmlGenerator!!.generateHtml(currentCard!!, reload, Side.FRONT) updateCard(content) hideEaseButtons() automaticAnswer.onDisplayQuestion() // If Card-based TTS is enabled, we "automatic display" after the TTS has finished as we don't know the duration if (!mTTS.enabled) { automaticAnswer.scheduleAutomaticDisplayAnswer(mUseTimerDynamicMS) } Timber.i("AbstractFlashcardViewer:: Question successfully shown for card id %d", currentCard!!.id) } @VisibleForTesting(otherwise = VisibleForTesting.PROTECTED) open fun displayCardAnswer() { // #7294 Required in case the animation end action does not fire: actualHideEaseButtons() Timber.d("displayCardAnswer()") mMissingImageHandler.onCardSideChange() mBackButtonPressedToReturn = false // prevent answering (by e.g. gestures) before card is loaded if (currentCard == null) { return } // TODO needs testing: changing a card's model without flipping it back to the front // (such as editing a card, then editing the card template) typeAnswer!!.updateInfo(currentCard!!, resources) // Explicitly hide the soft keyboard. It *should* be hiding itself automatically, // but sometimes failed to do so (e.g. if an OnKeyListener is attached). if (typeAnswer!!.validForEditText()) { val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(answerField!!.windowToken, 0) } displayAnswer = true mSoundPlayer.stopSounds() answerField!!.visibility = View.GONE // Clean up the user answer and the correct answer if (!typeAnswer!!.useInputTag) { typeAnswer!!.input = answerField!!.text.toString() } mIsSelecting = false val answerContent = mHtmlGenerator!!.generateHtml(currentCard!!, false, Side.BACK) updateCard(answerContent) displayAnswerBottomBar() automaticAnswer.onDisplayAnswer() // If Card-based TTS is enabled, we "automatic display" after the TTS has finished as we don't know the duration if (!mTTS.enabled) { automaticAnswer.scheduleAutomaticDisplayQuestion(mUseTimerDynamicMS) } } override fun scrollCurrentCardBy(dy: Int) { processCardAction { cardWebView: WebView? -> if (dy != 0 && cardWebView!!.canScrollVertically(dy)) { cardWebView.scrollBy(0, dy) } } } override fun tapOnCurrentCard(x: Int, y: Int) { // assemble suitable ACTION_DOWN and ACTION_UP events and forward them to the card's handler val eDown = MotionEvent.obtain( SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, x.toFloat(), y.toFloat(), 1f, 1f, 0, 1f, 1f, 0, 0 ) processCardAction { cardWebView: WebView? -> cardWebView!!.dispatchTouchEvent(eDown) } val eUp = MotionEvent.obtain( eDown.downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, x.toFloat(), y.toFloat(), 1f, 1f, 0, 1f, 1f, 0, 0 ) processCardAction { cardWebView: WebView? -> cardWebView!!.dispatchTouchEvent(eUp) } } @RustCleanup("mAnswerSoundsAdded is no longer necessary once we transition as it's a fast operation") private fun addAnswerSounds(answerSounds: Supplier<List<SoundOrVideoTag>>) { // don't add answer sounds multiple times, such as when reshowing card after exiting editor // additionally, this condition reduces computation time if (!mAnswerSoundsAdded) { mSoundPlayer.addSounds(mBaseUrl!!, answerSounds.get(), SoundSide.ANSWER) mAnswerSoundsAdded = true } } @KotlinCleanup("internal for AnkiDroidJsApi") internal val isInNightMode: Boolean get() = Themes.currentTheme.isNightMode private fun updateCard(content: CardHtml) { Timber.d("updateCard()") mUseTimerDynamicMS = 0 if (displayAnswer) { addAnswerSounds { content.getSoundTags(Side.BACK) } } else { // reset sounds each time first side of card is displayed, which may happen repeatedly without ever // leaving the card (such as when edited) mSoundPlayer.resetSounds() mAnswerSoundsAdded = false mSoundPlayer.addSounds(mBaseUrl!!, content.getSoundTags(Side.FRONT), SoundSide.QUESTION) if (automaticAnswer.isEnabled() && !mAnswerSoundsAdded && mCardSoundConfig!!.autoplay) { addAnswerSounds { content.getSoundTags(Side.BACK) } } } cardContent = content.getTemplateHtml() Timber.d("base url = %s", mBaseUrl) if (AnkiDroidApp.getSharedPrefs(this).getBoolean("html_javascript_debugging", false)) { try { FileOutputStream( File( CollectionHelper.getCurrentAnkiDroidDirectory(this), "card.html" ) ).use { f -> f.write(cardContent!!.toByteArray()) } } catch (e: IOException) { Timber.d(e, "failed to save card") } } fillFlashcard() playSounds(false) // Play sounds if appropriate } /** * Plays sounds (or TTS, if configured) for currently shown side of card. * * @param doAudioReplay indicates an anki desktop-like replay call is desired, whose behavior is identical to * pressing the keyboard shortcut R on the desktop */ protected open fun playSounds(doAudioReplay: Boolean) { val replayQuestion = mCardSoundConfig!!.replayQuestion if (mCardSoundConfig!!.autoplay || doAudioReplay) { // Use TTS if TTS preference enabled and no other sound source val useTTS = mTTS.enabled && !(displayAnswer && mSoundPlayer.hasAnswer()) && !(!displayAnswer && mSoundPlayer.hasQuestion()) // We need to play the sounds from the proper side of the card if (!useTTS) { // Text to speech not in effect here if (doAudioReplay && replayQuestion && displayAnswer) { // only when all of the above are true will question be played with answer, to match desktop playSounds(SoundSide.QUESTION_AND_ANSWER) } else if (displayAnswer) { playSounds(SoundSide.ANSWER) if (automaticAnswer.isEnabled()) { mUseTimerDynamicMS = mSoundPlayer.getSoundsLength(SoundSide.ANSWER) } } else { // question is displayed playSounds(SoundSide.QUESTION) // If the user wants to show the answer automatically if (automaticAnswer.isEnabled()) { mUseTimerDynamicMS = mSoundPlayer.getSoundsLength(SoundSide.QUESTION_AND_ANSWER) } } } else { // Text to speech is in effect here // If the question is displayed or if the question should be replayed, read the question if (mTtsInitialized) { if (!displayAnswer || doAudioReplay && replayQuestion) { readCardTts(SoundSide.QUESTION) } if (displayAnswer) { readCardTts(SoundSide.ANSWER) } } else { mReplayOnTtsInit = true } } } } private fun readCardTts(soundSide: SoundSide) { val tags = legacyGetTtsTags(currentCard!!, soundSide, this) if (tags != null) { mTTS.readCardText(tags, currentCard!!, soundSide) } } private fun playSounds(questionAndAnswer: SoundSide) { mSoundPlayer.playSounds(questionAndAnswer, soundErrorListener) } private val soundErrorListener: Sound.OnErrorListener get() = Sound.OnErrorListener { _: MediaPlayer?, what: Int, extra: Int, path: String? -> Timber.w("Media Error: (%d, %d). Calling OnCompletionListener", what, extra) try { val file = File(path!!) if (!file.exists()) { mMissingImageHandler.processMissingSound(file) { filename: String? -> displayCouldNotFindMediaSnackbar(filename) } } } catch (e: Exception) { Timber.w(e) return@OnErrorListener false } false } /** * Shows the dialogue for selecting TTS for the current card and cardside. */ protected fun showSelectTtsDialogue() { if (mTtsInitialized) { mTTS.selectTts(this, currentCard!!, if (displayAnswer) SoundSide.ANSWER else SoundSide.QUESTION) } } open fun fillFlashcard() { Timber.d("fillFlashcard()") Timber.d("base url = %s", mBaseUrl) if (cardContent == null) { Timber.w("fillFlashCard() called with no card content") return } val cardContent = cardContent!! processCardAction { cardWebView: WebView? -> loadContentIntoCard(cardWebView, cardContent) } mGestureDetectorImpl.onFillFlashcard() if (!displayAnswer) { updateForNewCard() } } private fun loadContentIntoCard(card: WebView?, content: String) { if (card != null) { card.settings.mediaPlaybackRequiresUserGesture = !mCardSoundConfig!!.autoplay card.loadDataWithBaseURL(mViewerUrl, content, "text/html", "utf-8", null) } } protected open fun unblockControls() { controlBlocked = ControlBlock.UNBLOCKED mCardFrame!!.isEnabled = true flipCardLayout!!.isEnabled = true easeButton1!!.unblockBasedOnEase(mCurrentEase) easeButton2!!.unblockBasedOnEase(mCurrentEase) easeButton3!!.unblockBasedOnEase(mCurrentEase) easeButton4!!.unblockBasedOnEase(mCurrentEase) if (typeAnswer!!.validForEditText()) { answerField!!.isEnabled = true } mTouchLayer!!.visibility = View.VISIBLE mInAnswer = false invalidateOptionsMenu() } /** * @param quick Whether we expect the control to come back quickly */ @VisibleForTesting protected open fun blockControls(quick: Boolean) { controlBlocked = if (quick) { ControlBlock.QUICK } else { ControlBlock.SLOW } mCardFrame!!.isEnabled = false flipCardLayout!!.isEnabled = false mTouchLayer!!.visibility = View.INVISIBLE mInAnswer = true easeButton1!!.blockBasedOnEase(mCurrentEase) easeButton2!!.blockBasedOnEase(mCurrentEase) easeButton3!!.blockBasedOnEase(mCurrentEase) easeButton4!!.blockBasedOnEase(mCurrentEase) if (typeAnswer!!.validForEditText()) { answerField!!.isEnabled = false } invalidateOptionsMenu() } /** * Select Text in the webview and automatically sends the selected text to the clipboard. From * http://cosmez.blogspot.com/2010/04/webview-emulateshiftheld-on-android.html */ @Suppress("deprecation") // Tracked separately in Github as #5024 private fun selectAndCopyText() { mIsSelecting = try { val shiftPressEvent = KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0) processCardAction { receiver: WebView? -> shiftPressEvent.dispatch(receiver) } shiftPressEvent.isShiftPressed true } catch (e: Exception) { throw AssertionError(e) } } internal fun buryCard(): Boolean { return dismiss(BuryCard(currentCard!!)) { showSnackbarWithUndoButton(R.string.buried_card) } } internal fun suspendCard(): Boolean { return dismiss(SuspendCard(currentCard!!)) { showSnackbarWithUndoButton(R.string.suspended_card) } } internal fun suspendNote(): Boolean { return dismiss(SuspendNote(currentCard!!)) { showSnackbarWithUndoButton(R.string.suspended_note) } } internal fun buryNote(): Boolean { return dismiss(BuryNote(currentCard!!)) { showSnackbarWithUndoButton(R.string.buried_note) } } override fun executeCommand(which: ViewerCommand, fromGesture: Gesture?): Boolean { return if (isControlBlocked && which !== ViewerCommand.EXIT) { false } else when (which) { ViewerCommand.SHOW_ANSWER -> { if (displayAnswer) { return false } displayCardAnswer() true } ViewerCommand.FLIP_OR_ANSWER_EASE1 -> { flipOrAnswerCard(EASE_1) true } ViewerCommand.FLIP_OR_ANSWER_EASE2 -> { flipOrAnswerCard(EASE_2) true } ViewerCommand.FLIP_OR_ANSWER_EASE3 -> { flipOrAnswerCard(EASE_3) true } ViewerCommand.FLIP_OR_ANSWER_EASE4 -> { flipOrAnswerCard(EASE_4) true } ViewerCommand.FLIP_OR_ANSWER_RECOMMENDED -> { flipOrAnswerCard(getRecommendedEase(false)) true } ViewerCommand.FLIP_OR_ANSWER_BETTER_THAN_RECOMMENDED -> { flipOrAnswerCard(getRecommendedEase(true)) true } ViewerCommand.EXIT -> { closeReviewer(RESULT_DEFAULT, false) true } ViewerCommand.UNDO -> { if (!isUndoAvailable) { return false } undo() true } ViewerCommand.EDIT -> { editCard(fromGesture) true } ViewerCommand.TAG -> { showTagsDialog() true } ViewerCommand.BURY_CARD -> buryCard() ViewerCommand.BURY_NOTE -> buryNote() ViewerCommand.SUSPEND_CARD -> suspendCard() ViewerCommand.SUSPEND_NOTE -> suspendNote() ViewerCommand.DELETE -> { showDeleteNoteDialog() true } ViewerCommand.PLAY_MEDIA -> { playSounds(true) true } ViewerCommand.PAGE_UP -> { onPageUp() true } ViewerCommand.PAGE_DOWN -> { onPageDown() true } ViewerCommand.ABORT_AND_SYNC -> { abortAndSync() true } ViewerCommand.RECORD_VOICE -> { recordVoice() true } ViewerCommand.REPLAY_VOICE -> { replayVoice() true } ViewerCommand.TOGGLE_WHITEBOARD -> { toggleWhiteboard() true } ViewerCommand.SHOW_HINT -> { loadUrlInViewer("javascript: showHint();") true } ViewerCommand.SHOW_ALL_HINTS -> { loadUrlInViewer("javascript: showAllHints();") true } else -> { Timber.w("Unknown command requested: %s", which) false } } } fun executeCommand(which: ViewerCommand): Boolean { return executeCommand(which, fromGesture = null) } protected open fun replayVoice() { // intentionally blank } protected open fun recordVoice() { // intentionally blank } protected open fun toggleWhiteboard() { // intentionally blank } private fun abortAndSync() { closeReviewer(RESULT_ABORT_AND_SYNC, true) } /** Displays a snackbar which does not obscure the answer buttons */ private fun showSnackbarAboveAnswerButtons( text: CharSequence, duration: Int = Snackbar.LENGTH_LONG, snackbarBuilder: SnackbarBuilder? = null ) { // BUG: Moving from full screen to non-full screen obscures the buttons showSnackbar(text, duration) { snackbarBuilder?.let { it() } if (mAnswerButtonsPosition == "bottom") { val easeButtons = findViewById<View>(R.id.answer_options_layout) val previewButtons = findViewById<View>(R.id.preview_buttons_layout) anchorView = if (previewButtons.isVisible) previewButtons else easeButtons } } } private fun showSnackbarAboveAnswerButtons( @StringRes textResource: Int, duration: Int = Snackbar.LENGTH_LONG, snackbarBuilder: SnackbarBuilder? = null ) { val text = getString(textResource) showSnackbarAboveAnswerButtons(text, duration, snackbarBuilder) } private fun onPageUp() { // pageUp performs a half scroll, we want a full page processCardAction { cardWebView: WebView? -> cardWebView!!.pageUp(false) cardWebView.pageUp(false) } } private fun onPageDown() { processCardAction { cardWebView: WebView? -> cardWebView!!.pageDown(false) cardWebView.pageDown(false) } } protected open fun performClickWithVisualFeedback(ease: Int) { // Delay could potentially be lower - testing with 20 left a visible "click" when (ease) { EASE_1 -> easeButton1!!.performClickWithVisualFeedback() EASE_2 -> easeButton2!!.performClickWithVisualFeedback() EASE_3 -> easeButton3!!.performClickWithVisualFeedback() EASE_4 -> easeButton4!!.performClickWithVisualFeedback() } } @get:VisibleForTesting protected open val isUndoAvailable: Boolean get() = col.undoAvailable() // ---------------------------------------------------------------------------- // INNER CLASSES // ---------------------------------------------------------------------------- /** * Provides a hook for calling "alert" from javascript. Useful for debugging your javascript. */ class AnkiDroidWebChromeClient : WebChromeClient() { override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean { Timber.i("AbstractFlashcardViewer:: onJsAlert: %s", message) result.confirm() return true } } protected open fun closeReviewer(result: Int, saveDeck: Boolean) { automaticAnswer.disable() mPreviousAnswerIndicator!!.stopAutomaticHide() mLongClickHandler.removeCallbacks(mLongClickTestRunnable) mLongClickHandler.removeCallbacks(mStartLongClickAction) [email protected](result) if (saveDeck) { saveCollectionInBackground() } finishWithAnimation(ActivityTransitionAnimation.Direction.END) } protected fun refreshActionBar() { invalidateOptionsMenu() } /** Fixing bug 720: <input></input> focus, thanks to pablomouzo on android issue 7189 */ internal inner class MyWebView(context: Context?) : WebView(context!!) { override fun loadDataWithBaseURL(baseUrl: String?, data: String, mimeType: String?, encoding: String?, historyUrl: String?) { if ([email protected]) { super.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl) } else { Timber.w("Not loading card - Activity is in the process of being destroyed.") } } override fun onScrollChanged(horiz: Int, vert: Int, oldHoriz: Int, oldVert: Int) { super.onScrollChanged(horiz, vert, oldHoriz, oldVert) if (abs(horiz - oldHoriz) > abs(vert - oldVert)) { mIsXScrolling = true mScrollHandler.removeCallbacks(mScrollXRunnable) mScrollHandler.postDelayed(mScrollXRunnable, 300) } else { mIsYScrolling = true mScrollHandler.removeCallbacks(mScrollYRunnable) mScrollHandler.postDelayed(mScrollYRunnable, 300) } } override fun onTouchEvent(event: MotionEvent): Boolean { if (event.action == MotionEvent.ACTION_DOWN) { val scrollParent = findScrollParent(this) scrollParent?.requestDisallowInterceptTouchEvent(true) } return super.onTouchEvent(event) } override fun onOverScrolled(scrollX: Int, scrollY: Int, clampedX: Boolean, clampedY: Boolean) { if (clampedX) { val scrollParent = findScrollParent(this) scrollParent?.requestDisallowInterceptTouchEvent(false) } super.onOverScrolled(scrollX, scrollY, clampedX, clampedY) } private fun findScrollParent(current: View): ViewParent? { val parent = current.parent ?: return null if (parent is FullDraggableContainer) { return parent } else if (parent is View) { return findScrollParent(parent as View) } return null } private val mScrollHandler = newHandler() private val mScrollXRunnable = Runnable { mIsXScrolling = false } private val mScrollYRunnable = Runnable { mIsYScrolling = false } } internal open inner class MyGestureDetector : SimpleOnGestureListener() { override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { Timber.d("onFling") // #5741 - A swipe from the top caused delayedHide to be triggered, // accepting a gesture and quickly disabling the status bar, which wasn't ideal. // it would be lovely to use e1.getEdgeFlags(), but alas, it doesn't work. if (isTouchingEdge(e1)) { Timber.d("ignoring edge fling") return false } // Go back to immersive mode if the user had temporarily exited it (and then execute swipe gesture) [email protected]() if (mGesturesEnabled) { try { val dy = e2.y - e1.y val dx = e2.x - e1.x mGestureProcessor.onFling(dx, dy, velocityX, velocityY, mIsSelecting, mIsXScrolling, mIsYScrolling) } catch (e: Exception) { Timber.e(e, "onFling Exception") } } return false } private fun isTouchingEdge(e1: MotionEvent): Boolean { val height = mTouchLayer!!.height val width = mTouchLayer!!.width val margin = Companion.NO_GESTURE_BORDER_DIP * resources.displayMetrics.density + 0.5f return e1.x < margin || e1.y < margin || height - e1.y < margin || width - e1.x < margin } override fun onDoubleTap(e: MotionEvent): Boolean { if (mGesturesEnabled) { mGestureProcessor.onDoubleTap() } return true } override fun onSingleTapUp(e: MotionEvent): Boolean { if (mTouchStarted) { mLongClickHandler.removeCallbacks(mLongClickTestRunnable) mTouchStarted = false } return false } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { // Go back to immersive mode if the user had temporarily exited it (and ignore the tap gesture) if (onSingleTap()) { return true } executeTouchCommand(e) return false } protected open fun executeTouchCommand(e: MotionEvent) { if (mGesturesEnabled && !mIsSelecting) { val height = mTouchLayer!!.height val width = mTouchLayer!!.width val posX = e.x val posY = e.y mGestureProcessor.onTap(height, width, posX, posY) } mIsSelecting = false } open fun onWebViewCreated(webView: WebView) { // intentionally blank } open fun onFillFlashcard() { // intentionally blank } open fun eventCanBeSentToWebView(event: MotionEvent): Boolean { return true } } protected open fun onSingleTap(): Boolean { return false } protected open fun onFling() {} /** #6141 - blocks clicking links from executing "touch" gestures. * COULD_BE_BETTER: Make base class static and move this out of the CardViewer */ internal inner class LinkDetectingGestureDetector : MyGestureDetector() { /** A list of events to process when listening to WebView touches */ private val mDesiredTouchEvents = HashSetInit<MotionEvent>(2) /** A list of events we sent to the WebView (to block double-processing) */ private val mDispatchedTouchEvents = HashSetInit<MotionEvent>(2) override fun onFillFlashcard() { Timber.d("Removing pending touch events for gestures") mDesiredTouchEvents.clear() mDispatchedTouchEvents.clear() } override fun eventCanBeSentToWebView(event: MotionEvent): Boolean { // if we processed the event, we don't want to perform it again return !mDispatchedTouchEvents.remove(event) } override fun executeTouchCommand(e: MotionEvent) { e.action = MotionEvent.ACTION_DOWN val upEvent = MotionEvent.obtainNoHistory(e) upEvent.action = MotionEvent.ACTION_UP // mark the events we want to process mDesiredTouchEvents.add(e) mDesiredTouchEvents.add(upEvent) // mark the events to can guard against double-processing mDispatchedTouchEvents.add(e) mDispatchedTouchEvents.add(upEvent) Timber.d("Dispatching touch events") processCardAction { cardWebView: WebView? -> cardWebView!!.dispatchTouchEvent(e) cardWebView.dispatchTouchEvent(upEvent) } } @SuppressLint("ClickableViewAccessibility") override fun onWebViewCreated(webView: WebView) { Timber.d("Initializing WebView touch handler") webView.setOnTouchListener { webViewAsView: View, motionEvent: MotionEvent -> if (!mDesiredTouchEvents.remove(motionEvent)) { return@setOnTouchListener false } // We need an associated up event so the WebView doesn't keep a selection // But we don't want to handle this as a touch event. if (motionEvent.action == MotionEvent.ACTION_UP) { return@setOnTouchListener true } val cardWebView = webViewAsView as WebView val result: HitTestResult = try { cardWebView.hitTestResult } catch (e: Exception) { Timber.w(e, "Cannot obtain HitTest result") return@setOnTouchListener true } if (isLinkClick(result)) { Timber.v("Detected link click - ignoring gesture dispatch") return@setOnTouchListener true } Timber.v("Executing continuation for click type: %d", result.type) super.executeTouchCommand(motionEvent) true } } private fun isLinkClick(result: HitTestResult?): Boolean { if (result == null) { return false } val type = result.type return ( type == HitTestResult.SRC_ANCHOR_TYPE || type == HitTestResult.SRC_IMAGE_ANCHOR_TYPE ) } } /** * Public method to start new video player activity */ fun playVideo(path: String?) { Timber.i("Launching Video: %s", path) val videoPlayer = Intent(this, VideoPlayer::class.java) videoPlayer.putExtra("path", path) startActivityWithoutAnimation(videoPlayer) } /** Callback for when TTS has been initialized. */ fun ttsInitialized() { mTtsInitialized = true if (mReplayOnTtsInit) { playSounds(true) } } protected open fun shouldDisplayMark(): Boolean { return isMarked(currentCard!!.note()) } protected fun <TResult : Computation<NextCard<*>>?> nextCardHandler(): TaskListenerBuilder<Unit, TResult> { return TaskListenerBuilder(NextCardHandler()) } /** * @param dismiss An action to execute, to ignore current card and get another one * @return whether the action succeeded. */ protected open fun dismiss(dismiss: AnkiMethod<Computation<NextCard<*>>>, executeAfter: Runnable): Boolean { blockControls(false) dismiss.runWithHandler(nextCardHandler<Computation<NextCard<*>>?>().alsoExecuteAfter { executeAfter.run() }) return true } val writeLock: Lock get() = mCardLock.writeLock() open var currentCard: Card? = null set(card) { field = card mCardSoundConfig = if (card == null) { null } else { create(col, card) } } /** Refreshes the WebView after a crash */ fun destroyWebViewFrame() { // Destroy the current WebView (to ensure WebView is GCed). // Otherwise, we get the following error: // "crash wasn't handled by all associated webviews, triggering application crash" mCardFrame!!.removeAllViews() mCardFrameParent!!.removeView(mCardFrame) // destroy after removal from the view - produces logcat warnings otherwise destroyWebView(webView) webView = null // inflate a new instance of mCardFrame mCardFrame = inflateNewView<FrameLayout>(R.id.flashcard) // Even with the above, I occasionally saw the above error. Manually trigger the GC. // I'll keep this line unless I see another crash, which would point to another underlying issue. System.gc() } fun recreateWebViewFrame() { // we need to add at index 0 so gestures still go through. mCardFrameParent!!.addView(mCardFrame, 0) recreateWebView() } /** Signals from a WebView represent actions with no parameters */ @VisibleForTesting internal object WebViewSignalParserUtils { /** A signal which we did not know how to handle */ const val SIGNAL_UNHANDLED = 0 /** A known signal which should perform a noop */ const val SIGNAL_NOOP = 1 const val TYPE_FOCUS = 2 /** Tell the app that we no longer want to focus the WebView and should instead return keyboard focus to a * native answer input method. */ const val RELINQUISH_FOCUS = 3 const val SHOW_ANSWER = 4 const val ANSWER_ORDINAL_1 = 5 const val ANSWER_ORDINAL_2 = 6 const val ANSWER_ORDINAL_3 = 7 const val ANSWER_ORDINAL_4 = 8 fun getSignalFromUrl(url: String): Int { when (url) { "signal:typefocus" -> return TYPE_FOCUS "signal:relinquishFocus" -> return RELINQUISH_FOCUS "signal:show_answer" -> return SHOW_ANSWER "signal:answer_ease1" -> return ANSWER_ORDINAL_1 "signal:answer_ease2" -> return ANSWER_ORDINAL_2 "signal:answer_ease3" -> return ANSWER_ORDINAL_3 "signal:answer_ease4" -> return ANSWER_ORDINAL_4 else -> {} } if (url.startsWith("signal:answer_ease")) { Timber.w("Unhandled signal: ease value: %s", url) return SIGNAL_NOOP } return SIGNAL_UNHANDLED // unknown, or not a signal. } } protected inner class CardViewerWebClient internal constructor( private val loader: WebViewAssetLoader?, private val onPageFinishedCallback: OnPageFinishedCallback? = null ) : WebViewClient() { @TargetApi(Build.VERSION_CODES.N) override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { val url = request.url.toString() Timber.d("Obtained URL from card: '%s'", url) return filterUrl(url) } // required for lower APIs (I think) override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? { // response is null if nothing required if (isLoadedFromProtocolRelativeUrl(url)) { mMissingImageHandler.processInefficientImage { displayMediaUpgradeRequiredSnackbar() } } return null } @TargetApi(Build.VERSION_CODES.N) override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? { val url = request.url val result = loader!!.shouldInterceptRequest(url) if (result != null) { return result } if (!hasWebBrowser(baseContext)) { val scheme = url.scheme!!.trim { it <= ' ' } if ("http".equals(scheme, ignoreCase = true) || "https".equals(scheme, ignoreCase = true)) { val response = resources.getString(R.string.no_outgoing_link_in_cardbrowser) return WebResourceResponse("text/html", "utf-8", ByteArrayInputStream(response.toByteArray())) } } if (isLoadedFromProtocolRelativeUrl(request.url.toString())) { mMissingImageHandler.processInefficientImage { displayMediaUpgradeRequiredSnackbar() } } return null } private fun isLoadedFromProtocolRelativeUrl(url: String): Boolean { // a URL provided as "//wikipedia.org" is currently transformed to file://wikipedia.org, we can catch this // because <img src="x.png"> maps to file:///.../x.png return url.startsWith("file://") && !url.startsWith("file:///") } override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { super.onReceivedError(view, request, error) mMissingImageHandler.processFailure(request) { filename: String? -> displayCouldNotFindMediaSnackbar(filename) } } override fun onReceivedHttpError(view: WebView, request: WebResourceRequest, errorResponse: WebResourceResponse) { super.onReceivedHttpError(view, request, errorResponse) mMissingImageHandler.processFailure(request) { filename: String? -> displayCouldNotFindMediaSnackbar(filename) } } override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { return filterUrl(url) } // Filter any links using the custom "playsound" protocol defined in Sound.java. // We play sounds through these links when a user taps the sound icon. @Suppress("deprecation") // resolveActivity fun filterUrl(url: String): Boolean { if (url.startsWith("playsound:")) { launchCatchingTask { controlSound(url) } return true } if (url.startsWith("file") || url.startsWith("data:")) { return false // Let the webview load files, i.e. local images. } if (url.startsWith("typeblurtext:")) { // Store the text the javascript has send us… typeAnswer!!.input = decodeUrl(url.replaceFirst("typeblurtext:".toRegex(), "")) // … and show the “SHOW ANSWER” button again. flipCardLayout!!.visibility = View.VISIBLE return true } if (url.startsWith("typeentertext:")) { // Store the text the javascript has send us… typeAnswer!!.input = decodeUrl(url.replaceFirst("typeentertext:".toRegex(), "")) // … and show the answer. flipCardLayout!!.performClick() return true } // Show options menu from WebView if (url.startsWith("signal:anki_show_options_menu")) { if (isFullscreen) { openOptionsMenu() } else { showThemedToast(this@AbstractFlashcardViewer, getString(R.string.ankidroid_turn_on_fullscreen_options_menu), true) } return true } // Show Navigation Drawer from WebView if (url.startsWith("signal:anki_show_navigation_drawer")) { if (isFullscreen) { onNavigationPressed() } else { showThemedToast(this@AbstractFlashcardViewer, getString(R.string.ankidroid_turn_on_fullscreen_nav_drawer), true) } return true } // card.html reload if (url.startsWith("signal:reload_card_html")) { redrawCard() return true } // mark card using javascript if (url.startsWith("signal:mark_current_card")) { if (!mAnkiDroidJsAPI!!.isInit(AnkiDroidJsAPIConstants.MARK_CARD, AnkiDroidJsAPIConstants.ankiJsErrorCodeMarkCard)) { return true } executeCommand(ViewerCommand.MARK) return true } // flag card (blue, green, orange, red) using javascript from AnkiDroid webview if (url.startsWith("signal:flag_")) { if (!mAnkiDroidJsAPI!!.isInit(AnkiDroidJsAPIConstants.TOGGLE_FLAG, AnkiDroidJsAPIConstants.ankiJsErrorCodeFlagCard)) { return true } return when (url.replaceFirst("signal:flag_".toRegex(), "")) { "none" -> { executeCommand(ViewerCommand.UNSET_FLAG) true } "red" -> { executeCommand(ViewerCommand.TOGGLE_FLAG_RED) true } "orange" -> { executeCommand(ViewerCommand.TOGGLE_FLAG_ORANGE) true } "green" -> { executeCommand(ViewerCommand.TOGGLE_FLAG_GREEN) true } "blue" -> { executeCommand(ViewerCommand.TOGGLE_FLAG_BLUE) true } else -> { Timber.d("No such Flag found.") true } } } // Show toast using JS if (url.startsWith("signal:anki_show_toast:")) { val msg = url.replaceFirst("signal:anki_show_toast:".toRegex(), "") val msgDecode = decodeUrl(msg) showThemedToast(this@AbstractFlashcardViewer, msgDecode, true) return true } when (val signalOrdinal = WebViewSignalParserUtils.getSignalFromUrl(url)) { WebViewSignalParserUtils.SIGNAL_UNHANDLED -> {} WebViewSignalParserUtils.SIGNAL_NOOP -> return true WebViewSignalParserUtils.TYPE_FOCUS -> { // Hide the “SHOW ANSWER” button when the input has focus. The soft keyboard takes up enough // space by itself. flipCardLayout!!.visibility = View.GONE return true } WebViewSignalParserUtils.RELINQUISH_FOCUS -> { // #5811 - The WebView could be focused via mouse. Allow components to return focus to Android. focusAnswerCompletionField() return true } WebViewSignalParserUtils.SHOW_ANSWER -> { // display answer when showAnswer() called from card.js if (!Companion.displayAnswer) { displayCardAnswer() } return true } WebViewSignalParserUtils.ANSWER_ORDINAL_1 -> { flipOrAnswerCard(EASE_1) return true } WebViewSignalParserUtils.ANSWER_ORDINAL_2 -> { flipOrAnswerCard(EASE_2) return true } WebViewSignalParserUtils.ANSWER_ORDINAL_3 -> { flipOrAnswerCard(EASE_3) return true } WebViewSignalParserUtils.ANSWER_ORDINAL_4 -> { flipOrAnswerCard(EASE_4) return true } else -> { // We know it was a signal, but forgot a case in the case statement. // This is not the same as SIGNAL_UNHANDLED, where it isn't a known signal. Timber.w("Unhandled signal case: %d", signalOrdinal) return true } } var intent: Intent? = null try { if (url.startsWith("intent:")) { intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME) } else if (url.startsWith("android-app:")) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) { intent = Intent.parseUri(url, 0) intent.data = null intent.setPackage(Uri.parse(url).host) } else { intent = Intent.parseUri(url, Intent.URI_ANDROID_APP_SCHEME) } } if (intent != null) { if (packageManager.resolveActivity(intent, 0) == null) { val packageName = intent.getPackage() if (packageName == null) { Timber.d("Not using resolved intent uri because not available: %s", intent) intent = null } else { Timber.d("Resolving intent uri to market uri because not available: %s", intent) intent = Intent( Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName") ) if (packageManager.resolveActivity(intent, 0) == null) { intent = null } } } else { // https://developer.chrome.com/multidevice/android/intents says that we should remove this intent.addCategory(Intent.CATEGORY_BROWSABLE) } } } catch (t: Throwable) { Timber.w("Unable to parse intent uri: %s because: %s", url, t.message) } if (intent == null) { Timber.d("Opening external link \"%s\" with an Intent", url) intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) } else { Timber.d("Opening resolved external link \"%s\" with an Intent: %s", url, intent) } try { startActivityWithoutAnimation(intent) } catch (e: ActivityNotFoundException) { Timber.w(e) // Don't crash if the intent is not handled } return true } /** * Check if the user clicked on another audio icon or the audio itself finished * Also, Check if the user clicked on the running audio icon * @param url */ @BlocksSchemaUpgrade("handle TTS tags") private suspend fun controlSound(url: String) { val replacedUrl = if (BackendFactory.defaultLegacySchema) { url.replaceFirst("playsound:".toRegex(), "") } else { val filename = when (val tag = currentCard?.let { getAvTag(it, url) }) { is SoundOrVideoTag -> tag.filename // not currently supported is TTSTag -> null else -> null } filename?.let { Sound.getSoundPath(mBaseUrl!!, it) } ?: return } if (replacedUrl != mSoundPlayer.currentAudioUri || mSoundPlayer.isCurrentAudioFinished) { onCurrentAudioChanged(replacedUrl) } else { mSoundPlayer.playOrPauseSound() } } private fun onCurrentAudioChanged(url: String) { mSoundPlayer.playSound(url, null, null, soundErrorListener) } private fun decodeUrl(url: String): String { try { return URLDecoder.decode(url, "UTF-8") } catch (e: UnsupportedEncodingException) { Timber.e(e, "UTF-8 isn't supported as an encoding?") } catch (e: Exception) { Timber.e(e, "Exception decoding: '%s'", url) showThemedToast(this@AbstractFlashcardViewer, getString(R.string.card_viewer_url_decode_error), true) } return "" } // Run any post-load events in javascript that rely on the window being completely loaded. override fun onPageFinished(view: WebView, url: String) { Timber.d("Java onPageFinished triggered: %s", url) // onPageFinished will be called multiple times if the WebView redirects by setting window.location.href if (url == mViewerUrl) { onPageFinishedCallback?.onPageFinished() Timber.d("New URL, triggering JS onPageFinished: %s", url) view.loadUrl("javascript:onPageFinished();") } } @TargetApi(Build.VERSION_CODES.O) override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean { return mOnRenderProcessGoneDelegate.onRenderProcessGone(view, detail) } } private fun displayCouldNotFindMediaSnackbar(filename: String?) { showSnackbarAboveAnswerButtons(getString(R.string.card_viewer_could_not_find_image, filename)) { setAction(R.string.help) { openUrl(Uri.parse(getString(R.string.link_faq_missing_media))) } } } private fun displayMediaUpgradeRequiredSnackbar() { showSnackbarAboveAnswerButtons(R.string.card_viewer_media_relative_protocol) { setAction(R.string.help) { openUrl(Uri.parse(getString(R.string.link_faq_invalid_protocol_relative))) } } } @VisibleForTesting(otherwise = VisibleForTesting.NONE) protected val typedInputText get() = typeAnswer!!.input @SuppressLint("WebViewApiAvailability") @VisibleForTesting(otherwise = VisibleForTesting.NONE) fun handleUrlFromJavascript(url: String) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // WebViewCompat recommended here, but I'll avoid the dependency as it's test code val c = webView?.webViewClient as? CardViewerWebClient? ?: throw IllegalStateException("Couldn't obtain WebView - maybe it wasn't created yet") c.filterUrl(url) } else { throw IllegalStateException("Can't get WebViewClient due to Android API") } } @VisibleForTesting fun loadInitialCard() { GetCard().runWithHandler(answerCardHandler(false)) } override val isDisplayingAnswer get() = displayAnswer override val isControlBlocked: Boolean get() = controlBlocked !== ControlBlock.UNBLOCKED @VisibleForTesting(otherwise = VisibleForTesting.NONE) @KotlinCleanup("move to test class as extension") val correctTypedAnswer get() = typeAnswer!!.correct internal fun showTagsDialog() { val tags = ArrayList(col.tags.all()) val selTags = ArrayList(currentCard!!.note().tags) val dialog = mTagsDialogFactory!!.newTagsDialog().withArguments(TagsDialog.DialogType.EDIT_TAGS, selTags, tags) showDialogFragment(dialog) } override fun onSelectedTags(selectedTags: List<String>, indeterminateTags: List<String>, option: Int) { if (currentCard!!.note().tags != selectedTags) { val tagString = TextUtils.join(" ", selectedTags) val note = currentCard!!.note() note.setTagsFromStr(tagString) note.flush() // Reload current card to reflect tag changes displayCardQuestion(true) } } open fun javaScriptFunction(): AnkiDroidJsAPI? { return AnkiDroidJsAPI(this) } override fun opExecuted(changes: OpChanges, handler: Any?) { if ((changes.studyQueues || changes.noteText || changes.card) && handler !== this) { // executing this only for the refresh side effects; there may be a better way GetCard().runWithHandler( answerCardHandler(false) ) } } companion object { /** * Result codes that are returned when this activity finishes. */ const val RESULT_DEFAULT = 50 const val RESULT_NO_MORE_CARDS = 52 const val RESULT_ABORT_AND_SYNC = 53 /** * Available options performed by other activities. */ const val EDIT_CURRENT_CARD = 0 const val DECK_OPTIONS = 1 const val EASE_1 = 1 const val EASE_2 = 2 const val EASE_3 = 3 const val EASE_4 = 4 /** * Time to wait in milliseconds before resuming fullscreen mode * * Should be protected, using non-JVM static members protected in the superclass companion is unsupported yet */ const val INITIAL_HIDE_DELAY = 200 // I don't see why we don't do this by intent. /** to be sent to and from the card editor */ @set:VisibleForTesting(otherwise = VisibleForTesting.NONE) var editorCard: Card? = null internal var displayAnswer = false const val DOUBLE_TAP_TIME_INTERVAL = "doubleTapTimeInterval" const val DEFAULT_DOUBLE_TAP_TIME_INTERVAL = 200 /** Handle providing help for "Image Not Found" */ private val mMissingImageHandler = MissingImageHandler() @KotlinCleanup("moved from MyGestureDetector") // Android design spec for the size of the status bar. private const val NO_GESTURE_BORDER_DIP = 24 @KotlinCleanup("moved from SelectEaseHandler") // maximum screen distance from initial touch where we will consider a click related to the touch private const val CLICK_ACTION_THRESHOLD = 200 /** * @return if [gesture] is a swipe, a transition to the same direction of the swipe * else return [ActivityTransitionAnimation.Direction.FADE] */ fun getAnimationTransitionFromGesture(gesture: Gesture?): ActivityTransitionAnimation.Direction { return when (gesture) { Gesture.SWIPE_UP -> ActivityTransitionAnimation.Direction.UP Gesture.SWIPE_DOWN -> ActivityTransitionAnimation.Direction.DOWN Gesture.SWIPE_RIGHT -> ActivityTransitionAnimation.Direction.RIGHT Gesture.SWIPE_LEFT -> ActivityTransitionAnimation.Direction.LEFT else -> ActivityTransitionAnimation.Direction.FADE } } } }
gpl-3.0
c1672d9e105288e7c1847f6bfb952423
40.407955
176
0.600593
5.031853
false
false
false
false
pdvrieze/ProcessManager
darwin/servletSupport/src/main/kotlin/io/github/pdvrieze/darwin/servlet/support/servlet.kt
1
2795
/* * Copyright (c) 2021. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package io.github.pdvrieze.darwin.servlet.support import kotlinx.html.HtmlBlockTag import uk.ac.bournemouth.darwin.html.RequestInfo import uk.ac.bournemouth.darwin.html.RequestServiceContext import uk.ac.bournemouth.darwin.html.darwinError import uk.ac.bournemouth.darwin.html.darwinResponse import uk.ac.bournemouth.darwin.sharedhtml.ContextTagConsumer import uk.ac.bournemouth.darwin.sharedhtml.ServiceContext import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse public fun HttpServletResponse.darwinResponse( request: HttpServletRequest, windowTitle: String = "Darwin", pageTitle: String? = null, includeLogin: Boolean = true, context: ServiceContext, bodyContent: ContextTagConsumer<HtmlBlockTag>.() -> Unit ) { val resp = ServletResponseContext(this) val req = ServletRequestInfo(request) return resp.darwinResponse(req, windowTitle, pageTitle, includeLogin, context, bodyContent) } public fun HttpServletResponse.darwinResponse( request: HttpServletRequest, windowTitle: String = "Darwin", pageTitle: String? = null, includeLogin: Boolean = true, bodyContent: ContextTagConsumer<HtmlBlockTag>.() -> Unit ) { val resp = ServletResponseContext(this) val req = ServletRequestInfo(request) val context = RequestServiceContext(req) return resp.darwinResponse(req, windowTitle, pageTitle, includeLogin, context, bodyContent) } public fun HttpServletResponse.darwinError(request: HttpServletRequest, message: String, code: Int = 500, status: String = "Server error", cause: Exception? = null) { val resp = ServletResponseContext(this) val req = ServletRequestInfo(request) resp.darwinError(req, message, code, status, cause) } public val HttpServletRequest.htmlAccepted: Boolean get() { return getHeader("Accept")?.let { it.contains("text/html") || it.contains("application/nochrome") } ?: false }
lgpl-3.0
49ed38e372cab7fe8a4f6f1db02b4641
39.507246
116
0.715564
4.681742
false
false
false
false
SirWellington/alchemy-http
src/main/java/tech/sirwellington/alchemy/http/AlchemyMachineImpl.kt
1
7460
/* * Copyright © 2019. Sir Wellington. * 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 tech.sirwellington.alchemy.http import com.google.gson.Gson import org.slf4j.LoggerFactory import tech.sirwellington.alchemy.annotations.access.Internal import tech.sirwellington.alchemy.annotations.designs.StepMachineDesign import tech.sirwellington.alchemy.annotations.designs.StepMachineDesign.Role.MACHINE import tech.sirwellington.alchemy.arguments.Arguments.checkThat import tech.sirwellington.alchemy.arguments.assertions.positiveLong import tech.sirwellington.alchemy.http.AlchemyRequestSteps.OnFailure import tech.sirwellington.alchemy.http.AlchemyRequestSteps.OnSuccess import tech.sirwellington.alchemy.http.HttpAssertions.okResponse import tech.sirwellington.alchemy.http.HttpAssertions.ready import tech.sirwellington.alchemy.http.HttpAssertions.validResponseClass import tech.sirwellington.alchemy.http.exceptions.AlchemyHttpException import java.util.concurrent.Executor /** * * @author SirWellington */ @Internal @StepMachineDesign(role = MACHINE) internal class AlchemyMachineImpl @JvmOverloads constructor(private val async: Executor, private val gson: Gson, private val requestExecutor: HttpRequestExecutor, private val timeoutMillis: Long = Constants.DEFAULT_TIMEOUT) : AlchemyHttpStateMachine { init { checkThat(timeoutMillis).isA(positiveLong()) } private val LOG = LoggerFactory.getLogger(AlchemyMachineImpl::class.java) @Throws(IllegalArgumentException::class) override fun begin(initialRequest: HttpRequest): AlchemyRequestSteps.Step1 { val requestCopy = HttpRequest.copyOf(initialRequest) LOG.debug("Beginning HTTP request {}", requestCopy) return Step1Impl(this, requestCopy) } @Throws(IllegalArgumentException::class) override fun jumpToStep2(request: HttpRequest): AlchemyRequestSteps.Step2 { val requestCopy = HttpRequest.copyOf(request) return Step2Impl(requestCopy, this, gson) } @Throws(IllegalArgumentException::class) override fun jumpToStep3(request: HttpRequest): AlchemyRequestSteps.Step3 { val requestCopy = HttpRequest.copyOf(request) return Step3Impl(this, requestCopy) } @Throws(IllegalArgumentException::class) override fun <ResponseType> jumpToStep4(request: HttpRequest, classOfResponseType: Class<ResponseType>): AlchemyRequestSteps.Step4<ResponseType> { checkThat(classOfResponseType).isA(validResponseClass()) val requestCopy = HttpRequest.copyOf(request) return Step4Impl(this, requestCopy, classOfResponseType) } @Throws(IllegalArgumentException::class) override fun <ResponseType> jumpToStep5(request: HttpRequest, classOfResponseType: Class<ResponseType>, successCallback: OnSuccess<ResponseType>): AlchemyRequestSteps.Step5<ResponseType> { checkThat(classOfResponseType).isA(validResponseClass()) val requestCopy = HttpRequest.copyOf(request) return Step5Impl(this, requestCopy, classOfResponseType, successCallback) } override fun <ResponseType> jumpToStep6(request: HttpRequest, classOfResponseType: Class<ResponseType>, successCallback: OnSuccess<ResponseType>, failureCallback: OnFailure): AlchemyRequestSteps.Step6<ResponseType> { checkThat(classOfResponseType).isA(validResponseClass()) val requestCopy = HttpRequest.copyOf(request) return Step6Impl(this, requestCopy, classOfResponseType, successCallback, failureCallback) } override fun <ResponseType> executeSync(request: HttpRequest, classOfResponseType: Class<ResponseType>): ResponseType { LOG.debug("Executing synchronous HTTP Request {}", request) checkThat(classOfResponseType).isA(validResponseClass()) checkThat(request).isA(ready()) val response = try { requestExecutor.execute(request, gson) } catch (ex: AlchemyHttpException) { throw ex } catch (ex: Exception) { LOG.error("Failed to execute request {}", request, ex) throw AlchemyHttpException(request, ex) } checkThat(response) .throwing { ex -> AlchemyHttpException(request, response, "Http Response not OK.") } .isA(okResponse()) LOG.trace("HTTP Request {} successfully executed: {}", request, response) return if (classOfResponseType == HttpResponse::class.java) { response as ResponseType } else if (classOfResponseType == String::class.java) { response.bodyAsString() as ResponseType } else { LOG.trace("Attempting to parse response {} as {}", response, classOfResponseType) response.bodyAs(classOfResponseType) } } override fun <ResponseType> executeAsync(request: HttpRequest, classOfResponseType: Class<ResponseType>, successCallback: OnSuccess<ResponseType>, failureCallback: OnFailure) { checkThat(request).isA(ready()) checkThat(classOfResponseType).isA(validResponseClass()) LOG.debug("Submitting Async HTTP Request {}", request) async.execute block@ { LOG.debug("Starting Async HTTP Request {}", request) val response = try { executeSync(request, classOfResponseType) } catch (ex: AlchemyHttpException) { LOG.trace("Async request failed", ex) failureCallback.handleError(ex) return@block } catch (ex: Exception) { LOG.trace("Async request failed", ex) failureCallback.handleError(AlchemyHttpException(ex)) return@block } try { successCallback.processResponse(response) } catch (ex: Exception) { val message = "Success Callback threw exception" LOG.warn(message, ex) failureCallback.handleError(AlchemyHttpException(message, ex)) } } } override fun toString(): String { return "AlchemyMachineImpl(async=$async, timeoutMillis=$timeoutMillis)" } }
apache-2.0
62fb99935b0419400fd4fce6da81e7c0
36.671717
146
0.636546
5.286322
false
false
false
false
songzhw/Hello-kotlin
AdvancedJ/src/main/kotlin/algorithm/stack/MinInStack.kt
1
1779
// 设计一个有min()找出最小值的栈. 要求push, pop, min均为O(1) package algorithm.stack import java.util.* fun stackSample() { val stack = Stack<Int>() stack.push(2) stack.push(1) stack.push(5) //=> 2, 1, 5 stack.pop() //=> 2, 1 println(stack) } fun wrong() { var minValue = -1 // push()时更新minValue // 但pop()时又得再找min(), 这就不是O(1)了 } class MinInStack : Stack<Int>() { val stackStoringMin = Stack<Int>() var minValue: Int = Int.MAX_VALUE override fun push(item: Int): Int { if (item <= minValue) { stackStoringMin.push(item) minValue = item } return super.push(item) } override fun pop(): Int { val value1 = super.pop() if (value1 == stackStoringMin.peek()) { stackStoringMin.pop() } return value1 } fun min(): Int { // to avoid "java.util.EmptyStackException" if (stackStoringMin.isEmpty()) { return Int.MAX_VALUE } return stackStoringMin.peek(); } override fun toString(): String { val s1 = super.toString() val s2 = stackStoringMin.toString(); return "s1 = $s1, s2 = $s2" } } fun main() { val s = MinInStack() s.push(3) s.push(5) s.push(4) s.push(2) println(s) println("min = ${s.min()}") println("============ (after pop() )") s.pop() println(s) println("min = ${s.min()}") println("============ (after pop() )") s.pop() println(s) println("min = ${s.min()}") } /* s1 = [3, 5, 4, 2], s2 = [3, 2] min = 2 ============ (after pop() ) s1 = [3, 5, 4], s2 = [3] min = 3 ============ (after pop() ) s1 = [3, 5], s2 = [3] min = 3 */
apache-2.0
4d67ce57e803a8f7a203cf54d9185db0
18.758621
51
0.499709
3.080645
false
false
false
false
devmil/PaperLaunch
app/src/main/java/de/devmil/paperlaunch/view/utils/ViewUtils.kt
1
1809
/* * Copyright 2015 Devmil Solutions * * 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 de.devmil.paperlaunch.view.utils import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.util.TypedValue import android.view.View import android.view.ViewGroup object ViewUtils { fun getPxFromDip(context: Context, dip: Float): Float { return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, context.resources.displayMetrics) } fun disableClipping(view: View) { view.clipToOutline = false } fun disableClipping(viewGroup: ViewGroup) { disableClipping(viewGroup as View) viewGroup.clipToPadding = false viewGroup.clipChildren = false } @Suppress("unused") fun drawableToBitmap(drawable: Drawable): Bitmap { if (drawable is BitmapDrawable) { return drawable.bitmap } val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, canvas.width, canvas.height) drawable.draw(canvas) return bitmap } }
apache-2.0
3d5b03f82c44538c577391cab345fc7f
30.736842
116
0.72471
4.455665
false
false
false
false
XanderWang/XanderPanel
xanderpanel/src/main/java/com/xander/panel/ActionMenuItem.kt
1
6956
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.xander.panel import android.annotation.SuppressLint import android.content.ComponentName import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.view.ActionProvider import android.view.ContextMenu.ContextMenuInfo import android.view.MenuItem import android.view.SubMenu import android.view.View import androidx.annotation.LayoutRes class ActionMenuItem(private val context: Context, private val groupId: Int, private val id: Int, private val categoryOrder: Int, private val order: Int, private var title: CharSequence) : MenuItem { private var titleCondensed: CharSequence = "" private var iconResId = NO_ICON private var iconDrawable: Drawable? = null private var mFlags = ENABLED private var shortcutAlphabeticChar = '0' private var shortcutNumericChar = '0' private var itemIntent: Intent? = null var componentName: ComponentName? = null private var clickListener: MenuItem.OnMenuItemClickListener? = null override fun getAlphabeticShortcut(): Char { return shortcutAlphabeticChar } override fun getGroupId(): Int { return groupId } override fun getIcon(): Drawable? { return iconDrawable } override fun getIntent(): Intent? { return itemIntent } override fun getItemId(): Int { return id } override fun getMenuInfo(): ContextMenuInfo? { return null } override fun getNumericShortcut(): Char { return shortcutNumericChar } override fun getOrder(): Int { return order } override fun getSubMenu(): SubMenu? { return null } override fun getTitle(): CharSequence { return title } override fun getTitleCondensed(): CharSequence { return if (titleCondensed.isNotEmpty()) titleCondensed else title } override fun hasSubMenu(): Boolean { return false } override fun isCheckable(): Boolean { return mFlags and CHECKABLE != 0 } override fun isChecked(): Boolean { return mFlags and CHECKED != 0 } override fun isEnabled(): Boolean { return mFlags and ENABLED != 0 } override fun isVisible(): Boolean { return mFlags and HIDDEN == 0 } override fun setAlphabeticShortcut(alphaChar: Char): MenuItem { shortcutAlphabeticChar = alphaChar return this } override fun setCheckable(checkable: Boolean): MenuItem { mFlags = mFlags and CHECKABLE.inv() or if (checkable) CHECKABLE else 0 return this } fun setExclusiveCheckable(exclusive: Boolean): ActionMenuItem { mFlags = mFlags and EXCLUSIVE.inv() or if (exclusive) EXCLUSIVE else 0 return this } override fun setChecked(checked: Boolean): MenuItem { mFlags = mFlags and CHECKED.inv() or if (checked) CHECKED else 0 return this } override fun setEnabled(enabled: Boolean): MenuItem { mFlags = mFlags and ENABLED.inv() or if (enabled) ENABLED else 0 return this } override fun setIcon(icon: Drawable): MenuItem { iconDrawable = icon iconResId = NO_ICON return this } @SuppressLint("ResourceType") override fun setIcon(iconRes: Int): MenuItem { iconResId = iconRes if (iconRes > 0) iconDrawable = context.resources?.getDrawable(iconRes) return this } override fun setIntent(intent: Intent?): MenuItem { itemIntent = intent return this } override fun setNumericShortcut(numericChar: Char): MenuItem { shortcutNumericChar = numericChar return this } override fun setOnMenuItemClickListener(menuItemClickListener: MenuItem.OnMenuItemClickListener): MenuItem { clickListener = menuItemClickListener return this } override fun setShortcut(numericChar: Char, alphaChar: Char): MenuItem { shortcutNumericChar = numericChar shortcutAlphabeticChar = alphaChar return this } override fun setTitle(titleStr: CharSequence): MenuItem { title = titleStr return this } override fun setTitle(titleResId: Int): MenuItem { title = context.resources?.getString(titleResId) ?: "" return this } override fun setTitleCondensed(title: CharSequence): MenuItem { titleCondensed = title return this } override fun setVisible(visible: Boolean): MenuItem { mFlags = mFlags and HIDDEN.inv() or if (visible) 0 else HIDDEN return this } operator fun invoke(): Boolean { val clickResult = clickListener?.onMenuItemClick(this) ?: false if (clickResult) { return true } if (itemIntent != null) { context.startActivity(itemIntent) return true } return false } override fun setShowAsAction(show: Int) { // Do nothing. ActionMenuItems always show as action buttons. } override fun getActionView(): View? { return null } override fun setActionProvider(actionProvider: ActionProvider): MenuItem { throw UnsupportedOperationException() } override fun getActionProvider(): ActionProvider { throw UnsupportedOperationException() } override fun setActionView(view: View): MenuItem { return this } override fun setActionView(@LayoutRes resId: Int): MenuItem { return this } override fun setOnActionExpandListener(listener: MenuItem.OnActionExpandListener?): MenuItem { throw UnsupportedOperationException() } override fun setShowAsActionFlags(actionEnum: Int): MenuItem { return this } override fun expandActionView(): Boolean { return false } override fun collapseActionView(): Boolean { return false } override fun isActionViewExpanded(): Boolean { return false } companion object { private const val NO_ICON = 0 private const val CHECKABLE = 0x00000001 private const val CHECKED = 0x00000002 private const val EXCLUSIVE = 0x00000004 private const val HIDDEN = 0x00000008 private const val ENABLED = 0x00000010 } }
apache-2.0
af768c698b71a0a56af1f8f8477f64b4
26.282353
112
0.668056
5.047896
false
false
false
false
mopsalarm/Pr0
model/src/main/java/com/pr0gramm/app/model/bookmark/BookmarkModel.kt
1
535
package com.pr0gramm.app.model.bookmark import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Bookmark( val title: String, // now optional fields, just here for migration val filterTags: String? = null, val filterUsername: String? = null, val filterFeedType: String? = null, val trending: Boolean = false, // new optional field for migrated bookmarks @Json(name = "link") val _link: String? = null)
mit
f757d3775fe65e7bdaea4f35f217c2aa
27.157895
55
0.657944
4.212598
false
false
false
false
FHannes/intellij-community
python/educational-core/src/com/jetbrains/edu/learning/ui/StudyHint.kt
3
3325
package com.jetbrains.edu.learning.ui import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.Presentation import com.intellij.openapi.project.Project import com.jetbrains.edu.coursecreator.actions.CCEditHintAction import com.jetbrains.edu.learning.StudyTaskManager import com.jetbrains.edu.learning.StudyUtils import com.jetbrains.edu.learning.courseFormat.AnswerPlaceholder import java.util.* open class StudyHint(private val myPlaceholder: AnswerPlaceholder?, private val myProject: Project) { companion object { private val OUR_WARNING_MESSAGE = "Put the caret in the answer placeholder to get hint" private val HINTS_NOT_AVAILABLE = "There is no hint for this answer placeholder" } val studyToolWindow: StudyToolWindow protected var myShownHintNumber = 0 protected var isEditingMode = false init { val taskManager = StudyTaskManager.getInstance(myProject) if (StudyUtils.hasJavaFx() && taskManager.shouldUseJavaFx()) { studyToolWindow = StudyJavaFxToolWindow() } else { studyToolWindow = StudySwingToolWindow() } studyToolWindow.init(myProject, false) if (myPlaceholder == null) { studyToolWindow.setText(OUR_WARNING_MESSAGE) studyToolWindow.setActionToolbar(DefaultActionGroup()) } val course = taskManager.course if (course != null) { val group = DefaultActionGroup() val hints = myPlaceholder?.hints if (hints != null) { group.addAll(Arrays.asList(GoBackward(), GoForward(), CCEditHintAction(myPlaceholder))) studyToolWindow.setActionToolbar(group) setHintText(hints) } } } protected fun setHintText(hints: List<String>) { if (!hints.isEmpty()) { studyToolWindow.setText(hints[myShownHintNumber]) } else { myShownHintNumber = -1 studyToolWindow.setText(HINTS_NOT_AVAILABLE) } } inner class GoForward : AnAction("Next Hint", "Next Hint", AllIcons.Actions.Forward) { override fun actionPerformed(e: AnActionEvent) { studyToolWindow.setText(myPlaceholder!!.hints[++myShownHintNumber]) } override fun update(e: AnActionEvent) { val presentation = e.presentation updateVisibility(myPlaceholder, presentation) presentation.isEnabled = !isEditingMode && myPlaceholder != null && myShownHintNumber + 1 < myPlaceholder.hints.size } } private fun updateVisibility(myPlaceholder: AnswerPlaceholder?, presentation: Presentation) { val hasMultipleHints = myPlaceholder != null && myPlaceholder.hints.size > 1 presentation.isVisible = !StudyUtils.isStudentProject(myProject) || hasMultipleHints } inner class GoBackward : AnAction("Previous Hint", "Previous Hint", AllIcons.Actions.Back) { override fun actionPerformed(e: AnActionEvent) { studyToolWindow.setText(myPlaceholder!!.hints[--myShownHintNumber]) } override fun update(e: AnActionEvent) { val presentation = e.presentation updateVisibility(myPlaceholder, presentation) presentation.isEnabled = !isEditingMode && myShownHintNumber - 1 >= 0 } } }
apache-2.0
b7b761889d2c742dacf186c14799d6f6
33.635417
122
0.726316
4.79798
false
false
false
false
misaochan/apps-android-commons
app/src/test/kotlin/fr/free/nrw/commons/category/CategoryDaoTest.kt
3
8741
package fr.free.nrw.commons.category import android.content.ContentProviderClient import android.content.ContentValues import android.database.Cursor import android.database.MatrixCursor import android.database.sqlite.SQLiteDatabase import android.os.RemoteException import com.nhaarman.mockitokotlin2.* import fr.free.nrw.commons.BuildConfig import fr.free.nrw.commons.TestCommonsApplication import fr.free.nrw.commons.category.CategoryContentProvider.BASE_URI import fr.free.nrw.commons.category.CategoryContentProvider.uriForId import fr.free.nrw.commons.category.CategoryDao.Table.* import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.util.* @RunWith(RobolectricTestRunner::class) @Config(sdk = [21], application = TestCommonsApplication::class) class CategoryDaoTest { private val columns = arrayOf(COLUMN_ID, COLUMN_NAME, COLUMN_LAST_USED, COLUMN_TIMES_USED) private val client: ContentProviderClient = mock() private val database: SQLiteDatabase = mock() private val captor = argumentCaptor<ContentValues>() private val queryCaptor = argumentCaptor<Array<String>>() private lateinit var testObject: CategoryDao @Before fun setUp() { testObject = CategoryDao { client } } @Test fun createTable() { onCreate(database) verify(database).execSQL(CREATE_TABLE_STATEMENT) } @Test fun deleteTable() { onDelete(database) inOrder(database) { verify(database).execSQL(DROP_TABLE_STATEMENT) verify(database).execSQL(CREATE_TABLE_STATEMENT) } } @Test fun migrateTableVersionFrom_v1_to_v2() { onUpdate(database, 1, 2) // Table didnt exist before v5 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v2_to_v3() { onUpdate(database, 2, 3) // Table didnt exist before v5 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v3_to_v4() { onUpdate(database, 3, 4) // Table didnt exist before v5 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v4_to_v5() { onUpdate(database, 4, 5) verify(database).execSQL(CREATE_TABLE_STATEMENT) } @Test fun migrateTableVersionFrom_v5_to_v6() { onUpdate(database, 5, 6) // Table didnt change in version 6 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v6_to_v7() { onUpdate(database, 6, 7) // Table didnt change in version 7 verifyZeroInteractions(database) } @Test fun migrateTableVersionFrom_v7_to_v8() { onUpdate(database, 7, 8) // Table didnt change in version 8 verifyZeroInteractions(database) } @Test fun createFromCursor() { createCursor(1).let { cursor -> cursor.moveToFirst() testObject.fromCursor(cursor).let { assertEquals(uriForId(1), it.contentUri) assertEquals("showImageWithItem", it.name) assertEquals(123, it.lastUsed.time) assertEquals(2, it.timesUsed) } } } @Test fun saveExistingCategory() { createCursor(1).let { val category = testObject.fromCursor(it.apply { moveToFirst() }) testObject.save(category) verify(client).update(eq(category.contentUri), captor.capture(), isNull(), isNull()) captor.firstValue.let { cv -> assertEquals(3, cv.size()) assertEquals(category.name, cv.getAsString(COLUMN_NAME)) assertEquals(category.lastUsed.time, cv.getAsLong(COLUMN_LAST_USED)) assertEquals(category.timesUsed, cv.getAsInteger(COLUMN_TIMES_USED)) } } } @Test fun saveNewCategory() { val contentUri = CategoryContentProvider.uriForId(111) whenever(client.insert(isA(), isA())).thenReturn(contentUri) val category = Category(null, "showImageWithItem", Date(234L), 1) testObject.save(category) verify(client).insert(eq(BASE_URI), captor.capture()) captor.firstValue.let { cv -> assertEquals(3, cv.size()) assertEquals(category.name, cv.getAsString(COLUMN_NAME)) assertEquals(category.lastUsed.time, cv.getAsLong(COLUMN_LAST_USED)) assertEquals(category.timesUsed, cv.getAsInteger(COLUMN_TIMES_USED)) assertEquals(contentUri, category.contentUri) } } @Test(expected = RuntimeException::class) fun testSaveTranslatesRemoteExceptions() { whenever(client.insert(isA(), isA())).thenThrow(RemoteException("")) testObject.save(Category()) } @Test fun whenTheresNoDataFindReturnsNull_nullCursor() { whenever(client.query(any(), any(), any(), any(), any())).thenReturn(null) assertNull(testObject.find("showImageWithItem")) } @Test fun whenTheresNoDataFindReturnsNull_emptyCursor() { whenever(client.query(any(), any(), any(), any(), any())).thenReturn(createCursor(0)) assertNull(testObject.find("showImageWithItem")) } @Test fun cursorsAreClosedAfterUse() { val mockCursor: Cursor = mock() whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(mockCursor) whenever(mockCursor.moveToFirst()).thenReturn(false) testObject.find("showImageWithItem") verify(mockCursor).close() } @Test fun findCategory() { whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenReturn(createCursor(1)) val category = testObject.find("showImageWithItem") assertNotNull(category) assertEquals(uriForId(1), category?.contentUri) assertEquals("showImageWithItem", category?.name) assertEquals(123L, category?.lastUsed?.time) assertEquals(2, category?.timesUsed) verify(client).query( eq(BASE_URI), eq(ALL_FIELDS), eq("$COLUMN_NAME=?"), queryCaptor.capture(), isNull() ) assertEquals("showImageWithItem", queryCaptor.firstValue[0]) } @Test(expected = RuntimeException::class) fun findCategoryTranslatesExceptions() { whenever(client.query(any(), any(), any(), any(), anyOrNull())).thenThrow(RemoteException("")) testObject.find("showImageWithItem") } @Test(expected = RuntimeException::class) fun recentCategoriesTranslatesExceptions() { whenever(client.query(any(), any(), anyOrNull(), any(), any())).thenThrow(RemoteException("")) testObject.recentCategories(1) } @Test fun recentCategoriesReturnsEmptyList_nullCursor() { whenever(client.query(any(), any(), anyOrNull(), any(), any())).thenReturn(null) assertTrue(testObject.recentCategories(1).isEmpty()) } @Test fun recentCategoriesReturnsEmptyList_emptyCursor() { whenever(client.query(any(), any(), any(), any(), any())).thenReturn(createCursor(0)) assertTrue(testObject.recentCategories(1).isEmpty()) } @Test fun cursorsAreClosedAfterRecentCategoriesQuery() { val mockCursor: Cursor = mock() whenever(client.query(any(), any(), anyOrNull(), any(), any())).thenReturn(mockCursor) whenever(mockCursor.moveToFirst()).thenReturn(false) testObject.recentCategories(1) verify(mockCursor).close() } @Test fun recentCategoriesReturnsLessThanLimit() { whenever(client.query(any(), any(), anyOrNull(), any(), any())).thenReturn(createCursor(1)) val result = testObject.recentCategories(10) assertEquals(1, result.size) assertEquals("showImageWithItem", result[0]) verify(client).query( eq(BASE_URI), eq(ALL_FIELDS), isNull(), queryCaptor.capture(), eq("$COLUMN_LAST_USED DESC") ) assertEquals(0, queryCaptor.firstValue.size) } @Test fun recentCategoriesHonorsLimit() { whenever(client.query(any(), any(), anyOrNull(), any(), any())).thenReturn(createCursor(10)) val result = testObject.recentCategories(5) assertEquals(5, result.size) } private fun createCursor(rowCount: Int) = MatrixCursor(columns, rowCount).apply { for (i in 0 until rowCount) { addRow(listOf("1", "showImageWithItem", "123", "2")) } } }
apache-2.0
151999246fc636bbee8c32fdc8f14ee1
31.258303
102
0.641917
4.487166
false
true
false
false
JVMDeveloperID/kotlin-android-example
app/src/main/kotlin/com/gojek/sample/kotlin/internal/injectors/module/NetworkModule.kt
1
2174
package com.gojek.sample.kotlin.internal.injectors.module import com.gojek.sample.kotlin.extensions.baseUrl import com.gojek.sample.kotlin.extensions.membersOf import com.gojek.sample.kotlin.internal.data.remote.Api import dagger.Module import dagger.Provides import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.jackson.JacksonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module class NetworkModule { @Provides @Singleton fun provideApi(): Api { val retrofit: Retrofit = Retrofit.Builder().client(getOkHttpClient()) .baseUrl(baseUrl()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() return retrofit.create(membersOf<Api>()) } private fun getOkHttpClient(): OkHttpClient { val httpLoggingInterceptor: HttpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY return OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS) .readTimeout(15, TimeUnit.SECONDS) .writeTimeout(15, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .addInterceptor(getInterceptor()) .addInterceptor(httpLoggingInterceptor) .build() } private fun getInterceptor(): Interceptor { return Interceptor { chain -> val request: Request = chain.request() val builder: Request.Builder = request.newBuilder().addHeader("Content-Type", "application/json") chain.proceed(builder.build()) } } }
apache-2.0
065913eb7ad6d7e2ddac452a9ed0f9e3
40.037736
109
0.619135
5.939891
false
false
false
false
remcohoetmer/remcorepo
demo/src/main/java/nl/cerios/demo/service/CustomerServiceKotlin.kt
1
946
package nl.cerios.demo.service import java.util.logging.Logger class CustomerServiceKotlin { @Throws(ValidationException::class) suspend fun retrieveCustomerData(customerId: Int): CustomerData { return CustomerData(customerId) } fun validateCustomer(customerData: CustomerData, locationData: LocationConfig): CustomerValidation { LOG.info(Thread.currentThread().name) val validation = CustomerValidation() var status = Status.OK if (customerData.customerId != locationData.locationId) { status = Status.NOT_OK } validation.status = status when (status) { Status.NOT_OK -> validation.setMessage("Customer validation failed") Status.OK -> validation.setMessage("Customer OK") } return validation } companion object { private val LOG = Logger.getLogger(CustomerService::class.java.name) } }
apache-2.0
3bb455da4bb14c0a28cd77178c0b589e
28.59375
104
0.668076
4.753769
false
false
false
false
graphql-java/graphql-java-tools
src/main/kotlin/graphql/kickstart/tools/RootTypeInfo.kt
1
1598
package graphql.kickstart.tools import graphql.language.Description import graphql.language.SchemaDefinition import graphql.language.TypeName /** * @author Andrew Potter */ internal class RootTypeInfo private constructor( private val queryType: TypeName?, private val mutationType: TypeName?, private val subscriptionType: TypeName?, private val description: Description? ) { companion object { const val DEFAULT_QUERY_NAME = "Query" const val DEFAULT_MUTATION_NAME = "Mutation" const val DEFAULT_SUBSCRIPTION_NAME = "Subscription" fun fromSchemaDefinitions(definitions: List<SchemaDefinition>): RootTypeInfo { val queryType = definitions.lastOrNull()?.operationTypeDefinitions?.find { it.name == "query" }?.typeName val mutationType = definitions.lastOrNull()?.operationTypeDefinitions?.find { it.name == "mutation" }?.typeName val subscriptionType = definitions.lastOrNull()?.operationTypeDefinitions?.find { it.name == "subscription" }?.typeName val description = definitions.lastOrNull()?.description return RootTypeInfo(queryType, mutationType, subscriptionType, description) } } fun getQueryName() = queryType?.name ?: DEFAULT_QUERY_NAME fun getMutationName() = mutationType?.name ?: DEFAULT_MUTATION_NAME fun getSubscriptionName() = subscriptionType?.name ?: DEFAULT_SUBSCRIPTION_NAME fun getDescription() = description?.content fun isMutationRequired() = mutationType != null fun isSubscriptionRequired() = subscriptionType != null }
mit
b8bad2af459b9da29e8f5979ceebe20a
41.052632
131
0.71965
4.978193
false
false
false
false
oboehm/jfachwert
src/main/kotlin/de/jfachwert/bank/IBAN.kt
1
6611
/* * Copyright (c) 2017-2020 by Oliver Boehm * * 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 orimplied. * See the License for the specific language governing permissions and * limitations under the License. * * (c)reated 10.03.17 by oliver ([email protected]) */ package de.jfachwert.bank import de.jfachwert.AbstractFachwert import de.jfachwert.PruefzifferVerfahren import de.jfachwert.KSimpleValidator import de.jfachwert.pruefung.LengthValidator import de.jfachwert.pruefung.Mod97Verfahren import de.jfachwert.pruefung.NullValidator import org.apache.commons.lang3.StringUtils import java.util.* /** * Die IBAN (International Bank Account Number) ist eine international * standardisierte Notation fuer Bankkonten, die durch die ISO-Norm ISO 13616-1 * beschrieben wird. * * @author oboehm */ open class IBAN /** * Dieser Konstruktor ist hauptsaechlich fuer abgeleitete Klassen gedacht, * damit diese das [PruefzifferVerfahren] ueberschreiben koennen. * Man kann es auch verwenden, um das PruefzifferVerfahren abzuschalten, * indem man das [de.jfachwert.pruefung.NoopVerfahren] verwendet. * * @param iban die IBAN * @param pzVerfahren das verwendete PruefzifferVerfahren (optional) */ @JvmOverloads constructor(iban: String, pzVerfahren: KSimpleValidator<String> = VALIDATOR) : AbstractFachwert<String, IBAN>(iban, pzVerfahren) { /** * Liefert die IBAN formattiert in der DIN-Form. Dies ist die uebliche * Papierform, in der die IBAN in 4er-Bloecke formattiert wird, jeweils * durch Leerzeichen getrennt. * * @return formatierte IBAN, z.B. "DE19 1234 1234 1234 1234 12" */ val formatted: String get() { val input = unformatted + " " val buf = StringBuilder() var i = 0 while (i < unformatted.length) { buf.append(input, i, i + 4) buf.append(' ') i += 4 } return buf.toString().trim { it <= ' ' } } /** * Liefert die unformattierte IBAN. * * @return unformattierte IBA */ val unformatted: String get() = code /** * Liefert das Land, zu dem die IBAN gehoert. * * @return z.B. "de_DE" (als Locale) * @since 0.1.0 */ val land: Locale get() { val country = unformatted.substring(0, 2) var language = country.lowercase() when (country) { "AT", "CH" -> language = "de" } return Locale(language, country) } /** * Liefert die 2-stellige Pruefziffer, die nach der Laenderkennung steht. * * @return the pruefziffer * @since 0.1.0 */ val pruefziffer: String get() = MOD97.getPruefziffer(unformatted) /** * Extrahiert aus der IBAN die Bankleitzahl. * * @return Bankleitzahl * @since 0.1.0 */ val bLZ: BLZ get() { val iban = unformatted return BLZ(iban.substring(4, 12)) } /** * Extrahiert aus der IBAN die Kontonummer nach der Standard-IBAN-Regel. * Ausnahmen, wie sie z.B. in * http://www.kigst.de/media/Deutsche_Bundesbank_Uebersicht_der_IBAN_Regeln_Stand_Juni_2013.pdf * beschrieben sind, werden nicht beruecksichtigt. * * @return 10-stellige Kontonummer * @since 0.1.0 */ val kontonummer: Kontonummer get() { val iban = unformatted return Kontonummer(iban.substring(12)) } /** * Dieser Validator ist fuer die Ueberpruefung von IBANS vorgesehen. * * @since 2.2 */ class Validator : KSimpleValidator<String> { /** * Mit dieser Methode kann man eine IBAN validieren, ohne dass man erst * den Konstruktor aufrufen muss. Falls die Pruefziffer nicht stimmt, * wird eine [javax.validation.ValidationException] geworfen, wenn * die Laenge nicht uebereinstimmt eine * [de.jfachwert.pruefung.exception.InvalidLengthException]. * Die Laenge liegt zwischen 16 (Belgien) und 34 Zeichen. * * @param value die 22-stellige IBAN * @return die IBAN in normalisierter Form (ohne Leerzeichen) */ override fun validate(value: String): String { val normalized = StringUtils.remove(value, ' ').uppercase() LengthValidator.validate(normalized, 16, 34) when (normalized.substring(0, 2)) { "AT" -> LengthValidator.validate(normalized, 20) "CH" -> LengthValidator.validate(normalized, 21) "DE" -> LengthValidator.validate(normalized, 22) } return MOD97.validate(normalized) } } companion object { private val MOD97 = Mod97Verfahren.instance private val WEAK_CACHE = WeakHashMap<String, IBAN>() private val VALIDATOR: KSimpleValidator<String> = Validator() /** Konstante fuer unbekannte IBAN (aus Wikipedia, aber mit korrigierter Pruefziffer). */ @JvmField val UNBEKANNT = IBAN("DE07123412341234123412") /** Null-Konstante. */ @JvmField val NULL = IBAN("", NullValidator()) /** * Liefert eine IBAN. * * @param code gueltige IBAN-Nummer * @return IBAN */ @JvmStatic fun of(code: String): IBAN { return WEAK_CACHE.computeIfAbsent(code) { iban: String -> IBAN(iban) } } /** * Mit dieser Methode kann man eine IBAN validieren, ohne dass man erst * den Konstruktor aufrufen muss. Falls die Pruefziffer nicht stimmt, * wird eine [javax.validation.ValidationException] geworfen, wenn * die Laenge nicht uebereinstimmt eine * [de.jfachwert.pruefung.exception.InvalidLengthException]. * Die Laenge liegt zwischen 16 (Belgien) und 34 Zeichen. * * @param iban die 22-stellige IBAN * @return die IBAN in normalisierter Form (ohne Leerzeichen) */ @JvmStatic fun validate(iban: String): String { return VALIDATOR.validate(iban) } } }
apache-2.0
a34448a27ef0c52339473da422221772
32.563452
144
0.621691
3.828025
false
false
false
false
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/forms/KatydidInputSearch.kt
1
2863
// // (C) Copyright 2017-2019 Martin E. Nordberg III // Apache 2.0 License // package i.katydid.vdom.elements.forms import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl import i.katydid.vdom.elements.KatydidHtmlElementImpl import o.katydid.vdom.builders.KatydidAttributesContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Virtual node for an input type="search" element. */ internal class KatydidInputSearch<Msg>( phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>, selector: String?, key: Any?, accesskey: Char?, autocomplete: String?, autofocus: Boolean?, contenteditable: Boolean?, dir: EDirection?, dirname: String?, disabled: Boolean?, draggable: Boolean?, form: String?, hidden: Boolean?, lang: String?, list: String?, maxlength: Int?, minlength: Int?, name: String?, pattern: String?, placeholder: String?, readonly: Boolean?, required: Boolean?, size: Int?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, value: String?, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) : KatydidHtmlElementImpl<Msg>(selector, key ?: name, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate) { init { phrasingContent.contentRestrictions.confirmInteractiveContentAllowed() require(maxlength == null || maxlength >= 0) { "Attribute maxlength must be non-negative." } require(minlength == null || minlength >= 0) { "Attribute minlength must be non-negative." } require(size == null || size >= 0) { "Attribute size must be non-negative." } setAttribute("autocomplete", autocomplete) setBooleanAttribute("autofocus", autofocus) setAttribute("dirname", dirname) setBooleanAttribute("disabled", disabled) setAttribute("form", form) setAttribute("list", list) setNumberAttribute("maxlength", maxlength) setNumberAttribute("minlength", minlength) setAttribute("name", name) setAttribute("pattern", pattern) setAttribute("placeholder", placeholder) setBooleanAttribute("readonly", readonly) setBooleanAttribute("required", required) setNumberAttribute("size", size) setAttribute("value", value) setAttribute("type", "search") phrasingContent.attributesContent(this).defineAttributes() this.freeze() } //// override val nodeName = "INPUT" } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
9ed9c08fa6a004ad8c21b8799a17a27f
31.534091
119
0.610898
5.186594
false
false
false
false
oldergod/red
app/src/main/java/com/benoitquenaudon/tvfoot/red/app/common/notification/MatchNotificationHelper.kt
1
2592
package com.benoitquenaudon.tvfoot.red.app.common.notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.TaskStackBuilder import android.content.Context import android.content.Intent import android.os.Build import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import com.benoitquenaudon.tvfoot.red.R import com.benoitquenaudon.tvfoot.red.app.data.entity.Match import com.benoitquenaudon.tvfoot.red.app.domain.match.MatchActivity import com.benoitquenaudon.tvfoot.red.app.domain.match.MatchDisplayable class MatchNotificationHelper( private val context: Context, private val match: Match ) { init { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel(context) } } fun publishMatchStarting() { val intent = Intent(context, MatchActivity::class.java).apply { putExtra(Match.MATCH_ID, match.id) } val stackBuilder = TaskStackBuilder.create(context).apply { addParentStack(MatchActivity::class.java) addNextIntent(intent) } val pendingIntent = stackBuilder .getPendingIntent(NotificationRepository.matchIdAsInt(match.id), PendingIntent.FLAG_UPDATE_CURRENT) val matchDisplayable = MatchDisplayable.fromMatch(match) val notificationBuilder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL) .setSmallIcon(R.drawable.logo) .setColor(ContextCompat.getColor(context, R.color.colorPrimary)) .setAutoCancel(true) .setContentIntent(pendingIntent) .setContentTitle(matchDisplayable.headline) .setContentText(matchDisplayable.matchDay) .setSubText(matchDisplayable.competition) .setWhen(match.startAt.time) (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) .notify(NotificationRepository.matchIdAsInt(match.id), notificationBuilder.build()) } @RequiresApi(api = Build.VERSION_CODES.O) private fun createNotificationChannel(context: Context) { val channel = NotificationChannel(NOTIFICATION_CHANNEL, context.getString(R.string.notification_match_starting_channel_name), NotificationManager.IMPORTANCE_DEFAULT).also { it.setShowBadge(false) } (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager) .createNotificationChannel(channel) } companion object Constant { const val NOTIFICATION_CHANNEL = "match_starting" } }
apache-2.0
f62d96f13f4b4bf78508ddef240ad104
35
91
0.763889
4.653501
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/api/security/Domain.kt
1
9554
package pl.wendigo.chrome.api.security import kotlinx.serialization.json.Json /** * Security * * @link Protocol [Security](https://chromedevtools.github.io/devtools-protocol/tot/Security) domain documentation. */ class SecurityDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) : pl.wendigo.chrome.protocol.Domain("Security", """Security""", connection) { /** * Disables tracking security state changes. * * @link Protocol [Security#disable](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-disable) method documentation. */ fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Enables tracking security state changes. * * @link Protocol [Security#enable](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-enable) method documentation. */ fun enable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.enable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Enable/disable whether all certificate errors should be ignored. * * @link Protocol [Security#setIgnoreCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setIgnoreCertificateErrors) method documentation. */ @pl.wendigo.chrome.protocol.Experimental fun setIgnoreCertificateErrors(input: SetIgnoreCertificateErrorsRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.setIgnoreCertificateErrors", Json.encodeToJsonElement(SetIgnoreCertificateErrorsRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Handles a certificate error that fired a certificateError event. * * @link Protocol [Security#handleCertificateError](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-handleCertificateError) method documentation. */ @Deprecated(level = DeprecationLevel.WARNING, message = "handleCertificateError is deprecated.") fun handleCertificateError(input: HandleCertificateErrorRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.handleCertificateError", Json.encodeToJsonElement(HandleCertificateErrorRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * Enable/disable overriding certificate errors. If enabled, all certificate error events need to be handled by the DevTools client and should be answered with `handleCertificateError` commands. * * @link Protocol [Security#setOverrideCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setOverrideCertificateErrors) method documentation. */ @Deprecated(level = DeprecationLevel.WARNING, message = "setOverrideCertificateErrors is deprecated.") fun setOverrideCertificateErrors(input: SetOverrideCertificateErrorsRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.setOverrideCertificateErrors", Json.encodeToJsonElement(SetOverrideCertificateErrorsRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer()) /** * There is a certificate error. If overriding certificate errors is enabled, then it should be handled with the `handleCertificateError` command. Note: this event does not fire if the certificate error has been allowed internally. Only one client per target should override certificate errors at the same time. */ fun certificateError(): io.reactivex.rxjava3.core.Flowable<CertificateErrorEvent> = connection.events("Security.certificateError", CertificateErrorEvent.serializer()) /** * The security state of the page changed. */ fun visibleSecurityStateChanged(): io.reactivex.rxjava3.core.Flowable<VisibleSecurityStateChangedEvent> = connection.events("Security.visibleSecurityStateChanged", VisibleSecurityStateChangedEvent.serializer()) /** * The security state of the page changed. */ fun securityStateChanged(): io.reactivex.rxjava3.core.Flowable<SecurityStateChangedEvent> = connection.events("Security.securityStateChanged", SecurityStateChangedEvent.serializer()) } /** * Represents request frame that can be used with [Security#setIgnoreCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setIgnoreCertificateErrors) operation call. * * Enable/disable whether all certificate errors should be ignored. * @link [Security#setIgnoreCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setIgnoreCertificateErrors) method documentation. * @see [SecurityDomain.setIgnoreCertificateErrors] */ @kotlinx.serialization.Serializable data class SetIgnoreCertificateErrorsRequest( /** * If true, all certificate errors will be ignored. */ val ignore: Boolean ) /** * Represents request frame that can be used with [Security#handleCertificateError](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-handleCertificateError) operation call. * * Handles a certificate error that fired a certificateError event. * @link [Security#handleCertificateError](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-handleCertificateError) method documentation. * @see [SecurityDomain.handleCertificateError] */ @kotlinx.serialization.Serializable data class HandleCertificateErrorRequest( /** * The ID of the event. */ val eventId: Int, /** * The action to take on the certificate error. */ val action: CertificateErrorAction ) /** * Represents request frame that can be used with [Security#setOverrideCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setOverrideCertificateErrors) operation call. * * Enable/disable overriding certificate errors. If enabled, all certificate error events need to be handled by the DevTools client and should be answered with `handleCertificateError` commands. * @link [Security#setOverrideCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setOverrideCertificateErrors) method documentation. * @see [SecurityDomain.setOverrideCertificateErrors] */ @kotlinx.serialization.Serializable data class SetOverrideCertificateErrorsRequest( /** * If true, certificate errors will be overridden. */ val override: Boolean ) /** * There is a certificate error. If overriding certificate errors is enabled, then it should be handled with the `handleCertificateError` command. Note: this event does not fire if the certificate error has been allowed internally. Only one client per target should override certificate errors at the same time. * * @link [Security#certificateError](https://chromedevtools.github.io/devtools-protocol/tot/Security#event-certificateError) event documentation. */ @kotlinx.serialization.Serializable data class CertificateErrorEvent( /** * The ID of the event. */ val eventId: Int, /** * The type of the error. */ val errorType: String, /** * The url that was requested. */ val requestURL: String ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Security" override fun eventName() = "certificateError" } /** * The security state of the page changed. * * @link [Security#visibleSecurityStateChanged](https://chromedevtools.github.io/devtools-protocol/tot/Security#event-visibleSecurityStateChanged) event documentation. */ @kotlinx.serialization.Serializable data class VisibleSecurityStateChangedEvent( /** * Security state information about the page. */ val visibleSecurityState: VisibleSecurityState ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Security" override fun eventName() = "visibleSecurityStateChanged" } /** * The security state of the page changed. * * @link [Security#securityStateChanged](https://chromedevtools.github.io/devtools-protocol/tot/Security#event-securityStateChanged) event documentation. */ @kotlinx.serialization.Serializable data class SecurityStateChangedEvent( /** * Security state. */ val securityState: SecurityState, /** * True if the page was loaded over cryptographic transport such as HTTPS. */ val schemeIsCryptographic: Boolean, /** * List of explanations for the security state. If the overall security state is `insecure` or `warning`, at least one corresponding explanation should be included. */ val explanations: List<SecurityStateExplanation>, /** * Information about insecure content on the page. */ val insecureContentStatus: InsecureContentStatus, /** * Overrides user-visible description of the state. */ val summary: String? = null ) : pl.wendigo.chrome.protocol.Event { override fun domain() = "Security" override fun eventName() = "securityStateChanged" }
apache-2.0
e42dfc0f1e110cc5ad1415dbcd23c82a
44.495238
390
0.761671
4.662762
false
false
false
false
dantman/gradle-mdicons
src/test/kotlin/com/tmiyamon/mdicons/repository/MaterialDesignIconsSpecs.kt
1
5438
package com.tmiyamon.mdicons.repository import com.tmiyamon.mdicons.Extension import com.tmiyamon.mdicons.ext.pathJoin import org.jetbrains.spek.api.Spek import java.io.File import kotlin.test.assertEquals class MaterialDesignIconsSpecs: Spek() { init { given("MaterialDesignIcons") { val repository = MaterialDesignIcons(File("/tmp")) val filename = "ic_camera_white_16dp.png" on(".convertToDensityDirNameFrom") { it("returns density dir name with density") { assertEquals( MaterialDesignIcons.convertToDensityDirNameFrom("mdpi"), "${MaterialDesignIcons.DENSITY_DIR_NAME_PREFIX}mdpi" ) } } on(".parseFileName") { it("parses file name into name, color, size and ext") { assertEquals( MaterialDesignIcons.parseFileName(filename), listOf("ic_camera", "white", "16dp", "png") ) } } on(".buildFileName") { it("builds file name with name, color, size and ext") { assertEquals( MaterialDesignIcons.buildFileName("a","b","c","d"), "a_b_c.d" ) } } on("#eachIconDir") { it("traverses each icon directories with specific categories and densities") { val categories = arrayOf("a", "b") val densities = arrayOf("c", "d") val expected = listOf( listOf("a","c", File(repository.rootDir, pathJoin("a", "drawable-c"))), listOf("a","d", File(repository.rootDir, pathJoin("a", "drawable-d"))), listOf("b","c", File(repository.rootDir, pathJoin("b", "drawable-c"))), listOf("b","d", File(repository.rootDir, pathJoin("b", "drawable-d"))) ) var i = 0 val block = { c: String, d: String, dir: File -> assertEquals(listOf(c, d, dir), expected[i++]) } repository.eachIconDir(categories, densities, block) } } on("#newIcon") { it("returns new icon with category, density and file name") { val icon = repository.newIcon("a", "b", filename) assertEquals(icon.category, "a") assertEquals(icon.density, "b") assertEquals(icon.name, "ic_camera") assertEquals(icon.color, "white") assertEquals(icon.size, "16dp") assertEquals(icon.ext, "png") } } } given("Icon") { val repository = MaterialDesignIcons(File("/tmp")) val filename = "ic_camera_white_16dp.png" val icon = repository.newIcon("a", "b", filename) on("#getFileName") { it("returns file name") { assertEquals(icon.getFileName(), filename) } } on("#getSourceRelativePath") { it("returns source relative path") { assertEquals(icon.getSourceRelativePath(), pathJoin("a", "drawable-b", filename)) } } on("#getDestinationRelativePath") { it("returns destination relative path") { assertEquals(icon.getDestinationRelativePath(), pathJoin(Extension.PROJECT_RESOURCE_RELATIVE_PATH, "drawable-b", filename)) } } on("#toFile") { it("returns file") { assertEquals(icon.toFile(), File(repository.rootDir, pathJoin("a", "drawable-b", filename))) } } on("#isBaseIcon") { it("return true if its color and density match to the base ones") { val baseIcon = repository.newIcon( "a", MaterialDesignIcons.BASE_DENSITY, MaterialDesignIcons.buildFileName("b", MaterialDesignIcons.BASE_COLOR, "c", "d") ) assertEquals(true, baseIcon.isBaseIcon()) } it("returns false if its density is not base one") { val notBaseIcon = repository.newIcon( "a", "notBaseDensity", MaterialDesignIcons.buildFileName("b", MaterialDesignIcons.BASE_COLOR, "c", "d") ) assertEquals(false, notBaseIcon.isBaseIcon()) } it("returns false if its color is not base one") { val notBaseIcon = repository.newIcon( "a", MaterialDesignIcons.BASE_DENSITY, MaterialDesignIcons.buildFileName("b", "notBaseColor", "c", "d") ) assertEquals(false, notBaseIcon.isBaseIcon()) } } on("#newIconVariantsForDensitires") { it("returns icon variants for densities") { assertEquals( icon.newIconVariantsForDensities(arrayOf("a", "b")), listOf( repository.newIcon("a", "a", filename), repository.newIcon("a", "b", filename) ) ) } } } }}
apache-2.0
aed0629cbb0e39d3a10bfd3043694c10
36.246575
139
0.495035
4.786972
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-tensorflow/src/main/kotlin/org/nd4j/samediff/frameworkimport/tensorflow/rule/attribute/TensorflowListNumberToListNumber.kt
1
5059
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * * License for the specific language governing permissions and limitations * * under the License. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.tensorflow.rule.attribute import org.nd4j.ir.OpNamespace import org.nd4j.samediff.frameworkimport.argDescriptorType import org.nd4j.samediff.frameworkimport.findOp import org.nd4j.samediff.frameworkimport.ir.IRAttribute import org.nd4j.samediff.frameworkimport.isNd4jTensorName import org.nd4j.samediff.frameworkimport.isOutputFrameworkAttributeName import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder import org.nd4j.samediff.frameworkimport.process.MappingProcess import org.nd4j.samediff.frameworkimport.rule.MappingRule import org.nd4j.samediff.frameworkimport.rule.attribute.AttributeValueType import org.nd4j.samediff.frameworkimport.rule.attribute.ListNumberToListNumber import org.nd4j.samediff.frameworkimport.tensorflow.ir.TensorflowIRAttr import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowAttributeName import org.nd4j.samediff.frameworkimport.tensorflow.ir.isTensorflowTensorName import org.nd4j.samediff.frameworkimport.tensorflow.ir.tensorflowAttributeValueTypeFor import org.tensorflow.framework.* @MappingRule("tensorflow","listnumbertolistnumber","attribute") class TensorflowListNumberToListNumber(mappingNamesToPerform: Map<String, String>, transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>>) : ListNumberToListNumber<GraphDef, OpDef, NodeDef, OpDef.AttrDef, AttrValue, TensorProto, DataType>(mappingNamesToPerform, transformerArgs) { override fun createIRAttribute(name: String, attrDef: OpDef.AttrDef, attributeValueType: AttrValue): IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType> { return TensorflowIRAttr(inputAttributeValue = attributeValueType, inputAttributeDef = attrDef) } override fun convertAttributesReverse(allInputArguments: List<OpNamespace.ArgDescriptor>, inputArgumentsToProcess: List<OpNamespace.ArgDescriptor>): List<IRAttribute<OpDef.AttrDef, AttrValue, TensorProto, DataType>> { TODO("Not yet implemented") } override fun isInputFrameworkTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowTensorName(name, opDef) } override fun isNd4jTensorName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isNd4jTensorName(name,nd4jOpDescriptor) } override fun isInputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return isTensorflowAttributeName(name, opDef) } override fun isOutputFrameworkAttributeName(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): Boolean { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return isOutputFrameworkAttributeName(name,nd4jOpDescriptor) } override fun argDescriptorType(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): OpNamespace.ArgDescriptor.ArgType { val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess.opName()) return argDescriptorType(name,nd4jOpDescriptor) } override fun attributeValueTypeFor(name: String, mappingProcess: MappingProcess<GraphDef, OpDef, NodeDef, TensorProto, OpDef.AttrDef, AttrValue, DataType>): AttributeValueType { val opDef = OpDescriptorLoaderHolder.listForFramework<OpDef>("tensorflow")[mappingProcess.inputFrameworkOpName()]!! return tensorflowAttributeValueTypeFor(attributeName = name, opDef = opDef) } }
apache-2.0
af0020857e975e4920c91314ebb65d08
63.871795
287
0.772682
4.984236
false
false
false
false
AndroidX/androidx
activity/activity-compose/samples/src/main/java/androidx/activity/compose/samples/RememberLauncherForActivityResult.kt
3
1756
/* * 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.activity.compose.samples import android.graphics.Bitmap import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.launch import androidx.annotation.Sampled import androidx.compose.foundation.Image import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.asImageBitmap @Sampled @Composable fun RememberLauncherForActivityResult() { val result = remember { mutableStateOf<Bitmap?>(null) } val launcher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicturePreview()) { result.value = it } Button(onClick = { launcher.launch() }) { Text(text = "Take a picture") } result.value?.let { image -> Image(image.asImageBitmap(), null, modifier = Modifier.fillMaxWidth()) } }
apache-2.0
babc18bef87fafd55ed1420c7c01823b
34.857143
100
0.776196
4.584856
false
false
false
false
satamas/fortran-plugin
src/main/kotlin/org/jetbrains/fortran/ide/typing/FortranEnterHandler.kt
1
7687
package org.jetbrains.fortran.ide.typing import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.actionSystem.EditorActionHandler import com.intellij.openapi.util.Ref import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.fortran.lang.psi.* import org.jetbrains.fortran.lang.psi.ext.* class FortranEnterHandler : EnterHandlerDelegateAdapter() { override fun preprocessEnter( file: PsiFile, editor: Editor, caretOffsetRef: Ref<Int>, caretAdvance: Ref<Int>, dataContext: DataContext, originalHandler: EditorActionHandler? ): EnterHandlerDelegate.Result? { val superProcessor = super.postProcessEnter(file, editor, dataContext) // we don't want to deal with fixed form now if (file is FortranFixedFormFile) return superProcessor val offset = editor.caretModel.offset val lineStartOffset = editor.caretModel.visualLineStart val indentString = CodeStyleManager.getInstance(file.project)!!.getLineIndent(editor.document, lineStartOffset) val previousElement = file.findElementAt(offset - 1) val constructOrUnit = PsiTreeUtil.getParentOfType(previousElement, FortranExecutableConstruct::class.java, FortranProgramUnit::class.java, FortranDeclarationConstruct::class.java ) // check we are not in the middle of the line val endFirstStmtOffset = constructOrUnit?.firstChild?.textRange?.endOffset ?: return superProcessor if (offset < endFirstStmtOffset) return superProcessor when (constructOrUnit) { // program units is FortranProgramUnit -> if ((constructOrUnit.beginUnitStmt != null && constructOrUnit.endUnitStmt == null) || sameTypeParentUnitHasNoEnd(constructOrUnit)) { val beginStmt = constructOrUnit.beginUnitStmt!! val programUnitName = beginStmt.entityDecl?.name val unit = constructOrUnit.unitType!! insertEndString(editor, offset, indentString, unit, programUnitName, beginStmtStyle(beginStmt)) return EnterHandlerDelegate.Result.DefaultForceIndent } // declaration constructs is FortranEnumDef -> if (constructOrUnit.endEnumStmt == null) { val enumStmt = constructOrUnit.enumDefStmt insertEndString(editor, offset, indentString, "enum", null, beginStmtStyle(enumStmt)) return EnterHandlerDelegate.Result.DefaultForceIndent } is FortranDerivedTypeDef -> if (constructOrUnit.endTypeStmt == null) { val typeStmt = constructOrUnit.derivedTypeStmt val typeName = typeStmt.typeDecl.name insertEndString(editor, offset, indentString, "type", typeName, beginStmtStyle(typeStmt)) return EnterHandlerDelegate.Result.DefaultForceIndent } is FortranInterfaceBlock -> if (constructOrUnit.endInterfaceStmt == null) { val interfaceStmt = constructOrUnit.interfaceStmt val interfaceName = interfaceStmt.entityDecl?.name insertEndString(editor, offset, indentString, "interface", interfaceName, beginStmtStyle(interfaceStmt)) return EnterHandlerDelegate.Result.DefaultForceIndent } // labeled do is not like all other peoples do is FortranLabeledDoConstruct -> if (constructOrUnit.endConstructStmt == null && constructOrUnit.doTermActionStmt == null && constructOrUnit.labeledDoTermConstract == null) { val beginStmt = constructOrUnit.beginConstructStmt!! val constructName = beginStmt.constructNameDecl?.name val indentStringWithLabel = indentString + constructOrUnit.labelDoStmt.label.text + " " insertEndString(editor, offset, indentStringWithLabel, constructOrUnit.constructType, constructName, beginStmtStyle(beginStmt)) return EnterHandlerDelegate.Result.DefaultForceIndent } // executable constructs is FortranExecutableConstruct -> if (constructOrUnit.endConstructStmt == null || sameTypeParentConstructHasNoEnd(constructOrUnit)) { val beginStmt = constructOrUnit.beginConstructStmt!! val constructName = beginStmt.constructNameDecl?.name insertEndString(editor, offset, indentString, constructOrUnit.constructType, constructName, beginStmtStyle(beginStmt)) return EnterHandlerDelegate.Result.DefaultForceIndent } } return super.postProcessEnter(file, editor, dataContext) } private fun sameTypeParentUnitHasNoEnd(unit: FortranProgramUnit): Boolean { var parent = PsiTreeUtil.getParentOfType(unit, FortranProgramUnit::class.java) while (parent != null) { if (parent.unitType != unit.unitType) return false if (parent.endUnitStmt == null) return true parent = PsiTreeUtil.getParentOfType(parent, FortranProgramUnit::class.java) } return false } private fun sameTypeParentConstructHasNoEnd(construct: FortranExecutableConstruct): Boolean { // construct parent is block and blocks parent may be construct var grandparent = construct.parent?.parent while (grandparent != null) { if (grandparent !is FortranExecutableConstruct || grandparent.constructType != construct.constructType) return false if (grandparent.endConstructStmt == null) return true grandparent = grandparent.parent?.parent } return false } private enum class KeywordStyle { UNKNOWN, UPPERCASE, LOWERCASE, CAMELCASE } private fun beginStmtStyle(stmt: FortranStmt): KeywordStyle { val keywordText = stmt.node.findChildByType(FortranTokenType.KEYWORD)?.text ?: return KeywordStyle.UNKNOWN return when { keywordText.all { it.isUpperCase() } -> KeywordStyle.UPPERCASE keywordText.all { it.isLowerCase() } -> KeywordStyle.LOWERCASE keywordText.first().isUpperCase() && keywordText.substring(1).all { it.isLowerCase() } -> KeywordStyle.CAMELCASE else -> KeywordStyle.UNKNOWN } } private fun formatEndString(endString: String, style: KeywordStyle): String { return when (style) { KeywordStyle.UPPERCASE -> endString.toUpperCase() KeywordStyle.CAMELCASE -> endString.capitalize() else -> endString } } private fun insertEndString(editor: Editor, offset: Int, indentString: String?, type: String?, name: String?, style: KeywordStyle ) { val end = formatEndString("end", style) val formattedType = formatEndString(type ?: "", style) if (name != null) { editor.document.insertString(offset, "\n$indentString$end $formattedType $name") } else { editor.document.insertString(offset, "\n$indentString$end $formattedType") } } }
apache-2.0
c267324f5786603142e97d0318da87e2
46.751553
144
0.659035
5.124667
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/screens/pastry/PastryTestScreen.kt
1
3904
package com.teamwizardry.librarianlib.facade.test.screens.pastry import com.teamwizardry.librarianlib.core.util.rect import com.teamwizardry.librarianlib.core.util.vec import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.layer.GuiLayerEvents import com.teamwizardry.librarianlib.facade.layers.StackLayout import com.teamwizardry.librarianlib.facade.pastry.Pastry import com.teamwizardry.librarianlib.facade.pastry.PastryBackgroundStyle import com.teamwizardry.librarianlib.facade.pastry.PastryScreen import com.teamwizardry.librarianlib.facade.pastry.layers.PastryBackground import com.teamwizardry.librarianlib.facade.pastry.layers.PastryButton import com.teamwizardry.librarianlib.facade.pastry.layers.PastryLabel import com.teamwizardry.librarianlib.facade.test.screens.pastry.tests.* import net.minecraft.text.Text class PastryTestScreen(title: Text): PastryScreen(title) { val tests: Map<Class<*>, String> = mutableMapOf( PastryTestButton::class.java to "Button", PastryTestDropdown::class.java to "Dropdown", PastryTestProgress::class.java to "Progress", PastryTestSwitches::class.java to "Switches", PastryTestTooltips::class.java to "Tooltips", PastryTestScroll::class.java to "Scroll Pane", PastryTestTabs::class.java to "Tabs", PastryTestDynamicBackground::class.java to "Dynamic Background", PastryTestColorPicker::class.java to "Color Picker", ) val selector = StackLayout.build() .vertical() .alignTop() .alignCenterX() .fit() .also { selector -> tests.forEach { (clazz, name) -> val label = PastryLabel(0, 0, name) val item = GuiLayer(0, 0, label.widthi, Pastry.lineHeight) item.add(label) item.BUS.hook<GuiLayerEvents.LayoutChildren> { label.frame = item.bounds } item.BUS.hook<GuiLayerEvents.MouseClick> { selectTest(clazz, name) } selector.add(item) } } .build() val contentBackground = PastryBackground(PastryBackgroundStyle.LIGHT_INSET, 0, 0, 0, 0) val contentArea = GuiLayer() val selectorArea = GuiLayer() val selectedTestLabel = PastryLabel(0, 1, "") val selectTestButton = PastryButton("Select Test", 1, 1) { selectorArea.isVisible = true contentArea.isVisible = false } var test = GuiLayer() init { main.size = vec(200, 200) main.add(contentBackground, contentArea, selectorArea, selectTestButton, selectedTestLabel) main.BUS.hook<GuiLayerEvents.LayoutChildren> { contentBackground.frame = main.bounds.offset(0, selectTestButton.frame.maxY + 1, 0, 0) selectedTestLabel.frame = rect( selectTestButton.frame.maxX + 5, 1, main.width - selectTestButton.width - 2, Pastry.lineHeight ) contentArea.frame = contentBackground.frame.offset(2, 2, -2, -2) selectorArea.frame = contentBackground.frame.offset(2, 2, -2, -2) } contentArea.add(test) contentArea.BUS.hook<GuiLayerEvents.LayoutChildren> { test.frame = contentArea.bounds } contentArea.isVisible = false selectorArea.add(selector) selectorArea.BUS.hook<GuiLayerEvents.LayoutChildren> { selector.frame = selectorArea.bounds } } fun selectTest(testClass: Class<*>, testName: String) { selectorArea.isVisible = false contentArea.isVisible = true contentArea.remove(this.test) this.test = testClass.newInstance() as GuiLayer contentArea.add(this.test) contentArea.markLayoutDirty() selectedTestLabel.text = testName } }
lgpl-3.0
1aeafe2f23d874e8cd37e3d84747b490
38.04
99
0.667008
4.352285
false
true
false
false
kennydo/papika2
src/main/kotlin/net/hanekawa/papika/fromslack/PapikaFromSlack.kt
1
2167
package net.hanekawa.papika.fromslack import com.timgroup.statsd.NonBlockingStatsDClient import net.hanekawa.papika.common.getLogger import net.hanekawa.papika.common.slack.SlackClient import org.apache.kafka.clients.producer.KafkaProducer import java.util.* class PapikaFromSlackBridge(val config: Config) { companion object { val LOG = getLogger(this::class.java) } fun run() { LOG.info("Starting the bridge from slack to kafka") val statsd = NonBlockingStatsDClient("papika.fromslack", config.statsDHost, config.statsDPort) LOG.info("Connecting to Kafka: {}", config.kafkaBootstrapServers) LOG.info("Sending Slack events to topic: {}", config.fromSlackTopic) val kafkaProducer = createKafkaProducer(config.kafkaBootstrapServers) LOG.info("Connecting to Zookeeper: {}", config.zookeeperConnect) val leaderCandidate = LeaderCandidate(statsd, config.zookeeperConnect) leaderCandidate.run() val eventHandler = SlackEventHandler(statsd, kafkaProducer, config.fromSlackTopic, leaderCandidate) LOG.info("Connecting to Slack") val slackClient = SlackClient(statsd, config.slackApiToken) slackClient.buildRtmSession(eventHandler).run() } private fun createKafkaProducer(bootstrapServers: String): KafkaProducer<String, String> { val props = Properties() props.put("bootstrap.servers", bootstrapServers) props.put("acks", "all") props.put("retries", 5) props.put("linger.ms", 0) props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer") props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer") val producer = KafkaProducer<String, String>(props) Runtime.getRuntime().addShutdownHook(object : Thread() { override fun run() { LOG.info("Closing Kafka producer") producer.close() } }) return producer } } fun main(args: Array<String>) { val config = Config.load() val bridge = PapikaFromSlackBridge(config) bridge.run() }
mit
a6e820ffcaa9641c3c813487da0f89a5
35.116667
107
0.688048
4.104167
false
true
false
false
kiruto/debug-bottle
demo/src/main/kotlin/me/chunyu/dev/yuriel/kotdebugtool/ContentInjector.kt
1
5238
package me.chunyu.dev.yuriel.kotdebugtool import android.app.Activity import android.content.Context import android.content.Intent import android.os.Process import android.view.View import android.view.animation.AnimationUtils import android.widget.Toast import com.exyui.android.debugbottle.components.injector.Injector import com.exyui.android.debugbottle.components.injector.QuickEntry /** * Created by yuriel on 9/4/16. * * This example file shows how to inject an Intent a Runnable, or a QuickEntry */ @Suppress("unused") class ContentInjector: Injector() { override fun inject() { /** * To inject a simple activity entry, just need call "put" function. * The "activity" object is current top Activity. * If current activity is not shown at foreground, may return null. * * About "put" function: * - first parameter for the Intent. * - second parameter for the name of entry. * All arguments to start activity, must put into Intent. */ put (Intent(activity, DemoActivity::class.java), "Demo Activity entry example") put (Intent(activity, ExampleActivity::class.java), "Setting Activity example") /** * To inject a Runnable, also need call "put" function. * Also can use "activity" as a context, and activity also return null if it'is not shown at foreground * This example just show a toast, but you may do many other amazing things. * * About "put" function: * - first parameter is the target Runnable object. * - second parameter is the name of Runnable entry. */ put (Runnable { Toast.makeText(activity, "Run!", Toast.LENGTH_SHORT).show() }, "Toast a \"Run!\"") /** * Like this, you can clean caches in runnable. */ put (Runnable { // Do something to clean the caches. // if done, Toast.makeText(activity, "Cache files delete!", Toast.LENGTH_SHORT).show() }, "Delete cache files example") /** * Like this, you can kill a task. */ put (Runnable { Process.killProcess(Process.myPid()) }, "Kill process example") /** * Here is the example of how to use QuickEntry. * To implement QuickEntry, you may extend class "QuickEntry.OnActivityDisplayedListener". * To add entry, just call "quickEntry" function. * * About "quickEntry" function: * - first parameter is the name of entry. * - second parameter is the object of QuickEntry's implementation. * * About "OnActivityDisplayedListener" interface: * - "shouldShowEntry" function returns result that if this entry shows at panel now. * - "run" function is the entry. * - "description" function returns the subtitle of this entry, may return null if it's not needed. * * This case shows how to work with current context (as an Activity). */ quickEntry ("Show Activity's package name", object: QuickEntry.OnActivityDisplayedListener { override fun shouldShowEntry(activity: Activity?) = true override fun run(context: Context?) { Toast.makeText(context, context?.javaClass?.name, Toast.LENGTH_LONG).show() } override fun description() = "This case shows how to run a function with context." }) /** * This case shows how to hack or test current Activity. * If the DemoActivity is not visible at foreground, this entry would not shown. * If current Activity is DemoActivity, entry may displayed and run correctly. */ quickEntry("Show address of title TextView 'Showcases'", object: QuickEntry.OnActivityDisplayedListener { override fun shouldShowEntry(activity: Activity?) = activity is DemoActivity override fun run(context: Context?) { if (context is DemoActivity) { val animation = AnimationUtils.loadAnimation(context, R.anim.shake_anim) fun View.shake() { startAnimation(animation) } val view: View = context.findViewById(R.id.tv_title)?: return view.shake() Toast.makeText(context, view.toString(), Toast.LENGTH_LONG).show() } } override fun description() = "This case shows how to run a function with views" }) /** * This case shows how to call a function in DemoActivity. */ quickEntry("Shake views in Activity without border", object: QuickEntry.OnActivityDisplayedListener { override fun shouldShowEntry(activity: Activity?) = activity is DemoActivity override fun run(context: Context?) { if (context is DemoActivity) { context.quickEntryTestFunction() } } override fun description() = "This case shows how to call a function in activity" }) } }
apache-2.0
4aa427b03f37bc835188fd3c554bcde7
39.3
113
0.609202
4.8011
false
false
false
false
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/SexualActivityRecord.kt
3
3364
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.annotation.IntDef import androidx.annotation.RestrictTo import androidx.health.connect.client.records.metadata.Metadata import java.time.Instant import java.time.ZoneOffset /** * Captures an occurrence of sexual activity. Each record is a single occurrence. ProtectionUsed * field is optional. */ public class SexualActivityRecord( override val time: Instant, override val zoneOffset: ZoneOffset?, /** * Whether protection was used during sexual activity. Optional field, null if unknown. Allowed * values: [Protection]. * * @see Protection */ @property:Protections public val protectionUsed: Int = PROTECTION_USED_UNKNOWN, override val metadata: Metadata = Metadata.EMPTY, ) : InstantaneousRecord { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SexualActivityRecord) return false if (protectionUsed != other.protectionUsed) return false if (time != other.time) return false if (zoneOffset != other.zoneOffset) return false if (metadata != other.metadata) return false return true } override fun hashCode(): Int { var result = protectionUsed result = 31 * result + time.hashCode() result = 31 * result + (zoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } companion object { const val PROTECTION_USED_UNKNOWN = 0 const val PROTECTION_USED_PROTECTED = 1 const val PROTECTION_USED_UNPROTECTED = 2 /** Internal mappings useful for interoperability between integers and strings. */ @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmField val PROTECTION_USED_STRING_TO_INT_MAP: Map<String, Int> = mapOf( Protection.PROTECTED to PROTECTION_USED_PROTECTED, Protection.UNPROTECTED to PROTECTION_USED_UNPROTECTED, ) @RestrictTo(RestrictTo.Scope.LIBRARY) @JvmField val PROTECTION_USED_INT_TO_STRING_MAP = PROTECTION_USED_STRING_TO_INT_MAP.reverse() } /** Whether protection was used during sexual activity. */ internal object Protection { const val PROTECTED = "protected" const val UNPROTECTED = "unprotected" } /** * Whether protection was used during sexual activity. * @suppress */ @Retention(AnnotationRetention.SOURCE) @IntDef( value = [ PROTECTION_USED_PROTECTED, PROTECTION_USED_UNPROTECTED, ] ) @RestrictTo(RestrictTo.Scope.LIBRARY) annotation class Protections }
apache-2.0
681c72c5658f44532153c4a39ae92a18
32.979798
99
0.670333
4.515436
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/LazyListScopeImpl.kt
3
2757
/* * 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.compose.foundation.lazy import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.lazy.layout.IntervalList import androidx.compose.foundation.lazy.layout.LazyLayoutIntervalContent import androidx.compose.foundation.lazy.layout.MutableIntervalList import androidx.compose.runtime.Composable @OptIn(ExperimentalFoundationApi::class) internal class LazyListScopeImpl : LazyListScope { private val _intervals = MutableIntervalList<LazyListIntervalContent>() val intervals: IntervalList<LazyListIntervalContent> = _intervals private var _headerIndexes: MutableList<Int>? = null val headerIndexes: List<Int> get() = _headerIndexes ?: emptyList() override fun items( count: Int, key: ((index: Int) -> Any)?, contentType: (index: Int) -> Any?, itemContent: @Composable LazyItemScope.(index: Int) -> Unit ) { _intervals.addInterval( count, LazyListIntervalContent( key = key, type = contentType, item = itemContent ) ) } override fun item(key: Any?, contentType: Any?, content: @Composable LazyItemScope.() -> Unit) { _intervals.addInterval( 1, LazyListIntervalContent( key = if (key != null) { _: Int -> key } else null, type = { contentType }, item = { content() } ) ) } @ExperimentalFoundationApi override fun stickyHeader( key: Any?, contentType: Any?, content: @Composable LazyItemScope.() -> Unit ) { val headersIndexes = _headerIndexes ?: mutableListOf<Int>().also { _headerIndexes = it } headersIndexes.add(_intervals.size) item(key, contentType, content) } } @OptIn(ExperimentalFoundationApi::class) internal class LazyListIntervalContent( override val key: ((index: Int) -> Any)?, override val type: ((index: Int) -> Any?), val item: @Composable LazyItemScope.(index: Int) -> Unit ) : LazyLayoutIntervalContent
apache-2.0
a302e9b4f2b33c8278287317ed8c3a99
33.037037
100
0.658324
4.778163
false
false
false
false
androidx/androidx
compose/animation/animation/src/commonMain/kotlin/androidx/compose/animation/ColorVectorConverter.kt
3
3664
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.animation import androidx.compose.animation.core.AnimationVector4D import androidx.compose.animation.core.TwoWayConverter import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.colorspace.ColorSpace import androidx.compose.ui.graphics.colorspace.ColorSpaces import kotlin.math.pow /** * A lambda that takes a [ColorSpace] and returns a converter that can both convert a [Color] to * a [AnimationVector4D], and convert a [AnimationVector4D]) back to a [Color] in the given * [ColorSpace]. */ private val ColorToVector: (colorSpace: ColorSpace) -> TwoWayConverter<Color, AnimationVector4D> = { colorSpace -> TwoWayConverter( convertToVector = { color -> // TODO: use Oklab when it is public API val colorXyz = color.convert(ColorSpaces.CieXyz) val x = colorXyz.red val y = colorXyz.green val z = colorXyz.blue val l = multiplyColumn(0, x, y, z, M1).pow(1f / 3f) val a = multiplyColumn(1, x, y, z, M1).pow(1f / 3f) val b = multiplyColumn(2, x, y, z, M1).pow(1f / 3f) AnimationVector4D(color.alpha, l, a, b) }, convertFromVector = { val l = it.v2.pow(3f) val a = it.v3.pow(3f) val b = it.v4.pow(3f) val x = multiplyColumn(0, l, a, b, InverseM1) val y = multiplyColumn(1, l, a, b, InverseM1) val z = multiplyColumn(2, l, a, b, InverseM1) val colorXyz = Color( alpha = it.v1.coerceIn(0f, 1f), red = x.coerceIn(-2f, 2f), green = y.coerceIn(-2f, 2f), blue = z.coerceIn(-2f, 2f), colorSpace = ColorSpaces.CieXyz // here we have the right color space ) colorXyz.convert(colorSpace) } ) } /** * A lambda that takes a [ColorSpace] and returns a converter that can both convert a [Color] to * a [AnimationVector4D], and convert a [AnimationVector4D]) back to a [Color] in the given * [ColorSpace]. */ val Color.Companion.VectorConverter: (colorSpace: ColorSpace) -> TwoWayConverter<Color, AnimationVector4D> get() = ColorToVector // These are utilities and constants to emulate converting to/from Oklab color space. // These can be removed when Oklab becomes public and we can use it directly in the conversion. private val M1 = floatArrayOf( 0.80405736f, 0.026893456f, 0.04586542f, 0.3188387f, 0.9319606f, 0.26299807f, -0.11419419f, 0.05105356f, 0.83999807f ) private val InverseM1 = floatArrayOf( 1.2485008f, -0.032856926f, -0.057883114f, -0.48331892f, 1.1044513f, -0.3194066f, 0.19910365f, -0.07159331f, 1.202023f ) private fun multiplyColumn(column: Int, x: Float, y: Float, z: Float, matrix: FloatArray): Float { return x * matrix[column] + y * matrix[3 + column] + z * matrix[6 + column] }
apache-2.0
71599465edbe681ff24256870dbfe773
38.836957
98
0.635371
3.624135
false
false
false
false
rocoty/BukkitGenericCommandSystem
src/main/kotlin/okkero/spigotutils/genericcommandsystem/CommandSystem.kt
1
9188
package okkero.spigotutils.genericcommandsystem import org.bukkit.ChatColor.* import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import java.util.ArrayList import java.util.TreeMap /** * Base class for all commands. Subclass this to define a new kind of command. Do not instantiate/subclass if you want * to create a simple command. Use [SimpleCommand] for that. * * @param senderClass the class for the type of sender allowed to execute this command * @param handler the handler callback to be called when the command is executed * @param S the type of sender allowed to execute this command * @param D the type of data this command passes to the handler callback */ abstract class Command<S : CommandSender, D : CommandData<S>>(senderClass: Class<S>, handler: (D) -> CommandResult) : CommandExecutor { protected val senderClass = senderClass private val handler = handler private val rules = ArrayList<(ArgumentList) -> Boolean>() private val permissions = ArrayList<String>() private val subCommands = TreeMap<String, Command<out S, out CommandData<S>>>(String.CASE_INSENSITIVE_ORDER) /** * Add a rule to this command. If not all rules are met when executing the command, the execution will fail and the * sender will be notified. Returns the current instance, and thus can be chained. * * @param rule the rule to add * @return this instance */ fun withRule(rule: (ArgumentList) -> Boolean): Command<S, D> { rules.add(rule) return this } /** * Add permissions to this command. If not all permissions are held by the sender upon execution, the execution will * fail and the sender will be notified. Returns the current instance, and thus can be chained. * * @param perms the permissions to add * @return this instance */ fun withPermissions(vararg perms: String): Command<S, D> { permissions.addAll(perms) return this } /** * Add a sub command to this command. If the first argument to this command matches one of the aliases given to one * of the sub commands, then the execution of the command will be delegated to said sub command. * Returns the current instance, and thus can be chained. * * @param command the sub command to add * @param aliases the aliases associated with the sub command * @return this instance */ fun withSubCommand(command: Command<out S, out CommandData<S>>, vararg aliases: String): Command<S, D> { for (alias in aliases) { subCommands[alias] = command } return this } internal fun execute(sender: CommandSender, args: ArgumentList.MutableDepth): CommandResult { if (!permissions.all { sender.hasPermission(it) }) { return CommandResult.MISSING_PERMS } if (!senderClass.isInstance(sender)) { return CommandResult.INVALID_SENDER_TYPE } sender as S if (!rules.all { it(args) }) { return CommandResult.INVALID_SYNTAX } if (args.size >= 1) { val subCommand = subCommands[args[0]] if (subCommand != null) { args.addDepth() return subCommand.execute(sender, args) } } return try { val data = buildData(args) data.sender = sender handler(data) } catch (e: IllegalCommandSyntaxException) { CommandResult.INVALID_SYNTAX } catch (e: Exception) { throw BadCommandException(e) } } /** * Construct the [CommandData] ([D]) to be passed to the handler callback, based on the given arguments. * * @param args the arguments supplied by the sender of the command * @return the command data */ protected abstract fun buildData(args: ArgumentList.MutableDepth): D override fun onCommand(sender: CommandSender, cmd: org.bukkit.command.Command, alias: String?, args: Array<out String>): Boolean { val result = execute(sender, ArgumentList.MutableDepth(args)) return when (result) { CommandResult.SUCCESS -> true CommandResult.MISSING_PERMS -> { sender.sendMessage("${RED}You do not have permission to use this command.") true } CommandResult.INVALID_SENDER_TYPE -> { sender.sendMessage("${RED}Only senders of type $WHITE${senderClass.simpleName}$RED may use this command.") true } CommandResult.INVALID_SYNTAX -> false } } } /** * A simple implementation of [Command]. This implementation merely wraps all arguments in a simple [CommandData] * object. * * @param senderClass the class for the type of sender allowed to execute this command * @param handler the handler callback to be called when the command is executed * @param S the type of sender allowed to execute this command */ open class SimpleCommand<S : CommandSender>(senderClass: Class<S>, handler: (CommandData<S>) -> CommandResult) : Command<S, CommandData<S>>(senderClass, handler) { override fun buildData(args: ArgumentList.MutableDepth) = CommandData<S>(args) } /** * Convenience "constructor" with reified type parameter for SimpleCommand * * @param handler the handler callback to be called when the command is executed * @param S the type of sender allowed to execute this command */ inline fun <reified S : CommandSender> SimpleCommand(noinline handler: (CommandData<S>) -> CommandResult): SimpleCommand<S> { return SimpleCommand(S::class.java, handler) } /** * Represents data to be passed to a command's handler callback. Contains information about an executed command. */ open class CommandData<S : CommandSender>(args: ArgumentList) { /** * The arguments passed by the sender of the command */ val args: ArgumentList by lazy { ArgumentList.ImmutableDepth(args) } lateinit var sender: S internal set } /** * Represents a list of arguments passed by a command sender when executing a command. The depth defines the list's * entry point. The arguments that a command handler is expected to have use for under normal circumstances, are all the * arguments from the entry point to the end of the list. */ sealed class ArgumentList(private val args: Array<out String>) { /** * The offset from the entry point. A call to [get] will be offset by this value. */ var depth = 0 protected set /** * The amount of arguments in this list from the entry point */ val size: Int get() = shallowSize - depth /** * The total amount of arguments in this list */ val shallowSize = args.size /** * Get the argument at the given index, starting from the entry point */ operator fun get(index: Int): String { return getShallow(index + depth) } /** * Get the argument at the given index, ignoring the entry point. */ fun getShallow(index: Int): String { return args[index] } internal class ImmutableDepth(copyFrom: ArgumentList) : ArgumentList(copyFrom.args) { init { depth = copyFrom.depth } } class MutableDepth(args: Array<out String>) : ArgumentList(args) { //TODO not too sure about this KDoc /** * Add depth to this argument list. This is to be used when an argument is deemed little or not useful because * it has been processed to create a more meaningful alternative. */ fun addDepth() { depth++ } } } /** * Represents the result of executing a command. Command handlers are to return either of these to indicate the result * of executing the command. */ enum class CommandResult { /** * The command was successfully executed and processed. */ SUCCESS, /** * The sender of the command used invalid syntax when executing the command. The sender will be notified and the * correct usage will be displayed. */ INVALID_SYNTAX, /** * The sender of the command is of an unsupported type. For example, a [ConsoleCommandSender][org.bukkit.command.ConsoleCommandSender] * tried to execute a [SimpleCommand]<[Player][org.bukkit.entity.Player]> */ INVALID_SENDER_TYPE, /** * The sender of the command does not have sufficient permissions to use the command. */ MISSING_PERMS } /** * Thrown internally when a sender uses a command with invalid syntax. Command handlers should not throw this exception, * but instead return [CommandResult.INVALID_SYNTAX]. */ class IllegalCommandSyntaxException : RuntimeException() /** * Thrown if a command is badly implemented. This signifies an internal bug made by a developer, and not a mistake on * the sender's side. Consequently, this exception is never caught and will result in the sender being presented with * an error message. */ class BadCommandException(cause: Throwable) : RuntimeException(cause)
gpl-3.0
6876a0726c78d378420a1e825b4aebe9
33.939163
138
0.665215
4.575697
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/refactorings/extract/KotlinExtractVariableRefactoring.kt
1
14184
/******************************************************************************* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.jetbrains.kotlin.ui.refactorings.extract import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.util.PsiTreeUtil import org.eclipse.core.runtime.IProgressMonitor import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages import org.eclipse.jdt.internal.corext.refactoring.changes.TextChangeCompatibility import org.eclipse.jface.text.ITextSelection import org.eclipse.jface.text.TextUtilities import org.eclipse.ltk.core.refactoring.Change import org.eclipse.ltk.core.refactoring.Refactoring import org.eclipse.ltk.core.refactoring.RefactoringStatus import org.eclipse.ltk.core.refactoring.TextFileChange import org.eclipse.text.edits.ReplaceEdit import org.jetbrains.kotlin.eclipse.ui.utils.IndenterUtil import org.jetbrains.kotlin.eclipse.ui.utils.LineEndUtil import org.jetbrains.kotlin.eclipse.ui.utils.getBindingContext import org.jetbrains.kotlin.eclipse.ui.utils.getOffsetByDocument import org.jetbrains.kotlin.eclipse.ui.utils.getTextDocumentOffset import org.jetbrains.kotlin.idea.util.psi.patternMatching.KotlinPsiUnifier import org.jetbrains.kotlin.idea.util.psi.patternMatching.toRange import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtArrayAccessExpression import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry import org.jetbrains.kotlin.psi.KtClassBody import org.jetbrains.kotlin.psi.KtContainerNode import org.jetbrains.kotlin.psi.KtDeclarationWithBody import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtIfExpression import org.jetbrains.kotlin.psi.KtLoopExpression import org.jetbrains.kotlin.psi.KtStringTemplateEntryWithExpression import org.jetbrains.kotlin.psi.KtWhenEntry import org.jetbrains.kotlin.psi.psiUtil.canPlaceAfterSimpleNameEntry import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement import org.jetbrains.kotlin.ui.editors.KotlinCommonEditor import org.jetbrains.kotlin.ui.formatter.AlignmentStrategy import org.jetbrains.kotlin.ui.refactorings.rename.FileEdit public class KotlinExtractVariableRefactoring(val selection: ITextSelection, val editor: KotlinCommonEditor) : Refactoring() { public var newName: String = "temp" public var replaceAllOccurrences = true private lateinit var expression: KtExpression override fun checkFinalConditions(pm: IProgressMonitor?): RefactoringStatus = RefactoringStatus() override fun checkInitialConditions(pm: IProgressMonitor?): RefactoringStatus { val startOffset = LineEndUtil.convertCrToDocumentOffset(editor.document, selection.getOffset()) val selectedExpression = PsiTreeUtil.findElementOfClassAtRange(editor.parsedFile!!, startOffset, startOffset + selection.getLength(), KtExpression::class.java) return if (selectedExpression != null) { expression = selectedExpression RefactoringStatus() } else { RefactoringStatus.createErrorStatus("Could not extract variable") } } override fun getName(): String = RefactoringCoreMessages.ExtractTempRefactoring_name override fun createChange(pm: IProgressMonitor?): Change { val edits = introduceVariable() val fileChange = TextFileChange("Introduce variable", editor.eclipseFile!!) edits.forEach { TextChangeCompatibility.addTextEdit(fileChange, "Kotlin change", it.edit) } return fileChange } private fun introduceVariable(): List<FileEdit> { val occurrenceContainer = expression.getOccurrenceContainer() if (occurrenceContainer == null) return emptyList() val allReplaces = if (replaceAllOccurrences) expression.findOccurrences(occurrenceContainer) else listOf(expression) val commonParent = PsiTreeUtil.findCommonParent(allReplaces) as KtElement val commonContainer = getContainer(commonParent) if (commonContainer == null) return emptyList() val anchor = calculateAnchor(commonParent, commonContainer, allReplaces) if (anchor == null) return emptyList() val indent = run { val indentNode = commonContainer.getFirstChild().getNode() val nodeIndent = AlignmentStrategy.computeIndent(indentNode) if (AlignmentStrategy.isBlockElement(indentNode)) nodeIndent - 1 else nodeIndent } val variableDeclarationText = "val $newName = ${expression.getText()}" val bindingContext = getBindingContext(expression) ?: return emptyList() return createEdits( commonContainer, expression.isUsedAsStatement(bindingContext), commonContainer !is KtBlockExpression, variableDeclarationText, indent, anchor, allReplaces) } private fun shouldReplaceInitialExpression(context: BindingContext): Boolean { return expression.isUsedAsStatement(context) } private fun replaceExpressionWithVariableDeclaration(variableText: String, firstOccurrence: KtExpression): FileEdit { val offset = firstOccurrence.getTextDocumentOffset(editor.document) return FileEdit(editor.eclipseFile!!, ReplaceEdit(offset, firstOccurrence.getTextLength(), variableText)) } private fun createEdits( container: PsiElement, isUsedAsStatement: Boolean, needBraces: Boolean, variableDeclarationText: String, indent: Int, anchor: PsiElement, replaces: List<KtExpression>): List<FileEdit> { val lineDelimiter = TextUtilities.getDefaultLineDelimiter(editor.document) val newLineWithShift = IndenterUtil.createWhiteSpace(indent, 1, lineDelimiter) val newLineBeforeBrace = IndenterUtil.createWhiteSpace(indent - 1, 1, lineDelimiter) val sortedReplaces = replaces.sortedBy { it.getTextOffset() } if (isUsedAsStatement && sortedReplaces.first() == anchor) { val variableText = if (needBraces) { "{${newLineWithShift}${variableDeclarationText}${newLineBeforeBrace}}" } else { variableDeclarationText } val replacesList = sortedReplaces.drop(1).map { replaceOccurrence(newName, it, editor) } return listOf(replaceExpressionWithVariableDeclaration(variableText, sortedReplaces.first())) + replacesList } else { val replacesList = replaces.map { replaceOccurrence(newName, it, editor) } if (needBraces) { val variableText = "{${newLineWithShift}${variableDeclarationText}${newLineWithShift}" val removeNewLineIfNeeded = if (isElseAfterContainer(container)) removeNewLineAfter(container, editor) else null return listOf( insertBefore(anchor, variableText, editor), addBraceAfter(expression, newLineBeforeBrace, editor), removeNewLineIfNeeded).filterNotNull() + replacesList } else { val variableText = "${variableDeclarationText}${newLineWithShift}" return replacesList + insertBefore(anchor, variableText, editor) } } } } private fun KtExpression.findOccurrences(occurrenceContainer: PsiElement): List<KtExpression> { return toRange() .match(occurrenceContainer, KotlinPsiUnifier.DEFAULT) .map { val candidate = it.range.elements.first() when (candidate) { is KtExpression -> candidate is KtStringTemplateEntryWithExpression -> candidate.expression else -> throw AssertionError("Unexpected candidate element: " + candidate.text) } as? KtExpression } .filterNotNull() } private fun addBraceAfter(expr: KtExpression, newLineBeforeBrace: String, editor: KotlinCommonEditor): FileEdit { val parent = expr.getParent() var endOffset = parent.getTextRange().getEndOffset() val text = editor.document.get() while (endOffset > 0 && text[endOffset] == ' ') { endOffset-- } val offset = expr.getParent().let { it.getOffsetByDocument(editor.document, endOffset + 1) } return FileEdit(editor.eclipseFile!!, ReplaceEdit(offset, 0, "$newLineBeforeBrace}")) } private fun removeNewLineAfter(container: PsiElement, editor: KotlinCommonEditor): FileEdit? { val next = container.nextSibling if (next is PsiWhiteSpace) { return FileEdit( editor.eclipseFile!!, ReplaceEdit(next.getTextDocumentOffset(editor.document), next.getTextLength(), " ")) } return null } private fun replaceOccurrence(newName: String, replaceExpression: KtExpression, editor: KotlinCommonEditor): FileEdit { val (offset, length) = replaceExpression.getReplacementRange(editor) return FileEdit(editor.eclipseFile!!, ReplaceEdit(offset, length, newName)) } private fun KtExpression.getReplacementRange(editor: KotlinCommonEditor): ReplacementRange { val p = getParent() if (p is KtBlockStringTemplateEntry) { if (canPlaceAfterSimpleNameEntry(p.nextSibling)) { return ReplacementRange(p.getTextDocumentOffset(editor.document) + 1, p.getTextLength() - 1) // '+- 1' is for '$' sign } } return ReplacementRange(getTextDocumentOffset(editor.document), getTextLength()) } private data class ReplacementRange(val offset: Int, val length: Int) private fun isElseAfterContainer(container: PsiElement): Boolean { val next = container.nextSibling if (next != null) { val nextnext = next.nextSibling if (nextnext != null && nextnext.node.elementType == KtTokens.ELSE_KEYWORD) { return true } } return false } private fun insertBefore(psiElement: PsiElement, text: String, editor: KotlinCommonEditor): FileEdit { val startOffset = psiElement.getOffsetByDocument(editor.document, psiElement.getTextRange().getStartOffset()) return FileEdit(editor.eclipseFile!!, ReplaceEdit(startOffset, 0, text)) } private fun calculateAnchor(commonParent: PsiElement, commonContainer: PsiElement, allReplaces: List<KtExpression>): PsiElement? { var anchor = commonParent if (anchor != commonContainer) { while (anchor.getParent() != commonContainer) { anchor = anchor.getParent() } } else { anchor = commonContainer.getFirstChild() var startOffset = commonContainer.getTextRange().getEndOffset() for (expr in allReplaces) { val offset = expr.getTextRange().getStartOffset() if (offset < startOffset) startOffset = offset } while (anchor != null && !anchor.getTextRange().contains(startOffset)) { anchor = anchor.getNextSibling() } } return anchor } private fun getContainer(place: PsiElement): PsiElement? { if (place is KtBlockExpression) return place var container = place while (container != null) { val parent = container.getParent() if (parent is KtContainerNode) { if (!isBadContainerNode(parent, container)) { return parent } } if (parent is KtBlockExpression || (parent is KtWhenEntry && container == parent.getExpression())) { return parent } if (parent is KtDeclarationWithBody && parent.getBodyExpression() == container) { return parent } container = parent } return null } private fun KtExpression.getOccurrenceContainer(): KtElement? { var result: KtElement? = null for ((place, parent) in parentsWithSelf.zip(parents)) { when { parent is KtContainerNode && place !is KtBlockExpression && !isBadContainerNode(parent, place) -> result = parent parent is KtClassBody || parent is KtFile -> return result parent is KtBlockExpression -> result = parent parent is KtWhenEntry && place !is KtBlockExpression -> result = parent parent is KtDeclarationWithBody && parent.bodyExpression == place && place !is KtBlockExpression -> result = parent } } return null } public val PsiElement.parentsWithSelf: Sequence<PsiElement> get() = generateSequence(this) { if (it is PsiFile) null else it.getParent() } public val PsiElement.parents: Sequence<PsiElement> get() = parentsWithSelf.drop(1) private fun isBadContainerNode(parent: KtContainerNode, place: PsiElement): Boolean { if (parent.getParent() is KtIfExpression && (parent.getParent() as KtIfExpression).getCondition() == place) { return true } else if (parent.getParent() is KtLoopExpression && (parent.getParent() as KtLoopExpression).getBody() != place) { return true } else if (parent.getParent() is KtArrayAccessExpression) { return true } return false }
apache-2.0
d216a591dd458e8e361f71a9dee1896a
42.646154
130
0.686619
5.120578
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/ui/ImageDetailActivity.kt
1
2219
package me.proxer.app.ui import android.app.Activity import android.graphics.drawable.Drawable import android.os.Bundle import android.widget.ImageView import androidx.core.view.ViewCompat import com.bumptech.glide.request.target.ImageViewTarget import com.jakewharton.rxbinding3.view.clicks import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import kotterknife.bindView import me.proxer.app.GlideApp import me.proxer.app.R import me.proxer.app.base.BaseActivity import me.proxer.app.util.ActivityUtils import me.proxer.app.util.extension.getSafeStringExtra import me.proxer.app.util.extension.intentFor import me.proxer.app.util.extension.logErrors import okhttp3.HttpUrl /** * @author Ruben Gees */ class ImageDetailActivity : BaseActivity() { companion object { private const val URL_EXTRA = "url" fun navigateTo(context: Activity, url: HttpUrl, imageView: ImageView? = null) { context.intentFor<ImageDetailActivity>(URL_EXTRA to url.toString()).let { ActivityUtils.navigateToWithImageTransition(it, context, imageView) } } } override val theme: Int get() = preferenceHelper.themeContainer.theme.noBackground private val url: String get() = intent.getSafeStringExtra(URL_EXTRA) private val image: ImageView by bindView(R.id.image) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_image_detail) supportPostponeEnterTransition() ViewCompat.setTransitionName(image, ActivityUtils.getTransitionName(this)) GlideApp.with(this) .load(url) .logErrors() .into(object : ImageViewTarget<Drawable>(image) { override fun setResource(resource: Drawable?) { image.setImageDrawable(resource) if (resource != null) { supportStartPostponedEnterTransition() } } }) root.clicks() .autoDisposable(this.scope()) .subscribe { supportFinishAfterTransition() } } }
gpl-3.0
0663fd40cb593f43bbf111a5c5d0a4b2
30.7
87
0.684543
4.701271
false
false
false
false
tasomaniac/OpenLinkWith
browser-preferred/src/main/kotlin/com/tasomaniac/openwith/browser/BrowserViewHolder.kt
1
1256
package com.tasomaniac.openwith.browser import android.content.ComponentName import android.view.ViewGroup import androidx.core.view.isGone import androidx.recyclerview.widget.RecyclerView import com.tasomaniac.openwith.browser.preferred.databinding.BrowserListItemBinding import com.tasomaniac.openwith.extensions.componentName import com.tasomaniac.openwith.extensions.inflater import com.tasomaniac.openwith.resolver.DisplayActivityInfo import javax.inject.Inject class BrowserViewHolder private constructor( private val binding: BrowserListItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind( info: DisplayActivityInfo, selectedBrowser: ComponentName?, onItemClicked: (DisplayActivityInfo) -> Unit ) = binding.apply { browserTitle.text = info.displayLabel browserIcon.setImageDrawable(info.displayIcon) browserSelected.isChecked = info.activityInfo.componentName() == selectedBrowser browserInfo.isGone = true itemView.setOnClickListener { onItemClicked(info) } } class Factory @Inject constructor() { fun createWith(parent: ViewGroup) = BrowserViewHolder(BrowserListItemBinding.inflate(parent.inflater(), parent, false)) } }
apache-2.0
21a3ba564b1acb06c62fad2f957639d2
35.941176
95
0.769108
5.003984
false
false
false
false
czyzby/ktx
math/src/test/kotlin/ktx/math/Matrix4Test.kt
2
10271
package ktx.math import com.badlogic.gdx.math.Matrix4 import com.badlogic.gdx.utils.GdxNativesLoader import org.junit.Assert.assertEquals import org.junit.Test /** * Tests [Matrix4]-related utilities. */ class Matrix4Test { private val floatTolerance = 0.00001f @Test fun `should create matrix`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) assertMatrixEquals( matrix, +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) } @Test fun `should negate matrix values`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) val result = -matrix assertMatrixEquals( result, -1f, -2f, -3f, -4f, -5f, -6f, -7f, -8f, -9f, -10f, -11f, -12f, -13f, -14f, -15f, -16f ) assertMatrixEquals( matrix, 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f, 9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) } @Test fun `should invert matrix`() { val matrix = mat4( 1f, 0f, 1f, 0f, 0f, 1f, 0f, 1f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f ) val result = !matrix assertMatrixEquals( result, 1f, 0f, -1f, 0f, 0f, 1f, 0f, -1f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f ) assertMatrixEquals( matrix, 1f, 0f, 1f, 0f, 0f, 1f, 0f, 1f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f ) } @Test fun `should addAssign matrices`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) matrix += mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) assertMatrixEquals( matrix, +2f, +4f, +6f, +8f, 10f, 12f, 14f, 16f, 18f, 20f, 22f, 24f, 26f, 28f, 30f, 32f ) } @Test fun `should subtractAssign matrices`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) matrix -= mat4( 16f, 15f, 14f, 13f, 12f, 11f, 10f, +9f, +8f, +7f, +6f, +5f, +4f, +3f, +2f, +1f ) assertMatrixEquals( matrix, -15f, -13f, -11f, -9f, -7f, -5.0f, -3f, -1f, 1.0f, 3.0f, 5.0f, 7f, 9.0f, 11.0f, 13f, 15f ) } @Test fun `should multiplyAssign matrices`() { GdxNativesLoader.load() // Matrix.mul4 is written with native code. val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) matrix *= mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) assertMatrixEquals( matrix, 1f * 1f + 2f * 5f + 3f * 9f + 4f * 13f, 1f * 2f + 2f * 6f + 3f * 10f + 4f * 14f, 1f * 3f + 2f * 7f + 3f * 11f + 4f * 15f, 1f * 4f + 2f * 8f + 3f * 12f + 4f * 16f, 5f * 1f + 6f * 5f + 7f * 9f + 8f * 13f, 5f * 2f + 6f * 6f + 7f * 10f + 8f * 14f, 5f * 3f + 6f * 7f + 7f * 11f + 8f * 15f, 5f * 4f + 6f * 8f + 7f * 12f + 8f * 16f, 9f * 1f + 10f * 5f + 11f * 9f + 12f * 13f, 9f * 2f + 10f * 6f + 11f * 10f + 12f * 14f, 9f * 3f + 10f * 7f + 11f * 11f + 12f * 15f, 9f * 4f + 10f * 8f + 11f * 12f + 12f * 16f, 13f * 1f + 14f * 5f + 15f * 9f + 16f * 13f, 13f * 2f + 14f * 6f + 15f * 10f + 16f * 14f, 13f * 3f + 14f * 7f + 15f * 11f + 16f * 15f, 13f * 4f + 14f * 8f + 15f * 12f + 16f * 16f ) } @Test fun `should multiplyAssign matrices with scalar`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) matrix *= 3f assertMatrixEquals( matrix, +3f, +2f, +3f, +4f, +5f, 18f, +7f, +8f, +9f, 10f, 33f, 12f, 13f, 14f, 15f, 16f ) } @Test fun `should multiplyAssign matrices with Vector3 scalar`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) matrix *= vec3(3f, 4f, 5f) assertMatrixEquals( matrix, +3f, +2f, +3f, +4f, +5f, 24f, +7f, +8f, +9f, 10f, 55f, 12f, 13f, 14f, 15f, 16f ) } @Test fun `should multiplyAssign Vector3 with matrices`() { val vector = vec3(1f, 2f, 3f) vector *= mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) assertEquals(1f * 1f + 2f * 2f + 3f * 3f + 1f * 4f, vector.x, floatTolerance) assertEquals(1f * 5f + 2f * 6f + 3f * 7f + 1f * 8f, vector.y, floatTolerance) assertEquals(1f * 9f + 2f * 10f + 3f * 11f + 1f * 12f, vector.z, floatTolerance) } @Test fun `should add matrices`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) val result = matrix + mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) assertMatrixEquals( result, +2f, +4f, +6f, +8f, 10f, 12f, 14f, 16f, 18f, 20f, 22f, 24f, 26f, 28f, 30f, 32f ) } @Test fun `should subtract matrices`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) val result = matrix - mat4( 16f, 15f, 14f, 13f, 12f, 11f, 10f, +9f, +8f, +7f, +6f, +5f, +4f, +3f, +2f, +1f ) assertMatrixEquals( result, -15f, -13f, -11f, -9f, -7f, -5.0f, -3f, -1f, 1.0f, 3.0f, 5.0f, 7f, 9.0f, 11.0f, 13f, 15f ) } @Test fun `should multiply matrices`() { GdxNativesLoader.load() // Matrix.mul4 is written with native code. val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) val result = matrix * mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) assertMatrixEquals( result, 1f * 1f + 2f * 5f + 3f * 9f + 4f * 13f, 1f * 2f + 2f * 6f + 3f * 10f + 4f * 14f, 1f * 3f + 2f * 7f + 3f * 11f + 4f * 15f, 1f * 4f + 2f * 8f + 3f * 12f + 4f * 16f, 5f * 1f + 6f * 5f + 7f * 9f + 8f * 13f, 5f * 2f + 6f * 6f + 7f * 10f + 8f * 14f, 5f * 3f + 6f * 7f + 7f * 11f + 8f * 15f, 5f * 4f + 6f * 8f + 7f * 12f + 8f * 16f, 9f * 1f + 10f * 5f + 11f * 9f + 12f * 13f, 9f * 2f + 10f * 6f + 11f * 10f + 12f * 14f, 9f * 3f + 10f * 7f + 11f * 11f + 12f * 15f, 9f * 4f + 10f * 8f + 11f * 12f + 12f * 16f, 13f * 1f + 14f * 5f + 15f * 9f + 16f * 13f, 13f * 2f + 14f * 6f + 15f * 10f + 16f * 14f, 13f * 3f + 14f * 7f + 15f * 11f + 16f * 15f, 13f * 4f + 14f * 8f + 15f * 12f + 16f * 16f ) } @Test fun `should multiply matrices with scalar`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) val result = matrix * 3f assertMatrixEquals( result, +3f, +2f, +3f, +4f, +5f, 18f, +7f, +8f, +9f, 10f, 33f, 12f, 13f, 14f, 15f, 16f ) } @Test fun `should multiply matrices with Vector3`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) val result = matrix * vec3(3f, 4f, 5f) assertEquals(3f * 1f + 4f * 2f + 5f * 3f + 1f * 4f, result.x, floatTolerance) assertEquals(3f * 5f + 4f * 6f + 5f * 7f + 1f * 8f, result.y, floatTolerance) assertEquals(3f * 9f + 4f * 10f + 5f * 11f + 1f * 12f, result.z, floatTolerance) } @Test fun `should destruct matrices into sixteen floats`() { val matrix = mat4( +1f, +2f, +3f, +4f, +5f, +6f, +7f, +8f, +9f, 10f, 11f, 12f, 13f, 14f, 15f, 16f ) val ( x0y0, x0y1, x0y2, x0y3, x1y0, x1y1, x1y2, x1y3, x2y0, x2y1, x2y2, x2y3, x3y0, x3y1, x3y2, x3y3 ) = matrix assertEquals(1f, x0y0, floatTolerance) assertEquals(2f, x0y1, floatTolerance) assertEquals(3f, x0y2, floatTolerance) assertEquals(4f, x0y3, floatTolerance) assertEquals(5f, x1y0, floatTolerance) assertEquals(6f, x1y1, floatTolerance) assertEquals(7f, x1y2, floatTolerance) assertEquals(8f, x1y3, floatTolerance) assertEquals(9f, x2y0, floatTolerance) assertEquals(10f, x2y1, floatTolerance) assertEquals(11f, x2y2, floatTolerance) assertEquals(12f, x2y3, floatTolerance) assertEquals(13f, x3y0, floatTolerance) assertEquals(14f, x3y1, floatTolerance) assertEquals(15f, x3y2, floatTolerance) assertEquals(16f, x3y3, floatTolerance) } private fun assertMatrixEquals( matrix: Matrix4, m00: Float, m01: Float, m02: Float, m03: Float, m10: Float, m11: Float, m12: Float, m13: Float, m20: Float, m21: Float, m22: Float, m23: Float, m30: Float, m31: Float, m32: Float, m33: Float, tolerance: Float = floatTolerance ) { val values = matrix.`val` assertEquals(m00, values[Matrix4.M00], tolerance) assertEquals(m01, values[Matrix4.M01], tolerance) assertEquals(m02, values[Matrix4.M02], tolerance) assertEquals(m03, values[Matrix4.M03], tolerance) assertEquals(m10, values[Matrix4.M10], tolerance) assertEquals(m11, values[Matrix4.M11], tolerance) assertEquals(m12, values[Matrix4.M12], tolerance) assertEquals(m13, values[Matrix4.M13], tolerance) assertEquals(m20, values[Matrix4.M20], tolerance) assertEquals(m21, values[Matrix4.M21], tolerance) assertEquals(m22, values[Matrix4.M22], tolerance) assertEquals(m23, values[Matrix4.M23], tolerance) assertEquals(m30, values[Matrix4.M30], tolerance) assertEquals(m31, values[Matrix4.M31], tolerance) assertEquals(m32, values[Matrix4.M32], tolerance) assertEquals(m33, values[Matrix4.M33], tolerance) } }
cc0-1.0
26688c283da782296a6e57c6db6fcca3
22.503432
84
0.50998
2.332198
false
false
false
false
HabitRPG/habitica-android
wearos/src/main/java/com/habitrpg/wearos/habitica/ui/viewmodels/StatsViewModel.kt
1
1565
package com.habitrpg.wearos.habitica.ui.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.asLiveData import androidx.lifecycle.viewModelScope import com.habitrpg.wearos.habitica.data.repositories.TaskRepository import com.habitrpg.wearos.habitica.data.repositories.UserRepository import com.habitrpg.wearos.habitica.managers.AppStateManager import com.habitrpg.wearos.habitica.models.user.User import com.habitrpg.wearos.habitica.util.ExceptionHandlerBuilder import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class StatsViewModel @Inject constructor(userRepository: UserRepository, taskRepository: TaskRepository, exceptionBuilder: ExceptionHandlerBuilder, appStateManager: AppStateManager ) : BaseViewModel(userRepository, taskRepository, exceptionBuilder, appStateManager) { fun retrieveUser() { viewModelScope.launch(exceptionBuilder.silent()) { userRepository.retrieveUser(true) } } var user: LiveData<User> = userRepository.getUser() .distinctUntilChanged { old, new -> val oldStats = old.stats ?: return@distinctUntilChanged false val newStats = new.stats ?: return@distinctUntilChanged false return@distinctUntilChanged (oldStats.hp ?: 0.0) + (oldStats.exp ?: 0.0) + (oldStats.exp ?: 0.0) == (newStats.hp ?: 0.0) + (newStats.exp ?: 0.0) + (newStats.exp ?: 0.0) } .asLiveData() }
gpl-3.0
dafb7ac03e95455bd20d0d062d38dd22
42.5
111
0.753355
4.589443
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/callableReference/function/innerConstructorFromClass.kt
3
260
class A { inner class Inner { val o = 111 val k = 222 } fun result() = (A::Inner)(this).o + (A::Inner)(this).k } fun box(): String { val result = A().result() if (result != 333) return "Fail $result" return "OK" }
apache-2.0
399f3c1d704657bc1b96b314f4ec0187
17.571429
58
0.496154
3.25
false
false
false
false
mattermost/mattermost-mobile
android/app/src/main/java/com/mattermost/helpers/PushNotificationDataHelper.kt
1
15275
package com.mattermost.helpers import android.content.Context import android.os.Bundle import android.util.Log import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.facebook.react.bridge.WritableNativeArray import com.nozbe.watermelondb.Database import java.io.IOException import java.util.concurrent.Executors import kotlin.coroutines.* import kotlinx.coroutines.* class PushNotificationDataHelper(private val context: Context) { private var scope = Executors.newSingleThreadExecutor() fun fetchAndStoreDataForPushNotification(initialData: Bundle) { scope.execute(Runnable { runBlocking { PushNotificationDataRunnable.start(context, initialData) } }) } } class PushNotificationDataRunnable { companion object { private val specialMentions = listOf("all", "here", "channel") @Synchronized suspend fun start(context: Context, initialData: Bundle) { try { val serverUrl: String = initialData.getString("server_url") ?: return val channelId = initialData.getString("channel_id") val rootId = initialData.getString("root_id") val isCRTEnabled = initialData.getString("is_crt_enabled") == "true" val db = DatabaseHelper.instance!!.getDatabaseForServer(context, serverUrl) Log.i("ReactNative", "Start fetching notification data in server="+serverUrl+" for channel="+channelId) if (db != null) { var postData: ReadableMap? var posts: ReadableMap? = null var userIdsToLoad: ReadableArray? = null var usernamesToLoad: ReadableArray? = null var threads: ReadableArray? = null var usersFromThreads: ReadableArray? = null val receivingThreads = isCRTEnabled && !rootId.isNullOrEmpty() coroutineScope { if (channelId != null) { postData = fetchPosts(db, serverUrl, channelId, isCRTEnabled, rootId) posts = postData?.getMap("posts") userIdsToLoad = postData?.getArray("userIdsToLoad") usernamesToLoad = postData?.getArray("usernamesToLoad") threads = postData?.getArray("threads") usersFromThreads = postData?.getArray("usersFromThreads") if (userIdsToLoad != null && userIdsToLoad!!.size() > 0) { val users = fetchUsersById(serverUrl, userIdsToLoad!!) userIdsToLoad = users?.getArray("data") } if (usernamesToLoad != null && usernamesToLoad!!.size() > 0) { val users = fetchUsersByUsernames(serverUrl, usernamesToLoad!!) usernamesToLoad = users?.getArray("data") } } } db.transaction { if (posts != null && channelId != null) { DatabaseHelper.instance!!.handlePosts(db, posts!!.getMap("data"), channelId, receivingThreads) } if (threads != null) { DatabaseHelper.instance!!.handleThreads(db, threads!!) } if (userIdsToLoad != null && userIdsToLoad!!.size() > 0) { DatabaseHelper.instance!!.handleUsers(db, userIdsToLoad!!) } if (usernamesToLoad != null && usernamesToLoad!!.size() > 0) { DatabaseHelper.instance!!.handleUsers(db, usernamesToLoad!!) } if (usersFromThreads != null) { DatabaseHelper.instance!!.handleUsers(db, usersFromThreads!!) } } db.close() Log.i("ReactNative", "Done processing push notification="+serverUrl+" for channel="+channelId) } } catch (e: Exception) { e.printStackTrace() } } private suspend fun fetchPosts(db: Database, serverUrl: String, channelId: String, isCRTEnabled: Boolean, rootId: String?): ReadableMap? { val regex = Regex("""\B@(([a-z0-9-._]*[a-z0-9_])[.-]*)""", setOf(RegexOption.IGNORE_CASE)) val since = DatabaseHelper.instance!!.queryPostSinceForChannel(db, channelId) val currentUserId = DatabaseHelper.instance!!.queryCurrentUserId(db)?.removeSurrounding("\"") val currentUser = DatabaseHelper.instance!!.find(db, "User", currentUserId) val currentUsername = currentUser?.getString("username") var additionalParams = "" if (isCRTEnabled) { additionalParams = "&collapsedThreads=true&collapsedThreadsExtended=true" } val receivingThreads = isCRTEnabled && !rootId.isNullOrEmpty() val endpoint = if (receivingThreads) { val queryParams = "?skipFetchThreads=false&perPage=60&fromCreatedAt=0&direction=up" "/api/v4/posts/$rootId/thread$queryParams$additionalParams" } else { val queryParams = if (since == null) "?page=0&per_page=60" else "?since=${since.toLong()}" "/api/v4/channels/$channelId/posts$queryParams$additionalParams" } val postsResponse = fetch(serverUrl, endpoint) val results = Arguments.createMap() if (postsResponse != null) { val data = ReadableMapUtils.toMap(postsResponse) results.putMap("posts", postsResponse) val postsData = data["data"] as? Map<*, *> if (postsData != null) { val postsMap = postsData["posts"] if (postsMap != null) { val posts = ReadableMapUtils.toWritableMap(postsMap as? Map<String, Any>) val iterator = posts.keySetIterator() val userIds = mutableListOf<String>() val usernames = mutableListOf<String>() val threads = WritableNativeArray() val threadParticipantUserIds = mutableListOf<String>() // Used to exclude the "userIds" present in the thread participants val threadParticipantUsernames = mutableListOf<String>() // Used to exclude the "usernames" present in the thread participants val threadParticipantUsers = HashMap<String, ReadableMap>() // All unique users from thread participants are stored here while(iterator.hasNextKey()) { val key = iterator.nextKey() val post = posts.getMap(key) val userId = post?.getString("user_id") if (userId != null && userId != currentUserId && !userIds.contains(userId)) { userIds.add(userId) } val message = post?.getString("message") if (message != null) { val matchResults = regex.findAll(message) matchResults.iterator().forEach { val username = it.value.removePrefix("@") if (!usernames.contains(username) && currentUsername != username && !specialMentions.contains(username)) { usernames.add(username) } } } if (isCRTEnabled) { // Add root post as a thread val threadId = post?.getString("root_id") if (threadId.isNullOrEmpty()) { threads.pushMap(post!!) } // Add participant userIds and usernames to exclude them from getting fetched again val participants = post.getArray("participants") if (participants != null) { for (i in 0 until participants.size()) { val participant = participants.getMap(i) val participantId = participant.getString("id") if (participantId != currentUserId && participantId != null) { if (!threadParticipantUserIds.contains(participantId)) { threadParticipantUserIds.add(participantId) } if (!threadParticipantUsers.containsKey(participantId)) { threadParticipantUsers[participantId] = participant } } val username = participant.getString("username") if (username != null && username != currentUsername && !threadParticipantUsernames.contains(username)) { threadParticipantUsernames.add(username) } } } } } val existingUserIds = DatabaseHelper.instance!!.queryIds(db, "User", userIds.toTypedArray()) val existingUsernames = DatabaseHelper.instance!!.queryByColumn(db, "User", "username", usernames.toTypedArray()) userIds.removeAll { it in existingUserIds } usernames.removeAll { it in existingUsernames } if (threadParticipantUserIds.size > 0) { // Do not fetch users found in thread participants as we get the user's data in the posts response already userIds.removeAll { it in threadParticipantUserIds } usernames.removeAll { it in threadParticipantUsernames } // Get users from thread participants val existingThreadParticipantUserIds = DatabaseHelper.instance!!.queryIds(db, "User", threadParticipantUserIds.toTypedArray()) // Exclude the thread participants already present in the DB from getting inserted again val usersFromThreads = WritableNativeArray() threadParticipantUsers.forEach{ (userId, user) -> if (!existingThreadParticipantUserIds.contains(userId)) { usersFromThreads.pushMap(user) } } if (usersFromThreads.size() > 0) { results.putArray("usersFromThreads", usersFromThreads) } } if (userIds.size > 0) { results.putArray("userIdsToLoad", ReadableArrayUtils.toWritableArray(userIds.toTypedArray())) } if (usernames.size > 0) { results.putArray("usernamesToLoad", ReadableArrayUtils.toWritableArray(usernames.toTypedArray())) } if (threads.size() > 0) { results.putArray("threads", threads) } } } } return results } private suspend fun fetchUsersById(serverUrl: String, userIds: ReadableArray): ReadableMap? { val endpoint = "api/v4/users/ids" val options = Arguments.createMap() options.putArray("body", ReadableArrayUtils.toWritableArray(ReadableArrayUtils.toArray(userIds))) return fetchWithPost(serverUrl, endpoint, options) } private suspend fun fetchUsersByUsernames(serverUrl: String, usernames: ReadableArray): ReadableMap? { val endpoint = "api/v4/users/usernames" val options = Arguments.createMap() options.putArray("body", ReadableArrayUtils.toWritableArray(ReadableArrayUtils.toArray(usernames))) return fetchWithPost(serverUrl, endpoint, options) } private suspend fun fetch(serverUrl: String, endpoint: String): ReadableMap? { return suspendCoroutine { cont -> Network.get(serverUrl, endpoint, null, object : ResolvePromise() { override fun resolve(value: Any?) { val response = value as ReadableMap? if (response != null && !response.getBoolean("ok")) { val error = response.getMap("data") cont.resumeWith(Result.failure((IOException("Unexpected code ${error?.getInt("status_code")} ${error?.getString("message")}")))) } else { cont.resumeWith(Result.success(response)) } } override fun reject(code: String, message: String) { cont.resumeWith(Result.failure(IOException("Unexpected code $code $message"))) } override fun reject(reason: Throwable?) { cont.resumeWith(Result.failure(IOException("Unexpected code $reason"))) } }) } } private suspend fun fetchWithPost(serverUrl: String, endpoint: String, options: ReadableMap?) : ReadableMap? { return suspendCoroutine { cont -> Network.post(serverUrl, endpoint, options, object : ResolvePromise() { override fun resolve(value: Any?) { val response = value as ReadableMap? cont.resumeWith(Result.success(response)) } override fun reject(code: String, message: String) { cont.resumeWith(Result.failure(IOException("Unexpected code $code $message"))) } override fun reject(reason: Throwable?) { cont.resumeWith(Result.failure(IOException("Unexpected code $reason"))) } }) } } } }
apache-2.0
825fc70157c720b9e758ce3880e525cc
50.779661
156
0.50455
6.051902
false
false
false
false
k-kagurazaka/rx-property-android
sample/src/main/kotlin/jp/keita/kagurazaka/rxproperty/sample/todo/TodoItemViewModel.kt
1
923
package jp.keita.kagurazaka.rxproperty.sample.todo import io.reactivex.Observable import jp.keita.kagurazaka.rxproperty.RxProperty import jp.keita.kagurazaka.rxproperty.sample.ViewModelBase class TodoItemViewModel constructor( val model: TodoItem = TodoItem(false, "") ) : ViewModelBase() { val isDone: RxProperty<Boolean> = RxProperty(model.isDone, DISABLE_RAISE_ON_SUBSCRIBE) .asManaged() val title: RxProperty<String> = RxProperty(model.title) .setValidator { if (it.isBlank()) "Blank isn't allowed." else null } .asManaged() val onHasErrorChanged: Observable<Boolean> get() = title.onHasErrorsChanged() init { isDone.subscribe { model.isDone = it TodoRepository.update(model) }.asManaged() title.subscribe { model.title = it ?: "" }.asManaged() } }
mit
aadae1d1644fb02c1952815b66ad8c34
27.84375
80
0.632719
4.395238
false
false
false
false
gisbertamm/kfz-kennzeichen-android
app/src/main/java/kfzkennzeichen/gisbertamm/de/kfz_kennzeichen/persistence/DatabaseHandler.kt
1
8526
package kfzkennzeichen.gisbertamm.de.kfz_kennzeichen.persistence import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteException import android.database.sqlite.SQLiteOpenHelper import android.util.Log import java.io.FileOutputStream import java.io.IOException import java.io.OutputStream import java.sql.SQLException import java.util.* class DatabaseHandler(private val context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { private var dataBase: SQLiteDatabase? = null /** * Creates a empty database on the system and rewrites it with your own database. */ fun createDataBase() { val dbExist = checkDataBase() if (dbExist != null) { val version = dbExist.version Log.d(this.javaClass.simpleName, "EXISTING DATABASE VERSION: $version") dbExist.close() if (DATABASE_VERSION > version) { // update existing database by overriding it copyDataBase() } } else { //By calling this method an empty database will be created into the default system path //of your application so we are gonna be able to overwrite that database with our database. this.readableDatabase copyDataBase() } } /** * Check if the database already exist to avoid re-copying the file each time you open the application. * * @return true if it exists, false if it doesn't */ private fun checkDataBase(): SQLiteDatabase? { var checkDB: SQLiteDatabase? = null try { checkDB = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null) } catch (e: SQLiteException) { //database does't exist yet. } return checkDB } /** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. * This is done by transfering bytestream. */ private fun copyDataBase() { try { //Open your local db as the input stream val myInput = context.assets.open(DATABASE_NAME) // Path to the just created empty db val outFileName = context.getDatabasePath(DATABASE_NAME).path Log.d(this.javaClass.simpleName, "Copying database from assets/ " + DATABASE_NAME + " to " + outFileName) //Open the empty db as the output stream val myOutput: OutputStream = FileOutputStream(outFileName) //transfer bytes from the inputfile to the outputfile val buffer = ByteArray(1024) var length: Int while (myInput.read(buffer).also { length = it } > 0) { myOutput.write(buffer, 0, length) } //Close the streams myOutput.flush() myOutput.close() myInput.close() } catch (e: IOException) { throw RuntimeException("Cannot copy database", e) } } @Throws(SQLException::class) fun openDataBase() { //Open the database dataBase = context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null) } @Synchronized override fun close() { if (dataBase != null) dataBase!!.close() super.close() } override fun onCreate(db: SQLiteDatabase) { // do nothing because database is provided from assets } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { // do nothing because database is provided from assets } fun searchForCode(code: String): SavedEntry? { try { openDataBase() } catch (e: SQLException) { e.printStackTrace() return null } val cursor = dataBase!!.query(TABLE_NUMBERPLATE_CODES, arrayOf("*"), COLUMN_CODE + "=?", arrayOf(code), null, null, null, null) if (cursor != null) { cursor.moveToFirst() } else { Log.e(this.javaClass.simpleName, "cursor is null") return null } var savedEntry: SavedEntry? = null if (cursor.count > 0) { savedEntry = SavedEntry(cursor.getString(0).toInt(), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)) if (!addJokes(code, savedEntry)) return null } return savedEntry } private fun addJokes(code: String, savedEntry: SavedEntry?): Boolean { val cursor = dataBase!!.query(TABLE_JOKES, arrayOf("*"), COLUMN_CODE + "=?", arrayOf(code), null, null, null, null) if (cursor != null) { cursor.moveToFirst() } else { Log.e(this.javaClass.simpleName, "cursor is null") return false } if (cursor.count > 0) { while (!cursor.isAfterLast) { val joke = cursor.getString(2) savedEntry!!.setJoke(joke) cursor.moveToNext() } } return true } fun searchRandom(): SavedEntry? { try { openDataBase() } catch (e: SQLException) { e.printStackTrace() return null } val cursor = dataBase!!.query(TABLE_NUMBERPLATE_CODES + " ORDER BY RANDOM() LIMIT 1", arrayOf("*"), null, null, null, null, null) if (cursor != null) { cursor.moveToFirst() } else { Log.e(this.javaClass.simpleName, "cursor is null") return null } var savedEntry: SavedEntry? = null if (cursor.count > 0) { savedEntry = SavedEntry(cursor.getString(0).toInt(), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)) } return if (!addJokes(cursor.getString(1), savedEntry)) null else savedEntry } fun createStatistics(): Map<String, Int> { try { openDataBase() } catch (e: SQLException) { e.printStackTrace() return HashMap<String, Int>() } var allWords = mutableListOf<String>() val cursor = dataBase!!.query(TABLE_JOKES, arrayOf(COLUMN_JOKES), null, null, null, null, null, null) cursor?.moveToFirst() ?: Log.e(this.javaClass.simpleName, "cursor is null") if (cursor!!.count > 0) { while (!cursor.isAfterLast) { allWords.addAll(cursor.getString(0).split(" ")) cursor.moveToNext() } } return allWords.groupingBy { it }.eachCount().filter { (key, value) -> isInteresting(key) && hasRelevantAmount(value) }.toList() .sortedByDescending { (key, value) -> value } .toMap() } private fun hasRelevantAmount(value: Int) = value >= 5 private fun isInteresting(key: String): Boolean { val excludeList = listOf("ein", "und", "ohne", "Ohne", "unterwegs", "Wir", "fährt", "Fahrer", "fährt", "im", "Kein", "Keine", "der", "am", "Noch", "kommen", "Nur") if (key in excludeList) return false return true } companion object { const val WIKIPEDIA_BASE_URL = "https://de.wikipedia.org" const val TAG = "DatabaseHandler" private const val DATABASE_VERSION = 9 private const val DATABASE_NAME = "NumberplateCodesManager.sqlite" private const val TABLE_NUMBERPLATE_CODES = "numberplate_codes" private const val TABLE_JOKES = "jokes" private const val COLUMN_JOKES = "jokes" private const val COLUMN_ID = "_id" private const val COLUMN_CODE = "code" private const val COLUMN_DISTRICT = "district" private const val COLUMN_DISTRICT_CENTER = "district_center" private const val COLUMN_STATE = "state" private const val COLUMN_DISTRICT_WIKIPEDIA_URL = "district_wikipedia_url" private val data: List<Array<String>> = ArrayList() } /** * Constructor * Takes and keeps a reference of the passed context in order to access to the application assets and resources. * * @param context */ init { // copy database implicitly when class instance is created for the first time createDataBase() } }
gpl-2.0
3ed1296794a6920aba767fc966da182a
35.904762
171
0.594439
4.458159
false
false
false
false
google/filament
android/samples/sample-hello-triangle/src/main/java/com/google/android/filament/hellotriangle/MainActivity.kt
1
13006
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.filament.hellotriangle import android.animation.ValueAnimator import android.app.Activity import android.opengl.Matrix import android.os.Bundle import android.view.Choreographer import android.view.Surface import android.view.SurfaceView import android.view.animation.LinearInterpolator import com.google.android.filament.* import com.google.android.filament.RenderableManager.PrimitiveType import com.google.android.filament.VertexBuffer.AttributeType import com.google.android.filament.VertexBuffer.VertexAttribute import com.google.android.filament.android.DisplayHelper import com.google.android.filament.android.UiHelper import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.Channels import kotlin.math.PI import kotlin.math.cos import kotlin.math.sin class MainActivity : Activity() { // Make sure to initialize Filament first // This loads the JNI library needed by most API calls companion object { init { Filament.init() } } // The View we want to render into private lateinit var surfaceView: SurfaceView // UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture private lateinit var uiHelper: UiHelper // DisplayHelper is provided by Filament to manage the display private lateinit var displayHelper: DisplayHelper // Choreographer is used to schedule new frames private lateinit var choreographer: Choreographer // Engine creates and destroys Filament resources // Each engine must be accessed from a single thread of your choosing // Resources cannot be shared across engines private lateinit var engine: Engine // A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.) private lateinit var renderer: Renderer // A scene holds all the renderable, lights, etc. to be drawn private lateinit var scene: Scene // A view defines a viewport, a scene and a camera for rendering private lateinit var view: View // Should be pretty obvious :) private lateinit var camera: Camera private lateinit var material: Material private lateinit var vertexBuffer: VertexBuffer private lateinit var indexBuffer: IndexBuffer // Filament entity representing a renderable object @Entity private var renderable = 0 // A swap chain is Filament's representation of a surface private var swapChain: SwapChain? = null // Performs the rendering and schedules new frames private val frameScheduler = FrameCallback() private val animator = ValueAnimator.ofFloat(0.0f, 360.0f) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) surfaceView = SurfaceView(this) setContentView(surfaceView) choreographer = Choreographer.getInstance() displayHelper = DisplayHelper(this) setupSurfaceView() setupFilament() setupView() setupScene() } private fun setupSurfaceView() { uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK) uiHelper.renderCallback = SurfaceCallback() // NOTE: To choose a specific rendering resolution, add the following line: // uiHelper.setDesiredSize(1280, 720) uiHelper.attachTo(surfaceView) } private fun setupFilament() { engine = Engine.create() renderer = engine.createRenderer() scene = engine.createScene() view = engine.createView() camera = engine.createCamera(engine.entityManager.create()) } private fun setupView() { scene.skybox = Skybox.Builder().color(0.035f, 0.035f, 0.035f, 1.0f).build(engine) // NOTE: Try to disable post-processing (tone-mapping, etc.) to see the difference // view.isPostProcessingEnabled = false // Tell the view which camera we want to use view.camera = camera // Tell the view which scene we want to render view.scene = scene } private fun setupScene() { loadMaterial() createMesh() // To create a renderable we first create a generic entity renderable = EntityManager.get().create() // We then create a renderable component on that entity // A renderable is made of several primitives; in this case we declare only 1 RenderableManager.Builder(1) // Overall bounding box of the renderable .boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.01f)) // Sets the mesh data of the first primitive .geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 3) // Sets the material of the first primitive .material(0, material.defaultInstance) .build(engine, renderable) // Add the entity to the scene to render it scene.addEntity(renderable) startAnimation() } private fun loadMaterial() { readUncompressedAsset("materials/baked_color.filamat").let { material = Material.Builder().payload(it, it.remaining()).build(engine) } } private fun createMesh() { val intSize = 4 val floatSize = 4 val shortSize = 2 // A vertex is a position + a color: // 3 floats for XYZ position, 1 integer for color val vertexSize = 3 * floatSize + intSize // Define a vertex and a function to put a vertex in a ByteBuffer data class Vertex(val x: Float, val y: Float, val z: Float, val color: Int) fun ByteBuffer.put(v: Vertex): ByteBuffer { putFloat(v.x) putFloat(v.y) putFloat(v.z) putInt(v.color) return this } // We are going to generate a single triangle val vertexCount = 3 val a1 = PI * 2.0 / 3.0 val a2 = PI * 4.0 / 3.0 val vertexData = ByteBuffer.allocate(vertexCount * vertexSize) // It is important to respect the native byte order .order(ByteOrder.nativeOrder()) .put(Vertex(1.0f, 0.0f, 0.0f, 0xffff0000.toInt())) .put(Vertex(cos(a1).toFloat(), sin(a1).toFloat(), 0.0f, 0xff00ff00.toInt())) .put(Vertex(cos(a2).toFloat(), sin(a2).toFloat(), 0.0f, 0xff0000ff.toInt())) // Make sure the cursor is pointing in the right place in the byte buffer .flip() // Declare the layout of our mesh vertexBuffer = VertexBuffer.Builder() .bufferCount(1) .vertexCount(vertexCount) // Because we interleave position and color data we must specify offset and stride // We could use de-interleaved data by declaring two buffers and giving each // attribute a different buffer index .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize) .attribute(VertexAttribute.COLOR, 0, AttributeType.UBYTE4, 3 * floatSize, vertexSize) // We store colors as unsigned bytes but since we want values between 0 and 1 // in the material (shaders), we must mark the attribute as normalized .normalized(VertexAttribute.COLOR) .build(engine) // Feed the vertex data to the mesh // We only set 1 buffer because the data is interleaved vertexBuffer.setBufferAt(engine, 0, vertexData) // Create the indices val indexData = ByteBuffer.allocate(vertexCount * shortSize) .order(ByteOrder.nativeOrder()) .putShort(0) .putShort(1) .putShort(2) .flip() indexBuffer = IndexBuffer.Builder() .indexCount(3) .bufferType(IndexBuffer.Builder.IndexType.USHORT) .build(engine) indexBuffer.setBuffer(engine, indexData) } private fun startAnimation() { // Animate the triangle animator.interpolator = LinearInterpolator() animator.duration = 4000 animator.repeatMode = ValueAnimator.RESTART animator.repeatCount = ValueAnimator.INFINITE animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { val transformMatrix = FloatArray(16) override fun onAnimationUpdate(a: ValueAnimator) { Matrix.setRotateM(transformMatrix, 0, -(a.animatedValue as Float), 0.0f, 0.0f, 1.0f) val tcm = engine.transformManager tcm.setTransform(tcm.getInstance(renderable), transformMatrix) } }) animator.start() } override fun onResume() { super.onResume() choreographer.postFrameCallback(frameScheduler) animator.start() } override fun onPause() { super.onPause() choreographer.removeFrameCallback(frameScheduler) animator.cancel() } override fun onDestroy() { super.onDestroy() // Stop the animation and any pending frame choreographer.removeFrameCallback(frameScheduler) animator.cancel(); // Always detach the surface before destroying the engine uiHelper.detach() // Cleanup all resources engine.destroyEntity(renderable) engine.destroyRenderer(renderer) engine.destroyVertexBuffer(vertexBuffer) engine.destroyIndexBuffer(indexBuffer) engine.destroyMaterial(material) engine.destroyView(view) engine.destroyScene(scene) engine.destroyCameraComponent(camera.entity) // Engine.destroyEntity() destroys Filament related resources only // (components), not the entity itself val entityManager = EntityManager.get() entityManager.destroy(renderable) entityManager.destroy(camera.entity) // Destroying the engine will free up any resource you may have forgotten // to destroy, but it's recommended to do the cleanup properly engine.destroy() } inner class FrameCallback : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { // Schedule the next frame choreographer.postFrameCallback(this) // This check guarantees that we have a swap chain if (uiHelper.isReadyToRender) { // If beginFrame() returns false you should skip the frame // This means you are sending frames too quickly to the GPU if (renderer.beginFrame(swapChain!!, frameTimeNanos)) { renderer.render(view) renderer.endFrame() } } } } inner class SurfaceCallback : UiHelper.RendererCallback { override fun onNativeWindowChanged(surface: Surface) { swapChain?.let { engine.destroySwapChain(it) } swapChain = engine.createSwapChain(surface, uiHelper.swapChainFlags) displayHelper.attach(renderer, surfaceView.display); } override fun onDetachedFromSurface() { displayHelper.detach(); swapChain?.let { engine.destroySwapChain(it) // Required to ensure we don't return before Filament is done executing the // destroySwapChain command, otherwise Android might destroy the Surface // too early engine.flushAndWait() swapChain = null } } override fun onResized(width: Int, height: Int) { val zoom = 1.5 val aspect = width.toDouble() / height.toDouble() camera.setProjection(Camera.Projection.ORTHO, -aspect * zoom, aspect * zoom, -zoom, zoom, 0.0, 10.0) view.viewport = Viewport(0, 0, width, height) } } private fun readUncompressedAsset(assetName: String): ByteBuffer { assets.openFd(assetName).use { fd -> val input = fd.createInputStream() val dst = ByteBuffer.allocate(fd.length.toInt()) val src = Channels.newChannel(input) src.read(dst) src.close() return dst.apply { rewind() } } } }
apache-2.0
615f2453a30bba734589681267aad71c
36.698551
104
0.640627
4.954667
false
false
false
false
y20k/trackbook
app/src/main/java/org/y20k/trackbook/core/Tracklist.kt
1
1809
/* * Tracklist.kt * Implements the Tracklist data class * A Tracklist stores a list of Tracks * * This file is part of * TRACKBOOK - Movement Recorder for Android * * Copyright (c) 2016-22 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT * * Trackbook uses osmdroid - OpenStreetMap-Tools for Android * https://github.com/osmdroid/osmdroid */ package org.y20k.trackbook.core import android.os.Parcelable import androidx.annotation.Keep import com.google.gson.annotations.Expose import kotlinx.parcelize.Parcelize import org.y20k.trackbook.Keys import org.y20k.trackbook.helpers.TrackHelper import java.util.* /* * Tracklist data class */ @Keep @Parcelize data class Tracklist (@Expose val tracklistFormatVersion: Int = Keys.CURRENT_TRACKLIST_FORMAT_VERSION, @Expose val tracklistElements: MutableList<TracklistElement> = mutableListOf<TracklistElement>(), @Expose var modificationDate: Date = Date(), @Expose var totalDistanceAll: Float = 0f, @Expose var totalDurationAll: Long = 0L, @Expose var totalRecordingPausedAll: Long = 0L, @Expose var totalStepCountAll: Float = 0f): Parcelable { /* Return trackelement for given track id */ fun getTrackElement(trackId: Long): TracklistElement? { tracklistElements.forEach { tracklistElement -> if (TrackHelper.getTrackId(tracklistElement) == trackId) { return tracklistElement } } return null } /* Create a deep copy */ fun deepCopy(): Tracklist { return Tracklist(tracklistFormatVersion, mutableListOf<TracklistElement>().apply { addAll(tracklistElements) }, modificationDate) } }
mit
69ef4b2cfd9aba451f174f8102198ad9
30.736842
137
0.674959
4.327751
false
false
false
false
shadowfacts/ShadowMC
src/main/kotlin/net/shadowfacts/forgelin/extensions/InventoryExtensions.kt
1
2879
package net.shadowfacts.forgelin.extensions import net.minecraft.inventory.IInventory import net.minecraft.item.ItemStack import java.util.* /** * @author shadowfacts */ operator fun IInventory.get(index: Int): ItemStack { return getStackInSlot(index) } operator fun IInventory.set(index: Int, stack: ItemStack) { setInventorySlotContents(index, stack) } operator fun IInventory.iterator(): Iterator<ItemStack> { return object: Iterator<ItemStack> { private var index = 0 override fun next(): ItemStack { return this@iterator[index++] } override fun hasNext(): Boolean { return index < [email protected] } } } inline fun IInventory.forEach(action: (ItemStack) -> Unit) { for (stack in this) action(stack) } inline fun IInventory.forEachIndexed(action: (Int, ItemStack) -> Unit) { var index = 0 for (stack in this) action(index++, stack) } inline fun <C: MutableCollection<ItemStack>> IInventory.filterIndexedTo(destination: C, predicate: (Int, ItemStack) -> Boolean): C { forEachIndexed { i, stack -> if (predicate(i, stack)) destination.add(stack) } return destination } inline fun IInventory.filterIndexed(predicate: (Int, ItemStack) -> Boolean): List<ItemStack> { return filterIndexedTo(ArrayList(), predicate) } inline fun <C: MutableCollection<ItemStack>> IInventory.filterTo(destination: C, predicate: (ItemStack) -> Boolean): C { forEach { if (predicate(it)) destination.add(it) } return destination } inline fun IInventory.filter(predicate: (ItemStack) -> Boolean): List<ItemStack> { return filterTo(ArrayList(), predicate) } inline fun IInventory.first(predicate: (ItemStack) -> Boolean): ItemStack { forEach { if (predicate(it)) { return it } } throw NoSuchElementException("IInventory contains no element matching the predicate") } inline fun IInventory.firstOrEmpty(predicate: (ItemStack) -> Boolean): ItemStack { forEach { if (predicate(it)) { return it } } return ItemStack.EMPTY } inline fun IInventory.find(predicate: (ItemStack) -> Boolean): ItemStack { return firstOrEmpty(predicate) } inline fun IInventory.sumBy(selector: (ItemStack) -> Int): Int { var sum = 0 forEach { sum += selector(it) } return sum } inline fun <R: Comparable<R>> IInventory.minBy(selector: (ItemStack) -> R): ItemStack { if (isEmpty) return ItemStack.EMPTY var minElem = this[0] var minValue = selector(minElem) for (i in 1..sizeInventory) { val e = this[i] val v = selector(e) if (minValue > v) { minElem = e minValue = v } } return minElem } inline fun <R: Comparable<R>> IInventory.maxBy(selector: (ItemStack) -> R): ItemStack { if (isEmpty) return ItemStack.EMPTY var maxElem = this[0] var maxValue = selector(maxElem) for (i in 1..sizeInventory) { val e = this[i] val v = selector(e) if (maxValue < v) { maxElem = e maxValue = v } } return maxElem }
lgpl-3.0
abea4cfb1ccfea41c580c6d9f774dcb1
22.801653
132
0.710663
3.391048
false
false
false
false
Heiner1/AndroidAPS
rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.kt
1
8410
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothManager import android.content.Context import android.content.Intent import dagger.android.DaggerService import dagger.android.HasAndroidInjector import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject /** * Created by andy on 5/6/18. * Split from original file and renamed. */ abstract class RileyLinkService : DaggerService() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP @Inject lateinit var context: Context @Inject lateinit var rxBus: RxBus @Inject lateinit var rileyLinkUtil: RileyLinkUtil @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var rh: ResourceHelper @Inject lateinit var rileyLinkServiceData: RileyLinkServiceData @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var rileyLinkBLE: RileyLinkBLE // android-bluetooth management @Inject lateinit var rfSpy: RFSpy // interface for RL xxx Mhz radio. private val bluetoothAdapter: BluetoothAdapter? get() = (context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter private var broadcastReceiver: RileyLinkBroadcastReceiver? = null private var bluetoothStateReceiver: RileyLinkBluetoothStateReceiver? = null override fun onCreate() { super.onCreate() rileyLinkUtil.encoding = encoding initRileyLinkServiceData() broadcastReceiver = RileyLinkBroadcastReceiver() broadcastReceiver?.registerBroadcasts(this) bluetoothStateReceiver = RileyLinkBluetoothStateReceiver() bluetoothStateReceiver?.registerBroadcasts(this) } /** * Get Encoding for RileyLink communication */ abstract val encoding: RileyLinkEncodingType /** * If you have customized RileyLinkServiceData you need to override this */ abstract fun initRileyLinkServiceData() override fun onUnbind(intent: Intent): Boolean { //aapsLogger.warn(LTag.PUMPBTCOMM, "onUnbind"); return super.onUnbind(intent) } override fun onRebind(intent: Intent) { //aapsLogger.warn(LTag.PUMPBTCOMM, "onRebind"); super.onRebind(intent) } override fun onDestroy() { super.onDestroy() rileyLinkBLE.disconnect() // dispose of Gatt (disconnect and close) broadcastReceiver?.unregisterBroadcasts(this) bluetoothStateReceiver?.unregisterBroadcasts(this) } abstract val deviceCommunicationManager: RileyLinkCommunicationManager<*> // Here is where the wake-lock begins: // We've received a service startCommand, we grab the lock. override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int = START_STICKY fun bluetoothInit(): Boolean { aapsLogger.debug(LTag.PUMPBTCOMM, "bluetoothInit: attempting to get an adapter") rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothInitializing) if (bluetoothAdapter == null) { aapsLogger.error("Unable to obtain a BluetoothAdapter.") rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.NoBluetoothAdapter) } else { if (bluetoothAdapter?.isEnabled != true) { aapsLogger.error("Bluetooth is not enabled.") rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.BluetoothDisabled) } else { rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothReady) return true } } return false } // returns true if our Rileylink configuration changed fun reconfigureRileyLink(deviceAddress: String): Boolean { rileyLinkServiceData.setServiceState(RileyLinkServiceState.RileyLinkInitializing) return if (rileyLinkBLE.isConnected) { if (deviceAddress == rileyLinkServiceData.rileyLinkAddress) { aapsLogger.info(LTag.PUMPBTCOMM, "No change to RL address. Not reconnecting.") false } else { aapsLogger.warn(LTag.PUMPBTCOMM, "Disconnecting from old RL (${rileyLinkServiceData.rileyLinkAddress}), reconnecting to new: $deviceAddress") rileyLinkBLE.disconnect() // need to shut down listening thread too? // SP.putString(MedtronicConst.Prefs.RileyLinkAddress, deviceAddress); rileyLinkServiceData.rileyLinkAddress = deviceAddress rileyLinkBLE.findRileyLink(deviceAddress) true } } else { aapsLogger.debug(LTag.PUMPBTCOMM, "Using RL $deviceAddress") if (rileyLinkServiceData.rileyLinkServiceState == RileyLinkServiceState.NotStarted) { if (!bluetoothInit()) { aapsLogger.error("RileyLink can't get activated, Bluetooth is not functioning correctly. ${rileyLinkServiceData.rileyLinkError?.name ?: "Unknown error (null)"}") return false } } rileyLinkBLE.findRileyLink(deviceAddress) true } } // FIXME: This needs to be run in a session so that is incorruptible, has a separate thread, etc. fun doTuneUpDevice() { rileyLinkServiceData.setServiceState(RileyLinkServiceState.TuneUpDevice) setPumpDeviceState(PumpDeviceState.Sleeping) val lastGoodFrequency = rileyLinkServiceData.lastGoodFrequency ?: sp.getDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, 0.0) val newFrequency = deviceCommunicationManager.tuneForDevice() if (newFrequency != 0.0 && newFrequency != lastGoodFrequency) { aapsLogger.info(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Saving new pump frequency of %.3f MHz", newFrequency)) sp.putDouble(RileyLinkConst.Prefs.LastGoodDeviceFrequency, newFrequency) rileyLinkServiceData.lastGoodFrequency = newFrequency rileyLinkServiceData.tuneUpDone = true rileyLinkServiceData.lastTuneUpTime = System.currentTimeMillis() } if (newFrequency == 0.0) { // error tuning pump, pump not present ?? rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorError, RileyLinkError.TuneUpOfDeviceFailed) } else { deviceCommunicationManager.clearNotConnectedCount() rileyLinkServiceData.setServiceState(RileyLinkServiceState.PumpConnectorReady) } } abstract fun setPumpDeviceState(pumpDeviceState: PumpDeviceState) fun disconnectRileyLink() { if (rileyLinkBLE.isConnected) { rileyLinkBLE.disconnect() rileyLinkServiceData.rileyLinkAddress = null rileyLinkServiceData.rileyLinkName = null } rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothReady) } fun changeRileyLinkEncoding(encodingType: RileyLinkEncodingType?) { rfSpy.setRileyLinkEncoding(encodingType) } fun verifyConfiguration(): Boolean { return verifyConfiguration(false) } abstract fun verifyConfiguration(forceRileyLinkAddressRenewal: Boolean): Boolean }
agpl-3.0
fa6a0ceaf13e910901267214982fa0f2
45.727778
181
0.725684
5.336294
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt
1
17704
package info.nightscout.androidaps.plugins.profile.local import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import com.google.android.material.tabs.TabLayout import dagger.android.support.DaggerFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.SingleFragmentActivity import info.nightscout.androidaps.data.ProfileSealed import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.databinding.LocalprofileFragmentBinding import info.nightscout.androidaps.dialogs.ProfileSwitchDialog import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.GlucoseUnit import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.ui.TimeListEdit import info.nightscout.shared.SafeParse import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.math.RoundingMode import java.text.DecimalFormat import javax.inject.Inject class LocalProfileFragment : DaggerFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBus @Inject lateinit var rh: ResourceHelper @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var hardLimits: HardLimits @Inject lateinit var protectionCheck: ProtectionCheck @Inject lateinit var dateUtil: DateUtil @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var uel: UserEntryLogger private var disposable: CompositeDisposable = CompositeDisposable() private var inMenu = false private var queryingProtection = false private var basalView: TimeListEdit? = null private val save = Runnable { doEdit() basalView?.updateLabel(rh.gs(R.string.basal_label) + ": " + sumLabel()) localProfilePlugin.getEditedProfile()?.let { binding.basalGraph.show(ProfileSealed.Pure(it)) binding.icGraph.show(ProfileSealed.Pure(it)) binding.isfGraph.show(ProfileSealed.Pure(it)) binding.targetGraph.show(ProfileSealed.Pure(it)) binding.insulinGraph.show(activePlugin.activeInsulin, SafeParse.stringToDouble(binding.dia.text)) } } private val textWatch = object : TextWatcher { override fun afterTextChanged(s: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { localProfilePlugin.currentProfile()?.dia = SafeParse.stringToDouble(binding.dia.text) localProfilePlugin.currentProfile()?.name = binding.name.text.toString() doEdit() } } private fun sumLabel(): String { val profile = localProfilePlugin.getEditedProfile() val sum = profile?.let { ProfileSealed.Pure(profile).baseBasalSum() } ?: 0.0 return " ∑" + DecimalFormatter.to2Decimal(sum) + rh.gs(R.string.insulin_unit_shortname) } private var _binding: LocalprofileFragmentBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = LocalprofileFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val parentClass = this.activity?.let { it::class.java } inMenu = parentClass == SingleFragmentActivity::class.java updateProtectedUi() processVisibility(0) binding.tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab) { processVisibility(tab.position) } override fun onTabUnselected(tab: TabLayout.Tab) {} override fun onTabReselected(tab: TabLayout.Tab) {} }) binding.diaLabel.labelFor = binding.dia.editTextId binding.unlock.setOnClickListener { queryProtection() } val profiles = localProfilePlugin.profile?.getProfileList() ?: ArrayList() val activeProfile = profileFunction.getProfileName() val profileIndex = profiles.indexOf(activeProfile) localProfilePlugin.currentProfileIndex = if (profileIndex >= 0) profileIndex else 0 } fun build() { val pumpDescription = activePlugin.activePump.pumpDescription if (localProfilePlugin.numOfProfiles == 0) localProfilePlugin.addNewProfile() val currentProfile = localProfilePlugin.currentProfile() ?: return val units = if (currentProfile.mgdl) Constants.MGDL else Constants.MMOL binding.name.removeTextChangedListener(textWatch) binding.name.setText(currentProfile.name) binding.name.addTextChangedListener(textWatch) binding.dia.setParams(currentProfile.dia, hardLimits.minDia(), hardLimits.maxDia(), 0.1, DecimalFormat("0.0"), false, null, textWatch) binding.dia.tag = "LP_DIA" TimeListEdit( context, aapsLogger, dateUtil, view, R.id.ic_holder, "IC", rh.gs(R.string.ic_long_label), currentProfile.ic, null, doubleArrayOf(hardLimits.minIC(), hardLimits.maxIC()), null, 0.1, DecimalFormat("0.0"), save ) basalView = TimeListEdit( context, aapsLogger, dateUtil, view, R.id.basal_holder, "BASAL", rh.gs(R.string.basal_long_label) + ": " + sumLabel(), currentProfile.basal, null, doubleArrayOf(pumpDescription.basalMinimumRate, pumpDescription.basalMaximumRate), null, 0.01, DecimalFormat("0.00"), save ) if (units == Constants.MGDL) { val isfRange = doubleArrayOf(HardLimits.MIN_ISF, HardLimits.MAX_ISF) TimeListEdit(context, aapsLogger, dateUtil, view, R.id.isf_holder, "ISF", rh.gs(R.string.isf_long_label), currentProfile.isf, null, isfRange, null, 1.0, DecimalFormat("0"), save) TimeListEdit( context, aapsLogger, dateUtil, view, R.id.target_holder, "TARGET", rh.gs(R.string.target_long_label), currentProfile.targetLow, currentProfile.targetHigh, HardLimits.VERY_HARD_LIMIT_MIN_BG, HardLimits.VERY_HARD_LIMIT_TARGET_BG, 1.0, DecimalFormat("0"), save ) } else { val isfRange = doubleArrayOf( roundUp(Profile.fromMgdlToUnits(HardLimits.MIN_ISF, GlucoseUnit.MMOL)), roundDown(Profile.fromMgdlToUnits(HardLimits.MAX_ISF, GlucoseUnit.MMOL)) ) TimeListEdit(context, aapsLogger, dateUtil, view, R.id.isf_holder, "ISF", rh.gs(R.string.isf_long_label), currentProfile.isf, null, isfRange, null, 0.1, DecimalFormat("0.0"), save) val range1 = doubleArrayOf( roundUp(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MIN_BG[0], GlucoseUnit.MMOL)), roundDown(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MIN_BG[1], GlucoseUnit.MMOL)) ) val range2 = doubleArrayOf( roundUp(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MAX_BG[0], GlucoseUnit.MMOL)), roundDown(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MAX_BG[1], GlucoseUnit.MMOL)) ) aapsLogger.info(LTag.CORE, "TimeListEdit", "build: range1" + range1[0] + " " + range1[1] + " range2" + range2[0] + " " + range2[1]) TimeListEdit( context, aapsLogger, dateUtil, view, R.id.target_holder, "TARGET", rh.gs(R.string.target_long_label), currentProfile.targetLow, currentProfile.targetHigh, range1, range2, 0.1, DecimalFormat("0.0"), save ) } context?.let { context -> val profileList: ArrayList<CharSequence> = localProfilePlugin.profile?.getProfileList() ?: ArrayList() binding.profileList.setAdapter(ArrayAdapter(context, R.layout.spinner_centered, profileList)) } ?: return binding.profileList.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> if (localProfilePlugin.isEdited) { activity?.let { activity -> OKDialog.showConfirmation( activity, rh.gs(R.string.doyouwantswitchprofile), { localProfilePlugin.currentProfileIndex = position localProfilePlugin.isEdited = false build() }, null ) } } else { localProfilePlugin.currentProfileIndex = position build() } } localProfilePlugin.getEditedProfile()?.let { binding.basalGraph.show(ProfileSealed.Pure(it)) binding.icGraph.show(ProfileSealed.Pure(it)) binding.isfGraph.show(ProfileSealed.Pure(it)) binding.targetGraph.show(ProfileSealed.Pure(it)) binding.insulinGraph.show(activePlugin.activeInsulin, SafeParse.stringToDouble(binding.dia.text)) } binding.profileAdd.setOnClickListener { if (localProfilePlugin.isEdited) { activity?.let { OKDialog.show(it, "", rh.gs(R.string.saveorresetchangesfirst)) } } else { uel.log(Action.NEW_PROFILE, Sources.LocalProfile) localProfilePlugin.addNewProfile() build() } } binding.profileClone.setOnClickListener { if (localProfilePlugin.isEdited) { activity?.let { OKDialog.show(it, "", rh.gs(R.string.saveorresetchangesfirst)) } } else { uel.log( Action.CLONE_PROFILE, Sources.LocalProfile, ValueWithUnit.SimpleString( localProfilePlugin.currentProfile()?.name ?: "" ) ) localProfilePlugin.cloneProfile() build() } } binding.profileRemove.setOnClickListener { activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(R.string.deletecurrentprofile), { uel.log( Action.PROFILE_REMOVED, Sources.LocalProfile, ValueWithUnit.SimpleString( localProfilePlugin.currentProfile()?.name ?: "" ) ) localProfilePlugin.removeCurrentProfile() build() }, null) } } // this is probably not possible because it leads to invalid profile // if (!pumpDescription.isTempBasalCapable) binding.basal.visibility = View.GONE @Suppress("SetTextI18n") binding.units.text = rh.gs(R.string.units_colon) + " " + (if (currentProfile.mgdl) rh.gs(R.string.mgdl) else rh.gs(R.string.mmol)) binding.profileswitch.setOnClickListener { ProfileSwitchDialog() .also { it.arguments = Bundle().also { bundle -> bundle.putString("profileName", localProfilePlugin.currentProfile()?.name) } } .show(childFragmentManager, "ProfileSwitchDialog") } binding.reset.setOnClickListener { localProfilePlugin.loadSettings() build() } binding.save.setOnClickListener { if (!localProfilePlugin.isValidEditState(activity)) { return@setOnClickListener //Should not happen as saveButton should not be visible if not valid } uel.log( Action.STORE_PROFILE, Sources.LocalProfile, ValueWithUnit.SimpleString( localProfilePlugin.currentProfile()?.name ?: "" ) ) localProfilePlugin.storeSettings(activity) build() } updateGUI() } @Synchronized override fun onResume() { super.onResume() if (inMenu) queryProtection() else updateProtectedUi() disposable += rxBus .toObservable(EventLocalProfileChanged::class.java) .observeOn(aapsSchedulers.main) .subscribe({ build() }, fabricPrivacy::logException) build() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } @Synchronized override fun onDestroyView() { super.onDestroyView() _binding = null } fun doEdit() { localProfilePlugin.isEdited = true updateGUI() } private fun roundUp(number: Double): Double { return number.toBigDecimal().setScale(1, RoundingMode.UP).toDouble() } private fun roundDown(number: Double): Double { return number.toBigDecimal().setScale(1, RoundingMode.DOWN).toDouble() } private fun updateGUI() { if (_binding == null) return val isValid = localProfilePlugin.isValidEditState(activity) val isEdited = localProfilePlugin.isEdited if (isValid) { this.view?.setBackgroundColor(rh.gac(context, R.attr.okBackgroundColor)) binding.profileList.isEnabled = true if (isEdited) { //edited profile -> save first binding.profileswitch.visibility = View.GONE binding.save.visibility = View.VISIBLE } else { binding.profileswitch.visibility = View.VISIBLE binding.save.visibility = View.GONE } } else { this.view?.setBackgroundColor(rh.gac(context, R.attr.errorBackgroundColor)) binding.profileList.isEnabled = false binding.profileswitch.visibility = View.GONE binding.save.visibility = View.GONE //don't save an invalid profile } //Show reset button if data was edited if (isEdited) { binding.reset.visibility = View.VISIBLE } else { binding.reset.visibility = View.GONE } } private fun processVisibility(position: Int) { binding.diaPlaceholder.visibility = (position == 0).toVisibility() binding.ic.visibility = (position == 1).toVisibility() binding.isf.visibility = (position == 2).toVisibility() binding.basal.visibility = (position == 3).toVisibility() binding.target.visibility = (position == 4).toVisibility() } private fun updateProtectedUi() { _binding ?: return val isLocked = protectionCheck.isLocked(ProtectionCheck.Protection.PREFERENCES) binding.mainLayout.visibility = isLocked.not().toVisibility() binding.unlock.visibility = isLocked.toVisibility() } private fun queryProtection() { val isLocked = protectionCheck.isLocked(ProtectionCheck.Protection.PREFERENCES) if (isLocked && !queryingProtection) { activity?.let { activity -> queryingProtection = true val doUpdate = { activity.runOnUiThread { queryingProtection = false; updateProtectedUi() } } protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, doUpdate, doUpdate, doUpdate) } } } }
agpl-3.0
5498a70d7d08fb80028535d6416637bf
41.147619
192
0.630833
4.902243
false
false
false
false
Heiner1/AndroidAPS
diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECT_DUAL_SUCCESS.kt
1
2033
package info.nightscout.androidaps.diaconn.pumplog import okhttp3.internal.and import java.nio.ByteBuffer import java.nio.ByteOrder /* * 듀얼주입 성공 */ class LOG_INJECT_DUAL_SUCCESS private constructor( val data: String, val dttm: String, typeAndKind: Byte, // 47.5=4750 val injectNormAmount: Short, // 47.5=4750 val injectSquareAmount: Short, // 1분단위 주입시간(124=124분=2시간4분) private val injectTime: Byte, val batteryRemain: Byte ) { val type: Byte = PumplogUtil.getType(typeAndKind) val kind: Byte = PumplogUtil.getKind(typeAndKind) fun getInjectTime(): Int { return injectTime and 0xff } override fun toString(): String { val sb = StringBuilder("LOG_INJECT_DUAL_SUCCESS{") sb.append("LOG_KIND=").append(LOG_KIND.toInt()) sb.append(", data='").append(data).append('\'') sb.append(", dttm='").append(dttm).append('\'') sb.append(", type=").append(type.toInt()) sb.append(", kind=").append(kind.toInt()) sb.append(", injectNormAmount=").append(injectNormAmount.toInt()) sb.append(", injectSquareAmount=").append(injectSquareAmount.toInt()) sb.append(", injectTime=").append(injectTime and 0xff) sb.append(", batteryRemain=").append(batteryRemain.toInt()) sb.append('}') return sb.toString() } companion object { const val LOG_KIND: Byte = 0x10 fun parse(data: String): LOG_INJECT_DUAL_SUCCESS { val bytes = PumplogUtil.hexStringToByteArray(data) val buffer = ByteBuffer.wrap(bytes) buffer.order(ByteOrder.LITTLE_ENDIAN) return LOG_INJECT_DUAL_SUCCESS( data, PumplogUtil.getDttm(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getShort(buffer), PumplogUtil.getShort(buffer), PumplogUtil.getByte(buffer), PumplogUtil.getByte(buffer) ) } } }
agpl-3.0
32e961131742c4abb037eeb2006734ba
32.333333
77
0.615808
4.014056
false
false
false
false
paslavsky/music-sync-manager
msm-server/src/main/kotlin/net/paslavsky/msm/setting/description/PropertyScope.kt
1
902
package net.paslavsky.msm.setting.description import javax.xml.bind.annotation.* /** * <p>Class for PropertyScope. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="PropertyScope"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="application"/> * &lt;enumeration value="user"/> * &lt;enumeration value="browser"/> * &lt;enumeration value="session"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * * @author Andrey Paslavsky * @version 1.0 */ XmlEnum XmlType(name = "PropertyScope", namespace = "http://paslavsky.net/property-description/1.0") public enum class PropertyScope { @XmlEnumValue("application") application, @XmlEnumValue("user") user, @XmlEnumValue("browser") browser, @XmlEnumValue("session") session }
apache-2.0
9ea25e0df7cfe34eef411e0d85e33fec
28.096774
95
0.686253
3.523438
false
false
false
false
naivekook/ZodiacView
zodiacview/src/main/java/io/github/naivekook/zodiacview/Star.kt
1
862
/** * Copyright 16/08/21 Vladimir Tanakov * * * 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 io.github.naivekook.zodiacview internal data class Star( var x: Float = 0f, var y: Float = 0f, var dirX: Float = 0f, var dirY: Float = 0f, var size: Float = 0f, var connectedStars: MutableList<Star> = mutableListOf() )
apache-2.0
bdb1981a5937936e04e97b99a4736b3e
29.785714
75
0.707657
3.683761
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/ui/item/holder/SongViewHolder.kt
1
4723
package com.sjn.stamp.ui.item.holder import android.app.Activity import android.content.Context import android.support.v4.app.Fragment import android.view.View import android.widget.ImageView import android.widget.TextView import com.sjn.stamp.R import com.sjn.stamp.ui.SongListFragmentFactory import com.sjn.stamp.utils.SongStateHelper import com.sjn.stamp.utils.ViewHelper import eu.davidea.flexibleadapter.FlexibleAdapter class SongViewHolder constructor(view: View, adapter: FlexibleAdapter<*>, activity: Activity) : StampContainsViewHolder(view, adapter, activity) { internal var mediaId: String = "" internal var albumArtView: ImageView = view.findViewById(R.id.image) internal var title: TextView = view.findViewById(R.id.title) internal var subtitle: TextView = view.findViewById(R.id.subtitle) internal var date: TextView = view.findViewById(R.id.date) internal var imageView: ImageView = view.findViewById(R.id.play_eq) private var _frontView: View = view.findViewById(R.id.front_view) init { this.imageView.setOnClickListener { mAdapter.mItemLongClickListener?.onItemLongClick(adapterPosition) } } fun createNextFragment(context: Context): Pair<Fragment, List<Pair<String, View>>> { return Pair(SongListFragmentFactory.create(mediaId).apply { arguments?.apply { putString("TITLE", title.text.toString()) putString("IMAGE_TYPE", albumArtView.getTag(R.id.image_view_album_art_type)?.toString()) putString("IMAGE_URL", albumArtView.getTag(R.id.image_view_album_art_url)?.toString()) putString("IMAGE_TEXT", albumArtView.getTag(R.id.image_view_album_art_text)?.toString()) } }, emptyList()) // var imageTransitionName = "" // var textTransitionName = "" // // if (CompatibleHelper.hasLollipop()) { // title.transitionName = "trans_text_" + mediaId + adapterPosition // albumArtView.transitionName = "trans_image_" + mediaId + adapterPosition // } // return Pair(SongListFragmentFactory.create(mediaId).apply { // if (CompatibleHelper.hasLollipop()) { // sharedElementReturnTransition = TransitionInflater.from(context).inflateTransition(R.transition.change_image_trans) // exitTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.fade) // // https://stackoverflow.com/questions/33641752/how-to-know-when-shared-element-transition-ends // sharedElementEnterTransition = TransitionInflater.from(context).inflateTransition(R.transition.change_image_trans)?.apply { // addListener(TransitionListenerAdapter()) // } // enterTransition = TransitionInflater.from(context).inflateTransition(android.R.transition.fade) // imageTransitionName = albumArtView.transitionName // textTransitionName = title.transitionName // } // arguments?.apply { // putString("TRANS_TITLE", textTransitionName) // putString("TRANS_IMAGE", imageTransitionName) // putString("TITLE", title.text.toString()) // putString("IMAGE_TYPE", albumArtView.getTag(R.id.image_view_album_art_type)?.toString()) // putString("IMAGE_URL", albumArtView.getTag(R.id.image_view_album_art_url)?.toString()) // putString("IMAGE_TEXT", albumArtView.getTag(R.id.image_view_album_art_text)?.toString()) // putParcelable("IMAGE_BITMAP", AlbumArtHelper.toBitmap(albumArtView.drawable)) // } // }, ArrayList<Pair<String, View>>().apply { // add(Pair(imageTransitionName, albumArtView)) // add(Pair(textTransitionName, title)) // }) } override fun getActivationElevation(): Float = ViewHelper.dpToPx(itemView.context, 4f) override fun getFrontView(): View = _frontView fun update(view: View, mediaId: String, isPlayable: Boolean) { val cachedState = view.getTag(R.id.tag_mediaitem_state_cache) as Int? val state = SongStateHelper.getMediaItemState(this.activity, mediaId, isPlayable) if (cachedState == null || cachedState != state) { val drawable = SongStateHelper.getDrawableByState(this.activity, state) if (drawable != null) { this.imageView.setImageDrawable(drawable) this.imageView.visibility = View.VISIBLE } else { this.imageView.visibility = View.GONE } view.setTag(R.id.tag_mediaitem_state_cache, state) } } }
apache-2.0
e452d4199c24f2928b9cd37254664531
50.347826
146
0.661867
4.357011
false
false
false
false
square/wire
wire-library/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/DurationJsonFormatter.kt
1
2765
/* * Copyright 2020 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.wire.internal import com.squareup.wire.Duration /** * Encode a duration as a JSON string like "1.200s". From the spec: * * > Generated output always contains 0, 3, 6, or 9 fractional digits, depending on required * > precision, followed by the suffix "s". Accepted are any fractional digits (also none) as long * > as they fit into nano-seconds precision and the suffix "s" is required. * * Note that [Duration] always returns a positive nanosPart, so "-1.200s" is represented as -2 * seconds and 800_000_000 nanoseconds. */ object DurationJsonFormatter : JsonFormatter<Duration> { override fun toStringOrNumber(value: Duration): String { var seconds = value.seconds var nanos = value.nano var prefix = "" if (seconds < 0L) { if (seconds == Long.MIN_VALUE) { prefix = "-922337203685477580" // Avoid overflow inverting MIN_VALUE. seconds = 8 } else { prefix = "-" seconds = -seconds } if (nanos != 0) { seconds -= 1L nanos = 1_000_000_000 - nanos } } return when { nanos == 0 -> "%s%ds".format(prefix, seconds) nanos % 1_000_000 == 0 -> "%s%d.%03ds".format(prefix, seconds, nanos / 1_000_000L) nanos % 1_000 == 0 -> "%s%d.%06ds".format(prefix, seconds, nanos / 1_000L) else -> "%s%d.%09ds".format(prefix, seconds, nanos / 1L) } } /** Throws a NumberFormatException if the string isn't a number like "1s" or "1.23456789s". */ override fun fromString(value: String): Duration { val sIndex = value.indexOf('s') if (sIndex != value.length - 1) throw NumberFormatException() val dotIndex = value.indexOf('.') if (dotIndex == -1) { val seconds = value.substring(0, sIndex).toLong() return Duration.ofSeconds(seconds) } val seconds = value.substring(0, dotIndex).toLong() var nanos = value.substring(dotIndex + 1, sIndex).toLong() if (value.startsWith("-")) nanos = -nanos val nanosDigits = sIndex - (dotIndex + 1) for (i in nanosDigits until 9) nanos *= 10 for (i in 9 until nanosDigits) nanos /= 10 return Duration.ofSeconds(seconds, nanos) } }
apache-2.0
cf78a2dbcc571a5742ca2fc61048edb3
35.866667
98
0.65859
3.798077
false
false
false
false
Maccimo/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/intention/impl/preview/IntentionPreviewModel.kt
1
9389
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.intention.impl.preview import com.intellij.diff.comparison.ComparisonManager import com.intellij.diff.comparison.ComparisonPolicy import com.intellij.diff.fragments.LineFragment import com.intellij.diff.fragments.LineFragmentImpl import com.intellij.openapi.diff.DiffColors import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.LineNumberConverter import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.markup.HighlighterLayer import com.intellij.openapi.editor.markup.HighlighterTargetArea import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.util.ui.JBUI import one.util.streamex.StreamEx import java.awt.Color internal class IntentionPreviewModel { companion object { fun reformatRange(project: Project, psiFileCopy: PsiFile, lineFragment: LineFragment) { val start = lineFragment.startOffset2 val end = lineFragment.endOffset2 if (start >= end) return val document = FileDocumentManager.getInstance().getDocument(psiFileCopy.viewProvider.virtualFile) if (document != null) PsiDocumentManager.getInstance(project).commitDocument(document) CodeStyleManager.getInstance(project).reformatRange(psiFileCopy, start, end, true) } private fun squash(lines: List<LineFragment>): List<LineFragment> = StreamEx.of(lines) .collapse({f1, f2 -> f2.startLine1 - f1.endLine1 == 1 && f2.startLine2 - f1.endLine2 == 1}, { f1, f2 -> LineFragmentImpl(f1.startLine1, f2.endLine1, f1.startLine2, f2.endLine2, f1.startOffset1, f2.endOffset1, f1.startOffset2, f2.endOffset2) }).toList() fun createEditors(project: Project, result: IntentionPreviewDiffResult?): List<EditorEx> { if (result == null) return emptyList() val psiFileCopy: PsiFile = result.psiFile val lines: List<LineFragment> = result.lineFragments if (result.fakeDiff) { lines.forEach { lineFragment -> reformatRange(project, psiFileCopy, lineFragment) } } val fileText = psiFileCopy.text val origText = result.origFile.text val diff = squash(ComparisonManager.getInstance().compareLines(origText, fileText, ComparisonPolicy.TRIM_WHITESPACES, DumbProgressIndicator.INSTANCE)) var diffs = diff.mapNotNull { fragment -> val start = getOffset(fileText, fragment.startLine2) val end = getOffset(fileText, fragment.endLine2) if (start > end) return@mapNotNull null val origStart = getOffset(origText, fragment.startLine1) val origEnd = getOffset(origText, fragment.endLine1) if (origStart > origEnd) return@mapNotNull null val newText = fileText.substring(start, end).trimStart('\n').trimEnd('\n').trimIndent() val oldText = origText.substring(origStart, origEnd).trimStart('\n').trimEnd('\n').trimIndent() val deleted = newText.isBlank() if (deleted) { if (oldText.isBlank()) return@mapNotNull null return@mapNotNull DiffInfo(oldText, fragment.startLine1, fragment.endLine1 - fragment.startLine1, HighlightingType.DELETED) } var highlightRange: TextRange? = null var highlightingType = HighlightingType.UPDATED if (fragment.endLine2 - fragment.startLine2 == 1 && fragment.endLine1 - fragment.startLine1 == 1) { val prefix = StringUtil.commonPrefixLength(oldText, newText) val suffix = StringUtil.commonSuffixLength(oldText, newText) if (prefix > 0 || suffix > 0) { var endPos = newText.length - suffix if (endPos > prefix) { highlightRange = TextRange.create(prefix, endPos) if (oldText.length - suffix == prefix) { highlightingType = HighlightingType.ADDED } } else { endPos = oldText.length - suffix if (endPos > prefix) { val deletedLength = oldText.length - newText.length endPos = deletedLength.coerceAtLeast(prefix + deletedLength) highlightRange = TextRange.create(prefix, endPos) highlightingType = HighlightingType.DELETED return@mapNotNull DiffInfo(oldText, fragment.startLine1, fragment.endLine1 - fragment.startLine1, highlightingType, highlightRange) } } } } return@mapNotNull DiffInfo(newText, fragment.startLine1, fragment.endLine2 - fragment.startLine2, highlightingType, highlightRange) } if (diffs.any { info -> info.highlightingType != HighlightingType.DELETED || info.updatedRange != null }) { // Do not display deleted fragments if anything is added diffs = diffs.filter { info -> info.highlightingType != HighlightingType.DELETED || info.updatedRange != null } } if (diffs.isNotEmpty()) { val last = diffs.last() val maxLine = if (result.fakeDiff) last.startLine + last.length else -1 return diffs.map { it.createEditor(project, result.origFile.fileType, maxLine) } } return emptyList() } private enum class HighlightingType { ADDED, UPDATED, DELETED } private data class DiffInfo(val fileText: String, val startLine: Int, val length: Int, val highlightingType: HighlightingType = HighlightingType.UPDATED, val updatedRange: TextRange? = null) { fun createEditor(project: Project, fileType: FileType, maxLine: Int): EditorEx { val editor = createEditor(project, fileType, fileText, startLine, maxLine) if (updatedRange != null) { val attr = when (highlightingType) { HighlightingType.UPDATED -> DiffColors.DIFF_MODIFIED HighlightingType.ADDED -> DiffColors.DIFF_INSERTED HighlightingType.DELETED -> DiffColors.DIFF_DELETED } editor.markupModel.addRangeHighlighter(attr, updatedRange.startOffset, updatedRange.endOffset, HighlighterLayer.ERROR + 1, HighlighterTargetArea.EXACT_RANGE) } else if (highlightingType == HighlightingType.DELETED) { val document = editor.document val lineCount = document.lineCount for (line in 0 until lineCount) { var start = document.getLineStartOffset(line) var end = document.getLineEndOffset(line) - 1 while (start <= end && Character.isWhitespace(fileText[start])) start++ while (start <= end && Character.isWhitespace(fileText[end])) end-- if (start <= end) { editor.markupModel.addRangeHighlighter(DiffColors.DIFF_DELETED, start, end + 1, HighlighterLayer.ERROR + 1, HighlighterTargetArea.EXACT_RANGE) } } } return editor } } private fun getOffset(fileText: String, lineNumber: Int): Int { return StringUtil.lineColToOffset(fileText, lineNumber, 0).let { pos -> if (pos == -1) fileText.length else pos } } private fun createEditor(project: Project, fileType: FileType, text: String, lineShift: Int, maxLine: Int): EditorEx { val editorFactory = EditorFactory.getInstance() val document = editorFactory.createDocument(text) val editor = (editorFactory.createEditor(document, project, fileType, false) as EditorEx) .apply { setBorder(JBUI.Borders.empty(2, 0, 2, 0)) } editor.settings.apply { isLineNumbersShown = maxLine != -1 isCaretRowShown = false isLineMarkerAreaShown = false isFoldingOutlineShown = false additionalColumnsCount = 4 additionalLinesCount = 0 isRightMarginShown = false isUseSoftWraps = false isAdditionalPageAtBottom = false } editor.backgroundColor = getEditorBackground() editor.settings.isUseSoftWraps = true editor.scrollingModel.disableAnimation() editor.gutterComponentEx.apply { isPaintBackground = false if (maxLine != -1) { setLineNumberConverter(object : LineNumberConverter { override fun convert(editor: Editor, line: Int): Int = line + lineShift override fun getMaxLineNumber(editor: Editor): Int = maxLine }) } } return editor } private fun getEditorBackground(): Color { return EditorColorsManager.getInstance().globalScheme.defaultBackground } } }
apache-2.0
9a747dbdef9a4a41634ad80fabdd69ed
45.485149
147
0.663329
4.817342
false
false
false
false
simone201/easy-auth0-java
src/main/kotlin/it/simonerenzo/easyauth0/client/Auth0Client.kt
1
11919
/* * Easy Auth0 Java Library * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/lgpl-3.0.html>. */ package it.simonerenzo.easyauth0.client import com.auth0.client.auth.AuthAPI import com.auth0.json.auth.TokenHolder import com.auth0.jwt.JWT import com.auth0.jwt.JWTVerifier import com.auth0.jwt.algorithms.Algorithm import com.auth0.jwt.exceptions.JWTVerificationException import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import it.simonerenzo.easyauth0.exceptions.LoginException import it.simonerenzo.easyauth0.models.Credentials import it.simonerenzo.easyauth0.models.RefreshResult import it.simonerenzo.easyauth0.models.User import mu.KLogging import okhttp3.FormBody import java.io.UnsupportedEncodingException import okhttp3.OkHttpClient import okhttp3.Request import org.apache.commons.validator.routines.UrlValidator import java.net.MalformedURLException /** * Auth0 Client Class * * Implements various helper methods to make life simpler. * Handles instance logged users, intended to be used as singleton. * * @property domain Auth0 Account domain URL * @property clientId application Client ID * @property clientSecret application Client Secret * @property connection users database in Auth0 * @constructor creates a single Auth0 client instance */ class Auth0Client(val domain: String, val clientId: String, val clientSecret: String, val connection: String) { // Auth0 Grants private val AUTH0_GRANT_REFRESH = "refresh_token" private val AUTH0_GRANT_REQUEST = "client_credentials" // Auth0 APIs private val AUTH0_OAUTH_TOKEN = "/oauth/token" // Auth0 Scopes private val AUTH0_SCOPE_OPENID = "openid" private val AUTH0_SCOPE_OFFACC = "offline_access" // JSON Keys private val KEY_ACCESS_TOKEN = "access_token" private val KEY_USERNAME = "username" private val KEY_NAME = "name" private val KEY_NICKNAME = "nickname" private val KEY_EMAIL = "email" // Kotlin Logger private companion object: KLogging() // Auth0 Client API private val authClient: AuthAPI = AuthAPI(domain, clientId, clientSecret) // OkHttp Client private val httpClient = OkHttpClient() // Jackson Parser private val jsonMapper = jacksonObjectMapper() // Auth0 JWT Verifier private val algorithm = Algorithm.HMAC256(clientSecret) private val verifier: JWTVerifier // Credentials Data private val credsMap: HashMap<String, Credentials> = HashMap() private val tokensMap: HashMap<String, String> = HashMap() // URLs private var fullUrl: String = "" // Initialization init { // Check domain and fix it if needed if (!domain.startsWith("https://") && !domain.startsWith("http://")) fullUrl = "https://$domain" else if (domain.startsWith("http://")) fullUrl = "https://" + domain.split("http://")[1] // Then check if it valid val validator = UrlValidator(UrlValidator.ALLOW_LOCAL_URLS) if(!validator.isValid(fullUrl)) throw MalformedURLException("Invalid Domain URL") // Now we can initialize the verifier with the domain verifier = JWT.require(algorithm) .withIssuer(fullUrl + "/") .acceptLeeway(1) .build() } /** * Do a simple authentication to Auth0 * * @param userOrEmail the username or email * @param password the user password * @return credentials object with logged user data */ fun login(userOrEmail: String, password: String): Credentials { logger.debug("User login request=[userOrEmail=$userOrEmail, password=$password]") try { // Get the auth tokens val tokenHolder = authClient.login(userOrEmail, password, connection) .setScope("$AUTH0_SCOPE_OPENID $AUTH0_SCOPE_OFFACC") .execute() return buildCredentials(tokenHolder) } catch (e: Exception) { logger.error(e) { e.message } throw LoginException(e.message!!) } } /** * Do a simple logout after being logged in * * @param accessToken logged user access token * @return logout result state */ fun logout(accessToken: String): Boolean { if (accessToken in tokensMap) { credsMap.remove(tokensMap[accessToken]) tokensMap.remove(accessToken) return true } else return false } /** * Validate an inbound access token * * @param idToken logged user id token * @return token validation result state */ fun validateAccessToken(idToken: String): Boolean { try { verifier.verify(idToken) return idToken in tokensMap } catch (e: UnsupportedEncodingException) { logger.error(e) { e.message } return false } catch (e: JWTVerificationException) { logger.error(e) { e.message } return false } } /** * Request a new access token by using a refresh token * * @param refreshToken logged user refresh token * @return credentials object with logged new user data */ fun refreshToken(refreshToken: String): Credentials? { val requestBody = FormBody.Builder() .add("grant_type", AUTH0_GRANT_REFRESH) .add("client_id", clientId) .add("client_secret", clientSecret) .add("refresh_token", refreshToken) .add("scope", AUTH0_SCOPE_OPENID) .build() val request = Request.Builder() .url("$fullUrl$AUTH0_OAUTH_TOKEN") .post(requestBody) .build() val response = httpClient.newCall(request).execute() if (response.isSuccessful) { try { return refreshCredentials(refreshToken, jsonMapper.readValue<RefreshResult>(response.body().string())) } catch(e: Exception) { logger.error(e) { e.message } throw LoginException("Refresh token request not valid: " + response.code() + " - " + response.message()) } } else { throw LoginException("Refresh token request failed: " + response.code() + " - " + response.message()) } } /** * Start a password reset flow * * @param email user email * @return request result state */ fun resetPassword(email: String): Boolean { try { authClient.resetPassword(email, connection).execute() return true } catch (e: Exception) { logger.error(e) { e.message } return false } } /** * Retrieve users from a realm * * @param audience api identifier * @return users list of the realm */ fun retrieveUsers(audience: String): MutableList<User> { val accessToken = grantRequest(audience) val request = Request.Builder() .url("$fullUrl/api/v2/users?connection=$connection") .header("Authorization", "Bearer $accessToken") .get().build() val response = httpClient.newCall(request).execute() val users = mutableListOf<User>() if(response.isSuccessful) { val jsonRoot = jsonMapper.readTree(response.body().string()) jsonRoot.asIterable().forEach { jsonNode -> val usr = User(jsonNode.get(KEY_NICKNAME).asText(), jsonNode.get(KEY_USERNAME).asText(), jsonNode.get(KEY_EMAIL).asText()) users.add(usr) } } else { logger.warn("Users request failed or no users found") } return users } /** * Grant an authorization request using audience * and Client ID and Secret tokens * * @param audience api identifier * @return access token to use APIs */ private fun grantRequest(audience: String): String { val requestBody = FormBody.Builder() .add("grant_type", AUTH0_GRANT_REQUEST) .add("client_id", clientId) .add("client_secret", clientSecret) .add("audience", audience) .build() val request = Request.Builder() .url("$fullUrl$AUTH0_OAUTH_TOKEN") .post(requestBody) .build() val response = httpClient.newCall(request).execute() if (response.isSuccessful) { try { val jsonNode = jsonMapper.readTree(response.body().string()) return jsonNode.get(KEY_ACCESS_TOKEN).asText("x.y.z") } catch (e: Exception) { logger.error(e) { e.message } } } return "x.y.z" } /** * Updates user credentials by injecting new idToken (access token) after refresh, * may throw NPE because of security purposes * * @param refreshToken request refresh_token to search for user * @param refreshResult result parsed from refresh request * @return updated credentials object with new idToken (access token) */ private fun refreshCredentials(refreshToken: String, refreshResult: RefreshResult): Credentials? { var updatedCred: Credentials? = null credsMap.forEach { _, credentials -> if (credentials.refreshToken == refreshToken) { tokensMap.remove(credentials.accessToken) tokensMap.put(refreshResult.idToken, credentials.user.email) credentials.accessToken = refreshResult.idToken credentials.expiresIn = refreshResult.expiresIn updatedCred = credentials return@forEach } } return updatedCred } /** * Builds Credentials object based on TokenHolder data * * @param tokenHolder Auth0 TokenHolder object from previous request * @return credentials object with logged user data */ private fun buildCredentials(tokenHolder: TokenHolder): Credentials { // Get logged user info val userInfo = authClient.userInfo(tokenHolder.accessToken) .execute() .values // Clean any eventual duplicate in data maps tokensMap.remove(credsMap[userInfo[KEY_EMAIL]]?.accessToken) credsMap.remove(userInfo[KEY_EMAIL]) // Parse info as User object val loggedUser = User(userInfo[KEY_NICKNAME] as String, userInfo[KEY_NAME] as String, userInfo[KEY_EMAIL] as String) // Parse auth data to Credentials object val credentials = Credentials(loggedUser, tokenHolder.idToken, tokenHolder.refreshToken, tokenHolder.expiresIn) // Save the new credentials credsMap.put(credentials.user.email, credentials) tokensMap.put(credentials.accessToken, credentials.user.email) return credentials } }
lgpl-3.0
a26e38dceea3f40478684f53d50e577a
32.483146
102
0.619096
4.742937
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/action/copy/PutVisualTextAction.kt
1
3453
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.action.copy import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimCaret import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.command.Command import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.command.OperatorArguments import com.maddyhome.idea.vim.group.visual.VimSelection import com.maddyhome.idea.vim.handler.VisualOperatorActionHandler import com.maddyhome.idea.vim.helper.enumSetOf import com.maddyhome.idea.vim.put.PutData import java.util.* /** * @author vlan */ sealed class PutVisualTextBaseAction( private val insertTextBeforeCaret: Boolean, private val indent: Boolean, private val caretAfterInsertedText: Boolean, ) : VisualOperatorActionHandler.SingleExecution() { override val type: Command.Type = Command.Type.OTHER_SELF_SYNCHRONIZED override val flags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_EXIT_VISUAL) override fun executeForAllCarets( editor: VimEditor, context: ExecutionContext, cmd: Command, caretsAndSelections: Map<VimCaret, VimSelection>, operatorArguments: OperatorArguments, ): Boolean { if (caretsAndSelections.isEmpty()) return false val count = cmd.count val caretToPutData = editor.sortedCarets().associateWith { getPutDataForCaret(it, caretsAndSelections[it], count) } injector.registerGroup.resetRegister() var result = true injector.application.runWriteAction { caretToPutData.forEach { result = injector.put.putTextForCaret(editor, it.key, context, it.value, true) && result } } return result } private fun getPutDataForCaret(caret: VimCaret, selection: VimSelection?, count: Int): PutData { val lastRegisterChar = injector.registerGroup.lastRegisterChar val register = caret.registerStorage.getRegister(caret, lastRegisterChar) val textData = register?.let { PutData.TextData( register.text ?: injector.parser.toPrintableString(register.keys), register.type, register.transferableData ) } val visualSelection = selection?.let { PutData.VisualSelection(mapOf(caret to it), it.type) } return PutData(textData, visualSelection, count, insertTextBeforeCaret, indent, caretAfterInsertedText) } } class PutVisualTextBeforeCursorAction : PutVisualTextBaseAction(insertTextBeforeCaret = true, indent = true, caretAfterInsertedText = false) class PutVisualTextAfterCursorAction : PutVisualTextBaseAction(insertTextBeforeCaret = false, indent = true, caretAfterInsertedText = false) class PutVisualTextBeforeCursorNoIndentAction : PutVisualTextBaseAction(insertTextBeforeCaret = true, indent = false, caretAfterInsertedText = false) class PutVisualTextAfterCursorNoIndentAction : PutVisualTextBaseAction(insertTextBeforeCaret = false, indent = false, caretAfterInsertedText = false) class PutVisualTextBeforeCursorMoveCursorAction : PutVisualTextBaseAction(insertTextBeforeCaret = true, indent = true, caretAfterInsertedText = true) class PutVisualTextAfterCursorMoveCursorAction : PutVisualTextBaseAction(insertTextBeforeCaret = false, indent = true, caretAfterInsertedText = true)
mit
a9f8ca2a569dd2d61071526bc795c1f0
42.708861
149
0.786852
4.321652
false
false
false
false
DomBlack/mal
kotlin/src/mal/step2_eval.kt
18
1961
package mal fun read(input: String?): MalType = read_str(input) fun eval(ast: MalType, env: Map<String, MalType>): MalType = if (ast is MalList && ast.count() > 0) { val evaluated = eval_ast(ast, env) as ISeq if (evaluated.first() !is MalFunction) throw MalException("cannot execute non-function") (evaluated.first() as MalFunction).apply(evaluated.rest()) } else eval_ast(ast, env) fun eval_ast(ast: MalType, env: Map<String, MalType>): MalType = when (ast) { is MalSymbol -> env[ast.value] ?: throw MalException("'${ast.value}' not found") is MalList -> ast.elements.fold(MalList(), { a, b -> a.conj_BANG(eval(b, env)); a }) is MalVector -> ast.elements.fold(MalVector(), { a, b -> a.conj_BANG(eval(b, env)); a }) is MalHashMap -> ast.elements.entries.fold(MalHashMap(), { a, b -> a.assoc_BANG(b.key, eval(b.value, env)); a }) else -> ast } fun print(result: MalType) = pr_str(result, print_readably = true) fun main(args: Array<String>) { val env = hashMapOf( Pair("+", MalFunction({ a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger + y as MalInteger }) })), Pair("-", MalFunction({ a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger - y as MalInteger }) })), Pair("*", MalFunction({ a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger * y as MalInteger }) })), Pair("/", MalFunction({ a: ISeq -> a.seq().reduce({ x, y -> x as MalInteger / y as MalInteger }) })) ) while (true) { val input = readline("user> ") try { println(print(eval(read(input), env))) } catch (e: EofException) { break } catch (e: MalContinue) { } catch (e: MalException) { println("Error: " + e.message) } catch (t: Throwable) { println("Uncaught " + t + ": " + t.message) } } }
mpl-2.0
1b42cedbabf7743ac3a8e54edf1046ec
42.577778
124
0.5436
3.604779
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/liftOut/ifToAssignment/hasNull.kt
13
172
fun bar(i: Int) { var str: String? = null <caret>if (i == 1) { str = null } else if (i == 2) { str = "2" } else { str = "3" } }
apache-2.0
77ff4cedf45d796965903e299694358f
14.727273
27
0.360465
2.819672
false
false
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/primary/kotlin/net/kourlas/voipms_sms/billing/Billing.kt
1
6737
/* * VoIP.ms SMS * Copyright (C) 2021 Michael Kourlas * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.kourlas.voipms_sms.billing import android.annotation.SuppressLint import android.content.Context import android.content.Intent import androidx.fragment.app.FragmentActivity import com.android.billingclient.api.* import com.android.billingclient.api.BillingClient.BillingResponseCode import com.android.billingclient.api.Purchase.PurchaseState import kotlinx.coroutines.* import net.kourlas.voipms_sms.R import net.kourlas.voipms_sms.utils.logException import net.kourlas.voipms_sms.utils.showSnackbar import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class Billing(private val context: Context) : PurchasesUpdatedListener, BillingClientStateListener { private val client = BillingClient.newBuilder(context) .enablePendingPurchases() .setListener(this) .build() private var connected = false init { // Initialize the billing client when the singleton is first // initialized. try { client.startConnection(this) } catch (e: Exception) { logException(e) } } suspend fun askForCoffee(activity: FragmentActivity) { try { // If the client is not connected, we can't do anything. if (!connected) { showSnackbar( activity, R.id.coordinator_layout, activity.getString( R.string.coffee_fail_google_play ) ) return } // Consume the purchase if it hasn't been consumed yet. val purchasesList = suspendCoroutine<List<Purchase>> { client.queryPurchasesAsync(SKU) { result, purchases -> if (result.responseCode == BillingResponseCode.OK) { it.resume(purchases) } else { it.resume(emptyList()) } } } consumeDonationPurchases(purchasesList) // Get the SKU. val skuDetails = getCoffeeSkuDetails() if (skuDetails == null) { showSnackbar( activity, R.id.coordinator_layout, activity.getString( R.string.coffee_fail_unknown ) ) return } // Open the purchase flow for that SKU. val flowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetails) .build() client.launchBillingFlow(activity, flowParams) } catch (e: Exception) { logException(e) showSnackbar( activity, R.id.coordinator_layout, activity.getString( R.string.coffee_fail_unknown ) ) } } @OptIn(DelicateCoroutinesApi::class) override fun onPurchasesUpdated( result: BillingResult, purchases: MutableList<Purchase>? ) { if (result.responseCode == BillingResponseCode.OK && purchases != null ) { GlobalScope.launch { consumeDonationPurchases(purchases) } } } override fun onBillingSetupFinished(result: BillingResult) { connected = result.responseCode == BillingResponseCode.OK } override fun onBillingServiceDisconnected() { connected = false } private suspend fun consumeDonationPurchases(purchases: List<Purchase>) = withContext(Dispatchers.IO) { for (purchase in purchases) { if (purchase.skus.contains(SKU) && purchase.purchaseState == PurchaseState.PURCHASED ) { val coffeeCompleteBroadcastIntent = Intent( context.getString( R.string.coffee_complete_action ) ) context.sendBroadcast(coffeeCompleteBroadcastIntent) val consumeParams = ConsumeParams.newBuilder() .setPurchaseToken(purchase.purchaseToken).build() suspendCoroutine<Unit> { client.consumeAsync(consumeParams) { _, _ -> it.resume(Unit) } } } } } private suspend fun getCoffeeSkuDetails() = withContext(Dispatchers.IO) { val skuDetailsParams = SkuDetailsParams.newBuilder() skuDetailsParams .setSkusList(listOf(SKU)) .setType(BillingClient.SkuType.INAPP) val skuDetailsList = suspendCoroutine<List<SkuDetails>> { client.querySkuDetailsAsync( skuDetailsParams.build() ) { result, details -> if (result.responseCode == BillingResponseCode.OK && details != null ) { it.resume(details) } else { it.resume(emptyList()) } } } if (skuDetailsList.size == 1 && skuDetailsList[0].sku == SKU) { skuDetailsList[0] } else { null } } companion object { // It is not a leak to store an instance to the application context, // since it has the same lifetime as the application itself. @SuppressLint("StaticFieldLeak") private var instance: Billing? = null // The SKU for buying me a coffee. private const val SKU = "coffee" /** * Gets the sole instance of the Billing class. Initializes the * instance if it does not already exist. */ fun getInstance(context: Context): Billing = instance ?: synchronized(this) { instance ?: Billing( context.applicationContext ).also { instance = it } } } }
apache-2.0
82ec0ac9a0f64dba836c493a536df8dc
33.030303
77
0.559151
5.402566
false
false
false
false
ingokegel/intellij-community
plugins/settings-repository/testSrc/SettingsRepositoryGitTest.kt
12
12713
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.settingsRepository.test import com.intellij.configurationStore.ApplicationStoreImpl import com.intellij.configurationStore.write import com.intellij.openapi.vcs.merge.MergeSession import com.intellij.testFramework.file import com.intellij.util.PathUtilRt import com.intellij.util.io.delete import com.intellij.util.io.writeChild import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.jetbrains.settingsRepository.CannotResolveConflictInTestMode import org.jetbrains.settingsRepository.SyncType import org.jetbrains.settingsRepository.conflictResolver import org.jetbrains.settingsRepository.copyLocalConfig import org.jetbrains.settingsRepository.git.commit import org.jetbrains.settingsRepository.git.computeIndexDiff import org.jetbrains.settingsRepository.git.deletePath import org.jetbrains.settingsRepository.git.writePath import org.junit.Test import java.util.* val MARKER_ACCEPT_MY = "__accept my__".toByteArray() val MARKER_ACCEPT_THEIRS = "__accept theirs__".toByteArray() internal class SettingsRepositoryGitTest : SettingsRepositoryGitTestBase() { init { conflictResolver = { files, mergeProvider -> val mergeSession = mergeProvider.createMergeSession(files) for (file in files) { val mergeData = mergeProvider.loadRevisions(file) if (Arrays.equals(mergeData.CURRENT, MARKER_ACCEPT_MY) || Arrays.equals(mergeData.LAST, MARKER_ACCEPT_THEIRS)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedYours) } else if (mergeData.CURRENT!!.contentEquals(MARKER_ACCEPT_THEIRS) || mergeData.LAST!!.contentEquals(MARKER_ACCEPT_MY)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedTheirs) } else if (Arrays.equals(mergeData.LAST, MARKER_ACCEPT_MY)) { file.setBinaryContent(mergeData.LAST) mergeProvider.conflictResolvedForFile(file) } else { throw CannotResolveConflictInTestMode() } } } } @Test fun add() { provider.write(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) val diff = repository.computeIndexDiff() assertThat(diff.diff()).isTrue() assertThat(diff.added).containsOnly(SAMPLE_FILE_NAME) assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } @Test fun addSeveral() { val addedFile = "foo.xml" val addedFile2 = "bar.xml" provider.write(addedFile, "foo") provider.write(addedFile2, "bar") val diff = repository.computeIndexDiff() assertThat(diff.diff()).isTrue() assertThat(diff.added).containsOnly(addedFile, addedFile2) assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } @Test fun delete() { fun delete(directory: Boolean) { val dir = "dir" val fullFileSpec = "$dir/file.xml" provider.write(fullFileSpec, SAMPLE_FILE_CONTENT) provider.delete(if (directory) dir else fullFileSpec) val diff = repository.computeIndexDiff() assertThat(diff.diff()).isFalse() assertThat(diff.added).isEmpty() assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() } delete(false) delete(true) } @Test fun `set upstream`() { val url = "https://github.com/user/repo.git" repositoryManager.setUpstream(url) assertThat(repositoryManager.getUpstream()).isEqualTo(url) } @Test fun pullToRepositoryWithoutCommits() = runBlocking { doPullToRepositoryWithoutCommits(null) } @Test fun pullToRepositoryWithoutCommitsAndCustomRemoteBranchName() = runBlocking { doPullToRepositoryWithoutCommits("customRemoteBranchName") } private suspend fun doPullToRepositoryWithoutCommits(remoteBranchName: String?) { createLocalAndRemoteRepositories(remoteBranchName) repositoryManager.pull() compareFiles(repository.workTreePath, remoteRepository.workTreePath) } @Test fun pullToRepositoryWithCommits() = runBlocking { doPullToRepositoryWithCommits(null) } @Test fun pullToRepositoryWithCommitsAndCustomRemoteBranchName() = runBlocking { doPullToRepositoryWithCommits("customRemoteBranchName") } private suspend fun doPullToRepositoryWithCommits(remoteBranchName: String?) { createLocalAndRemoteRepositories(remoteBranchName) val file = addAndCommit("local.xml") repositoryManager.commit() repositoryManager.pull() assertThat(repository.workTree.resolve(file.name)).hasBinaryContent(file.data) compareFiles(repository.workTreePath, remoteRepository.workTreePath, PathUtilRt.getFileName(file.name)) } // never was merged. we reset using "merge with strategy "theirs", so, we must test - what's happen if it is not first merge? - see next test @Test fun resetToTheirsIfFirstMerge() = runBlocking<Unit> { createLocalAndRemoteRepositories(initialCommit = true) sync(SyncType.OVERWRITE_LOCAL) fs .file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) .compare() } @Test fun `overwrite local - second merge is null`() = runBlocking { createLocalAndRemoteRepositories(initialCommit = true) sync(SyncType.MERGE) restoreRemoteAfterPush() fun testRemote() { fs .file("local.xml", """<file path="local.xml" />""") .file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) .compare() } testRemote() addAndCommit("_mac/local2.xml") sync(SyncType.OVERWRITE_LOCAL) fs.compare() // test: merge and push to remote after such reset sync(SyncType.MERGE) restoreRemoteAfterPush() testRemote() } @Test fun `merge - resolve conflicts to my`() = runBlocking<Unit> { createLocalAndRemoteRepositories() val data = MARKER_ACCEPT_MY provider.write(SAMPLE_FILE_NAME, data) sync(SyncType.MERGE) restoreRemoteAfterPush() fs.file(SAMPLE_FILE_NAME, data.toString(Charsets.UTF_8)).compare() } @Test fun `merge - theirs file deleted, my modified, accept theirs`() = runBlocking<Unit> { createLocalAndRemoteRepositories() sync(SyncType.MERGE) val data = MARKER_ACCEPT_THEIRS provider.write(SAMPLE_FILE_NAME, data) repositoryManager.commit() remoteRepository.deletePath(SAMPLE_FILE_NAME) remoteRepository.commit("delete $SAMPLE_FILE_NAME") sync(SyncType.MERGE) fs.compare() } @Test fun `merge - my file deleted, theirs modified, accept my`() = runBlocking<Unit> { createLocalAndRemoteRepositories() sync(SyncType.MERGE) provider.delete(SAMPLE_FILE_NAME) repositoryManager.commit() remoteRepository.writePath(SAMPLE_FILE_NAME, MARKER_ACCEPT_THEIRS) remoteRepository.commit("") sync(SyncType.MERGE) restoreRemoteAfterPush() fs.compare() } @Test fun `commit if unmerged`() = runBlocking<Unit> { createLocalAndRemoteRepositories() val data = "<foo />" provider.write(SAMPLE_FILE_NAME, data) try { sync(SyncType.MERGE) } catch (e: CannotResolveConflictInTestMode) { } // repository in unmerged state conflictResolver = {files, mergeProvider -> assertThat(files).hasSize(1) assertThat(files.first().path).isEqualTo(SAMPLE_FILE_NAME) val mergeSession = mergeProvider.createMergeSession(files) mergeSession.conflictResolvedForFile(files.first(), MergeSession.Resolution.AcceptedTheirs) } sync(SyncType.MERGE) fs.file(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT).compare() } // remote is uninitialized (empty - initial commit is not done) @Test fun `merge with uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.MERGE) } @Test fun `overwrite remote - uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.OVERWRITE_REMOTE) } @Test fun `overwrite local - uninitialized upstream`() { doSyncWithUninitializedUpstream(SyncType.OVERWRITE_LOCAL) } @Test fun `remove deleted files`() = runBlocking<Unit> { createLocalAndRemoteRepositories() val workDir = repositoryManager.repository.workTree.toPath() provider.write("foo.xml", SAMPLE_FILE_CONTENT) sync(SyncType.MERGE) var diff = repository.computeIndexDiff() assertThat(diff.diff()).isFalse() val file = workDir.resolve("foo.xml") assertThat(file).isRegularFile() file.delete() diff = repository.computeIndexDiff() assertThat(diff.diff()).isTrue() assertThat(diff.added).isEmpty() assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).isEmpty() assertThat(diff.missing).containsOnly("foo.xml") sync(SyncType.MERGE) diff = repository.computeIndexDiff() assertThat(diff.diff()).isFalse() } @Test fun gitignore() = runBlocking { createLocalAndRemoteRepositories() provider.write(".gitignore", "*.html") sync(SyncType.MERGE) val workDir = repositoryManager.repository.workTree.toPath() val filePaths = listOf("bar.html", "i/am/a/long/path/to/file/foo.html") for (path in filePaths) { provider.write(path, path) } fun assertThatFileExist() { for (path in filePaths) { assertThat(workDir.resolve(path)).isRegularFile() } } assertThatFileExist() fun assertStatus() { val diff = repository.computeIndexDiff() assertThat(diff.diff()).isFalse() assertThat(diff.added).isEmpty() assertThat(diff.changed).isEmpty() assertThat(diff.removed).isEmpty() assertThat(diff.modified).isEmpty() assertThat(diff.untracked).isEmpty() assertThat(diff.untrackedFolders).containsOnly("i") } assertStatus() for (path in filePaths) { provider.read(path) { assertThat(it).isNotNull() } } assertThatFileExist() sync(SyncType.MERGE) assertThatFileExist() assertStatus() } @Test fun `initial copy to repository - no local files`() = runBlocking { createRemoteRepository(initialCommit = false) // check error during findRemoteRefUpdatesFor (no master ref) testInitialCopy(false) } @Test fun `initial copy to repository - some local files`() = runBlocking { createRemoteRepository(initialCommit = false) // check error during findRemoteRefUpdatesFor (no master ref) testInitialCopy(true) } @Test fun `initial copy to repository - remote files removed`() = runBlocking { createRemoteRepository(initialCommit = true) // check error during findRemoteRefUpdatesFor (no master ref) testInitialCopy(true, SyncType.OVERWRITE_REMOTE) } private suspend fun testInitialCopy(addLocalFiles: Boolean, syncType: SyncType = SyncType.MERGE) { repositoryManager.createRepositoryIfNeeded() repositoryManager.setUpstream(remoteRepository.workTree.absolutePath) val store = ApplicationStoreImpl() val localConfigPath = tempDirManager.newPath("local_config", refreshVfs = true) val lafData = """<application> <component name="UISettings"> <option name="HIDE_TOOL_STRIPES" value="false" /> </component> </application>""" if (addLocalFiles) { localConfigPath.writeChild("options/ui.lnf.xml", lafData) } store.setPath(localConfigPath) store.storageManager.addStreamProvider(provider) icsManager.sync(syncType, projectRule.project) { copyLocalConfig(store.storageManager) } if (addLocalFiles) { assertThat(localConfigPath).isDirectory() fs .file("ui.lnf.xml", lafData) restoreRemoteAfterPush() } else { assertThat(localConfigPath).doesNotExist() } fs.compare() } private fun doSyncWithUninitializedUpstream(syncType: SyncType) = runBlocking<Unit> { createRemoteRepository(initialCommit = false) repositoryManager.setUpstream(remoteRepository.workTree.absolutePath) val path = "local.xml" val data = "<application />" provider.write(path, data) sync(syncType) if (syncType != SyncType.OVERWRITE_LOCAL) { fs.file(path, data) } restoreRemoteAfterPush() fs.compare() } }
apache-2.0
ec7fe553893f15eed9111a911961dbea
29.489209
143
0.715409
4.571377
false
true
false
false
Emberwalker/Forgelin
src/dev/kotlin/io/drakon/forgelin/debug/ForgelinWorkbenchClass.kt
1
1387
package io.drakon.forgelin.debug import net.minecraftforge.fml.common.event.FMLInitializationEvent import net.minecraftforge.fml.common.event.FMLPostInitializationEvent import net.minecraftforge.fml.common.event.FMLPreInitializationEvent import org.apache.logging.log4j.LogManager import kotlin.platform.platformStatic import net.minecraftforge.fml.common.Mod as mod import net.minecraftforge.fml.common.Mod.EventHandler as handler import net.minecraftforge.fml.common.SidedProxy as proxy /** * Test mod (class-style) */ mod(modid = "Forgelin-Workbench-Class", name = "Forgelin Debug - Class", modLanguageAdapter = "KotlinAdapter") public class ForgelinWorkbenchClass { private val log = LogManager.getLogger("Workbench/Cls") companion object { proxy(clientSide = "io.drakon.forgelin.debug.ProxyClient", serverSide = "io.drakon.forgelin.debug.ProxyServer") platformStatic var proxy: Proxy? = null // Cannot be private, crashes the Kotlin compiler // platformStatic will indicate to the compiler that the field should be a top-level static field } public handler fun preinit(evt:FMLPreInitializationEvent) { log.info("Preinit.") } public handler fun init(evt: FMLInitializationEvent) { log.info("Init.") } public handler fun postinit(evt: FMLPostInitializationEvent) { log.info("Postinit.") } }
isc
d3734695c69a3eb9c571e314e5bef010
35.526316
119
0.754867
4.320872
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/serialonly/AtHopTransitData.kt
1
3180
/* * AtHopStubTransitData.kt * * Copyright 2015 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.serialonly import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.desfire.DesfireCard import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.transit.CardInfo import au.id.micolous.metrodroid.transit.TransitIdentity import au.id.micolous.metrodroid.transit.TransitRegion import au.id.micolous.metrodroid.util.NumberUtils /** * Stub implementation for AT HOP (Auckland, NZ). * * * https://github.com/micolous/metrodroid/wiki/AT-HOP */ @Parcelize data class AtHopTransitData (private val mSerial: Int?): SerialOnlyTransitData() { override val reason: SerialOnlyTransitData.Reason get() = SerialOnlyTransitData.Reason.LOCKED override val serialNumber get() = formatSerial(mSerial) override val cardName get() = NAME companion object { private const val APP_ID_SERIAL = 0xffffff private const val NAME = "AT HOP" private val CARD_INFO = CardInfo( name = NAME, locationId = R.string.location_auckland, cardType = CardType.MifareDesfire, imageId = R.drawable.athopcard, imageAlphaId = R.drawable.iso7810_id1_alpha, region = TransitRegion.NEW_ZEALAND, resourceExtraNote = R.string.card_note_card_number_only) private fun getSerial(card: DesfireCard) = card.getApplication(APP_ID_SERIAL)?.getFile(8)?.data?.getBitsFromBuffer( 61, 32) private fun formatSerial(serial: Int?) = if (serial != null) "7824 6702 " + NumberUtils.formatNumber(serial.toLong(), " ", 4, 4, 3) else null val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory { override fun earlyCheck(appIds: IntArray) = (0x4055 in appIds) && (APP_ID_SERIAL in appIds) override fun parseTransitData(card: DesfireCard) = AtHopTransitData(mSerial = getSerial(card)) override fun parseTransitIdentity(card: DesfireCard) = TransitIdentity(NAME, formatSerial(getSerial(card))) override val allCards get() = listOf(CARD_INFO) } } }
gpl-3.0
cd4325b3dd34003091827c36e3bd572c
37.780488
90
0.677044
4.320652
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/hsl/HSLTransitData.kt
1
8157
/* * HSLTransitData.kt * * Copyright 2013 Lauri Andler <[email protected]> * Copyright 2018 Michael Farrell <[email protected]> * Copyright 2019 Google * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.transit.hsl import au.id.micolous.metrodroid.card.CardType import au.id.micolous.metrodroid.card.desfire.DesfireApplication import au.id.micolous.metrodroid.card.desfire.DesfireCard import au.id.micolous.metrodroid.card.desfire.DesfireCardTransitFactory import au.id.micolous.metrodroid.card.desfire.files.RecordDesfireFile import au.id.micolous.metrodroid.multi.Parcelize import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.multi.VisibleForTesting import au.id.micolous.metrodroid.transit.* import au.id.micolous.metrodroid.ui.ListItem import au.id.micolous.metrodroid.util.NumberUtils /** * Implements a reader for HSL transit cards. * * Documentation and sample libraries for this are available at: * http://dev.hsl.fi/#travel-card * * The documentation (in Finnish) is available at: * http://dev.hsl.fi/hsl-card-java/HSL-matkakortin-kuvaus.pdf (old) * https://github.com/HSLdevcom/hsl-card-java/blob/master/HSL%20Matkakortin%20kuvaus%20ja%20API%20kehitt%C3%A4jille%20v1.11.pdf (new) * * Machine translation to English: * https://translate.google.com/translate?sl=auto&tl=en&js=y&prev=_t&hl=en&ie=UTF-8&u=http%3A%2F%2Fdev.hsl.fi%2Fhsl-card-java%2FHSL-matkakortin-kuvaus.pdf&edit-text=&act=url */ @Parcelize class HSLTransitData(override val serialNumber: String?, private val mBalance: Int, override val trips: List<Trip>, override val subscriptions: List<Subscription>?, val applicationVersion: Int?, val applicationKeyVersion: Int?, val platformType: Int?, val securityLevel: Int?, val version: Variant) : TransitData() { override fun getRawFields(level: RawLevel): List<ListItem> = super.getRawFields(level).orEmpty() + listOf( ListItem("Application version", applicationVersion.toString()), ListItem("Application key version", applicationKeyVersion.toString()), ListItem("Platform type", platformType.toString()), ListItem("Security Level", securityLevel.toString()) ) override val cardName: String get() = if (version == Variant.WALTTI) CARD_NAME_WALTTI else CARD_NAME_HSL public override val balance: TransitCurrency? get() = TransitCurrency.EUR(mBalance) enum class Variant { HSL_V1, HSL_V2, WALTTI; } companion object { private fun parseTrips(app: DesfireApplication, version: Variant): List<HSLTransaction> { val recordFile = app.getFile(0x04) as? RecordDesfireFile ?: return listOf() return recordFile.records.mapNotNull { HSLTransaction.parseLog(it, version) } } private fun addEmbedTransaction(trips: MutableList<HSLTransaction>, embed: HSLTransaction) { val sameIdx = trips.indices.find { idx -> trips[idx].timestamp == embed.timestamp } if (sameIdx != null) { val same = trips[sameIdx] trips.removeAt(sameIdx) trips.add(HSLTransaction.merge(same, embed)) } else { trips.add(embed) } } private fun parse(app: DesfireApplication, version: Variant): HSLTransitData { val appInfo = app.getFile(0x08)?.data val serialNumber = appInfo?.toHexString()?.substring(2, 20)?.let { formatSerial(it) } val balData = app.getFile(0x02)!!.data val mBalance = balData.getBitsFromBuffer(0, 20) val mLastRefill = HSLRefill.parse(balData) val trips = parseTrips(app, version).toMutableList() val arvo = app.getFile(0x03)?.data?.let { HSLArvo.parse(it, version) } val kausi = app.getFile(0x01)?.data?.let { HSLKausi.parse(it, version) } arvo?.lastTransaction?.let { addEmbedTransaction(trips, it) } kausi?.transaction?.let { addEmbedTransaction(trips, it) } return HSLTransitData(serialNumber = serialNumber, subscriptions = kausi?.subs.orEmpty() + listOfNotNull(arvo), mBalance = mBalance, //Read data from application info applicationVersion = appInfo?.getBitsFromBuffer(0, 4), applicationKeyVersion = appInfo?.getBitsFromBuffer(4, 4), platformType = appInfo?.getBitsFromBuffer(80, 3), securityLevel = appInfo?.getBitsFromBuffer(83, 1), trips = TransactionTrip.merge(trips + listOfNotNull(mLastRefill)), version = version) } private const val CARD_NAME_HSL = "HSL" private const val CARD_NAME_WALTTI = "Waltti" private val HSL_CARD_INFO = CardInfo( imageId = R.drawable.hsl_card, name = CARD_NAME_HSL, locationId = R.string.location_helsinki_finland, resourceExtraNote = R.string.hsl_extra_note, region = TransitRegion.FINLAND, cardType = CardType.MifareDesfire) private val WALTTI_CARD_INFO = CardInfo( imageId = R.drawable.waltti_logo, name = CARD_NAME_WALTTI, locationId = R.string.location_finland, region = TransitRegion.FINLAND, cardType = CardType.MifareDesfire) private const val APP_ID_V1 = 0x1120ef @VisibleForTesting const val APP_ID_V2 = 0x1420ef private const val APP_ID_WALTTI = 0x10ab private val HSL_IDS = listOf(APP_ID_V1, APP_ID_V2) private val ALL_IDS = HSL_IDS + listOf(APP_ID_WALTTI) fun formatSerial(input: String) = input.let { NumberUtils.groupString(it, " ", 6, 4, 4) } val FACTORY: DesfireCardTransitFactory = object : DesfireCardTransitFactory { override val allCards: List<CardInfo> get() = listOf(HSL_CARD_INFO, WALTTI_CARD_INFO) override fun getCardInfo(appIds: IntArray): CardInfo? = if (HSL_IDS.any { it in appIds }) HSL_CARD_INFO else WALTTI_CARD_INFO override fun earlyCheck(appIds: IntArray) = ALL_IDS.any { it in appIds } override fun parseTransitData(card: DesfireCard) = card.getApplication(APP_ID_V1)?.let { parse(it, Variant.HSL_V1) } ?: card.getApplication(APP_ID_V2)?.let { parse(it, Variant.HSL_V2) } ?: card.getApplication(APP_ID_WALTTI)?.let { parse(it, Variant.WALTTI) } override fun parseTransitIdentity(card: DesfireCard): TransitIdentity { val dataHSL = card.getApplication(APP_ID_V1)?.getFile(0x08)?.data ?: card.getApplication(APP_ID_V2)?.getFile(0x08)?.data if (dataHSL != null) return TransitIdentity(CARD_NAME_HSL, formatSerial(dataHSL.toHexString().substring(2, 20))) val dataWaltti = card.getApplication(APP_ID_WALTTI)?.getFile(0x08)?.data if (dataWaltti != null) return TransitIdentity(CARD_NAME_WALTTI, formatSerial(dataWaltti.toHexString().substring(2, 20))) return TransitIdentity(CARD_NAME_HSL, null) } } } }
gpl-3.0
596b4e3e3e735d6be8baf13571ace4a4
44.825843
173
0.638102
4.064275
false
false
false
false
GunoH/intellij-community
plugins/gradle/java/testSources/execution/test/runner/GradleRerunFailedTestsTestCase.kt
1
6976
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution.test.runner import com.intellij.execution.executors.DefaultRunExecutor.EXECUTOR_ID import com.intellij.execution.process.ProcessHandler import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.testframework.TestConsoleProperties import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.ExecutionDataKeys import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.externalSystem.execution.ExternalSystemExecutionConsoleManager import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings import com.intellij.openapi.externalSystem.model.task.ExternalSystemTask import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode.NO_PROGRESS_SYNC import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.NaturalComparator import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.ExtensionTestUtil import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.RunAll import com.intellij.testFramework.TestActionEvent import com.intellij.util.ThrowableRunnable import org.jetbrains.plugins.gradle.action.GradleRerunFailedTestsAction import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID import org.jetbrains.plugins.gradle.util.waitForTaskExecution import java.io.File abstract class GradleRerunFailedTestsTestCase : GradleImportingTestCase() { private lateinit var testDisposable: Disposable private lateinit var testExecutionEnvironment: ExecutionEnvironment private lateinit var testExecutionConsole: GradleTestsExecutionConsole override fun setUp() { super.setUp() testDisposable = Disposer.newDisposable() initExecutionConsoleHandler() } override fun tearDown() { RunAll( ThrowableRunnable { Disposer.dispose(testDisposable) }, ThrowableRunnable { super.tearDown() } ).run() } /** * Call this method inside [setUp] to print events trace to console */ @Suppress("unused") private fun initTextNotificationEventsPrinter() { val notificationManager = ExternalSystemProgressNotificationManager.getInstance() notificationManager.addNotificationListener(object : ExternalSystemTaskNotificationListenerAdapter() { override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { if (id.type == ExternalSystemTaskType.EXECUTE_TASK) { when (stdOut) { true -> print(text) else -> System.err.print(text) } } } }, testDisposable) } private fun initExecutionConsoleHandler() { ExtensionTestUtil.maskExtensions(ExternalSystemExecutionConsoleManager.EP_NAME, listOf(object : GradleTestsExecutionConsoleManager() { override fun attachExecutionConsole( project: Project, task: ExternalSystemTask, env: ExecutionEnvironment?, processHandler: ProcessHandler? ) = super.attachExecutionConsole(project, task, env, processHandler).also { testExecutionEnvironment = env!! testExecutionConsole = it!! } }), testDisposable) } private fun getTestsExecutionTree() = invokeAndWaitIfNeeded { val tree = testExecutionConsole.resultsViewer.treeView!! TestConsoleProperties.HIDE_PASSED_TESTS.set(testExecutionConsole.properties, false) PlatformTestUtil.expandAll(tree) PlatformTestUtil.dispatchAllEventsInIdeEventQueue() PlatformTestUtil.waitWhileBusy(tree) PlatformTestUtil.print(tree, false) } fun getJUnitTestsExecutionTree(): String { val flattenTree = getTestsExecutionTree() // removes trailing () for test methods in junit 5 .replace("()", "") .split("\n") // removes package for tests classes in junit 4 .map { if (it.trim().startsWith("-")) it.substringBefore("-") + "-" + it.substringAfter("-").split(".").last() else it } .toMutableList() partitionLeaves(flattenTree) .map { flattenTree.subList(it.first, it.last + 1) } .forEach { it.sortWith(NaturalComparator.INSTANCE) } return flattenTree.joinToString("\n") } private fun partitionLeaves(flattenTree: List<String>) = sequence { var left = -1 for ((i, node) in flattenTree.withIndex()) { val isLeaf = !node.trim().startsWith("-") if (isLeaf && left == -1) { left = i } else if (!isLeaf && left != -1) { yield(left until i) left = -1 } } if (left != -1) { yield(left until flattenTree.size) } } fun execute(tasksAndArguments: String, parameters: String? = null) { val settings = ExternalSystemTaskExecutionSettings().apply { externalProjectPath = projectPath taskNames = tasksAndArguments.split(" ") scriptParameters = parameters externalSystemIdString = SYSTEM_ID.id } ExternalSystemUtil.runTask(settings, EXECUTOR_ID, myProject, SYSTEM_ID, null, NO_PROGRESS_SYNC) } fun performRerunFailedTestsAction(): Boolean = invokeAndWaitIfNeeded { val rerunAction = GradleRerunFailedTestsAction(testExecutionConsole) rerunAction.setModelProvider { testExecutionConsole.resultsViewer } val actionEvent = TestActionEvent( SimpleDataContext.builder() .add(ExecutionDataKeys.EXECUTION_ENVIRONMENT, testExecutionEnvironment) .add(CommonDataKeys.PROJECT, myProject) .build()) rerunAction.update(actionEvent) if (actionEvent.presentation.isEnabled) { waitForTaskExecution { rerunAction.actionPerformed(actionEvent) } } actionEvent.presentation.isEnabled } fun VirtualFile.replaceFirst(old: String, new: String) = updateIoFile { writeText(readText().replaceFirst(old, new)) } private fun VirtualFile.updateIoFile(action: File.() -> Unit) { File(path).apply(action) refreshIoFiles(path) } private fun refreshIoFiles(vararg paths: String) { val localFileSystem = LocalFileSystem.getInstance() localFileSystem.refreshIoFiles(paths.map { File(it) }, false, true, null) } }
apache-2.0
9e5a9beb2cb77ada9138496bccf6f85f
40.529762
140
0.757741
4.861324
false
true
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/overwrite/OverwriteModifiersInspection.kt
1
3670
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.inspection.overwrite import com.demonwav.mcdev.platform.mixin.util.mixinTargets import com.demonwav.mcdev.platform.mixin.util.resolveFirstOverwriteTarget import com.demonwav.mcdev.util.findKeyword import com.demonwav.mcdev.util.ifEmpty import com.demonwav.mcdev.util.isAccessModifier import com.intellij.codeInsight.intention.AddAnnotationFix import com.intellij.codeInsight.intention.QuickFixFactory import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiModifier import com.intellij.psi.util.PsiUtil class OverwriteModifiersInspection : OverwriteInspection() { override fun getStaticDescription() = "Validates the modifiers of @Overwrite methods" override fun visitOverwrite(holder: ProblemsHolder, method: PsiMethod, overwrite: PsiAnnotation) { val psiClass = method.containingClass ?: return val targetClasses = psiClass.mixinTargets.ifEmpty { return } val target = resolveFirstOverwriteTarget(targetClasses, method)?.modifierList ?: return val nameIdentifier = method.nameIdentifier ?: return val modifierList = method.modifierList // Check access modifiers val targetAccessLevel = PsiUtil.getAccessLevel(target) val currentAccessLevel = PsiUtil.getAccessLevel(modifierList) if (currentAccessLevel < targetAccessLevel) { val targetModifier = PsiUtil.getAccessModifier(targetAccessLevel) val currentModifier = PsiUtil.getAccessModifier(currentAccessLevel) holder.registerProblem(modifierList.findKeyword(currentModifier) ?: nameIdentifier, "$currentModifier @Overwrite cannot reduce visibility of ${PsiUtil.getAccessModifier(targetAccessLevel)} target method", QuickFixFactory.getInstance().createModifierListFix(modifierList, targetModifier, true, false)) } for (modifier in PsiModifier.MODIFIERS) { if (isAccessModifier(modifier)) { // Access modifiers are already checked above continue } val targetModifier = target.hasModifierProperty(modifier) val overwriteModifier = modifierList.hasModifierProperty(modifier) if (targetModifier != overwriteModifier) { val marker: PsiElement val message = if (targetModifier) { marker = nameIdentifier "Method must be '$modifier'" } else { marker = modifierList.findKeyword(modifier) ?: nameIdentifier "'$modifier' modifier does not match target method" } holder.registerProblem(marker, message, QuickFixFactory.getInstance().createModifierListFix(modifierList, modifier, targetModifier, false)) } } for (annotation in target.annotations) { val qualifiedName = annotation.qualifiedName ?: continue val overwriteAnnotation = modifierList.findAnnotation(qualifiedName) if (overwriteAnnotation == null) { holder.registerProblem(nameIdentifier, "Missing @${annotation.nameReferenceElement?.text} annotation", AddAnnotationFix(qualifiedName, method, annotation.parameterList.attributes)) } // TODO: Check if attributes are specified correctly? } } }
mit
6df4f9123433daa27145ab9de1871813
42.690476
136
0.693733
5.585997
false
false
false
false
syrop/GPS-Texter
texter/src/main/kotlin/pl/org/seva/texter/main/MainActivity.kt
1
10348
/* * Copyright (C) 2017 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.texter.main import android.Manifest import android.annotation.SuppressLint import android.app.Dialog import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.preference.PreferenceManager import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import androidx.core.content.ContextCompat import androidx.appcompat.app.AppCompatActivity import android.view.* import android.webkit.WebView import android.widget.Toast import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.GoogleApiAvailability import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.toolbar.* import java.util.ArrayList import java.util.Locale import pl.org.seva.texter.R import pl.org.seva.texter.ui.TitledPagerAdapter import pl.org.seva.texter.history.HistoryFragment import pl.org.seva.texter.main.extension.readString import pl.org.seva.texter.movement.location import pl.org.seva.texter.stats.StatsFragment import pl.org.seva.texter.navigation.NavigationFragment import pl.org.seva.texter.settings.SettingsActivity import pl.org.seva.texter.sms.smsSender class MainActivity : AppCompatActivity() { /** Used when counting a double click. */ private var clickTime: Long = 0 private var exitToast: Toast? = null /** Obtained from intent, may be null. */ private var action: String? = null private var shuttingDown: Boolean = false private var dialog: Dialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) action = intent.action action?: finish() setContentView(R.layout.activity_main) val titles = arrayOf<CharSequence>( getString(R.string.stats_tab_name), getString(R.string.map_tab_name), getString(R.string.history_tab_name)) setSupportActionBar(toolbar) val fragments = ArrayList<Fragment>() fragments.add(StatsFragment.newInstance()) fragments.add(NavigationFragment.newInstance()) fragments.add(HistoryFragment.newInstance()) val adapter = TitledPagerAdapter(supportFragmentManager, titles).setItems(fragments) pager.adapter = adapter val tabColor: Int if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { tabColor = resources.getColor(R.color.tabsScrollColor, theme) } else { @Suppress("DEPRECATION") tabColor = resources.getColor(R.color.tabsScrollColor) } tabs.setDistributeEvenly() tabs.setCustomTabColorizer { tabColor } tabs.setViewPager(pager) smsSender.init(getString(R.string.speed_unit)) val googlePlay = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this) if (googlePlay != ConnectionResult.SUCCESS) { GoogleApiAvailability.getInstance().getErrorDialog(this, googlePlay, GOOGLE_REQUEST_CODE).show() } if (!showStartupDialog()) { processPermissions() } (application as TexterApplication).startService() } /** * All actions that require permissions must be placed here. The method performs them or * asks for permissions if they haven't been granted already. * @return true if all permissions had been granted before calling the method */ @SuppressLint("CheckResult") private fun processPermissions(): Boolean { val permissionsToRequest = ArrayList<String>() if (ContextCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { permissionsToRequest.add(Manifest.permission.ACCESS_FINE_LOCATION) permissions .permissionGrantedListener() .filter { it.first == Permissions.LOCATION_PERMISSION_REQUEST_ID } .filter { it.second == Manifest.permission.ACCESS_FINE_LOCATION } .subscribe { onLocationPermissionGranted() } } else { initGps() } if (smsSender.isTextingEnabled) { permissionsToRequest.addAll(smsSender.permissionsToRequest()) } if (permissionsToRequest.isEmpty()) { return true } val arr = permissionsToRequest.toTypedArray() ActivityCompat.requestPermissions( this, arr, Permissions.LOCATION_PERMISSION_REQUEST_ID) return false } private fun initGps() = location.initGpsOnLocationGranted(applicationContext) private fun showStartupDialog(): Boolean { val prefs = PreferenceManager.getDefaultSharedPreferences(this) if (prefs.getBoolean(PREF_STARTUP_SHOWN, false)) { return false } dialog = Dialog(this) checkNotNull(dialog).setCancelable(false) val dialog = Dialog(this) dialog.setContentView(R.layout.dialog_startup) val web = dialog.findViewById<WebView>(R.id.web) val language = Locale.getDefault().language web.settings.defaultTextEncodingName = "utf-8" val content = assets.open(if (language == "pl") "startup_pl.html" else "startup_en.html") .readString() .replace(APP_VERSION_PLACEHOLDER, versionName) web.loadDataWithBaseURL("file:///android_asset/", content, "text/html", "UTF-8", null) dialog.findViewById<View>(R.id.dismiss).setOnClickListener { processPermissions() dialog.dismiss() prefs.edit().putBoolean(PREF_STARTUP_SHOWN, true).apply() // asynchronously } dialog.findViewById<View>(R.id.settings).setOnClickListener { dialog.dismiss() prefs.edit().putBoolean(PREF_STARTUP_SHOWN, true).apply() startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) } dialog.show() return true } private fun showHelpDialog() { dialog = Dialog(this) checkNotNull(dialog).setCancelable(false) checkNotNull(dialog).setContentView(R.layout.dialog_help) val web = checkNotNull(dialog).findViewById<WebView>(R.id.web) web.settings.defaultTextEncodingName = "utf-8" val language = Locale.getDefault().language val content = assets.open(if (language == "pl") "help_pl.html" else "help_en.html") .readString() .replace(APP_VERSION_PLACEHOLDER, versionName) web.loadDataWithBaseURL( "file:///android_asset/", content, "text/html", "UTF-8", null) checkNotNull(dialog).findViewById<View>(R.id.ok).setOnClickListener { checkNotNull(dialog).dismiss() } checkNotNull(dialog).show() } private val versionName: String get() = packageManager.getPackageInfo(packageName, 0).versionName override fun onRequestPermissionsResult( requestCode: Int, permissionsArray: Array<String>, grantResults: IntArray) = // If request is cancelled, the result arrays are empty. permissions.onRequestPermissionsResult(requestCode, permissionsArray, grantResults) public override fun onDestroy() { // Also called when the screen is rotated. dialog?.dismiss() if (action == Intent.ACTION_MAIN && shuttingDown) { // action != Intent.ACTION_MAIN when activity has been launched from a notification. stopService() } super.onDestroy() } private fun stopService() = (application as TexterApplication).stopService() override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onBackPressed() = if (System.currentTimeMillis() - clickTime < DOUBLE_CLICK_MS) { shuttingDown = true exitToast?.cancel() super.onBackPressed() } else { exitToast?.cancel() exitToast = Toast.makeText(this, R.string.tap_back_second_time, Toast.LENGTH_SHORT) checkNotNull(exitToast).show() clickTime = System.currentTimeMillis() } override fun onOptionsItemSelected(item: MenuItem): Boolean = // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. when (item.itemId) { R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)) true } R.id.action_help -> { showHelpDialog() true } else -> super.onOptionsItemSelected(item) } private fun onLocationPermissionGranted() = initGps() companion object { private const val APP_VERSION_PLACEHOLDER = "[app_version]" private const val PREF_STARTUP_SHOWN = "pref_startup_shown" private const val GOOGLE_REQUEST_CODE = 0 /** Number of milliseconds that will be taken for a double click. */ private const val DOUBLE_CLICK_MS = 1000L } }
gpl-3.0
aba12f95d088d93327291922bb022bcc
36.904762
108
0.653846
4.764273
false
false
false
false
chromeos/video-decode-encode-demo
app/src/main/java/dev/hadrosaur/videodecodeencodedemo/AudioHelpers/AudioBufferManager.kt
1
1900
/* * Copyright (c) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.hadrosaur.videodecodeencodedemo.AudioHelpers import java.util.concurrent.LinkedBlockingDeque class AudioBufferManager { /** * Callback to be triggered if a user of the AudioBufferManager wants to be notified of new * audio data added via addData */ interface AudioBufferManagerListener { fun newAudioData() } private val queue = LinkedBlockingDeque<AudioBuffer>() var listener: AudioBufferManagerListener? = null var audioDecodeComplete = false /** * Adds AudioBuffer to the queue. If a callback is registered, trigger it */ fun addData(audioBuffer: AudioBuffer, triggerCallback: Boolean = true): Boolean { // Add to tail of queue val success = queue.add(audioBuffer) // If there is a listener registered, trigger it if (triggerCallback) { listener?.newAudioData() } return success } fun addDataFirst(audioBuffer: AudioBuffer, triggerCallback: Boolean = true) { // Add to front of queue queue.addFirst(audioBuffer) // If there is a listener registered, trigger it if (triggerCallback) { listener?.newAudioData() } } fun pollData() : AudioBuffer? { return queue.poll() } }
apache-2.0
ad012dceb14c6d921b191ed64eb520aa
28.230769
95
0.676842
4.50237
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter13/src/main/kotlin/com/packt/chapter13/13.8.Atomics.kt
1
644
package com.packt.chapter13 import counter import java.sql.Connection import java.util.concurrent.atomic.AtomicLong import java.util.concurrent.atomic.AtomicReference import kotlin.concurrent.thread fun atomicCounters() { val counter = AtomicLong(0) (1..8).forEach { thread { while (true) { val id = counter.incrementAndGet() println("Creating item with id $id") } } } } fun openConnection(): Connection = TODO() fun atomicReferences() { val ref = AtomicReference<Connection>() (1..8).forEach { thread { ref.compareAndSet(null, openConnection()) val conn = ref.get() } } }
mit
7da4e5e0d54e7cace9928e231a668dea
19.806452
50
0.670807
3.95092
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/columnviewholder/ViewHolderHeaderProfile.kt
1
27014
package jp.juggler.subwaytooter.columnviewholder import android.app.Dialog import android.graphics.Color import android.text.Spannable import android.text.SpannableStringBuilder import android.text.Spanned import android.text.style.ForegroundColorSpan import android.view.View import android.widget.* import jp.juggler.subwaytooter.ActMain import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.Styler import jp.juggler.subwaytooter.action.followFromAnotherAccount import jp.juggler.subwaytooter.action.userProfileLocal import jp.juggler.subwaytooter.actmain.nextPosition import jp.juggler.subwaytooter.api.MisskeyAccountDetailMap import jp.juggler.subwaytooter.api.TootApiResult import jp.juggler.subwaytooter.api.entity.TootAccount import jp.juggler.subwaytooter.api.entity.TootAccountRef import jp.juggler.subwaytooter.api.entity.TootStatus import jp.juggler.subwaytooter.api.runApiTask import jp.juggler.subwaytooter.column.* import jp.juggler.subwaytooter.dialog.DlgTextInput import jp.juggler.subwaytooter.emoji.EmojiMap import jp.juggler.subwaytooter.itemviewholder.DlgContextMenu import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.pref.PrefI import jp.juggler.subwaytooter.span.EmojiImageSpan import jp.juggler.subwaytooter.span.LinkInfo import jp.juggler.subwaytooter.span.MyClickableSpan import jp.juggler.subwaytooter.span.createSpan import jp.juggler.subwaytooter.table.AcctColor import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.table.UserRelation import jp.juggler.subwaytooter.util.DecodeOptions import jp.juggler.subwaytooter.util.NetworkEmojiInvalidator import jp.juggler.subwaytooter.util.openCustomTab import jp.juggler.subwaytooter.util.startMargin import jp.juggler.subwaytooter.view.MyLinkMovementMethod import jp.juggler.subwaytooter.view.MyNetworkImageView import jp.juggler.subwaytooter.view.MyTextView import jp.juggler.util.* import org.jetbrains.anko.textColor internal class ViewHolderHeaderProfile( activity: ActMain, viewRoot: View, ) : ViewHolderHeaderBase(activity, viewRoot), View.OnClickListener, View.OnLongClickListener { companion object { private fun SpannableStringBuilder.appendSpan(text: String, span: Any) { val start = length append(text) setSpan( span, start, length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } } private val ivBackground: MyNetworkImageView private val tvCreated: TextView private val tvLastStatusAt: TextView private val tvFeaturedTags: TextView private val ivAvatar: MyNetworkImageView private val tvDisplayName: TextView private val tvAcct: TextView private val btnFollowing: Button private val btnFollowers: Button private val btnStatusCount: Button private val tvNote: TextView private val tvMisskeyExtra: TextView private val btnFollow: ImageButton private val ivFollowedBy: ImageView private val llProfile: View private val tvRemoteProfileWarning: TextView private val nameInvalidator1: NetworkEmojiInvalidator private val noteInvalidator: NetworkEmojiInvalidator private val llFields: LinearLayout private var whoRef: TootAccountRef? = null private var movedRef: TootAccountRef? = null private val llMoved: View private val tvMoved: TextView private val ivMoved: MyNetworkImageView private val tvMovedName: TextView private val tvMovedAcct: TextView private val btnMoved: ImageButton private val ivMovedBy: ImageView private val movedCaptionInvalidator: NetworkEmojiInvalidator private val movedNameInvalidator: NetworkEmojiInvalidator private val density: Float private val btnMore: ImageButton private val tvPersonalNotes: TextView private val btnPersonalNotesEdit: ImageButton private var contentColor = 0 private var relation: UserRelation? = null init { ivBackground = viewRoot.findViewById(R.id.ivBackground) llProfile = viewRoot.findViewById(R.id.llProfile) tvCreated = viewRoot.findViewById(R.id.tvCreated) tvLastStatusAt = viewRoot.findViewById(R.id.tvLastStatusAt) tvFeaturedTags = viewRoot.findViewById(R.id.tvFeaturedTags) ivAvatar = viewRoot.findViewById(R.id.ivAvatar) tvDisplayName = viewRoot.findViewById(R.id.tvDisplayName) tvAcct = viewRoot.findViewById(R.id.tvAcct) btnFollowing = viewRoot.findViewById(R.id.btnFollowing) btnFollowers = viewRoot.findViewById(R.id.btnFollowers) btnStatusCount = viewRoot.findViewById(R.id.btnStatusCount) tvNote = viewRoot.findViewById(R.id.tvNote) tvMisskeyExtra = viewRoot.findViewById(R.id.tvMisskeyExtra) btnMore = viewRoot.findViewById(R.id.btnMore) btnFollow = viewRoot.findViewById(R.id.btnFollow) ivFollowedBy = viewRoot.findViewById(R.id.ivFollowedBy) tvRemoteProfileWarning = viewRoot.findViewById(R.id.tvRemoteProfileWarning) llMoved = viewRoot.findViewById(R.id.llMoved) tvMoved = viewRoot.findViewById(R.id.tvMoved) ivMoved = viewRoot.findViewById(R.id.ivMoved) tvMovedName = viewRoot.findViewById(R.id.tvMovedName) tvMovedAcct = viewRoot.findViewById(R.id.tvMovedAcct) btnMoved = viewRoot.findViewById(R.id.btnMoved) ivMovedBy = viewRoot.findViewById(R.id.ivMovedBy) llFields = viewRoot.findViewById(R.id.llFields) tvPersonalNotes = viewRoot.findViewById(R.id.tvPersonalNotes) btnPersonalNotesEdit = viewRoot.findViewById(R.id.btnPersonalNotesEdit) density = tvDisplayName.resources.displayMetrics.density for (v in arrayOf( ivBackground, btnFollowing, btnFollowers, btnStatusCount, btnMore, btnFollow, tvRemoteProfileWarning, btnPersonalNotesEdit, btnMoved, llMoved, btnPersonalNotesEdit )) { v.setOnClickListener(this) } btnMoved.setOnLongClickListener(this) btnFollow.setOnLongClickListener(this) tvNote.movementMethod = MyLinkMovementMethod nameInvalidator1 = NetworkEmojiInvalidator(activity.handler, tvDisplayName) noteInvalidator = NetworkEmojiInvalidator(activity.handler, tvNote) movedCaptionInvalidator = NetworkEmojiInvalidator(activity.handler, tvMoved) movedNameInvalidator = NetworkEmojiInvalidator(activity.handler, tvMovedName) ivBackground.measureProfileBg = true } override fun getAccount(): TootAccountRef? = whoRef override fun onViewRecycled() { } // fun updateRelativeTime() { // val who = whoRef?.get() // if(who != null) { // tvCreated.text = TootStatus.formatTime(tvCreated.context, who.time_created_at, true) // } // } override fun bindData(column: Column) { super.bindData(column) bindFonts() bindColors() llMoved.visibility = View.GONE tvMoved.visibility = View.GONE llFields.visibility = View.GONE llFields.removeAllViews() val whoRef = column.whoAccount this.whoRef = whoRef when (val who = whoRef?.get()) { null -> bindAccountNull() else -> bindAccount(who, whoRef) } } // カラム設定から戻った際に呼ばれる override fun showColor() { llProfile.setBackgroundColor( when (val c = column.columnBgColor) { 0 -> activity.attrColor(R.attr.colorProfileBackgroundMask) else -> -0x40000000 or (0x00ffffff and c) } ) } // bind時に呼ばれる private fun bindColors() { val contentColor = column.getContentColor() this.contentColor = contentColor tvPersonalNotes.textColor = contentColor tvMoved.textColor = contentColor tvMovedName.textColor = contentColor tvDisplayName.textColor = contentColor tvNote.textColor = contentColor tvRemoteProfileWarning.textColor = contentColor btnStatusCount.textColor = contentColor btnFollowing.textColor = contentColor btnFollowers.textColor = contentColor tvFeaturedTags.textColor = contentColor setIconDrawableId( activity, btnMore, R.drawable.ic_more, color = contentColor, alphaMultiplier = Styler.boostAlpha ) setIconDrawableId( activity, btnPersonalNotesEdit, R.drawable.ic_edit, color = contentColor, alphaMultiplier = Styler.boostAlpha ) val acctColor = column.getAcctColor() tvCreated.textColor = acctColor tvMovedAcct.textColor = acctColor tvLastStatusAt.textColor = acctColor showColor() } private fun bindFonts() { var f: Float f = activity.timelineFontSizeSp if (!f.isNaN()) { tvMovedName.textSize = f tvMoved.textSize = f tvPersonalNotes.textSize = f tvFeaturedTags.textSize = f } f = activity.acctFontSizeSp if (!f.isNaN()) { tvMovedAcct.textSize = f tvCreated.textSize = f tvLastStatusAt.textSize = f } val spacing = activity.timelineSpacing if (spacing != null) { tvMovedName.setLineSpacing(0f, spacing) tvMoved.setLineSpacing(0f, spacing) } } private fun bindAccountNull() { relation = null tvCreated.text = "" tvLastStatusAt.vg(false) tvFeaturedTags.vg(false) ivBackground.setImageDrawable(null) ivAvatar.setImageDrawable(null) tvAcct.text = "@" tvDisplayName.text = "" nameInvalidator1.register(null) tvNote.text = "" tvMisskeyExtra.text = "" noteInvalidator.register(null) btnStatusCount.text = activity.getString(R.string.statuses) + "\n" + "?" btnFollowing.text = activity.getString(R.string.following) + "\n" + "?" btnFollowers.text = activity.getString(R.string.followers) + "\n" + "?" btnFollow.setImageDrawable(null) tvRemoteProfileWarning.visibility = View.GONE } private fun bindAccount(who: TootAccount, whoRef: TootAccountRef) { // Misskeyの場合はNote中のUserエンティティと /api/users/show の情報量がかなり異なる val whoDetail = MisskeyAccountDetailMap.get(accessInfo, who.id) tvCreated.text = TootStatus.formatTime(tvCreated.context, (whoDetail ?: who).time_created_at, true) who.setAccountExtra( accessInfo, tvLastStatusAt, invalidator = null, fromProfileHeader = true ) val featuredTagsText = formatFeaturedTags() tvFeaturedTags.vg(featuredTagsText != null)?.let { it.text = featuredTagsText!! it.movementMethod = MyLinkMovementMethod } ivBackground.setImageUrl(0f, accessInfo.supplyBaseUrl(who.header_static)) ivAvatar.setImageUrl( Styler.calcIconRound(ivAvatar.layoutParams), accessInfo.supplyBaseUrl(who.avatar_static), accessInfo.supplyBaseUrl(who.avatar) ) val name = whoDetail?.decodeDisplayName(activity) ?: whoRef.decoded_display_name tvDisplayName.text = name nameInvalidator1.register(name) tvRemoteProfileWarning.vg(column.accessInfo.isRemoteUser(who)) tvAcct.text = encodeAcctText(who, whoDetail) val note = whoRef.decoded_note tvNote.text = note noteInvalidator.register(note) tvMisskeyExtra.text = encodeMisskeyExtra(whoDetail) tvMisskeyExtra.vg(tvMisskeyExtra.text.isNotEmpty()) btnStatusCount.text = "${activity.getString(R.string.statuses)}\n${ whoDetail?.statuses_count ?: who.statuses_count }" val hideFollowCount = PrefB.bpHideFollowCount(activity.pref) var caption = activity.getString(R.string.following) btnFollowing.text = when { hideFollowCount -> caption else -> "${caption}\n${whoDetail?.following_count ?: who.following_count}" } caption = activity.getString(R.string.followers) btnFollowers.text = when { hideFollowCount -> caption else -> "${caption}\n${whoDetail?.followers_count ?: who.followers_count}" } val relation = UserRelation.load(accessInfo.db_id, who.id) this.relation = relation Styler.setFollowIcon( activity, btnFollow, ivFollowedBy, relation, who, contentColor, alphaMultiplier = Styler.boostAlpha ) tvPersonalNotes.text = relation.note ?: "" showMoved(who, who.movedRef) (whoDetail?.fields ?: who.fields)?.notEmpty()?.let { showFields(who, it) } } private fun showMoved(who: TootAccount, movedRef: TootAccountRef?) { if (movedRef == null) return this.movedRef = movedRef val moved = movedRef.get() llMoved.visibility = View.VISIBLE tvMoved.visibility = View.VISIBLE val caption = who.decodeDisplayName(activity) .intoStringResource(activity, R.string.account_moved_to) tvMoved.text = caption movedCaptionInvalidator.register(caption) ivMoved.layoutParams.width = activity.avatarIconSize ivMoved.setImageUrl( Styler.calcIconRound(ivMoved.layoutParams), accessInfo.supplyBaseUrl(moved.avatar_static) ) tvMovedName.text = movedRef.decoded_display_name movedNameInvalidator.register(movedRef.decoded_display_name) setAcct(tvMovedAcct, accessInfo, moved) val relation = UserRelation.load(accessInfo.db_id, moved.id) Styler.setFollowIcon( activity, btnMoved, ivMovedBy, relation, moved, contentColor, alphaMultiplier = Styler.boostAlpha ) } override fun onClick(v: View) { when (v.id) { R.id.ivBackground, R.id.tvRemoteProfileWarning -> activity.openCustomTab(whoRef?.get()?.url) R.id.btnFollowing -> { column.profileTab = ProfileTab.Following activity.appState.saveColumnList() column.startLoading() } R.id.btnFollowers -> { column.profileTab = ProfileTab.Followers activity.appState.saveColumnList() column.startLoading() } R.id.btnStatusCount -> { column.profileTab = ProfileTab.Status activity.appState.saveColumnList() column.startLoading() } R.id.btnMore -> whoRef?.let { whoRef -> DlgContextMenu(activity, column, whoRef, null, null, null).show() } R.id.btnFollow -> whoRef?.let { whoRef -> DlgContextMenu(activity, column, whoRef, null, null, null).show() } R.id.btnMoved -> movedRef?.let { movedRef -> DlgContextMenu(activity, column, movedRef, null, null, null).show() } R.id.llMoved -> movedRef?.let { movedRef -> if (accessInfo.isPseudo) { DlgContextMenu(activity, column, movedRef, null, null, null).show() } else { activity.userProfileLocal( activity.nextPosition(column), accessInfo, movedRef.get() ) } } R.id.btnPersonalNotesEdit -> whoRef?.let { whoRef -> val who = whoRef.get() val relation = this.relation val lastColumn = column DlgTextInput.show( activity, AcctColor.getStringWithNickname(activity, R.string.personal_notes_of, who.acct), relation?.note ?: "", allowEmpty = true, callback = object : DlgTextInput.Callback { override fun onEmptyError() { } override fun onOK(dialog: Dialog, text: String) { launchMain { activity.runApiTask(column.accessInfo) { client -> when { accessInfo.isPseudo -> TootApiResult("Personal notes is not supported on pseudo account.") accessInfo.isMisskey -> TootApiResult("Personal notes is not supported on Misskey account.") else -> client.request( "/api/v1/accounts/${who.id}/note", jsonObject { put("comment", text) }.toPostRequestBuilder() ) } }?.let { result -> when (val error = result.error) { null -> { relation?.note = text dialog.dismissSafe() if (lastColumn == column) bindData(column) } else -> activity.showToast(true, error) } } } } } ) } } } override fun onLongClick(v: View): Boolean { when (v.id) { R.id.btnFollow -> { activity.followFromAnotherAccount( activity.nextPosition(column), accessInfo, whoRef?.get() ) return true } R.id.btnMoved -> { activity.followFromAnotherAccount( activity.nextPosition(column), accessInfo, movedRef?.get() ) return true } } return false } private fun setAcct(tv: TextView, accessInfo: SavedAccount, who: TootAccount) { val ac = AcctColor.load(accessInfo, who) tv.text = when { AcctColor.hasNickname(ac) -> ac.nickname PrefB.bpShortAcctLocalUser() -> "@${who.acct.pretty}" else -> "@${ac.nickname}" } tv.textColor = ac.color_fg.notZero() ?: column.getAcctColor() tv.setBackgroundColor(ac.color_bg) // may 0 tv.setPaddingRelative(activity.acctPadLr, 0, activity.acctPadLr, 0) } private fun formatFeaturedTags() = column.whoFeaturedTags?.notEmpty()?.let { tagList -> SpannableStringBuilder().apply { append(activity.getString(R.string.featured_hashtags)) append(":") tagList.forEach { tag -> append(" ") val tagWithSharp = "#" + tag.name val start = length append(tagWithSharp) val end = length tag.url?.notEmpty()?.let { url -> val span = MyClickableSpan( LinkInfo(url = url, tag = tag.name, caption = tagWithSharp) ) setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } } } private fun encodeAcctText(who: TootAccount, whoDetail: TootAccount?) = SpannableStringBuilder().apply { append("@") append(accessInfo.getFullAcct(who).pretty) if (whoDetail?.locked ?: who.locked) { append(" ") val emoji = EmojiMap.shortNameMap["lock"] when { emoji == null -> append("locked") PrefB.bpUseTwemoji() -> appendSpan("locked", emoji.createSpan(activity)) else -> append(emoji.unifiedCode) } } if (who.bot) { append(" ") val emoji = EmojiMap.shortNameMap["robot_face"] when { emoji == null -> append("bot") PrefB.bpUseTwemoji() -> appendSpan("bot", emoji.createSpan(activity)) else -> append(emoji.unifiedCode) } } if (who.suspended) { append(" ") val emoji = EmojiMap.shortNameMap["cross_mark"] when { emoji == null -> append("suspended") PrefB.bpUseTwemoji() -> appendSpan("suspended", emoji.createSpan(activity)) else -> append(emoji.unifiedCode) } } } private fun encodeMisskeyExtra(whoDetail: TootAccount?) = SpannableStringBuilder().apply { var s = whoDetail?.location if (s?.isNotEmpty() == true) { if (isNotEmpty()) append('\n') appendSpan( activity.getString(R.string.location), EmojiImageSpan( activity, R.drawable.ic_location, useColorShader = true ) ) append(' ') append(s) } s = whoDetail?.birthday if (s?.isNotEmpty() == true) { if (isNotEmpty()) append('\n') appendSpan( activity.getString(R.string.birthday), EmojiImageSpan( activity, R.drawable.ic_cake, useColorShader = true ) ) append(' ') append(s) } } private fun showFields(who: TootAccount, fields: List<TootAccount.Field>) { llFields.visibility = View.VISIBLE // fieldsのnameにはカスタム絵文字が適用されるようになった // https://github.com/tootsuite/mastodon/pull/11350 // fieldsのvalueはMisskeyならMFM、MastodonならHTML val fieldDecodeOptions = DecodeOptions( context = activity, decodeEmoji = true, linkHelper = accessInfo, short = true, emojiMapCustom = who.custom_emojis, emojiMapProfile = who.profile_emojis, authorDomain = who ) val nameTypeface = ActMain.timelineFontBold val valueTypeface = ActMain.timelineFont for (item in fields) { // val nameView = MyTextView(activity) val nameLp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) val nameText = fieldDecodeOptions.decodeEmoji(item.name) val nameInvalidator = NetworkEmojiInvalidator(activity.handler, nameView) nameInvalidator.register(nameText) nameLp.topMargin = (density * 6f).toInt() nameView.layoutParams = nameLp nameView.text = nameText nameView.setTextColor(contentColor) nameView.typeface = nameTypeface nameView.movementMethod = MyLinkMovementMethod llFields.addView(nameView) // 値の方はHTMLエンコードされている val valueView = MyTextView(activity) val valueLp = LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT ) val valueText = fieldDecodeOptions.decodeHTML(item.value) if (item.verified_at > 0L) { valueText.append('\n') val start = valueText.length valueText.append(activity.getString(R.string.verified_at)) valueText.append(": ") valueText.append(TootStatus.formatTime(activity, item.verified_at, false)) val end = valueText.length val linkFgColor = PrefI.ipVerifiedLinkFgColor(activity.pref).notZero() ?: (Color.BLACK or 0x7fbc99) valueText.setSpan( ForegroundColorSpan(linkFgColor), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } val valueInvalidator = NetworkEmojiInvalidator(activity.handler, valueView) valueInvalidator.register(valueText) valueLp.startMargin = (density * 32f).toInt() valueView.layoutParams = valueLp valueView.text = valueText valueView.setTextColor(contentColor) valueView.typeface = valueTypeface valueView.movementMethod = MyLinkMovementMethod if (item.verified_at > 0L) { val linkBgColor = PrefI.ipVerifiedLinkBgColor(activity.pref).notZero() ?: (0x337fbc99) valueView.setBackgroundColor(linkBgColor) } llFields.addView(valueView) } } }
apache-2.0
b0093d4a4d82cedae3d788ea998dd66c
34.215924
112
0.561783
5.003916
false
false
false
false
airbnb/epoxy
epoxy-sample/src/main/java/com/airbnb/epoxy/sample/models/TestModel3.kt
1
522
package com.airbnb.epoxy.sample.models import android.view.View import com.airbnb.epoxy.EpoxyAttribute import com.airbnb.epoxy.EpoxyModel import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.sample.R @EpoxyModelClass(layout = R.layout.model_color) abstract class TestModel3 : EpoxyModel<View>() { @EpoxyAttribute var num: Int = 0 @EpoxyAttribute var num2: Int = 0 @EpoxyAttribute var num3: Int = 0 @EpoxyAttribute var num4: Int = 0 @EpoxyAttribute var num5: Int = 0 }
apache-2.0
553cd7f41c6a4158fac7691de2ffa665
22.727273
48
0.726054
3.755396
false
false
false
false
flesire/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/support/GQLScalarJSON.kt
1
3341
package net.nemerosa.ontrack.graphql.support import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.* import graphql.language.NullValue import graphql.language.StringValue import graphql.schema.Coercing import graphql.schema.CoercingParseValueException import graphql.schema.GraphQLScalarType import net.nemerosa.ontrack.json.ObjectMapperFactory /** * JSON scalar type. */ class GQLScalarJSON private constructor() : GraphQLScalarType( "JSON", "Custom JSON value", object : Coercing<JsonNode, JsonNode> { private val mapper = ObjectMapperFactory.create() override fun serialize(dataFetcherResult: Any): JsonNode { val json = when (dataFetcherResult) { is JsonNode -> dataFetcherResult else -> mapper.valueToTree<JsonNode>(dataFetcherResult) } return json.obfuscate() } override fun parseValue(input: Any): JsonNode = when (input) { is String -> mapper.readTree(input) is JsonNode -> input else -> throw CoercingParseValueException("Cannot parse value for ${input::class}") } override fun parseLiteral(input: Any): JsonNode? = when (input) { is NullValue -> NullNode.instance is StringValue -> mapper.readTree(input.value) else -> null // Meaning invalid } private fun JsonNode.obfuscate(): JsonNode { val factory: JsonNodeFactory = mapper.nodeFactory return when (this) { // Transforms each element is ArrayNode -> ArrayNode( factory, map { it.obfuscate() } ) // Filters at field level is ObjectNode -> ObjectNode( factory, fields().asSequence() .associate { (name: String, value: JsonNode?) -> when (value) { is TextNode -> when { name.toLowerCase().contains("password") -> name to NullNode.instance name.toLowerCase().contains("token") -> name to NullNode.instance else -> name to value } else -> name to value.obfuscate() } } ) // No transformation for an end element else -> this } } } ) { companion object { @JvmField val INSTANCE: GraphQLScalarType = GQLScalarJSON() } }
mit
6db7b2353fceb4d7ef62194581a2e199
40.246914
124
0.438192
6.682
false
false
false
false
esafirm/android-playground
app/src/main/java/com/esafirm/androidplayground/others/FileController.kt
1
2102
package com.esafirm.androidplayground.others import android.Manifest import android.os.Environment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.esafirm.androidplayground.common.BaseController import com.esafirm.androidplayground.libs.Logger import com.esafirm.androidplayground.utils.button import com.esafirm.androidplayground.utils.logger import com.esafirm.androidplayground.utils.row import java.io.File class FileController : BaseController() { companion object { private const val RC_WRITE_FILE = 1 private const val RC_READ_FILE = 2 } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup): View { return row { button("Write File") { requestAccessFile(RC_WRITE_FILE) } button("Read File") { requestAccessFile(RC_READ_FILE) } logger() } } private fun requestAccessFile(rcCode: Int) { requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), rcCode) } private fun readFile() { val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) val file = File(dir, "text.txt") if (file.exists().not()) { Logger.log("File not exist") return } val content = file.readText() Logger.log("Content: $content") } private fun writeFile() { val dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) val file = File(dir, "text.txt") if (file.exists().not()) { file.createNewFile() } file.writeText("Hello World!") } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { RC_WRITE_FILE -> writeFile() RC_READ_FILE -> readFile() else -> throw IllegalStateException("Invalid request code") } } }
mit
241d4bc98b5c1ed9ea66a22868ef45f6
32.903226
119
0.675071
4.755656
false
false
false
false
paplorinc/intellij-community
platform/projectModel-api/src/org/jetbrains/concurrency/AsyncPromise.kt
2
4636
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.concurrency import com.intellij.openapi.diagnostic.ControlFlowException import com.intellij.openapi.diagnostic.logger import com.intellij.util.ExceptionUtilRt import com.intellij.util.Function import org.jetbrains.concurrency.Promise.State import java.util.concurrent.* import java.util.concurrent.atomic.AtomicBoolean import java.util.function.Consumer open class AsyncPromise<T> private constructor(private val f: CompletableFuture<T>, private val hasErrorHandler: AtomicBoolean) : CancellablePromise<T>, InternalPromiseUtil.CompletablePromise<T> { constructor() : this(CompletableFuture(), AtomicBoolean()) override fun isDone() = f.isDone override fun get() = nullizeCancelled { f.get() } override fun get(timeout: Long, unit: TimeUnit) = nullizeCancelled { f.get(timeout, unit) } // because of the contract: get() should return null for canceled promise private inline fun nullizeCancelled(value: () -> T?): T? { if (isCancelled) { return null } return try { value() } catch (e: CancellationException) { null } } override fun isCancelled() = f.isCancelled // because of the unorthodox contract: "double cancel must return false" override fun cancel(mayInterruptIfRunning: Boolean) = !isCancelled && f.cancel(mayInterruptIfRunning) override fun cancel() { cancel(true) } override fun getState(): State { return when { !f.isDone -> State.PENDING f.isCompletedExceptionally -> State.REJECTED else -> State.SUCCEEDED } } override fun onSuccess(handler: Consumer<in T>): Promise<T> { return AsyncPromise(f.whenComplete { value, exception -> if (exception == null && !InternalPromiseUtil.isHandlerObsolete(handler)) { try { handler.accept(value) } catch (e: Throwable) { if (e !is ControlFlowException) { logger<AsyncPromise<*>>().error(e) } } } }, hasErrorHandler) } override fun onError(rejected: Consumer<Throwable>): Promise<T> { hasErrorHandler.set(true) return AsyncPromise(f.whenComplete { _, exception -> if (exception != null) { val toReport = if (exception is CompletionException && exception.cause != null) exception.cause!! else exception if (!InternalPromiseUtil.isHandlerObsolete(rejected)) { rejected.accept(toReport) } } }, hasErrorHandler) } override fun onProcessed(processed: Consumer<in T>): Promise<T> { hasErrorHandler.set(true) return AsyncPromise(f.whenComplete { value, _ -> if (!InternalPromiseUtil.isHandlerObsolete(processed)) { processed.accept(value) } }, hasErrorHandler) } override fun blockingGet(timeout: Int, timeUnit: TimeUnit): T? { try { return get(timeout.toLong(), timeUnit) } catch (e: ExecutionException) { if (e.cause === InternalPromiseUtil.OBSOLETE_ERROR) { return null } ExceptionUtilRt.rethrowUnchecked(e.cause) throw e } } override fun <SUB_RESULT : Any?> then(done: Function<in T, out SUB_RESULT>): Promise<SUB_RESULT> { return AsyncPromise(f.thenApply { done.`fun`(it) }, hasErrorHandler) } override fun <SUB_RESULT : Any?> thenAsync(doneF: Function<in T, Promise<SUB_RESULT>>): Promise<SUB_RESULT> { val convert: (T) -> CompletableFuture<SUB_RESULT> = { val promise = doneF.`fun`(it) val future = CompletableFuture<SUB_RESULT>() promise .onSuccess { value -> future.complete(value) } .onError { error -> future.completeExceptionally(error) } future } return AsyncPromise(f.thenCompose(convert), hasErrorHandler) } override fun processed(child: Promise<in T>): Promise<T> { if (child !is AsyncPromise) { return this } return onSuccess { child.setResult(it) } .onError { child.setError(it) } } override fun setResult(t: T?) { f.complete(t) } override fun setError(error: Throwable): Boolean { if (!f.completeExceptionally(error)) { return false } if (!hasErrorHandler.get()) { logger<AsyncPromise<*>>().errorIfNotMessage(error) } return true } fun setError(error: String) = setError(createError(error)) } inline fun <T> AsyncPromise<*>.catchError(runnable: () -> T): T? { return try { runnable() } catch (e: Throwable) { setError(e) null } }
apache-2.0
a169f34c3baf6210b4d6fb42e1d4c7bc
28.916129
159
0.660052
4.222222
false
false
false
false
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/productInfo/ProductInfoValidator.kt
1
6695
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.impl.productInfo import com.fasterxml.jackson.databind.ObjectMapper import com.intellij.openapi.util.io.FileUtilRt import com.intellij.util.lang.ImmutableZipFile import com.networknt.schema.JsonSchemaFactory import com.networknt.schema.SpecVersion import kotlinx.serialization.decodeFromString import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream import org.jetbrains.intellij.build.BuildContext import org.jetbrains.intellij.build.BuildMessages import org.jetbrains.intellij.build.CompilationContext import org.jetbrains.intellij.build.OsFamily import java.nio.file.Files import java.nio.file.Path /** * Checks that product-info.json file located in `archivePath` archive in `pathInArchive` subdirectory is correct */ internal fun checkInArchive(archiveFile: Path, pathInArchive: String, context: BuildContext) { val productJsonPath = joinPaths(pathInArchive, PRODUCT_INFO_FILE_NAME) val entryData = loadEntry(archiveFile, productJsonPath) ?: throw RuntimeException("Failed to validate product-info.json: cannot find \'$productJsonPath\' in $archiveFile") validateProductJson(jsonText = entryData.decodeToString(), relativePathToProductJson = "", installationDirectories = emptyList(), installationArchives = listOf(Pair(archiveFile, pathInArchive)), context = context) } /** * Checks that product-info.json file is correct. * * @param installationDirectories directories which will be included into product installation * @param installationArchives archives which will be unpacked and included into product installation (the first part specified path to archive, * the second part specifies path inside archive) */ internal fun validateProductJson(jsonText: String, relativePathToProductJson: String, installationDirectories: List<Path>, installationArchives: List<Pair<Path, String>>, context: CompilationContext) { val schemaPath = context.paths.communityHomeDir.communityRoot .resolve("platform/build-scripts/src/org/jetbrains/intellij/build/product-info.schema.json") val messages = context.messages verifyJsonBySchema(jsonText, schemaPath, messages) val productJson = jsonEncoder.decodeFromString<ProductInfoData>(jsonText) checkFileExists(path = productJson.svgIconPath, description = "svg icon", relativePathToProductJson = relativePathToProductJson, installationDirectories = installationDirectories, installationArchives = installationArchives) for ((os, launcherPath, javaExecutablePath, vmOptionsFilePath) in productJson.launch) { if (OsFamily.ALL.none { it.osName == os }) { messages.error("Incorrect os name \'$os\' in $relativePathToProductJson/product-info.json") } checkFileExists(launcherPath, "$os launcher", relativePathToProductJson, installationDirectories, installationArchives) checkFileExists(javaExecutablePath, "$os java executable", relativePathToProductJson, installationDirectories, installationArchives) checkFileExists(vmOptionsFilePath, "$os VM options file", relativePathToProductJson, installationDirectories, installationArchives) } } private fun verifyJsonBySchema(jsonData: String, jsonSchemaFile: Path, messages: BuildMessages) { val schema = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V7).getSchema(Files.readString(jsonSchemaFile)) val errors = schema.validate(ObjectMapper().readTree(jsonData)) if (!errors.isEmpty()) { messages.error("Unable to validate JSON against $jsonSchemaFile:" + "\n${errors.joinToString(separator = "\n")}\njson file content:\n$jsonData") } } private fun checkFileExists(path: String?, description: String, relativePathToProductJson: String, installationDirectories: List<Path>, installationArchives: List<Pair<Path, String>>) { if (path == null) { return } val pathFromProductJson = relativePathToProductJson + path if (installationDirectories.none { Files.exists(it.resolve(pathFromProductJson)) } && installationArchives.none { archiveContainsEntry(it.first, joinPaths(it.second, pathFromProductJson)) }) { throw RuntimeException("Incorrect path to $description '$path' in $relativePathToProductJson/product-info.json: " + "the specified file doesn't exist in directories $installationDirectories " + "and archives ${installationArchives.map { "${it.first}/${it.second}" }}") } } private fun joinPaths(parent: String, child: String): String { return FileUtilRt.toCanonicalPath(/* path = */ "$parent/$child", /* separatorChar = */ '/', /* removeLastSlash = */ true) .dropWhile { it == '/' } } private fun archiveContainsEntry(archiveFile: Path, entryPath: String): Boolean { val fileName = archiveFile.fileName.toString() if (fileName.endsWith(".zip") || fileName.endsWith(".jar")) { ImmutableZipFile.load(archiveFile).use { return it.getResource(entryPath) != null } } else if (fileName.endsWith(".tar.gz")) { Files.newInputStream(archiveFile).use { val inputStream = TarArchiveInputStream(GzipCompressorInputStream(it)) val altEntryPath = "./$entryPath" while (true) { val entry = inputStream.nextEntry ?: break if (entry.name == entryPath || entry.name == altEntryPath) { return true } } } } return false } private fun loadEntry(archiveFile: Path, entryPath: String): ByteArray? { val fileName = archiveFile.fileName.toString() if (fileName.endsWith(".zip") || fileName.endsWith(".jar")) { ImmutableZipFile.load(archiveFile).use { return it.getResource(entryPath)?.data } } else if (fileName.endsWith(".tar.gz")) { TarArchiveInputStream(GzipCompressorInputStream(Files.newInputStream(archiveFile))).use { inputStream -> val altEntryPath = "./$entryPath" while (true) { val entry = inputStream.nextEntry ?: break if (entry.name == entryPath || entry.name == altEntryPath) { return inputStream.readAllBytes() } } } } return null }
apache-2.0
760b7db514d7a5922b5c712f5faed1b1
46.48227
147
0.699776
4.886861
false
false
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/simpleapp1_16_0/FR_OBJECT_BAZ.kt
2
11776
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.snapshots.simpleapp1_16_0 import org.apache.causeway.client.kroviz.snapshots.Response object FR_OBJECT_BAZ : Response(){ override val url = "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==" override val str = """{ "links": [ { "rel": "self", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "domain-app-demo/persist-all/item-3: Object: Baz" }, { "rel": "describedby", "href": "http://localhost:8080/restful/domain-types/causewayApplib.FixtureResult", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel": "urn:org.apache.causeway.restfulobjects:rels/object-layout", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/object-layout", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "domain-app-demo/persist-all/item-3: Object: Baz" }, { "rel": "urn:org.restfulobjects:rels/update", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==", "method": "PUT", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "arguments": {} } ], "extensions": { "oid": "*causewayApplib.FixtureResult:PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==", "isService": false, "isPersistent": true }, "title": "domain-app-demo/persist-all/item-3: Object: Baz", "domainType": "causewayApplib.FixtureResult", "instanceId": "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==", "members": { "fixtureScriptClassName": { "id": "fixtureScriptClassName", "memberType": "property", "links": [ { "rel": "urn:org.restfulobjects:rels/detailsproperty=\"fixtureScriptClassName\"", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/properties/fixtureScriptClassName", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\"" } ], "value": null, "extensions": { "x-causeway-format": "string" }, "disabledReason": "Non-cloneable view models are read-only Immutable" }, "key": { "id": "key", "memberType": "property", "links": [ { "rel": "urn:org.restfulobjects:rels/detailsproperty=\"key\"", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/properties/key", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\"" } ], "value": "", "extensions": { "x-causeway-format": "string" }, "disabledReason": "Non-cloneable view models are read-only Immutable" }, "object": { "id": "object", "memberType": "property", "links": [ { "rel": "urn:org.restfulobjects:rels/detailsproperty=\"object\"", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/properties/object", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\"" } ], "value": { "rel": "urn:org.restfulobjects:rels/value", "href": "http://localhost:8080/restful/objects/simple.SimpleObject/52", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object\"", "title": "Object: Baz" }, "disabledReason": "Non-cloneable view models are read-only Immutable" }, "className": { "id": "className", "memberType": "property", "links": [ { "rel": "urn:org.restfulobjects:rels/detailsproperty=\"className\"", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/properties/className", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-property\"" } ], "value": "domainapp.modules.simple.dom.impl.SimpleObject", "extensions": { "x-causeway-format": "string" }, "disabledReason": "Non-cloneable view models are read-only Immutable" }, "rebuildMetamodel": { "id": "rebuildMetamodel", "memberType": "action", "links": [ { "rel": "urn:org.restfulobjects:rels/detailsaction=\"rebuildMetamodel\"", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/actions/rebuildMetamodel", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "openRestApi": { "id": "openRestApi", "memberType": "action", "links": [ { "rel": "urn:org.restfulobjects:rels/detailsaction=\"openRestApi\"", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/actions/openRestApi", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "downloadLayoutXml": { "id": "downloadLayoutXml", "memberType": "action", "links": [ { "rel": "urn:org.restfulobjects:rels/detailsaction=\"downloadLayoutXml\"", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/actions/downloadLayoutXml", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "clearHints": { "id": "clearHints", "memberType": "action", "links": [ { "rel": "urn:org.restfulobjects:rels/detailsaction=\"clearHints\"", "href": "http://localhost:8080/restful/objects/causewayApplib.FixtureResult/PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPG1lbWVudG8-PGtleT5kb21haW4tYXBwLWRlbW8vcGVyc2lzdC1hbGwvaXRlbS0zPC9rZXk-PG9iamVjdC5ib29rbWFyaz5zaW1wbGUuU2ltcGxlT2JqZWN0OjUyPC9vYmplY3QuYm9va21hcms-PC9tZW1lbnRvPg==/actions/clearHints", "method": "GET", "type": "application/jsonprofile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] } } }""" }
apache-2.0
174f50a965ac6483e1e969a5ad31525e
62.654054
352
0.622452
4.169972
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/JavaToJKTreeBuilder.kt
1
56512
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k import com.intellij.codeInsight.AnnotationTargetUtil import com.intellij.codeInsight.daemon.impl.quickfix.AddTypeArgumentsFix import com.intellij.lang.jvm.JvmModifier import com.intellij.psi.* import com.intellij.psi.JavaTokenType.SUPER_KEYWORD import com.intellij.psi.JavaTokenType.THIS_KEYWORD import com.intellij.psi.impl.light.LightRecordMethod import com.intellij.psi.impl.source.PsiMethodImpl import com.intellij.psi.impl.source.tree.ChildRole import com.intellij.psi.impl.source.tree.CompositeElement import com.intellij.psi.impl.source.tree.java.PsiClassObjectAccessExpressionImpl import com.intellij.psi.impl.source.tree.java.PsiLabeledStatementImpl import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl import com.intellij.psi.impl.source.tree.java.PsiNewExpressionImpl import com.intellij.psi.infos.MethodCandidateInfo import com.intellij.psi.javadoc.PsiDocComment import com.intellij.psi.tree.IElementType import com.intellij.psi.util.JavaPsiRecordUtil.getFieldForComponent import com.intellij.psi.util.TypeConversionUtil.calcTypeForBinaryExpression import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclaration import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacade import org.jetbrains.kotlin.asJava.elements.KtLightElement import org.jetbrains.kotlin.asJava.elements.KtLightField import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.idea.base.psi.kotlinFqName import org.jetbrains.kotlin.idea.j2k.content import org.jetbrains.kotlin.j2k.ReferenceSearcher import org.jetbrains.kotlin.j2k.ast.Nullability.NotNull import org.jetbrains.kotlin.j2k.getContainingClass import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.nj2k.symbols.* import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.tree.JKLiteralExpression.LiteralType.* import org.jetbrains.kotlin.nj2k.tree.Mutability.IMMUTABLE import org.jetbrains.kotlin.nj2k.tree.Mutability.UNKNOWN import org.jetbrains.kotlin.nj2k.types.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration import org.jetbrains.kotlin.resolve.QualifiedExpressionResolver import org.jetbrains.kotlin.utils.addToStdlib.safeAs class JavaToJKTreeBuilder constructor( private val symbolProvider: JKSymbolProvider, private val typeFactory: JKTypeFactory, converterServices: NewJavaToKotlinServices, private val importStorage: JKImportStorage, private val bodyFilter: ((PsiElement) -> Boolean)?, ) { private fun todoExpression(): JKExpression = JKCallExpressionImpl( symbolProvider.provideMethodSymbol("kotlin.TODO"), JKArgumentList( JKArgumentImpl( JKLiteralExpression( "\"${QualifiedExpressionResolver.ROOT_PREFIX_FOR_IDE_RESOLUTION_MODE}\"", STRING, ) ) ), ) private fun PsiType?.toJK(): JKType { if (this == null) return JKNoType return typeFactory.fromPsiType(this) } private val expressionTreeMapper = ExpressionTreeMapper() private val referenceSearcher: ReferenceSearcher = converterServices.oldServices.referenceSearcher private val declarationMapper = DeclarationMapper(expressionTreeMapper, bodyFilter == null) private val formattingCollector = FormattingCollector() // we don't want to capture comments of previous declaration/statement private fun PsiElement.takeLeadingCommentsNeeded() = this !is PsiMember && this !is PsiStatement private fun <T : JKFormattingOwner> T.withFormattingFrom( psi: PsiElement?, assignLineBreaks: Boolean = false, takeTrailingComments: Boolean = true, takeLeadingComments: Boolean = psi?.takeLeadingCommentsNeeded() ?: false ): T = with(formattingCollector) { takeFormattingFrom(this@withFormattingFrom, psi, assignLineBreaks, takeTrailingComments, takeLeadingComments) this@withFormattingFrom } private fun <O : JKFormattingOwner> O.withLineBreaksFrom(psi: PsiElement?) = with(formattingCollector) { takeLineBreaksFrom(this@withLineBreaksFrom, psi) this@withLineBreaksFrom } private fun <O : JKFormattingOwner> O.withLeadingCommentsWithParent(psi: PsiElement?) = with(formattingCollector) { if (psi == null) return@with this@withLeadingCommentsWithParent [email protected] += psi.leadingCommentsWithParent() return this@withLeadingCommentsWithParent } private fun PsiJavaFile.toJK(): JKFile = JKFile( packageStatement?.toJK() ?: JKPackageDeclaration(JKNameIdentifier("")), importList.toJK(saveImports = false), with(declarationMapper) { classes.map { it.toJK() } } ) private fun PsiImportList?.toJK(saveImports: Boolean): JKImportList = JKImportList(this?.allImportStatements?.mapNotNull { it.toJK(saveImports) }.orEmpty()).also { importList -> val innerComments = this?.collectDescendantsOfType<PsiComment>()?.map { comment -> JKComment(comment.text) }.orEmpty() importList.trailingComments += innerComments } private fun PsiPackageStatement.toJK(): JKPackageDeclaration = JKPackageDeclaration(JKNameIdentifier(packageName)) .also { it.withFormattingFrom(this) symbolProvider.provideUniverseSymbol(this, it) } private fun PsiImportStatementBase.toJK(saveImports: Boolean): JKImportStatement? { val target = when (this) { is PsiImportStaticStatement -> resolveTargetClass() else -> resolve() } val rawName = (importReference?.canonicalText ?: return null) + if (isOnDemand) ".*" else "" // We will save only unresolved imports and print all static calls with fqNames // to avoid name clashes in future if (!saveImports) { return if (target == null) JKImportStatement(JKNameIdentifier(rawName)) else null } fun KtLightClassForDecompiledDeclaration.fqName(): FqName = kotlinOrigin?.fqName ?: FqName(qualifiedName.orEmpty()) val name = target.safeAs<KtLightElement<*, *>>()?.kotlinOrigin?.kotlinFqName?.asString() ?: target.safeAs<KtLightClass>()?.containingFile?.safeAs<KtFile>()?.packageFqName?.asString()?.let { "$it.*" } ?: target.safeAs<KtLightClassForFacade>()?.facadeClassFqName?.parent()?.asString()?.let { "$it.*" } ?: target.safeAs<KtLightClassForDecompiledDeclaration>()?.fqName()?.parent()?.asString()?.let { "$it.*" } ?: rawName return JKImportStatement(JKNameIdentifier(name)).also { it.withFormattingFrom(this) } } private fun PsiIdentifier?.toJK(): JKNameIdentifier = this?.let { JKNameIdentifier(it.text).also { identifier -> identifier.withFormattingFrom(this) } } ?: JKNameIdentifier("") private inner class ExpressionTreeMapper { fun PsiExpression?.toJK(): JKExpression = when (this) { null -> JKStubExpression() is PsiBinaryExpression -> toJK() is PsiPrefixExpression -> toJK() is PsiPostfixExpression -> toJK() is PsiLiteralExpression -> toJK() is PsiMethodCallExpression -> toJK() is PsiReferenceExpression -> toJK() is PsiNewExpression -> toJK() is PsiArrayAccessExpression -> toJK() is PsiTypeCastExpression -> toJK() is PsiParenthesizedExpression -> toJK() is PsiAssignmentExpression -> toJK() is PsiInstanceOfExpression -> toJK() is PsiThisExpression -> JKThisExpression( qualifier?.referenceName?.let { JKLabelText(JKNameIdentifier(it)) } ?: JKLabelEmpty(), type.toJK() ) is PsiSuperExpression -> { val qualifyingType = qualifier?.resolve() as? PsiClass if (qualifyingType == null) { // Case 0: plain "super.foo()" call JKSuperExpression(type.toJK()) } else { // Java's qualified super call syntax "A.super.foo()" is represented by two different cases in Kotlin. // See https://kotlinlang.org/docs/inheritance.html#calling-the-superclass-implementation val isQualifiedSuperTypeCall = getContainingClass()?.supers?.contains(qualifyingType) == true var superTypeQualifier: JKClassSymbol? = null var outerTypeQualifier: JKLabel = JKLabelEmpty() if (isQualifiedSuperTypeCall) { // Case 1: "super<A>.foo()" for accessing the superclass of the current class superTypeQualifier = symbolProvider.provideDirectSymbol(qualifyingType) as? JKClassSymbol } else { // Case 2: "[email protected]()" for accessing the superclass of the outer class outerTypeQualifier = qualifier?.referenceName?.let { JKLabelText(JKNameIdentifier(it)) } ?: outerTypeQualifier } JKSuperExpression(type.toJK(), superTypeQualifier, outerTypeQualifier) } } is PsiConditionalExpression -> JKIfElseExpression( condition.toJK(), thenExpression.toJK(), elseExpression.toJK(), type.toJK() ) is PsiPolyadicExpression -> { val token = JKOperatorToken.fromElementType(operationTokenType) val jkOperandsWithPsiTypes = operands.map { it.toJK().withLineBreaksFrom(it).parenthesizeIfCompoundExpression() to it.type } jkOperandsWithPsiTypes.reduce { (left, leftType), (right, rightType) -> val psiType = calcTypeForBinaryExpression(leftType, rightType, operationTokenType, true) val jkType = psiType?.toJK() ?: typeFactory.types.nullableAny JKBinaryExpression(left, right, JKKtOperatorImpl(token, jkType)) to psiType }.let { (folded, _) -> if (jkOperandsWithPsiTypes.any { it.first.containsNewLine() }) folded.parenthesize() else folded } } is PsiArrayInitializerExpression -> toJK() is PsiLambdaExpression -> toJK() is PsiClassObjectAccessExpressionImpl -> toJK() is PsiSwitchExpression -> JKJavaSwitchExpression(expression.toJK(), collectSwitchCases()) else -> createErrorExpression() }.also { if (this != null) { (it as PsiOwner).psi = this it.withFormattingFrom(this) } } fun PsiClassObjectAccessExpressionImpl.toJK(): JKClassLiteralExpression { val type = operand.type.toJK().updateNullabilityRecursively(NotNull) return JKClassLiteralExpression( JKTypeElement(type), when (type) { is JKJavaPrimitiveType -> JKClassLiteralExpression.ClassLiteralType.JAVA_PRIMITIVE_CLASS is JKJavaVoidType -> JKClassLiteralExpression.ClassLiteralType.JAVA_VOID_TYPE else -> JKClassLiteralExpression.ClassLiteralType.JAVA_CLASS } ).also { it.withFormattingFrom(this) } } fun PsiInstanceOfExpression.toJK(): JKIsExpression { val pattern = pattern.safeAs<PsiTypeTestPattern>() val psiTypeElement = checkType ?: pattern?.checkType val type = psiTypeElement?.type?.toJK() ?: JKNoType val typeElement = with(declarationMapper) { JKTypeElement(type, psiTypeElement.annotationList()) } val expr = JKIsExpression(operand.toJK(), typeElement).also { it.withFormattingFrom(this) } val patternVariable = pattern?.patternVariable if (patternVariable != null) { val name = expr.expression.safeAs<JKFieldAccessExpression>()?.identifier?.name ?: patternVariable.name val typeElementForPattern = with(declarationMapper) { JKTypeElement(type, psiTypeElement.annotationList()) } // Executed for the side effect of binding the symbol to a valid target JKParameter(typeElementForPattern, JKNameIdentifier(name)).also { symbolProvider.provideUniverseSymbol(patternVariable, it) it.psi = this } } return expr } fun PsiAssignmentExpression.toJK(): JKJavaAssignmentExpression { return JKJavaAssignmentExpression( lExpression.toJK(), rExpression.toJK(), createOperator(operationSign.tokenType, type) ).also { it.withFormattingFrom(this) } } fun PsiBinaryExpression.toJK(): JKExpression { val token = when (operationSign.tokenType) { JavaTokenType.EQEQ, JavaTokenType.NE -> when { canKeepEqEq(lOperand, rOperand) -> JKOperatorToken.fromElementType(operationSign.tokenType) operationSign.tokenType == JavaTokenType.EQEQ -> JKOperatorToken.fromElementType(KtTokens.EQEQEQ) else -> JKOperatorToken.fromElementType(KtTokens.EXCLEQEQEQ) } else -> JKOperatorToken.fromElementType(operationSign.tokenType) } return JKBinaryExpression( lOperand.toJK().withLineBreaksFrom(lOperand), rOperand.toJK().withLineBreaksFrom(rOperand), JKKtOperatorImpl( token, type?.toJK() ?: typeFactory.types.nullableAny ) ).also { it.withFormattingFrom(this) } } fun PsiLiteralExpression.toJK(): JKExpression { require(this is PsiLiteralExpressionImpl) return when (literalElementType) { JavaTokenType.NULL_KEYWORD -> JKLiteralExpression("null", NULL) JavaTokenType.TRUE_KEYWORD -> JKLiteralExpression("true", BOOLEAN) JavaTokenType.FALSE_KEYWORD -> JKLiteralExpression("false", BOOLEAN) JavaTokenType.STRING_LITERAL -> JKLiteralExpression(text, STRING) JavaTokenType.TEXT_BLOCK_LITERAL -> JKLiteralExpression(text, TEXT_BLOCK) JavaTokenType.CHARACTER_LITERAL -> JKLiteralExpression(text, CHAR) JavaTokenType.INTEGER_LITERAL -> JKLiteralExpression(text, INT) JavaTokenType.LONG_LITERAL -> JKLiteralExpression(text, LONG) JavaTokenType.FLOAT_LITERAL -> JKLiteralExpression(text, FLOAT) JavaTokenType.DOUBLE_LITERAL -> JKLiteralExpression(text, DOUBLE) else -> createErrorExpression() }.also { it.withFormattingFrom(this) } } private fun createOperator(elementType: IElementType, type: PsiType?) = JKKtOperatorImpl( JKOperatorToken.fromElementType(elementType), type?.toJK() ?: typeFactory.types.nullableAny ) fun PsiPrefixExpression.toJK(): JKExpression = when (operationSign.tokenType) { JavaTokenType.TILDE -> operand.toJK().callOn(symbolProvider.provideMethodSymbol("kotlin.Int.inv")) else -> JKPrefixExpression(operand.toJK(), createOperator(operationSign.tokenType, type)) }.also { it.withFormattingFrom(this) } fun PsiPostfixExpression.toJK(): JKExpression = JKPostfixExpression(operand.toJK(), createOperator(operationSign.tokenType, type)).also { it.withFormattingFrom(this) } fun PsiLambdaExpression.toJK(): JKExpression { return JKLambdaExpression( body.let { when (it) { is PsiExpression -> JKExpressionStatement(it.toJK()) is PsiCodeBlock -> JKBlockStatement(with(declarationMapper) { it.toJK() }) else -> JKBlockStatement(JKBodyStub) } }, with(declarationMapper) { parameterList.parameters.map { it.toJK() } }, functionalType() ).also { it.withFormattingFrom(this) } } private fun PsiMethodCallExpression.getExplicitTypeArguments(): PsiReferenceParameterList { if (typeArguments.isNotEmpty()) return typeArgumentList val resolveResult = resolveMethodGenerics() if (resolveResult is MethodCandidateInfo && resolveResult.isApplicable) { val method = resolveResult.element if (method.isConstructor || !method.hasTypeParameters()) return typeArgumentList } return AddTypeArgumentsFix.addTypeArguments(this, null, false) ?.safeAs<PsiMethodCallExpression>() ?.typeArgumentList ?: typeArgumentList } //TODO mostly copied from old j2k, refactor fun PsiMethodCallExpression.toJK(): JKExpression { val arguments = argumentList val typeArguments = getExplicitTypeArguments().toJK() val qualifier = methodExpression.qualifierExpression?.toJK()?.withLineBreaksFrom(methodExpression.qualifierExpression) var target = methodExpression.resolve() if (target is PsiMethodImpl && target.name.canBeGetterOrSetterName()) { val baseCallable = target.findSuperMethods().firstOrNull() if (baseCallable is KtLightMethod) { target = baseCallable } } val symbol = target?.let { symbolProvider.provideDirectSymbol(it) } ?: JKUnresolvedMethod(methodExpression, typeFactory) return when { methodExpression.referenceNameElement is PsiKeyword -> { val callee = when ((methodExpression.referenceNameElement as PsiKeyword).tokenType) { SUPER_KEYWORD -> JKSuperExpression() THIS_KEYWORD -> JKThisExpression(JKLabelEmpty(), JKNoType) else -> createErrorExpression("unknown keyword in callee position") } val calleeSymbol = when { symbol is JKMethodSymbol -> symbol target is KtLightMethod -> KtClassImplicitConstructorSymbol(target, typeFactory) else -> JKUnresolvedMethod(methodExpression, typeFactory) } JKDelegationConstructorCall(calleeSymbol, callee, arguments.toJK()) } target is KtLightMethod -> { when (val origin = target.kotlinOrigin) { is KtNamedFunction -> { if (origin.isExtensionDeclaration()) { val receiver = arguments.expressions.firstOrNull()?.toJK()?.parenthesizeIfCompoundExpression() origin.fqName?.also { importStorage.addImport(it) } JKCallExpressionImpl( symbolProvider.provideDirectSymbol(origin) as JKMethodSymbol, arguments.expressions.drop(1).map { it.toJK() }.toArgumentList(), typeArguments ).qualified(receiver) } else { origin.fqName?.also { importStorage.addImport(it) } JKCallExpressionImpl( symbolProvider.provideDirectSymbol(origin) as JKMethodSymbol, arguments.toJK(), typeArguments ).qualified(qualifier) } } is KtProperty, is KtPropertyAccessor, is KtParameter -> { origin.kotlinFqName?.also { importStorage.addImport(it) } val property = if (origin is KtPropertyAccessor) origin.parent as KtProperty else origin as KtNamedDeclaration val parameterCount = target.parameterList.parameters.size val propertyAccessExpression = JKFieldAccessExpression(symbolProvider.provideDirectSymbol(property) as JKFieldSymbol) val isExtension = property.isExtensionDeclaration() val isTopLevel = origin.getStrictParentOfType<KtClassOrObject>() == null val propertyAccess = if (isTopLevel) { if (isExtension) JKQualifiedExpression( arguments.expressions.first().toJK(), propertyAccessExpression ) else propertyAccessExpression } else propertyAccessExpression.qualified(qualifier) when (if (isExtension) parameterCount - 1 else parameterCount) { 0 /* getter */ -> propertyAccess 1 /* setter */ -> { val argument = (arguments.expressions[if (isExtension) 1 else 0]).toJK() JKJavaAssignmentExpression( propertyAccess, argument, createOperator(JavaTokenType.EQ, type) //TODO correct type ) } else -> createErrorExpression("expected getter or setter call") } } else -> { JKCallExpressionImpl( JKMultiverseMethodSymbol(target, typeFactory), arguments.toJK(), typeArguments ).qualified(qualifier) } } } target is LightRecordMethod -> { val field = getFieldForComponent(target.recordComponent) ?: return createErrorExpression() JKFieldAccessExpression(symbolProvider.provideDirectSymbol(field) as JKFieldSymbol) .qualified(qualifier ?: JKThisExpression(JKLabelEmpty())) } symbol is JKMethodSymbol -> JKCallExpressionImpl(symbol, arguments.toJK(), typeArguments) .qualified(qualifier) symbol is JKFieldSymbol -> JKFieldAccessExpression(symbol).qualified(qualifier) else -> createErrorExpression() }.also { it.withFormattingFrom(this) } } fun PsiFunctionalExpression.functionalType(): JKTypeElement = functionalInterfaceType ?.takeUnless { type -> type.safeAs<PsiClassType>()?.parameters?.any { it is PsiCapturedWildcardType } == true }?.takeUnless { type -> type.isKotlinFunctionalType }?.toJK() ?.asTypeElement() ?: JKTypeElement(JKNoType) fun PsiMethodReferenceExpression.toJK(): JKMethodReferenceExpression { val symbol = symbolProvider.provideSymbolForReference<JKSymbol>(this).let { symbol -> when { symbol.isUnresolved && isConstructor -> JKUnresolvedClassSymbol(qualifier?.text ?: text, typeFactory) symbol.isUnresolved && !isConstructor -> JKUnresolvedMethod(referenceName ?: text, typeFactory) else -> symbol } } return JKMethodReferenceExpression( methodReferenceQualifier(), symbol, functionalType(), isConstructor ) } fun PsiMethodReferenceExpression.methodReferenceQualifier(): JKExpression { val qualifierType = qualifierType if (qualifierType != null) return JKTypeQualifierExpression(typeFactory.fromPsiType(qualifierType.type)) return qualifierExpression?.toJK() ?: JKStubExpression() } fun PsiReferenceExpression.toJK(): JKExpression { if (this is PsiMethodReferenceExpression) return toJK() val target = resolve() if (target is KtLightClassForFacade || target is KtLightClassForDecompiledDeclaration ) return JKStubExpression() if (target is KtLightField && target.name == "INSTANCE" && target.containingClass.kotlinOrigin is KtObjectDeclaration ) { return qualifierExpression?.toJK() ?: JKStubExpression() } val symbol = symbolProvider.provideSymbolForReference<JKSymbol>(this) return when (symbol) { is JKClassSymbol -> JKClassAccessExpression(symbol) is JKFieldSymbol -> JKFieldAccessExpression(symbol) is JKPackageSymbol -> JKPackageAccessExpression(symbol) is JKMethodSymbol -> JKMethodAccessExpression(symbol) is JKTypeParameterSymbol -> JKTypeQualifierExpression(JKTypeParameterType(symbol)) else -> createErrorExpression() }.qualified(qualifierExpression?.toJK()).also { it.withFormattingFrom(this) } } fun PsiArrayInitializerExpression.toJK(): JKExpression { return JKJavaNewArray( initializers.map { it.toJK().withLineBreaksFrom(it) }, JKTypeElement(type?.toJK().safeAs<JKJavaArrayType>()?.type ?: JKContextType) ).also { it.withFormattingFrom(this) } } fun PsiNewExpression.toJK(): JKExpression { require(this is PsiNewExpressionImpl) val newExpression = if (findChildByRole(ChildRole.LBRACKET) != null) { arrayInitializer?.toJK() ?: run { val dimensions = mutableListOf<JKExpression>() var child = firstChild while (child != null) { if (child.node.elementType == JavaTokenType.LBRACKET) { child = child.getNextSiblingIgnoringWhitespaceAndComments() if (child.node.elementType == JavaTokenType.RBRACKET) { dimensions += JKStubExpression() } else { child.safeAs<PsiExpression>()?.toJK()?.also { dimensions += it } } } child = child.nextSibling } JKJavaNewEmptyArray( dimensions, JKTypeElement(generateSequence(type?.toJK()) { it.safeAs<JKJavaArrayType>()?.type }.last()) ).also { it.psi = this } } } else { val classSymbol = classOrAnonymousClassReference?.resolve()?.let { symbolProvider.provideDirectSymbol(it) as JKClassSymbol } ?: JKUnresolvedClassSymbol( classOrAnonymousClassReference?.referenceName ?: NO_NAME_PROVIDED, typeFactory ) val typeArgumentList = this.typeArgumentList.toJK() .takeIf { it.typeArguments.isNotEmpty() } ?: classOrAnonymousClassReference ?.typeParameters ?.let { typeParameters -> JKTypeArgumentList(typeParameters.map { JKTypeElement(it.toJK()) }) } ?: JKTypeArgumentList() JKNewExpression( classSymbol, argumentList?.toJK() ?: JKArgumentList(), typeArgumentList, with(declarationMapper) { anonymousClass?.createClassBody() } ?: JKClassBody(), anonymousClass != null ).also { it.psi = this } } return newExpression.qualified(qualifier?.toJK()) } fun PsiReferenceParameterList.toJK(): JKTypeArgumentList = JKTypeArgumentList( typeParameterElements.map { JKTypeElement(it.type.toJK(), with(declarationMapper) { it.annotationList() }) } ).also { it.withFormattingFrom(this) } fun PsiArrayAccessExpression.toJK(): JKExpression = arrayExpression.toJK() .callOn( symbolProvider.provideMethodSymbol("kotlin.Array.get"), arguments = listOf(indexExpression?.toJK() ?: JKStubExpression()) ).also { it.withFormattingFrom(this) } fun PsiTypeCastExpression.toJK(): JKExpression { return JKTypeCastExpression( operand?.toJK() ?: createErrorExpression(), (castType?.type?.toJK() ?: JKNoType).asTypeElement(with(declarationMapper) { castType.annotationList() }) ).also { it.withFormattingFrom(this) } } fun PsiParenthesizedExpression.toJK(): JKExpression { return JKParenthesizedExpression(expression.toJK()) .also { it.withFormattingFrom(this) } } fun PsiExpressionList.toJK(): JKArgumentList { val jkExpressions = expressions.map { it.toJK().withLineBreaksFrom(it) } return ((parent as? PsiCall)?.resolveMethod() ?.let { method -> val lastExpressionType = expressions.lastOrNull()?.type if (jkExpressions.size == method.parameterList.parameters.size && method.parameterList.parameters.getOrNull(jkExpressions.lastIndex)?.isVarArgs == true && lastExpressionType is PsiArrayType ) { val staredExpression = JKPrefixExpression( jkExpressions.last(), JKKtSpreadOperator(lastExpressionType.toJK()) ).withFormattingFrom(jkExpressions.last()) staredExpression.expression.also { it.hasLeadingLineBreak = false it.hasTrailingLineBreak = false } jkExpressions.dropLast(1) + staredExpression } else jkExpressions } ?: jkExpressions) .toArgumentList() .also { it.withFormattingFrom(this) } } } private inner class DeclarationMapper(val expressionTreeMapper: ExpressionTreeMapper, var withBody: Boolean) { fun <R> withBodyGeneration( elementToCheck: PsiElement, trueBranch: DeclarationMapper.() -> R, elseBranch: DeclarationMapper.() -> R = trueBranch ): R = when { withBody -> trueBranch() bodyFilter?.invoke(elementToCheck) == true -> { withBody = true trueBranch().also { withBody = false } } else -> elseBranch() } fun PsiTypeParameterList.toJK(): JKTypeParameterList = JKTypeParameterList(typeParameters.map { it.toJK() }) .also { it.withFormattingFrom(this) } fun PsiTypeParameter.toJK(): JKTypeParameter = JKTypeParameter( nameIdentifier.toJK(), extendsListTypes.map { type -> JKTypeElement(type.toJK(), JKAnnotationList(type.annotations.map { it.toJK() })) }, JKAnnotationList(annotations.mapNotNull { it?.toJK() }) ).also { symbolProvider.provideUniverseSymbol(this, it) it.withFormattingFrom(this) } fun PsiClass.toJK(): JKClass = JKClass( nameIdentifier.toJK(), inheritanceInfo(), classKind(), typeParameterList?.toJK() ?: JKTypeParameterList(), createClassBody(), annotationList(this), otherModifiers(), visibility(), modality(), recordComponents() ).also { klass -> klass.psi = this symbolProvider.provideUniverseSymbol(this, klass) klass.withFormattingFrom(this) } private fun PsiClass.recordComponents(): List<JKJavaRecordComponent> = recordComponents.map { component -> val psiTypeElement = component.typeElement val type = psiTypeElement?.type?.toJK() ?: JKNoType val typeElement = with(declarationMapper) { JKTypeElement(type, psiTypeElement.annotationList()) } JKJavaRecordComponent( typeElement, JKNameIdentifier(component.name), component.isVarArgs, component.annotationList(docCommentOwner = this) ).also { it.withFormattingFrom(component) symbolProvider.provideUniverseSymbol(component, it) it.psi = component } } fun PsiClass.inheritanceInfo(): JKInheritanceInfo { val implementsTypes = implementsList?.referencedTypes?.map { type -> JKTypeElement( type.toJK().updateNullability(NotNull), JKAnnotationList(type.annotations.map { it.toJK() }) ) }.orEmpty() val extendsTypes = extendsList?.referencedTypes?.map { type -> JKTypeElement( type.toJK().updateNullability(NotNull), JKAnnotationList(type.annotations.map { it.toJK() }) ) }.orEmpty() return JKInheritanceInfo(extendsTypes, implementsTypes) .also { if (implementsList != null) { it.withFormattingFrom(implementsList!!) } } } fun PsiClass.createClassBody() = JKClassBody( children.mapNotNull { when (it) { is PsiEnumConstant -> it.toJK() is PsiClass -> it.toJK() is PsiAnnotationMethod -> it.toJK() is PsiMethod -> it.toJK() is PsiField -> it.toJK() is PsiClassInitializer -> it.toJK() else -> null } } ).also { it.leftBrace.withFormattingFrom( lBrace, takeLeadingComments = false ) // do not capture comments which belongs to following declarations it.rightBrace.withFormattingFrom(rBrace) it.declarations.lastOrNull()?.let { lastMember -> lastMember.withLeadingCommentsWithParent(lastMember.psi) } } fun PsiClassInitializer.toJK(): JKDeclaration = when { hasModifier(JvmModifier.STATIC) -> JKJavaStaticInitDeclaration(body.toJK()) else -> JKKtInitDeclaration(body.toJK()) }.also { it.withFormattingFrom(this) } fun PsiEnumConstant.toJK(): JKEnumConstant = JKEnumConstant( nameIdentifier.toJK(), with(expressionTreeMapper) { argumentList?.toJK() ?: JKArgumentList() }, initializingClass?.createClassBody() ?: JKClassBody(), JKTypeElement( containingClass?.let { klass -> JKClassType(symbolProvider.provideDirectSymbol(klass) as JKClassSymbol) } ?: JKNoType ), annotationList(this), ).also { symbolProvider.provideUniverseSymbol(this, it) it.psi = this it.withFormattingFrom(this) } fun PsiMember.modality() = modality { ast, psi -> ast.withFormattingFrom(psi) } fun PsiMember.otherModifiers() = modifierList?.children?.mapNotNull { child -> if (child !is PsiKeyword) return@mapNotNull null when (child.text) { PsiModifier.NATIVE -> OtherModifier.NATIVE PsiModifier.STATIC -> OtherModifier.STATIC PsiModifier.STRICTFP -> OtherModifier.STRICTFP PsiModifier.SYNCHRONIZED -> OtherModifier.SYNCHRONIZED PsiModifier.TRANSIENT -> OtherModifier.TRANSIENT PsiModifier.VOLATILE -> OtherModifier.VOLATILE else -> null }?.let { JKOtherModifierElement(it).withFormattingFrom(child) } }.orEmpty() private fun PsiMember.visibility(): JKVisibilityModifierElement = visibility(referenceSearcher) { ast, psi -> ast.withFormattingFrom(psi) } fun PsiField.toJK(): JKField = JKField( JKTypeElement(type.toJK(), typeElement.annotationList()).withFormattingFrom(typeElement), nameIdentifier.toJK(), with(expressionTreeMapper) { withBodyGeneration( this@toJK, trueBranch = { initializer.toJK() }, elseBranch = { todoExpression() } ) }, annotationList(this), otherModifiers(), visibility(), modality(), JKMutabilityModifierElement( if (containingClass?.isInterface == true) IMMUTABLE else UNKNOWN ) ).also { symbolProvider.provideUniverseSymbol(this, it) it.psi = this it.withFormattingFrom(this) } fun <T : PsiModifierListOwner> T.annotationList(docCommentOwner: PsiDocCommentOwner?): JKAnnotationList { val deprecatedAnnotation = docCommentOwner?.docComment?.deprecatedAnnotation() val plainAnnotations = annotations.mapNotNull { annotation -> when { annotation !is PsiAnnotation -> null annotation.qualifiedName == DEPRECATED_ANNOTATION_FQ_NAME && deprecatedAnnotation != null -> null AnnotationTargetUtil.isTypeAnnotation(annotation) -> null else -> annotation.toJK() } } return JKAnnotationList(plainAnnotations + listOfNotNull(deprecatedAnnotation)) } fun PsiTypeElement?.annotationList(): JKAnnotationList { return JKAnnotationList(this?.applicableAnnotations?.map { it.toJK() }.orEmpty()) } fun PsiAnnotation.toJK(): JKAnnotation { val symbol = when (val reference = nameReferenceElement) { null -> JKUnresolvedClassSymbol(NO_NAME_PROVIDED, typeFactory) else -> symbolProvider.provideSymbolForReference<JKSymbol>(reference).safeAs<JKClassSymbol>() ?: JKUnresolvedClassSymbol(nameReferenceElement?.text ?: NO_NAME_PROVIDED, typeFactory) } return JKAnnotation( symbol, parameterList.attributes.map { parameter -> if (parameter.nameIdentifier != null) { JKAnnotationNameParameter( parameter.value?.toJK() ?: JKStubExpression(), JKNameIdentifier(parameter.name ?: NO_NAME_PROVIDED) ) } else { JKAnnotationParameterImpl( parameter.value?.toJK() ?: JKStubExpression() ) } } ).also { it.withFormattingFrom(this) } } fun PsiDocComment.deprecatedAnnotation(): JKAnnotation? = findTagByName("deprecated")?.let { tag -> JKAnnotation( symbolProvider.provideClassSymbol("kotlin.Deprecated"), listOf( JKAnnotationParameterImpl(stringLiteral(tag.content(), typeFactory)) ) ) } private fun PsiAnnotationMemberValue.toJK(): JKAnnotationMemberValue = when (this) { is PsiExpression -> with(expressionTreeMapper) { toJK() } is PsiAnnotation -> toJK() is PsiArrayInitializerMemberValue -> JKKtAnnotationArrayInitializerExpression(initializers.map { it.toJK() }) else -> createErrorExpression() }.also { it.withFormattingFrom(this) } fun PsiAnnotationMethod.toJK(): JKJavaAnnotationMethod = JKJavaAnnotationMethod( JKTypeElement( returnType?.toJK() ?: JKJavaVoidType.takeIf { isConstructor } ?: JKNoType, returnTypeElement?.annotationList() ?: JKAnnotationList() ), nameIdentifier.toJK(), defaultValue?.toJK() ?: JKStubExpression(), annotationList(this), otherModifiers(), visibility(), modality() ).also { it.psi = this symbolProvider.provideUniverseSymbol(this, it) it.withFormattingFrom(this) } fun PsiMethod.toJK(): JKMethod { return JKMethodImpl( JKTypeElement( returnType?.toJK() ?: JKJavaVoidType.takeIf { isConstructor } ?: JKNoType, returnTypeElement.annotationList()), nameIdentifier.toJK(), parameterList.parameters.map { it.toJK().withLineBreaksFrom(it) }, withBodyGeneration(this, trueBranch = { body?.toJK() ?: JKBodyStub }), typeParameterList?.toJK() ?: JKTypeParameterList(), annotationList(this), throwsList.referencedTypes.map { JKTypeElement(it.toJK()) }, otherModifiers(), visibility(), modality() ).also { jkMethod -> jkMethod.psi = this symbolProvider.provideUniverseSymbol(this, jkMethod) parameterList.node ?.safeAs<CompositeElement>() ?.also { jkMethod.leftParen.withFormattingFrom(it.findChildByRoleAsPsiElement(ChildRole.LPARENTH)) jkMethod.rightParen.withFormattingFrom(it.findChildByRoleAsPsiElement(ChildRole.RPARENTH)) } }.withFormattingFrom(this) } fun PsiParameter.toJK(): JKParameter { val rawType = type.toJK() val type = if (isVarArgs && rawType is JKJavaArrayType) JKTypeElement(rawType.type, typeElement.annotationList()) else rawType.asTypeElement(typeElement.annotationList()) val name = if (nameIdentifier != null) nameIdentifier.toJK() else JKNameIdentifier(name) return JKParameter( type, name, isVarArgs, annotationList = annotationList(null) ).also { symbolProvider.provideUniverseSymbol(this, it) it.psi = this it.withFormattingFrom(this) } } fun PsiCodeBlock.toJK(): JKBlock = JKBlockImpl( if (withBody) statements.map { it.toJK() } else listOf(todoExpression().asStatement()) ).withFormattingFrom(this).also { it.leftBrace.withFormattingFrom(lBrace) it.rightBrace.withFormattingFrom(rBrace) } fun PsiLocalVariable.toJK(): JKLocalVariable { return JKLocalVariable( JKTypeElement(type.toJK(), typeElement.annotationList()).withFormattingFrom(typeElement), nameIdentifier.toJK(), with(expressionTreeMapper) { initializer.toJK() }, JKMutabilityModifierElement( if (hasModifierProperty(PsiModifier.FINAL)) IMMUTABLE else UNKNOWN ), annotationList(null) ).also { i -> symbolProvider.provideUniverseSymbol(this, i) i.psi = this }.also { it.withFormattingFrom(this) } } fun PsiStatement?.asJKStatementsList() = when (this) { null -> emptyList() is PsiExpressionListStatement -> expressionList.expressions.map { expression -> JKExpressionStatement(with(expressionTreeMapper) { expression.toJK() }) } else -> listOf(toJK()) } fun PsiStatement?.toJK(): JKStatement { return when (this) { null -> JKExpressionStatement(JKStubExpression()) is PsiExpressionStatement -> JKExpressionStatement(with(expressionTreeMapper) { expression.toJK() }) is PsiReturnStatement -> JKReturnStatement(with(expressionTreeMapper) { returnValue.toJK() }) is PsiDeclarationStatement -> JKDeclarationStatement(declaredElements.mapNotNull { when (it) { is PsiClass -> it.toJK() is PsiLocalVariable -> it.toJK() else -> null } }) is PsiAssertStatement -> JKJavaAssertStatement( with(expressionTreeMapper) { assertCondition.toJK() }, with(expressionTreeMapper) { assertDescription?.toJK() } ?: JKStubExpression()) is PsiIfStatement -> with(expressionTreeMapper) { JKIfElseStatement(condition.toJK(), thenBranch.toJK(), elseBranch.toJK()) } is PsiForStatement -> JKJavaForLoopStatement( initialization.asJKStatementsList(), with(expressionTreeMapper) { condition.toJK() }, update.asJKStatementsList(), body.toJK() ) is PsiForeachStatement -> JKForInStatement( iterationParameter.toJK(), with(expressionTreeMapper) { iteratedValue?.toJK() ?: JKStubExpression() }, body?.toJK() ?: blockStatement() ) is PsiBlockStatement -> JKBlockStatement(codeBlock.toJK()) is PsiWhileStatement -> JKWhileStatement(with(expressionTreeMapper) { condition.toJK() }, body.toJK()) is PsiDoWhileStatement -> JKDoWhileStatement(body.toJK(), with(expressionTreeMapper) { condition.toJK() }) is PsiSwitchStatement -> JKJavaSwitchStatement(with(expressionTreeMapper) { expression.toJK() }, collectSwitchCases()) is PsiBreakStatement -> JKBreakStatement(labelIdentifier?.let { JKLabelText(JKNameIdentifier(it.text)) } ?: JKLabelEmpty()) is PsiContinueStatement -> { val label = labelIdentifier?.let { JKLabelText(JKNameIdentifier(it.text)) } ?: JKLabelEmpty() JKContinueStatement(label) } is PsiLabeledStatement -> { val (labels, statement) = collectLabels() JKLabeledExpression(statement.toJK(), labels.map { JKNameIdentifier(it.text) }).asStatement() } is PsiEmptyStatement -> JKEmptyStatement() is PsiThrowStatement -> JKThrowExpression(with(expressionTreeMapper) { exception.toJK() }).asStatement() is PsiTryStatement -> JKJavaTryStatement( resourceList?.toList()?.map { (it as PsiResourceListElement).toJK() }.orEmpty(), tryBlock?.toJK() ?: JKBodyStub, finallyBlock?.toJK() ?: JKBodyStub, catchSections.map { it.toJK() } ) is PsiSynchronizedStatement -> JKJavaSynchronizedStatement( with(expressionTreeMapper) { lockExpression?.toJK() } ?: JKStubExpression(), body?.toJK() ?: JKBodyStub ) is PsiYieldStatement -> JKJavaYieldStatement(with(expressionTreeMapper) { expression.toJK() }) else -> createErrorStatement() }.also { if (this != null) { (it as PsiOwner).psi = this it.withFormattingFrom(this) } } } fun PsiResourceListElement.toJK(): JKJavaResourceElement = when (this) { is PsiResourceVariable -> JKJavaResourceDeclaration((this as PsiLocalVariable).toJK()) is PsiResourceExpression -> JKJavaResourceExpression(with(expressionTreeMapper) { [email protected]() }) else -> error("Unexpected resource list ${this::class.java}") } fun PsiCatchSection.toJK(): JKJavaTryCatchSection = JKJavaTryCatchSection( parameter?.toJK() ?: JKParameter(JKTypeElement(JKNoType), JKNameIdentifier(NO_NAME_PROVIDED)), catchBlock?.toJK() ?: JKBodyStub ).also { it.psi = this it.withFormattingFrom(this) } } fun PsiLabeledStatement.collectLabels(): Pair<List<PsiIdentifier>, PsiStatement> { val labels = mutableListOf<PsiIdentifier>() var currentStatement: PsiStatement? = this while (currentStatement is PsiLabeledStatementImpl) { labels += currentStatement.labelIdentifier currentStatement = currentStatement.statement ?: return labels to currentStatement } return labels to currentStatement!! } fun buildTree(psi: PsiElement, saveImports: Boolean): JKTreeRoot? = when (psi) { is PsiJavaFile -> psi.toJK() is PsiExpression -> with(expressionTreeMapper) { psi.toJK() } is PsiStatement -> with(declarationMapper) { psi.toJK() } is PsiTypeParameter -> with(declarationMapper) { psi.toJK() } is PsiClass -> with(declarationMapper) { psi.toJK() } is PsiField -> with(declarationMapper) { psi.toJK() } is PsiMethod -> with(declarationMapper) { psi.toJK() } is PsiAnnotation -> with(declarationMapper) { psi.toJK() } is PsiImportList -> psi.toJK(saveImports) is PsiImportStatementBase -> psi.toJK(saveImports) is PsiJavaCodeReferenceElement -> if (psi.parent is PsiReferenceList) { val factory = JavaPsiFacade.getInstance(psi.project).elementFactory val type = factory.createType(psi) JKTypeElement(type.toJK().updateNullabilityRecursively(NotNull)) } else null else -> null }?.let { JKTreeRoot(it) } private fun PsiElement.createErrorExpression(message: String? = null): JKExpression { return JKErrorExpression(this, message) } private fun PsiElement.createErrorStatement(message: String? = null): JKStatement { return JKErrorStatement(this, message) } private fun PsiSwitchBlock.collectSwitchCases(): List<JKJavaSwitchCase> = with(declarationMapper) { val statements = body?.statements ?: return emptyList() val cases = mutableListOf<JKJavaSwitchCase>() for (statement in statements) { when (statement) { is PsiSwitchLabelStatement -> cases += when { statement.isDefaultCase -> JKJavaDefaultSwitchCase(emptyList()) else -> JKJavaClassicLabelSwitchCase( with(expressionTreeMapper) { statement.caseLabelElementList?.elements?.map { (it as? PsiExpression).toJK() }.orEmpty() }, emptyList() ) }.withFormattingFrom(statement) is PsiSwitchLabeledRuleStatement -> { val body = statement.body.toJK() cases += when { statement.isDefaultCase -> JKJavaDefaultSwitchCase(listOf(body)) else -> { JKJavaArrowSwitchLabelCase( with(expressionTreeMapper) { statement.caseLabelElementList?.elements?.map { (it as? PsiExpression).toJK() }.orEmpty() }, listOf(body), ) } }.withFormattingFrom(statement) } else -> cases.lastOrNull()?.also { it.statements = it.statements + statement.toJK() } ?: run { cases += JKJavaClassicLabelSwitchCase( listOf(JKStubExpression()), listOf(statement.toJK()) ) } } } return cases } companion object { private const val DEPRECATED_ANNOTATION_FQ_NAME = "java.lang.Deprecated" private const val NO_NAME_PROVIDED = "NO_NAME_PROVIDED" } }
apache-2.0
c0a389503a6391f99b1c42c04e9ad304
45.019544
140
0.556289
6.133275
false
false
false
false
SimpleMobileTools/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/SaveAsDialog.kt
1
5158
package com.simplemobiletools.gallery.pro.dialogs import androidx.appcompat.app.AlertDialog import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.dialogs.ConfirmationDialog import com.simplemobiletools.commons.dialogs.FilePickerDialog import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.isRPlus import com.simplemobiletools.gallery.pro.R import kotlinx.android.synthetic.main.dialog_save_as.view.* import java.io.File class SaveAsDialog( val activity: BaseSimpleActivity, val path: String, val appendFilename: Boolean, val cancelCallback: (() -> Unit)? = null, val callback: (savePath: String) -> Unit ) { init { var realPath = path.getParentPath() if (activity.isRestrictedWithSAFSdk30(realPath) && !activity.isInDownloadDir(realPath)) { realPath = activity.getPicturesDirectoryPath(realPath) } val view = activity.layoutInflater.inflate(R.layout.dialog_save_as, null).apply { folder_value.setText("${activity.humanizePath(realPath).trimEnd('/')}/") val fullName = path.getFilenameFromPath() val dotAt = fullName.lastIndexOf(".") var name = fullName if (dotAt > 0) { name = fullName.substring(0, dotAt) val extension = fullName.substring(dotAt + 1) extension_value.setText(extension) } if (appendFilename) { name += "_1" } filename_value.setText(name) folder_value.setOnClickListener { activity.hideKeyboard(folder_value) FilePickerDialog(activity, realPath, false, false, true, true) { folder_value.setText(activity.humanizePath(it)) realPath = it } } } activity.getAlertDialogBuilder() .setPositiveButton(R.string.ok, null) .setNegativeButton(R.string.cancel) { dialog, which -> cancelCallback?.invoke() } .setOnCancelListener { cancelCallback?.invoke() } .apply { activity.setupDialogStuff(view, this, R.string.save_as) { alertDialog -> alertDialog.showKeyboard(view.filename_value) alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener { val filename = view.filename_value.value val extension = view.extension_value.value if (filename.isEmpty()) { activity.toast(R.string.filename_cannot_be_empty) return@setOnClickListener } if (extension.isEmpty()) { activity.toast(R.string.extension_cannot_be_empty) return@setOnClickListener } val newFilename = "$filename.$extension" val newPath = "${realPath.trimEnd('/')}/$newFilename" if (!newFilename.isAValidFilename()) { activity.toast(R.string.filename_invalid_characters) return@setOnClickListener } if (activity.getDoesFilePathExist(newPath)) { val title = String.format(activity.getString(R.string.file_already_exists_overwrite), newFilename) ConfirmationDialog(activity, title) { val newFile = File(newPath) val isInDownloadDir = activity.isInDownloadDir(newPath) val isInSubFolderInDownloadDir = activity.isInSubFolderInDownloadDir(newPath) if ((isRPlus() && !isExternalStorageManager()) && isInDownloadDir && !isInSubFolderInDownloadDir && !newFile.canWrite()) { val fileDirItem = arrayListOf(File(newPath).toFileDirItem(activity)) val fileUris = activity.getFileUrisFromFileDirItems(fileDirItem) activity.updateSDK30Uris(fileUris) { success -> if (success) { selectPath(alertDialog, newPath) } } } else { selectPath(alertDialog, newPath) } } } else { selectPath(alertDialog, newPath) } } } } } private fun selectPath(alertDialog: AlertDialog, newPath: String) { activity.handleSAFDialogSdk30(newPath) { if (!it) { return@handleSAFDialogSdk30 } callback(newPath) alertDialog.dismiss() } } }
gpl-3.0
b0408ee984e25df15b67395d9385c190
44.646018
154
0.531408
5.782511
false
false
false
false
apollographql/apollo-android
apollo-api/src/commonMain/kotlin/com/apollographql/apollo3/api/json/BufferedSinkJsonWriter.kt
1
10656
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apollographql.apollo3.api.json import com.apollographql.apollo3.api.Upload import com.apollographql.apollo3.api.json.internal.JsonScope import com.apollographql.apollo3.api.json.BufferedSourceJsonReader.Companion.MAX_STACK_SIZE import com.apollographql.apollo3.exception.JsonDataException import okio.BufferedSink import okio.IOException import kotlin.jvm.JvmOverloads /** * A [JsonWriter] that writes json to an okio [BufferedSink] * * The base implementation was taken from Moshi and ported to Kotlin multiplatform with some tweaks to make it better suited for GraphQL * (see [JsonWriter] and [path]). * * To writer to a [Map], see also [MapJsonWriter] * * * @param indent: A string containing a full set of spaces for a single level of indentation, or null for no pretty printing. */ class BufferedSinkJsonWriter @JvmOverloads constructor( private val sink: BufferedSink, private val indent: String? = null, ) : JsonWriter { // The nesting stack. Using a manual array rather than an ArrayList saves 20%. This stack permits up to MAX_STACK_SIZE levels of nesting including // the top-level document. Deeper nesting is prone to trigger StackOverflowErrors. private var stackSize = 0 private val scopes = IntArray(MAX_STACK_SIZE) private val pathNames = arrayOfNulls<String>(MAX_STACK_SIZE) private val pathIndices = IntArray(MAX_STACK_SIZE) /** * Configure this writer to relax its syntax rules. * * By default, this writer only emits well-formed JSON as specified by [RFC 7159](http://www.ietf.org/rfc/rfc7159.txt). */ private var isLenient = false /** The name/value separator; either ":" or ": ". */ private val separator: String get() = if (indent.isNullOrEmpty()) ":" else ": " private var deferredName: String? = null /** * Returns a [JsonPath](http://goessner.net/articles/JsonPath/) to the current location in the JSON value. * * Note: the implementation is modified from the Moshi implementation to: * - Remove the leading "$." * - Remove square brackets in lists. This isn't great because it doesn't allow distinguishing lists from "0" keys but * this is how File Upload works: https://github.com/jaydenseric/graphql-multipart-request-spec */ override val path: String get() = JsonScope.getPath(stackSize, scopes, pathNames, pathIndices) init { pushScope(JsonScope.EMPTY_DOCUMENT) } override fun beginArray(): JsonWriter { writeDeferredName() return open(JsonScope.EMPTY_ARRAY, "[") } override fun endArray(): JsonWriter { return close(JsonScope.EMPTY_ARRAY, JsonScope.NONEMPTY_ARRAY, "]") } override fun beginObject(): JsonWriter { writeDeferredName() return open(JsonScope.EMPTY_OBJECT, "{") } override fun endObject(): JsonWriter { return close(JsonScope.EMPTY_OBJECT, JsonScope.NONEMPTY_OBJECT, "}") } /** * Enters a new scope by appending any necessary whitespace and the given bracket. */ private fun open(empty: Int, openBracket: String): JsonWriter { beforeValue() pushScope(empty) pathIndices[stackSize - 1] = 0 sink.writeUtf8(openBracket) return this } /** * Closes the current scope by appending any necessary whitespace and the given bracket. */ private fun close(empty: Int, nonempty: Int, closeBracket: String): JsonWriter { val context = peekScope() check(!(context != nonempty && context != empty)) { "Nesting problem." } check(deferredName == null) { "Dangling name: $deferredName" } stackSize-- pathNames[stackSize] = null // Free the last path name so that it can be garbage collected! pathIndices[stackSize - 1]++ if (context == nonempty) { newline() } sink.writeUtf8(closeBracket) return this } override fun name(name: String): JsonWriter { check(stackSize != 0) { "JsonWriter is closed." } check(deferredName == null) { "Nesting problem." } deferredName = name pathNames[stackSize - 1] = name return this } private fun writeDeferredName() { if (deferredName != null) { beforeName() string(sink, deferredName!!) deferredName = null } } override fun value(value: String): JsonWriter { writeDeferredName() beforeValue() string(sink, value) pathIndices[stackSize - 1]++ return this } override fun nullValue() = jsonValue("null") override fun value(value: Boolean) = jsonValue(if (value) "true" else "false") override fun value(value: Double): JsonWriter { require(!(!isLenient && (value.isNaN() || value.isInfinite()))) { "Numeric values must be finite, but was $value" } return jsonValue(value.toString()) } override fun value(value: Int) = jsonValue(value.toString()) override fun value(value: Long) = jsonValue(value.toString()) override fun value(value: JsonNumber) = jsonValue(value.toString()) override fun value(value: Upload) = apply { nullValue() } /** * Writes the given value as raw json without escaping. It is the caller responsibility to make sure * [value] is a valid json string */ fun jsonValue(value: String): JsonWriter { writeDeferredName() beforeValue() sink.writeUtf8(value) pathIndices[stackSize - 1]++ return this } /** * Ensures all buffered data is written to the underlying [okio.Sink] * and flushes that writer. */ override fun flush() { check(stackSize != 0) { "JsonWriter is closed." } sink.flush() } /** * Flushes and closes this writer and the underlying [okio.Sink]. * * @throws IOException if the JSON document is incomplete. */ override fun close() { sink.close() val size = stackSize if (size > 1 || size == 1 && scopes[size - 1] != JsonScope.NONEMPTY_DOCUMENT) { throw IOException("Incomplete document") } stackSize = 0 } private fun newline() { if (indent == null) { return } sink.writeByte('\n'.code) var i = 1 val size = stackSize while (i < size) { sink.writeUtf8(indent) i++ } } /** * Inserts any necessary separators and whitespace before a name. Also adjusts the stack to expect the name's value. */ private fun beforeName() { val context = peekScope() if (context == JsonScope.NONEMPTY_OBJECT) { // first in object sink.writeByte(','.code) } else check(context == JsonScope.EMPTY_OBJECT) { // not in an object! "Nesting problem." } newline() replaceTop(JsonScope.DANGLING_NAME) } /** * Inserts any necessary separators and whitespace before a literal value, inline array, or inline object. Also adjusts the stack to * expect either a closing bracket or another element. */ private fun beforeValue() { when (peekScope()) { JsonScope.NONEMPTY_DOCUMENT -> { check(isLenient) { "JSON must have only one top-level value." } replaceTop(JsonScope.NONEMPTY_DOCUMENT) } JsonScope.EMPTY_DOCUMENT -> replaceTop(JsonScope.NONEMPTY_DOCUMENT) JsonScope.EMPTY_ARRAY -> { replaceTop(JsonScope.NONEMPTY_ARRAY) newline() } JsonScope.NONEMPTY_ARRAY -> { sink.writeByte(','.code) newline() } JsonScope.DANGLING_NAME -> { sink.writeUtf8(separator) replaceTop(JsonScope.NONEMPTY_OBJECT) } else -> throw IllegalStateException("Nesting problem.") } } /** * Returns the scope on the top of the stack. */ private fun peekScope(): Int { check(stackSize != 0) { "JsonWriter is closed." } return scopes[stackSize - 1] } private fun pushScope(newTop: Int) { if (stackSize == scopes.size) { throw JsonDataException("Nesting too deep at $path: circular reference?") } scopes[stackSize++] = newTop } /** * Replace the value on the top of the stack with the given value. */ private fun replaceTop(topOfStack: Int) { scopes[stackSize - 1] = topOfStack } companion object { private const val HEX_ARRAY = "0123456789abcdef" private fun Byte.hexString(): String { val value = toInt() return "${HEX_ARRAY[value.ushr(4)]}${HEX_ARRAY[value and 0x0F]}" } /** * From RFC 7159, "All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: * quotation mark, reverse solidus, and the control characters (U+0000 through U+001F)." * * We also escape '\u2028' and '\u2029', which JavaScript interprets as newline characters. This prevents eval() from failing with a * syntax error. http://code.google.com/p/google-gson/issues/detail?id=341 */ private val REPLACEMENT_CHARS: Array<String?> = arrayOfNulls<String?>(128).apply { for (i in 0..0x1f) { this[i] = "\\u00${i.toByte().hexString()}" } this['"'.code] = "\\\"" this['\\'.code] = "\\\\" this['\t'.code] = "\\t" this['\b'.code] = "\\b" this['\n'.code] = "\\n" this['\r'.code] = "\\r" } /** * Writes `value` as a string literal to `sink`. This wraps the value in double quotes and escapes those characters that require it. */ fun string(sink: BufferedSink, value: String) { val replacements = REPLACEMENT_CHARS sink.writeByte('"'.code) var last = 0 val length = value.length for (i in 0 until length) { val c = value[i] var replacement: String? if (c.code < 128) { replacement = replacements[c.code] if (replacement == null) { continue } } else if (c == '\u2028') { replacement = "\\u2028" } else if (c == '\u2029') { replacement = "\\u2029" } else { continue } if (last < i) { sink.writeUtf8(value, last, i) } sink.writeUtf8(replacement) last = i + 1 } if (last < length) { sink.writeUtf8(value, last, length) } sink.writeByte('"'.code) } } }
mit
5802e50210c8f1f4626b07a6774cf690
30.157895
149
0.65137
4.112698
false
false
false
false
ViolentOr/RWinquisition
src/test/kotlin/me/violentor/rwinquisition/model/ResultTest.kt
1
13505
package me.violentor.rwinquisition.model import io.kotlintest.matchers.* import io.kotlintest.properties.forAll import io.kotlintest.properties.headers import io.kotlintest.properties.row import io.kotlintest.properties.table import io.kotlintest.specs.StringSpec import me.violentor.rwinquisition.model.result.ConverterImpl import me.violentor.rwinquisition.model.result.Result import me.violentor.rwinquisition.model.result.Status class ResultModelTests: StringSpec(){ val resultJson = this::class.java.classLoader.getResource("mac.json").readText() val result: Result = ConverterImpl.fromJsonString(resultJson) val reverseResult: String = ConverterImpl.toJsonString(result) init { "Result version should be 2.0.32" { result.version shouldBe "2.0.32" } "Results should have statistics" { result.statistics!!.duration shouldBe 57.447338 } "Results should describe platform" { result.platform!!.name shouldBe "mac_os_x" result.platform!!.release shouldBe "17.4.0" } "Results should describe profile" { result.profiles!![0].name shouldBe "cis-appleosx10.11-level2" result.profiles!![0].version shouldBe "1.0.0" result.profiles!![0].sha256 shouldBe "f623bb37c6e7fba43c7d68be805a06824fb073bef361897c2e3a62c0e5bda4eb" result.profiles!![0].title shouldBe "CIS Apple OSX 10.11 Benchmark Level 2" result.profiles!![0].maintainer shouldBe "Chef Software, Inc." result.profiles!![0].summary shouldBe "CIS Apple OSX 10.11 Benchmark Level 2 translated from SCAP" result.profiles!![0].license shouldBe "Proprietary, All rights reserved" result.profiles!![0].copyright shouldBe "Chef Software, Inc." result.profiles!![0].copyrightEmail shouldBe "[email protected]" result.profiles!![0].supports?. should(beEmpty()) result.profiles!![0].attributes?. should(beEmpty()) } "Results should include specific controls"{ result.profiles!![0].groups!![0].controls?. should(containsAll( "xccdf_org.cisecurity.benchmarks_rule_1.1_Verify_all_Apple_provided_software_is_current", "xccdf_org.cisecurity.benchmarks_rule_1.2_Enable_Auto_Update", "xccdf_org.cisecurity.benchmarks_rule_1.3_Enable_app_update_installs", "xccdf_org.cisecurity.benchmarks_rule_1.4_Enable_system_data_files_and_security_update_installs", "xccdf_org.cisecurity.benchmarks_rule_1.5_Enable_OS_X_update_installs", "xccdf_org.cisecurity.benchmarks_rule_2.1.1_Turn_off_Bluetooth_if_no_paired_devices_exist", "xccdf_org.cisecurity.benchmarks_rule_2.1.2_Turn_off_Bluetooth_Discoverable_mode_when_not_pairing_devices", "xccdf_org.cisecurity.benchmarks_rule_2.1.3_Show_Bluetooth_status_in_menu_bar", "xccdf_org.cisecurity.benchmarks_rule_2.2.1_Enable_Set_time_and_date_automatically", "xccdf_org.cisecurity.benchmarks_rule_2.2.2_Ensure_time_set_is_within_appropriate_limits", "xccdf_org.cisecurity.benchmarks_rule_2.3.1_Set_an_inactivity_interval_of_20_minutes_or_less_for_the_screen_saver", "xccdf_org.cisecurity.benchmarks_rule_2.3.2_Secure_screen_saver_corners", "xccdf_org.cisecurity.benchmarks_rule_2.3.3_Verify_Display_Sleep_is_set_to_a_value_larger_than_the_Screen_Saver", "xccdf_org.cisecurity.benchmarks_rule_2.3.4_Set_a_screen_corner_to_Start_Screen_Saver", "xccdf_org.cisecurity.benchmarks_rule_2.4.1_Disable_Remote_Apple_Events", "xccdf_org.cisecurity.benchmarks_rule_2.4.2_Disable_Internet_Sharing", "xccdf_org.cisecurity.benchmarks_rule_2.4.3_Disable_Screen_Sharing", "xccdf_org.cisecurity.benchmarks_rule_2.4.4_Disable_Printer_Sharing", "xccdf_org.cisecurity.benchmarks_rule_2.4.5_Disable_Remote_Login", "xccdf_org.cisecurity.benchmarks_rule_2.4.6_Disable_DVD_or_CD_Sharing", "xccdf_org.cisecurity.benchmarks_rule_2.4.7_Disable_Bluetooth_Sharing", "xccdf_org.cisecurity.benchmarks_rule_2.4.8_Disable_File_Sharing", "xccdf_org.cisecurity.benchmarks_rule_2.4.9_Disable_Remote_Management", "xccdf_org.cisecurity.benchmarks_rule_2.5.1_Disable_Wake_for_network_access", "xccdf_org.cisecurity.benchmarks_rule_2.5.2_Disable_sleeping_the_computer_when_connected_to_power", "xccdf_org.cisecurity.benchmarks_rule_2.6.1_Enable_FileVault", "xccdf_org.cisecurity.benchmarks_rule_2.6.2_Enable_Gatekeeper", "xccdf_org.cisecurity.benchmarks_rule_2.6.3_Enable_Firewall", "xccdf_org.cisecurity.benchmarks_rule_2.6.4_Enable_Firewall_Stealth_Mode", "xccdf_org.cisecurity.benchmarks_rule_2.6.5_Review_Application_Firewall_Rules", "xccdf_org.cisecurity.benchmarks_rule_2.7.1_iCloud_configuration", "xccdf_org.cisecurity.benchmarks_rule_2.7.2_iCloud_keychain", "xccdf_org.cisecurity.benchmarks_rule_2.7.3_iCloud_Drive", "xccdf_org.cisecurity.benchmarks_rule_2.8_Pair_the_remote_control_infrared_receiver_if_enabled", "xccdf_org.cisecurity.benchmarks_rule_2.9_Enable_Secure_Keyboard_Entry_in_terminal.app", "xccdf_org.cisecurity.benchmarks_rule_2.10_Java_6_is_not_the_default_Java_runtime", "xccdf_org.cisecurity.benchmarks_rule_2.11_Securely_delete_files_as_needed", "xccdf_org.cisecurity.benchmarks_rule_3.1.1_Retain_system.log_for_90_or_more_days", "xccdf_org.cisecurity.benchmarks_rule_3.1.2_Retain_appfirewall.log_for_90_or_more_days", "xccdf_org.cisecurity.benchmarks_rule_3.1.3_Retain_authd.log_for_90_or_more_days", "xccdf_org.cisecurity.benchmarks_rule_3.2_Enable_security_auditing", "xccdf_org.cisecurity.benchmarks_rule_3.3_Configure_Security_Auditing_Flags", "xccdf_org.cisecurity.benchmarks_rule_3.4_Enable_remote_logging_for_Desktops_on_trusted_networks", "xccdf_org.cisecurity.benchmarks_rule_3.5_Retain_install.log_for_365_or_more_days", "xccdf_org.cisecurity.benchmarks_rule_4.1_Disable_Bonjour_advertising_service", "xccdf_org.cisecurity.benchmarks_rule_4.2_Enable_Show_Wi-Fi_status_in_menu_bar", "xccdf_org.cisecurity.benchmarks_rule_4.3_Create_network_specific_locations", "xccdf_org.cisecurity.benchmarks_rule_4.4_Ensure_http_server_is_not_running", "xccdf_org.cisecurity.benchmarks_rule_4.5_Ensure_ftp_server_is_not_running", "xccdf_org.cisecurity.benchmarks_rule_4.6_Ensure_nfs_server_is_not_running", "xccdf_org.cisecurity.benchmarks_rule_5.1.1_Secure_Home_Folders", "xccdf_org.cisecurity.benchmarks_rule_5.1.2_Check_System_Wide_Applications_for_appropriate_permissions", "xccdf_org.cisecurity.benchmarks_rule_5.1.3_Check_System_folder_for_world_writable_files", "xccdf_org.cisecurity.benchmarks_rule_5.1.4_Check_Library_folder_for_world_writable_files", "xccdf_org.cisecurity.benchmarks_rule_5.2.1_Configure_account_lockout_threshold", "xccdf_org.cisecurity.benchmarks_rule_5.2.2_Set_a_minimum_password_length", "xccdf_org.cisecurity.benchmarks_rule_5.2.3_Complex_passwords_must_contain_an_Alphabetic_Character", "xccdf_org.cisecurity.benchmarks_rule_5.2.4_Complex_passwords_must_contain_a_Numeric_Character", "xccdf_org.cisecurity.benchmarks_rule_5.2.5_Complex_passwords_must_contain_a_Special_Character", "xccdf_org.cisecurity.benchmarks_rule_5.2.6_Complex_passwords_must_uppercase_and_lowercase_letters", "xccdf_org.cisecurity.benchmarks_rule_5.2.7_Password_Age", "xccdf_org.cisecurity.benchmarks_rule_5.2.8_Password_History", "xccdf_org.cisecurity.benchmarks_rule_5.3_Reduce_the_sudo_timeout_period", "xccdf_org.cisecurity.benchmarks_rule_5.4_Automatically_lock_the_login_keychain_for_inactivity", "xccdf_org.cisecurity.benchmarks_rule_5.5_Ensure_login_keychain_is_locked_when_the_computer_sleeps", "xccdf_org.cisecurity.benchmarks_rule_5.6_Enable_OCSP_and_CRL_certificate_checking", "xccdf_org.cisecurity.benchmarks_rule_5.7_Do_not_enable_the_root_account", "xccdf_org.cisecurity.benchmarks_rule_5.8_Disable_automatic_login", "xccdf_org.cisecurity.benchmarks_rule_5.9_Require_a_password_to_wake_the_computer_from_sleep_or_screen_saver", "xccdf_org.cisecurity.benchmarks_rule_5.10_Require_an_administrator_password_to_access_system-wide_preferences", "xccdf_org.cisecurity.benchmarks_rule_5.11_Disable_ability_to_login_to_another_users_active_and_locked_session", "xccdf_org.cisecurity.benchmarks_rule_5.12_Create_a_custom_message_for_the_Login_Screen", "xccdf_org.cisecurity.benchmarks_rule_5.13_Create_a_Login_window_banner", "xccdf_org.cisecurity.benchmarks_rule_5.14_Do_not_enter_a_password-related_hint", "xccdf_org.cisecurity.benchmarks_rule_5.15_Disable_Fast_User_Switching", "xccdf_org.cisecurity.benchmarks_rule_5.16_Secure_individual_keychains_and_items", "xccdf_org.cisecurity.benchmarks_rule_5.17_Create_specialized_keychains_for_different_purposes", "xccdf_org.cisecurity.benchmarks_rule_5.18_System_Integrity_Protection_status", "xccdf_org.cisecurity.benchmarks_rule_5.19_Install_an_approved_tokend_for_smartcard_authentication_", "xccdf_org.cisecurity.benchmarks_rule_6.1.1_Display_login_window_as_name_and_password", "xccdf_org.cisecurity.benchmarks_rule_6.1.2_Disable_Show_password_hints", "xccdf_org.cisecurity.benchmarks_rule_6.1.3_Disable_guest_account_login", "xccdf_org.cisecurity.benchmarks_rule_6.1.4_Disable_Allow_guests_to_connect_to_shared_folders", "xccdf_org.cisecurity.benchmarks_rule_6.2_Turn_on_filename_extensions", "xccdf_org.cisecurity.benchmarks_rule_6.3_Disable_the_automatic_run_of_safe_files_in_Safari", "xccdf_org.cisecurity.benchmarks_rule_6.4_Use_parental_controls_for_systems_that_are_not_centrally_managed", "xccdf_org.cisecurity.benchmarks_rule_7.1_Wireless_technology_on_OS_X", "xccdf_org.cisecurity.benchmarks_rule_7.2_iSight_Camera_Privacy_and_Confidentiality_Concerns", "xccdf_org.cisecurity.benchmarks_rule_7.3_Computer_Name_Considerations", "xccdf_org.cisecurity.benchmarks_rule_7.4_Software_Inventory_Considerations", "xccdf_org.cisecurity.benchmarks_rule_7.5_Firewall_Consideration", "xccdf_org.cisecurity.benchmarks_rule_7.6_Automatic_Actions_for_Optical_Media", "xccdf_org.cisecurity.benchmarks_rule_7.7_App_Store_Automatically_download_apps_purchased_on_other_Macs_Considerations", "xccdf_org.cisecurity.benchmarks_rule_7.8_Extensible_Firmware_Interface_EFI_password", "xccdf_org.cisecurity.benchmarks_rule_7.9_Apple_ID_password_reset", "xccdf_org.cisecurity.benchmarks_rule_7.10_Repairing_permissions_is_no_longer_needed_with_10.11", "xccdf_org.cisecurity.benchmarks_rule_7.11_App_Store_Password_Settings", "xccdf_org.cisecurity.benchmarks_rule_8.1_Password_Policy_Plist_generated_through_OS_X_Server", "xccdf_org.cisecurity.benchmarks_rule_8.2_Password_Policy_Plist_from_man_page")) } "Tests can be FAILED or PASSED"{ val myTable = table( headers("i", "status", "success", "message"), row(0, Status.PASSED, true, ""), row(1, Status.FAILED, false, "expected \"\" to match /1/\nDiff:\n@@ -1,2 +1,2 @@\n-/1/\n+\"\"\n") ) forAll(myTable) { id:Int, status:Status, success:Boolean, message:String -> result.profiles!![0].controls!![id].results!![0].status shouldBe status result.profiles!![0].controls!![id].isSuccessfull() shouldBe success result.profiles!![0].controls!![id].results!![0].message shouldBe if(message == "") null else message } } "reverse convertion should go correctly too" { reverseResult.toLowerCase() should { startWith("{\"platform\":{\"name\":\"mac_os_x\"") include("\"start_time\":\"2018-03-08t18:55:50+03:00\"") endWith("\"statistics\":{\"duration\":57.447338},\"version\":\"2.0.32\"}") haveLength(219132) } } } }
apache-2.0
57781244c9d876a9929959ad4f21a550
77.069364
140
0.642577
3.486061
false
false
false
false
BartoszJarocki/Design-patterns-in-Kotlin
src/structural/Bridge.kt
1
665
package structural interface Switch { var appliance: Appliance fun turnOn() } interface Appliance { fun run() } class RemoteControl(override var appliance: Appliance) : Switch { override fun turnOn() = appliance.run() } class TV : Appliance { override fun run() = println("TV turned on") } class VacuumCleaner : Appliance { override fun run() = println("VacuumCleaner turned on") } fun main(args: Array<String>) { var tvRemoteControl = RemoteControl(appliance = TV()) tvRemoteControl.turnOn() var fancyVacuumCleanerRemoteControl = RemoteControl(appliance = VacuumCleaner()) fancyVacuumCleanerRemoteControl.turnOn() }
apache-2.0
6c248359080f2f3028b852914b4243e5
20.451613
84
0.714286
3.674033
false
false
false
false
googlemaps/android-places-demos
demo-kotlin/app/src/gms/java/com/example/placesdemo/programmatic_autocomplete/ProgrammaticAutocompleteToolbarActivity.kt
1
9717
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.placesdemo.programmatic_autocomplete import android.os.Bundle import android.os.Handler import android.util.Log import android.view.Menu import android.view.MenuItem import android.widget.ProgressBar import android.widget.SearchView import android.widget.ViewAnimator import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import com.example.placesdemo.BuildConfig import com.example.placesdemo.MainActivity import com.example.placesdemo.R import com.example.placesdemo.model.GeocodingResult import com.google.android.gms.common.api.ApiException import com.google.android.gms.maps.model.LatLng import com.google.android.libraries.places.api.Places import com.google.android.libraries.places.api.model.AutocompletePrediction import com.google.android.libraries.places.api.model.AutocompleteSessionToken import com.google.android.libraries.places.api.model.LocationBias import com.google.android.libraries.places.api.model.RectangularBounds import com.google.android.libraries.places.api.model.TypeFilter import com.google.android.libraries.places.api.net.FindAutocompletePredictionsRequest import com.google.android.libraries.places.api.net.PlacesClient import com.google.gson.GsonBuilder import org.json.JSONArray import org.json.JSONException /** * An Activity that demonstrates programmatic as-you-type place predictions. The parameters of the * request are currently hard coded in this Activity, to modify these parameters (e.g. location * bias, place types, etc.), see [ProgrammaticAutocompleteToolbarActivity.getPlacePredictions] * * @see https://developers.google.com/places/android-sdk/autocomplete#get_place_predictions_programmatically */ class ProgrammaticAutocompleteToolbarActivity : AppCompatActivity() { private val handler = Handler() private val adapter = PlacePredictionAdapter() private val gson = GsonBuilder().registerTypeAdapter(LatLng::class.java, LatLngAdapter()).create() private lateinit var queue: RequestQueue private lateinit var placesClient: PlacesClient private var sessionToken: AutocompleteSessionToken? = null private lateinit var viewAnimator: ViewAnimator private lateinit var progressBar: ProgressBar override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Use whatever theme was set from the MainActivity - some of these colors (e.g primary color) // will get picked up by the AutocompleteActivity. val theme = intent.getIntExtra(MainActivity.THEME_RES_ID_EXTRA, 0) if (theme != 0) { setTheme(theme) } setContentView(R.layout.activity_programmatic_autocomplete) setSupportActionBar(findViewById(R.id.toolbar)) // Initialize members progressBar = findViewById(R.id.progress_bar) viewAnimator = findViewById(R.id.view_animator) placesClient = Places.createClient(this) queue = Volley.newRequestQueue(this) initRecyclerView() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu, menu) val searchView = menu.findItem(R.id.search).actionView as SearchView initSearchView(searchView) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == R.id.search) { sessionToken = AutocompleteSessionToken.newInstance() return false } return super.onOptionsItemSelected(item) } private fun initSearchView(searchView: SearchView) { searchView.queryHint = getString(R.string.search_a_place) searchView.isIconifiedByDefault = false searchView.isFocusable = true searchView.isIconified = false searchView.requestFocusFromTouch() searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { return false } override fun onQueryTextChange(newText: String): Boolean { progressBar.isIndeterminate = true // Cancel any previous place prediction requests handler.removeCallbacksAndMessages(null) // Start a new place prediction request in 300 ms handler.postDelayed({ getPlacePredictions(newText) }, 300) return true } }) } private fun initRecyclerView() { val recyclerView = findViewById<RecyclerView>(R.id.recycler_view) val layoutManager = LinearLayoutManager(this) recyclerView.layoutManager = layoutManager recyclerView.adapter = adapter recyclerView.addItemDecoration(DividerItemDecoration(this, layoutManager.orientation)) adapter.onPlaceClickListener = { geocodePlaceAndDisplay(it) } } /** * This method demonstrates the programmatic approach to getting place predictions. The * parameters in this request are currently biased to Kolkata, India. * * @param query the plus code query string (e.g. "GCG2+3M K") */ private fun getPlacePredictions(query: String) { // The value of 'bias' biases prediction results to the rectangular region provided // (currently Kolkata). Modify these values to get results for another area. Make sure to // pass in the appropriate value/s for .setCountries() in the // FindAutocompletePredictionsRequest.Builder object as well. val bias: LocationBias = RectangularBounds.newInstance( LatLng(22.458744, 88.208162), // SW lat, lng LatLng(22.730671, 88.524896) // NE lat, lng ) // Create a new programmatic Place Autocomplete request in Places SDK for Android val newRequest = FindAutocompletePredictionsRequest .builder() .setSessionToken(sessionToken) .setLocationBias(bias) .setTypeFilter(TypeFilter.ESTABLISHMENT) .setQuery(query) .setCountries("IN") .build() // Perform autocomplete predictions request placesClient.findAutocompletePredictions(newRequest).addOnSuccessListener { response -> val predictions = response.autocompletePredictions adapter.setPredictions(predictions) progressBar.isIndeterminate = false viewAnimator.displayedChild = if (predictions.isEmpty()) 0 else 1 }.addOnFailureListener { exception: Exception? -> progressBar.isIndeterminate = false if (exception is ApiException) { Log.e(TAG, "Place not found: " + exception.statusCode) } } } /** * Performs a Geocoding API request and displays the result in a dialog. * * @see https://developers.google.com/places/android-sdk/autocomplete#get_place_predictions_programmatically */ private fun geocodePlaceAndDisplay(placePrediction: AutocompletePrediction) { // Construct the request URL val apiKey = BuildConfig.PLACES_API_KEY val requestURL = "https://maps.googleapis.com/maps/api/geocode/json?place_id=${placePrediction.placeId}&key=$apiKey" // Use the HTTP request URL for Geocoding API to get geographic coordinates for the place val request = JsonObjectRequest(Request.Method.GET, requestURL, null, { response -> try { // Inspect the value of "results" and make sure it's not empty val results: JSONArray = response.getJSONArray("results") if (results.length() == 0) { Log.w(TAG, "No results from geocoding request.") return@JsonObjectRequest } // Use Gson to convert the response JSON object to a POJO val result: GeocodingResult = gson.fromJson(results.getString(0), GeocodingResult::class.java) displayDialog(placePrediction, result) } catch (e: JSONException) { e.printStackTrace() } }, { error -> Log.e(TAG, "Request failed", error) }) // Add the request to the Request queue. queue.add(request) } private fun displayDialog(place: AutocompletePrediction, result: GeocodingResult): Unit { AlertDialog.Builder(this) .setTitle(place.getPrimaryText(null)) .setMessage("Geocoding result:\n" + result.geometry?.location) .setPositiveButton(android.R.string.ok, null) .show() } companion object { private val TAG = ProgrammaticAutocompleteToolbarActivity::class.java.simpleName } }
apache-2.0
4c3e7dfa7a863ccca6e751453f4c3693
41.432314
112
0.70001
4.851223
false
false
false
false
mrebollob/RestaurantBalance
app/src/main/java/com/mrebollob/m2p/utils/creditcard/CardNumberTextWatcher.kt
2
3346
/* * Copyright (c) 2017. Manuel Rebollo Báez * * 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.mrebollob.m2p.utils.creditcard import android.text.Editable import android.widget.EditText class CardNumberTextWatcher constructor(val numberEditText: EditText, actionListener: CardActionListener) : CreditCardTextWatcher(actionListener) { val MAX_LENGTH_CARD_NUMBER_WITH_SPACES = 19 val MAX_LENGTH_CARD_NUMBER = 16 val SPACE_SEPERATOR = " " override fun afterTextChanged(s: Editable?) { val cursorPosition = numberEditText.selectionEnd val previousLength = numberEditText.text.length val cardNumber = handleCardNumber(s.toString()) val modifiedLength = cardNumber.length numberEditText.removeTextChangedListener(this) numberEditText.setText(cardNumber) numberEditText.setSelection(if (cardNumber.length > MAX_LENGTH_CARD_NUMBER_WITH_SPACES) MAX_LENGTH_CARD_NUMBER_WITH_SPACES else cardNumber.length) numberEditText.addTextChangedListener(this) if (modifiedLength <= previousLength && cursorPosition < modifiedLength) { numberEditText.setSelection(cursorPosition) } if (cardNumber.replace(SPACE_SEPERATOR, "").length == MAX_LENGTH_CARD_NUMBER) { onComplete() } } fun handleCardNumber(inputCardNumber: String): String { return handleCardNumber(inputCardNumber, " ") } fun handleCardNumber(inputCardNumber: String, seperator: String): String { val formattingText = inputCardNumber.replace(seperator, "") var text: String if (formattingText.length >= 4) { text = formattingText.substring(0, 4) if (formattingText.length >= 8) { text = text + seperator + formattingText.substring(4, 8) } else if (formattingText.length > 4) { text = text + seperator + formattingText.substring(4) } if (formattingText.length >= 12) { text = text + seperator + formattingText.substring(8, 12) } else if (formattingText.length > 8) { text = text + seperator + formattingText.substring(8) } if (formattingText.length >= 16) { text = text + seperator + formattingText.substring(12) } else if (formattingText.length > 12) { text = text + seperator + formattingText.substring(12) } return text } else { text = formattingText.trim { it <= ' ' } return text } } override fun getIndex(): Int { return 0 } override fun focus() { numberEditText.requestFocus() numberEditText.selectAll() } }
apache-2.0
3d3e6131194cae40e642f97a6f0347db
34.221053
95
0.638565
4.59478
false
false
false
false
Skatteetaten/boober
src/main/kotlin/no/skatteetaten/aurora/boober/controller/security/User.kt
1
1112
package no.skatteetaten.aurora.boober.controller.security import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.userdetails.User as SpringSecurityUser class User( username: String, val token: String, val fullName: String? = null, grantedAuthorities: Collection<GrantedAuthority> = listOf() ) : SpringSecurityUser(username, token, true, true, true, true, grantedAuthorities.toList()) { fun hasRole(role: String): Boolean { return authorities.any { it.authority == role } } fun hasAccess(roles: Collection<String>): Boolean { return (this.username.startsWith("system:serviceaccount") && roles.contains(this.username)) || this.hasAnyRole(roles) } fun hasAnyRole(roles: Collection<String>?): Boolean { if (roles?.isEmpty() != false) return true return authorities.any { roles.contains(it.authority) } } val tokenSnippet: String get() = token.takeLast(Integer.min(token.length, 5)) val groupNames: List<String> get() = authorities.map { it.authority } }
apache-2.0
c3b73264c7e962fea0bbddcc9372290a
30.771429
102
0.693345
4.276923
false
false
false
false
nobuoka/vc-oauth-java
core/src/main/kotlin/info/vividcode/oauth/protocol/ParameterTransmission.kt
1
1024
package info.vividcode.oauth.protocol import info.vividcode.oauth.* object ParameterTransmission { /** * See : [OAuth 1.0 Specification - 3.5.1 Authorization Header](https://tools.ietf.org/html/rfc5849#section-3.5.1) */ fun getAuthorizationHeaderString(protocolParams: ProtocolParameterSet, realm: String): String = getAuthorizationHeaderString(protocolParams.map { Param(it.name.toString(), it.value.toString()) }, realm) /** * See : [OAuth 1.0 Specification - 3.5.1 Authorization Header](https://tools.ietf.org/html/rfc5849#section-3.5.1) */ fun getAuthorizationHeaderString(protocolParams: ParamList, realm: String): String { val sb = StringBuilder() sb.append("OAuth realm=\"").append(realm).append('"') val pp = protocolParams.stream() .map { p -> PercentEncode.encode(p.key) + "=\"" + PercentEncode.encode(p.value) + '"' } .reduce({ s1, s2 -> s1 + ", " + s2 }).orElse("") return "OAuth " + pp } }
apache-2.0
c721ec8302ff9fc076d3467df563b751
39.96
118
0.634766
3.737226
false
false
false
false
leafclick/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/table/Selection.kt
1
4131
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.vcs.log.ui.table import com.google.common.primitives.Ints import com.intellij.ui.ScrollingUtil import com.intellij.util.containers.ContainerUtil import com.intellij.vcs.log.graph.VisibleGraph import com.intellij.vcs.log.util.TroveUtil import gnu.trove.TIntHashSet import java.awt.Rectangle import javax.swing.JTable internal class Selection(private val table: VcsLogGraphTable) { private val selectedCommits: TIntHashSet = TIntHashSet() private val isOnTop: Boolean private val scrollingTarget: ScrollingTarget? init { val selectedRows = ContainerUtil.sorted(Ints.asList(*table.selectedRows)) val selectedRowsToCommits = selectedRows.associateWith { table.visibleGraph.getRowInfo(it).commit } TroveUtil.addAll(selectedCommits, selectedRowsToCommits.values) val visibleRows = getVisibleRows(table) if (visibleRows == null) { isOnTop = false scrollingTarget = null } else { isOnTop = visibleRows.first == 0 val visibleRow = selectedRowsToCommits.keys.find { visibleRows.contains(it) } ?: visibleRows.first val visibleCommit = selectedRowsToCommits[visibleRow] ?: table.visibleGraph.getRowInfo(visibleRow).commit scrollingTarget = ScrollingTarget(visibleCommit, getTopGap(visibleRow)) } } private fun getTopGap(row: Int) = table.getCellRect(row, 0, false).y - table.visibleRect.y private fun getVisibleRows(table: JTable): IntRange? { val visibleRows = ScrollingUtil.getVisibleRows(table) val range = IntRange(visibleRows.first, visibleRows.second) if (range.isEmpty() || range.first < 0) return null return range } fun restore(graph: VisibleGraph<Int>, scroll: Boolean, permanentGraphChanged: Boolean) { val scrollToTop = isOnTop && permanentGraphChanged val commitsToRows = mapCommitsToRows(graph, scroll && !scrollToTop) table.selectionModel.valueIsAdjusting = true for (commit in selectedCommits) { val row = commitsToRows[commit] if (row != null) { table.addRowSelectionInterval(row, row) } } table.selectionModel.valueIsAdjusting = false if (scroll) { if (scrollToTop) { scrollToRow(0, 0) } else if (scrollingTarget != null) { val scrollingTargetRow = commitsToRows[scrollingTarget.commit] if (scrollingTargetRow != null) { scrollToRow(scrollingTargetRow, scrollingTarget.topGap) } } } } private fun mapCommitsToRows(graph: VisibleGraph<Int>, scroll: Boolean): MutableMap<Int, Int> { val commits = mutableSetOf<Int>() TroveUtil.addAll(commits, selectedCommits) if (scroll && scrollingTarget != null) commits.add(scrollingTarget.commit) return mapCommitsToRows(commits, graph) } private fun mapCommitsToRows(commits: MutableCollection<Int>, graph: VisibleGraph<Int>): MutableMap<Int, Int> { val commitsToRows = mutableMapOf<Int, Int>() for (row in 0 until graph.visibleCommitCount) { val commit = graph.getRowInfo(row).commit if (commits.remove(commit)) { commitsToRows[commit] = row } if (commits.isEmpty()) break } return commitsToRows } private fun scrollToRow(row: Int?, delta: Int?) { val startRect = table.getCellRect(row!!, 0, true) table.scrollRectToVisible(Rectangle(startRect.x, Math.max(startRect.y - delta!!, 0), startRect.width, table.visibleRect.height)) } } private data class ScrollingTarget(val commit: Int, val topGap: Int)
apache-2.0
7c8416d21305209efd2710e5d4cbdb92
35.892857
113
0.715323
4.3807
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/caches/FileAttributeServiceImpl.kt
2
3125
// 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.caches import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileWithId import com.intellij.openapi.vfs.newvfs.FileAttribute import com.intellij.util.io.DataInputOutputUtil import java.io.DataInput import java.io.DataOutput import java.util.concurrent.ConcurrentHashMap class FileAttributeServiceImpl : FileAttributeService { val attributes: MutableMap<String, FileAttribute> = ConcurrentHashMap() override fun register(id: String, version: Int, fixedSize: Boolean) { attributes[id] = FileAttribute(id, version, fixedSize) } override fun <T : Enum<T>> writeEnumAttribute(id: String, file: VirtualFile, value: T): CachedAttributeData<T> = write(file, id, value) { output, v -> DataInputOutputUtil.writeINT(output, v.ordinal) } override fun <T : Enum<T>> readEnumAttribute(id: String, file: VirtualFile, klass: Class<T>): CachedAttributeData<T>? = read(file, id) { input -> deserializeEnumValue(DataInputOutputUtil.readINT(input), klass) } override fun writeBooleanAttribute(id: String, file: VirtualFile, value: Boolean): CachedAttributeData<Boolean> = write(file, id, value) { output, v -> DataInputOutputUtil.writeINT(output, if (v) 1 else 0) } override fun readBooleanAttribute(id: String, file: VirtualFile): CachedAttributeData<Boolean>? = read(file, id) { input -> DataInputOutputUtil.readINT(input) > 0 } override fun <T> write(file: VirtualFile, id: String, value: T, writeValueFun: (DataOutput, T) -> Unit): CachedAttributeData<T> { val attribute = attributes[id] ?: throw IllegalArgumentException("Attribute with $id wasn't registered") val data = CachedAttributeData(value, timeStamp = file.timeStamp) attribute.writeAttribute(file).use { DataInputOutputUtil.writeTIME(it, data.timeStamp) writeValueFun(it, value) } return data } override fun <T> read(file: VirtualFile, id: String, readValueFun: (DataInput) -> T): CachedAttributeData<T>? { val attribute = attributes[id] ?: throw IllegalArgumentException("Attribute with $id wasn't registered") if (file !is VirtualFileWithId) return null if (!file.isValid) return null val stream = attribute.readAttribute(file) ?: return null return stream.use { val timeStamp = DataInputOutputUtil.readTIME(it) val value = readValueFun(it) if (file.timeStamp == timeStamp) { CachedAttributeData(value, timeStamp) } else { null } } } private fun <T : Enum<T>> deserializeEnumValue(i: Int, klass: Class<T>): T { val method = klass.getMethod("values") @Suppress("UNCHECKED_CAST") val values = method.invoke(null) as Array<T> return values[i] } }
apache-2.0
275e5c276710c5981bcc5e61edc635a0
38.0625
158
0.67168
4.358438
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/State.kt
1
9307
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet", "ReplaceGetOrSet") package com.intellij.openapi.updateSettings.impl.pluginsAdvertisement import com.github.benmanes.caffeine.cache.Caffeine import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.ide.plugins.advertiser.PluginData import com.intellij.ide.plugins.advertiser.PluginFeatureCacheService import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.extensions.PluginDescriptor import com.intellij.openapi.fileTypes.FileNameMatcher import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.fileTypes.FileTypeFactory import com.intellij.openapi.fileTypes.PlainTextLikeFileType import com.intellij.openapi.fileTypes.ex.DetectedByContentFileType import com.intellij.openapi.fileTypes.ex.FakeFileType import com.intellij.openapi.project.Project import com.intellij.openapi.util.SimpleModificationTracker import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.Strings import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence import com.intellij.util.containers.mapSmartSet import kotlinx.serialization.Serializable import org.jetbrains.annotations.VisibleForTesting import java.util.* import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit data class PluginAdvertiserExtensionsData( // Either extension or file name. Depends on which of the two properties has more priority for advertising plugins for this specific file. val extensionOrFileName: String, val plugins: Set<PluginData> = emptySet(), ) @State(name = "PluginAdvertiserExtensions", storages = [Storage(StoragePathMacros.CACHE_FILE)]) @Service(Service.Level.APP) class PluginAdvertiserExtensionsStateService : SerializablePersistentStateComponent<PluginAdvertiserExtensionsStateService.State>( State() ) { private val tracker = SimpleModificationTracker() @Serializable data class State(val plugins: MutableMap<String, PluginData> = HashMap()) override fun getStateModificationCount() = tracker.modificationCount companion object { private val LOG = logger<PluginAdvertiserExtensionsStateService>() @JvmStatic val instance get() = service<PluginAdvertiserExtensionsStateService>() @JvmStatic fun getFullExtension(fileName: String): String? = Strings.toLowerCase( FileUtilRt.getExtension(fileName)).takeIf { it.isNotEmpty() }?.let { "*.$it" } @RequiresBackgroundThread @RequiresReadLockAbsence private fun requestCompatiblePlugins( extensionOrFileName: String, dataSet: Set<PluginData>, ): Set<PluginData> { if (dataSet.isEmpty()) { LOG.debug("No features for extension $extensionOrFileName") return emptySet() } val pluginIdsFromMarketplace = MarketplaceRequests .getLastCompatiblePluginUpdate(dataSet.mapSmartSet { it.pluginId }) .map { it.pluginId } .toSet() val plugins = dataSet .asSequence() .filter { it.isFromCustomRepository || it.isBundled || pluginIdsFromMarketplace.contains(it.pluginIdString) }.toSet() LOG.debug { if (plugins.isEmpty()) "No plugins for extension $extensionOrFileName" else "Found following plugins for '${extensionOrFileName}': ${plugins.joinToString { it.pluginIdString }}" } return plugins } @Suppress("HardCodedStringLiteral") private fun createUnknownExtensionFeature(extensionOrFileName: String) = UnknownFeature( FileTypeFactory.FILE_TYPE_FACTORY_EP.name, "File Type", extensionOrFileName, extensionOrFileName, ) private fun findEnabledPlugin(plugins: Set<String>): IdeaPluginDescriptor? { return if (plugins.isNotEmpty()) PluginManagerCore.getLoadedPlugins().find { it.isEnabled && plugins.contains(it.pluginId.idString) } else null } } private val cache = Caffeine .newBuilder() .expireAfterWrite(1, TimeUnit.HOURS) .build<String, PluginAdvertiserExtensionsData>() fun createExtensionDataProvider(project: Project) = ExtensionDataProvider(project) fun registerLocalPlugin(matcher: FileNameMatcher, descriptor: PluginDescriptor) { state.plugins.put(matcher.presentableString, PluginData(descriptor)) // no need to waste time to check that map is really changed - registerLocalPlugin is not called often after start-up, // so, mod count will be not incremented too often tracker.incModificationCount() } @RequiresBackgroundThread @RequiresReadLockAbsence fun updateCache(extensionOrFileName: String): Boolean { if (cache.getIfPresent(extensionOrFileName) != null) { return false } val knownExtensions = PluginFeatureCacheService.getInstance().extensions if (knownExtensions == null) { LOG.debug("No known extensions loaded") return false } val compatiblePlugins = requestCompatiblePlugins(extensionOrFileName, knownExtensions.get(extensionOrFileName)) updateCache(extensionOrFileName, compatiblePlugins) return true } @VisibleForTesting fun updateCache(extensionOrFileName: String, compatiblePlugins: Set<PluginData>) { cache.put(extensionOrFileName, PluginAdvertiserExtensionsData(extensionOrFileName, compatiblePlugins)) } inner class ExtensionDataProvider(private val project: Project) { private val unknownFeaturesCollector get() = UnknownFeaturesCollector.getInstance(project) private val enabledExtensionOrFileNames = Collections.newSetFromMap<String>(ConcurrentHashMap()) fun ignoreExtensionOrFileNameAndInvalidateCache(extensionOrFileName: String) { unknownFeaturesCollector.ignoreFeature(createUnknownExtensionFeature(extensionOrFileName)) cache.invalidate(extensionOrFileName) } fun addEnabledExtensionOrFileNameAndInvalidateCache(extensionOrFileName: String) { enabledExtensionOrFileNames.add(extensionOrFileName) cache.invalidate(extensionOrFileName) } private fun getByFilenameOrExt(fileNameOrExtension: String): PluginAdvertiserExtensionsData? { return state.plugins[fileNameOrExtension]?.let { PluginAdvertiserExtensionsData(fileNameOrExtension, setOf(it)) } } fun requestExtensionData(fileName: String, fileType: FileType): PluginAdvertiserExtensionsData? { val fullExtension = getFullExtension(fileName) if (fullExtension != null && isIgnored(fullExtension)) { LOG.debug("Extension '$fullExtension' is ignored in project '${project.name}'") return null } if (isIgnored(fileName)) { LOG.debug("File '$fileName' is ignored in project '${project.name}'") return null } if (fullExtension == null && fileType is FakeFileType) { return null } // Check if there's a plugin matching the exact file name getByFilenameOrExt(fileName)?.let { return it } val knownExtensions = PluginFeatureCacheService.getInstance().extensions if (knownExtensions == null) { LOG.debug("No known extensions loaded") return null } val plugin = findEnabledPlugin(knownExtensions.get(fileName).mapTo(HashSet()) { it.pluginIdString }) if (plugin != null) { // Plugin supporting the exact file name is installed and enabled, no advertiser is needed return null } val pluginsForExactFileName = cache.getIfPresent(fileName) if (pluginsForExactFileName != null && pluginsForExactFileName.plugins.isNotEmpty()) { return pluginsForExactFileName } if (knownExtensions.get(fileName).isNotEmpty()) { // there is a plugin that can support the exact file name, but we don't know a compatible version, // return null to force request to update cache return null } // Check if there's a plugin matching the extension fullExtension?.let { getByFilenameOrExt(it) }?.let { return it } if (fileType is PlainTextLikeFileType || fileType is DetectedByContentFileType) { return fullExtension?.let { cache.getIfPresent(it) } ?: if (fullExtension?.let { knownExtensions.get(it) }?.isNotEmpty() == true) { // there is a plugin that can support the file type, but we don't know a compatible version, // return null to force request to update cache null } else { PluginAdvertiserExtensionsData(fileName) } } return null } private fun isIgnored(extensionOrFileName: String): Boolean { return enabledExtensionOrFileNames.contains(extensionOrFileName) || unknownFeaturesCollector.isIgnored(createUnknownExtensionFeature(extensionOrFileName)) } } }
apache-2.0
7eabc2528e7f461537fa98c52ee150c9
37.300412
140
0.733212
5.150526
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/models/EnvironmentalCommitment.kt
1
1337
package com.kickstarter.models import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * EnvironmentalCommitments Data Structure * * Note: This data model is written in kotlin and using kotlin * parcelize because it's meant to be used only with GraphQL * networking client. */ @Parcelize class EnvironmentalCommitment private constructor( val id: Long, val description: String, val category: String ) : Parcelable { @Parcelize data class Builder( var id: Long = -1, var description: String = "", var category: String = "" ) : Parcelable { fun id(id: Long) = apply { this.id = id } fun description(description: String) = apply { this.description = description } fun category(category: String) = apply { this.category = category } fun build() = EnvironmentalCommitment(id = id, description = description, category = category) } companion object { fun builder() = Builder() } fun toBuilder() = Builder(id = this.id, description = this.description, category = category) override fun equals(other: Any?): Boolean = if (other is EnvironmentalCommitment) { other.id == this.id && other.description == this.description && other.category == this.category } else false }
apache-2.0
631e48854bed756c915639aa13a09451
30.093023
102
0.655198
4.398026
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowDragHelper.kt
1
15656
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl import com.intellij.openapi.Disposable import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowAnchor.* import com.intellij.openapi.wm.ToolWindowType import com.intellij.ui.ComponentUtil import com.intellij.ui.MouseDragHelper import com.intellij.ui.ScreenUtil import com.intellij.ui.awt.RelativePoint import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.ui.paint.RectanglePainter import com.intellij.util.IconUtil import com.intellij.util.ui.ImageUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.NotNull import org.jetbrains.annotations.Nullable import java.awt.* import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.awt.image.BufferedImage import java.lang.ref.WeakReference import javax.swing.JComponent import javax.swing.JDialog import javax.swing.JLabel import javax.swing.SwingUtilities internal class ToolWindowDragHelper(parent: @NotNull Disposable, val pane: @NotNull ToolWindowsPane) : MouseDragHelper<ToolWindowsPane>(parent, pane) { private var toolWindowRef = null as WeakReference<ToolWindowImpl?>? private var myInitialAnchor = null as ToolWindowAnchor? private var myInitialButton = null as StripeButton? private var myInitialSize = Dimension() private var myLastStripe = null as Stripe? private var myDialog = null as MyDialog? private val myHighlighter = createHighlighterComponent() private val myInitialOffset = Point() private var mySourceIsHeader = false companion object { const val THUMB_SIZE = 220 const val THUMB_OPACITY = .85f @Nullable fun createDragImage(component: JComponent, thumbSize: Int = JBUI.scale(THUMB_SIZE)): BufferedImage { val image = UIUtil.createImage(component, component.width, component.height, BufferedImage.TYPE_INT_RGB) val graphics = image.graphics graphics.color = UIUtil.getBgFillColor(component) RectanglePainter.FILL.paint(graphics as @NotNull Graphics2D, 0, 0, component.width, component.height, null) component.paint(graphics) graphics.dispose() val width: Double = image.getWidth(null).toDouble() val height: Double = image.getHeight(null).toDouble() if (thumbSize == -1 || width <= thumbSize && height <= thumbSize) return image val ratio: Double = if (width > height) { thumbSize / width } else { thumbSize / height } return ImageUtil.scaleImage(image, (width * ratio).toInt(), (height * ratio).toInt()) as BufferedImage } fun createHighlighterComponent() = object: NonOpaquePanel() { override fun paint(g: Graphics) { g.color = JBUI.CurrentTheme.DragAndDrop.Area.BACKGROUND g.fillRect(0, 0, width, height) } } } override fun isDragOut(event: MouseEvent, dragToScreenPoint: Point, startScreenPoint: Point): Boolean { return isDragOut(dragToScreenPoint) } private fun isDragOut(dragToScreenPoint: Point): Boolean { val toolWindow = getToolWindow() if (toolWindow != null && toolWindow.getBoundsOnScreen(toolWindow.anchor, dragToScreenPoint).contains(dragToScreenPoint)) { return false } return myLastStripe == null } override fun canStartDragging(dragComponent: JComponent, dragComponentPoint: Point): Boolean { return getToolWindow(RelativePoint(dragComponent, dragComponentPoint)) != null } fun getToolWindow(startScreenPoint: RelativePoint): ToolWindowImpl? { val decorators = ArrayList(ComponentUtil.findComponentsOfType(pane, InternalDecoratorImpl::class.java)) for (decorator in decorators) { val bounds = decorator.headerScreenBounds if (bounds != null && bounds.contains(startScreenPoint.screenPoint)) { val point = startScreenPoint.getPoint(decorator) val child = SwingUtilities.getDeepestComponentAt(decorator, point.x, point.y) if (isComponentDraggable(child) && ComponentUtil.findParentByCondition(child) { t -> t is ToolWindowHeader } != null) { if (decorator.toolWindow.anchor != BOTTOM || decorator.locationOnScreen.y <= startScreenPoint.screenPoint.y - ToolWindowsPane.getHeaderResizeArea()) return decorator.toolWindow } } } val point = startScreenPoint.getPoint(pane) val component = SwingUtilities.getDeepestComponentAt(pane, point.x, point.y) if (component is StripeButton) { return component.toolWindow } return null } override fun processMousePressed(event: MouseEvent) { val relativePoint = RelativePoint(event) val toolWindow = getToolWindow(relativePoint) if (toolWindow == null) { return } val decorator = if (toolWindow.isVisible) toolWindow.decorator else null toolWindowRef = WeakReference(toolWindow) myInitialAnchor = toolWindow.anchor myLastStripe = pane.getStripeFor(toolWindow.anchor) myInitialButton = pane.getStripeFor(toolWindow.anchor).getButtonFor(toolWindow.id) myInitialSize = toolWindow.getBoundsOnScreen(toolWindow.anchor, relativePoint.screenPoint).size val dragOutImage = if (decorator != null && !decorator.bounds.isEmpty) createDragImage(decorator) else null val dragImage = if (myInitialButton != null) myInitialButton!!.createDragImage() else dragOutImage val point = relativePoint.getPoint(pane) val component = SwingUtilities.getDeepestComponentAt(pane, point.x, point.y) mySourceIsHeader = true if (component is StripeButton) { myInitialOffset.location = relativePoint.getPoint(component) mySourceIsHeader = false } else if (dragImage != null) { myInitialOffset.location = Point(dragImage.getWidth(pane) / 4, dragImage.getHeight(pane) / 4) } if (dragImage != null) { myDialog = MyDialog(pane, this, dragImage, dragOutImage) } } override fun mouseReleased(e: MouseEvent?) { if (getToolWindow() == null) return super.mouseReleased(e) stopDrag() } override fun processDragOut(event: MouseEvent, dragToScreenPoint: Point, startScreenPoint: Point, justStarted: Boolean) { if (getToolWindow() == null) return relocate(event) event.consume() } override fun processDragFinish(event: MouseEvent, willDragOutStart: Boolean) { if (getToolWindow() == null) return if (willDragOutStart) { setDragOut(true) return } val screenPoint = event.locationOnScreen val window = getToolWindow() if (window == null || !willDragOutStart && pane.getStripeFor(screenPoint, pane.getStripeFor(myInitialAnchor!!)) == null && window.getBoundsOnScreen(myInitialAnchor!!, screenPoint).contains(screenPoint)) { cancelDragging() return } val stripe = myLastStripe if (stripe != null) { stripe.finishDrop(window.toolWindowManager) } else { window.toolWindowManager.setToolWindowType(window.id, ToolWindowType.FLOATING) window.toolWindowManager.activateToolWindow(window.id, Runnable { val w = UIUtil.getWindow(window.component) if (w is JDialog) { val locationOnScreen = event.locationOnScreen if (mySourceIsHeader) { val decorator = ComponentUtil.getParentOfType(InternalDecoratorImpl::class.java, window.component) if (decorator != null) { val shift = SwingUtilities.convertPoint(decorator, decorator.location, w) locationOnScreen.translate(-shift.x, -shift.y) } locationOnScreen.translate(-myInitialOffset.x, -myInitialOffset.y) } w.location = locationOnScreen val bounds = w.bounds bounds.size = myInitialSize ScreenUtil.fitToScreen(bounds) w.bounds = bounds } }, true, null) } } private fun getToolWindow(): ToolWindowImpl? { return toolWindowRef?.get() } override fun processDragOutFinish(event: MouseEvent) { processDragFinish(event, false) } override fun cancelDragging(): Boolean { if (super.cancelDragging()) { stopDrag() return true } return false } override fun stop() { super.stop() stopDrag() } private fun stopDrag() { val window = getToolWindow() getStripeButton(window)?.isVisible = true pane.stopDrag() with(pane.rootPane.glassPane as JComponent) { remove(myHighlighter) revalidate() repaint() } @Suppress("SSBasedInspection") myDialog?.dispose() myDialog = null toolWindowRef = null myInitialAnchor = null if (myLastStripe != null) { myLastStripe!!.resetDrop() myLastStripe = null } myInitialButton = null } override fun processDrag(event: MouseEvent, dragToScreenPoint: Point, startScreenPoint: Point) { if (!checkModifiers(event)) return; if (isDragJustStarted) { startDrag(event) } else { relocate(event) } } override fun getDragStartDeadzone(pressedScreenPoint: Point , draggedScreenPoint: Point): Int { val point = RelativePoint(pressedScreenPoint).getPoint(pane) if (SwingUtilities.getDeepestComponentAt(pane, point.x, point.y) is StripeButton) { return super.getDragStartDeadzone(pressedScreenPoint, draggedScreenPoint) } return JBUI.scale(Registry.intValue("ide.new.tool.window.start.drag.deadzone", 7, 0, 100)) } private fun startDrag(event: MouseEvent) { relocate(event) if (myInitialButton != null) { myInitialButton!!.isVisible = false } myDialog?.isVisible = true with(pane.rootPane.glassPane as JComponent) { add(myHighlighter) revalidate() repaint() } pane.startDrag() } private fun ToolWindowImpl.getBoundsOnScreen(anchor: ToolWindowAnchor, screenPoint : Point): Rectangle { val trueStripe = pane.getStripeFor(screenPoint, pane.getStripeFor(myInitialAnchor!!)) val location = pane.locationOnScreen location.x += getStripeWidth(LEFT) location.y += getStripeHeight(TOP) var width = pane.width - getStripeWidth(LEFT) - getStripeWidth(RIGHT) var height = pane.height - getStripeHeight(TOP) - getStripeHeight(BOTTOM) if (anchor === myInitialAnchor && trueStripe == null && isVisible) { if (anchor.isHorizontal) height = (pane.rootPane.height * windowInfo.weight).toInt() else width = (pane.rootPane.width * windowInfo.weight).toInt() } else { if (anchor.isHorizontal) height = Stripe.DROP_DISTANCE_SENSITIVITY else width = Stripe.DROP_DISTANCE_SENSITIVITY } when (anchor) { BOTTOM -> { location.y = pane.locationOnScreen.y + pane.height - height - getStripeHeight(BOTTOM) } RIGHT -> { location.x = pane.locationOnScreen.x + pane.width - width - getStripeWidth(RIGHT) } } return Rectangle(location.x, location.y, width, height) } private fun getStripeWidth(anchor: ToolWindowAnchor): Int { with(pane.getStripeFor(anchor)) { return if (isVisible && isShowing) width else 0 } } private fun getStripeHeight(anchor: ToolWindowAnchor): Int { with(pane.getStripeFor(anchor)) { return if (isVisible && isShowing) height else 0 } } private fun getStripeButton(window: ToolWindowImpl?): StripeButton? { if (window == null) return null return pane.getStripeFor(window.anchor).getButtonFor(window.id) } private fun relocate(event: MouseEvent) { val screenPoint = event.locationOnScreen val dialog = myDialog val toolWindow = getToolWindow() if (dialog == null || toolWindow == null) return val dragOut = isDragOut(screenPoint) dialog.setLocation(screenPoint.x - myInitialOffset.x, screenPoint.y - myInitialOffset.y) setDragOut(dragOut) val stripe = getStripe(screenPoint) if (myLastStripe != null && myLastStripe != stripe) { myLastStripe!!.resetDrop() } myHighlighter.isVisible = stripe != null if (stripe != null && myInitialButton != null) { //if (myLastStripe != stripe) {//attempt to rotate thumb image on fly to show actual button view if user drops it right here // val button = object : StripeButton(pane, toolWindow) { // override fun getAnchor(): ToolWindowAnchor { // return stripe.anchor // } // } // val info = (toolWindow.windowInfo as WindowInfoImpl).copy() // //info.anchor = stripe.anchor // button.apply(info) // button.updatePresentation() // button.size = button.preferredSize // stripe.add(button) // val image = button.createDragImage(event) // dialog.updateIcon(image) // stripe.remove(button) //} stripe.processDropButton(myInitialButton as StripeButton, dialog.contentPane as @NotNull JComponent, screenPoint) SwingUtilities.invokeLater(Runnable { val bounds = toolWindow.getBoundsOnScreen(stripe.anchor, screenPoint) val p = bounds.location SwingUtilities.convertPointFromScreen(p, pane.rootPane.layeredPane) bounds.location = p val dropToSide = stripe.dropToSide if (dropToSide != null) { val half = if (stripe.anchor.isHorizontal) bounds.width / 2 else bounds.height / 2 if (!stripe.anchor.isHorizontal) { bounds.height -= half if (dropToSide) { bounds.y += half } } else { bounds.width -= half if (dropToSide) { bounds.x += half } } } myHighlighter.bounds = bounds }) } myLastStripe = stripe } private fun getStripe(screenPoint: Point): Stripe? { var stripe = pane.getStripeFor(screenPoint, pane.getStripeFor(myInitialAnchor!!)) if (stripe == null && getToolWindow()!!.getBoundsOnScreen(myInitialAnchor!!, screenPoint).contains(screenPoint)) { stripe = pane.getStripeFor(myInitialAnchor!!) } if (stripe?.anchor == TOP) return null return stripe } private fun setDragOut(dragOut: Boolean) { myDialog?.setDragOut(dragOut) myHighlighter.isVisible = !dragOut } class MyDialog(owner: JComponent, val helper: ToolWindowDragHelper, val stripeButtonImage: BufferedImage, val toolWindowThumbnailImage: BufferedImage?) : JDialog( UIUtil.getWindow(owner), null, ModalityType.MODELESS) { var myDragOut = null as Boolean? init { isUndecorated = true try { opacity = THUMB_OPACITY } catch (ignored: Exception) { } isAlwaysOnTop = true contentPane = JLabel() contentPane.addMouseListener(object : MouseAdapter() { override fun mouseReleased(e: MouseEvent?) { helper.mouseReleased(e) //stop drag } override fun mouseDragged(e: MouseEvent?) { helper.relocate(e!!) } }) setDragOut(false) } fun setDragOut(dragOut: Boolean) { if (dragOut == myDragOut) return myDragOut = dragOut val image = if (dragOut && toolWindowThumbnailImage != null) toolWindowThumbnailImage else stripeButtonImage updateIcon(image) } fun updateIcon(image: BufferedImage) { with(contentPane as JLabel) { icon = IconUtil.createImageIcon(image as Image) revalidate() pack() repaint() } } } }
apache-2.0
ccf9c7f63bba5e8ab03db154a09cec61
35.159353
158
0.685041
4.391585
false
false
false
false
Zeroami/CommonLib-Kotlin
commonlib/src/main/java/com/zeroami/commonlib/mvp/LBaseMvpActivity.kt
1
2149
package com.zeroami.commonlib.mvp import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import com.zeroami.commonlib.R import com.zeroami.commonlib.base.LBaseActivity import com.zeroami.commonlib.utils.LT import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty /** * BaseMvpActivity,实现MvpView,完成View的通用操作 * * @author Zeroami */ abstract class LBaseMvpActivity<out P : LMvpPresenter<*>> : LBaseActivity(), LMvpView { /** * 获取MvpPresenter */ protected val mvpPresenter: P by object : ReadOnlyProperty<Any?, P> { override fun getValue(thisRef: Any?, property: KProperty<*>): P { return presenter ?: throw NullPointerException() } } private var presenter: P? = null /** * 获取SwipeRefreshLayout */ protected var swipeRefreshLayout: SwipeRefreshLayout? = null private set override fun onCreate(savedInstanceState: Bundle?) { presenter = createPresenter() super.onCreate(savedInstanceState) } override fun onDestroy() { presenter?.detachView() super.onDestroy() } override fun onViewCreated() { super.onViewCreated() swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout) as SwipeRefreshLayout? } /** * 创建Presenter */ protected abstract fun createPresenter(): P? override fun showLoading() { swipeRefreshLayout?.post { swipeRefreshLayout?.isRefreshing = true } } override fun hideLoading() { swipeRefreshLayout?.post { swipeRefreshLayout?.isRefreshing = false } } override fun showMessage(text: CharSequence) { LT.show(text) } override fun showError(text: CharSequence) { LT.show(text) } override fun finishCurrent() { finish() } override fun handleExtras(extras: Bundle) { super.handleExtras(extras) presenter?.handleExtras(extras) } override fun onInitialized() { super.onInitialized() presenter?.doViewInitialized() presenter?.subscribeEvent() } }
apache-2.0
74328304b4a13a89342a7e714f153e4c
23.593023
89
0.664303
4.873272
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/util/testProject.kt
4
1797
// 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.performance.tests.utils.project.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
e356190aa90fec8b98143d63eb1d2973
43.925
158
0.715637
4.728947
false
false
false
false
androidx/androidx
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/decoys/RecordDecoySignaturesTransformer.kt
3
3864
/* * 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.compose.compiler.plugins.kotlin.lower.decoys import androidx.compose.compiler.plugins.kotlin.ModuleMetrics import androidx.compose.compiler.plugins.kotlin.lower.ModuleLoweringPass import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.backend.common.serialization.signature.IdSignatureSerializer import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.declarations.IrDeclaration import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.util.DeepCopySymbolRemapper import org.jetbrains.kotlin.ir.util.IdSignature import org.jetbrains.kotlin.ir.util.KotlinMangler import org.jetbrains.kotlin.ir.util.dump import org.jetbrains.kotlin.ir.util.getAnnotation /** * Record signatures of the functions created by the [CreateDecoysTransformer] to match them from * other compilation units. This step should be applied after other transforms are finished to * ensure that signature are matching serialized functions. */ class RecordDecoySignaturesTransformer( pluginContext: IrPluginContext, symbolRemapper: DeepCopySymbolRemapper, override val signatureBuilder: IdSignatureSerializer, metrics: ModuleMetrics, val mangler: KotlinMangler.IrMangler ) : AbstractDecoysLowering( pluginContext = pluginContext, symbolRemapper = symbolRemapper, metrics = metrics, signatureBuilder = signatureBuilder ), ModuleLoweringPass { override fun lower(module: IrModuleFragment) { module.transformChildrenVoid() } override fun visitFunction(declaration: IrFunction): IrStatement { if (!declaration.isDecoy() || !declaration.canBeLinkedAgainst()) { return super.visitFunction(declaration) } val decoyAnnotation = declaration.getAnnotation(DecoyFqNames.Decoy)!! val decoyFunction = symbolRemapper.getReferencedFunction(declaration.getComposableForDecoy()) val sig: IdSignature = signatureBuilder.computeSignature(decoyFunction.owner) val commonSignature: IdSignature.CommonSignature? = findNearestCommonSignature(sig) if (commonSignature != null) { decoyAnnotation.putValueArgument( 1, irVarargString( listOf( commonSignature.packageFqName, commonSignature.declarationFqName, commonSignature.id.toString(), commonSignature.mask.toString() ) ) ) } else { error("${declaration.dump()} produced unsupported signature $sig") } return super.visitFunction(declaration) } private fun findNearestCommonSignature( sig: IdSignature ): IdSignature.CommonSignature? { return when (sig) { is IdSignature.CommonSignature -> sig is IdSignature.CompositeSignature -> findNearestCommonSignature(sig.inner) else -> null } } private fun IrDeclaration.canBeLinkedAgainst(): Boolean = mangler.run { [email protected](false) } }
apache-2.0
3cd726bc94428b07469d4e281ea08bfe
38.030303
97
0.717391
4.903553
false
false
false
false
stoyicker/dinger
data/src/main/kotlin/data/tinder/recommendation/GetRecommendationFacadeModule.kt
1
4059
package data.tinder.recommendation import dagger.Module import dagger.Provides import javax.inject.Singleton import dagger.Lazy as DaggerLazy @Module(includes = [RecommendationSourceModule::class, RecommendationEventTrackerModule::class]) internal class GetRecommendationFacadeModule { @Provides @Singleton fun requestObjectMapper() = RecommendationRequestObjectMapper() @Provides @Singleton fun commonFriendPhotoObjectMapper() = RecommendationUserCommonFriendPhotoObjectMapper() @Provides @Singleton fun commonFriendObjectMapper( photoDelegate: RecommendationUserCommonFriendPhotoObjectMapper) = RecommendationUserCommonFriendObjectMapper(photoDelegate) @Provides @Singleton fun instagramPhotoObjectMapper() = RecommendationInstagramPhotoObjectMapper() @Provides @Singleton fun instagramObjectMapper(instagramPhotoDelegate: RecommendationInstagramPhotoObjectMapper) = RecommendationInstagramObjectMapper(instagramPhotoDelegate) @Provides @Singleton fun teaserObjectMapper() = RecommendationTeaserObjectMapper() @Provides @Singleton fun processedFileObjectMapper() = RecommendationProcessedFileObjectMapper() @Provides @Singleton fun spotifyAlbumObjectMapper(processedFileDelegate: RecommendationProcessedFileObjectMapper) = RecommendationSpotifyThemeTrackAlbumObjectMapper(processedFileDelegate) @Provides @Singleton fun spotifyArtistObjectMapper() = RecommendationSpotifyThemeTrackArtistObjectMapper() @Provides @Singleton fun spotifyThemeTrackObjectMapper( albumDelegate: RecommendationSpotifyThemeTrackAlbumObjectMapper, artistDelegate: RecommendationSpotifyThemeTrackArtistObjectMapper) = RecommendationSpotifyThemeTrackObjectMapper( albumDelegate = albumDelegate, artistDelegate = artistDelegate) @Provides @Singleton fun likeObjectMapper() = RecommendationLikeObjectMapper() @Provides @Singleton fun photoObjectMapper( processedFileDelegate: RecommendationProcessedFileObjectMapper) = RecommendationPhotoObjectMapper(processedFileDelegate) @Provides @Singleton fun jobCompanyObjectMapper() = RecommendationJobCompanyObjectMapper() @Provides @Singleton fun jobTitleObjectMapper() = RecommendationJobTitleObjectMapper() @Provides @Singleton fun jobObjectMapper( companyDelegate: RecommendationJobCompanyObjectMapper, titleDelegate: RecommendationJobTitleObjectMapper) = RecommendationJobObjectMapper( companyDelegate = companyDelegate, titleDelegate = titleDelegate) @Provides @Singleton fun schoolObjectMapper() = RecommendationSchoolObjectMapper() @Provides @Singleton fun responseObjectMapper( eventTracker: RecommendationEventTracker, commonFriendDelegate: RecommendationUserCommonFriendObjectMapper, instagramDelegate: RecommendationInstagramObjectMapper, teaserDelegate: RecommendationTeaserObjectMapper, spotifyThemeTrackDelegate: RecommendationSpotifyThemeTrackObjectMapper, commonLikeDelegate: RecommendationLikeObjectMapper, photoDelegate: RecommendationPhotoObjectMapper, jobDelegate: RecommendationJobObjectMapper, schoolDelegate: RecommendationSchoolObjectMapper) = RecommendationResponseObjectMapper( eventTracker = eventTracker, commonFriendDelegate = commonFriendDelegate, instagramDelegate = instagramDelegate, teaserDelegate = teaserDelegate, spotifyThemeTrackDelegate = spotifyThemeTrackDelegate, commonLikeDelegate = commonLikeDelegate, photoDelegate = photoDelegate, jobDelegate = jobDelegate, schoolDelegate = schoolDelegate) @Provides @Singleton fun facade( getRecommendationSource: GetRecommendationSource, requestObjectMapper: RecommendationRequestObjectMapper, responseObjectMapper: RecommendationResponseObjectMapper) = GetRecommendationFacade(getRecommendationSource, requestObjectMapper, responseObjectMapper) }
mit
6ba5924f4d4c321da22b502ac4a57726
32.825
97
0.796994
5.782051
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/customize/transferSettings/providers/vswin/utilities/Version2.kt
2
1847
package com.intellij.ide.customize.transferSettings.providers.vswin.utilities // If minorVersion is set to -1, it means any minor version is supported and we don't care about minor version. class Version2(var major: Int, var minor: Int = -1) { companion object { fun parse(s: String): Version2 { if (s.isEmpty()) { throw IllegalArgumentException("The version string can't be empty") } val parts = s.split('.') when { parts.size > 2 -> throw IllegalArgumentException("Too many dot-separated parts") parts.isEmpty() -> throw IllegalArgumentException("Too few dot-separated parts") } if (parts[0].toIntOrNull() == null || parts[1].toIntOrNull() == null) { throw IllegalArgumentException("Can't parse to int") } return Version2(parts[0].toInt(), parts[1].toInt()) } } override operator fun equals(other: Any?): Boolean { if (other !is Version2) { return false } if (minor == -1 || other.minor == -1) { return major == other.major } return major == other.major && minor == other.minor } operator fun compareTo(other: Version2): Int { // todo: Current approach is terrible if (minor == -1 || other.minor == -1) { return major.compareTo(other.major) } return (major*1000+minor).compareTo(other.major*1000+other.minor) } override fun hashCode(): Int { return if (minor != -1) { 31 * major + minor } else { 31 * major } } override fun toString(): String { if (minor == -1) { return major.toString() } return "$major.$minor" } }
apache-2.0
08e6e27e320800dc2ddfbc886f635b68
28.333333
111
0.541419
4.48301
false
false
false
false
GunoH/intellij-community
java/java-tests/testSrc/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageOrderTest.kt
4
2506
// 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.codeInsight.daemon.impl.quickfix import com.intellij.codeInsight.daemon.QuickFixBundle.message import com.intellij.codeInspection.CommonQuickFixBundle import com.intellij.psi.codeStyle.JavaCodeStyleSettings import com.intellij.psi.util.JavaElementKind import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase class CreateFromUsageOrderTest : LightJavaCodeInsightFixtureTestCase() { fun `test local variable first with default settings`() { myFixture.configureByText("_.java", "class A { void usage() { foo(<caret>lllbar); } }") val action = myFixture.availableIntentions.first() assertEquals(CreateLocalFromUsageFix.getMessage("lllbar"), action.text) } fun `test constant first when uppercase`() { myFixture.configureByText("_.java", "class A { void usage() { foo(<caret>CCCC); } }") val action = myFixture.availableIntentions.first() assertEquals(message("create.element.in.class", JavaElementKind.CONSTANT.`object`(), "CCCC", "A"), action.text) } fun `test local variable first by prefix`() { testWithSettings { settings -> settings.LOCAL_VARIABLE_NAME_PREFIX = "lll" myFixture.configureByText("_.java", "class A { void usage() { foo(<caret>lllbar); } }") val action = myFixture.availableIntentions.first() assertEquals(CreateLocalFromUsageFix.getMessage("lllbar"), action.text) } } fun `test parameter first by prefix`() { testWithSettings { settings -> settings.PARAMETER_NAME_PREFIX = "ppp" myFixture.configureByText("_.java", "class A { void usage() { foo(<caret>pppbar); } }") val action = myFixture.availableIntentions.first() assertEquals(CommonQuickFixBundle.message("fix.create.title.x", JavaElementKind.PARAMETER.`object`(), "pppbar"), action.text) } } fun `test create field first by prefix`() { testWithSettings { settings -> settings.FIELD_NAME_PREFIX = "fff" myFixture.configureByText("_.java", "class A { void usage() { foo(<caret>fffbar); } }") val action = myFixture.availableIntentions.first() assertEquals(message("create.element.in.class", JavaElementKind.FIELD.`object`(), "fffbar", "A"), action.text) } } private fun testWithSettings(theTest: (JavaCodeStyleSettings) -> Unit) { val settings = JavaCodeStyleSettings.getInstance(project) theTest(settings) } }
apache-2.0
c93288cbd7c4e42abb44459a1a96b4ea
44.563636
131
0.721069
4.283761
false
true
false
false