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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/AppBar.kt | 3 | 73900 | /*
* 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.material3
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.AnimationState
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.DecayAnimationSpec
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateDecay
import androidx.compose.animation.core.animateTo
import androidx.compose.animation.core.spring
import androidx.compose.animation.rememberSplineBasedDecay
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material3.tokens.BottomAppBarTokens
import androidx.compose.material3.tokens.FabSecondaryTokens
import androidx.compose.material3.tokens.TopAppBarLargeTokens
import androidx.compose.material3.tokens.TopAppBarMediumTokens
import androidx.compose.material3.tokens.TopAppBarSmallCenteredTokens
import androidx.compose.material3.tokens.TopAppBarSmallTokens
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.layout.AlignmentLine
import androidx.compose.ui.layout.LastBaseline
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
/**
* <a href="https://m3.material.io/components/top-app-bar/overview" class="external" target="_blank">Material Design small top app bar</a>.
*
* Top app bars display information and actions at the top of a screen.
*
* This small TopAppBar has slots for a title, navigation icon, and actions.
*
* 
*
* A simple top app bar looks like:
* @sample androidx.compose.material3.samples.SimpleTopAppBar
* A top app bar that uses a [scrollBehavior] to customize its nested scrolling behavior when
* working in conjunction with a scrolling content looks like:
* @sample androidx.compose.material3.samples.PinnedTopAppBar
* @sample androidx.compose.material3.samples.EnterAlwaysTopAppBar
*
* @param title the title to be displayed in the top app bar
* @param modifier the [Modifier] to be applied to this top app bar
* @param navigationIcon the navigation icon displayed at the start of the top app bar. This should
* typically be an [IconButton] or [IconToggleButton].
* @param actions the actions displayed at the end of the top app bar. This should typically be
* [IconButton]s. The default layout here is a [Row], so icons inside will be placed horizontally.
* @param windowInsets a window insets that app bar will respect.
* @param colors [TopAppBarColors] that will be used to resolve the colors used for this top app
* bar in different states. See [TopAppBarDefaults.topAppBarColors].
* @param scrollBehavior a [TopAppBarScrollBehavior] which holds various offset values that will be
* applied by this top app bar to set up its height and colors. A scroll behavior is designed to
* work in conjunction with a scrolled content to change the top app bar appearance as the content
* scrolls. See [TopAppBarScrollBehavior.nestedScrollConnection].
*/
@ExperimentalMaterial3Api
@Composable
fun TopAppBar(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable () -> Unit = {},
actions: @Composable RowScope.() -> Unit = {},
windowInsets: WindowInsets = TopAppBarDefaults.windowInsets,
colors: TopAppBarColors = TopAppBarDefaults.topAppBarColors(),
scrollBehavior: TopAppBarScrollBehavior? = null
) {
SingleRowTopAppBar(
modifier = modifier,
title = title,
titleTextStyle = MaterialTheme.typography.fromToken(TopAppBarSmallTokens.HeadlineFont),
centeredTitle = false,
navigationIcon = navigationIcon,
actions = actions,
windowInsets = windowInsets,
colors = colors,
scrollBehavior = scrollBehavior
)
}
/**
* <a href="https://m3.material.io/components/top-app-bar/overview" class="external" target="_blank">Material Design small top app bar</a>.
*
* Top app bars display information and actions at the top of a screen.
*
* This SmallTopAppBar has slots for a title, navigation icon, and actions.
*
* 
*
* A simple top app bar looks like:
* @sample androidx.compose.material3.samples.SimpleTopAppBar
* A top app bar that uses a [scrollBehavior] to customize its nested scrolling behavior when
* working in conjunction with a scrolling content looks like:
* @sample androidx.compose.material3.samples.PinnedTopAppBar
* @sample androidx.compose.material3.samples.EnterAlwaysTopAppBar
*
* @param title the title to be displayed in the top app bar
* @param modifier the [Modifier] to be applied to this top app bar
* @param navigationIcon the navigation icon displayed at the start of the top app bar. This should
* typically be an [IconButton] or [IconToggleButton].
* @param actions the actions displayed at the end of the top app bar. This should typically be
* [IconButton]s. The default layout here is a [Row], so icons inside will be placed horizontally.
* @param windowInsets a window insets that app bar will respect.
* @param colors [TopAppBarColors] that will be used to resolve the colors used for this top app
* bar in different states. See [TopAppBarDefaults.topAppBarColors].
* @param scrollBehavior a [TopAppBarScrollBehavior] which holds various offset values that will be
* applied by this top app bar to set up its height and colors. A scroll behavior is designed to
* work in conjunction with a scrolled content to change the top app bar appearance as the content
* scrolls. See [TopAppBarScrollBehavior.nestedScrollConnection].
* @deprecated use [TopAppBar] instead
*/
@Deprecated(
message = "Use TopAppBar instead.",
replaceWith = ReplaceWith(
"TopAppBar(title, modifier, navigationIcon, actions, windowInsets, colors, " +
"scrollBehavior)"
),
level = DeprecationLevel.WARNING
)
@ExperimentalMaterial3Api
@Composable
fun SmallTopAppBar(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable () -> Unit = {},
actions: @Composable RowScope.() -> Unit = {},
windowInsets: WindowInsets = TopAppBarDefaults.windowInsets,
colors: TopAppBarColors = TopAppBarDefaults.topAppBarColors(),
scrollBehavior: TopAppBarScrollBehavior? = null
) = TopAppBar(title, modifier, navigationIcon, actions, windowInsets, colors, scrollBehavior)
/**
* <a href="https://m3.material.io/components/top-app-bar/overview" class="external" target="_blank">Material Design center-aligned small top app bar</a>.
*
* Top app bars display information and actions at the top of a screen.
*
* This small top app bar has a header title that is horizontally aligned to the center.
*
* 
*
* This CenterAlignedTopAppBar has slots for a title, navigation icon, and actions.
*
* A center aligned top app bar that uses a [scrollBehavior] to customize its nested scrolling
* behavior when working in conjunction with a scrolling content looks like:
* @sample androidx.compose.material3.samples.SimpleCenterAlignedTopAppBar
*
* @param title the title to be displayed in the top app bar
* @param modifier the [Modifier] to be applied to this top app bar
* @param navigationIcon the navigation icon displayed at the start of the top app bar. This should
* typically be an [IconButton] or [IconToggleButton].
* @param actions the actions displayed at the end of the top app bar. This should typically be
* [IconButton]s. The default layout here is a [Row], so icons inside will be placed horizontally.
* @param windowInsets a window insets that app bar will respect.
* @param colors [TopAppBarColors] that will be used to resolve the colors used for this top app
* bar in different states. See [TopAppBarDefaults.centerAlignedTopAppBarColors].
* @param scrollBehavior a [TopAppBarScrollBehavior] which holds various offset values that will be
* applied by this top app bar to set up its height and colors. A scroll behavior is designed to
* work in conjunction with a scrolled content to change the top app bar appearance as the content
* scrolls. See [TopAppBarScrollBehavior.nestedScrollConnection].
*/
@ExperimentalMaterial3Api
@Composable
fun CenterAlignedTopAppBar(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable () -> Unit = {},
actions: @Composable RowScope.() -> Unit = {},
windowInsets: WindowInsets = TopAppBarDefaults.windowInsets,
colors: TopAppBarColors = TopAppBarDefaults.centerAlignedTopAppBarColors(),
scrollBehavior: TopAppBarScrollBehavior? = null
) {
SingleRowTopAppBar(
modifier = modifier,
title = title,
titleTextStyle =
MaterialTheme.typography.fromToken(TopAppBarSmallTokens.HeadlineFont),
centeredTitle = true,
navigationIcon = navigationIcon,
actions = actions,
colors = colors,
windowInsets = windowInsets,
scrollBehavior = scrollBehavior
)
}
/**
* <a href="https://m3.material.io/components/top-app-bar/overview" class="external" target="_blank">Material Design medium top app bar</a>.
*
* Top app bars display information and actions at the top of a screen.
*
* 
*
* This MediumTopAppBar has slots for a title, navigation icon, and actions. In its default expanded
* state, the title is displayed in a second row under the navigation and actions.
*
* A medium top app bar that uses a [scrollBehavior] to customize its nested scrolling behavior when
* working in conjunction with scrolling content looks like:
* @sample androidx.compose.material3.samples.ExitUntilCollapsedMediumTopAppBar
*
* @param title the title to be displayed in the top app bar. This title will be used in the app
* bar's expanded and collapsed states, although in its collapsed state it will be composed with a
* smaller sized [TextStyle]
* @param modifier the [Modifier] to be applied to this top app bar
* @param navigationIcon the navigation icon displayed at the start of the top app bar. This should
* typically be an [IconButton] or [IconToggleButton].
* @param actions the actions displayed at the end of the top app bar. This should typically be
* [IconButton]s. The default layout here is a [Row], so icons inside will be placed horizontally.
* @param windowInsets a window insets that app bar will respect.
* @param colors [TopAppBarColors] that will be used to resolve the colors used for this top app
* bar in different states. See [TopAppBarDefaults.mediumTopAppBarColors].
* @param scrollBehavior a [TopAppBarScrollBehavior] which holds various offset values that will be
* applied by this top app bar to set up its height and colors. A scroll behavior is designed to
* work in conjunction with a scrolled content to change the top app bar appearance as the content
* scrolls. See [TopAppBarScrollBehavior.nestedScrollConnection].
*/
@ExperimentalMaterial3Api
@Composable
fun MediumTopAppBar(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable () -> Unit = {},
actions: @Composable RowScope.() -> Unit = {},
windowInsets: WindowInsets = TopAppBarDefaults.windowInsets,
colors: TopAppBarColors = TopAppBarDefaults.mediumTopAppBarColors(),
scrollBehavior: TopAppBarScrollBehavior? = null
) {
TwoRowsTopAppBar(
modifier = modifier,
title = title,
titleTextStyle = MaterialTheme.typography.fromToken(TopAppBarMediumTokens.HeadlineFont),
smallTitleTextStyle = MaterialTheme.typography.fromToken(TopAppBarSmallTokens.HeadlineFont),
titleBottomPadding = MediumTitleBottomPadding,
smallTitle = title,
navigationIcon = navigationIcon,
actions = actions,
colors = colors,
windowInsets = windowInsets,
maxHeight = TopAppBarMediumTokens.ContainerHeight,
pinnedHeight = TopAppBarSmallTokens.ContainerHeight,
scrollBehavior = scrollBehavior
)
}
/**
* <a href="https://m3.material.io/components/top-app-bar/overview" class="external" target="_blank">Material Design large top app bar</a>.
*
* Top app bars display information and actions at the top of a screen.
*
* 
*
* This LargeTopAppBar has slots for a title, navigation icon, and actions. In its default expanded
* state, the title is displayed in a second row under the navigation and actions.
*
* A large top app bar that uses a [scrollBehavior] to customize its nested scrolling behavior when
* working in conjunction with scrolling content looks like:
* @sample androidx.compose.material3.samples.ExitUntilCollapsedLargeTopAppBar
*
* @param title the title to be displayed in the top app bar. This title will be used in the app
* bar's expanded and collapsed states, although in its collapsed state it will be composed with a
* smaller sized [TextStyle]
* @param modifier the [Modifier] to be applied to this top app bar
* @param navigationIcon the navigation icon displayed at the start of the top app bar. This should
* typically be an [IconButton] or [IconToggleButton].
* @param actions the actions displayed at the end of the top app bar. This should typically be
* [IconButton]s. The default layout here is a [Row], so icons inside will be placed horizontally.
* @param windowInsets a window insets that app bar will respect.
* @param colors [TopAppBarColors] that will be used to resolve the colors used for this top app
* bar in different states. See [TopAppBarDefaults.largeTopAppBarColors].
* @param scrollBehavior a [TopAppBarScrollBehavior] which holds various offset values that will be
* applied by this top app bar to set up its height and colors. A scroll behavior is designed to
* work in conjunction with a scrolled content to change the top app bar appearance as the content
* scrolls. See [TopAppBarScrollBehavior.nestedScrollConnection].
*/
@ExperimentalMaterial3Api
@Composable
fun LargeTopAppBar(
title: @Composable () -> Unit,
modifier: Modifier = Modifier,
navigationIcon: @Composable () -> Unit = {},
actions: @Composable RowScope.() -> Unit = {},
windowInsets: WindowInsets = TopAppBarDefaults.windowInsets,
colors: TopAppBarColors = TopAppBarDefaults.largeTopAppBarColors(),
scrollBehavior: TopAppBarScrollBehavior? = null
) {
TwoRowsTopAppBar(
title = title,
titleTextStyle = MaterialTheme.typography.fromToken(TopAppBarLargeTokens.HeadlineFont),
smallTitleTextStyle = MaterialTheme.typography.fromToken(TopAppBarSmallTokens.HeadlineFont),
titleBottomPadding = LargeTitleBottomPadding,
smallTitle = title,
modifier = modifier,
navigationIcon = navigationIcon,
actions = actions,
colors = colors,
windowInsets = windowInsets,
maxHeight = TopAppBarLargeTokens.ContainerHeight,
pinnedHeight = TopAppBarSmallTokens.ContainerHeight,
scrollBehavior = scrollBehavior
)
}
/**
* <a href="https://m3.material.io/components/bottom-app-bar/overview" class="external" target="_blank">Material Design bottom app bar</a>.
*
* A bottom app bar displays navigation and key actions at the bottom of mobile screens.
*
* 
*
* @sample androidx.compose.material3.samples.SimpleBottomAppBar
*
* It can optionally display a [FloatingActionButton] embedded at the end of the BottomAppBar.
*
* @sample androidx.compose.material3.samples.BottomAppBarWithFAB
*
* Also see [NavigationBar].
*
* @param actions the icon content of this BottomAppBar. The default layout here is a [Row],
* so content inside will be placed horizontally.
* @param modifier the [Modifier] to be applied to this BottomAppBar
* @param floatingActionButton optional floating action button at the end of this BottomAppBar
* @param containerColor the color used for the background of this BottomAppBar. Use
* [Color.Transparent] to have no color.
* @param contentColor the preferred color for content inside this BottomAppBar. Defaults to either
* the matching content color for [containerColor], or to the current [LocalContentColor] if
* [containerColor] is not a color from the theme.
* @param tonalElevation when [containerColor] is [ColorScheme.surface], a translucent primary color
* overlay is applied on top of the container. A higher tonal elevation value will result in a
* darker color in light theme and lighter color in dark theme. See also: [Surface].
* @param contentPadding the padding applied to the content of this BottomAppBar
* @param windowInsets a window insets that app bar will respect.
*/
@Composable
fun BottomAppBar(
actions: @Composable RowScope.() -> Unit,
modifier: Modifier = Modifier,
floatingActionButton: @Composable (() -> Unit)? = null,
containerColor: Color = BottomAppBarDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,
contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,
windowInsets: WindowInsets = BottomAppBarDefaults.windowInsets,
) = BottomAppBar(
modifier = modifier,
containerColor = containerColor,
contentColor = contentColor,
tonalElevation = tonalElevation,
windowInsets = windowInsets,
contentPadding = contentPadding
) {
actions()
if (floatingActionButton != null) {
Spacer(Modifier.weight(1f, true))
Box(
Modifier
.fillMaxHeight()
.padding(
top = FABVerticalPadding,
end = FABHorizontalPadding
),
contentAlignment = Alignment.TopStart
) {
floatingActionButton()
}
}
}
/**
* <a href="https://m3.material.io/components/bottom-app-bar/overview" class="external" target="_blank">Material Design bottom app bar</a>.
*
* A bottom app bar displays navigation and key actions at the bottom of mobile screens.
*
* 
*
* If you are interested in displaying a [FloatingActionButton], consider using another overload.
*
* Also see [NavigationBar].
*
* @param modifier the [Modifier] to be applied to this BottomAppBar
* @param containerColor the color used for the background of this BottomAppBar. Use
* [Color.Transparent] to have no color.
* @param contentColor the preferred color for content inside this BottomAppBar. Defaults to either
* the matching content color for [containerColor], or to the current [LocalContentColor] if
* [containerColor] is not a color from the theme.
* @param tonalElevation when [containerColor] is [ColorScheme.surface], a translucent primary color
* overlay is applied on top of the container. A higher tonal elevation value will result in a
* darker color in light theme and lighter color in dark theme. See also: [Surface].
* @param contentPadding the padding applied to the content of this BottomAppBar
* @param windowInsets a window insets that app bar will respect.
* @param content the content of this BottomAppBar. The default layout here is a [Row],
* so content inside will be placed horizontally.
*/
@Composable
fun BottomAppBar(
modifier: Modifier = Modifier,
containerColor: Color = BottomAppBarDefaults.containerColor,
contentColor: Color = contentColorFor(containerColor),
tonalElevation: Dp = BottomAppBarDefaults.ContainerElevation,
contentPadding: PaddingValues = BottomAppBarDefaults.ContentPadding,
windowInsets: WindowInsets = BottomAppBarDefaults.windowInsets,
content: @Composable RowScope.() -> Unit
) {
Surface(
color = containerColor,
contentColor = contentColor,
tonalElevation = tonalElevation,
// TODO(b/209583788): Consider adding a shape parameter if updated design guidance allows
shape = BottomAppBarTokens.ContainerShape.toShape(),
modifier = modifier
) {
Row(
Modifier
.fillMaxWidth()
.windowInsetsPadding(windowInsets)
.height(BottomAppBarTokens.ContainerHeight)
.padding(contentPadding),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically,
content = content
)
}
}
/**
* A TopAppBarScrollBehavior defines how an app bar should behave when the content under it is
* scrolled.
*
* @see [TopAppBarDefaults.pinnedScrollBehavior]
* @see [TopAppBarDefaults.enterAlwaysScrollBehavior]
* @see [TopAppBarDefaults.exitUntilCollapsedScrollBehavior]
*/
@ExperimentalMaterial3Api
@Stable
interface TopAppBarScrollBehavior {
/**
* A [TopAppBarState] that is attached to this behavior and is read and updated when scrolling
* happens.
*/
val state: TopAppBarState
/**
* Indicates whether the top app bar is pinned.
*
* A pinned app bar will stay fixed in place when content is scrolled and will not react to any
* drag gestures.
*/
val isPinned: Boolean
/**
* An optional [AnimationSpec] that defines how the top app bar snaps to either fully collapsed
* or fully extended state when a fling or a drag scrolled it into an intermediate position.
*/
val snapAnimationSpec: AnimationSpec<Float>?
/**
* An optional [DecayAnimationSpec] that defined how to fling the top app bar when the user
* flings the app bar itself, or the content below it.
*/
val flingAnimationSpec: DecayAnimationSpec<Float>?
/**
* A [NestedScrollConnection] that should be attached to a [Modifier.nestedScroll] in order to
* keep track of the scroll events.
*/
val nestedScrollConnection: NestedScrollConnection
}
/** Contains default values used for the top app bar implementations. */
@ExperimentalMaterial3Api
object TopAppBarDefaults {
/**
* Creates a [TopAppBarColors] for small [TopAppBar]. The default implementation animates
* between the provided colors according to the Material Design specification.
*
* @param containerColor the container color
* @param scrolledContainerColor the container color when content is scrolled behind it
* @param navigationIconContentColor the content color used for the navigation icon
* @param titleContentColor the content color used for the title
* @param actionIconContentColor the content color used for actions
* @return the resulting [TopAppBarColors] used for the top app bar
*/
@Composable
fun topAppBarColors(
containerColor: Color = TopAppBarSmallTokens.ContainerColor.toColor(),
scrolledContainerColor: Color = MaterialTheme.colorScheme.applyTonalElevation(
backgroundColor = containerColor,
elevation = TopAppBarSmallTokens.OnScrollContainerElevation
),
navigationIconContentColor: Color = TopAppBarSmallTokens.LeadingIconColor.toColor(),
titleContentColor: Color = TopAppBarSmallTokens.HeadlineColor.toColor(),
actionIconContentColor: Color = TopAppBarSmallTokens.TrailingIconColor.toColor(),
): TopAppBarColors =
TopAppBarColors(
containerColor,
scrolledContainerColor,
navigationIconContentColor,
titleContentColor,
actionIconContentColor
)
/**
* Creates a [TopAppBarColors] for small [TopAppBar]s. The default implementation animates
* between the provided colors according to the Material Design specification.
*
* @param containerColor the container color
* @param scrolledContainerColor the container color when content is scrolled behind it
* @param navigationIconContentColor the content color used for the navigation icon
* @param titleContentColor the content color used for the title
* @param actionIconContentColor the content color used for actions
* @return the resulting [TopAppBarColors] used for the top app bar
* @deprecated use [topAppBarColors] instead
*/
@Deprecated(
message = "Use topAppBarColors instead.",
replaceWith = ReplaceWith(
"topAppBarColors(containerColor, scrolledContainerColor, " +
"navigationIconContentColor, titleContentColor, actionIconContentColor)"
),
level = DeprecationLevel.WARNING
)
@Composable
fun smallTopAppBarColors(
containerColor: Color = TopAppBarSmallTokens.ContainerColor.toColor(),
scrolledContainerColor: Color = MaterialTheme.colorScheme.applyTonalElevation(
backgroundColor = containerColor,
elevation = TopAppBarSmallTokens.OnScrollContainerElevation
),
navigationIconContentColor: Color = TopAppBarSmallTokens.LeadingIconColor.toColor(),
titleContentColor: Color = TopAppBarSmallTokens.HeadlineColor.toColor(),
actionIconContentColor: Color = TopAppBarSmallTokens.TrailingIconColor.toColor(),
): TopAppBarColors =
topAppBarColors(
containerColor,
scrolledContainerColor,
navigationIconContentColor,
titleContentColor,
actionIconContentColor
)
/**
* Default insets to be used and consumed by the top app bars
*/
val windowInsets: WindowInsets
@Composable
get() = WindowInsets.systemBarsForVisualComponents
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top)
/**
* Creates a [TopAppBarColors] for [CenterAlignedTopAppBar]s. The default implementation
* animates between the provided colors according to the Material Design specification.
*
* @param containerColor the container color
* @param scrolledContainerColor the container color when content is scrolled behind it
* @param navigationIconContentColor the content color used for the navigation icon
* @param titleContentColor the content color used for the title
* @param actionIconContentColor the content color used for actions
* @return the resulting [TopAppBarColors] used for the top app bar
*/
@Composable
fun centerAlignedTopAppBarColors(
containerColor: Color = TopAppBarSmallCenteredTokens.ContainerColor.toColor(),
scrolledContainerColor: Color = MaterialTheme.colorScheme.applyTonalElevation(
backgroundColor = containerColor,
elevation = TopAppBarSmallTokens.OnScrollContainerElevation
),
navigationIconContentColor: Color = TopAppBarSmallCenteredTokens.LeadingIconColor.toColor(),
titleContentColor: Color = TopAppBarSmallCenteredTokens.HeadlineColor.toColor(),
actionIconContentColor: Color = TopAppBarSmallCenteredTokens.TrailingIconColor.toColor(),
): TopAppBarColors =
TopAppBarColors(
containerColor,
scrolledContainerColor,
navigationIconContentColor,
titleContentColor,
actionIconContentColor
)
/**
* Creates a [TopAppBarColors] for [MediumTopAppBar]s. The default implementation interpolates
* between the provided colors as the top app bar scrolls according to the Material Design
* specification.
*
* @param containerColor the container color
* @param scrolledContainerColor the container color when content is scrolled behind it
* @param navigationIconContentColor the content color used for the navigation icon
* @param titleContentColor the content color used for the title
* @param actionIconContentColor the content color used for actions
* @return the resulting [TopAppBarColors] used for the top app bar
*/
@Composable
fun mediumTopAppBarColors(
containerColor: Color = TopAppBarMediumTokens.ContainerColor.toColor(),
scrolledContainerColor: Color = MaterialTheme.colorScheme.applyTonalElevation(
backgroundColor = containerColor,
elevation = TopAppBarSmallTokens.OnScrollContainerElevation
),
navigationIconContentColor: Color = TopAppBarMediumTokens.LeadingIconColor.toColor(),
titleContentColor: Color = TopAppBarMediumTokens.HeadlineColor.toColor(),
actionIconContentColor: Color = TopAppBarMediumTokens.TrailingIconColor.toColor(),
): TopAppBarColors =
TopAppBarColors(
containerColor,
scrolledContainerColor,
navigationIconContentColor,
titleContentColor,
actionIconContentColor
)
/**
* Creates a [TopAppBarColors] for [LargeTopAppBar]s. The default implementation interpolates
* between the provided colors as the top app bar scrolls according to the Material Design
* specification.
*
* @param containerColor the container color
* @param scrolledContainerColor the container color when content is scrolled behind it
* @param navigationIconContentColor the content color used for the navigation icon
* @param titleContentColor the content color used for the title
* @param actionIconContentColor the content color used for actions
* @return the resulting [TopAppBarColors] used for the top app bar
*/
@Composable
fun largeTopAppBarColors(
containerColor: Color = TopAppBarLargeTokens.ContainerColor.toColor(),
scrolledContainerColor: Color = MaterialTheme.colorScheme.applyTonalElevation(
backgroundColor = containerColor,
elevation = TopAppBarSmallTokens.OnScrollContainerElevation
),
navigationIconContentColor: Color = TopAppBarLargeTokens.LeadingIconColor.toColor(),
titleContentColor: Color = TopAppBarLargeTokens.HeadlineColor.toColor(),
actionIconContentColor: Color = TopAppBarLargeTokens.TrailingIconColor.toColor(),
): TopAppBarColors =
TopAppBarColors(
containerColor,
scrolledContainerColor,
navigationIconContentColor,
titleContentColor,
actionIconContentColor
)
/**
* Returns a pinned [TopAppBarScrollBehavior] that tracks nested-scroll callbacks and
* updates its [TopAppBarState.contentOffset] accordingly.
*
* @param state the state object to be used to control or observe the top app bar's scroll
* state. See [rememberTopAppBarState] for a state that is remembered across compositions.
* @param canScroll a callback used to determine whether scroll events are to be handled by this
* pinned [TopAppBarScrollBehavior]
*/
@ExperimentalMaterial3Api
@Composable
fun pinnedScrollBehavior(
state: TopAppBarState = rememberTopAppBarState(),
canScroll: () -> Boolean = { true }
): TopAppBarScrollBehavior = PinnedScrollBehavior(state = state, canScroll = canScroll)
/**
* Returns a [TopAppBarScrollBehavior]. A top app bar that is set up with this
* [TopAppBarScrollBehavior] will immediately collapse when the content is pulled up, and will
* immediately appear when the content is pulled down.
*
* @param state the state object to be used to control or observe the top app bar's scroll
* state. See [rememberTopAppBarState] for a state that is remembered across compositions.
* @param canScroll a callback used to determine whether scroll events are to be
* handled by this [EnterAlwaysScrollBehavior]
* @param snapAnimationSpec an optional [AnimationSpec] that defines how the top app bar snaps
* to either fully collapsed or fully extended state when a fling or a drag scrolled it into an
* intermediate position
* @param flingAnimationSpec an optional [DecayAnimationSpec] that defined how to fling the top
* app bar when the user flings the app bar itself, or the content below it
*/
@ExperimentalMaterial3Api
@Composable
fun enterAlwaysScrollBehavior(
state: TopAppBarState = rememberTopAppBarState(),
canScroll: () -> Boolean = { true },
snapAnimationSpec: AnimationSpec<Float>? = spring(stiffness = Spring.StiffnessMediumLow),
flingAnimationSpec: DecayAnimationSpec<Float>? = rememberSplineBasedDecay()
): TopAppBarScrollBehavior =
EnterAlwaysScrollBehavior(
state = state,
snapAnimationSpec = snapAnimationSpec,
flingAnimationSpec = flingAnimationSpec,
canScroll = canScroll
)
/**
* Returns a [TopAppBarScrollBehavior] that adjusts its properties to affect the colors and
* height of the top app bar.
*
* A top app bar that is set up with this [TopAppBarScrollBehavior] will immediately collapse
* when the nested content is pulled up, and will expand back the collapsed area when the
* content is pulled all the way down.
*
* @param state the state object to be used to control or observe the top app bar's scroll
* state. See [rememberTopAppBarState] for a state that is remembered across compositions.
* @param canScroll a callback used to determine whether scroll events are to be
* handled by this [ExitUntilCollapsedScrollBehavior]
* @param snapAnimationSpec an optional [AnimationSpec] that defines how the top app bar snaps
* to either fully collapsed or fully extended state when a fling or a drag scrolled it into an
* intermediate position
* @param flingAnimationSpec an optional [DecayAnimationSpec] that defined how to fling the top
* app bar when the user flings the app bar itself, or the content below it
*/
@ExperimentalMaterial3Api
@Composable
fun exitUntilCollapsedScrollBehavior(
state: TopAppBarState = rememberTopAppBarState(),
canScroll: () -> Boolean = { true },
snapAnimationSpec: AnimationSpec<Float>? = spring(stiffness = Spring.StiffnessMediumLow),
flingAnimationSpec: DecayAnimationSpec<Float>? = rememberSplineBasedDecay()
): TopAppBarScrollBehavior =
ExitUntilCollapsedScrollBehavior(
state = state,
snapAnimationSpec = snapAnimationSpec,
flingAnimationSpec = flingAnimationSpec,
canScroll = canScroll
)
}
/**
* Creates a [TopAppBarState] that is remembered across compositions.
*
* @param initialHeightOffsetLimit the initial value for [TopAppBarState.heightOffsetLimit],
* which represents the pixel limit that a top app bar is allowed to collapse when the scrollable
* content is scrolled
* @param initialHeightOffset the initial value for [TopAppBarState.heightOffset]. The initial
* offset height offset should be between zero and [initialHeightOffsetLimit].
* @param initialContentOffset the initial value for [TopAppBarState.contentOffset]
*/
@ExperimentalMaterial3Api
@Composable
fun rememberTopAppBarState(
initialHeightOffsetLimit: Float = -Float.MAX_VALUE,
initialHeightOffset: Float = 0f,
initialContentOffset: Float = 0f
): TopAppBarState {
return rememberSaveable(saver = TopAppBarState.Saver) {
TopAppBarState(
initialHeightOffsetLimit,
initialHeightOffset,
initialContentOffset
)
}
}
/**
* A state object that can be hoisted to control and observe the top app bar state. The state is
* read and updated by a [TopAppBarScrollBehavior] implementation.
*
* In most cases, this state will be created via [rememberTopAppBarState].
*
* @param initialHeightOffsetLimit the initial value for [TopAppBarState.heightOffsetLimit]
* @param initialHeightOffset the initial value for [TopAppBarState.heightOffset]
* @param initialContentOffset the initial value for [TopAppBarState.contentOffset]
*/
@ExperimentalMaterial3Api
@Stable
class TopAppBarState(
initialHeightOffsetLimit: Float,
initialHeightOffset: Float,
initialContentOffset: Float
) {
/**
* The top app bar's height offset limit in pixels, which represents the limit that a top app
* bar is allowed to collapse to.
*
* Use this limit to coerce the [heightOffset] value when it's updated.
*/
var heightOffsetLimit by mutableStateOf(initialHeightOffsetLimit)
/**
* The top app bar's current height offset in pixels. This height offset is applied to the fixed
* height of the app bar to control the displayed height when content is being scrolled.
*
* Updates to the [heightOffset] value are coerced between zero and [heightOffsetLimit].
*/
var heightOffset: Float
get() = _heightOffset.value
set(newOffset) {
_heightOffset.value = newOffset.coerceIn(
minimumValue = heightOffsetLimit,
maximumValue = 0f
)
}
/**
* The total offset of the content scrolled under the top app bar.
*
* The content offset is used to compute the [overlappedFraction], which can later be read
* by an implementation.
*
* This value is updated by a [TopAppBarScrollBehavior] whenever a nested scroll connection
* consumes scroll events. A common implementation would update the value to be the sum of all
* [NestedScrollConnection.onPostScroll] `consumed.y` values.
*/
var contentOffset by mutableStateOf(initialContentOffset)
/**
* A value that represents the collapsed height percentage of the app bar.
*
* A `0.0` represents a fully expanded bar, and `1.0` represents a fully collapsed bar (computed
* as [heightOffset] / [heightOffsetLimit]).
*/
val collapsedFraction: Float
get() = if (heightOffsetLimit != 0f) {
heightOffset / heightOffsetLimit
} else {
0f
}
/**
* A value that represents the percentage of the app bar area that is overlapping with the
* content scrolled behind it.
*
* A `0.0` indicates that the app bar does not overlap any content, while `1.0` indicates that
* the entire visible app bar area overlaps the scrolled content.
*/
val overlappedFraction: Float
get() = if (heightOffsetLimit != 0f) {
1 - ((heightOffsetLimit - contentOffset).coerceIn(
minimumValue = heightOffsetLimit,
maximumValue = 0f
) / heightOffsetLimit)
} else {
0f
}
companion object {
/**
* The default [Saver] implementation for [TopAppBarState].
*/
val Saver: Saver<TopAppBarState, *> = listSaver(
save = { listOf(it.heightOffsetLimit, it.heightOffset, it.contentOffset) },
restore = {
TopAppBarState(
initialHeightOffsetLimit = it[0],
initialHeightOffset = it[1],
initialContentOffset = it[2]
)
}
)
}
private var _heightOffset = mutableStateOf(initialHeightOffset)
}
/**
* Represents the colors used by a top app bar in different states.
* This implementation animates the container color according to the top app bar scroll state. It
* does not animate the leading, headline, or trailing colors.
*/
@ExperimentalMaterial3Api
@Stable
class TopAppBarColors internal constructor(
private val containerColor: Color,
private val scrolledContainerColor: Color,
internal val navigationIconContentColor: Color,
internal val titleContentColor: Color,
internal val actionIconContentColor: Color,
) {
/**
* Represents the container color used for the top app bar.
*
* A [colorTransitionFraction] provides a percentage value that can be used to generate a color.
* Usually, an app bar implementation will pass in a [colorTransitionFraction] read from
* the [TopAppBarState.collapsedFraction] or the [TopAppBarState.overlappedFraction].
*
* @param colorTransitionFraction a `0.0` to `1.0` value that represents a color transition
* percentage
*/
@Composable
internal fun containerColor(colorTransitionFraction: Float): Color {
return lerp(
containerColor,
scrolledContainerColor,
FastOutLinearInEasing.transform(colorTransitionFraction)
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other !is TopAppBarColors) return false
if (containerColor != other.containerColor) return false
if (scrolledContainerColor != other.scrolledContainerColor) return false
if (navigationIconContentColor != other.navigationIconContentColor) return false
if (titleContentColor != other.titleContentColor) return false
if (actionIconContentColor != other.actionIconContentColor) return false
return true
}
override fun hashCode(): Int {
var result = containerColor.hashCode()
result = 31 * result + scrolledContainerColor.hashCode()
result = 31 * result + navigationIconContentColor.hashCode()
result = 31 * result + titleContentColor.hashCode()
result = 31 * result + actionIconContentColor.hashCode()
return result
}
}
/** Contains default values used for the bottom app bar implementations. */
object BottomAppBarDefaults {
/** Default color used for [BottomAppBar] container **/
val containerColor: Color @Composable get() = BottomAppBarTokens.ContainerColor.toColor()
/** Default elevation used for [BottomAppBar] **/
val ContainerElevation: Dp = BottomAppBarTokens.ContainerElevation
/**
* Default padding used for [BottomAppBar] when content are default size (24dp) icons in
* [IconButton] that meet the minimum touch target (48.dp).
*/
val ContentPadding = PaddingValues(
start = BottomAppBarHorizontalPadding,
top = BottomAppBarVerticalPadding,
end = BottomAppBarHorizontalPadding
)
/**
* Default insets that will be used and consumed by [BottomAppBar].
*/
val windowInsets: WindowInsets
@Composable
get() {
return WindowInsets.systemBarsForVisualComponents
.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom)
}
/** The color of a [BottomAppBar]'s [FloatingActionButton] */
val bottomAppBarFabColor: Color
@Composable get() =
FabSecondaryTokens.ContainerColor.toColor()
}
// Padding minus IconButton's min touch target expansion
private val BottomAppBarHorizontalPadding = 16.dp - 12.dp
internal val BottomAppBarVerticalPadding = 16.dp - 12.dp
// Padding minus content padding
private val FABHorizontalPadding = 16.dp - BottomAppBarHorizontalPadding
private val FABVerticalPadding = 12.dp - BottomAppBarVerticalPadding
/**
* A single-row top app bar that is designed to be called by the small and center aligned top app
* bar composables.
*
* This SingleRowTopAppBar has slots for a title, navigation icon, and actions. When the
* [centeredTitle] flag is true, the title will be horizontally aligned to the center of the top app
* bar width.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SingleRowTopAppBar(
modifier: Modifier = Modifier,
title: @Composable () -> Unit,
titleTextStyle: TextStyle,
centeredTitle: Boolean,
navigationIcon: @Composable () -> Unit,
actions: @Composable RowScope.() -> Unit,
windowInsets: WindowInsets,
colors: TopAppBarColors,
scrollBehavior: TopAppBarScrollBehavior?
) {
// Sets the app bar's height offset to collapse the entire bar's height when content is
// scrolled.
val heightOffsetLimit =
with(LocalDensity.current) { -TopAppBarSmallTokens.ContainerHeight.toPx() }
SideEffect {
if (scrollBehavior?.state?.heightOffsetLimit != heightOffsetLimit) {
scrollBehavior?.state?.heightOffsetLimit = heightOffsetLimit
}
}
// Obtain the container color from the TopAppBarColors using the `overlapFraction`. This
// ensures that the colors will adjust whether the app bar behavior is pinned or scrolled.
// This may potentially animate or interpolate a transition between the container-color and the
// container's scrolled-color according to the app bar's scroll state.
val colorTransitionFraction = scrollBehavior?.state?.overlappedFraction ?: 0f
val fraction = if (colorTransitionFraction > 0.01f) 1f else 0f
val appBarContainerColor by animateColorAsState(
targetValue = colors.containerColor(fraction),
animationSpec = spring(stiffness = Spring.StiffnessMediumLow)
)
// Wrap the given actions in a Row.
val actionsRow = @Composable {
Row(
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
content = actions
)
}
// Set up support for resizing the top app bar when vertically dragging the bar itself.
val appBarDragModifier = if (scrollBehavior != null && !scrollBehavior.isPinned) {
Modifier.draggable(
orientation = Orientation.Vertical,
state = rememberDraggableState { delta ->
scrollBehavior.state.heightOffset = scrollBehavior.state.heightOffset + delta
},
onDragStopped = { velocity ->
settleAppBar(
scrollBehavior.state,
velocity,
scrollBehavior.flingAnimationSpec,
scrollBehavior.snapAnimationSpec
)
}
)
} else {
Modifier
}
// Compose a Surface with a TopAppBarLayout content.
// The surface's background color is animated as specified above.
// The height of the app bar is determined by subtracting the bar's height offset from the
// app bar's defined constant height value (i.e. the ContainerHeight token).
Surface(modifier = modifier.then(appBarDragModifier), color = appBarContainerColor) {
val height = LocalDensity.current.run {
TopAppBarSmallTokens.ContainerHeight.toPx() + (scrollBehavior?.state?.heightOffset
?: 0f)
}
TopAppBarLayout(
modifier = Modifier
.windowInsetsPadding(windowInsets)
// clip after padding so we don't show the title over the inset area
.clipToBounds(),
heightPx = height,
navigationIconContentColor = colors.navigationIconContentColor,
titleContentColor = colors.titleContentColor,
actionIconContentColor = colors.actionIconContentColor,
title = title,
titleTextStyle = titleTextStyle,
titleAlpha = 1f,
titleVerticalArrangement = Arrangement.Center,
titleHorizontalArrangement =
if (centeredTitle) Arrangement.Center else Arrangement.Start,
titleBottomPadding = 0,
hideTitleSemantics = false,
navigationIcon = navigationIcon,
actions = actionsRow,
)
}
}
/**
* A two-rows top app bar that is designed to be called by the Large and Medium top app bar
* composables.
*
* @throws [IllegalArgumentException] if the given [maxHeight] is equal or smaller than the
* [pinnedHeight]
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TwoRowsTopAppBar(
modifier: Modifier = Modifier,
title: @Composable () -> Unit,
titleTextStyle: TextStyle,
titleBottomPadding: Dp,
smallTitle: @Composable () -> Unit,
smallTitleTextStyle: TextStyle,
navigationIcon: @Composable () -> Unit,
actions: @Composable RowScope.() -> Unit,
windowInsets: WindowInsets,
colors: TopAppBarColors,
maxHeight: Dp,
pinnedHeight: Dp,
scrollBehavior: TopAppBarScrollBehavior?
) {
if (maxHeight <= pinnedHeight) {
throw IllegalArgumentException(
"A TwoRowsTopAppBar max height should be greater than its pinned height"
)
}
val pinnedHeightPx: Float
val maxHeightPx: Float
val titleBottomPaddingPx: Int
LocalDensity.current.run {
pinnedHeightPx = pinnedHeight.toPx()
maxHeightPx = maxHeight.toPx()
titleBottomPaddingPx = titleBottomPadding.roundToPx()
}
// Sets the app bar's height offset limit to hide just the bottom title area and keep top title
// visible when collapsed.
SideEffect {
if (scrollBehavior?.state?.heightOffsetLimit != pinnedHeightPx - maxHeightPx) {
scrollBehavior?.state?.heightOffsetLimit = pinnedHeightPx - maxHeightPx
}
}
// Obtain the container Color from the TopAppBarColors using the `collapsedFraction`, as the
// bottom part of this TwoRowsTopAppBar changes color at the same rate the app bar expands or
// collapse.
// This will potentially animate or interpolate a transition between the container color and the
// container's scrolled color according to the app bar's scroll state.
val colorTransitionFraction = scrollBehavior?.state?.collapsedFraction ?: 0f
val appBarContainerColor by rememberUpdatedState(colors.containerColor(colorTransitionFraction))
// Wrap the given actions in a Row.
val actionsRow = @Composable {
Row(
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
content = actions
)
}
val topTitleAlpha = TopTitleAlphaEasing.transform(colorTransitionFraction)
val bottomTitleAlpha = 1f - colorTransitionFraction
// Hide the top row title semantics when its alpha value goes below 0.5 threshold.
// Hide the bottom row title semantics when the top title semantics are active.
val hideTopRowSemantics = colorTransitionFraction < 0.5f
val hideBottomRowSemantics = !hideTopRowSemantics
// Set up support for resizing the top app bar when vertically dragging the bar itself.
val appBarDragModifier = if (scrollBehavior != null && !scrollBehavior.isPinned) {
Modifier.draggable(
orientation = Orientation.Vertical,
state = rememberDraggableState { delta ->
scrollBehavior.state.heightOffset = scrollBehavior.state.heightOffset + delta
},
onDragStopped = { velocity ->
settleAppBar(
scrollBehavior.state,
velocity,
scrollBehavior.flingAnimationSpec,
scrollBehavior.snapAnimationSpec
)
}
)
} else {
Modifier
}
Surface(modifier = modifier.then(appBarDragModifier), color = appBarContainerColor) {
Column {
TopAppBarLayout(
modifier = Modifier
.windowInsetsPadding(windowInsets)
// clip after padding so we don't show the title over the inset area
.clipToBounds(),
heightPx = pinnedHeightPx,
navigationIconContentColor =
colors.navigationIconContentColor,
titleContentColor = colors.titleContentColor,
actionIconContentColor =
colors.actionIconContentColor,
title = smallTitle,
titleTextStyle = smallTitleTextStyle,
titleAlpha = topTitleAlpha,
titleVerticalArrangement = Arrangement.Center,
titleHorizontalArrangement = Arrangement.Start,
titleBottomPadding = 0,
hideTitleSemantics = hideTopRowSemantics,
navigationIcon = navigationIcon,
actions = actionsRow,
)
TopAppBarLayout(
modifier = Modifier.clipToBounds(),
heightPx = maxHeightPx - pinnedHeightPx + (scrollBehavior?.state?.heightOffset
?: 0f),
navigationIconContentColor =
colors.navigationIconContentColor,
titleContentColor = colors.titleContentColor,
actionIconContentColor =
colors.actionIconContentColor,
title = title,
titleTextStyle = titleTextStyle,
titleAlpha = bottomTitleAlpha,
titleVerticalArrangement = Arrangement.Bottom,
titleHorizontalArrangement = Arrangement.Start,
titleBottomPadding = titleBottomPaddingPx,
hideTitleSemantics = hideBottomRowSemantics,
navigationIcon = {},
actions = {}
)
}
}
}
/**
* The base [Layout] for all top app bars. This function lays out a top app bar navigation icon
* (leading icon), a title (header), and action icons (trailing icons). Note that the navigation and
* the actions are optional.
*
* @param heightPx the total height this layout is capped to
* @param navigationIconContentColor the content color that will be applied via a
* [LocalContentColor] when composing the navigation icon
* @param titleContentColor the color that will be applied via a [LocalContentColor] when composing
* the title
* @param actionIconContentColor the content color that will be applied via a [LocalContentColor]
* when composing the action icons
* @param title the top app bar title (header)
* @param titleTextStyle the title's text style
* @param modifier a [Modifier]
* @param titleAlpha the title's alpha
* @param titleVerticalArrangement the title's vertical arrangement
* @param titleHorizontalArrangement the title's horizontal arrangement
* @param titleBottomPadding the title's bottom padding
* @param hideTitleSemantics hides the title node from the semantic tree. Apply this
* boolean when this layout is part of a [TwoRowsTopAppBar] to hide the title's semantics
* from accessibility services. This is needed to avoid having multiple titles visible to
* accessibility services at the same time, when animating between collapsed / expanded states.
* @param navigationIcon a navigation icon [Composable]
* @param actions actions [Composable]
*/
@Composable
private fun TopAppBarLayout(
modifier: Modifier,
heightPx: Float,
navigationIconContentColor: Color,
titleContentColor: Color,
actionIconContentColor: Color,
title: @Composable () -> Unit,
titleTextStyle: TextStyle,
titleAlpha: Float,
titleVerticalArrangement: Arrangement.Vertical,
titleHorizontalArrangement: Arrangement.Horizontal,
titleBottomPadding: Int,
hideTitleSemantics: Boolean,
navigationIcon: @Composable () -> Unit,
actions: @Composable () -> Unit,
) {
Layout(
{
Box(
Modifier
.layoutId("navigationIcon")
.padding(start = TopAppBarHorizontalPadding)
) {
CompositionLocalProvider(
LocalContentColor provides navigationIconContentColor,
content = navigationIcon
)
}
Box(
Modifier
.layoutId("title")
.padding(horizontal = TopAppBarHorizontalPadding)
.then(if (hideTitleSemantics) Modifier.clearAndSetSemantics { } else Modifier)
.graphicsLayer(alpha = titleAlpha)
) {
ProvideTextStyle(value = titleTextStyle) {
CompositionLocalProvider(
LocalContentColor provides titleContentColor,
content = title
)
}
}
Box(
Modifier
.layoutId("actionIcons")
.padding(end = TopAppBarHorizontalPadding)
) {
CompositionLocalProvider(
LocalContentColor provides actionIconContentColor,
content = actions
)
}
},
modifier = modifier
) { measurables, constraints ->
val navigationIconPlaceable =
measurables.first { it.layoutId == "navigationIcon" }
.measure(constraints.copy(minWidth = 0))
val actionIconsPlaceable =
measurables.first { it.layoutId == "actionIcons" }
.measure(constraints.copy(minWidth = 0))
val maxTitleWidth = if (constraints.maxWidth == Constraints.Infinity) {
constraints.maxWidth
} else {
(constraints.maxWidth - navigationIconPlaceable.width - actionIconsPlaceable.width)
.coerceAtLeast(0)
}
val titlePlaceable =
measurables.first { it.layoutId == "title" }
.measure(constraints.copy(minWidth = 0, maxWidth = maxTitleWidth))
// Locate the title's baseline.
val titleBaseline =
if (titlePlaceable[LastBaseline] != AlignmentLine.Unspecified) {
titlePlaceable[LastBaseline]
} else {
0
}
val layoutHeight = heightPx.roundToInt()
layout(constraints.maxWidth, layoutHeight) {
// Navigation icon
navigationIconPlaceable.placeRelative(
x = 0,
y = (layoutHeight - navigationIconPlaceable.height) / 2
)
// Title
titlePlaceable.placeRelative(
x = when (titleHorizontalArrangement) {
Arrangement.Center -> (constraints.maxWidth - titlePlaceable.width) / 2
Arrangement.End ->
constraints.maxWidth - titlePlaceable.width - actionIconsPlaceable.width
// Arrangement.Start.
// An TopAppBarTitleInset will make sure the title is offset in case the
// navigation icon is missing.
else -> max(TopAppBarTitleInset.roundToPx(), navigationIconPlaceable.width)
},
y = when (titleVerticalArrangement) {
Arrangement.Center -> (layoutHeight - titlePlaceable.height) / 2
// Apply bottom padding from the title's baseline only when the Arrangement is
// "Bottom".
Arrangement.Bottom ->
if (titleBottomPadding == 0) layoutHeight - titlePlaceable.height
else layoutHeight - titlePlaceable.height - max(
0,
titleBottomPadding - titlePlaceable.height + titleBaseline
)
// Arrangement.Top
else -> 0
}
)
// Action icons
actionIconsPlaceable.placeRelative(
x = constraints.maxWidth - actionIconsPlaceable.width,
y = (layoutHeight - actionIconsPlaceable.height) / 2
)
}
}
}
/**
* Returns a [TopAppBarScrollBehavior] that only adjusts its content offset, without adjusting any
* properties that affect the height of a top app bar.
*
* @param state a [TopAppBarState]
* @param canScroll a callback used to determine whether scroll events are to be
* handled by this [PinnedScrollBehavior]
*/
@OptIn(ExperimentalMaterial3Api::class)
private class PinnedScrollBehavior(
override val state: TopAppBarState,
val canScroll: () -> Boolean = { true }
) : TopAppBarScrollBehavior {
override val isPinned: Boolean = true
override val snapAnimationSpec: AnimationSpec<Float>? = null
override val flingAnimationSpec: DecayAnimationSpec<Float>? = null
override var nestedScrollConnection =
object : NestedScrollConnection {
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
if (!canScroll()) return Offset.Zero
if (consumed.y == 0f && available.y > 0f) {
// Reset the total content offset to zero when scrolling all the way down.
// This will eliminate some float precision inaccuracies.
state.contentOffset = 0f
} else {
state.contentOffset += consumed.y
}
return Offset.Zero
}
}
}
/**
* A [TopAppBarScrollBehavior] that adjusts its properties to affect the colors and height of a top
* app bar.
*
* A top app bar that is set up with this [TopAppBarScrollBehavior] will immediately collapse when
* the nested content is pulled up, and will immediately appear when the content is pulled down.
*
* @param state a [TopAppBarState]
* @param snapAnimationSpec an optional [AnimationSpec] that defines how the top app bar snaps to
* either fully collapsed or fully extended state when a fling or a drag scrolled it into an
* intermediate position
* @param flingAnimationSpec an optional [DecayAnimationSpec] that defined how to fling the top app
* bar when the user flings the app bar itself, or the content below it
* @param canScroll a callback used to determine whether scroll events are to be
* handled by this [EnterAlwaysScrollBehavior]
*/
@OptIn(ExperimentalMaterial3Api::class)
private class EnterAlwaysScrollBehavior(
override val state: TopAppBarState,
override val snapAnimationSpec: AnimationSpec<Float>?,
override val flingAnimationSpec: DecayAnimationSpec<Float>?,
val canScroll: () -> Boolean = { true }
) : TopAppBarScrollBehavior {
override val isPinned: Boolean = false
override var nestedScrollConnection =
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (!canScroll()) return Offset.Zero
val prevHeightOffset = state.heightOffset
state.heightOffset = state.heightOffset + available.y
return if (prevHeightOffset != state.heightOffset) {
// We're in the middle of top app bar collapse or expand.
// Consume only the scroll on the Y axis.
available.copy(x = 0f)
} else {
Offset.Zero
}
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
if (!canScroll()) return Offset.Zero
state.contentOffset += consumed.y
if (state.heightOffset == 0f || state.heightOffset == state.heightOffsetLimit) {
if (consumed.y == 0f && available.y > 0f) {
// Reset the total content offset to zero when scrolling all the way down.
// This will eliminate some float precision inaccuracies.
state.contentOffset = 0f
}
}
state.heightOffset = state.heightOffset + consumed.y
return Offset.Zero
}
override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
val superConsumed = super.onPostFling(consumed, available)
return superConsumed + settleAppBar(
state,
available.y,
flingAnimationSpec,
snapAnimationSpec
)
}
}
}
/**
* A [TopAppBarScrollBehavior] that adjusts its properties to affect the colors and height of a top
* app bar.
*
* A top app bar that is set up with this [TopAppBarScrollBehavior] will immediately collapse when
* the nested content is pulled up, and will expand back the collapsed area when the content is
* pulled all the way down.
*
* @param state a [TopAppBarState]
* @param snapAnimationSpec an optional [AnimationSpec] that defines how the top app bar snaps to
* either fully collapsed or fully extended state when a fling or a drag scrolled it into an
* intermediate position
* @param flingAnimationSpec an optional [DecayAnimationSpec] that defined how to fling the top app
* bar when the user flings the app bar itself, or the content below it
* @param canScroll a callback used to determine whether scroll events are to be
* handled by this [ExitUntilCollapsedScrollBehavior]
*/
@OptIn(ExperimentalMaterial3Api::class)
private class ExitUntilCollapsedScrollBehavior(
override val state: TopAppBarState,
override val snapAnimationSpec: AnimationSpec<Float>?,
override val flingAnimationSpec: DecayAnimationSpec<Float>?,
val canScroll: () -> Boolean = { true }
) : TopAppBarScrollBehavior {
override val isPinned: Boolean = false
override var nestedScrollConnection =
object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
// Don't intercept if scrolling down.
if (!canScroll() || available.y > 0f) return Offset.Zero
val prevHeightOffset = state.heightOffset
state.heightOffset = state.heightOffset + available.y
return if (prevHeightOffset != state.heightOffset) {
// We're in the middle of top app bar collapse or expand.
// Consume only the scroll on the Y axis.
available.copy(x = 0f)
} else {
Offset.Zero
}
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
if (!canScroll()) return Offset.Zero
state.contentOffset += consumed.y
if (available.y < 0f || consumed.y < 0f) {
// When scrolling up, just update the state's height offset.
val oldHeightOffset = state.heightOffset
state.heightOffset = state.heightOffset + consumed.y
return Offset(0f, state.heightOffset - oldHeightOffset)
}
if (consumed.y == 0f && available.y > 0) {
// Reset the total content offset to zero when scrolling all the way down. This
// will eliminate some float precision inaccuracies.
state.contentOffset = 0f
}
if (available.y > 0f) {
// Adjust the height offset in case the consumed delta Y is less than what was
// recorded as available delta Y in the pre-scroll.
val oldHeightOffset = state.heightOffset
state.heightOffset = state.heightOffset + available.y
return Offset(0f, state.heightOffset - oldHeightOffset)
}
return Offset.Zero
}
override suspend fun onPostFling(consumed: Velocity, available: Velocity): Velocity {
val superConsumed = super.onPostFling(consumed, available)
return superConsumed + settleAppBar(
state,
available.y,
flingAnimationSpec,
snapAnimationSpec
)
}
}
}
/**
* Settles the app bar by flinging, in case the given velocity is greater than zero, and snapping
* after the fling settles.
*/
@OptIn(ExperimentalMaterial3Api::class)
private suspend fun settleAppBar(
state: TopAppBarState,
velocity: Float,
flingAnimationSpec: DecayAnimationSpec<Float>?,
snapAnimationSpec: AnimationSpec<Float>?
): Velocity {
// Check if the app bar is completely collapsed/expanded. If so, no need to settle the app bar,
// and just return Zero Velocity.
// Note that we don't check for 0f due to float precision with the collapsedFraction
// calculation.
if (state.collapsedFraction < 0.01f || state.collapsedFraction == 1f) {
return Velocity.Zero
}
var remainingVelocity = velocity
// In case there is an initial velocity that was left after a previous user fling, animate to
// continue the motion to expand or collapse the app bar.
if (flingAnimationSpec != null && abs(velocity) > 1f) {
var lastValue = 0f
AnimationState(
initialValue = 0f,
initialVelocity = velocity,
)
.animateDecay(flingAnimationSpec) {
val delta = value - lastValue
val initialHeightOffset = state.heightOffset
state.heightOffset = initialHeightOffset + delta
val consumed = abs(initialHeightOffset - state.heightOffset)
lastValue = value
remainingVelocity = this.velocity
// avoid rounding errors and stop if anything is unconsumed
if (abs(delta - consumed) > 0.5f) this.cancelAnimation()
}
}
// Snap if animation specs were provided.
if (snapAnimationSpec != null) {
if (state.heightOffset < 0 &&
state.heightOffset > state.heightOffsetLimit
) {
AnimationState(initialValue = state.heightOffset).animateTo(
if (state.collapsedFraction < 0.5f) {
0f
} else {
state.heightOffsetLimit
},
animationSpec = snapAnimationSpec
) { state.heightOffset = value }
}
}
return Velocity(0f, remainingVelocity)
}
// An easing function used to compute the alpha value that is applied to the top title part of a
// Medium or Large app bar.
/*@VisibleForTesting*/
internal val TopTitleAlphaEasing = CubicBezierEasing(.8f, 0f, .8f, .15f)
private val MediumTitleBottomPadding = 24.dp
private val LargeTitleBottomPadding = 28.dp
private val TopAppBarHorizontalPadding = 4.dp
// A title inset when the App-Bar is a Medium or Large one. Also used to size a spacer when the
// navigation icon is missing.
private val TopAppBarTitleInset = 16.dp - TopAppBarHorizontalPadding
| apache-2.0 | 89695aa6e6ea70d6db0f12eb8a32ee1c | 43.544907 | 154 | 0.690528 | 5.139082 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/src/git4idea/rebase/interactive/dialog/ChangeEntryStateActions.kt | 2 | 9998 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.rebase.interactive.dialog
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.ui.AnActionButton
import com.intellij.ui.TableUtil
import git4idea.i18n.GitBundle
import git4idea.rebase.GitRebaseEntry
import git4idea.rebase.GitRebaseEntryWithDetails
import git4idea.rebase.interactive.GitRebaseTodoModel
import git4idea.rebase.interactive.convertToEntries
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.util.function.Supplier
import javax.swing.Icon
import javax.swing.JButton
import javax.swing.KeyStroke
private fun getActionShortcutList(actionId: String): List<Shortcut> = KeymapUtil.getActiveKeymapShortcuts(actionId).shortcuts.toList()
private fun findNewRoot(
rebaseTodoModel: GitRebaseTodoModel<*>,
elementIndex: Int
): GitRebaseTodoModel.Element<*>? {
val element = rebaseTodoModel.elements[elementIndex]
return rebaseTodoModel.elements.take(element.index).findLast {
it is GitRebaseTodoModel.Element.UniteRoot ||
(it is GitRebaseTodoModel.Element.Simple && it.type is GitRebaseTodoModel.Type.NonUnite.KeepCommit)
}
}
private fun getIndicesToUnite(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<*>): List<Int>? {
if (rebaseTodoModel.canUnite(selection)) {
return selection
}
val index = selection.singleOrNull() ?: return null
val newRoot = findNewRoot(rebaseTodoModel, index) ?: return null
return (listOf(newRoot.index) + selection).takeIf { rebaseTodoModel.canUnite(it) }
}
internal abstract class ChangeEntryStateSimpleAction(
protected val action: GitRebaseEntry.Action,
title: Supplier<String>,
description: Supplier<String>,
icon: Icon?,
private val table: GitRebaseCommitsTableView,
additionalShortcuts: List<Shortcut> = listOf()
) : AnActionButton(title, description, icon), DumbAware {
constructor(
action: GitRebaseEntry.Action,
icon: Icon?,
table: GitRebaseCommitsTableView,
additionalShortcuts: List<Shortcut> = listOf()
) : this(action, action.visibleName, action.visibleName, icon, table, additionalShortcuts)
init {
val keyStroke = KeyStroke.getKeyStroke(
KeyEvent.getExtendedKeyCodeForChar(action.mnemonic),
InputEvent.ALT_MASK
)
val shortcuts = additionalShortcuts + KeyboardShortcut(keyStroke, null)
shortcutSet = CustomShortcutSet(*shortcuts.toTypedArray())
this.registerCustomShortcutSet(table, null)
}
final override fun actionPerformed(e: AnActionEvent) {
updateModel(::performEntryAction)
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun updateButton(e: AnActionEvent) {
val hasSelection = table.editingRow == -1 && table.selectedRowCount != 0
e.presentation.isEnabled = hasSelection && isEntryActionEnabled(table.selectedRows.toList(), table.model.rebaseTodoModel)
}
protected abstract fun performEntryAction(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<out GitRebaseEntryWithDetails>)
protected abstract fun isEntryActionEnabled(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<*>): Boolean
private fun updateModel(f: (List<Int>, GitRebaseTodoModel<out GitRebaseEntryWithDetails>) -> Unit) {
val model = table.model
val selectedRows = table.selectedRows.toList()
val selectedEntries = selectedRows.map { model.getEntry(it) }
table.model.updateModel { rebaseTodoModel ->
f(selectedRows, rebaseTodoModel)
}
restoreSelection(selectedEntries)
}
private fun restoreSelection(selectedEntries: List<GitRebaseEntry>) {
val selectedEntriesSet = selectedEntries.toSet()
val newSelection = mutableListOf<Int>()
table.model.rebaseTodoModel.elements.forEachIndexed { index, element ->
if (element.entry in selectedEntriesSet) {
newSelection.add(index)
}
}
TableUtil.selectRows(table, newSelection.toIntArray())
}
protected fun reword(row: Int) {
TableUtil.selectRows(table, intArrayOf(row))
TableUtil.editCellAt(table, row, GitRebaseCommitsTableModel.SUBJECT_COLUMN)
}
}
internal abstract class ChangeEntryStateButtonAction(
action: GitRebaseEntry.Action,
table: GitRebaseCommitsTableView,
additionalShortcuts: List<Shortcut> = listOf()
) : ChangeEntryStateSimpleAction(action, null, table, additionalShortcuts), CustomComponentAction, DumbAware {
protected val button = object : JButton(action.visibleName.get()) {
init {
adjustForToolbar()
addActionListener {
val dataContext = ActionToolbar.getDataContextFor(this)
actionPerformed(
AnActionEvent.createFromAnAction(this@ChangeEntryStateButtonAction, null, GitInteractiveRebaseDialog.PLACE, dataContext)
)
}
mnemonic = action.mnemonic
}
}
private val buttonPanel = button.withLeftToolbarBorder()
override fun updateButton(e: AnActionEvent) {
super.updateButton(e)
button.isEnabled = e.presentation.isEnabled
}
override fun createCustomComponent(presentation: Presentation, place: String) = buttonPanel
}
internal class FixupAction(table: GitRebaseCommitsTableView) : ChangeEntryStateSimpleAction(GitRebaseEntry.Action.FIXUP, null, table) {
override fun isEntryActionEnabled(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<*>) =
getIndicesToUnite(selection, rebaseTodoModel) != null
override fun performEntryAction(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<out GitRebaseEntryWithDetails>) {
rebaseTodoModel.unite(getIndicesToUnite(selection, rebaseTodoModel)!!)
}
}
// squash = reword + fixup
internal class SquashAction(private val table: GitRebaseCommitsTableView) :
ChangeEntryStateSimpleAction(GitRebaseEntry.Action.SQUASH, null, table) {
override fun isEntryActionEnabled(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<*>) =
getIndicesToUnite(selection, rebaseTodoModel) != null
override fun performEntryAction(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<out GitRebaseEntryWithDetails>) {
val indicesToUnite = getIndicesToUnite(selection, rebaseTodoModel)!!
val currentRoot = indicesToUnite.firstOrNull()?.let { rebaseTodoModel.elements[it] }?.let { element ->
when (element) {
is GitRebaseTodoModel.Element.UniteRoot -> element
is GitRebaseTodoModel.Element.UniteChild -> element.root
is GitRebaseTodoModel.Element.Simple -> null
}
}
val currentChildrenCount = currentRoot?.children?.size
val root = rebaseTodoModel.unite(indicesToUnite)
if (currentRoot != null) {
// added commits to already squashed
val newChildren = root.children.drop(currentChildrenCount!!)
val model = table.model
rebaseTodoModel.reword(
root.index,
(listOf(root) + newChildren).joinToString("\n".repeat(3)) { model.getCommitMessage(it.index) }
)
}
else {
rebaseTodoModel.reword(root.index, root.getUnitedCommitMessage { it.commitDetails.fullMessage })
}
reword(root.index)
}
}
internal class RewordAction(table: GitRebaseCommitsTableView) :
ChangeEntryStateButtonAction(GitRebaseEntry.Action.REWORD, table, getActionShortcutList("Git.Reword.Commit")) {
override fun isEntryActionEnabled(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<*>) =
selection.size == 1 && rebaseTodoModel.canReword(selection.single())
override fun performEntryAction(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<out GitRebaseEntryWithDetails>) {
reword(selection.single())
}
}
internal class PickAction(table: GitRebaseCommitsTableView) :
ChangeEntryStateSimpleAction(GitRebaseEntry.Action.PICK, AllIcons.Actions.Rollback, table) {
override fun isEntryActionEnabled(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<*>) = rebaseTodoModel.canPick(selection)
override fun performEntryAction(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<out GitRebaseEntryWithDetails>) {
rebaseTodoModel.pick(selection)
}
}
internal class EditAction(table: GitRebaseCommitsTableView) :
ChangeEntryStateSimpleAction(
GitRebaseEntry.Action.EDIT,
GitBundle.messagePointer("rebase.interactive.dialog.stop.to.edit.text"),
GitBundle.messagePointer("rebase.interactive.dialog.stop.to.edit.text"),
AllIcons.Actions.Pause,
table
) {
override fun isEntryActionEnabled(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<*>) = rebaseTodoModel.canEdit(selection)
override fun performEntryAction(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<out GitRebaseEntryWithDetails>) {
rebaseTodoModel.edit(selection)
}
}
internal class DropAction(table: GitRebaseCommitsTableView) :
ChangeEntryStateButtonAction(GitRebaseEntry.Action.DROP, table, getActionShortcutList(IdeActions.ACTION_DELETE)) {
override fun isEntryActionEnabled(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<*>) = rebaseTodoModel.canDrop(selection)
override fun performEntryAction(selection: List<Int>, rebaseTodoModel: GitRebaseTodoModel<out GitRebaseEntryWithDetails>) {
rebaseTodoModel.drop(selection)
}
}
internal class ShowGitRebaseCommandsDialog(private val project: Project, private val table: GitRebaseCommitsTableView) :
DumbAwareAction(GitBundle.messagePointer("rebase.interactive.dialog.view.git.commands.text")) {
private fun getEntries(): List<GitRebaseEntry> = table.model.rebaseTodoModel.convertToEntries()
override fun actionPerformed(e: AnActionEvent) {
val dialog = GitRebaseCommandsDialog(project, getEntries())
dialog.show()
}
} | apache-2.0 | 51e2a72c9b5d6039c3e4280faaf4e219 | 40.148148 | 140 | 0.774055 | 4.377408 | false | false | false | false |
GunoH/intellij-community | plugins/completion-ml-ranking/src/com/intellij/completion/ml/storage/MutableLookupStorage.kt | 4 | 7082 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.storage
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.ml.ContextFeatures
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.ml.experiment.ExperimentStatus
import com.intellij.completion.ml.features.ContextFeaturesStorage
import com.intellij.completion.ml.performance.MLCompletionPerformanceTracker
import com.intellij.completion.ml.personalization.UserFactorStorage
import com.intellij.completion.ml.personalization.UserFactorsManager
import com.intellij.completion.ml.personalization.session.LookupSessionFactorsStorage
import com.intellij.completion.ml.sorting.RankingModelWrapper
import com.intellij.completion.ml.sorting.RankingSupport
import com.intellij.completion.ml.util.idString
import com.intellij.lang.Language
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.UserDataHolderBase
import org.jetbrains.annotations.TestOnly
class MutableLookupStorage(
override val startedTimestamp: Long,
override val language: Language,
override val model: RankingModelWrapper?)
: LookupStorage {
private var _userFactors: Map<String, String>? = null
override val userFactors: Map<String, String>
get() = _userFactors ?: emptyMap()
private var contextFeaturesStorage: ContextFeatures? = null
override val contextFactors: Map<String, String>
get() = contextFeaturesStorage?.asMap() ?: emptyMap()
private var mlUsed: Boolean = false
private var shouldReRank = model != null
private var _loggingEnabled: Boolean = false
override val performanceTracker: MLCompletionPerformanceTracker = MLCompletionPerformanceTracker()
companion object {
private val LOG = logger<MutableLookupStorage>()
private val LOOKUP_STORAGE = Key.create<MutableLookupStorage>("completion.ml.lookup.storage")
@Volatile
private var alwaysComputeFeaturesInTests = true
@TestOnly
fun setComputeFeaturesAlways(value: Boolean, parentDisposable: Disposable) {
val valueBefore = alwaysComputeFeaturesInTests
alwaysComputeFeaturesInTests = value
Disposer.register(parentDisposable, Disposable {
alwaysComputeFeaturesInTests = valueBefore
})
}
fun get(lookup: LookupImpl): MutableLookupStorage? {
return lookup.getUserData(LOOKUP_STORAGE)
}
fun initOrGetLookupStorage(lookup: LookupImpl, language: Language): MutableLookupStorage {
val existed = get(lookup)
if (existed != null) return existed
val storage = MutableLookupStorage(System.currentTimeMillis(), language, RankingSupport.getRankingModel(language))
lookup.putUserData(LOOKUP_STORAGE, storage)
return storage
}
fun get(parameters: CompletionParameters): MutableLookupStorage? {
var storage = parameters.getUserData(LOOKUP_STORAGE)
if (storage == null) {
val activeLookup = LookupManager.getActiveLookup(parameters.editor) as? LookupImpl
if (activeLookup != null) {
storage = get(activeLookup)
if (storage != null) {
LOG.debug("Can't get storage from parameters. Fallback to storage from active lookup")
saveAsUserData(parameters, storage)
}
}
}
return storage
}
fun saveAsUserData(parameters: CompletionParameters, storage: MutableLookupStorage) {
val completionProcess = parameters.process
if (completionProcess is UserDataHolder) {
completionProcess.putUserData(LOOKUP_STORAGE, storage)
}
}
private fun <T> CompletionParameters.getUserData(key: Key<T>): T? {
return (process as? UserDataHolder)?.getUserData(key)
}
}
override val sessionFactors: LookupSessionFactorsStorage = LookupSessionFactorsStorage(startedTimestamp)
private val item2storage: MutableMap<String, MutableElementStorage> = mutableMapOf()
override fun getItemStorage(id: String): MutableElementStorage = item2storage.computeIfAbsent(id) {
MutableElementStorage()
}
override fun mlUsed(): Boolean = mlUsed
fun fireReorderedUsingMLScores() {
mlUsed = true
performanceTracker.reorderedByML()
}
override fun shouldComputeFeatures(): Boolean = shouldReRank() ||
(ApplicationManager.getApplication().isUnitTestMode && alwaysComputeFeaturesInTests) ||
(_loggingEnabled && !experimentWithoutComputingFeatures())
override fun shouldReRank(): Boolean = model != null && shouldReRank
fun disableReRanking() {
shouldReRank = false
}
fun isContextFactorsInitialized(): Boolean = contextFeaturesStorage != null
fun fireElementScored(element: LookupElement, factors: MutableMap<String, Any>, mlScore: Double?) {
getItemStorage(element.idString()).fireElementScored(factors, mlScore)
}
fun initUserFactors(project: Project) {
ApplicationManager.getApplication().assertIsDispatchThread()
if (_userFactors == null && UserFactorsManager.ENABLE_USER_FACTORS) {
val userFactorValues = mutableMapOf<String, String>()
val userFactors = UserFactorsManager.getInstance().getAllFactors()
val applicationStorage: UserFactorStorage = UserFactorStorage.getInstance()
val projectStorage: UserFactorStorage = UserFactorStorage.getInstance(project)
for (factor in userFactors) {
factor.compute(applicationStorage)?.let { userFactorValues["${factor.id}:App"] = it }
factor.compute(projectStorage)?.let { userFactorValues["${factor.id}:Project"] = it }
}
_userFactors = userFactorValues
}
}
override fun contextProvidersResult(): ContextFeatures = contextFeaturesStorage ?: ContextFeaturesStorage.EMPTY
fun initContextFactors(contextFactors: MutableMap<String, MLFeatureValue>,
environment: UserDataHolderBase) {
if (isContextFactorsInitialized()) {
LOG.error("Context factors should be initialized only once")
}
else {
val features = ContextFeaturesStorage(contextFactors)
environment.copyUserDataTo(features)
contextFeaturesStorage = features
}
}
private fun experimentWithoutComputingFeatures(): Boolean {
val experimentInfo = ExperimentStatus.getInstance().forLanguage(language)
if (experimentInfo.inExperiment) {
return !experimentInfo.shouldCalculateFeatures
}
return false
}
fun markLoggingEnabled() {
_loggingEnabled = true
}
} | apache-2.0 | 466adb6425e5259726a6d1264518c556 | 39.474286 | 140 | 0.749223 | 4.860673 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/live-templates-shared/src/org/jetbrains/kotlin/idea/liveTemplates/macro/FunctionParametersMacro.kt | 4 | 1447 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.liveTemplates.macro
import com.intellij.codeInsight.template.*
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.psi.KtFunction
import java.util.*
class FunctionParametersMacro : KotlinMacro() {
override fun getName() = "functionParameters"
override fun getPresentableName() = "functionParameters()"
override fun calculateResult(params: Array<Expression>, context: ExpressionContext): Result? {
val project = context.project
val templateStartOffset = context.templateStartOffset
val offset = if (templateStartOffset > 0) context.templateStartOffset - 1 else context.templateStartOffset
PsiDocumentManager.getInstance(project).commitAllDocuments()
val file = PsiDocumentManager.getInstance(project).getPsiFile(context.editor!!.document) ?: return null
var place = file.findElementAt(offset)
while (place != null) {
if (place is KtFunction) {
val result = ArrayList<Result>()
for (param in place.valueParameters) {
result.add(TextResult(param.name!!))
}
return ListResult(result)
}
place = place.parent
}
return null
}
}
| apache-2.0 | f710510e3cb4991e9e9d0ad7f230e50a | 40.342857 | 158 | 0.68141 | 5.024306 | false | true | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/viewholders/SimpleLinkViewHolder.kt | 1 | 5281 | package io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Link
import io.github.feelfreelinux.wykopmobilny.ui.fragments.links.LinkActionListener
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import io.github.feelfreelinux.wykopmobilny.utils.loadImage
import io.github.feelfreelinux.wykopmobilny.utils.preferences.LinksPreferences
import io.github.feelfreelinux.wykopmobilny.utils.preferences.SettingsPreferencesApi
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.simple_link_layout.*
class SimpleLinkViewHolder(
override val containerView: View,
val settingsApi: SettingsPreferencesApi,
val navigatorApi: NewNavigatorApi,
val userManagerApi: UserManagerApi,
private val linkActionListener: LinkActionListener
) : RecyclableViewHolder(containerView), LayoutContainer {
companion object {
const val ALPHA_NEW = 1f
const val ALPHA_VISITED = 0.6f
const val TYPE_SIMPLE_LINK = 77
const val TYPE_BLOCKED = 78
/**
* Inflates correct view (with embed, survey or both) depending on viewType
*/
fun inflateView(
parent: ViewGroup,
userManagerApi: UserManagerApi,
settingsPreferencesApi: SettingsPreferencesApi,
navigatorApi: NewNavigatorApi,
linkActionListener: LinkActionListener
): SimpleLinkViewHolder {
return SimpleLinkViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.simple_link_layout, parent, false),
settingsPreferencesApi,
navigatorApi,
userManagerApi,
linkActionListener
)
}
fun getViewTypeForLink(link: Link): Int {
return if (link.isBlocked) TYPE_BLOCKED
else TYPE_SIMPLE_LINK
}
}
private val linkPreferences by lazy { LinksPreferences(containerView.context) }
private val digCountDrawable by lazy {
val typedArray = containerView.context.obtainStyledAttributes(
arrayOf(
R.attr.digCountDrawable
).toIntArray()
)
val selectedDrawable = typedArray.getDrawable(0)
typedArray.recycle()
selectedDrawable
}
fun bindView(link: Link) {
setupBody(link)
}
private fun setupBody(link: Link) {
if (link.gotSelected) {
setWidgetAlpha(ALPHA_VISITED)
} else {
setWidgetAlpha(ALPHA_NEW)
}
when (link.userVote) {
"dig" -> showDigged(link)
"bury" -> showBurried(link)
else -> showUnvoted(link)
}
simple_digg_count.text = link.voteCount.toString()
simple_title.text = link.title
hotBadgeStripSimple.isVisible = link.isHot
simple_digg_hot.isVisible = link.isHot
simple_image.isVisible = link.preview != null && settingsApi.linkShowImage
if (settingsApi.linkShowImage) {
link.preview?.let { simple_image.loadImage(link.preview) }
}
containerView.setOnClickListener {
navigatorApi.openLinkDetailsActivity(link)
if (!link.gotSelected) {
setWidgetAlpha(ALPHA_VISITED)
link.gotSelected = true
linkPreferences.readLinksIds = linkPreferences.readLinksIds.plusElement("link_${link.id}")
}
}
}
private fun showBurried(link: Link) {
link.userVote = "bury"
simple_digg.isEnabled = true
simple_digg.background = ContextCompat.getDrawable(containerView.context, R.drawable.ic_frame_votes_buried)
simple_digg.setOnClickListener {
userManagerApi.runIfLoggedIn(containerView.context) {
simple_digg.isEnabled = false
linkActionListener.removeVote(link)
}
}
}
private fun showDigged(link: Link) {
link.userVote = "dig"
simple_digg.isEnabled = true
simple_digg.background = ContextCompat.getDrawable(containerView.context, R.drawable.ic_frame_votes_digged)
simple_digg.setOnClickListener {
userManagerApi.runIfLoggedIn(containerView.context) {
simple_digg.isEnabled = false
linkActionListener.removeVote(link)
}
}
}
private fun showUnvoted(link: Link) {
link.userVote = null
simple_digg.isEnabled = true
simple_digg.background = digCountDrawable
simple_digg.setOnClickListener {
userManagerApi.runIfLoggedIn(containerView.context) {
simple_digg.isEnabled = false
linkActionListener.dig(link)
}
}
}
private fun setWidgetAlpha(alpha: Float) {
simple_image.alpha = alpha
simple_title.alpha = alpha
}
} | mit | 935dc82290414fb060883dea3de2b1c1 | 35.178082 | 115 | 0.658587 | 4.761948 | false | false | false | false |
siosio/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/SwitcherActions.kt | 1 | 8115 | // 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.ide.actions
import com.intellij.featureStatistics.FeatureUsageTracker
import com.intellij.ide.IdeBundle.message
import com.intellij.ide.actions.Switcher.SwitcherPanel
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.DumbAwareToggleAction
import com.intellij.util.BitUtil.isSet
import java.awt.event.*
import java.util.function.Consumer
import javax.swing.AbstractAction
import javax.swing.JList
import javax.swing.KeyStroke
private fun forward(event: AnActionEvent) = true != event.inputEvent?.isShiftDown
internal class ShowSwitcherForwardAction : BaseSwitcherAction(true)
internal class ShowSwitcherBackwardAction : BaseSwitcherAction(false)
internal abstract class BaseSwitcherAction(val forward: Boolean?) : DumbAwareAction() {
override fun update(event: AnActionEvent) {
event.presentation.isEnabled = event.project != null
event.presentation.isVisible = forward == null
}
override fun actionPerformed(event: AnActionEvent) {
val project = event.project ?: return
val switcher = Switcher.SWITCHER_KEY.get(project)
if (switcher != null && (!switcher.recent || forward != null)) {
switcher.go(forward ?: forward(event))
}
else {
FeatureUsageTracker.getInstance().triggerFeatureUsed("switcher")
SwitcherPanel(project, message("window.title.switcher"), event.inputEvent, null, forward ?: forward(event))
}
}
}
internal class ShowRecentFilesAction : LightEditCompatible, BaseRecentFilesAction(false)
internal class ShowRecentlyEditedFilesAction : BaseRecentFilesAction(true)
internal abstract class BaseRecentFilesAction(val onlyEditedFiles: Boolean) : DumbAwareAction() {
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = event.project != null
}
override fun actionPerformed(event: AnActionEvent) {
val project = event.project ?: return
Switcher.SWITCHER_KEY.get(project)?.cbShowOnlyEditedFiles?.apply { isSelected = !isSelected } ?: run {
FeatureUsageTracker.getInstance().triggerFeatureUsed("navigation.recent.files")
SwitcherPanel(project, message("title.popup.recent.files"), null, onlyEditedFiles, true)
}
}
}
internal class SwitcherIterateThroughItemsAction : DumbAwareAction() {
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = Switcher.SWITCHER_KEY.get(event.project) != null
}
override fun actionPerformed(event: AnActionEvent) {
Switcher.SWITCHER_KEY.get(event.project)?.go(forward(event))
}
}
internal class SwitcherToggleOnlyEditedFilesAction : DumbAwareToggleAction() {
private fun getCheckBox(event: AnActionEvent) =
Switcher.SWITCHER_KEY.get(event.project)?.cbShowOnlyEditedFiles
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = getCheckBox(event) != null
}
override fun isSelected(event: AnActionEvent) = getCheckBox(event)?.isSelected ?: false
override fun setSelected(event: AnActionEvent, selected: Boolean) {
getCheckBox(event)?.isSelected = selected
}
}
internal class SwitcherNextProblemAction : SwitcherProblemAction(true)
internal class SwitcherPreviousProblemAction : SwitcherProblemAction(false)
internal abstract class SwitcherProblemAction(val forward: Boolean) : DumbAwareAction() {
private fun getFileList(event: AnActionEvent) =
Switcher.SWITCHER_KEY.get(event.project)?.let { if (it.pinned) it.files else null }
private fun getErrorIndex(list: JList<SwitcherVirtualFile>): Int? {
val model = list.model ?: return null
val size = model.size
if (size <= 0) return null
val range = 0 until size
val start = when (forward) {
true -> list.leadSelectionIndex.let { if (range.first <= it && it < range.last) it + 1 else range.first }
else -> list.leadSelectionIndex.let { if (range.first < it && it <= range.last) it - 1 else range.last }
}
for (i in range) {
val index = when (forward) {
true -> (start + i).let { if (it > range.last) it - size else it }
else -> (start - i).let { if (it < range.first) it + size else it }
}
if (model.getElementAt(index)?.isProblemFile == true) return index
}
return null
}
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = getFileList(event) != null
}
override fun actionPerformed(event: AnActionEvent) {
val list = getFileList(event) ?: return
val index = getErrorIndex(list) ?: return
list.selectedIndex = index
list.ensureIndexIsVisible(index)
}
}
internal class SwitcherListFocusAction(val fromList: JList<*>, val toList: JList<*>, vararg listActionIds: String)
: FocusListener, AbstractAction() {
override fun actionPerformed(event: ActionEvent) {
if (toList.isShowing) toList.requestFocusInWindow()
}
override fun focusLost(event: FocusEvent) = Unit
override fun focusGained(event: FocusEvent) {
val size = toList.model.size
if (size > 0) {
val fromIndex = fromList.selectedIndex
when {
fromIndex >= 0 -> toIndex = fromIndex.coerceAtMost(size - 1)
toIndex < 0 -> toIndex = 0
}
}
}
private var toIndex: Int
get() = toList.selectedIndex
set(index) {
fromList.clearSelection()
toList.selectedIndex = index
toList.ensureIndexIsVisible(index)
}
init {
listActionIds.forEach { fromList.actionMap.put(it, this) }
toList.addFocusListener(this)
toList.addListSelectionListener {
if (!fromList.isSelectionEmpty && !toList.isSelectionEmpty) {
fromList.selectionModel.clearSelection()
}
}
}
}
internal class SwitcherKeyReleaseListener(event: InputEvent?, val consumer: Consumer<InputEvent>) : KeyAdapter() {
private val wasAltDown = true == event?.isAltDown
private val wasAltGraphDown = true == event?.isAltGraphDown
private val wasControlDown = true == event?.isControlDown
private val wasMetaDown = true == event?.isMetaDown
val isEnabled = wasAltDown || wasAltGraphDown || wasControlDown || wasMetaDown
val initialModifiers = if (!isEnabled) null
else StringBuilder().apply {
if (wasAltDown) append("alt ")
if (wasAltGraphDown) append("altGraph ")
if (wasControlDown) append("control ")
if (wasMetaDown) append("meta ")
}.toString()
val forbiddenMnemonic = (event as? KeyEvent)?.keyCode?.let { getMnemonic(it) }
fun getForbiddenMnemonic(keyStroke: KeyStroke) = when {
isSet(keyStroke.modifiers, InputEvent.ALT_DOWN_MASK) != wasAltDown -> null
isSet(keyStroke.modifiers, InputEvent.ALT_GRAPH_DOWN_MASK) != wasAltGraphDown -> null
isSet(keyStroke.modifiers, InputEvent.CTRL_DOWN_MASK) != wasControlDown -> null
isSet(keyStroke.modifiers, InputEvent.META_DOWN_MASK) != wasMetaDown -> null
else -> getMnemonic(keyStroke.keyCode)
}
private fun getMnemonic(keyCode: Int) = when (keyCode) {
in KeyEvent.VK_0..KeyEvent.VK_9 -> keyCode.toChar().toString()
in KeyEvent.VK_A..KeyEvent.VK_Z -> keyCode.toChar().toString()
else -> null
}
fun getShortcuts(vararg keys: String): CustomShortcutSet {
val modifiers = initialModifiers ?: return CustomShortcutSet.fromString(*keys)
val list = mutableListOf<String>()
keys.mapTo(list) { modifiers + it }
keys.mapTo(list) { modifiers + "shift " + it }
return CustomShortcutSet.fromStrings(list)
}
override fun keyReleased(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ALT -> if (wasAltDown) consumer.accept(keyEvent)
KeyEvent.VK_ALT_GRAPH -> if (wasAltGraphDown) consumer.accept(keyEvent)
KeyEvent.VK_CONTROL -> if (wasControlDown) consumer.accept(keyEvent)
KeyEvent.VK_META -> if (wasMetaDown) consumer.accept(keyEvent)
}
}
}
| apache-2.0 | a34a44a802b3ff5630cdfe9393c8fcdb | 37.459716 | 158 | 0.72902 | 4.3676 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/suite/CryptoTestCase.kt | 1 | 2854 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.jsontestsuite.suite
import org.ethereum.crypto.ECIESCoder
import org.ethereum.crypto.ECKey
import org.slf4j.LoggerFactory
import org.spongycastle.util.encoders.Hex
import java.math.BigInteger
/**
* @author Roman Mandeleil
* *
* @since 08.02.2015
*/
class CryptoTestCase {
var decryption_type = ""
var key = ""
var cipher = ""
var payload = ""
fun execute() {
val key = Hex.decode(this.key)
val cipher = Hex.decode(this.cipher)
val ecKey = ECKey.fromPrivate(key)
var resultPayload = ByteArray(0)
if (decryption_type == "aes_ctr")
resultPayload = ecKey.decryptAES(cipher)
if (decryption_type == "ecies_sec1_altered")
try {
resultPayload = ECIESCoder.decrypt(BigInteger(Hex.toHexString(key), 16), cipher)
} catch (e: Throwable) {
e.printStackTrace()
}
if (Hex.toHexString(resultPayload) != payload) {
val error = String.format("payload should be: %s, but got that result: %s ",
payload, Hex.toHexString(resultPayload))
logger.info(error)
System.exit(-1)
}
}
override fun toString(): String {
return "CryptoTestCase{" +
"decryption_type='" + decryption_type + '\'' +
", key='" + key + '\'' +
", cipher='" + cipher + '\'' +
", payload='" + payload + '\'' +
'}'
}
companion object {
private val logger = LoggerFactory.getLogger("TCK-Test")
}
}
| mit | 5ca32341c72f42930aab440fe88ce60d | 31.067416 | 96 | 0.638753 | 4.272455 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/IdeErrorDialogUsageCollector.kt | 10 | 1014 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.diagnostic
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
class IdeErrorDialogUsageCollector : CounterUsagesCollector() {
override fun getGroup() = GROUP
companion object {
private val GROUP = EventLogGroup("ide.error.dialog", 2)
private val CLEAR_ALL = GROUP.registerEvent("clear.all")
private val REPORT = GROUP.registerEvent("report")
private val REPORT_ALL = GROUP.registerEvent("report.all")
private val REPORT_AND_CLEAR_ALL = GROUP.registerEvent("report.and.clear.all")
@JvmStatic
fun logClearAll() = CLEAR_ALL.log()
@JvmStatic
fun logReport() = REPORT.log()
@JvmStatic
fun logReportAll() = REPORT_ALL.log()
@JvmStatic
fun logReportAndClearAll() = REPORT_AND_CLEAR_ALL.log()
}
}
| apache-2.0 | fd075730340c581e52061ea3da115378 | 31.709677 | 140 | 0.737673 | 4.17284 | false | false | false | false |
smmribeiro/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/diff/MutableDiffRequestChainProcessor.kt | 1 | 3812 | // 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.collaboration.ui.codereview.diff
import com.intellij.diff.chains.AsyncDiffRequestChain
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.impl.CacheDiffRequestProcessor
import com.intellij.diff.util.DiffUserDataKeysEx.ScrollToPolicy
import com.intellij.openapi.ListSelection
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.changes.actions.diff.PresentableGoToChangePopupAction
import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain
import kotlin.properties.Delegates
open class MutableDiffRequestChainProcessor(project: Project, chain: DiffRequestChain?) : CacheDiffRequestProcessor.Simple(project) {
private val asyncChangeListener = AsyncDiffRequestChain.Listener {
dropCaches()
currentIndex = (this.chain?.index ?: 0)
updateRequest(true)
}
var chain: DiffRequestChain? by Delegates.observable(null) { _, oldValue, newValue ->
if (oldValue is AsyncDiffRequestChain) {
oldValue.onAssigned(false)
oldValue.removeListener(asyncChangeListener)
}
if (newValue is AsyncDiffRequestChain) {
newValue.onAssigned(true)
// listener should be added after `onAssigned` call to avoid notification about synchronously loaded requests
newValue.addListener(asyncChangeListener, this)
}
currentIndex = newValue?.index ?: 0
updateRequest()
}
private var currentIndex: Int = 0
init {
this.chain = chain
}
override fun onDispose() {
val chain = chain
if (chain is AsyncDiffRequestChain) chain.onAssigned(false)
super.onDispose()
}
override fun getCurrentRequestProvider(): DiffRequestProducer? {
val requests = chain?.requests ?: return null
return if (currentIndex < 0 || currentIndex >= requests.size) null else requests[currentIndex]
}
override fun hasNextChange(fromUpdate: Boolean): Boolean {
val chain = chain ?: return false
return currentIndex < chain.requests.lastIndex
}
override fun hasPrevChange(fromUpdate: Boolean): Boolean {
val chain = chain ?: return false
return currentIndex > 0 && chain.requests.size > 1
}
override fun goToNextChange(fromDifferences: Boolean) {
currentIndex += 1
selectCurrentChange()
updateRequest(false, if (fromDifferences) ScrollToPolicy.FIRST_CHANGE else null)
}
override fun goToPrevChange(fromDifferences: Boolean) {
currentIndex -= 1
selectCurrentChange()
updateRequest(false, if (fromDifferences) ScrollToPolicy.LAST_CHANGE else null)
}
override fun isNavigationEnabled(): Boolean {
val chain = chain ?: return false
return chain.requests.size > 1
}
override fun createGoToChangeAction(): AnAction? {
return MyGoToChangePopupAction()
}
open fun selectFilePath(filePath: FilePath) = Unit
private fun selectCurrentChange() {
val producer = currentRequestProvider as? ChangeDiffRequestChain.Producer ?: return
selectFilePath(producer.filePath)
}
private inner class MyGoToChangePopupAction : PresentableGoToChangePopupAction.Default<ChangeDiffRequestChain.Producer>() {
override fun getChanges(): ListSelection<out ChangeDiffRequestChain.Producer> {
val requests = chain?.requests ?: return ListSelection.empty()
val list = ListSelection.createAt(requests, currentIndex)
return list.map { it as? ChangeDiffRequestChain.Producer }
}
override fun onSelected(change: ChangeDiffRequestChain.Producer) {
selectFilePath(change.filePath)
}
}
}
| apache-2.0 | 539578c6f57f224175c579e9ba4ac0e2 | 34.962264 | 158 | 0.759706 | 4.70037 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/photo/MatrixUtils.kt | 1 | 2261 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.sinyuk.fanfou.ui.photo
import android.graphics.Matrix
import android.graphics.Rect
import android.util.Log
import android.widget.ImageView
/**
* Created by danylo.volokh on 3/14/16.
*
*/
object MatrixUtils {
private val TAG = MatrixUtils::class.java.simpleName
fun getImageMatrix(imageView: ImageView): Matrix? {
Log.v(TAG, "getImageMatrix, imageView " + imageView)
val left = imageView.left
val top = imageView.top
val right = imageView.right
val bottom = imageView.bottom
val bounds = Rect(left, top, right, bottom)
val drawable = imageView.drawable
var matrix: Matrix?
val scaleType = imageView.scaleType
Log.v(TAG, "getImageMatrix, scaleType " + scaleType)
if (scaleType == ImageView.ScaleType.FIT_XY) {
matrix = imageView.imageMatrix
if (!matrix!!.isIdentity) {
matrix = Matrix(matrix)
} else {
val drawableWidth = drawable.intrinsicWidth
val drawableHeight = drawable.intrinsicHeight
if (drawableWidth > 0 && drawableHeight > 0) {
val scaleX = bounds.width().toFloat() / drawableWidth
val scaleY = bounds.height().toFloat() / drawableHeight
matrix = Matrix()
matrix.setScale(scaleX, scaleY)
} else {
matrix = null
}
}
} else {
matrix = Matrix(imageView.imageMatrix)
}
return matrix
}
} | mit | 0878b870069ab94ad87181458e359d85 | 29.567568 | 78 | 0.602831 | 4.407407 | false | false | false | false |
blan4/MangaReader | api/src/main/kotlin/org/seniorsigan/mangareader/sources/readmanga/ReadmangaMangaApiConverter.kt | 1 | 4866 | package org.seniorsigan.mangareader.sources.readmanga
import org.json.JSONArray
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.seniorsigan.mangareader.models.ChapterItem
import org.seniorsigan.mangareader.models.MangaItem
import org.seniorsigan.mangareader.models.PageItem
import org.slf4j.LoggerFactory
import java.net.URI
import java.util.regex.Pattern
class ReadmangaMangaApiConverter {
private val log = LoggerFactory.getLogger(ReadmangaMangaApiConverter::class.java)
/**
* Parses list of manga items such as search, popular, etc.
*/
fun parseList(data: String?, baseURL: URI): List<MangaItem> {
if (data == null) return emptyList()
val doc = Jsoup.parse(data)
val elements = doc.select(".tiles .tile")
return elements.toList().mapIndexed { i, el ->
val img = el.select(".img img").first().attr("src")
val title = el.select(".desc h3 a").first().text()
val url = baseURL.resolve(el.select(".desc h3 a").first().attr("href"))
MangaItem(coverURL = img, title = title, url = url)
}
}
/**
* Parses manga page and retrieve detailed info about manga
*/
fun parseManga(html: String?, uri: URI): MangaItem? {
if (html == null) return null
try {
val doc = Jsoup.parse(html)
val description = doc.select("#mangaBox > div[itemscope] > meta[itemprop=description]").first().attr("content")
val title = doc.select("#mangaBox > div[itemscope] > meta[itemprop=name]").first().attr("content")
val url = doc.select("#mangaBox > div[itemscope] > meta[itemprop=url]").first().attr("content")
val images = doc.select(".picture-fotorama > img[itemprop=image]").map { it.attr("src") }
return MangaItem(
title = title,
url = URI(url),
coverURL = images.firstOrNull(),
description = description,
coverURLS = images,
chapters = parseChapterList(doc, uri))
} catch (e: Exception) {
log.error("Can't parseManga: ${e.message}", e)
return null
}
}
/**
* Parses manga page and retrieve list of available chapters
*/
fun parseChapterList(html: String?, uri: URI): List<ChapterItem> {
if (html == null) return emptyList()
val doc = Jsoup.parse(html)
return parseChapterList(doc, uri)
}
fun parseChapterList(doc: Document, uri: URI): List<ChapterItem> {
val elements = doc.select(".table tbody tr td a")
return elements.map { el ->
val title = el.text()
val url = uri.resolve(el.attr("href"))
ChapterItem(title = title, url = url)
}
}
/**
* Parses chapter page and retrieve list of pages-images.
*/
fun parseChapter(html: String?): List<PageItem> {
if (html == null) return emptyList()
val data = extract(html) ?: return emptyList()
val doc = Jsoup.parse(html) ?: return emptyList()
val commentsPerPage = doc.select("div.cm").map { el ->
val cn = el.classNames().findLast { name ->
name.startsWith("cm_")
} ?: return@map null
val pageID = cn.substring(3).toIntOrNull() ?: return@map null
Pair(pageID, el)
}.filterNotNull().sortedBy { it.first }.map {
it.second.select("div > span")
.map(Element::ownText)
.filterNotNull()
.map(String::trim)
.filterNot(String::isBlank)
}
val pages = arrayListOf<Page>()
with(JSONArray(data), {
(0..length() - 1)
.map { getJSONArray(it) }
.mapTo(pages) {
Page(
host = it.getString(1),
path = it.getString(0),
item = it.getString(2)
)
}
})
return pages.zip(commentsPerPage).map { pair ->
PageItem(
pictureURL = pair.first.uri,
comments = pair.second
)
}
}
private fun extract(html: String): String? {
val regexp = "\\[\\[(.*?)\\]\\]"
val pattern = Pattern.compile(regexp)
val matcher = pattern.matcher(html)
if (matcher.find()) {
return matcher.group(0)
} else {
return null
}
}
private data class Page(
val host: String,
val path: String,
val item: String
) {
val uri: URI
get() = URI("$host$path$item")
}
} | mit | f5cc96618ef3d79c50623d64e6f8fde3 | 34.014388 | 123 | 0.537402 | 4.415608 | false | false | false | false |
fkorotkov/k8s-kotlin-dsl | DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/batch/v1beta1/ClassBuilders.kt | 1 | 1348 | // GENERATE
package com.fkorotkov.kubernetes.batch.v1beta1
import io.fabric8.kubernetes.api.model.batch.v1beta1.CronJob as v1beta1_CronJob
import io.fabric8.kubernetes.api.model.batch.v1beta1.CronJobList as v1beta1_CronJobList
import io.fabric8.kubernetes.api.model.batch.v1beta1.CronJobSpec as v1beta1_CronJobSpec
import io.fabric8.kubernetes.api.model.batch.v1beta1.CronJobStatus as v1beta1_CronJobStatus
import io.fabric8.kubernetes.api.model.batch.v1beta1.JobTemplateSpec as v1beta1_JobTemplateSpec
fun newCronJob(block : v1beta1_CronJob.() -> Unit = {}): v1beta1_CronJob {
val instance = v1beta1_CronJob()
instance.block()
return instance
}
fun newCronJobList(block : v1beta1_CronJobList.() -> Unit = {}): v1beta1_CronJobList {
val instance = v1beta1_CronJobList()
instance.block()
return instance
}
fun newCronJobSpec(block : v1beta1_CronJobSpec.() -> Unit = {}): v1beta1_CronJobSpec {
val instance = v1beta1_CronJobSpec()
instance.block()
return instance
}
fun newCronJobStatus(block : v1beta1_CronJobStatus.() -> Unit = {}): v1beta1_CronJobStatus {
val instance = v1beta1_CronJobStatus()
instance.block()
return instance
}
fun newJobTemplateSpec(block : v1beta1_JobTemplateSpec.() -> Unit = {}): v1beta1_JobTemplateSpec {
val instance = v1beta1_JobTemplateSpec()
instance.block()
return instance
}
| mit | 2b5228cffa6922791236342a8c6084f4 | 29.636364 | 98 | 0.764837 | 3.142191 | false | false | false | false |
vector-im/vector-android | vector/src/app/java/im/vector/push/fcm/troubleshoot/TestPlayServices.kt | 2 | 2389 | /*
* Copyright 2018 New Vector Ltd
*
* 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 im.vector.push.fcm.troubleshoot
import androidx.fragment.app.Fragment
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import im.vector.R
import im.vector.fragments.troubleshoot.TroubleshootTest
import org.matrix.androidsdk.core.Log
/*
* Check that the play services APK is available an up-to-date. If needed provide quick fix to install it.
*/
class TestPlayServices(val fragment: Fragment) : TroubleshootTest(R.string.settings_troubleshoot_test_play_services_title) {
override fun perform() {
val apiAvailability = GoogleApiAvailability.getInstance()
val resultCode = apiAvailability.isGooglePlayServicesAvailable(fragment.context)
if (resultCode == ConnectionResult.SUCCESS) {
quickFix = null
description = fragment.getString(R.string.settings_troubleshoot_test_play_services_success)
status = TestStatus.SUCCESS
} else {
if (apiAvailability.isUserResolvableError(resultCode)) {
quickFix = object : TroubleshootQuickFix(R.string.settings_troubleshoot_test_play_services_quickfix) {
override fun doFix() {
fragment.activity?.let {
apiAvailability.getErrorDialog(it, resultCode, 9000 /*hey does the magic number*/).show()
}
}
}
Log.e(this::javaClass.name, "Play Services apk error $resultCode -> ${apiAvailability.getErrorString(resultCode)}.")
}
description = fragment.getString(R.string.settings_troubleshoot_test_play_services_failed, apiAvailability.getErrorString(resultCode))
status = TestStatus.FAILED
}
}
}
| apache-2.0 | 99f3606563d5de60421accbce790eb0d | 42.436364 | 146 | 0.690247 | 4.64786 | false | true | false | false |
apioo/psx-schema | tests/Generator/resource/kotlin_complex.kt | 1 | 3609 | /**
* Common properties which can be used at any schema
*/
open class CommonProperties {
var title: String? = null
var description: String? = null
var type: String? = null
var nullable: Boolean? = null
var deprecated: Boolean? = null
var readonly: Boolean? = null
}
open class ScalarProperties {
var format: String? = null
var enum: Any? = null
var default: Any? = null
}
import java.util.HashMap;
/**
* Properties of a schema
*/
open class Properties : HashMap<String, PropertyValue>() {
}
/**
* Properties specific for a container
*/
open class ContainerProperties {
var type: String? = null
}
/**
* Struct specific properties
*/
open class StructProperties {
var properties: Properties? = null
var required: Array<String>? = null
}
/**
* Map specific properties
*/
open class MapProperties {
var additionalProperties: Any? = null
var maxProperties: Int? = null
var minProperties: Int? = null
}
/**
* Array properties
*/
open class ArrayProperties {
var type: String? = null
var items: Any? = null
var maxItems: Int? = null
var minItems: Int? = null
var uniqueItems: Boolean? = null
}
/**
* Boolean properties
*/
open class BooleanProperties {
var type: String? = null
}
/**
* Number properties
*/
open class NumberProperties {
var type: String? = null
var multipleOf: Float? = null
var maximum: Float? = null
var exclusiveMaximum: Boolean? = null
var minimum: Float? = null
var exclusiveMinimum: Boolean? = null
}
/**
* String properties
*/
open class StringProperties {
var type: String? = null
var maxLength: Int? = null
var minLength: Int? = null
var pattern: String? = null
}
import java.util.HashMap;
/**
* An object to hold mappings between payload values and schema names or references
*/
open class DiscriminatorMapping : HashMap<String, String>() {
}
/**
* Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description
*/
open class Discriminator {
var propertyName: String? = null
var mapping: DiscriminatorMapping? = null
}
/**
* An intersection type combines multiple schemas into one
*/
open class AllOfProperties {
var description: String? = null
var allOf: Array<OfValue>? = null
}
/**
* An union type can contain one of the provided schemas
*/
open class OneOfProperties {
var description: String? = null
var discriminator: Discriminator? = null
var oneOf: Array<OfValue>? = null
}
import java.util.HashMap;
open class TemplateProperties : HashMap<String, ReferenceType>() {
}
/**
* Represents a reference to another schema
*/
open class ReferenceType {
var ref: String? = null
var template: TemplateProperties? = null
}
/**
* Represents a generic type
*/
open class GenericType {
var generic: String? = null
}
import java.util.HashMap;
/**
* Schema definitions which can be reused
*/
open class Definitions : HashMap<String, DefinitionValue>() {
}
import java.util.HashMap;
/**
* Contains external definitions which are imported. The imported schemas can be used via the namespace
*/
open class Import : HashMap<String, String>() {
}
/**
* TypeSchema meta schema which describes a TypeSchema
*/
open class TypeSchema {
var import: Import? = null
var title: String? = null
var description: String? = null
var type: String? = null
var definitions: Definitions? = null
var properties: Properties? = null
var required: Array<String>? = null
}
| apache-2.0 | 8a44f6ca318baae8757a74d85162593e | 20.229412 | 163 | 0.683569 | 4.018931 | false | false | false | false |
KrenVpravo/CheckReaction | app/src/main/java/com/two_two/checkreaction/domain/science/colors/ColourShaker.kt | 1 | 1706 | package com.two_two.checkreaction.domain.science.colors
import com.two_two.checkreaction.utils.Constants
import java.util.*
/**
* @author Dmitry Borodin on 2017-01-29.
*/
class ColourShaker() {
val shakedOrder = ArrayList<Int>()
private val setOfIndexes = ArrayList<Int>()
private val random = Random()
fun shake() {
val prevShaked = ArrayList(shakedOrder)
do {
shakedOrder.clear()
generateIndexes()
fillShakedOrder()
} while (shareElementsWithPrevious(prevShaked))
}
private fun shareElementsWithPrevious(prevShaked: ArrayList<Int>): Boolean {
if (prevShaked.isEmpty()) return false
if (prevShaked.size != shakedOrder.size) return false
for (i in 0..shakedOrder.lastIndex) {
if (shakedOrder.get(i) == prevShaked.get(i)) {
//match - we should regenerate list
return true
}
}
return false
}
private fun fillShakedOrder() {
while (setOfIndexes.size > 0) {
val index = random.nextInt(setOfIndexes.size)
val element = setOfIndexes.get(index)
shakedOrder.add(element)
setOfIndexes.removeAt(index)
}
}
private fun generateIndexes() {
setOfIndexes.clear()
for (i in 0..Constants.COLOURS_AVAILABLE_SCIENCE) {
setOfIndexes.add(i)
}
}
fun getShakedIndex(realIndex: Int): Int {
if (shakedOrder.size < realIndex) {
return -1
}
return shakedOrder.get(realIndex)
}
fun getRealIndex(shakedIndex: Int): Int {
return shakedOrder.indexOf(shakedIndex)
}
} | mit | 2b855e094a6a281fdfbef1e52fac5b96 | 26.983607 | 80 | 0.598476 | 4.042654 | false | false | false | false |
jrenner/kotlin-voxel | core/src/main/kotlin/org/jrenner/learngl/Physics.kt | 1 | 1548 | package org.jrenner.learngl
import com.badlogic.gdx.math.Vector3
import org.jrenner.learngl.gameworld.CubeData
import com.badlogic.gdx.math.collision.Ray
import com.badlogic.gdx.math.Intersector
import com.badlogic.gdx.math.collision.BoundingBox
/** returns position correction needed */
object Physics {
private val tmp = Vector3()
private val tmp2 = Vector3()
private val tmp3 = Vector3()
private val tmp4 = Vector3()
private val intersect = Vector3()
private val ray = Ray(tmp, tmp)
private val bbox = BoundingBox()
val rayStart = Vector3()
val rayDir = Vector3()
val rayEnd = Vector3()
fun collision(pos: Vector3): Vector3 {
tmp.setZero()
if (world.hasChunkAt(pos.x, pos.y, pos.z)) {
val center = tmp2.set(world.getCubeAt(pos.x, pos.y, pos.z).getPositionTempVec()).add(0.5f, 0.5f, 0.5f)
val diff = tmp.set(center).sub(pos)
rayStart.set(diff.scl(2f)).add(pos)
rayDir.set(diff)
rayEnd.set(rayDir).scl(10f).add(rayStart)
ray.set(rayStart, rayDir)
bbox.set(tmp3.set(center.x - 0.5f, center.y - 0.5f, center.z - 0.5f),
tmp4.set(center.x + 0.5f, center.y + 0.5f, center.z + 0.5f))
val didHit = Intersector.intersectRayBounds(ray, bbox, intersect)
if (didHit) {
//println("hit: $didHit \t intersection: $intersect")
}
}
return intersect
}
fun update() {
collision(view.camera.position)
}
} | apache-2.0 | 97edb3d375cc7769f91bb92303e812bf | 29.98 | 114 | 0.612403 | 3.293617 | false | false | false | false |
gradle/gradle | .teamcity/src/main/kotlin/promotion/PublishNightlySnapshotFromQuickFeedbackStepPromote.kt | 2 | 1828 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package promotion
import common.VersionedSettingsBranch
import vcsroots.gradlePromotionBranches
class PublishNightlySnapshotFromQuickFeedbackStepPromote(branch: VersionedSettingsBranch) : BasePublishGradleDistribution(
promotedBranch = branch.branchName,
prepTask = branch.prepNightlyTaskName(),
triggerName = "QuickFeedback",
vcsRootId = gradlePromotionBranches,
cleanCheckout = false
) {
init {
id("Promotion_SnapshotFromQuickFeedbackStepPromote")
name = "Nightly Snapshot (from QuickFeedback) - Promote"
description = "Promotes a previously built distribution on this agent on '${branch.branchName}' from Quick Feedback as a new nightly snapshot"
steps {
buildStep(
this@PublishNightlySnapshotFromQuickFeedbackStepPromote.extraParameters,
this@PublishNightlySnapshotFromQuickFeedbackStepPromote.gitUserName,
this@PublishNightlySnapshotFromQuickFeedbackStepPromote.gitUserEmail,
this@PublishNightlySnapshotFromQuickFeedbackStepPromote.triggerName,
branch.prepNightlyTaskName(),
branch.promoteNightlyTaskName()
)
}
}
}
| apache-2.0 | 50fb50c3a327e095eb6f41a3e69c6935 | 39.622222 | 150 | 0.729212 | 5.035813 | false | false | false | false |
marlonlom/timeago | ta_library/src/main/java/com/github/marlonlom/utilities/timeago/TimeAgoMessages.kt | 1 | 3574 | /*
* Copyright (c) 2016, marlonlom
*
* 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.github.marlonlom.utilities.timeago
import java.text.MessageFormat
import java.util.*
/**
* The Class **TimeAgoMessages**. it contains a [ResourceBundle] for
* loading and parsing localized messages related to the 'time ago' time syntax.
*
* Usage:*
*
* 1: Using default Locale:
*
* <pre>
* TimeAgoMessages resources = new TimeAgoMessages.Builder().defaultLocale().build();
* </pre>
*
* 2: Using a specific Locale by language tag:
*
* <pre>
* Locale localeByLanguageTag = Locale.forLanguageTag("es");
* TimeAgoMessages resources = new TimeAgoMessages.Builder().withLocale(localeByLanguageTag).build();
* </pre>
*
*
* *Tip: available languages for messages: spanish (es), english (en), german
* (de), french (fr), italian (it), portuguese (pt) and more...*
*
*
* @author marlonlom
* @version 4.1.0
* @since 1.0.0
*/
class TimeAgoMessages
/**
* Instantiates a new time ago messages.
*/
private constructor() {
/**
* The resource bundle for holding the language messages.
*/
private var bundle: ResourceBundle? = null
/**
* Gets the property value.
*
* @param property the property key
* @return the property value
*/
fun getPropertyValue(property: String): String {
return bundle!!.getString(property)
}
/**
* Gets the property value.
*
* @param property the property key
* @param values the property values
* @return the property value
*/
fun getPropertyValue(property: String, vararg values: Any): String {
val propertyVal = getPropertyValue(property)
return MessageFormat.format(propertyVal, *values)
}
/**
* The Inner Class Builder for *TimeAgoMessages*.
*
* @author marlonlom
*/
class Builder {
/**
* The inner bundle.
*/
private var innerBundle: ResourceBundle? = null
/**
* Builds the TimeAgoMessages instance.
*
* @return the time ago messages instance.
*/
fun build(): TimeAgoMessages {
val resources = TimeAgoMessages()
resources.bundle = this.innerBundle
return resources
}
/**
* Build messages with the default locale.
*
* @return the builder
*/
fun defaultLocale(): Builder {
this.innerBundle = ResourceBundle.getBundle(MESSAGES)
return this
}
/**
* Build messages with the selected locale.
*
* @param locale the locale
* @return the builder
*/
fun withLocale(locale: Locale): Builder {
this.innerBundle = ResourceBundle.getBundle(MESSAGES, locale)
return this
}
}
companion object {
/**
* The property path for MESSAGES.
*/
private const val MESSAGES = "com.github.marlonlom.utilities.timeago.messages"
}
} | apache-2.0 | 83356a44e554d73a013fcdfb0ccfccd6 | 25.481481 | 101 | 0.621433 | 4.342649 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/IEC61131Facade.kt | 1 | 12737 | package edu.kit.iti.formal.automation
import edu.kit.iti.formal.automation.analysis.*
import edu.kit.iti.formal.automation.builtin.BuiltinLoader
import edu.kit.iti.formal.automation.il.IlBody
import edu.kit.iti.formal.automation.parser.IEC61131Lexer
import edu.kit.iti.formal.automation.parser.IEC61131Parser
import edu.kit.iti.formal.automation.parser.IECParseTreeToAST
import edu.kit.iti.formal.automation.plcopenxml.IECXMLFacade
import edu.kit.iti.formal.automation.scope.Scope
import edu.kit.iti.formal.automation.st.StructuredTextPrinter
import edu.kit.iti.formal.automation.st.TranslationSfcToStOld
import edu.kit.iti.formal.automation.st.TranslationSfcToStPipeline
import edu.kit.iti.formal.automation.st.ast.*
import edu.kit.iti.formal.automation.visitors.Visitable
import edu.kit.iti.formal.automation.visitors.findFirstProgram
import edu.kit.iti.formal.automation.visitors.findProgram
import edu.kit.iti.formal.automation.visitors.selectByName
import edu.kit.iti.formal.util.CodeWriter
import edu.kit.iti.formal.util.warn
import org.antlr.v4.runtime.*
import java.io.*
import java.nio.charset.Charset
import java.nio.file.Path
import java.util.stream.Collectors
/**
* IEC61131Facade class.
* @author Alexander Weigl
* @since 27.11.16
*/
object IEC61131Facade {
/**
* Parse the given string into an expression.
*
* @param input an expression in Structured Text
* @return The AST of the Expression
*/
fun expr(input: CharStream): Expression {
val parser = getParser(input)
val ctx = parser.expression()
val expr = ctx.accept(IECParseTreeToAST()) as Expression
parser.errorReporter.throwException()
return expr
}
fun expr(input: String): Expression {
return expr(CharStreams.fromString(input))
}
fun getParser(input: CharStream): IEC61131Parser {
val lexer = IEC61131Lexer(input)
val p = IEC61131Parser(CommonTokenStream(lexer))
p.errorListeners.clear()
p.addErrorListener(p.errorReporter)
return p
}
fun statements(input: CharStream): StatementList {
val parser = getParser(input)
val stmts = parser.statement_list_eof().stBody().accept(IECParseTreeToAST()) as StatementList
parser.errorReporter.throwException()
return stmts
}
fun statements(input: String): StatementList = statements(CharStreams.fromString(input))
fun file(input: CharStream): PouElements {
val parser = getParser(input)
val tle = parser.start().accept(IECParseTreeToAST()) as PouElements
parser.errorReporter.throwException()
return tle
}
fun file(path: Path, tee: File? = null): PouElements {
return if (path.endsWith("xml")) {
val out = IECXMLFacade.extractPLCOpenXml(path)
if (tee != null) {
tee.bufferedWriter().use {
it.write(out)
}
file(tee)
} else {
file(CharStreams.fromString(out, path.toString()))
}
} else
file(CharStreams.fromPath(path))
}
@Throws(IOException::class)
fun file(f: File, teeXmlParser: Boolean = true): PouElements {
return if (f.extension == "xml") {
val out = IECXMLFacade.extractPLCOpenXml(f.absolutePath)
if (teeXmlParser) {
val stfile = File(f.parentFile, f.nameWithoutExtension + ".st")
stfile.bufferedWriter().use {
it.write(out)
}
file(CharStreams.fromFileName(stfile.absolutePath))
} else {
file(CharStreams.fromString(out, f.absolutePath))
}
} else
file(CharStreams.fromFileName(f.absolutePath))
}
fun file(resource: InputStream) = file(CharStreams.fromStream(resource, Charset.defaultCharset()))
fun getParser(s: String): IEC61131Parser {
return getParser(CharStreams.fromString(s))
}
fun resolveDataTypes(elements: PouElements, scope: Scope = Scope.defaultScope()): Scope {
val fdt = RegisterDataTypes(scope)
val rdt = ResolveDataTypes(scope)
//val oo = ResolveOO(scope)
//val rr = ResolveReferences(scope)
elements.accept(EnsureFunctionReturnValue)
elements.accept(fdt)
elements.accept(rdt)
elements.accept(RewriteEnums)
elements.accept(MaintainInitialValues())
//elements.accept(oo)
//elements.accept(rr)
return scope
}
fun resolveDataTypes(scope: Scope = Scope.defaultScope(), vararg elements: Visitable): Scope {
val fdt = RegisterDataTypes(scope)
val rdt = ResolveDataTypes(scope)
//val rr = ResolveReferences(scope)
elements.forEach { it.accept(fdt) }
elements.forEach { it.accept(rdt) }
elements.forEach { it.accept(RewriteEnums) }
elements.forEach { it.accept(MaintainInitialValues()) }
//elements.accept(rr)
return scope
}
fun fileResolve(input: List<CharStream>, builtins: Boolean = false): Pair<PouElements, List<ReporterMessage>> {
val seq = input.parallelStream()
.map { file(it) }
.flatMap { it.stream() }
.collect(Collectors.toList())
val p = PouElements(seq)
if (builtins)
p.addAll(BuiltinLoader.loadDefault())
resolveDataTypes(p)
return p to check(p)
}
fun fileResolve(input: CharStream, builtins: Boolean = false): Pair<PouElements, List<ReporterMessage>> = fileResolve(listOf(input), builtins)
fun fileResolve(input: File, builtins: Boolean = false) = fileResolve(CharStreams.fromFileName(input.absolutePath), builtins)
fun filefr(inputs: List<File>, builtins: Boolean = false) =
fileResolve(inputs.map { CharStreams.fromFileName(it.absolutePath) }, builtins)
/**
*
*/
fun readProgramsWLN(libraryElements: List<File>, programs: List<File>, names: List<String>)
: List<PouExecutable?> {
val selectors = names.map { name ->
{ elements: PouElements -> elements.find { it.name == name } as PouExecutable? }
}
return readProgramsWLS(libraryElements, programs, selectors)
}
/**
* Read programs with support for common libraries and a selection either by name or PROGRAM_DECLARATION
*/
fun readProgramsWLPN(libraryElements: List<File>, programs: List<String>)
: List<PouExecutable?> {
val p = programs.map {
if ('@' in it) {
val a = it.split('@', limit = 2)
a[0] to a[1]
} else {
null to it
}
}
val selectorByType = { elements: PouElements -> elements.findFirstProgram() }
val pfiles = p.map { (_, a) -> File(a) }
val selectors = p.map { (name, _) ->
if (name == null) selectorByType
else selectByName(name)
}
return readProgramsWLS(libraryElements, pfiles, selectors)
}
fun readProgramWLNP(libraryElements: List<File>,
it: String)
: Pair<PouElements, PouExecutable?> {
val (name, path) = if ('@' in it) {
val a = it.split('@', limit = 2)
a[0] to a[1]
} else {
null to it
}
val selectorByType = { elements: PouElements -> elements.findFirstProgram() }
val selector =
if (name == null) selectorByType
else selectByName(name)
return readProgramWLS(libraryElements, File(path), selector)
}
fun readProgramWLS(libraryElements: List<File>,
programs: File,
selectors: (PouElements) -> PouExecutable?)
: Pair<PouElements, PouExecutable?> {
val (elements, error) = filefr(libraryElements + programs)
error.forEach { warn(it.toHuman()) }
return elements to selectors(elements)
}
/**
*
*/
fun readProgramsWLS(libraryElements: List<File>,
programs: List<File>,
selectors: List<(PouElements) -> PouExecutable?>)
: List<PouExecutable?> {
return programs.zip(selectors).map { (it, selector) ->
val (elements, error) = filefr(libraryElements + it)
error.forEach { warn(it.toHuman()) }
selector(elements)
}
}
/**
*
*/
fun readProgramsWLP(libraryElements: List<File>, programs: List<File>): List<PouExecutable?> =
readProgramsWLS(libraryElements, programs,
programs.map { _ -> ::findProgram })
/**
*
*/
fun check(p: PouElements): MutableList<ReporterMessage> {
val r = Reporter()
getCheckers(r).forEach { p.accept(it) }
return r.messages
}
/**
* Return the textual representation of the given AST.
*
* @param ast a [edu.kit.iti.formal.automation.st.ast.Top] object.
* @return a [java.lang.String] object.
*/
fun print(ast: Top, comments: Boolean = true): String {
val sw = StringWriter()
printTo(sw, ast, comments)
return sw.toString()
}
fun printTo(stream: Writer, ast: Top, comments: Boolean = false) {
val stp = StructuredTextPrinter(CodeWriter(stream))
stp.isPrintComments = comments
ast.accept(stp)
}
var useOldSfcTranslator = true
//region translations
fun translateSfcToSt(scope: Scope, sfc: SFCImplementation,
name: String, old: Boolean = useOldSfcTranslator): Pair<TypeDeclarations, StatementList> {
val st = StatementList()
val td = TypeDeclarations()
sfc.networks.forEachIndexed { index, network ->
val element = if (old) TranslationSfcToStOld(network, name, index, scope)
else TranslationSfcToStPipeline(network, name, index, scope)
td.add(element.pipelineData.stateEnumTypeDeclaration)
st.add(element.call())
}
return td to st
}
fun translateSfcToSt(elements: PouElements) {
val t = TranslateSfcToSt()
elements.forEach { it.accept(t) }
elements.add(t.newTypes)
}
fun translateFbd(elements: PouElements) {
elements.forEach { it.accept(TranslateFbdToSt) }
}
//endregion
object InstructionList {
/*
fun getParser(input: Token): IlParser {
return getParser(
CharStreams.fromString(input.text),
ShiftedTokenFactory(input))
}
fun getParser(input: CharStream, position: Position): IlParser {
return getParser(input, ShiftedTokenFactory(position))
}
fun getParser(input: CharStream, tokenFactory: TokenFactory<*>? = null): IlParser {
val lexer = IlLexer(input)
if (tokenFactory != null)
lexer.tokenFactory = tokenFactory
val p = IlParser(CommonTokenStream(lexer))
p.errorListeners.clear()
p.addErrorListener(p.errorReporter)
return p
}
fun parseBody(token: Token): IlBody {
val ctx = getParser(token).ilBody()
return ctx.accept(IlTransformToAst()) as IlBody
}
*/
fun parseBody(token: String): IlBody {
val lexer = IEC61131Lexer(CharStreams.fromString(token))
lexer.pushMode(1)
val parser = IEC61131Parser(CommonTokenStream(lexer))
val ctx = parser.ilBody()
return ctx.accept(IECParseTreeToAST()) as IlBody
}
private class ShiftedTokenFactory(val offset: Int = 0,
val offsetLine: Int = 0,
val offsetChar: Int = 0) : CommonTokenFactory() {
constructor(position: Position) : this(position.offset, position.lineNumber, position.charInLine)
constructor(token: Token) : this(token.startIndex, token.line, token.charPositionInLine)
override fun create(source: org.antlr.v4.runtime.misc.Pair<TokenSource, CharStream>?, type: Int, text: String?, channel: Int, start: Int, stop: Int, line: Int, charPositionInLine: Int): CommonToken {
val token = super.create(source, type, text, channel, start, stop, line, charPositionInLine)
token.startIndex += offset
token.stopIndex += offset
token.charPositionInLine += offsetChar
token.line += offsetLine
return token
}
}
}
}
| gpl-3.0 | 20d35e6c7ffb5c3d0e5a77148ecbe3d0 | 35.495702 | 211 | 0.61184 | 4.235783 | false | false | false | false |
davidluckystar/adventofcode | src/main/java/com/luckystar/advent2020/Advent5.kt | 1 | 916 | package com.luckystar.advent2020
fun main() {
val file = object {}.javaClass.getResource("/2020/input_5.txt").readText()
val tickets = file.split("\r\n")
val data = tickets.map { t ->
val row = Integer.parseInt(t.substring(0, 7).replace("F", "0").replace("B", "1"), 2)
val seat = Integer.parseInt(t.substring(7).replace("R", "1").replace("L", "0"), 2)
Ticket(row, seat)
}
// part 1
val ticketIds = data.map(::toTicketId)
val ticketMax = ticketIds.max()
println(ticketMax)
// part 2
if (ticketMax != null) {
val missingTickets = mutableListOf<Int>()
for (i in 0..ticketMax) {
if (!ticketIds.contains(i)) {
missingTickets.add(i)
}
}
println(missingTickets)
}
}
fun toTicketId(t: Ticket): Int {
return t.row * 8 + t.seat
}
data class Ticket(val row: Int, val seat: Int) | apache-2.0 | 7bb1cce22ebf617bdea51a3ed2f9ca3e | 25.970588 | 92 | 0.568777 | 3.405204 | false | false | false | false |
Fondesa/RecyclerViewDivider | recycler-view-divider/src/test/kotlin/com/fondesa/recyclerviewdivider/drawable/GetDefaultDrawableKtTest.kt | 1 | 3615 | /*
* Copyright (c) 2020 Giorgio Antonioli
*
* 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.fondesa.recyclerviewdivider.drawable
import android.graphics.drawable.ColorDrawable
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.fondesa.recyclerviewdivider.test.R
import com.fondesa.recyclerviewdivider.test.ThemeTestActivity
import com.fondesa.recyclerviewdivider.test.assertEqualDrawables
import com.fondesa.recyclerviewdivider.test.context
import com.fondesa.recyclerviewdivider.test.launchThemeActivity
import com.fondesa.recyclerviewdivider.test.letActivity
import org.junit.After
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
/**
* Tests of GetDefaultDrawable.kt file.
*/
@RunWith(AndroidJUnit4::class)
class GetDefaultDrawableKtTest {
private lateinit var scenario: ActivityScenario<ThemeTestActivity>
@After
fun destroyScenario() {
if (::scenario.isInitialized) {
scenario.close()
}
}
@Test
fun `transparentDrawable - returns transparent ColorDrawable`() {
val drawable = transparentDrawable()
assertEqualDrawables(transparentDrawable(), drawable)
}
@Test
fun `getThemeDrawable - no attrs in the theme - returns null`() {
scenario = launchThemeActivity(R.style.TestTheme_NullAndroidListDivider)
val drawable = scenario.letActivity { it.getThemeDrawable() }
assertNull(drawable)
}
@Test
fun `getThemeDrawable - listDivider in theme - returns listDivider value`() {
scenario = launchThemeActivity(R.style.TestTheme_OnlyAndroidListDivider)
@ColorInt val expectedColor = ContextCompat.getColor(context, R.color.test_androidListDivider)
val drawable = scenario.letActivity { it.getThemeDrawable() }
assertNotNull(drawable)
assertEqualDrawables(ColorDrawable(expectedColor), drawable)
}
@Test
fun `getThemeDrawable - recyclerViewDividerDrawable in theme - returns recyclerViewDividerDrawable value`() {
scenario = launchThemeActivity(R.style.TestTheme_OnlyDrawable)
@ColorInt val expectedColor = ContextCompat.getColor(context, R.color.test_recyclerViewDividerDrawable)
val drawable = scenario.letActivity { it.getThemeDrawable() }
assertNotNull(drawable)
assertEqualDrawables(ColorDrawable(expectedColor), drawable)
}
@Test
fun `getThemeDrawable - listDivider and recyclerViewDividerDrawable in theme - returns recyclerViewDividerDrawable value`() {
scenario = launchThemeActivity(R.style.TestTheme_AndroidListDividerAndDrawable)
@ColorInt val expectedColor = ContextCompat.getColor(context, R.color.test_recyclerViewDividerDrawable)
val drawable = scenario.letActivity { it.getThemeDrawable() }
assertNotNull(drawable)
assertEqualDrawables(ColorDrawable(expectedColor), drawable)
}
}
| apache-2.0 | b40a66e3f2c5882200ebd0e95dafd742 | 35.887755 | 129 | 0.75491 | 4.750329 | false | true | false | false |
lvtanxi/TanxiNote | app/src/main/java/com/lv/note/widget/selectpop/SelectPopupWindow.kt | 1 | 6668 | package com.lv.note.widget.selectpop
import android.app.Activity
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.support.v4.content.ContextCompat
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup.LayoutParams
import android.widget.*
import com.lv.note.R
import com.lv.test.ArrayUtils
import com.lv.test.StrUtils
import java.util.*
/**
* User: 吕勇
* Date: 2015-11-17
* Time: 11:51
* Description:选择PopupWindow(后期如果item太多了,可换成ListView处理)
*/
abstract class SelectPopupWindow<T : ExtendItem>(private val mContext: Context, title: String?, spinnerItems: List<T>) : PopupWindow(mContext), OnClickListener {
private var popLayout: LinearLayout? = null
private var selectPopPanent: LinearLayout? = null
private var btnTakeTitle: TextView? = null
private var btnCancel: Button? = null
private var scrollView: ScrollView? = null
private fun assignViews(title: String?): View {
val inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.select_pop, null, false)
popLayout = view.findViewById(R.id.pop_layout) as LinearLayout
selectPopPanent = view.findViewById(R.id.select_pop_panent) as LinearLayout
btnTakeTitle = view.findViewById(R.id.btn_take_title) as TextView
btnCancel = view.findViewById(R.id.btn_cancel) as Button
scrollView = view.findViewById(R.id.select_pop_scrollView) as ScrollView
if (StrUtils.notEmpty(title)) {
btnTakeTitle!!.visibility = View.VISIBLE
btnTakeTitle!!.text = title
}
//取消按钮
btnCancel!!.setOnClickListener {
//销毁弹出框
dismiss()
// SettingActivity.isClick = false;
}
return view
}
init {
val popup = assignViews(title)
addItem(spinnerItems)
//设置按钮监听
//设置SelectPicPopupWindow的View
this.contentView = popup
//设置SelectPicPopupWindow弹出窗体的宽
this.width = LayoutParams.MATCH_PARENT
//设置SelectPicPopupWindow弹出窗体的高
this.height = LayoutParams.MATCH_PARENT
//设置SelectPicPopupWindow弹出窗体可点击
this.isFocusable = true
//设置SelectPicPopupWindow弹出窗体动画效果
this.animationStyle = R.style.ActionSheetAnimation
//实例化一个ColorDrawable颜色为半透明
val dw = ColorDrawable(0xb0000000.toInt())
//设置SelectPicPopupWindow弹出窗体的背景
this.setBackgroundDrawable(dw)
//mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
popup.setOnTouchListener { v, event ->
val height = popLayout!!.top
val y = event.y.toInt()
if (event.action == MotionEvent.ACTION_UP) {
if (y < height) {
dismiss()
}
}
true
}
}
internal fun addItem(spinnerItems: List<T>) {
if (ArrayUtils.isNotEmpty(spinnerItems)) {
if (spinnerItems.size >= 7) {
val dm = DisplayMetrics()
(mContext as Activity).windowManager.defaultDisplay.getMetrics(dm)
val params = scrollView!!.layoutParams as LinearLayout.LayoutParams
params.height = dm.heightPixels / 2
scrollView!!.layoutParams = params
}
val dividerMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
48.0f, mContext.resources.displayMetrics).toInt()
val params = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, dividerMargin)
val color = ContextCompat.getColor(mContext, R.color.blue)
var itemBtn: Button
val paramsLine = LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 1)
var itemView:View
for ((index, item) in spinnerItems.withIndex()) {
itemBtn = Button(mContext)
itemBtn.textSize = 15.0f
itemBtn.setTextColor(color)
itemBtn.layoutParams = params
itemBtn.text = item.value
itemBtn.tag = item
itemBtn.setOnClickListener(this)
if(0 == index){
if(btnTakeTitle!!.visibility == View.VISIBLE){
itemBtn.setBackgroundResource(if(spinnerItems.size==1)R.drawable.btn_dialog_selector else R.drawable.border_top_bottom_gray_selector)
}else{
itemBtn.setBackgroundResource(if(spinnerItems.size==1)R.drawable.btn_dialog_selector else R.drawable.btn_top)
}
}else if(index == spinnerItems.size - 1){
if(spinnerItems.size==2&&btnTakeTitle!!.visibility != View.VISIBLE){
itemView= View(mContext)
itemView.layoutParams=paramsLine
selectPopPanent!!.addView(itemView)
}
itemBtn.setBackgroundResource(R.drawable.btn_bottom)
} else{
if(btnTakeTitle!!.visibility != View.VISIBLE &&index==1){
itemBtn.setBackgroundResource(R.drawable.border_top_bottom_gray_selector)
}else{
itemBtn.setBackgroundResource(R.drawable.background_border_bottom_gray_selector)
}
}
selectPopPanent!!.addView(itemBtn)
}
}
}
override fun onClick(v: View) {
if (v.tag != null)
selectPopupBack(v.tag as T)
dismiss()
}
protected open fun selectPopupBack(item:T){
}
fun show(view: View) {
showAtLocation(view, Gravity.CENTER_VERTICAL, 0, 0)
}
companion object {
/**获取默认的item选项
* @param items item的字符串
*/
fun getDefExtendItems(vararg items: String): List<DefExtendItem> {
val itemList = ArrayList<DefExtendItem>()
var item: ExtendItem
for (i in items.indices) {
item = DefExtendItem(i, items[i])
itemList.add(item)
}
return itemList
}
}
} | apache-2.0 | 324869ef7dbb8f1ea9c40b03e0769c0f | 36.080925 | 162 | 0.609136 | 4.48218 | false | false | false | false |
androidx/constraintlayout | projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/motion/dsl/transition/KeyPositionsDsl.kt | 2 | 1783 | /*
* 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 com.example.constraintlayout.motion.dsl.transition
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import androidx.constraintlayout.compose.OnSwipe
import androidx.constraintlayout.compose.RelativePosition
import androidx.constraintlayout.compose.SwipeDirection
import androidx.constraintlayout.compose.SwipeMode
import androidx.constraintlayout.compose.SwipeSide
@Preview
@Composable
fun KeyPositionsSimpleDslExample() {
TwoItemLayout(transitionContent = { img1, img2 ->
onSwipe = OnSwipe(
anchor = img1,
side = SwipeSide.Top,
direction = SwipeDirection.Up,
mode = SwipeMode.Spring
)
keyPositions(img1) {
type = RelativePosition.Delta
frame(50) {
percentX = -0.2f
}
}
keyPositions(img2) {
type = RelativePosition.Parent
frame(25) {
percentX = 0.2f
}
frame(50) {
percentX = 0.5f
}
frame(75) {
percentX = 0.2f
}
}
})
} | apache-2.0 | e2df7b9d42554831d9175aa349378085 | 30.298246 | 75 | 0.648345 | 4.446384 | false | false | false | false |
ericberman/MyFlightbookAndroid | app/src/main/java/model/MFBTakeoffSpeed.kt | 1 | 2030 | /*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2017-2022 MyFlightbook, LLC
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 model
import java.text.DecimalFormat
object MFBTakeoffSpeed {
private const val TOSpeedBreak = 50
private const val TOLandingSpreadHigh = 15
private const val TOLandingSpreadLow = 10
private val rgTOSpeeds = intArrayOf(20, 40, 55, 70, 85, 100)
const val DefaultTakeOffIndex = 3 // 70kts
private var m_iTakeOffSpeed = DefaultTakeOffIndex
// get/set the N'th takeoff speed.
@JvmStatic
var takeOffSpeedIndex: Int
get() = m_iTakeOffSpeed
set(value) {
if (value >= 0 && value < rgTOSpeeds.size) m_iTakeOffSpeed = value
}
/// <summary>
/// Currently set Take-off speed
/// </summary>
@JvmStatic
val takeOffspeed: Int
get() = rgTOSpeeds[takeOffSpeedIndex]
/// <summary>
/// Currently set Landing speed
/// </summary>
@JvmStatic
val landingSpeed: Int
get() = takeOffspeed - if (takeOffspeed >= TOSpeedBreak) TOLandingSpreadHigh else TOLandingSpreadLow
@JvmStatic
fun getDisplaySpeeds(): ArrayList<String> {
val df = DecimalFormat("#,###")
val l = ArrayList<String>()
for (speed in rgTOSpeeds) l.add(String.format("%skts", df.format(speed.toLong())))
return l
}
} | gpl-3.0 | b792b4a9ff556711c9b36e9e33c4e7c6 | 32.85 | 108 | 0.680788 | 4.168378 | false | false | false | false |
sav007/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo/compiler/FragmentsResponseMapperBuilder.kt | 1 | 4765 | package com.apollographql.apollo.compiler
import com.apollographql.apollo.api.FragmentResponseFieldMapper
import com.apollographql.apollo.api.ResponseReader
import com.apollographql.apollo.compiler.ir.CodeGenerationContext
import com.apollographql.apollo.compiler.ir.Fragment
import com.squareup.javapoet.*
import javax.annotation.Nonnull
import javax.lang.model.element.Modifier
/**
* Responsible for [Fragments.Mapper] class generation
*
* Example of generated class:
*
* ```
* public static final class Mapper implements FragmentResponseFieldMapper<Fragments> {
* final HeroDetails.Mapper heroDetailsFieldMapper = new HeroDetails.Mapper();
*
* @Override
* public Fragments map(ResponseReader reader, @Nonnull String conditionalType) {
* HeroDetails heroDetails = null;
* if (conditionalType.equals(HeroDetails.TYPE_CONDITION)) {
* heroDetails = heroDetailsFieldMapper.map(reader);
* }
* return new Fragments(heroDetails);
* }
* }
*
*```
*/
class FragmentsResponseMapperBuilder(
val fragments: List<String>,
val context: CodeGenerationContext
) {
fun build(): TypeSpec {
val fragmentFields = fragments.map { FieldSpec.builder(fragmentType(it), it.decapitalize()).build() }
return TypeSpec.classBuilder(Util.RESPONSE_FIELD_MAPPER_TYPE_NAME)
.addModifiers(Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.addSuperinterface(RESPONSE_FIELD_MAPPER_TYPE)
.addFields(mapperFields(fragmentFields))
.addMethod(mapMethod(fragmentFields))
.build()
}
private fun fragmentType(fragmentName: String) =
ClassName.get(context.fragmentsPackage, fragmentName.capitalize())
private fun mapMethod(fragmentFields: List<FieldSpec>) =
MethodSpec.methodBuilder("map")
.addModifiers(Modifier.PUBLIC)
.addAnnotation(Override::class.java)
.addParameter(READER_PARAM)
.addParameter(CONDITIONAL_TYPE_PARAM)
.returns(SchemaTypeSpecBuilder.FRAGMENTS_FIELD.type)
.addCode(mapMethodCode(fragmentFields))
.build()
private fun mapMethodCode(fragmentFields: List<FieldSpec>) =
CodeBlock.builder()
.add(initFragmentsCode(fragmentFields))
.add(createFragmentsCode(fragmentFields))
.add(");\n")
.build()
private fun initFragmentsCode(fragmentFields: List<FieldSpec>) =
CodeBlock.builder()
.add(fragmentFields
.fold(CodeBlock.builder()) { builder, field -> builder.addStatement("\$T \$N = null", field.type, field) }
.build())
.add(fragmentFields
.fold(CodeBlock.builder()) { builder, field -> builder.add(initFragmentCode(field)) }
.build())
.build()
private fun initFragmentCode(fragmentField: FieldSpec): CodeBlock {
val fieldClass = fragmentField.type as ClassName
return CodeBlock.builder()
.beginControlFlow("if (\$T.\$L.contains(\$L))", fieldClass, Fragment.POSSIBLE_TYPES_VAR, CONDITIONAL_TYPE_VAR)
.addStatement("\$N = \$L.map(\$L)", fragmentField, fieldClass.mapperFieldName(), READER_VAR)
.endControlFlow()
.build()
}
private fun createFragmentsCode(fragmentFields: List<FieldSpec>) =
CodeBlock.builder()
.add("return new \$L(", SchemaTypeSpecBuilder.FRAGMENTS_FIELD.type.withoutAnnotations())
.add(fragmentFields
.mapIndexed { i, fieldSpec -> CodeBlock.of("\$L\$L", if (i > 0) ", " else "", fieldSpec.name) }
.fold(CodeBlock.builder(), CodeBlock.Builder::add)
.build())
.build()
private fun mapperFields(fragments: List<FieldSpec>) =
fragments
.map { it.type as ClassName }
.map {
val mapperClassName = ClassName.get(context.fragmentsPackage, it.simpleName(),
Util.RESPONSE_FIELD_MAPPER_TYPE_NAME)
FieldSpec.builder(mapperClassName, it.mapperFieldName(), Modifier.FINAL)
.initializer(CodeBlock.of("new \$T()", mapperClassName))
.build()
}
companion object {
private val API_RESPONSE_FIELD_MAPPER_TYPE = ClassName.get(
FragmentResponseFieldMapper::class.java)
private val RESPONSE_FIELD_MAPPER_TYPE = ParameterizedTypeName.get(API_RESPONSE_FIELD_MAPPER_TYPE,
SchemaTypeSpecBuilder.FRAGMENTS_FIELD.type.withoutAnnotations())
private val CONDITIONAL_TYPE_VAR = "conditionalType"
private val CONDITIONAL_TYPE_PARAM = ParameterSpec.builder(String::class.java, CONDITIONAL_TYPE_VAR)
.addAnnotation(Nonnull::class.java).build()
private val READER_VAR = "reader"
private val READER_PARAM = ParameterSpec.builder(ResponseReader::class.java, READER_VAR).build()
}
} | mit | d6bd362b1517fa2589da6da3879b5680 | 40.086207 | 120 | 0.682267 | 4.37156 | false | false | false | false |
kotlintest/kotlintest | kotest-core/src/jvmMain/kotlin/io/kotest/core/spec/style/AnnotationSpec.kt | 1 | 7423 | package io.kotest.core.spec.style
import io.kotest.assertions.Failures
import io.kotest.core.config.Project
import io.kotest.core.spec.Spec
import io.kotest.core.test.*
import io.kotest.core.internal.unwrapIfReflectionCall
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.full.callSuspend
import kotlin.reflect.full.memberFunctions
typealias Test = AnnotationSpec.Test
abstract class AnnotationSpec : Spec() {
private fun defaultConfig() = defaultTestConfig ?: defaultTestCaseConfig() ?: Project.testCaseConfig()
override fun beforeSpec(spec: Spec) {
executeBeforeSpecFunctions()
}
private fun executeBeforeSpecFunctions() = this::class.findBeforeSpecFunctions().forEach { it.call(this) }
override fun beforeTest(testCase: TestCase) {
executeBeforeTestFunctions()
}
private fun executeBeforeTestFunctions() = this::class.findBeforeTestFunctions().forEach { it.call(this) }
override fun afterTest(testCase: TestCase, result: TestResult) {
executeAfterTestFunctions()
}
private fun executeAfterTestFunctions() = this::class.findAfterTestFunctions().forEach { it.call(this) }
override fun afterSpec(spec: Spec) {
executeAfterSpecFunctions()
}
private fun executeAfterSpecFunctions() = this::class.findAfterSpecFunctions().forEach { it.call(this) }
private fun KFunction<*>.toIgnoredTestCase() {
createTestCase(defaultConfig().copy(enabled = false))
}
private fun KFunction<*>.toEnabledTestCase() {
createTestCase(defaultConfig())
}
private fun KFunction<*>.createTestCase(config: TestCaseConfig) {
if (this.isExpectingException()) {
val expected = this.getExpectedException()
addRootTestCase(name, callWhileExpectingException(expected), config, TestType.Test)
} else {
addRootTestCase(name, { callSuspend(this@AnnotationSpec) }, config, TestType.Test)
}
}
private fun KFunction<*>.isExpectingException(): Boolean {
return annotations.filterIsInstance<Test>().first().expected != Test.None::class
}
private fun KFunction<*>.getExpectedException(): KClass<out Throwable> {
return annotations.filterIsInstance<Test>().first().expected
}
private fun KFunction<*>.callWhileExpectingException(expected: KClass<out Throwable>): suspend TestContext.() -> Unit {
return {
val thrown = try {
callSuspend(this@AnnotationSpec)
null
} catch (t: Throwable) {
t.unwrapIfReflectionCall()
} ?: failNoExceptionThrown(expected)
if (thrown::class != expected) failWrongExceptionThrown(expected, thrown)
}
}
private fun failNoExceptionThrown(expected: KClass<out Throwable>): Nothing {
throw Failures.failure("Expected exception of class ${expected.simpleName}, but no exception was thrown.")
}
private fun failWrongExceptionThrown(expected: KClass<out Throwable>, thrown: Throwable): Nothing {
throw Failures.failure("Expected exception of class ${expected.simpleName}, but ${thrown::class.simpleName} was thrown instead.")
}
// All annotations should be kept inside this class, to avoid any usage outside of AnnotationSpec.
// One can only use annotations to execute code inside AnnotationSpec.
/**
* Marks a function to be executed before each test
*
* This can be used in AnnotationSpec to mark a function to be executed before every test by Kotest Engine
* @see BeforeAll
* @see AfterEach
*/
annotation class BeforeEach
/**
* Marks a function to be executed before each test
*
* This can be used in AnnotationSpec to mark a function to be executed before every test by Kotest Engine
* @see BeforeClass
* @see After
*/
annotation class Before
/**
* Marks a function to be executed before each spec
*
* This can be used in AnnotationSpec to mark a function to be executed before a spec by Kotest Engine.
* @see BeforeEach
* @see AfterAll
*/
annotation class BeforeAll
/**
* Marks a function to be executed before each spec
*
* This can be used in AnnotationSpec to mark a function to be executed before a spec by Kotest Engine.
* @see Before
* @see AfterClass
*/
annotation class BeforeClass
/**
* Marks a function to be executed after each test
*
* This can be used in AnnotationSpec to mark a function to be executed before a test by Kotest Engine.
* @see AfterAll
* @see BeforeEach
*/
annotation class AfterEach
/**
* Marks a function to be executed after each test
*
* This can be used in AnnotationSpec to mark a function to be executed before a test by Kotest Engine.
* @see AfterClass
* @see Before
*/
annotation class After
/**
* Marks a function to be executed after each spec
*
* This can be used in AnnotationSpec to mark a function to be executed before a spec by Kotest Engine.
* @see AfterEach
* @see BeforeAll
*/
annotation class AfterAll
/**
* Marks a function to be executed after each spec
*
* This can be used in AnnotationSpec to mark a function to be executed before a spec by Kotest Engine.
* @see After
* @see BeforeClass
*/
annotation class AfterClass
/**
* Marks a function to be executed as a Test
*
* This can be used in AnnotationSpec to mark a function to be executed as a test by Kotest Engine.
*
*
* [expected] can be used to mark a test to expect a specific exception.
*
* This is useful when moving from JUnit, in which you use expected to verify for an exception.
*
* ```
* @Test(expected = FooException::class)
* fun foo() {
* throw FooException() // Pass
* }
*
* @Test(expected = FooException::class
* fun bar() {
* throw BarException() // Fails, FooException was expected
* }
* ```
*/
annotation class Test(val expected: KClass<out Throwable> = None::class) {
object None : Throwable()
}
/**
* Marks a Test to be ignored
*
* This can be used in AnnotationSpec to mark a Test as Ignored.
*/
annotation class Ignore
}
fun KClass<out AnnotationSpec>.findBeforeTestFunctions() =
findFunctionAnnotatedWithAnyOf(AnnotationSpec.BeforeEach::class, AnnotationSpec.Before::class)
fun KClass<out AnnotationSpec>.findBeforeSpecFunctions() =
findFunctionAnnotatedWithAnyOf(AnnotationSpec.BeforeAll::class, AnnotationSpec.BeforeClass::class)
fun KClass<out AnnotationSpec>.findAfterSpecFunctions() =
findFunctionAnnotatedWithAnyOf(AnnotationSpec.AfterAll::class, AnnotationSpec.AfterClass::class)
fun KClass<out AnnotationSpec>.findAfterTestFunctions() =
findFunctionAnnotatedWithAnyOf(AnnotationSpec.AfterEach::class, AnnotationSpec.After::class)
fun KClass<out AnnotationSpec>.findTestFunctions() =
findFunctionAnnotatedWithAnyOf(AnnotationSpec.Test::class)
fun KFunction<*>.isIgnoredTest() = isFunctionAnnotatedWithAnyOf(AnnotationSpec.Ignore::class)
private fun KClass<out AnnotationSpec>.findFunctionAnnotatedWithAnyOf(vararg annotation: KClass<*>) =
memberFunctions.filter { it.isFunctionAnnotatedWithAnyOf(*annotation) }
private fun KFunction<*>.isFunctionAnnotatedWithAnyOf(vararg annotation: KClass<*>) =
annotations.any { it.annotationClass in annotation }
| apache-2.0 | 8d35eae4cea17c3bb1b25d0daa1dc1d7 | 32.436937 | 135 | 0.706588 | 4.665619 | false | true | false | false |
TerrenceMiao/IPAQ | src/main/kotlin/org/paradise/ipaq/services/rest/RestServiceClient.kt | 1 | 4125 | package org.paradise.ipaq.services.rest
import org.apache.commons.lang3.math.NumberUtils
import org.apache.http.HttpHost
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.impl.client.ProxyAuthenticationStrategy
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.http.ResponseEntity
import org.springframework.http.client.ClientHttpResponse
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory
import org.springframework.stereotype.Component
import org.springframework.web.client.ResponseErrorHandler
import org.springframework.web.client.RestTemplate
import java.io.IOException
/**
* RESTful service client, based on Spring RestTemplate and Apache HTTP Client.
*/
@Component
class RestServiceClient {
private val restTemplate: RestTemplate = RestTemplate()
init {
restTemplate.requestFactory = httpComponentsClientHttpRequestFactory()
restTemplate.errorHandler = createResponseErrorHandler()
}
fun <T> exchange(url: String, method: HttpMethod, requestEntity: HttpEntity<*>, responseType: Class<T>, vararg uriVariables: Any): ResponseEntity<T>
= restTemplate.exchange(url, method, requestEntity, responseType, *uriVariables)
private fun httpComponentsClientHttpRequestFactory(): HttpComponentsClientHttpRequestFactory {
/**
* Consider using HttpClientBuilder.useSystemProperties() call in Apache HttpClient which use system properties
* when creating and configuring default implementations, including http.proxyHost and http.proxyPort.
* In Apache HTTP Client 5, http.proxyUser and http.proxyPassword also defined in:
* @see org.apache.hc.client5.http.impl.auth.SystemDefaultCredentialsProvider
*/
val systemProperties = System.getProperties()
val proxyHost = systemProperties.getProperty(PROXY_HOST_PROPERTY)
val proxyPort = NumberUtils.toInt(systemProperties.getProperty(PROXY_PORT_PROPERTY), -1)
val proxyUser = systemProperties.getProperty(PROXY_USER_PROPERTY)
val proxyPassword = systemProperties.getProperty(PROXY_PASSWORD_PROPERTY)
val httpClientBuilder = HttpClientBuilder.create()
if (proxyHost != null && proxyPort != -1) {
httpClientBuilder.setProxy(HttpHost(proxyHost, proxyPort))
if (proxyUser != null && proxyPassword != null) {
val passwordCredentials = UsernamePasswordCredentials(proxyUser, proxyPassword)
val credentialsProvider = BasicCredentialsProvider()
credentialsProvider.setCredentials(AuthScope(proxyHost, proxyPort), passwordCredentials)
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
httpClientBuilder.setProxyAuthenticationStrategy(ProxyAuthenticationStrategy())
}
}
return HttpComponentsClientHttpRequestFactory(httpClientBuilder.build())
}
/**
* By pass the default Exception Handler. When make RESTful call, disable any error handler when use this
* restTemplate, and directly back error message to service(s) or controller(s).
* @return ResponseErrorHandler created
*/
private fun createResponseErrorHandler(): ResponseErrorHandler {
return object : ResponseErrorHandler {
@Throws(IOException::class)
override fun hasError(response: ClientHttpResponse): Boolean {
return false
}
@Throws(IOException::class)
override fun handleError(response: ClientHttpResponse) {
}
}
}
companion object {
private val PROXY_HOST_PROPERTY = "http.proxyHost"
private val PROXY_PORT_PROPERTY = "http.proxyPort"
private val PROXY_USER_PROPERTY = "http.proxyUser"
private val PROXY_PASSWORD_PROPERTY = "http.proxyPassword"
}
}
| apache-2.0 | f203bbd53537145ff0549d08caa994cd | 38.663462 | 152 | 0.733576 | 5.162703 | false | false | false | false |
jitsi/jitsi-videobridge | jvb-api/jvb-api-client/src/main/kotlin/org/jitsi/videobridge/api/util/WebSocketClient.kt | 1 | 3561 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.videobridge.api.util
import io.ktor.client.HttpClient
import io.ktor.client.plugins.websocket.ws
import io.ktor.websocket.Frame
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ClosedReceiveChannelException
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.jitsi.utils.logging2.Logger
import org.jitsi.utils.logging2.createChildLogger
/**
* A websocket client which sends messages and invokes a handler upon receiving
* messages from the far side. Sending is non-blocking, and the client has no
* notion of correlating "responses" to "requests": if request/response
* semantics are required then they must be implemented by a layer on top of
* this class.
*/
class WebSocketClient(
private val client: HttpClient,
private val host: String,
private val port: Int,
/**
* The path of the remote websocket URL
*/
private val path: String,
parentLogger: Logger,
var incomingMessageHandler: (Frame) -> Unit = {},
/**
* The dispatcher which will be used for all of the request and response
* processing.
*/
dispatcher: CoroutineDispatcher = Dispatchers.IO
) {
private val logger = createChildLogger(parentLogger)
private val job = Job()
private val coroutineScope = CoroutineScope(dispatcher + job)
private val msgsToSend = Channel<Frame>(Channel.RENDEZVOUS)
fun sendString(data: String) {
coroutineScope.launch {
msgsToSend.send(Frame.Text(data))
}
}
/**
* Establish the websocket connection and start a loop to handle
* sending and receiving websocket messages.
*/
fun run() {
coroutineScope.launch {
client.ws(host = host, port = port, path = path) {
launch {
for (msg in incoming) {
incomingMessageHandler(msg)
}
}
try {
for (msg in msgsToSend) {
send(msg)
}
} catch (e: ClosedReceiveChannelException) {
logger.info("Websocket was closed")
return@ws
} catch (e: CancellationException) {
logger.info("Websocket job was cancelled")
throw e
} catch (t: Throwable) {
logger.error("Error in websocket connection: ", t)
return@ws
}
}
}
}
/**
* Stop and close the websocket connection
*/
fun stop() {
runBlocking {
job.cancelAndJoin()
}
}
}
| apache-2.0 | a4bc27cab55f98389b42af8b7f6a12ad | 32.280374 | 79 | 0.641112 | 4.741678 | false | false | false | false |
yschimke/oksocial | src/test/kotlin/com/baulsupp/okurl/i9n/SurveyMonkeyTest.kt | 1 | 1432 | package com.baulsupp.okurl.i9n
import com.baulsupp.oksocial.output.TestOutputHandler
import com.baulsupp.okurl.Main
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.credentials.DefaultToken
import com.baulsupp.okurl.services.surveymonkey.SurveyMonkeyAuthInterceptor
import kotlinx.coroutines.runBlocking
import okhttp3.Response
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SurveyMonkeyTest {
private val main = Main()
private val output = TestOutputHandler<Response>()
private val completionCache = TestCompletionVariableCache()
private val credentialsStore = TestCredentialsStore()
init {
main.outputHandler = output
main.completionVariableCache = completionCache
main.credentialsStore = credentialsStore
}
@Test
fun completeEndpointWithReplacements() {
main.arguments = mutableListOf("https://api.surveymonkey.net/")
main.urlComplete = true
completionCache["surveymonkey", "survey"] = listOf("AA", "BB")
runBlocking {
credentialsStore.set(SurveyMonkeyAuthInterceptor().serviceDefinition, DefaultToken.name, Oauth2Token(""))
main.run()
}
assertEquals(mutableListOf(), output.failures)
assertEquals(1, output.stdout.size)
assertTrue(output.stdout[0].contains("/v3/surveys/AA/details"))
assertTrue(output.stdout[0].contains("/v3/surveys/BB/details"))
}
}
| apache-2.0 | 27eaaf9b8785135330339098ecdaaf92 | 32.302326 | 111 | 0.77514 | 4.3003 | false | true | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/smartystreets/SmartyStreetsAuthInterceptor.kt | 1 | 2155 | package com.baulsupp.okurl.services.smartystreets
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.AuthInterceptor
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.services.AbstractServiceDefinition
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
class SmartyStreetsAuthInterceptor : AuthInterceptor<SmartStreetsToken>() {
override suspend fun intercept(chain: Interceptor.Chain, credentials: SmartStreetsToken): Response {
var request = chain.request()
val signedUrl = request.url.newBuilder().addQueryParameter("auth-id", credentials.authId)
.addQueryParameter("auth-token", credentials.authToken).build()
request = request.newBuilder().url(signedUrl).build()
return chain.proceed(request)
}
override val serviceDefinition = object :
AbstractServiceDefinition<SmartStreetsToken>(
"api.smartystreets.com", "SmartyStreets", "smartystreets",
"https://smartystreets.com/docs/cloud", "https://smartystreets.com/account"
) {
override fun parseCredentialsString(s: String): SmartStreetsToken {
val (token, key) = s.split(":", limit = 2)
return SmartStreetsToken(token, key)
}
override fun formatCredentialsString(credentials: SmartStreetsToken): String =
credentials.authId + ":" + credentials.authToken
}
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): SmartStreetsToken {
return SmartyStreetsAuthFlow.login()
}
override suspend fun supportsUrl(url: HttpUrl, credentialsStore: CredentialsStore): Boolean {
return url.host == "api.smartystreets.com" || url.host.endsWith(".api.smartystreets.com")
}
override fun hosts(credentialsStore: CredentialsStore): Set<String> = setOf(
"international-street.api.smartystreets.com",
"us-street.api.smartystreets.com",
"us-zipcode.api.smartystreets.com",
"us-autocomplete.api.smartystreets.com",
"us-extract.api.smartystreets.com",
"download.api.smartystreets.com"
)
}
| apache-2.0 | 7ac7b59ae8470aa5ee1d579826cd7726 | 35.525424 | 102 | 0.75406 | 4.192607 | false | false | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ConventionExtensions.kt | 1 | 3899 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl
import org.gradle.api.plugins.Convention
import org.gradle.kotlin.dsl.accessors.runtime.conventionOf
import org.gradle.kotlin.dsl.accessors.runtime.conventionPluginByName
import kotlin.reflect.KClass
/**
* Looks for the convention plugin of a given name and casts it to the expected type [T].
*
* If no convention is found or if the one found cannot be cast to the expected type it will throw an [IllegalStateException].
*
* @param name convention plugin name
* @return the convention plugin, never null
* @throws [IllegalStateException] When the convention cannot be found or cast to the expected type.
*/
inline fun <reified T : Any> Convention.getPluginByName(name: String): T =
conventionPluginByName(this, name).let {
(it as T?) ?: throw IllegalStateException("Convention '$name' of type '${it::class.java.name}' cannot be cast to '${T::class.java.name}'.")
}
/**
* Locates the plugin convention object with the given type.
*
* @param T the convention plugin type
* @return the convention plugin
* @throws [IllegalStateException] when there is no such object contained in this convention, or when there are multiple such objects
* @see [Convention.getPlugin]
*/
inline fun <reified T : Any> Convention.getPlugin(): T =
getPlugin(T::class)
/**
* Locates the plugin convention object with the given type.
*
* @param conventionType the convention plugin type
* @return the convention plugin
* @throws [IllegalStateException] when there is no such object contained in this convention, or when there are multiple such objects
* @see [Convention.getPlugin]
*/
fun <T : Any> Convention.getPlugin(conventionType: KClass<T>): T =
getPlugin(conventionType.java)
/**
* Locates the plugin convention object with the given type.
*
* @param T the convention plugin type.
* @return the convention plugin, or null if there is no such convention plugin
* @throws [IllegalStateException] when there are multiple matching objects
* @see [Convention.findPlugin]
*/
inline fun <reified T : Any> Convention.findPlugin(): T? =
findPlugin(T::class)
/**
* Locates the plugin convention object with the given type.
*
* @param conventionType the convention plugin type.
* @return the convention plugin, or null if there is no such convention plugin
* @throws [IllegalStateException] when there are multiple matching objects
* @see [Convention.findPlugin]
*/
fun <T : Any> Convention.findPlugin(conventionType: KClass<T>): T? =
findPlugin(conventionType.java)
/**
* Evaluates the given [function] against the convention plugin of the given [conventionType].
*
* @param conventionType the type of the convention to be located.
* @param function function to be evaluated.
* @return the value returned by the given [function].
* @throws [IllegalStateException] When the receiver does not support convention plugins, when there is no convention plugin of the given type, or when there are multiple such plugins.
*
* @see [Convention.getPlugin]
*/
inline fun <ConventionType : Any, ReturnType> Any.withConvention(
conventionType: KClass<ConventionType>,
function: ConventionType.() -> ReturnType
): ReturnType =
conventionOf(this).getPlugin(conventionType.java).run(function)
| apache-2.0 | 6a8cb6271950b303a69a66d8c815a1c5 | 36.490385 | 184 | 0.74455 | 4.233442 | false | false | false | false |
sklegg/twserver | src/main/kotlin/sklegg/server/Server.kt | 1 | 1825 | package sklegg.server
import com.natpryce.konfig.ConfigurationProperties
import com.natpryce.konfig.Key
import com.natpryce.konfig.intType
import sklegg.bigbang.MapCreator
import sklegg.game.Game
import sklegg.game.GameConfig
import sklegg.gameobjects.Player
/**
* Created by scott on 12/21/16.
* Server application entry point
*/
class Server {
/* TODO: clean this up and make null-safe */
private var port: Int? = null
private var threads: Int? = null
fun start() {
/* TODO: read game state from disk/db instead of generating on startup */
val gameConfig = getGameConfig()
val game = Game(MapCreator().generateNewMap(gameConfig.numSectors), generateDefaultPlayerArray())
println("Server - sector length = " + game.map.sectors.size)
readServerConfig()
val connections = ClientConnectionThread(port!!, threads!!, game)
print("Starting server on port $port with $threads threads. ")
Thread(connections).start()
println(" OK!")
}
private fun readServerConfig() {
val config = ConfigurationProperties.fromResource("server.properties")
port = config[Key("server.port", intType)]
threads = config[Key("server.threads", intType)]
}
private fun getGameConfig(): GameConfig {
val config = ConfigurationProperties.fromResource("game.properties")
val gameConfig = GameConfig()
gameConfig.numSectors = config[Key("game.initialSectors", intType)]
println("Server - got gameconfig: $gameConfig.numSectors")
return gameConfig
}
private fun generateDefaultPlayerArray() : Array<Player> {
val defaultPlayer = Player("scott")
val players: Array<Player> = emptyArray()
players.plus(defaultPlayer)
return players
}
} | mit | 2c1e29371e7c3c1f45d5837979f2fc0a | 31.607143 | 105 | 0.680548 | 4.355609 | false | true | false | false |
capehorn/swagger-vertx-elm | src/test/kotlin/codegen/vertx/VertxCodeGeneratorTest.kt | 1 | 2390 | package codegen.vertx
import codegen.model.*
import io.swagger.models.HttpMethod
import io.swagger.models.properties.PropertyBuilder
import io.swagger.models.properties.RefProperty
import io.swagger.parser.SwaggerParser
import org.junit.Test
class VertxCodeGeneratorTest {
val rootDirectory = "/home/peter/dev/github/capehorn/swagger-vertx-elm/generated-code/src/main/kotlin/generated"
@Test
fun generateDataClassTest(){
val generator = VertxCodeGenerator("")
val definition = Definition(
"User",
listOf(
Field("userName", "String", PropertyBuilder.build("string", "", null)),
Field("yearOfBirth", "Integer", PropertyBuilder.build("string", "", null))
)
)
val dataClass = generator.generateDataClass(definition)
println(dataClass)
}
@Test
fun generateRouteTest(){
val generator = VertxCodeGenerator("")
val route = generator.generateRoute(anOperation)
println(route)
}
@Test
fun generateAbstractOperationMethodTest(){
val generator = VertxCodeGenerator("")
val method = generator.generateAbstractOperationMethod(anOperation)
println(method)
}
@Test
fun generateOperationMethodTest(){
val generator = VertxCodeGenerator("")
val method = generator.generateOperationHandler(anOperation)
println(method)
}
@Test
fun codeGeneratorTest(){
val swagger = SwaggerParser().read("/home/peter/dev/github/capehorn/swagger-vertx-elm/src/main/resources/upbeat-api.json");
val generator = VertxCodeGenerator(rootDirectory)
val codeGen = generator.processSwagger(swagger)
val codeGenResult = generator.generate(codeGen)
val files = generator.write(codeGenResult)
files.forEach(::println)
}
val anOperation = Operation(
"getUserById",
"Get a user by its id",
HttpMethod.GET,
"/user/{userId}",
listOf(
Parameter("userId", ParameterIn.Path, Field("userId", "Integer", PropertyBuilder.build("integer", "", null)))
),
listOf(
Response("200", Field("200", "User", RefProperty("User")))
)
)
} | apache-2.0 | 4a7aaf6feb9f4713f5f89d0e06cda02a | 30.460526 | 133 | 0.612971 | 4.84787 | false | true | false | false |
android/trackr | app-compose/src/main/java/com/example/android/trackr/compose/ui/TaskSummaryCard.kt | 1 | 4983 | /*
* Copyright (C) 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 com.example.android.trackr.compose.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.Card
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.android.trackr.compose.R
import com.example.android.trackr.data.Avatar
import com.example.android.trackr.data.Tag
import com.example.android.trackr.data.TagColor
import com.example.android.trackr.data.TaskStatus
import com.example.android.trackr.data.TaskSummary
import com.example.android.trackr.data.User
import com.example.android.trackr.utils.DateTimeUtils
import java.time.Clock
import java.time.Duration
import java.time.Instant
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun TaskSummaryCard(
summary: TaskSummary,
clock: Clock,
onStarClick: () -> Unit,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Card(
onClick = onClick,
modifier = modifier,
) {
Row {
Spacer(modifier = Modifier.width(8.dp))
// The star icon.
StarIconButton(
onClick = onStarClick,
filled = summary.starred,
contentDescription = "",
modifier = Modifier.padding(top = 8.dp),
)
Spacer(modifier = Modifier.width(8.dp))
Column(modifier = Modifier.padding(top = 12.dp, end = 12.dp, bottom = 12.dp)) {
// The title.
Text(
text = summary.title,
style = MaterialTheme.typography.h5.copy(fontWeight = FontWeight.Bold),
)
Spacer(modifier = Modifier.height(4.dp))
// The owner.
TaskSummaryOwner(owner = summary.owner)
Spacer(modifier = Modifier.height(2.dp))
// The due date.
TaskSummaryDueAt(dueAt = summary.dueAt, clock = clock)
Spacer(modifier = Modifier.height(4.dp))
// The tags.
TagGroup(
tags = summary.tags,
max = 3
)
}
}
}
}
@Composable
private fun TaskSummaryOwner(owner: User) {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(
painter = painterResource(owner.avatar.drawableResId),
contentDescription = stringResource(R.string.owner)
)
Spacer(modifier = Modifier.width(4.dp))
Text(text = owner.username)
}
}
@Composable
private fun TaskSummaryDueAt(dueAt: Instant, clock: Clock) {
val resources = LocalContext.current.resources
Text(
text = DateTimeUtils.durationMessageOrDueDate(resources, dueAt, clock),
)
}
@Preview
@Composable
private fun PreviewTaskSummaryCard() {
TrackrTheme {
TaskSummaryCard(
summary = TaskSummary(
id = 1L,
title = "Create default illustrations for event types",
status = TaskStatus.IN_PROGRESS,
dueAt = Instant.now() + Duration.ofHours(73),
orderInCategory = 1,
isArchived = false,
owner = User(id = 1L, username = "Daring Dove", avatar = Avatar.DARING_DOVE),
tags = listOf(
Tag(id = 1L, label = "2.3 release", color = TagColor.BLUE),
Tag(id = 4L, label = "UI/UX", color = TagColor.PURPLE),
),
starred = true,
),
clock = Clock.systemDefaultZone(),
onStarClick = {},
onClick = {},
)
}
}
| apache-2.0 | 055fd23d1e42e2b3397d9f5a99488d32 | 34.340426 | 93 | 0.641782 | 4.35958 | false | false | false | false |
google/horologist | media-ui/src/androidTest/java/com/google/android/horologist/media/ui/components/PodcastControlButtonsWithProgressTest.kt | 1 | 13373 | /*
* 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.
*/
@file:OptIn(ExperimentalHorologistMediaUiApi::class)
package com.google.android.horologist.media.ui.components
import androidx.compose.ui.semantics.ProgressBarRangeInfo
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.assertIsEnabled
import androidx.compose.ui.test.assertIsNotEnabled
import androidx.compose.ui.test.hasProgressBarRangeInfo
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.performClick
import androidx.test.filters.FlakyTest
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.components.controls.SeekButtonIncrement
import org.junit.Rule
import org.junit.Test
@FlakyTest(detail = "https://github.com/google/horologist/issues/407")
class PodcastControlButtonsWithProgressTest {
@get:Rule
val composeTestRule = createComposeRule()
@Test
fun givenIsPlaying_thenPauseButtonIsDisplayed() {
// given
val playing = true
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = playing,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = true,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = true
)
}
// then
composeTestRule.onNodeWithContentDescription("Pause")
.assertIsDisplayed()
composeTestRule.onNodeWithContentDescription("Play")
.assertDoesNotExist()
}
@Test
fun givenIsPlaying_whenPauseIsClicked_thenCorrectEventIsTriggered() {
// given
val playing = true
var clicked = false
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = { clicked = true },
playPauseButtonEnabled = true,
playing = playing,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = true,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = true
)
}
// when
composeTestRule.onNodeWithContentDescription("Pause")
.performClick()
// then
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
}
@Test
fun givenIsNOTPlaying_thenPlayButtonIsDisplayed() {
// given
val playing = false
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = playing,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = true,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = true
)
}
// then
composeTestRule.onNodeWithContentDescription("Play")
.assertIsDisplayed()
composeTestRule.onNodeWithContentDescription("Pause")
.assertDoesNotExist()
}
@Test
fun givenIsNOTPlaying_whenPlayIsClicked_thenCorrectEventIsTriggered() {
// given
val playing = false
var clicked = false
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = { clicked = true },
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = playing,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = true,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = true
)
}
// when
composeTestRule.onNodeWithContentDescription("Play")
.performClick()
// then
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
}
@Test
fun whenSeekBackIsClicked_thenCorrectEventIsTriggered() {
// given
var clicked = false
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = false,
percent = 0.25f,
onSeekBackButtonClick = { clicked = true },
seekBackButtonEnabled = true,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = true
)
}
// when
composeTestRule.onNodeWithContentDescription("Rewind")
.performClick()
// then
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
}
@Test
fun whenSeekForwardIsClicked_thenCorrectEventIsTriggered() {
// given
var clicked = false
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = false,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = true,
onSeekForwardButtonClick = { clicked = true },
seekForwardButtonEnabled = true
)
}
// when
composeTestRule.onNodeWithContentDescription("Forward")
.performClick()
// then
// assert that the click event was assigned to the correct button
composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked }
}
@Test
fun givenPercentParam_thenProgressBarIsDisplayed() {
// given
val percent = 0.25f
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = true,
playing = false,
percent = percent,
onSeekBackButtonClick = {},
seekBackButtonEnabled = true,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = true
)
}
// then
composeTestRule.onNode(hasProgressBarRangeInfo(ProgressBarRangeInfo(percent, 0.0f..1.0f)))
.assertIsDisplayed()
}
@Test
fun givenIsPlayingAndPlayPauseEnabledIsTrue_thenPauseButtonIsEnabled() {
// given
val playing = true
val playPauseButtonEnabled = true
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = playPauseButtonEnabled,
playing = playing,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = false,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = false
)
}
// then
composeTestRule.onNodeWithContentDescription("Pause")
.assertIsEnabled()
composeTestRule.onNodeWithContentDescription("Rewind")
.assertIsNotEnabled()
composeTestRule.onNodeWithContentDescription("Forward")
.assertIsNotEnabled()
}
@Test
fun givenIsNOTPlayingAndPlayPauseEnabledIsTrue_thenPlayButtonIsEnabled() {
// given
val playing = false
val playPauseButtonEnabled = true
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = playPauseButtonEnabled,
playing = playing,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = false,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = false
)
}
// then
composeTestRule.onNodeWithContentDescription("Play")
.assertIsEnabled()
composeTestRule.onNodeWithContentDescription("Rewind")
.assertIsNotEnabled()
composeTestRule.onNodeWithContentDescription("Forward")
.assertIsNotEnabled()
}
@Test
fun givenSeekBackButtonEnabledIsTrue_thenSeekBackButtonIsEnabled() {
// given
val seekBackButtonEnabled = true
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = false,
playing = false,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = seekBackButtonEnabled,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = false,
seekBackButtonIncrement = SeekButtonIncrement.Unknown
)
}
// then
composeTestRule.onNodeWithContentDescription("Rewind")
.assertIsEnabled()
composeTestRule.onNodeWithContentDescription("Play")
.assertIsNotEnabled()
composeTestRule.onNodeWithContentDescription("Forward")
.assertIsNotEnabled()
}
@Test
fun givenSeekForwardButtonEnabledIsTrue_thenSeekForwardButtonIsEnabled() {
// given
val seekForwardButtonEnabled = true
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = false,
playing = false,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = false,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = seekForwardButtonEnabled
)
}
// then
composeTestRule.onNodeWithContentDescription("Forward")
.assertIsEnabled()
composeTestRule.onNodeWithContentDescription("Play")
.assertIsNotEnabled()
composeTestRule.onNodeWithContentDescription("Rewind")
.assertIsNotEnabled()
}
@Test
fun givenSeekBackIncrementIsFive_thenSeekBackDescriptionIsFive() {
// given
val seekBackButtonIncrement = SeekButtonIncrement.Five
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = false,
playing = false,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = false,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = false,
seekBackButtonIncrement = seekBackButtonIncrement
)
}
// then
composeTestRule.onNodeWithContentDescription("Rewind 5 seconds")
.assertExists()
composeTestRule.onNodeWithContentDescription("Forward")
.assertExists()
}
@Test
fun givenSeekForwardIncrementIsFive_thenSeekForwardDescriptionIsFive() {
// given
val seekForwardButtonIncrement = SeekButtonIncrement.Five
composeTestRule.setContent {
PodcastControlButtons(
onPlayButtonClick = {},
onPauseButtonClick = {},
playPauseButtonEnabled = false,
playing = false,
percent = 0.25f,
onSeekBackButtonClick = {},
seekBackButtonEnabled = false,
onSeekForwardButtonClick = {},
seekForwardButtonEnabled = false,
seekForwardButtonIncrement = seekForwardButtonIncrement
)
}
// then
composeTestRule.onNodeWithContentDescription("Forward 5 seconds")
.assertExists()
composeTestRule.onNodeWithContentDescription("Rewind")
.assertExists()
}
}
| apache-2.0 | a1bb13b092fc8a58bed6308fe4a3ee32 | 31.857494 | 98 | 0.591341 | 6.81948 | false | true | false | false |
alexpensato/spring-boot-repositories-samples | spring-data-jpa-sample/src/main/java/net/pensato/data/jpa/sample/App.kt | 1 | 2790 | /*
* Copyright 2017 twitter.com/PensatoAlex
*
* 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.pensato.data.jpa.sample
import net.pensato.data.jpa.sample.domain.College
import net.pensato.data.jpa.sample.domain.Student
import net.pensato.data.jpa.sample.repository.CollegeRepository
import net.pensato.data.jpa.sample.repository.StudentRepository
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.boot.web.support.SpringBootServletInitializer
import org.springframework.context.annotation.Bean
import org.springframework.data.jpa.repository.config.EnableJpaRepositories
@SpringBootApplication
@EnableJpaRepositories(basePackages = arrayOf("net.pensato.data.jpa.sample.repository"))
open class App : SpringBootServletInitializer() {
override fun configure(application: SpringApplicationBuilder): SpringApplicationBuilder {
return application.sources(App::class.java)
}
@Bean
open fun init(
collegeRepository: CollegeRepository,
studentRepository: StudentRepository) = CommandLineRunner {
val result = collegeRepository.findAll()
if (result == null || result.toList().isEmpty()) {
val uc = collegeRepository.save(College(name = "University of California", city = "Berkeley"))
studentRepository.save(Student(name = "Mark", address = "Telegraph Ave", college = uc))
studentRepository.save(Student(name = "Susie", address = "Shattuck Ave", college = uc))
studentRepository.save(Student(name = "Valerie", address = "Euclid Ave", college = uc))
val harvard = collegeRepository.save(College(name = "Harvard University", city = "Cambridge"))
studentRepository.save(Student(name = "John", address = "Oxford St", college = harvard))
studentRepository.save(Student(name = "Mary", address = "Washington St", college = harvard))
studentRepository.save(Student(name = "Joseph", address = "Everett St", college = harvard))
}
}
}
fun main(args: Array<String>) {
SpringApplication.run(App::class.java, *args)
}
| apache-2.0 | 3f11776d97f3f808d42337d367bf91ee | 42.59375 | 106 | 0.743369 | 4.115044 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/ui/base/BaseAdapter.kt | 1 | 1185 | package com.booboot.vndbandroid.ui.base
import android.os.Handler
import android.os.Looper
import androidx.recyclerview.widget.RecyclerView
abstract class BaseAdapter<T : RecyclerView.ViewHolder> : RecyclerView.Adapter<T>() {
var onFinishDrawing = mutableListOf<() -> Unit>()
var onUpdate: (Boolean) -> Unit = {}
protected fun onUpdateInternal() = Handler(Looper.getMainLooper()).post {
onUpdate(itemCount <= 0)
/* If the Adapter is empty: onViewAttachedToWindow is not called, so we're calling onFinishDrawingInternal() here */
if (itemCount <= 0) {
onFinishDrawingInternal()
}
}
private fun onFinishDrawingInternal() {
onFinishDrawing.forEach { it() }
onFinishDrawing.clear()
}
protected fun notifyChanged() {
super.notifyDataSetChanged()
onUpdateInternal()
}
/**
* Latest existing callback to get notified that the Adapter has done drawing its views after an update.
*/
override fun onViewAttachedToWindow(holder: T) {
super.onViewAttachedToWindow(holder)
holder.itemView.post {
onFinishDrawingInternal()
}
}
} | gpl-3.0 | 4c0335be175d16b1ba41c91de40cde11 | 30.210526 | 124 | 0.665823 | 4.978992 | false | false | false | false |
uber/RIBs | android/libraries/rib-compiler-app/src/main/kotlin/com/uber/rib/compiler/RibProcessor.kt | 1 | 2573 | /*
* Copyright (C) 2017. Uber Technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.uber.rib.compiler
import java.util.ArrayList
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
import javax.lang.model.SourceVersion
import javax.lang.model.element.TypeElement
import javax.lang.model.util.Elements
import javax.lang.model.util.Types
/** Process the annotations with [ProcessorPipeline]. */
abstract class RibProcessor : AbstractProcessor(), ProcessContext {
override var errorReporter: ErrorReporter? = null
protected set
override var elementUtils: Elements? = null
protected set
override var typesUtils: Types? = null
protected set
var processorPipelines: MutableList<ProcessorPipeline> = ArrayList()
@Synchronized
override fun init(processingEnv: ProcessingEnvironment) {
super.init(processingEnv)
elementUtils = processingEnv.elementUtils
errorReporter = ErrorReporter(processingEnv.messager)
typesUtils = processingEnv.typeUtils
processorPipelines.addAll(getProcessorPipelines(this))
}
override fun getSupportedSourceVersion(): SourceVersion {
return SourceVersion.latestSupported()
}
override fun process(annotations: Set<TypeElement>, roundEnv: RoundEnvironment): Boolean {
if (roundEnv.processingOver()) {
return false
}
for (processorPipeline in processorPipelines) {
try {
processorPipeline.process(annotations, roundEnv)
} catch (e: Throwable) {
errorReporter?.reportError(
"Fatal error running ${processorPipeline.annotationType.simpleName} processor: ${e.message}"
)
}
}
return false
}
/**
* Get list of [ProcessorPipeline] to process each annotation.
*
* @param processContext the [ProcessContext].
* @return the list of processor pipelines.
*/
protected abstract fun getProcessorPipelines(processContext: ProcessContext): List<ProcessorPipeline>
}
| apache-2.0 | a1611adb4c143482f8e61e6a2c2ec448 | 33.306667 | 103 | 0.750097 | 4.773655 | false | false | false | false |
http4k/http4k | http4k-multipart/src/main/kotlin/org/http4k/lens/multipartForm.kt | 1 | 3537 | package org.http4k.lens
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.ContentType.Companion.MULTIPART_FORM_DATA
import org.http4k.core.ContentType.Companion.MultipartFormWithBoundary
import org.http4k.core.HttpMessage
import org.http4k.core.MultipartEntity
import org.http4k.core.MultipartFormBody
import org.http4k.core.MultipartFormBody.Companion.DEFAULT_DISK_THRESHOLD
import org.http4k.core.with
import org.http4k.lens.ContentNegotiation.Companion.Strict
import org.http4k.lens.Header.CONTENT_TYPE
import java.io.Closeable
import java.util.UUID
data class MultipartForm(val fields: Map<String, List<MultipartFormField>> = emptyMap(),
val files: Map<String, List<MultipartFormFile>> = emptyMap(),
val errors: List<Failure> = emptyList()) : Closeable {
override fun close() = files.values.flatten().forEach(MultipartFormFile::close)
operator fun plus(kv: Pair<String, String>) =
copy(fields = fields + (kv.first to fields.getOrDefault(kv.first, emptyList()) + MultipartFormField(kv.second)))
@JvmName("plusField")
operator fun plus(kv: Pair<String, MultipartFormField>) =
copy(fields = fields + (kv.first to fields.getOrDefault(kv.first, emptyList()) + kv.second))
@JvmName("plusFile")
operator fun plus(kv: Pair<String, MultipartFormFile>) =
copy(files = files + (kv.first to files.getOrDefault(kv.first, emptyList()) + kv.second))
fun minusField(name: String) = copy(fields = fields - name)
fun minusFile(name: String) = copy(files = files - name)
}
val MULTIPART_BOUNDARY = UUID.randomUUID().toString()
fun Body.Companion.multipartForm(
validator: Validator,
vararg parts: Lens<MultipartForm, *>,
defaultBoundary: String = MULTIPART_BOUNDARY,
diskThreshold: Int = DEFAULT_DISK_THRESHOLD,
contentTypeFn: (String) -> ContentType = ::MultipartFormWithBoundary
): BiDiBodyLensSpec<MultipartForm> =
BiDiBodyLensSpec(parts.map { it.meta }, MULTIPART_FORM_DATA,
LensGet { _, target ->
listOf(MultipartFormBody.from(target, diskThreshold).apply {
Strict(contentTypeFn(boundary), CONTENT_TYPE(target))
})
},
LensSet { _: String, values: List<Body>, target: HttpMessage ->
values.fold(target) { a, b ->
a.body(b)
.with(CONTENT_TYPE of contentTypeFn(defaultBoundary))
}
})
.map({ it.toMultipartForm() }, { it.toMultipartFormBody(defaultBoundary) })
.map({ it.copy(errors = validator(it, parts.toList())) }, { it.copy(errors = validator(it, parts.toList())) })
internal fun Body.toMultipartForm(): MultipartForm = (this as MultipartFormBody).let {
it.formParts.fold(MultipartForm()) { memo, next ->
when (next) {
is MultipartEntity.File -> memo + (next.name to next.file)
is MultipartEntity.Field -> memo + (next.name to next.value)
}
}
}
internal fun MultipartForm.toMultipartFormBody(boundary: String): MultipartFormBody {
val withFields = fields.toList()
.fold(MultipartFormBody(boundary = boundary)) { body, (name, values) ->
values.fold(body) { bodyMemo, fieldValue ->
bodyMemo + (name to fieldValue)
}
}
return files.toList()
.fold(withFields) { body, (name, values) ->
values.fold(body) { bodyMemo, file ->
bodyMemo + (name to file)
}
}
}
| apache-2.0 | 1bd5485ec51ebfd6833e8b56408f5ca2 | 40.611765 | 120 | 0.662426 | 3.974157 | false | false | false | false |
vhromada/Catalog-Swing | src/main/kotlin/cz/vhromada/catalog/gui/common/AbstractInfoDialog.kt | 1 | 16920 | package cz.vhromada.catalog.gui.common
import cz.vhromada.catalog.entity.Genre
import cz.vhromada.catalog.facade.GenreFacade
import cz.vhromada.catalog.facade.PictureFacade
import cz.vhromada.catalog.gui.genre.GenreChooseDialog
import cz.vhromada.catalog.gui.picture.PictureChooseDialog
import cz.vhromada.common.entity.Language
import java.awt.EventQueue
import javax.swing.ButtonModel
import javax.swing.GroupLayout
import javax.swing.JButton
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JDialog
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JRadioButton
import javax.swing.JSpinner
import javax.swing.WindowConstants
import javax.swing.text.JTextComponent
/**
* An abstract class represents dialog for adding or updating data.
*
* @param <T> type of data
* @author Vladimir Hromada
*/
abstract class AbstractInfoDialog<T> : JDialog {
/**
* Return status
*/
var returnStatus = DialogResult.CANCEL
private set
/**
* Data
*/
var data: T? = null
private set
/**
* Button OK
*/
private val okButton = JButton("OK", Picture.OK.icon)
/**
* Button Cancel
*/
private val cancelButton = JButton("Cancel", Picture.CANCEL.icon)
/**
* Creates a new instance of AbstractInfoDialog.
*/
constructor() : this("Add", Picture.ADD) {
okButton.isEnabled = false
}
/**
* Creates a new instance of AbstractInfoDialog.
*
* @param data data
* @throws IllegalArgumentException if data are null
*/
constructor(data: T) : this("Update", Picture.UPDATE) {
this.data = data
}
/**
* Creates a new instance of AbstractInfoDialog.
*
* @param name name
* @param picture picture
*/
private constructor(name: String, picture: Picture) : super(JFrame(), name, true) {
initDialog(picture)
okButton.addActionListener { okAction() }
cancelButton.addActionListener { cancelAction() }
}
/**
* Initializes components.
*/
protected abstract fun initComponents()
/**
* Returns object with filled data.
*
* @param objectData object for filling data
* @return object with filled data
*/
protected abstract fun processData(objectData: T?): T?
/**
* Returns horizontal layout with added components.
*
* @param layout horizontal layout
* @param group group in vertical layout
* @return horizontal layout with added components
*/
protected abstract fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group
/**
* Returns vertical layout with added components.
*
* @param layout vertical layout
* @param group group in vertical layout
* @return vertical layout with added components
*/
protected abstract fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group
/**
* Initializes.
*/
protected fun init() {
initComponents()
createLayout()
}
/**
* Initializes label with component.
*
* @param label label
* @param component component
*/
protected fun initLabelComponent(label: JLabel, component: JComponent) {
label.labelFor = component
label.isFocusable = false
}
/**
* Adds validator to input.
*
* @param input input
*/
protected fun addInputValidator(input: JTextComponent) {
input.document.addDocumentListener(object : InputValidator(okButton) {
override val isInputValid: Boolean
get() = [email protected]()
})
}
/**
* Adds validator to spinner.
*
* @param spinner spinner
*/
protected fun addSpinnerValidator(spinner: JSpinner) {
spinner.addChangeListener { okButton.isEnabled = isInputValid() }
}
/**
* Returns true if input is valid.
*
* @return true if input is valid
*/
protected open fun isInputValid(): Boolean {
return true
}
/**
* Sets enabled to button OK.
*
* @param enabled true if button should be enabled
*/
protected fun setOkButtonEnabled(enabled: Boolean) {
okButton.isEnabled = enabled
}
/**
* Returns genres.
*
* @param genres list of genres
* @return genres
*/
@Suppress("DuplicatedCode")
protected fun getGenres(genres: List<Genre>): String {
if (genres.isEmpty()) {
return ""
}
val genresString = StringBuilder()
for (genre in genres) {
genresString.append(genre.name)
genresString.append(", ")
}
return genresString.substring(0, genresString.length - 2)
}
/**
* Returns picture.
*
* @param pictures list of pictures
* @return picture
*/
protected fun getPicture(pictures: List<Int>): String {
return if (pictures.isEmpty()) "" else pictures[0].toString()
}
/**
* Performs action for button Genres.
*
* @param genreFacade facade for genres
* @param genres list of genres
* @param genreData data with genres
*/
protected fun genresAction(genreFacade: GenreFacade, genres: MutableList<Genre>, genreData: JLabel) {
EventQueue.invokeLater {
val dialog = GenreChooseDialog(genreFacade, genres)
dialog.isVisible = true
if (dialog.returnStatus === DialogResult.OK) {
genreData.text = getGenres(genres)
setOkButtonEnabled(isInputValid())
}
}
}
/**
* Performs action for button Change pictures.
*
* @param pictureFacade facade for pictures
* @param pictures list of pictures
* @param pictureData data with genres
*/
protected fun pictureAction(pictureFacade: PictureFacade, pictures: MutableList<Int>, pictureData: JLabel) {
EventQueue.invokeLater {
val pictureEntity = cz.vhromada.catalog.entity.Picture(id = if (pictures.isEmpty()) null else pictures[0], content = null, position = null)
val dialog = PictureChooseDialog(pictureFacade, pictureEntity)
dialog.isVisible = true
if (dialog.returnStatus === DialogResult.OK) {
pictures.clear()
pictures.add(dialog.picture.id!!)
pictureData.text = getPicture(pictures)
setOkButtonEnabled(isInputValid())
}
}
}
/**
* Initializes language.
*
* @param language language
* @param czechLanguageData radio button for czech language
* @param englishLanguageData radio button for english language
* @param frenchLanguageData radio button for french language
* @param japaneseLanguageData radio button for japanese language
* @param slovakLanguageData radio button for slovak language
*/
protected fun initLanguage(language: Language,
czechLanguageData: JRadioButton,
englishLanguageData: JRadioButton,
frenchLanguageData: JRadioButton,
japaneseLanguageData: JRadioButton,
slovakLanguageData: JRadioButton) {
when (language) {
Language.CZ -> czechLanguageData.isSelected = true
Language.EN -> englishLanguageData.isSelected = true
Language.FR -> frenchLanguageData.isSelected = true
Language.JP -> japaneseLanguageData.isSelected = true
Language.SK -> slovakLanguageData.isSelected = true
}
}
/**
* Returns selected language.
*
* @param model button model
* @param czechLanguageData radio button for czech language
* @param englishLanguageData radio button for english language
* @param frenchLanguageData radio button for french language
* @param japaneseLanguageData radio button for japanese language
* @return selected language
*/
protected fun getSelectedLanguage(model: ButtonModel,
czechLanguageData: JRadioButton,
englishLanguageData: JRadioButton,
frenchLanguageData: JRadioButton,
japaneseLanguageData: JRadioButton): Language {
return when (model) {
czechLanguageData.model -> Language.CZ
englishLanguageData.model -> Language.EN
frenchLanguageData.model -> Language.FR
japaneseLanguageData.model -> Language.JP
else -> Language.SK
}
}
/**
* Initializes subtitles.
*
* @param subtitles list of subtitles
* @param czechSubtitlesData check box for czech subtitles
* @param englishSubtitlesData check box for english subtitles
*/
protected fun initSubtitles(subtitles: List<Language?>, czechSubtitlesData: JCheckBox, englishSubtitlesData: JCheckBox) {
for (language in subtitles.filterNotNull()) {
when (language) {
Language.CZ -> czechSubtitlesData.isSelected = true
Language.EN -> englishSubtitlesData.isSelected = true
else -> throw IndexOutOfBoundsException("Bad subtitles")
}
}
}
/**
* Returns selected subtitles.
*
* @param czechSubtitlesData check box for czech subtitles
* @param englishSubtitlesData check box for english subtitles
* @return selected subtitles
*/
protected fun getSelectedSubtitles(czechSubtitlesData: JCheckBox, englishSubtitlesData: JCheckBox): List<Language> {
val subtitles = mutableListOf<Language>()
if (czechSubtitlesData.isSelected) {
subtitles.add(Language.CZ)
}
if (englishSubtitlesData.isSelected) {
subtitles.add(Language.EN)
}
return subtitles
}
/**
* Creates layout.
*/
protected fun createLayout() {
val layout = GroupLayout(getRootPane())
getRootPane().layout = layout
layout.setHorizontalGroup(createHorizontalLayout(layout))
layout.setVerticalGroup(createVerticalLayout(layout))
pack()
setLocationRelativeTo(getRootPane())
}
/**
* Returns horizontal layout for label component with data component.
*
* @param layout layout
* @param labelComponent label component
* @param dataComponent data component
* @return horizontal layout for label component with data component
*/
protected fun createHorizontalComponents(layout: GroupLayout, labelComponent: JComponent, dataComponent: JComponent): GroupLayout.Group {
return layout.createSequentialGroup()
.addComponent(labelComponent, HORIZONTAL_LABEL_DIALOG_SIZE, HORIZONTAL_LABEL_DIALOG_SIZE, HORIZONTAL_LABEL_DIALOG_SIZE)
.addGap(HORIZONTAL_DATA_GAP_SIZE)
.addComponent(dataComponent, HORIZONTAL_DATA_DIALOG_SIZE, HORIZONTAL_DATA_DIALOG_SIZE, HORIZONTAL_DATA_DIALOG_SIZE)
}
/**
* Returns horizontal layout for selectable component.
*
* @param layout layout
* @param component component
* @return horizontal layout for selectable component
*/
protected fun createHorizontalSelectableComponent(layout: GroupLayout, component: JComponent): GroupLayout.Group {
return layout.createSequentialGroup()
.addGap(HORIZONTAL_SELECTABLE_COMPONENT_GAP_SIZE)
.addComponent(component, HORIZONTAL_DATA_DIALOG_SIZE, HORIZONTAL_DATA_DIALOG_SIZE, HORIZONTAL_DATA_DIALOG_SIZE)
}
/**
* Returns vertical layout for label component with data component.
*
* @param layout layout
* @param labelComponent label component
* @param dataComponent data component
* @return vertical layout for label component with data component
*/
protected fun createVerticalComponents(layout: GroupLayout, labelComponent: JComponent, dataComponent: JComponent): GroupLayout.Group {
return layout.createParallelGroup()
.addComponent(labelComponent, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
.addComponent(dataComponent, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE, CatalogSwingConstants.VERTICAL_COMPONENT_SIZE)
}
/**
* Initializes dialog.
*
* @param picture
*/
private fun initDialog(picture: Picture) {
defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE
isResizable = false
setIconImage(picture.icon.image)
}
/**
* Performs action for button OK.
*/
private fun okAction() {
returnStatus = DialogResult.OK
data = processData(data)
close()
}
/**
* Performs action for button Cancel.
*/
private fun cancelAction() {
returnStatus = DialogResult.CANCEL
data = null
close()
}
/**
* Closes dialog.
*/
private fun close() {
isVisible = false
dispose()
}
/**
* Returns horizontal layout of components.
*
* @param layout layout
* @return horizontal layout of components
*/
private fun createHorizontalLayout(layout: GroupLayout): GroupLayout.Group {
val buttons = layout.createSequentialGroup()
.addGap(HORIZONTAL_BUTTON_GAP_SIZE)
.addComponent(okButton, HORIZONTAL_BUTTON_SIZE, HORIZONTAL_BUTTON_SIZE, HORIZONTAL_BUTTON_SIZE)
.addGap(HORIZONTAL_BUTTONS_GAP_SIZE)
.addComponent(cancelButton, HORIZONTAL_BUTTON_SIZE, HORIZONTAL_BUTTON_SIZE, HORIZONTAL_BUTTON_SIZE)
.addGap(HORIZONTAL_BUTTON_GAP_SIZE)
val components = getHorizontalLayoutWithComponents(layout, layout.createParallelGroup())
.addGroup(buttons)
return layout.createSequentialGroup()
.addGap(HORIZONTAL_GAP_SIZE)
.addGroup(components)
.addGap(HORIZONTAL_GAP_SIZE)
}
/**
* Returns vertical layout of components.
*
* @param layout layout
* @return vertical layout of components
*/
private fun createVerticalLayout(layout: GroupLayout): GroupLayout.Group {
val buttons = layout.createParallelGroup()
.addComponent(okButton, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE)
.addComponent(cancelButton, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE, CatalogSwingConstants.VERTICAL_BUTTON_SIZE)
val components = layout.createSequentialGroup()
.addGap(VERTICAL_LONG_GAP_SIZE)
return getVerticalLayoutWithComponents(layout, components)
.addGap(VERTICAL_LONG_GAP_SIZE)
.addGroup(buttons)
.addGap(VERTICAL_LONG_GAP_SIZE)
}
companion object {
/**
* Horizontal long component size
*/
const val HORIZONTAL_LONG_COMPONENT_SIZE = 310
/**
* Vertical gap size
*/
const val VERTICAL_GAP_SIZE = 10
/**
* SerialVersionUID
*/
private const val serialVersionUID = 1L
/**
* Horizontal label size
*/
private const val HORIZONTAL_LABEL_DIALOG_SIZE = 100
/**
* Horizontal data size
*/
private const val HORIZONTAL_DATA_DIALOG_SIZE = 200
/**
* Horizontal button size
*/
private const val HORIZONTAL_BUTTON_SIZE = 96
/**
* Horizontal size of gap between label and data
*/
private const val HORIZONTAL_DATA_GAP_SIZE = 10
/**
* Horizontal selectable component gap size
*/
private const val HORIZONTAL_SELECTABLE_COMPONENT_GAP_SIZE = 110
/**
* Horizontal button gap size
*/
private const val HORIZONTAL_BUTTON_GAP_SIZE = 32
/**
* Horizontal size of gap between button
*/
private const val HORIZONTAL_BUTTONS_GAP_SIZE = 54
/**
* Horizontal gap size
*/
private const val HORIZONTAL_GAP_SIZE = 20
/**
* Vertical long gap size
*/
private const val VERTICAL_LONG_GAP_SIZE = 20
}
}
| mit | 8a98201ae7d3004b2d988307e6a639bd | 31.1673 | 186 | 0.627305 | 5.183824 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/libanki/TemplateManager.kt | 1 | 13429 | /*
* Copyright (c) 2021 David Allison <[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/>.
*
* This file incorporates code under the following license
* https://github.com/ankitects/anki/blob/2.1.34/pylib/anki/template.py
*
* Copyright: Ankitects Pty Ltd and contributors
* License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
*/
package com.ichi2.libanki
import com.ichi2.libanki.TemplateManager.PartiallyRenderedCard.Companion.av_tags_to_native
import com.ichi2.libanki.backend.BackendUtils
import com.ichi2.libanki.backend.model.toBackendNote
import com.ichi2.libanki.utils.append
import com.ichi2.libanki.utils.len
import com.ichi2.utils.deepClone
import net.ankiweb.rsdroid.RustCleanup
import net.ankiweb.rsdroid.exceptions.BackendTemplateException
import org.json.JSONObject
import timber.log.Timber
private typealias Union<A, B> = Pair<A, B>
private typealias TemplateReplacementList = MutableList<Union<str?, TemplateManager.TemplateReplacement?>>
/**
* Template.py in python. Called TemplateManager for technical reasons (conflict with Kotlin typealias)
*
* This file contains the Kotlin portion of the template rendering code.
* Templates can have filters applied to field replacements.
*
* The Rust template rendering code will apply any built in filters, and stop at the first
* unrecognized filter. The remaining filters are returned to Kotlin, and applied using the hook system.
*
* For example, {{myfilter:hint:text:Field}} will apply the built in text and hint filters,
* and then attempt to apply myfilter. If no add-ons have provided the filter,
* the filter is skipped.
*/
class TemplateManager {
data class TemplateReplacement(val field_name: str, var current_text: str, val filters: List<str>)
data class PartiallyRenderedCard(val qnodes: TemplateReplacementList, val anodes: TemplateReplacementList) {
companion object {
fun from_proto(out: anki.card_rendering.RenderCardResponse): PartiallyRenderedCard {
val qnodes = nodes_from_proto(out.questionNodesList)
val anodes = nodes_from_proto(out.answerNodesList)
return PartiallyRenderedCard(qnodes, anodes)
}
fun nodes_from_proto(nodes: List<anki.card_rendering.RenderedTemplateNode>): TemplateReplacementList {
val results: TemplateReplacementList = mutableListOf()
for (node in nodes) {
if (node.valueCase == anki.card_rendering.RenderedTemplateNode.ValueCase.TEXT) {
results.append(Pair(node.text, null))
} else {
results.append(
Pair(
null,
TemplateReplacement(
field_name = node.replacement.fieldName,
current_text = node.replacement.currentText,
filters = node.replacement.filtersList,
)
)
)
}
}
return results
}
fun av_tag_to_native(tag: anki.card_rendering.AVTag): AvTag {
val value = tag.valueCase
return if (value == anki.card_rendering.AVTag.ValueCase.SOUND_OR_VIDEO) {
SoundOrVideoTag(filename = tag.soundOrVideo)
} else {
TTSTag(
fieldText = tag.tts.fieldText,
lang = tag.tts.lang,
voices = tag.tts.voicesList,
otherArgs = tag.tts.otherArgsList,
speed = tag.tts.speed,
)
}
}
fun av_tags_to_native(tags: List<anki.card_rendering.AVTag>): List<AvTag> {
return tags.map { av_tag_to_native(it) }.toList()
}
}
}
/**
* Holds information for the duration of one card render.
* This may fetch information lazily in the future, so please avoid
* using the _private fields directly.
*/
class TemplateRenderContext(
col: Collection,
card: Card,
note: Note,
browser: bool = false,
notetype: NoteType? = null,
template: JSONObject? = null,
fill_empty: bool = false
) {
@RustCleanup("internal variables should be private, revert them once we're on V16")
@RustCleanup("this was a WeakRef")
internal val _col: Collection = col
internal var _card: Card = card
internal var _note: Note = note
internal var _browser: bool = browser
internal var _template: JSONObject? = template
internal var _fill_empty: bool = fill_empty
private var _fields: Dict<str, str>? = null
internal var _note_type: NoteType = notetype ?: note.model()
/**
* if you need to store extra state to share amongst rendering
* hooks, you can insert it into this dictionary
*/
private var extra_state: HashMap<str, Any> = Dict()
companion object {
fun from_existing_card(card: Card, browser: bool): TemplateRenderContext {
return TemplateRenderContext(card.col, card, card.note(), browser)
}
fun from_card_layout(
note: Note,
card: Card,
notetype: NoteType,
template: JSONObject,
fill_empty: bool,
): TemplateRenderContext {
return TemplateRenderContext(
note.col,
card,
note,
notetype = notetype,
template = template,
fill_empty = fill_empty,
)
}
}
fun col() = _col
fun fields(): Dict<str, str> {
Timber.w(".fields() is obsolete, use .note() or .card()")
if (_fields == null) {
// fields from note
val fields = _note.items().map { Pair(it[0]!!, it[1]!!) }.toMap().toMutableMap()
// add (most) special fields
fields["Tags"] = _note.stringTags().trim()
fields["Type"] = _note_type.name
fields["Deck"] = _col.decks.name(_card.oDid or _card.did)
fields["Subdeck"] = Decks.basename(fields["Deck"]!!)
if (_template != null) {
fields["Card"] = _template!!["name"] as String
} else {
fields["Card"] = ""
}
val flag = _card.userFlag()
fields["CardFlag"] = if (flag != 0) "flag$flag" else ""
_fields = HashMap(fields)
}
return _fields!!
}
/**
* Returns the card being rendered.
* Be careful not to call .q() or .a() on the card, or you'll create an
* infinite loop.
*/
fun card() = _card
fun note() = _note
fun note_type() = _note_type
@RustCleanup("legacy")
fun qfmt(): str {
return templates_for_card(card(), _browser).first
}
@RustCleanup("legacy")
fun afmt(): str {
return templates_for_card(card(), _browser).second
}
fun render(): TemplateRenderOutput {
val partial: PartiallyRenderedCard
try {
partial = _partially_render()
} catch (e: BackendTemplateException) {
return TemplateRenderOutput(
question_text = e.localizedMessage ?: e.toString(),
answer_text = e.localizedMessage ?: e.toString(),
question_av_tags = emptyList(),
answer_av_tags = emptyList(),
)
}
val qtext = apply_custom_filters(partial.qnodes, this, front_side = null)
val qout = col().backend.extractAVTags(text = qtext, questionSide = true)
var qoutText = qout.text
val atext = apply_custom_filters(partial.anodes, this, front_side = qout.text)
val aout = col().backend.extractAVTags(text = atext, questionSide = false)
var aoutText = aout.text
if (!_browser) {
val svg = _note_type.optBoolean("latexsvg", false)
qoutText = LaTeX.mungeQA(qout.text, _col, svg)
aoutText = LaTeX.mungeQA(aout.text, _col, svg)
}
val output = TemplateRenderOutput(
question_text = qoutText,
answer_text = aoutText,
question_av_tags = av_tags_to_native(qout.avTagsList),
answer_av_tags = av_tags_to_native(aout.avTagsList),
css = note_type().getString("css"),
)
return output
}
@RustCleanup("Remove when DroidBackend supports named arguments")
fun _partially_render(): PartiallyRenderedCard {
val proto = col().newBackend.run {
if (_template != null) {
// card layout screen
backend.renderUncommittedCardLegacy(
_note.toBackendNote(),
_card.ord,
BackendUtils.to_json_bytes(_template!!.deepClone()),
_fill_empty,
)
} else {
// existing card (eg study mode)
backend.renderExistingCard(_card.id, _browser)
}
}
return PartiallyRenderedCard.from_proto(proto)
}
/** Stores the rendered templates and extracted AV tags. */
data class TemplateRenderOutput(
@get:JvmName("getQuestionText")
@set:JvmName("setQuestionText")
var question_text: str,
@get:JvmName("getAnswerText")
@set:JvmName("setAnswerText")
var answer_text: str,
val question_av_tags: List<AvTag>,
val answer_av_tags: List<AvTag>,
val css: str = ""
) {
fun question_and_style() = "<style>$css</style>$question_text"
fun answer_and_style() = "<style>$css</style>$answer_text"
}
@RustCleanup("legacy")
fun templates_for_card(card: Card, browser: bool): Pair<str, str> {
val template = card.template()
var a: String? = null
var q: String? = null
if (browser) {
q = template.getString("bqfmt")
a = template.getString("bafmt")
}
q = q ?: template.getString("qfmt")
a = a ?: template.getString("afmt")
return Pair(q!!, a!!)
}
/** Complete rendering by applying any pending custom filters. */
fun apply_custom_filters(
rendered: TemplateReplacementList,
@Suppress("unused_parameter") ctx: TemplateRenderContext,
front_side: str?
): str {
// template already fully rendered?
if (len(rendered) == 1 && rendered[0].first != null) {
return rendered[0].first!!
}
var res = ""
for (union in rendered) {
if (union.first != null) {
res += union.first!!
} else {
val node = union.second!!
// do we need to inject in FrontSide?
if (node.field_name == "FrontSide" && front_side != null) {
node.current_text = front_side
}
val field_text = node.current_text
// AnkiDroid: ignored hook-based code
// for (filter_name in node.filters) {
// field_text = hooks.field_filter(field_text, node.field_name, filter_name, ctx
// )
// // legacy hook - the second and fifth argument are no longer used.
// field_text = anki.hooks.runFilter(
// "fmod_" + filter_name,
// field_text,
// "",
// ctx.note().items(),
// node.field_name,
// "",
// )
// }
res += field_text
}
}
return res
}
}
}
| gpl-3.0 | 9f7958a6ad1c76db91a4083987261434 | 38.151603 | 114 | 0.528707 | 4.638687 | false | false | false | false |
magnusja/libaums | libaums/src/main/java/me/jahnen/libaums/core/usb/JellyBeanMr2Communication.kt | 2 | 2014 | package me.jahnen.libaums.core.usb
/**
* Created by magnusja on 21/12/16.
*/
import android.annotation.TargetApi
import android.hardware.usb.*
import android.os.Build
import android.system.OsConstants.EPIPE
import me.jahnen.libaums.core.ErrNo
import java.io.IOException
import java.nio.ByteBuffer
/**
* Usb communication which uses the newer API in Android Jelly Bean MR2 (API
* level 18). It just delegates the calls to the [UsbDeviceConnection]
* .
*
* @author mjahnen
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
internal class JellyBeanMr2Communication(
usbManager: UsbManager,
usbDevice: UsbDevice,
usbInterface: UsbInterface,
outEndpoint: UsbEndpoint,
inEndpoint: UsbEndpoint
) : AndroidUsbCommunication(usbManager, usbDevice, usbInterface, outEndpoint, inEndpoint) {
@Throws(IOException::class)
override fun bulkOutTransfer(src: ByteBuffer): Int {
val result = deviceConnection!!.bulkTransfer(outEndpoint,
src.array(), src.position(), src.remaining(), UsbCommunication.TRANSFER_TIMEOUT)
if (result == -1) {
when (ErrNo.errno) {
EPIPE -> throw PipeException()
else -> throw IOException("Could not read from device, result == -1 errno " + ErrNo.errno + " " + ErrNo.errstr)
}
}
src.position(src.position() + result)
return result
}
@Throws(IOException::class)
override fun bulkInTransfer(dest: ByteBuffer): Int {
val result = deviceConnection!!.bulkTransfer(inEndpoint,
dest.array(), dest.position(), dest.remaining(), UsbCommunication.TRANSFER_TIMEOUT)
if (result == -1) {
when (ErrNo.errno) {
EPIPE -> throw PipeException()
else -> throw IOException("Could not read from device, result == -1 errno " + ErrNo.errno + " " + ErrNo.errstr)
}
}
dest.position(dest.position() + result)
return result
}
}
| apache-2.0 | 8a2d412513159261e9c9df71a6459014 | 31.483871 | 127 | 0.644489 | 4.068687 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/processModel/SplitInstance.kt | 1 | 10562 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.processModel
import net.devrieze.util.Handle
import net.devrieze.util.collection.replaceByNotNull
import net.devrieze.util.overlay
import net.devrieze.util.security.SecureObject
import nl.adaptivity.process.IMessageService
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.engine.impl.LogLevel
import nl.adaptivity.process.processModel.Join
import nl.adaptivity.process.processModel.engine.ConditionResult
import nl.adaptivity.process.processModel.engine.ExecutableSplit
import nl.adaptivity.util.security.Principal
import nl.adaptivity.xmlutil.util.ICompactFragment
/**
* Specialisation of process node instance for splits
*/
class SplitInstance : ProcessNodeInstance<SplitInstance> {
interface Builder : ProcessNodeInstance.Builder<ExecutableSplit, SplitInstance> {
override fun build(): SplitInstance
var predecessor: Handle<SecureObject<ProcessNodeInstance<*>>>?
get() = predecessors.firstOrNull()
set(value) = predecessors.replaceByNotNull(value)
override fun doProvideTask(engineData: MutableProcessEngineDataAccess): Boolean {
return node.provideTask(engineData, this)
}
override fun doTakeTask(engineData: MutableProcessEngineDataAccess): Boolean {
return node.takeTask(this)
}
override fun doStartTask(engineData: MutableProcessEngineDataAccess): Boolean {
state = NodeInstanceState.Started
return updateState(engineData)
}
override fun doFinishTask(engineData: MutableProcessEngineDataAccess, resultPayload: ICompactFragment?) {
val committedSuccessors = processInstanceBuilder.allChildNodeInstances { it.state.isCommitted }
if (committedSuccessors.count() < node.min) {
throw ProcessException("A split can only be finished once the minimum amount of children is committed")
}
super.doFinishTask(engineData, resultPayload)
}
}
class ExtBuilder(private val instance: SplitInstance, processInstanceBuilder: ProcessInstance.Builder) :
ProcessNodeInstance.ExtBuilder<ExecutableSplit, SplitInstance>(instance, processInstanceBuilder), Builder {
override var node: ExecutableSplit by overlay { instance.node }
override fun build() = if (changed) SplitInstance(this).also { invalidateBuilder(it) } else base
override fun tickle(engineData: MutableProcessEngineDataAccess, messageService: IMessageService<*>) {
super<Builder>.tickle(engineData, messageService) // XXX for debugging
}
}
class BaseBuilder(
node: ExecutableSplit,
predecessor: Handle<SecureObject<ProcessNodeInstance<*>>>,
processInstanceBuilder: ProcessInstance.Builder,
owner: Principal,
entryNo: Int,
handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(),
state: NodeInstanceState = NodeInstanceState.Pending
) : ProcessNodeInstance.BaseBuilder<ExecutableSplit, SplitInstance>(
node, listOf(predecessor), processInstanceBuilder, owner, entryNo,
handle, state
), Builder {
override fun build() = SplitInstance(this)
override fun tickle(engineData: MutableProcessEngineDataAccess, messageService: IMessageService<*>) {
super<Builder>.tickle(engineData, messageService)
}
}
override val node: ExecutableSplit
get() = super.node as ExecutableSplit
@Suppress("UNCHECKED_CAST")
override val handle: Handle<SecureObject<SplitInstance>>
get() = super.handle as Handle<SecureObject<SplitInstance>>
constructor(
node: ExecutableSplit,
predecessor: Handle<SecureObject<ProcessNodeInstance<*>>>,
processInstanceBuilder: ProcessInstance.Builder,
hProcessInstance: Handle<SecureObject<ProcessInstance>>,
owner: Principal,
handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(),
state: NodeInstanceState = NodeInstanceState.Pending,
results: Iterable<ProcessData> = emptyList(),
entryNo: Int
) : super(
node,
listOf(predecessor),
processInstanceBuilder,
hProcessInstance,
owner,
entryNo,
handle,
state,
results
)
constructor(builder: Builder) : this(
builder.node,
builder.predecessor ?: throw NullPointerException("Missing predecessor node instance"),
builder.processInstanceBuilder,
builder.hProcessInstance,
builder.owner,
builder.handle,
builder.state,
builder.results,
builder.entryNo
)
override fun builder(processInstanceBuilder: ProcessInstance.Builder): ExtBuilder {
return ExtBuilder(this, processInstanceBuilder)
}
private fun successorInstances(engineData: ProcessEngineDataAccess): Sequence<ProcessNodeInstance<*>> {
val instance = engineData.instance(hProcessInstance).withPermission()
return node.successors
.asSequence()
.mapNotNull { instance.getChild(it.id, entryNo)?.withPermission() }
.filter { it.entryNo == entryNo }
}
companion object {
internal fun isActiveOrCompleted(it: IProcessNodeInstance): Boolean {
return when (it.state) {
NodeInstanceState.Started,
NodeInstanceState.Complete,
NodeInstanceState.Skipped,
NodeInstanceState.SkippedCancel,
NodeInstanceState.SkippedFail,
NodeInstanceState.Failed,
NodeInstanceState.Taken -> true
else -> false
}
}
}
}
/**
* Update the state of the split.
*
* @return Whether or not the split is complete.
*
* TODO Review this algorithm
*/
internal fun SplitInstance.Builder.updateState(engineData: MutableProcessEngineDataAccess): Boolean {
if (state.isFinal) return true
val successorNodes = node.successors.map { node.ownerModel.getNode(it).mustExist(it) }.toList()
var skippedCount = 0
var failedCount = 0
var activeCount = 0
var committedCount = 0
var otherwiseNode: ProcessNodeInstance.Builder<*, *>? = null
for (successorNode in successorNodes) {
if (committedCount >= node.max) break // stop the loop when we are at the maximum successor count
if (successorNode is Join && successorNode.conditions[node.identifier] == null) {
throw IllegalStateException("Splits cannot be immediately followed by unconditional joins")
}
// Don't attempt to create an additional instance for a non-multi-instance successor
if (!successorNode.isMultiInstance &&
processInstanceBuilder.allChildNodeInstances {
it.node == successorNode && !it.state.isSkipped && it.entryNo != entryNo
}.count() > 0) continue
val successorBuilder = successorNode
.createOrReuseInstance(engineData, processInstanceBuilder, this, entryNo, allowFinalInstance = true)
processInstanceBuilder.storeChild(successorBuilder)
if (successorBuilder.state == NodeInstanceState.Pending ||
(successorBuilder.node is Join && successorBuilder.state.isActive)
) {
if (successorBuilder.isOtherwiseCondition(this)) {
otherwiseNode = successorBuilder
}
when (successorBuilder.condition(processInstanceBuilder, this)) {
// only if it can be executed, otherwise just drop it.
ConditionResult.TRUE -> if (
successorBuilder.state.canRestart ||
successorBuilder is Join.Builder
) successorBuilder.provideTask(engineData)
ConditionResult.NEVER -> successorBuilder.skipTask(engineData, NodeInstanceState.Skipped)
ConditionResult.MAYBE -> Unit /*option can not be advanced for now*/
}
}
successorBuilder.state.also { state ->
when {
state.isSkipped -> skippedCount++
state == NodeInstanceState.Failed -> failedCount++
state.isCommitted -> committedCount++
state.isActive -> activeCount++
}
}
}
if ((successorNodes.size - (skippedCount + failedCount)) < node.min) { // No way to succeed, try to cancel anything that is not in a final state
for (successor in processInstanceBuilder.allChildNodeInstances { handle in it.predecessors && !it.state.isFinal }) {
try {
successor.builder(processInstanceBuilder).cancel(engineData)
} catch (e: IllegalArgumentException) {
engineData.logger.log(LogLevel.WARNING, "Task could not be cancelled", e)
} // mainly ignore
}
state = NodeInstanceState.Failed
return true // complete, but invalid
}
// If we determined the maximum
if (committedCount >= node.max) {
processInstanceBuilder
.allChildNodeInstances { !SplitInstance.isActiveOrCompleted(it) && handle in it.predecessors }
.forEach {
processInstanceBuilder.updateChild(it) {
cancelAndSkip(engineData)
}
}
return true // We reached the max
}
// If all successors are committed
if (activeCount == 0 && successorNodes.size <= skippedCount + failedCount + committedCount) {
// no need to cancel, just complete
return true
}
// If we have an otherwise node
if (otherwiseNode != null && (skippedCount + failedCount + 1) == successorNodes.size) {
otherwiseNode.provideTask(engineData)
return true
}
return false
}
| lgpl-3.0 | c98dd76d871e277bb65a39a1c7073bca | 38.263941 | 148 | 0.669949 | 5.307538 | false | false | false | false |
SimonVT/cathode | cathode-provider/src/main/java/net/simonvt/cathode/provider/helper/PersonDatabaseHelper.kt | 1 | 4558 | /*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* 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.simonvt.cathode.provider.helper
import android.content.ContentValues
import android.content.Context
import net.simonvt.cathode.api.entity.Person
import net.simonvt.cathode.common.database.getInt
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.PersonColumns
import net.simonvt.cathode.provider.ProviderSchematic.People
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.provider.update
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PersonDatabaseHelper @Inject constructor(private val context: Context) {
fun getId(traktId: Long): Long {
val c = context.contentResolver.query(
People.PEOPLE,
arrayOf(PersonColumns.ID),
PersonColumns.TRAKT_ID + "=?",
arrayOf(traktId.toString())
)
val id = if (!c.moveToFirst()) -1L else c.getLong(PersonColumns.ID)
c.close()
return id
}
fun getIdFromTmdb(tmdbId: Int): Long {
val c = context.contentResolver.query(
People.PEOPLE,
arrayOf(PersonColumns.ID),
PersonColumns.TMDB_ID + "=?",
arrayOf(tmdbId.toString())
)
val id = if (!c.moveToFirst()) -1L else c.getLong(PersonColumns.ID)
c.close()
return id
}
fun getTraktId(personId: Long): Long {
val c = context.contentResolver.query(People.withId(personId), arrayOf(PersonColumns.TRAKT_ID))
val id = if (!c.moveToFirst()) -1L else c.getLong(PersonColumns.TRAKT_ID)
c.close()
return id
}
fun getTmdbId(personId: Long): Int {
val c = context.contentResolver.query(People.withId(personId), arrayOf(PersonColumns.TMDB_ID))
val id = if (!c.moveToFirst()) -1 else c.getInt(PersonColumns.TMDB_ID)
c.close()
return id
}
private fun createPerson(traktId: Long): Long {
val values = ContentValues()
values.put(PersonColumns.TRAKT_ID, traktId)
values.put(PersonColumns.NEEDS_SYNC, true)
return People.getId(context.contentResolver.insert(People.PEOPLE, values)!!)
}
fun getIdOrCreate(person: Person): Long {
synchronized(LOCK_ID) {
val traktId = person.ids.trakt!!
val personId = getId(traktId)
return if (personId == -1L) {
createPerson(traktId)
} else {
personId
}
}
}
fun partialUpdate(person: Person): Long {
val id = getIdOrCreate(person)
val values = getPartialValues(person)
context.contentResolver.update(People.withId(id), values)
return id
}
fun fullUpdate(person: Person): Long {
val id = getIdOrCreate(person)
val values = getValues(person)
values.put(PersonColumns.NEEDS_SYNC, false)
context.contentResolver.update(People.withId(id), values)
return id
}
private fun getPartialValues(person: Person): ContentValues {
val values = ContentValues()
values.put(PersonColumns.NAME, person.name)
values.put(PersonColumns.TRAKT_ID, person.ids.trakt)
values.put(PersonColumns.SLUG, person.ids.slug)
values.put(PersonColumns.IMDB_ID, person.ids.imdb)
values.put(PersonColumns.TMDB_ID, person.ids.tmdb)
values.put(PersonColumns.TVRAGE_ID, person.ids.tvrage)
return values
}
private fun getValues(person: Person): ContentValues {
val values = ContentValues()
values.put(PersonColumns.NAME, person.name)
values.put(PersonColumns.TRAKT_ID, person.ids.trakt)
values.put(PersonColumns.SLUG, person.ids.slug)
values.put(PersonColumns.IMDB_ID, person.ids.imdb)
values.put(PersonColumns.TMDB_ID, person.ids.tmdb)
values.put(PersonColumns.TVRAGE_ID, person.ids.tvrage)
values.put(PersonColumns.BIOGRAPHY, person.biography)
values.put(PersonColumns.BIRTHDAY, person.birthday)
values.put(PersonColumns.DEATH, person.death)
values.put(PersonColumns.BIRTHPLACE, person.birthplace)
values.put(PersonColumns.HOMEPAGE, person.homepage)
return values
}
companion object {
private val LOCK_ID = Any()
}
}
| apache-2.0 | aadca08d632cb797d4be8db55dd47e78 | 31.557143 | 99 | 0.717639 | 3.827036 | false | false | false | false |
android/android-studio-poet | aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/GradleUtils.kt | 1 | 1813 | /*
Copyright 2017 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
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.androidstudiopoet.generators
import com.google.androidstudiopoet.gradle.Closure
import com.google.androidstudiopoet.gradle.Expression
import com.google.androidstudiopoet.gradle.StringStatement
import com.google.androidstudiopoet.models.Dependency
import com.google.androidstudiopoet.models.LibraryDependency
import com.google.androidstudiopoet.models.ModuleDependency
import com.google.androidstudiopoet.models.Repository
fun ModuleDependency.toExpression() = Expression(this.method, "project(':${this.name}')")
fun LibraryDependency.toExpression() = Expression(this.method, "\"${this.name}\"")
fun String.toApplyPluginExpression() = Expression("apply plugin:", "'$this'")
fun String.toClasspathExpression() = Expression("classpath", "\"$this\"")
fun Repository.toExpression() = when (this) {
is Repository.Named -> this.toExpression()
is Repository.Remote -> this.toExpression()
}
fun Repository.Named.toExpression() = StringStatement("${this.name}()")
fun Repository.Remote.toExpression() = Closure("maven", listOf(Expression("url", "\"${this.url}\"")))
fun Dependency.toExpression() = when (this) {
is ModuleDependency -> this.toExpression()
is LibraryDependency -> this.toExpression()
else -> null
}
| apache-2.0 | 82e62b4a4040f19db1d0c21fde5342f5 | 36.770833 | 101 | 0.772752 | 4.476543 | false | false | false | false |
googlesamples/mlkit | android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/demo/kotlin/barcodescanner/BarcodeGraphic.kt | 1 | 2986 | /*
* Copyright 2020 Google LLC. All rights reserved.
*
* 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.mlkit.vision.demo.kotlin.barcodescanner
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.demo.GraphicOverlay
import com.google.mlkit.vision.demo.GraphicOverlay.Graphic
import kotlin.math.max
import kotlin.math.min
/** Graphic instance for rendering Barcode position and content information in an overlay view. */
class BarcodeGraphic constructor(overlay: GraphicOverlay?, private val barcode: Barcode?) :
Graphic(overlay) {
private val rectPaint: Paint = Paint()
private val barcodePaint: Paint
private val labelPaint: Paint
init {
rectPaint.color = MARKER_COLOR
rectPaint.style = Paint.Style.STROKE
rectPaint.strokeWidth = STROKE_WIDTH
barcodePaint = Paint()
barcodePaint.color = TEXT_COLOR
barcodePaint.textSize = TEXT_SIZE
labelPaint = Paint()
labelPaint.color = MARKER_COLOR
labelPaint.style = Paint.Style.FILL
}
/**
* Draws the barcode block annotations for position, size, and raw value on the supplied canvas.
*/
override fun draw(canvas: Canvas) {
checkNotNull(barcode) { "Attempting to draw a null barcode." }
// Draws the bounding box around the BarcodeBlock.
val rect = RectF(barcode.boundingBox)
// If the image is flipped, the left will be translated to right, and the right to left.
val x0 = translateX(rect.left)
val x1 = translateX(rect.right)
rect.left = min(x0, x1)
rect.right = max(x0, x1)
rect.top = translateY(rect.top)
rect.bottom = translateY(rect.bottom)
canvas.drawRect(rect, rectPaint)
// Draws other object info.
val lineHeight = TEXT_SIZE + 2 * STROKE_WIDTH
val textWidth = barcodePaint.measureText(barcode.displayValue)
canvas.drawRect(
rect.left - STROKE_WIDTH,
rect.top - lineHeight,
rect.left + textWidth + 2 * STROKE_WIDTH,
rect.top,
labelPaint
)
// Renders the barcode at the bottom of the box.
canvas.drawText(barcode.displayValue!!, rect.left, rect.top - STROKE_WIDTH, barcodePaint)
}
companion object {
private const val TEXT_COLOR = Color.BLACK
private const val MARKER_COLOR = Color.WHITE
private const val TEXT_SIZE = 54.0f
private const val STROKE_WIDTH = 4.0f
}
}
| apache-2.0 | 83d37a8f385dae03cf08664d3acc65dd | 34.975904 | 98 | 0.72505 | 4.07367 | false | false | false | false |
Esri/arcgis-runtime-demos-android | android-demos/GeotriggerMonitoring/GeotriggerMonitoringDemo-WithGeotriggers/app/src/main/java/com/arcgisruntime/sample/geotriggermonitoringdemo/domain/GeotriggerInteractor.kt | 1 | 3949 | package com.arcgisruntime.sample.geotriggermonitoringdemo.domain
import android.content.Context
import android.util.Log
import android.widget.Toast
import com.arcgisruntime.sample.geotriggermonitoringdemo.model.MapRepository
import com.esri.arcgisruntime.arcade.ArcadeExpression
import com.esri.arcgisruntime.geotriggers.FenceGeotrigger
import com.esri.arcgisruntime.geotriggers.FenceRuleType
import com.esri.arcgisruntime.geotriggers.GeotriggerMonitor
import com.esri.arcgisruntime.geotriggers.GeotriggerMonitorNotificationEvent
import com.esri.arcgisruntime.geotriggers.GeotriggerMonitorStatusChangedEvent
import com.esri.arcgisruntime.geotriggers.GeotriggerMonitorWarningChangedEvent
import com.esri.arcgisruntime.geotriggers.GraphicsOverlayFenceParameters
import com.esri.arcgisruntime.geotriggers.LocationGeotriggerFeed
import com.esri.arcgisruntime.location.AndroidLocationDataSource
import com.esri.arcgisruntime.location.LocationDataSource
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class GeotriggerInteractor @Inject constructor(
@ApplicationContext private val applicationContext: Context
) {
val monitors = mutableListOf<GeotriggerMonitor>()
private val _shouldMonitor = MutableStateFlow(false)
val shouldMonitor: StateFlow<Boolean> = _shouldMonitor
val lds: LocationDataSource = AndroidLocationDataSource(applicationContext)
fun createMonitors(graphicsOverlay: GraphicsOverlay, bufferDistance: Double) {
val feed = LocationGeotriggerFeed(lds)
val ruleType = FenceRuleType.ENTER_OR_EXIT
val fenceParameters = GraphicsOverlayFenceParameters(graphicsOverlay, bufferDistance)
val arcadeExpression =
ArcadeExpression("return {message:\$fencenotificationtype + ' a fence(' + \$fencefeature.name + ') with a course of ' + \$feedfeature.course, extra_info:456}")
val geotrigger =
FenceGeotrigger(
feed,
ruleType,
fenceParameters,
arcadeExpression,
"Graphics Overlay Geotrigger"
)
monitors.add(GeotriggerMonitor(geotrigger))
}
fun onNotificationEvent(geotriggerMonitorNotificationEvent: GeotriggerMonitorNotificationEvent) {
val message = geotriggerMonitorNotificationEvent.geotriggerNotificationInfo.message
Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}
fun onWarningEvent(geotriggerMonitorWarningChangedEvent: GeotriggerMonitorWarningChangedEvent) {
val warning = geotriggerMonitorWarningChangedEvent.warning?.additionalMessage
warning?.let {
Toast.makeText(applicationContext, it, Toast.LENGTH_LONG).show()
Log.e("GeotriggerInteractor", warning)
}
}
fun onMonitorStatuschanged(geotriggerMonitorStatusChangedEvent: GeotriggerMonitorStatusChangedEvent) {
val status = geotriggerMonitorStatusChangedEvent.status
Toast.makeText(applicationContext, status.name, Toast.LENGTH_SHORT).show()
}
fun setMonitoring(start: Boolean) {
// if starting, start the location data source first
if (start) {
lds.startAsync()
lds.addStatusChangedListener { statusChangedEvent ->
if (statusChangedEvent.status != LocationDataSource.Status.STARTED) {
lds.error?.message?.let { errorMessage ->
Log.e("MapViewModel", "Location data source not started: $errorMessage")
}
} else {
_shouldMonitor.value = true
}
}
}
else {
_shouldMonitor.value = false
lds.stop()
}
}
} | apache-2.0 | 9d52332f1901df5177f82ffd44282133 | 42.406593 | 171 | 0.731071 | 4.786667 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/history/HistoryFragment.kt | 1 | 2860 | package cc.aoeiuv020.panovel.history
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cc.aoeiuv020.panovel.App.Companion.ctx
import cc.aoeiuv020.panovel.IView
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.data.NovelManager
import cc.aoeiuv020.panovel.list.NovelListAdapter
import cc.aoeiuv020.panovel.main.MainActivity
import cc.aoeiuv020.panovel.settings.ListSettings
import kotlinx.android.synthetic.main.novel_item_list.*
/**
* 绝大部分照搬书架,
* Created by AoEiuV020 on 2017.10.15-18:07:39.
*/
class HistoryFragment : androidx.fragment.app.Fragment(), IView {
private val novelListAdapter by lazy {
NovelListAdapter(onError = ::showError)
}
private val presenter: HistoryPresenter = HistoryPresenter()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.novel_item_list, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rvNovel.layoutManager = if (ListSettings.gridView) {
androidx.recyclerview.widget.GridLayoutManager(ctx, if (ListSettings.largeView) 3 else 5)
} else {
androidx.recyclerview.widget.LinearLayoutManager(ctx)
}
rvNovel.adapter = novelListAdapter
srlRefresh.setOnRefreshListener {
forceRefresh()
}
presenter.attach(this)
}
override fun onDestroyView() {
presenter.detach()
super.onDestroyView()
}
override fun onStart() {
super.onStart()
refresh()
}
private fun refresh() {
srlRefresh.isRefreshing = true
presenter.refresh()
}
/**
* 强行刷新,重新下载小说详情,主要是看最新章,
*/
private fun forceRefresh() {
novelListAdapter.refresh()
refresh()
}
fun showNovelList(list: List<NovelManager>) {
novelListAdapter.data = list
// 历史页面不询问章节更新,
srlRefresh.isRefreshing = false
}
fun showAskUpdateResult(hasUpdateList: List<Long>) {
srlRefresh.isRefreshing = false
// 就算是空列表也要传进去,更新一下刷新时间,
// 空列表可能是因为连不上服务器,
novelListAdapter.hasUpdate(hasUpdateList)
}
@Suppress("UNUSED_PARAMETER")
fun askUpdateError(message: String, e: Throwable) {
// 询问服务器更新出错不展示,
srlRefresh.isRefreshing = false
}
fun showError(message: String, e: Throwable) {
srlRefresh.isRefreshing = false
(activity as? MainActivity)?.showError(message, e)
}
} | gpl-3.0 | c4c9c2274667704a8ac56439d3187447 | 27.784946 | 128 | 0.676009 | 4.22082 | false | false | false | false |
rickshory/VegNab | app/src/main/java/com/rickshory/vegnab/AppProvider.kt | 1 | 11422 | package com.rickshory.vegnab
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.SQLException
import android.database.sqlite.SQLiteQueryBuilder
import android.net.Uri
import android.util.Log
import com.rickshory.vegnab.contracts.Contract_Namers
import com.rickshory.vegnab.contracts.Contract_Projects
import com.rickshory.vegnab.contracts.Contract_Visits
/**
* Provider for the VegNab app
* This is the only class that knows about [AppDatabase]
* */
private const val TAG = "AppProvider"
const val CONTENT_AUTHORITY = "com.rickshory.vegnab.provider"
private const val PROJECTS = 100
private const val PROJECTS_ID = 102
private const val VISITS = 110
private const val VISITS_ID = 112
private const val VEGITEMS = 120
private const val VEGITEMS_ID = 122
private const val NAMERS = 130
private const val NAMERS_ID = 132
val CONTENT_AUTHORITY_URI: Uri = Uri.parse("content://$CONTENT_AUTHORITY")
class AppProvider: ContentProvider() {
private val uriMatcher by lazy { buildUriMatcher() }
private fun buildUriMatcher() : UriMatcher {
Log.d(TAG, "buildUriMatcher: starts")
val matcher = UriMatcher(UriMatcher.NO_MATCH)
matcher.addURI(CONTENT_AUTHORITY, Contract_Projects.TABLE_NAME, PROJECTS)
matcher.addURI(CONTENT_AUTHORITY, "${Contract_Projects.TABLE_NAME}/#", PROJECTS_ID)
matcher.addURI(CONTENT_AUTHORITY, Contract_Visits.TABLE_NAME, VISITS)
matcher.addURI(CONTENT_AUTHORITY, "${Contract_Visits.TABLE_NAME}/#", VISITS_ID)
// matcher.addURI(CONTENT_AUTHORITY, Contract_VegItems.TABLE_NAME, VEGITEMS)
// matcher.addURI(CONTENT_AUTHORITY, "${Contract_VegItems.TABLE_NAME}/#", VEGITEMS_ID)
matcher.addURI(CONTENT_AUTHORITY, Contract_Namers.TABLE_NAME, NAMERS)
matcher.addURI(CONTENT_AUTHORITY, "${Contract_Namers.TABLE_NAME}/#", NAMERS_ID)
return matcher
}
override fun onCreate(): Boolean {
Log.d(TAG, "onCreate: starts")
return true
}
override fun getType(uri: Uri): String? {
val match = uriMatcher.match(uri)
return when (match) {
PROJECTS -> Contract_Projects.CONTENT_TYPE
PROJECTS_ID -> Contract_Projects.CONTENT_ITEM_TYPE
VISITS -> Contract_Projects.CONTENT_TYPE
VISITS_ID -> Contract_Projects.CONTENT_ITEM_TYPE
NAMERS -> Contract_Namers.CONTENT_TYPE
NAMERS_ID -> Contract_Namers.CONTENT_ITEM_TYPE
else -> throw IllegalArgumentException("unknown uri: $uri")
}
}
override fun query(
uri: Uri,
projection: Array<String>?,
selection: String?,
selectionArgs: Array<String>?,
sortOrder: String?
): Cursor? {
Log.d(TAG, "query: called with uri $uri")
val match = uriMatcher.match(uri)
Log.d(TAG, "query: match = $match")
val queryBuilder = SQLiteQueryBuilder()
when (match) {
PROJECTS -> queryBuilder.tables = Contract_Projects.TABLE_NAME
PROJECTS_ID -> {
queryBuilder.tables = Contract_Projects.TABLE_NAME
val id = Contract_Projects.getID(uri)
queryBuilder.appendWhere("${Contract_Projects.Columns.ID} = ")
queryBuilder.appendWhereEscapeString("$id")
}
VISITS -> queryBuilder.tables = Contract_Visits.TABLE_NAME
VISITS_ID -> {
queryBuilder.tables = Contract_Visits.TABLE_NAME
val id = Contract_Visits.getID(uri)
queryBuilder.appendWhere("${Contract_Visits.Columns.ID} = ")
queryBuilder.appendWhereEscapeString("$id")
}
NAMERS -> queryBuilder.tables = Contract_Namers.TABLE_NAME
NAMERS_ID -> {
queryBuilder.tables = Contract_Namers.TABLE_NAME
val id = Contract_Namers.getID(uri)
queryBuilder.appendWhere("${Contract_Namers.Columns.ID} = ")
queryBuilder.appendWhereEscapeString("$id")
}
else -> throw IllegalArgumentException("Unknown URI: $uri")
}
val db = AppDatabase.getInstance(context).readableDatabase
val cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder)
Log.d(TAG, "query: rows in returned cursor = ${cursor.count}") // TODO remove this line
return cursor
}
override fun insert(uri: Uri, values: ContentValues): Uri? {
Log.d(TAG, "insert: called with uri $uri")
val match = uriMatcher.match(uri)
Log.d(TAG, "insert: match = $match")
val recordID: Long
val returnUri: Uri
when (match) {
PROJECTS -> {
val db = AppDatabase.getInstance(context).writableDatabase
recordID = db.insert(Contract_Projects.TABLE_NAME, null, values)
if (recordID != -1L) {
returnUri = Contract_Projects.buildUriFromId(recordID)
} else {
throw SQLException("Failed to insert. Uri was: $uri")
}
}
VISITS -> {
val db = AppDatabase.getInstance(context).writableDatabase
recordID = db.insert(Contract_Visits.TABLE_NAME, null, values)
if (recordID != -1L) {
returnUri = Contract_Visits.buildUriFromId(recordID)
} else {
throw SQLException("Failed to insert. Uri was: $uri")
}
}
NAMERS -> {
val db = AppDatabase.getInstance(context).writableDatabase
recordID = db.insert(Contract_Namers.TABLE_NAME, null, values)
if (recordID != -1L) {
returnUri = Contract_Namers.buildUriFromId(recordID)
} else {
throw SQLException("Failed to insert. Uri was: $uri")
}
}
else -> throw IllegalArgumentException("Unknown URI: $uri")
}
Log.d(TAG, "Exiting insert, returning Uri: $returnUri")
return returnUri
}
override fun update(uri: Uri, values: ContentValues, selection: String?, selectionArgs: Array<String>?): Int {
Log.d(TAG, "update: called with uri $uri")
val match = uriMatcher.match(uri)
Log.d(TAG, "update: match = $match")
var count: Int
var selectionCriteria: String
when (match) {
PROJECTS -> {
val db = AppDatabase.getInstance(context).writableDatabase
count = db.update(Contract_Projects.TABLE_NAME, values, selection, selectionArgs)
}
PROJECTS_ID -> {
val db = AppDatabase.getInstance(context).writableDatabase
val id = Contract_Projects.getID(uri)
selectionCriteria = "${Contract_Projects.Columns.ID}=$id"
if (selection != null && selection.isNotEmpty()) {
selectionCriteria += " AND ($selection)"
}
count = db.update(Contract_Projects.TABLE_NAME, values, selectionCriteria, selectionArgs)
}
VISITS -> {
val db = AppDatabase.getInstance(context).writableDatabase
count = db.update(Contract_Visits.TABLE_NAME, values, selection, selectionArgs)
}
VISITS_ID -> {
val db = AppDatabase.getInstance(context).writableDatabase
val id = Contract_Visits.getID(uri)
selectionCriteria = "${Contract_Visits.Columns.ID}=$id"
if (selection != null && selection.isNotEmpty()) {
selectionCriteria += " AND ($selection)"
}
count = db.update(Contract_Visits.TABLE_NAME, values, selectionCriteria, selectionArgs)
}
NAMERS -> {
val db = AppDatabase.getInstance(context).writableDatabase
count = db.update(Contract_Namers.TABLE_NAME, values, selection, selectionArgs)
}
NAMERS_ID -> {
val db = AppDatabase.getInstance(context).writableDatabase
val id = Contract_Namers.getID(uri)
selectionCriteria = "${Contract_Namers.Columns.ID}=$id"
if (selection != null && selection.isNotEmpty()) {
selectionCriteria += " AND ($selection)"
}
count = db.update(Contract_Namers.TABLE_NAME, values, selectionCriteria, selectionArgs)
}
else -> throw IllegalArgumentException("Unknown URI: $uri")
}
Log.d(TAG, "done with update: count = $count")
return count
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
Log.d(TAG, "delete: called with uri $uri")
val match = uriMatcher.match(uri)
Log.d(TAG, "delete: match = $match")
var count: Int
var selectionCriteria: String
when (match) {
PROJECTS -> {
val db = AppDatabase.getInstance(context).writableDatabase
count = db.delete(Contract_Projects.TABLE_NAME, selection, selectionArgs)
}
PROJECTS_ID -> {
val db = AppDatabase.getInstance(context).writableDatabase
val id = Contract_Projects.getID(uri)
selectionCriteria = "${Contract_Projects.Columns.ID}=$id"
if (selection != null && selection.isNotEmpty()) {
selectionCriteria += " AND ($selection)"
}
count = db.delete(Contract_Projects.TABLE_NAME, selectionCriteria, selectionArgs)
}
VISITS -> {
val db = AppDatabase.getInstance(context).writableDatabase
count = db.delete(Contract_Visits.TABLE_NAME, selection, selectionArgs)
}
VISITS_ID -> {
val db = AppDatabase.getInstance(context).writableDatabase
val id = Contract_Visits.getID(uri)
selectionCriteria = "${Contract_Visits.Columns.ID}=$id"
if (selection != null && selection.isNotEmpty()) {
selectionCriteria += " AND ($selection)"
}
count = db.delete(Contract_Visits.TABLE_NAME, selectionCriteria, selectionArgs)
}
NAMERS -> {
val db = AppDatabase.getInstance(context).writableDatabase
count = db.delete(Contract_Namers.TABLE_NAME, selection, selectionArgs)
}
NAMERS_ID -> {
val db = AppDatabase.getInstance(context).writableDatabase
val id = Contract_Namers.getID(uri)
selectionCriteria = "${Contract_Namers.Columns.ID}=$id"
if (selection != null && selection.isNotEmpty()) {
selectionCriteria += " AND ($selection)"
}
count = db.delete(Contract_Namers.TABLE_NAME, selectionCriteria, selectionArgs)
}
else -> throw IllegalArgumentException("Unknown URI: $uri")
}
Log.d(TAG, "done with delete: count = $count")
return count
}
} | gpl-3.0 | dc90457adf19e047af5b36aaabc529e2 | 39.363958 | 114 | 0.588338 | 4.650651 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/client/ClientNotification.kt | 2 | 10391 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.client
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.VisibleForTesting
import androidx.core.app.NotificationCompat
import androidx.core.content.getSystemService
import edu.berkeley.boinc.BOINCActivity
import edu.berkeley.boinc.R
import edu.berkeley.boinc.rpc.Result
import edu.berkeley.boinc.utils.Logging
import edu.berkeley.boinc.utils.getBitmapFromVectorDrawable
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@SuppressLint("WrongConstant")
@Singleton
class ClientNotification @Inject constructor(private val context: Context) {
private val nm = context.getSystemService<NotificationManager>()!!
private val notificationId: Int = context.resources.getInteger(R.integer.autostart_notification_id)
private val contentIntent: PendingIntent
private var n: Notification? = null
@VisibleForTesting
internal var mOldComputingStatus = -1
@VisibleForTesting
internal var mOldSuspendReason = -1
@VisibleForTesting
internal var mOldActiveTasks: MutableList<Result> = ArrayList()
@VisibleForTesting
internal var notificationShown = false
// debug foreground state by running
// adb shell: dumpsys activity services edu.berkeley.boinc
@VisibleForTesting
internal var foreground = false
/**
* Updates notification with client's current status. Notifies if not present. Checking
* notification-related preferences.
*
* @param updatedStatus client status data
* @param service reference to service, sets to foreground if active
* @param active indicator whether BOINC should stay in foreground (during computing and
* idle, i.e. not suspended)
*/
fun update(updatedStatus: ClientStatus?, service: Monitor?, active: Boolean) {
// nop if data is not present
if (service == null || updatedStatus == null) {
return
}
//check if active tasks have changed to force update
var activeTasksChanged = false
if (active && updatedStatus.computingStatus == ClientStatus.COMPUTING_STATUS_COMPUTING) {
val activeTasks = updatedStatus.executingTasks
if (activeTasks.size != mOldActiveTasks.size) {
activeTasksChanged = true
} else {
for (x in activeTasks.indices) {
if (activeTasks[x].name != mOldActiveTasks[x].name) {
activeTasksChanged = true
Logging.logVerbose(
Logging.Category.TASKS, "Active task: " + activeTasks[x].name +
", old active task: " +
mOldActiveTasks[x].name
)
break
}
}
}
if (activeTasksChanged) {
mOldActiveTasks = activeTasks
}
} else if (mOldActiveTasks.isNotEmpty()) {
mOldActiveTasks.clear()
activeTasksChanged = true
}
// update notification, only if it hasn't been shown before, or after change in status
Logging.logVerbose(
Logging.Category.CLIENT,
"ClientNotification: notification needs update? "
+ (mOldComputingStatus == -1) + " "
+ activeTasksChanged + " "
+ !notificationShown + " "
+ (updatedStatus.computingStatus != mOldComputingStatus) + " "
+ (updatedStatus.computingStatus == ClientStatus.COMPUTING_STATUS_SUSPENDED
&& updatedStatus.computingSuspendReason != mOldSuspendReason)
)
if (mOldComputingStatus == -1 || activeTasksChanged
|| !notificationShown
|| updatedStatus.computingStatus != mOldComputingStatus || (updatedStatus.computingStatus == ClientStatus.COMPUTING_STATUS_SUSPENDED
&& updatedStatus.computingSuspendReason != mOldSuspendReason)
) {
// update, build and notify
nm.notify(notificationId, buildNotification(updatedStatus, active, mOldActiveTasks))
Logging.logVerbose(Logging.Category.CLIENT, "ClientNotification: update")
notificationShown = true
// save status for comparison next time
mOldComputingStatus = updatedStatus.computingStatus
mOldSuspendReason = updatedStatus.computingSuspendReason
}
// start foreground service, if requested
// notification instance exists now, but might be out-dated (if screen is off)
if (!foreground) {
setForegroundState(service)
}
}
// Notification must be built, before setting service to foreground!
@VisibleForTesting
internal fun setForegroundState(service: Monitor) {
service.startForeground(notificationId, n)
Logging.logInfo(Logging.Category.CLIENT, "ClientNotification.setForeground() start service as foreground.")
foreground = true
}
@SuppressLint("InlinedApi")
@VisibleForTesting
internal fun buildNotification(
status: ClientStatus,
active: Boolean,
activeTasks: List<Result>?
): Notification {
// get current client computing status
val computingStatus = status.computingStatus
// get status strings from ClientStatus
val statusDesc = status.currentStatusDescription
val statusTitle = status.currentStatusTitle
// build notification
val nb = NotificationCompat.Builder(context, "main-channel")
nb.setContentTitle(statusTitle)
.setSmallIcon(getIcon(computingStatus, true))
.setLargeIcon(context.getBitmapFromVectorDrawable(getIcon(computingStatus, false)))
.setContentIntent(contentIntent)
// adapt priority based on computing status
// computing: IDLE and COMPUTING (see wakelock handling)
if (active) {
@Suppress("DEPRECATION")
nb.priority = Notification.PRIORITY_HIGH
} else {
@Suppress("DEPRECATION")
nb.priority = Notification.PRIORITY_LOW
}
// set action based on computing status
if (computingStatus == ClientStatus.COMPUTING_STATUS_NEVER) {
// add resume button
// 0 - only text. Unify all versions of android with text button.
nb.addAction(
0,
context.getString(R.string.menu_run_mode_enable), getActionIntent(2)
)
} else {
// add suspend button
// 0 - only text. Unify all versions of android with text button.
nb.addAction(
0,
context.getString(R.string.menu_run_mode_disable), getActionIntent(1)
)
}
// set tasks if computing
if (computingStatus == ClientStatus.COMPUTING_STATUS_COMPUTING && activeTasks != null && activeTasks.isNotEmpty()) {
// set summary text
nb.setSubText(statusDesc)
// set number as content info
nb.setNumber(activeTasks.size)
// set names in list
val inboxStyle = NotificationCompat.InboxStyle()
for ((_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, project, _, app) in activeTasks) {
var line = if (project == null) "" else project.name
line += ": "
line += if (app == null) "" else app.displayName
inboxStyle.addLine(line)
}
nb.setStyle(inboxStyle)
} else {
nb.setContentText(statusDesc)
}
n = nb.build()
return n!!
}
// creates pending intent to service with specified action code
private fun getActionIntent(actionCode: Int): PendingIntent {
val si = Intent(context, Monitor::class.java)
si.putExtra("action", actionCode)
return PendingIntent.getService(context, 0, si, PendingIntent.FLAG_CANCEL_CURRENT)
}
// returns resource id of icon
@VisibleForTesting
internal fun getIcon(status: Int, isSmall: Boolean): Int {
return when (status) {
ClientStatus.COMPUTING_STATUS_NEVER, ClientStatus.COMPUTING_STATUS_SUSPENDED, ClientStatus.COMPUTING_STATUS_IDLE -> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && isSmall) {
R.mipmap.ic_boinc_paused_white
} else {
R.drawable.ic_boinc_paused
}
else -> if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && isSmall) {
R.mipmap.ic_boinc_white
} else {
R.drawable.ic_boinc
}
}
}
init {
val intent = Intent(context, BOINCActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.putExtra("targetFragment", R.string.tab_tasks)
val flags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_CANCEL_CURRENT
} else {
Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
}
contentIntent = PendingIntent.getActivity(context,0, intent, flags)
}
}
| lgpl-3.0 | 9e2d905b4c71a94483e5f4d31127582c | 39.909449 | 198 | 0.629391 | 4.903728 | false | false | false | false |
Ztiany/Repository | Kotlin/Kotlin-Coroutine-V1.1.2/src/main/kotlin/cn/kotliner/coroutine/ui/MainKt.kt | 2 | 2446 | package cn.kotliner.coroutine.ui
import cn.kotliner.coroutine.async.DownloadContext
import cn.kotliner.coroutine.async.我要开始加载图片啦
import cn.kotliner.coroutine.async.我要开始协程啦
import cn.kotliner.coroutine.async.我要开始耗时操作了
import cn.kotliner.coroutine.common.log
import javax.swing.JFrame.EXIT_ON_CLOSE
/**
* Created by benny on 5/20/17.
*/
const val LOGO_URL = "http://www.imooc.com/static/img/index/logo.png?t=1.1"
fun main(args: Array<String>) {
val frame = MainWindow()
frame.title = "Coroutine@Bennyhuo"
frame.setSize(200, 150)
frame.isResizable = true
frame.defaultCloseOperation = EXIT_ON_CLOSE
frame.init()
frame.isVisible = true
frame.onButtonClick {
log("协程之前")
我要开始协程啦(DownloadContext(LOGO_URL)) {
log("协程开始")
try {
val imageData = 我要开始耗时操作了 {
我要开始加载图片啦(this[DownloadContext]!!.url)
}
log("拿到图片")
frame.setLogo(imageData)
} catch(e: Exception) {
e.printStackTrace()
}
}
log("协程之后")
}
// frame.onButtonClick {
// HttpService.service.getLogo(LOGO_URL)
// .enqueue(object : Callback<ResponseBody> {
// override fun onResponse(
// call: Call<ResponseBody>,
// response: Response<ResponseBody>) {
// if (response.isSuccessful) {
// val imageData = response.body()?.byteStream()?.readBytes()
// if (imageData == null) {
// throw HttpException(HttpError.HTTP_ERROR_NO_DATA)
// } else {
// SwingUtilities.invokeLater {
// frame.setLogo(imageData)
// }
// }
// } else {
// throw HttpException(response.code())
// }
// }
//
// override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
// throw HttpException(HttpError.HTTP_ERROR_UNKNOWN)
// }
//
// })
// }
}
| apache-2.0 | f87c3de658313ed1d3a8559d7f58e853 | 32.536232 | 88 | 0.489196 | 4.245872 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/dialogs/DatabaseErrorDialog.kt | 1 | 21872 | /****************************************************************************************
* Copyright (c) 2015 Timothy Rae <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.dialogs
import android.content.DialogInterface
import android.os.Bundle
import android.os.Message
import android.view.KeyEvent
import android.view.View
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.*
import com.ichi2.async.Connection
import com.ichi2.libanki.Consts
import com.ichi2.utils.UiUtil.makeBold
import com.ichi2.utils.contentNullable
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.util.*
class DatabaseErrorDialog : AsyncDialogFragment() {
private lateinit var mRepairValues: IntArray
private lateinit var mBackups: Array<File?>
override fun onCreateDialog(savedInstanceState: Bundle?): MaterialDialog {
super.onCreate(savedInstanceState)
val type = requireArguments().getInt("dialogType")
val res = resources
val builder = MaterialDialog.Builder(requireActivity())
builder.cancelable(true)
.title(title)
var sqliteInstalled = false
try {
sqliteInstalled = Runtime.getRuntime().exec("sqlite3 --version").waitFor() == 0
} catch (e: IOException) {
Timber.w(e)
} catch (e: InterruptedException) {
Timber.w(e)
}
return when (type) {
DIALOG_LOAD_FAILED -> {
// Collection failed to load; give user the option of either choosing from repair options, or closing
// the activity
builder.cancelable(false)
.contentNullable(message)
.iconAttr(R.attr.dialogErrorIcon)
.positiveText(R.string.error_handling_options)
.negativeText(R.string.close)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as DeckPicker?)
?.showDatabaseErrorDialog(DIALOG_ERROR_HANDLING)
}
.onNegative { _: MaterialDialog?, _: DialogAction? -> exit() }
.show()
}
DIALOG_DB_ERROR -> {
// Database Check failed to execute successfully; give user the option of either choosing from repair
// options, submitting an error report, or closing the activity
val dialog = builder
.cancelable(false)
.contentNullable(message)
.iconAttr(R.attr.dialogErrorIcon)
.positiveText(R.string.error_handling_options)
.negativeText(R.string.answering_error_report)
.neutralText(res.getString(R.string.close))
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as DeckPicker?)
?.showDatabaseErrorDialog(DIALOG_ERROR_HANDLING)
}
.onNegative { _: MaterialDialog?, _: DialogAction? ->
(activity as DeckPicker?)!!.sendErrorReport()
dismissAllDialogFragments()
}
.onNeutral { _: MaterialDialog?, _: DialogAction? -> exit() }
.show()
dialog.customView!!.findViewById<View>(R.id.md_buttonDefaultNegative).isEnabled = (activity as DeckPicker?)!!.hasErrorFiles()
dialog
}
DIALOG_ERROR_HANDLING -> {
// The user has asked to see repair options; allow them to choose one of the repair options or go back
// to the previous dialog
val options = ArrayList<String>(6)
val values = ArrayList<Int>(6)
if (!(activity as AnkiActivity?)!!.colIsOpen()) {
// retry
options.add(res.getString(R.string.backup_retry_opening))
values.add(0)
} else {
// fix integrity
options.add(res.getString(R.string.check_db))
values.add(1)
}
// repair db with sqlite
if (sqliteInstalled) {
options.add(res.getString(R.string.backup_error_menu_repair))
values.add(2)
}
// // restore from backup
options.add(res.getString(R.string.backup_restore))
values.add(3)
// delete old collection and build new one
options.add(res.getString(R.string.backup_full_sync_from_server))
values.add(4)
// delete old collection and build new one
options.add(res.getString(R.string.backup_del_collection))
values.add(5)
val titles = arrayOfNulls<String>(options.size)
mRepairValues = IntArray(options.size)
var i = 0
while (i < options.size) {
titles[i] = options[i]
mRepairValues[i] = values[i]
i++
}
builder.iconAttr(R.attr.dialogErrorIcon)
.negativeText(R.string.dialog_cancel)
.items(*titles)
.itemsCallback { _: MaterialDialog?, _: View?, which: Int, _: CharSequence? ->
when (mRepairValues[which]) {
0 -> {
(activity as DeckPicker?)!!.restartActivity()
return@itemsCallback
}
1 -> {
(activity as DeckPicker?)!!.showDatabaseErrorDialog(DIALOG_CONFIRM_DATABASE_CHECK)
return@itemsCallback
}
2 -> {
(activity as DeckPicker?)!!.showDatabaseErrorDialog(DIALOG_REPAIR_COLLECTION)
return@itemsCallback
}
3 -> {
(activity as DeckPicker?)!!.showDatabaseErrorDialog(DIALOG_RESTORE_BACKUP)
return@itemsCallback
}
4 -> {
(activity as DeckPicker?)!!.showDatabaseErrorDialog(DIALOG_FULL_SYNC_FROM_SERVER)
return@itemsCallback
}
5 -> {
(activity as DeckPicker?)!!.showDatabaseErrorDialog(DIALOG_NEW_COLLECTION)
return@itemsCallback
}
else -> throw RuntimeException("Unknown dialog selection: " + mRepairValues[which])
}
}
.show()
}
DIALOG_REPAIR_COLLECTION -> {
// Allow user to run BackupManager.repairCollection()
builder.contentNullable(message)
.iconAttr(R.attr.dialogErrorIcon)
.positiveText(R.string.dialog_positive_repair)
.negativeText(R.string.dialog_cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as DeckPicker?)!!.repairCollection()
dismissAllDialogFragments()
}
.show()
}
DIALOG_RESTORE_BACKUP -> {
// Allow user to restore one of the backups
val path = CollectionHelper.getCollectionPath(activity)
val files = BackupManager.getBackups(File(path))
mBackups = arrayOfNulls(files.size)
var i = 0
while (i < files.size) {
mBackups[i] = files[files.size - 1 - i]
i++
}
if (mBackups.isEmpty()) {
builder.title(res.getString(R.string.backup_restore))
.contentNullable(message)
.positiveText(R.string.dialog_ok)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as DeckPicker?)
?.showDatabaseErrorDialog(DIALOG_ERROR_HANDLING)
}
} else {
val dates = arrayOfNulls<String>(mBackups.size)
var j = 0
while (j < mBackups.size) {
dates[j] = mBackups[j]!!.name.replace(
".*-(\\d{4}-\\d{2}-\\d{2})-(\\d{2})-(\\d{2}).apkg".toRegex(), "$1 ($2:$3 h)"
)
j++
}
builder.title(res.getString(R.string.backup_restore_select_title))
.negativeText(R.string.dialog_cancel)
.items(*dates)
.itemsCallbackSingleChoice(
dates.size
) { _: MaterialDialog?, _: View?, which: Int, _: CharSequence? ->
if (mBackups[which]!!.length() > 0) {
// restore the backup if it's valid
(activity as DeckPicker?)
?.restoreFromBackup(
mBackups[which]
?.path
)
dismissAllDialogFragments()
} else {
// otherwise show an error dialog
MaterialDialog.Builder(requireActivity())
.title(R.string.vague_error)
.content(R.string.backup_invalid_file_error)
.positiveText(R.string.dialog_ok)
.build().show()
}
true
}
}
val materialDialog = builder.build()
materialDialog.setOnKeyListener { _: DialogInterface?, keyCode: Int, _: KeyEvent? ->
if (keyCode == KeyEvent.KEYCODE_BACK) {
Timber.i("DIALOG_RESTORE_BACKUP caught hardware back button")
dismissAllDialogFragments()
return@setOnKeyListener true
}
false
}
materialDialog
}
DIALOG_NEW_COLLECTION -> {
// Allow user to create a new empty collection
builder.contentNullable(message)
.positiveText(R.string.dialog_positive_create)
.negativeText(R.string.dialog_cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
val ch = CollectionHelper.getInstance()
val time = ch.getTimeSafe(context)
ch.closeCollection(false, "DatabaseErrorDialog: Before Create New Collection")
val path1 = CollectionHelper.getCollectionPath(activity)
if (BackupManager.moveDatabaseToBrokenFolder(path1, false, time)) {
(activity as DeckPicker?)!!.restartActivity()
} else {
(activity as DeckPicker?)!!.showDatabaseErrorDialog(DIALOG_LOAD_FAILED)
}
}
.show()
}
DIALOG_CONFIRM_DATABASE_CHECK -> {
// Confirmation dialog for database check
builder.contentNullable(message)
.positiveText(R.string.dialog_ok)
.negativeText(R.string.dialog_cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as DeckPicker?)!!.integrityCheck()
dismissAllDialogFragments()
}
.show()
}
DIALOG_CONFIRM_RESTORE_BACKUP -> {
// Confirmation dialog for backup restore
builder.contentNullable(message)
.positiveText(R.string.dialog_continue)
.negativeText(R.string.dialog_cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as DeckPicker?)
?.showDatabaseErrorDialog(DIALOG_RESTORE_BACKUP)
}
.show()
}
DIALOG_FULL_SYNC_FROM_SERVER -> {
// Allow user to do a full-sync from the server
builder.contentNullable(message)
.positiveText(R.string.dialog_positive_overwrite)
.negativeText(R.string.dialog_cancel)
.onPositive { _: MaterialDialog?, _: DialogAction? ->
(activity as DeckPicker?)!!.sync(Connection.ConflictResolution.FULL_DOWNLOAD)
dismissAllDialogFragments()
}
.show()
}
DIALOG_DB_LOCKED -> {
// If the database is locked, all we can do is ask the user to exit.
builder.contentNullable(message)
.positiveText(R.string.close)
.cancelable(false)
.onPositive { _: MaterialDialog?, _: DialogAction? -> exit() }
.show()
}
INCOMPATIBLE_DB_VERSION -> {
val values: MutableList<Int> = ArrayList(2)
val options = arrayOf<CharSequence>(makeBold(res.getString(R.string.backup_restore)), makeBold(res.getString(R.string.backup_full_sync_from_server)))
values.add(0)
values.add(1)
builder
.cancelable(false)
.contentNullable(message)
.iconAttr(R.attr.dialogErrorIcon)
.positiveText(R.string.close)
.onPositive { _: MaterialDialog?,
_: DialogAction? ->
exit()
}
.items(*options) // .itemsColor(ContextCompat.getColor(requireContext(), R.color.material_grey_500))
.itemsCallback { _: MaterialDialog?, _: View?, position: Int, _: CharSequence? ->
when (values[position]) {
0 -> (activity as DeckPicker?)!!.showDatabaseErrorDialog(DIALOG_RESTORE_BACKUP)
1 -> (activity as DeckPicker?)!!.showDatabaseErrorDialog(DIALOG_FULL_SYNC_FROM_SERVER)
}
}
.show()
}
else -> null!!
}
}
private fun exit() {
(activity as DeckPicker?)!!.exit()
} // Generic message shown when a libanki task failed
// The sqlite database has been corrupted (DatabaseErrorHandler.onCorrupt() was called)
// Show a specific message appropriate for the situation
private val message: String?
get() = when (requireArguments().getInt("dialogType")) {
DIALOG_LOAD_FAILED -> if (databaseCorruptFlag) {
// The sqlite database has been corrupted (DatabaseErrorHandler.onCorrupt() was called)
// Show a specific message appropriate for the situation
res().getString(R.string.corrupt_db_message, res().getString(R.string.repair_deck))
} else {
// Generic message shown when a libanki task failed
res().getString(R.string.access_collection_failed_message, res().getString(R.string.link_help))
}
DIALOG_DB_ERROR -> res().getString(R.string.answering_error_message)
DIALOG_REPAIR_COLLECTION -> res().getString(R.string.repair_deck_dialog, BackupManager.BROKEN_DECKS_SUFFIX)
DIALOG_RESTORE_BACKUP -> res().getString(R.string.backup_restore_no_backups)
DIALOG_NEW_COLLECTION -> res().getString(R.string.backup_del_collection_question)
DIALOG_CONFIRM_DATABASE_CHECK -> res().getString(R.string.check_db_warning)
DIALOG_CONFIRM_RESTORE_BACKUP -> res().getString(R.string.restore_backup)
DIALOG_FULL_SYNC_FROM_SERVER -> res().getString(R.string.backup_full_sync_from_server_question)
DIALOG_DB_LOCKED -> res().getString(R.string.database_locked_summary)
INCOMPATIBLE_DB_VERSION -> {
var databaseVersion = -1
try {
databaseVersion = CollectionHelper.getDatabaseVersion(requireContext())
} catch (e: Exception) {
Timber.w(e, "Failed to get database version, using -1")
}
res().getString(R.string.incompatible_database_version_summary, Consts.SCHEMA_VERSION, databaseVersion)
}
else -> requireArguments().getString("dialogMessage")
}
private val title: String
get() = when (requireArguments().getInt("dialogType")) {
DIALOG_LOAD_FAILED -> res().getString(R.string.open_collection_failed_title)
DIALOG_ERROR_HANDLING -> res().getString(R.string.error_handling_title)
DIALOG_REPAIR_COLLECTION -> res().getString(R.string.dialog_positive_repair)
DIALOG_RESTORE_BACKUP -> res().getString(R.string.backup_restore)
DIALOG_NEW_COLLECTION -> res().getString(R.string.backup_new_collection)
DIALOG_CONFIRM_DATABASE_CHECK -> res().getString(R.string.check_db_title)
DIALOG_CONFIRM_RESTORE_BACKUP -> res().getString(R.string.restore_backup_title)
DIALOG_FULL_SYNC_FROM_SERVER -> res().getString(R.string.backup_full_sync_from_server)
DIALOG_DB_LOCKED -> res().getString(R.string.database_locked_title)
INCOMPATIBLE_DB_VERSION -> res().getString(R.string.incompatible_database_version_title)
DIALOG_DB_ERROR -> res().getString(R.string.answering_error_title)
else -> res().getString(R.string.answering_error_title)
}
override fun getNotificationMessage(): String? {
return message
}
override fun getNotificationTitle(): String {
return res().getString(R.string.answering_error_title)
}
override fun getDialogHandlerMessage(): Message {
val msg = Message.obtain()
msg.what = DialogHandler.MSG_SHOW_DATABASE_ERROR_DIALOG
val b = Bundle()
b.putInt("dialogType", requireArguments().getInt("dialogType"))
msg.data = b
return msg
}
fun dismissAllDialogFragments() {
(activity as DeckPicker?)!!.dismissAllDialogFragments()
}
companion object {
const val DIALOG_LOAD_FAILED = 0
const val DIALOG_DB_ERROR = 1
const val DIALOG_ERROR_HANDLING = 2
const val DIALOG_REPAIR_COLLECTION = 3
const val DIALOG_RESTORE_BACKUP = 4
const val DIALOG_NEW_COLLECTION = 5
const val DIALOG_CONFIRM_DATABASE_CHECK = 6
const val DIALOG_CONFIRM_RESTORE_BACKUP = 7
const val DIALOG_FULL_SYNC_FROM_SERVER = 8
/** If the database is locked, all we can do is reset the app */
const val DIALOG_DB_LOCKED = 9
/** If the database is at a version higher than what we can currently handle */
const val INCOMPATIBLE_DB_VERSION = 10
// public flag which lets us distinguish between inaccessible and corrupt database
@JvmField
var databaseCorruptFlag = false
/**
* A set of dialogs which deal with problems with the database when it can't load
*
* @param dialogType An integer which specifies which of the sub-dialogs to show
*/
@JvmStatic
fun newInstance(dialogType: Int): DatabaseErrorDialog {
val f = DatabaseErrorDialog()
val args = Bundle()
args.putInt("dialogType", dialogType)
f.arguments = args
return f
}
}
}
| gpl-3.0 | 278ea51d182e11fb15e267a318bf8517 | 48.484163 | 165 | 0.505029 | 5.496859 | false | false | false | false |
stripe/stripe-android | link/src/main/java/com/stripe/android/link/ui/PrimaryButton.kt | 1 | 7413 | package com.stripe.android.link.ui
import android.content.res.Resources
import androidx.annotation.DrawableRes
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Icon
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.stripe.android.link.R
import com.stripe.android.link.theme.DefaultLinkTheme
import com.stripe.android.link.theme.PrimaryButtonHeight
import com.stripe.android.link.theme.linkColors
import com.stripe.android.link.theme.linkShapes
import com.stripe.android.model.PaymentIntent
import com.stripe.android.model.SetupIntent
import com.stripe.android.model.StripeIntent
import com.stripe.android.ui.core.Amount
/**
* Represent the possible states for the primary button on a Link screen.
*
* @property isBlocking Whether being in this state should block user interaction with all other
* UI elements.
*/
internal enum class PrimaryButtonState(val isBlocking: Boolean) {
Enabled(false),
Disabled(false),
Processing(true),
Completed(true);
companion object {
// The delay between showing the [Completed] state and dismissing the screen.
const val COMPLETED_DELAY_MS = 1000L
}
}
private val PrimaryButtonIconWidth = 13.dp
private val PrimaryButtonIconHeight = 16.dp
internal const val progressIndicatorTestTag = "CircularProgressIndicator"
internal const val completedIconTestTag = "CompletedIcon"
internal fun completePaymentButtonLabel(
stripeIntent: StripeIntent,
resources: Resources
) = when (stripeIntent) {
is PaymentIntent -> Amount(
requireNotNull(stripeIntent.amount),
requireNotNull(stripeIntent.currency)
).buildPayButtonLabel(resources)
is SetupIntent -> resources.getString(R.string.stripe_setup_button_label)
}
@Composable
@Preview
private fun PrimaryButton() {
DefaultLinkTheme {
PrimaryButton(
label = "Testing",
state = PrimaryButtonState.Enabled,
onButtonClick = { },
iconEnd = R.drawable.stripe_ic_lock
)
}
}
@Composable
internal fun PrimaryButton(
label: String,
state: PrimaryButtonState,
onButtonClick: () -> Unit,
@DrawableRes iconStart: Int? = null,
@DrawableRes iconEnd: Int? = null
) {
CompositionLocalProvider(
LocalContentAlpha provides
if (state == PrimaryButtonState.Disabled) ContentAlpha.disabled else ContentAlpha.high
) {
Box(modifier = Modifier.padding(vertical = 16.dp)) {
Button(
onClick = onButtonClick,
modifier = Modifier
.height(PrimaryButtonHeight)
.fillMaxWidth(),
enabled = state == PrimaryButtonState.Enabled,
elevation = ButtonDefaults.elevation(0.dp, 0.dp, 0.dp, 0.dp, 0.dp),
shape = MaterialTheme.linkShapes.medium,
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.primary,
disabledBackgroundColor = MaterialTheme.colors.primary
)
) {
when (state) {
PrimaryButtonState.Processing -> CircularProgressIndicator(
modifier = Modifier
.size(18.dp)
.semantics {
testTag = progressIndicatorTestTag
},
color = MaterialTheme.linkColors.buttonLabel,
strokeWidth = 2.dp
)
PrimaryButtonState.Completed -> Icon(
painter = painterResource(id = R.drawable.ic_link_complete),
contentDescription = null,
modifier = Modifier
.size(24.dp)
.semantics {
testTag = completedIconTestTag
},
tint = MaterialTheme.linkColors.buttonLabel
)
else -> Row(
Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
PrimaryButtonIcon(iconStart)
Text(
text = label,
modifier = Modifier.weight(1f),
color = MaterialTheme.linkColors.buttonLabel
.copy(alpha = LocalContentAlpha.current),
textAlign = TextAlign.Center
)
PrimaryButtonIcon(iconEnd)
}
}
}
}
}
}
@Composable
private fun PrimaryButtonIcon(
@DrawableRes icon: Int?
) {
Box(
modifier = Modifier
.width(PrimaryButtonIconWidth)
.height(PrimaryButtonIconHeight),
contentAlignment = Alignment.Center
) {
icon?.let { icon ->
Icon(
painter = painterResource(id = icon),
contentDescription = null,
modifier = Modifier
.width(PrimaryButtonIconWidth)
.height(PrimaryButtonIconHeight),
tint = MaterialTheme.linkColors.buttonLabel.copy(alpha = LocalContentAlpha.current)
)
}
}
}
@Composable
internal fun SecondaryButton(
enabled: Boolean,
label: String,
onClick: () -> Unit
) {
TextButton(
onClick = onClick,
modifier = Modifier
.fillMaxWidth()
.height(PrimaryButtonHeight),
enabled = enabled,
shape = MaterialTheme.linkShapes.medium,
colors = ButtonDefaults.buttonColors(
backgroundColor = MaterialTheme.colors.secondary,
disabledBackgroundColor = MaterialTheme.colors.secondary
)
) {
CompositionLocalProvider(
LocalContentAlpha provides if (enabled) ContentAlpha.high else ContentAlpha.disabled
) {
Text(
text = label,
color = MaterialTheme.linkColors.secondaryButtonLabel
.copy(alpha = LocalContentAlpha.current)
)
}
}
}
| mit | 579ebd6aa0623a749bbf2a344180f08b | 35.160976 | 99 | 0.620936 | 5.306371 | false | false | false | false |
stripe/stripe-android | example/src/main/java/com/stripe/example/activity/IDEALPaymentMethodActivity.kt | 1 | 6317 | package com.stripe.example.activity
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import com.stripe.android.model.Address
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodCreateParams
class IDEALPaymentMethodActivity : StripeIntentActivity() {
private val bankNameMap = mapOf(
"abn_amro" to "ABN AMRO",
"asn_bank" to "ASN Bank",
"bunq" to "Bunq",
"handelsbanken" to "Handelsbanken",
"ing" to "ING",
"knab" to "Knab",
"moneyou" to "Moneyou",
"rabobank" to "Rabobank",
"revolut" to "Revolut",
"regiobank" to "RegioBank",
"sns_bank" to "SNS Bank (De Volksbank)",
"triodos_bank" to "Triodos Bank",
"van_lanschot" to "Van Lanschot"
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launchWhenStarted {
setContent {
IDEALScreen()
}
}
}
@Composable
private fun IDEALScreen() {
val inProgress by viewModel.inProgress.observeAsState(false)
val status by viewModel.status.observeAsState("")
val scrollState = rememberScrollState()
val name = remember { mutableStateOf("Johnny Lawrence") }
var selectedBank by remember { mutableStateOf(bankNameMap.firstNotNullOf { it.key }) }
var expandedBankDropdown by remember { mutableStateOf(false) }
if (inProgress) {
LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
}
if (status.isNotEmpty()) {
Text(text = status)
} else {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
.verticalScroll(scrollState)
) {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
label = { Text("Name") },
value = name.value,
maxLines = 1,
onValueChange = { name.value = it }
)
Box(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp, bottom = 16.dp)
) {
OutlinedTextField(
value = bankNameMap[selectedBank] ?: "",
onValueChange = {},
enabled = false,
trailingIcon = {
Icon(
Icons.Filled.ArrowDropDown,
contentDescription = null,
tint = MaterialTheme.colors.onBackground,
modifier = Modifier.height(24.dp)
)
},
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = { expandedBankDropdown = true })
)
DropdownMenu(
expanded = expandedBankDropdown,
onDismissRequest = { expandedBankDropdown = false }
) {
bankNameMap.forEach {
DropdownMenuItem(onClick = {
selectedBank = it.key
expandedBankDropdown = false
}) {
Text(it.value)
}
}
}
}
Button(
onClick = {
createAndConfirmPaymentIntent(
country = "NL",
paymentMethodCreateParams = PaymentMethodCreateParams.create(
ideal = PaymentMethodCreateParams.Ideal(selectedBank),
billingDetails = PaymentMethod.BillingDetails(
name = name.value,
phone = "1-800-555-1234",
email = "[email protected]",
address = Address.Builder()
.setCity("San Francisco")
.setCountry("US")
.setLine1("123 Market St")
.setLine2("#345")
.setPostalCode("94107")
.setState("CA")
.build()
)
)
)
},
modifier = Modifier.fillMaxWidth()
) {
Text("Confirm with iDEAL")
}
}
}
}
}
| mit | 38f80ab30011aa1e4288e0b1e9ac7d40 | 40.019481 | 94 | 0.515276 | 5.76895 | false | false | false | false |
AndroidX/androidx | buildSrc/private/src/main/kotlin/androidx/build/AarManifestTransformerTask.kt | 3 | 3717 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build
import java.io.File
import java.nio.file.Files
import java.nio.file.attribute.FileTime
import org.apache.tools.zip.ZipEntry
import org.apache.tools.zip.ZipFile
import org.apache.tools.zip.ZipOutputStream
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
/**
* Transforms an AAR by removing the `android:targetSdkVersion` element from the manifest.
*/
@CacheableTask
abstract class AarManifestTransformerTask : DefaultTask() {
@get:InputFile
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val aarFile: RegularFileProperty
@get:OutputFile
abstract val updatedAarFile: RegularFileProperty
@TaskAction
fun taskAction() {
val aar = aarFile.get().asFile
val updatedAar = updatedAarFile.get().asFile
val tempDir = Files.createTempDirectory("${name}Unzip").toFile()
tempDir.deleteOnExit()
ZipFile(aar).use { aarFile ->
aarFile.unzipTo(tempDir)
}
val manifestFile = File(tempDir, "AndroidManifest.xml")
manifestFile.writeText(removeTargetSdkVersion(manifestFile.readText()))
tempDir.zipTo(updatedAar)
tempDir.deleteRecursively()
}
}
/**
* Removes the `android:targetSdkVersion` element from the [manifest].
*/
fun removeTargetSdkVersion(manifest: String): String = manifest.replace(
"\\s*android:targetSdkVersion=\".+?\"".toRegex(),
""
)
private fun ZipFile.unzipTo(tempDir: File) {
entries.iterator().forEach { entry ->
if (entry.isDirectory) {
File(tempDir, entry.name).mkdirs()
} else {
val file = File(tempDir, entry.name)
file.parentFile.mkdirs()
getInputStream(entry).use { stream ->
file.writeBytes(stream.readBytes())
}
}
}
}
private fun File.zipTo(outZip: File) {
ZipOutputStream(outZip.outputStream()).use { stream ->
listFiles()!!.forEach { file ->
stream.addFileRecursive(null, file)
}
}
}
private fun ZipOutputStream.addFileRecursive(parentPath: String?, file: File) {
val entryPath = if (parentPath != null) "$parentPath/${file.name}" else file.name
val entry = ZipEntry(file, entryPath)
// Reset creation time of entry to make it deterministic.
entry.time = 0
entry.creationTime = FileTime.fromMillis(0)
if (file.isFile) {
putNextEntry(entry)
file.inputStream().use { stream ->
stream.copyTo(this)
}
closeEntry()
} else if (file.isDirectory) {
val listFiles = file.listFiles()
if (!listFiles.isNullOrEmpty()) {
putNextEntry(entry)
closeEntry()
listFiles.forEach { containedFile ->
addFileRecursive(entryPath, containedFile)
}
}
}
}
| apache-2.0 | 60212aca96e76df1caba5a06357c24d8 | 30.235294 | 90 | 0.67689 | 4.292148 | false | false | false | false |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/gesturehandler/react/RNGestureHandlerRootHelper.kt | 2 | 4761 | package abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.react
import android.os.SystemClock
import android.util.Log
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.ViewParent
import abi44_0_0.com.facebook.react.bridge.ReactContext
import abi44_0_0.com.facebook.react.bridge.UiThreadUtil
import abi44_0_0.com.facebook.react.common.ReactConstants
import abi44_0_0.com.facebook.react.uimanager.RootView
import abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandler
import abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler.GestureHandlerOrchestrator
class RNGestureHandlerRootHelper(private val context: ReactContext, wrappedView: ViewGroup) {
private val orchestrator: GestureHandlerOrchestrator?
private val jsGestureHandler: GestureHandler<*>?
val rootView: ViewGroup
private var shouldIntercept = false
private var passingTouch = false
init {
UiThreadUtil.assertOnUiThread()
val wrappedViewTag = wrappedView.id
check(wrappedViewTag >= 1) { "Expect view tag to be set for $wrappedView" }
val module = context.getNativeModule(RNGestureHandlerModule::class.java)!!
val registry = module.registry
rootView = findRootViewTag(wrappedView)
Log.i(
ReactConstants.TAG,
"[GESTURE HANDLER] Initialize gesture handler for root view $rootView"
)
orchestrator = GestureHandlerOrchestrator(
wrappedView, registry, RNViewConfigurationHelper()
).apply {
minimumAlphaForTraversal = MIN_ALPHA_FOR_TOUCH
}
jsGestureHandler = RootViewGestureHandler().apply { tag = -wrappedViewTag }
with(registry) {
registerHandler(jsGestureHandler)
attachHandlerToView(jsGestureHandler.tag, wrappedViewTag)
}
module.registerRootHelper(this)
}
fun tearDown() {
Log.i(
ReactConstants.TAG,
"[GESTURE HANDLER] Tearing down gesture handler registered for root view $rootView"
)
val module = context.getNativeModule(RNGestureHandlerModule::class.java)!!
with(module) {
registry.dropHandler(jsGestureHandler!!.tag)
unregisterRootHelper(this@RNGestureHandlerRootHelper)
}
}
private inner class RootViewGestureHandler : GestureHandler<RootViewGestureHandler>() {
override fun onHandle(event: MotionEvent) {
val currentState = state
if (currentState == STATE_UNDETERMINED) {
begin()
shouldIntercept = false
}
if (event.actionMasked == MotionEvent.ACTION_UP) {
end()
}
}
override fun onCancel() {
shouldIntercept = true
val time = SystemClock.uptimeMillis()
val event = MotionEvent.obtain(time, time, MotionEvent.ACTION_CANCEL, 0f, 0f, 0).apply {
action = MotionEvent.ACTION_CANCEL
}
if (rootView is RootView) {
rootView.onChildStartedNativeGesture(event)
}
}
}
fun requestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
// If this method gets called it means that some native view is attempting to grab lock for
// touch event delivery. In that case we cancel all gesture recognizers
if (orchestrator != null && !passingTouch) {
// if we are in the process of delivering touch events via GH orchestrator, we don't want to
// treat it as a native gesture capturing the lock
tryCancelAllHandlers()
}
}
fun dispatchTouchEvent(ev: MotionEvent): Boolean {
// We mark `mPassingTouch` before we get into `mOrchestrator.onTouchEvent` so that we can tell
// if `requestDisallow` has been called as a result of a normal gesture handling process or
// as a result of one of the gesture handlers activating
passingTouch = true
orchestrator!!.onTouchEvent(ev)
passingTouch = false
return shouldIntercept
}
private fun tryCancelAllHandlers() {
// In order to cancel handlers we activate handler that is hooked to the root view
jsGestureHandler?.apply {
if (state == GestureHandler.STATE_BEGAN) {
// Try activate main JS handler
activate()
end()
}
}
}
/*package*/
fun handleSetJSResponder(viewTag: Int, blockNativeResponder: Boolean) {
if (blockNativeResponder) {
UiThreadUtil.runOnUiThread { tryCancelAllHandlers() }
}
}
companion object {
private const val MIN_ALPHA_FOR_TOUCH = 0.1f
private fun findRootViewTag(viewGroup: ViewGroup): ViewGroup {
UiThreadUtil.assertOnUiThread()
var parent: ViewParent? = viewGroup
while (parent != null && parent !is RootView) {
parent = parent.parent
}
checkNotNull(parent) {
"View $viewGroup has not been mounted under ReactRootView"
}
return parent as ViewGroup
}
}
}
| bsd-3-clause | 26ec310ce64169ca79e10e7e48e6d087 | 34.529851 | 99 | 0.714136 | 4.432961 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/welcome/CreateEmpireScreen.kt | 1 | 3242 | package au.com.codeka.warworlds.client.game.welcome
import android.view.ViewGroup
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.concurrency.Threads
import au.com.codeka.warworlds.client.net.HttpRequest
import au.com.codeka.warworlds.client.net.ServerUrl.url
import au.com.codeka.warworlds.client.ui.Screen
import au.com.codeka.warworlds.client.ui.ScreenContext
import au.com.codeka.warworlds.client.ui.SharedViews
import au.com.codeka.warworlds.client.ui.ShowInfo
import au.com.codeka.warworlds.client.util.GameSettings
import au.com.codeka.warworlds.client.util.GameSettings.edit
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.proto.NewAccountRequest
import au.com.codeka.warworlds.common.proto.NewAccountResponse
/**
* This screen is shown when you don't have a cookie saved. We'll want to either let you create
* a new empire, or sign in with an existing account (if you have one).
*/
class CreateEmpireScreen : Screen() {
private lateinit var layout: CreateEmpireLayout
private lateinit var context: ScreenContext
override fun onCreate(context: ScreenContext, container: ViewGroup) {
super.onCreate(context, container)
this.context = context
layout = CreateEmpireLayout(context.activity, layoutCallbacks)
}
override fun onShow(): ShowInfo? {
return ShowInfo.builder().view(layout).toolbarVisible(false).build()
}
private val layoutCallbacks = object : CreateEmpireLayout.Callbacks {
override fun onDoneClick(empireName: String?) {
registerEmpire(empireName!!)
}
override fun onSwitchAccountClick() {
context.pushScreen(SignInScreen(true /* immediate */))
}
}
private fun registerEmpire(empireName: String) {
layout.showSpinner()
App.taskRunner.runTask({
val request = HttpRequest.Builder()
.url(url + "accounts")
.method(HttpRequest.Method.POST)
.header("Content-Type", "application/x-protobuf")
.body(NewAccountRequest(
empire_name = empireName, id_token = App.auth.account?.idToken).encode())
.build()
val resp = request.getBody(NewAccountResponse::class.java)
if (resp == null) {
// TODO: report the error to the server?
log.error("Didn't get NewAccountResponse, as expected.", request.exception)
} else if (resp.cookie == null) {
App.taskRunner.runTask({ layout.showError(resp.message) }, Threads.UI)
} else {
log.info("New account response, cookie: %s, message: %s", resp.cookie, resp.message)
App.taskRunner.runTask({ onRegisterSuccess(resp) }, Threads.UI)
}
}, Threads.BACKGROUND)
}
private fun onRegisterSuccess(resp: NewAccountResponse) {
// Save the cookie.
edit()
.setString(GameSettings.Key.COOKIE, resp.cookie!!)
.commit()
context.home()
context.pushScreen(
WelcomeScreen(),
SharedViews.builder()
.addSharedView(R.id.next_btn, R.id.start_btn)
.addSharedView(R.id.title)
.addSharedView(R.id.title_icon)
.build())
}
companion object {
private val log = Log("CreateEmpireScreen")
}
} | mit | d71f6febacbc7e4627ba02d662ba6390 | 35.033333 | 95 | 0.704503 | 3.939247 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/runconfig/command/CompositeCargoRunConfigurationProducer.kt | 3 | 5507 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig.command
import com.intellij.execution.PsiLocation
import com.intellij.execution.RunManager
import com.intellij.execution.RunnerAndConfigurationSettings
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.ConfigurationFromContext
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import org.rust.cargo.runconfig.test.CargoBenchRunConfigurationProducer
import org.rust.cargo.runconfig.test.CargoTestRunConfigurationProducer
import java.util.*
import java.util.function.Function
/**
* This class aggregates other Rust run configuration [producers] and manages the search & creation of run
* configurations, taking into account configurations that other [producers] can create.
* The problem with the previous approach is that if there is an existing configuration that matches the context, the
* platform does not compare this configuration with those that can be created by other producers, even if these
* configurations are better matched with the context (see [#1252](https://github.com/intellij-rust/intellij-rust/issues/1252)).
*/
class CompositeCargoRunConfigurationProducer : CargoRunConfigurationProducer() {
private val producers: List<CargoRunConfigurationProducer> =
listOf(
CargoExecutableRunConfigurationProducer(),
CargoTestRunConfigurationProducer(),
CargoBenchRunConfigurationProducer()
)
override fun findExistingConfiguration(context: ConfigurationContext): RunnerAndConfigurationSettings? {
val preferredConfig = createPreferredConfigurationFromContext(context) ?: return null
val runManager = RunManager.getInstance(context.project)
val configurations = getConfigurationSettingsList(runManager)
for (configurationSettings in configurations) {
if (preferredConfig.configuration.isSame(configurationSettings.configuration)) {
return configurationSettings
}
}
return null
}
override fun findOrCreateConfigurationFromContext(context: ConfigurationContext): ConfigurationFromContext? {
val preferredConfig = createPreferredConfigurationFromContext(context) ?: return null
val psiElement = preferredConfig.sourceElement
val locationFromContext = context.location ?: return null
val locationFromElement = PsiLocation.fromPsiElement(psiElement, locationFromContext.module)
if (locationFromElement != null) {
val settings = findExistingConfiguration(context)
if (preferredConfig.configuration.isSame(settings?.configuration)) {
preferredConfig.setConfigurationSettings(settings)
} else {
RunManager.getInstance(context.project).setUniqueNameIfNeeded(preferredConfig.configuration)
}
}
return preferredConfig
}
override fun isConfigurationFromContext(
configuration: CargoCommandConfiguration,
context: ConfigurationContext
): Boolean = producers.any { it.isConfigurationFromContext(configuration, context) }
override fun setupConfigurationFromContext(
configuration: CargoCommandConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean = producers.any { it.setupConfigurationFromContext(configuration, context, sourceElement) }
override fun createLightConfiguration(context: ConfigurationContext): RunConfiguration? {
val producer = getPreferredProducerForContext(context) ?: return null
val configuration =
configurationFactory.createTemplateConfiguration(context.project) as CargoCommandConfiguration
val ref = Ref(context.psiLocation)
try {
if (!producer.setupConfigurationFromContext(configuration, context, ref)) {
return null
}
} catch (e: ClassCastException) {
return null
}
return configuration
}
private fun createPreferredConfigurationFromContext(context: ConfigurationContext): ConfigurationFromContext? =
producers
.mapNotNull { it.createConfigurationFromContext(context) }
.sortedWith(ConfigurationFromContext.COMPARATOR)
.firstOrNull()
private fun getPreferredProducerForContext(context: ConfigurationContext): CargoRunConfigurationProducer? =
producers.asSequence()
.mapNotNull { it.createConfigurationFromContext(context)?.let { key -> Pair(key, it) } }
.sortedWith(
Comparator.comparing(
Function(Pair<ConfigurationFromContext, *>::first::get),
ConfigurationFromContext.COMPARATOR
)
)
.map { it.second }
.firstOrNull()
private fun RunConfiguration.isSame(other: RunConfiguration?): Boolean =
when {
this === other -> true
this !is CargoCommandConfiguration || other !is CargoCommandConfiguration -> equals(other)
channel != other.channel -> false
command != other.command -> false
backtrace != other.backtrace -> false
workingDirectory != other.workingDirectory -> false
else -> true
}
}
| mit | f7cf2ca217e48f3f8771fb39f2c116c5 | 45.669492 | 128 | 0.714 | 6.051648 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/inlineTypeAlias/RsInlineTypeAliasProcessor.kt | 2 | 6964 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.inlineTypeAlias
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiWhiteSpace
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import org.rust.ide.inspections.fixes.deleteUseSpeck
import org.rust.ide.intentions.SubstituteTypeAliasIntention
import org.rust.ide.presentation.getStubOnlyText
import org.rust.ide.refactoring.RsInlineUsageViewDescriptor
import org.rust.ide.utils.import.RsImportHelper
import org.rust.lang.core.macros.isExpandedFromMacro
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.ancestorOrSelf
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.searchReferences
import org.rust.lang.core.resolve.ref.RsReference
import org.rust.lang.core.types.Substitution
import org.rust.lang.core.types.implLookup
import org.rust.lang.core.types.infer.substitute
import org.rust.lang.core.types.normType
import org.rust.lang.core.types.ty.TyTypeParameter
import org.rust.openapiext.testAssert
/** See also [SubstituteTypeAliasIntention] */
class RsInlineTypeAliasProcessor(
project: Project,
private val typeAlias: RsTypeAlias,
private val reference: RsReference?,
private val inlineThisOnly: Boolean,
) : BaseRefactoringProcessor(project) {
override fun findUsages(): Array<UsageInfo> {
val usages = if (inlineThisOnly && reference != null) {
listOf(reference)
} else {
typeAlias.searchReferences(typeAlias.useScope)
}
return usages
.map { UsageInfo(it) }
.toTypedArray()
}
private class PathUsage(val path: RsPath, val substitution: Substitution)
override fun performRefactoring(usages: Array<UsageInfo>) {
val (pathUsages, useSpecks, hasOtherUsages) = partitionUsages(usages)
val typeReference = typeAlias.typeReference ?: return
val inlined = pathUsages.mapNotNull {
fillPathWithActualType(it.path, typeReference, it.substitution)
}
for (useSpeck in useSpecks) {
deleteUseSpeck(useSpeck)
}
addNeededImports(inlined)
if (!inlineThisOnly && !hasOtherUsages && inlined.size == pathUsages.size) {
(typeAlias.prevSibling as? PsiWhiteSpace)?.delete()
typeAlias.delete()
}
}
private fun partitionUsages(usages: Array<UsageInfo>): Triple<List<PathUsage>, List<RsUseSpeck>, Boolean> {
val paths = mutableListOf<PathUsage>()
val useSpecks = mutableListOf<RsUseSpeck>()
for (usage in usages) {
val path = usage.element as? RsPath ?: continue
if (path.isExpandedFromMacro) continue
val useSpeck = path.ancestorOrSelf<RsUseSpeck>()
if (useSpeck != null) {
useSpecks += useSpeck
} else {
val resolved = path.reference?.advancedResolve() ?: continue
testAssert { resolved.element == typeAlias }
val substitution = tryGetTypeAliasSubstitutionUsingParent(path, typeAlias) ?: resolved.subst
paths += PathUsage(path, substitution)
}
}
val hasOtherUsages = paths.size + useSpecks.size != usages.size
return Triple(paths, useSpecks, hasOtherUsages)
}
private fun addNeededImports(inlined: List<RsElement>) {
val typeReference = typeAlias.typeReference ?: return
val handledMods = hashSetOf(typeAlias.containingMod)
for (context in inlined) {
val mod = context.containingMod
if (!handledMods.add(mod)) continue
RsImportHelper.importTypeReferencesFromElement(context, typeReference)
}
}
override fun getCommandName(): String = "Inline Type Alias ${typeAlias.name}"
override fun createUsageViewDescriptor(usages: Array<UsageInfo>): UsageViewDescriptor =
RsInlineUsageViewDescriptor(typeAlias, "Type Alias to inline")
}
/**
* type Foo<T> = Vec<T>;
* fn main() {
* let v = Foo::new();
* ~~~ has substitution `T => T`
* ~~~~~~~~ has substitution `Self => Vec<i32>`
* v.push(1);
* }
*/
fun tryGetTypeAliasSubstitutionUsingParent(path: RsPath, typeAlias: RsTypeAlias): Substitution? {
val parentPath = path.parent as? RsPath ?: return null
if (parentPath.parent !is RsPathExpr) return null
val resolvedMethod = parentPath.reference?.advancedResolve() ?: return null
val selfTy = resolvedMethod.subst[TyTypeParameter.self()] ?: return null
val inference = path.implLookup.ctx
val subst = inference.instantiateBounds(typeAlias, selfTy)
val typeReference = typeAlias.typeReference ?: return null
val type = typeReference.normType.substitute(subst)
inference.combineTypes(type, selfTy)
return subst.mapTypeValues { (_, v) -> inference.resolveTypeVarsIfPossible(v) }
}
/**
* type Foo<T> = Vec<T>;
* ~~~~~~ type
* fn main() {
* let _: Foo<i32>;
* ~~~~~~~~ path
* } subst = "T => i32"
*/
fun fillPathWithActualType(path: RsPath, typeReference: RsTypeReference, substitution: Substitution): RsElement? {
// TODO: Render qualified paths if needed (see `test qualify path`)
val typeText = typeReference.getStubOnlyText(substitution, shortPaths = false)
return fillPathWithActualType(path, typeText)
}
private fun fillPathWithActualType(path: RsPath, typeText: String): RsElement? {
val factory = RsPsiFactory(path.project)
val typeReference = factory.tryCreateType(typeText) ?: return null
val typeAsPath = (typeReference as? RsPathType)?.path
val parent = path.parent
return when {
parent is RsTypeReference -> {
parent.replace(typeReference)
}
typeAsPath != null -> {
if (path.ancestorStrict<RsTypeReference>() == null) {
// Consider `type Foo = HashSet<i32>;`
// Replace `Foo::new()` to `HashSet::<i32>::new()`
typeAsPath.typeArgumentList?.addAfter(factory.createColonColon(), null)
}
path.replace(typeAsPath)
}
parent is RsPath -> {
// Consider `type Foo = [i32];`
// Replace `Foo::is_empty(x)` to `<[i32]>::is_empty(x)`
val parentName = parent.referenceName ?: return null
val parentTypeArguments = parent.typeArgumentList?.text.orEmpty()
val parentNewText = "<$typeText>::$parentName$parentTypeArguments"
val parentNew = factory.tryCreatePath(parentNewText) ?: return null
parent.replace(parentNew)
}
// should be no other cases
else -> return null
} as RsElement
}
| mit | 4aadf1d541707e642e30a2f60589c996 | 38.344633 | 114 | 0.669012 | 4.519143 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/other/wifimeasurement/model/WifiMeasurement.kt | 1 | 1421 | package de.tum.`in`.tumcampusapp.component.other.wifimeasurement.model
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.arch.persistence.room.RoomWarnings
import android.net.wifi.ScanResult
import org.joda.time.DateTime
@Entity(tableName = "wifi_measurement")
@SuppressWarnings(RoomWarnings.DEFAULT_CONSTRUCTOR)
data class WifiMeasurement(@PrimaryKey
var date: DateTime = DateTime(),
var ssid: String = "",
var bssid: String = "",
var dBm: Int = -1,
var accuracyInMeters: Float = -1f,
var latitude: Double = -1.0,
var longitude: Double = -1.0) {
companion object {
fun create(ssid: String, bssid: String, dBm: Int, accuracyInMeters: Float, latitude: Double, longitude: Double): WifiMeasurement {
return WifiMeasurement(ssid = ssid, bssid = bssid, dBm = dBm,
accuracyInMeters = accuracyInMeters, latitude = latitude, longitude = longitude)
}
fun fromScanResult(scanResult: ScanResult): WifiMeasurement {
return WifiMeasurement(ssid = scanResult.SSID, bssid = scanResult.BSSID, dBm = scanResult.level,
accuracyInMeters = -1f, latitude = -1.0, longitude = -1.0)
}
}
}
| gpl-3.0 | dd220d39244e9b123215c14ff45fc8fb | 43.40625 | 138 | 0.611541 | 4.511111 | false | false | false | false |
oleksiyp/mockk | mockk/common/src/main/kotlin/io/mockk/impl/eval/RecordedBlockEvaluator.kt | 1 | 2663 | package io.mockk.impl.eval
import io.mockk.InternalPlatformDsl
import io.mockk.MockKException
import io.mockk.MockKGateway.CallRecorder
import io.mockk.MockKMatcherScope
import io.mockk.impl.InternalPlatform
import io.mockk.impl.recording.AutoHinter
abstract class RecordedBlockEvaluator(
val callRecorder: () -> CallRecorder,
val autoHinterFactory: () -> AutoHinter
) {
fun <T, S : MockKMatcherScope> record(
scope: S,
mockBlock: (S.() -> T)?,
coMockBlock: (suspend S.() -> T)?
) {
try {
val callRecorderInstance = callRecorder()
val block: () -> T = if (mockBlock != null) {
{ scope.mockBlock() }
} else if (coMockBlock != null) {
{ InternalPlatformDsl.runCoroutine { scope.coMockBlock() } }
} else {
{ throw MockKException("You should specify either 'mockBlock' or 'coMockBlock'") }
}
val blockWithRethrow = enhanceWithNPERethrow(block, callRecorderInstance::isLastCallReturnsNothing)
val autoHinter = autoHinterFactory()
try {
autoHinter.autoHint(
callRecorderInstance,
0,
64,
blockWithRethrow
)
} catch (npe: NothingThrownNullPointerException) {
// skip
}
val n = callRecorderInstance.estimateCallRounds();
for (i in 1 until n) {
try {
autoHinter.autoHint(
callRecorderInstance,
i,
n,
blockWithRethrow
)
} catch (npe: NothingThrownNullPointerException) {
// skip
}
}
callRecorderInstance.round(n, n)
callRecorderInstance.done()
} catch (ex: Throwable) {
throw InternalPlatform.prettifyRecordingException(ex)
}
}
private class NothingThrownNullPointerException : RuntimeException()
private fun <T> enhanceWithNPERethrow(
block: () -> T,
checkLastCallReturnsNothing: () -> Boolean
) =
{
try {
block()
} catch (npe: NullPointerException) {
if (checkLastCallReturnsNothing()) {
throw NothingThrownNullPointerException()
} else {
throw npe
}
}
}
protected fun initializeCoroutines() = InternalPlatformDsl.runCoroutine {}
}
| apache-2.0 | c042b6c2acc4a45ab8faaeda7882d246 | 29.965116 | 111 | 0.523845 | 5.15087 | false | false | false | false |
goldmansachs/obevo | obevo-db/src/main/java/com/gs/obevo/db/impl/core/changetypes/CsvStaticDataDeployer.kt | 1 | 19206 | /**
* Copyright 2017 Goldman Sachs.
* 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.gs.obevo.db.impl.core.changetypes
import com.gs.obevo.api.appdata.Change
import com.gs.obevo.api.appdata.PhysicalSchema
import com.gs.obevo.api.platform.DeployerRuntimeException
import com.gs.obevo.db.api.appdata.DbEnvironment
import com.gs.obevo.db.api.platform.DbPlatform
import com.gs.obevo.db.api.platform.SqlExecutor
import com.gs.obevo.db.impl.core.jdbc.JdbcHelper
import com.gs.obevo.dbmetadata.api.*
import com.gs.obevo.impl.reader.TextMarkupDocumentReader
import com.gs.obevocomparer.compare.CatoDataSide
import com.gs.obevocomparer.compare.CatoProperties
import com.gs.obevocomparer.compare.breaks.DataObjectBreak
import com.gs.obevocomparer.compare.breaks.FieldBreak
import com.gs.obevocomparer.compare.simple.SimpleCatoProperties
import com.gs.obevocomparer.input.CatoDataSource
import com.gs.obevocomparer.input.db.QueryDataSource
import com.gs.obevocomparer.input.db.QueryDataSource.QueryExecutor
import com.gs.obevocomparer.util.CatoBaseUtil
import org.apache.commons.lang3.Validate
import org.eclipse.collections.api.block.procedure.Procedure
import org.eclipse.collections.impl.factory.Lists
import org.eclipse.collections.impl.map.mutable.UnifiedMap
import org.slf4j.LoggerFactory
import java.sql.*
import java.util.*
import java.util.Date
import javax.sql.DataSource
/**
* Deployer class for loading CSV data into the target table.
*
* The deployArtifact method in this class will read in the data from the CSV file and then delegate to the abstract
* executeInserts method (implemented in the different subclasses) to do the actual loading. This is separated as
* there may be different ways to load data to the DB (e.g. incremental sqls vs. bulk loads,
* and bulk load logic may differ across different DBMSs)
*
* We separate the calculation of diffs (getStaticDataChangesForTable) from the execution of the changes
* (executeInserts) as this class will get called by the static data getDeployer to work across multiple tables.
* e.g. based on the foreign key associations for a number of tables, we calculate the diffs for all,
* and then in order, we would execute the inserts on all tables in the proper FK order, then updates on all tables,
* then deletes on all tables in the proper FK order
*/
open class CsvStaticDataDeployer(
private val env: DbEnvironment,
private val sqlExecutor: SqlExecutor,
private val dataSource: DataSource,
private val metadataManager: DbMetadataManager,
private val dbPlatform: DbPlatform
) {
protected val jdbcTemplate: JdbcHelper = sqlExecutor.jdbcTemplate
fun deployArtifact(staticData: Change) {
this.deployArtifact(Lists.mutable.with(staticData))
}
/**
* The table list should be in proper insertion order via FK (i.e. if TABLE_B has an FK pointing to TABLE_A,
* then TABLE_A should come first in the sorted list here)
*/
fun deployArtifact(staticDatas: List<Change>) {
val staticDataChanges = staticDatas.map { artifact -> getStaticDataChangesForTable(env, artifact) }
for (staticDataChange in staticDataChanges) {
sqlExecutor.executeWithinContext(staticDataChange.schema) { conn -> executeInserts(conn, staticDataChange) }
}
for (staticDataChange in staticDataChanges) {
sqlExecutor.executeWithinContext(staticDataChange.schema) { conn -> executeUpdates(conn, staticDataChange) }
}
// note here that deletes must be done in reverse order of the inserts
for (staticDataChange in staticDataChanges.asReversed()) {
sqlExecutor.executeWithinContext(staticDataChange.schema) { conn -> executeDeletes(conn, staticDataChange) }
}
}
private fun getStaticDataChangesForTable(env: DbEnvironment, artifact: Change): StaticDataChangeRows {
val table = Validate.notNull(
this.metadataManager.getTableInfo(artifact.getPhysicalSchema(env), artifact.objectName, DaSchemaInfoLevel()
.setRetrieveTables(true)
.setRetrieveTableColumns(true)
.setRetrieveTableCheckConstraints(true)
.setRetrieveTableIndexes(true)
// not retrieving foreign keys
),
"Could not find table %1\$s.%2\$s", artifact.getPhysicalSchema(env), artifact.objectName)
val fileSource = CsvStaticDataReader().getFileDataSource(env.csvVersion, table, artifact.convertedContent,
env.dataDelimiter, env.nullToken, dbPlatform.convertDbObjectName())
// we check this here to ensure that in case there are more fields in the DB than in the csv file
// (i.e. for default columns), that we exclude them later on
val fileColumnNames = fileSource.fields.map(this.dbPlatform.convertDbObjectName()::valueOf).toSet()
val dbColumnNames = table.columns.map(DaNamedObject::getName).map(this.dbPlatform.convertDbObjectName()::valueOf).toSet()
var updateTimeColumn = artifact.getMetadataAttribute(TextMarkupDocumentReader.ATTR_UPDATE_TIME_COLUMN)
if (updateTimeColumn != null) {
updateTimeColumn = this.dbPlatform.convertDbObjectName().valueOf(updateTimeColumn)
if (fileColumnNames.contains(updateTimeColumn)) {
throw IllegalArgumentException(String.format(
"The updateTimeColumn value %1\$s should not also be specified in the CSV column content: %2\$s",
updateTimeColumn, fileColumnNames))
} else if (!dbColumnNames.contains(updateTimeColumn)) {
throw IllegalArgumentException(String.format(
"The updateTimeColumn value %1\$s is expected in the database, but was not found: %2\$s",
updateTimeColumn, dbColumnNames))
}
}
val keyFields = getUniqueIndexColumnNames(artifact, table, fileColumnNames)
// exclude fields that are in the db table but not in the file; we'd assume the default/null value would be
// taken care of by the table definition
val excludeFields = dbColumnNames.filter { !fileColumnNames.contains(it) }
val reconFields = SimpleCatoProperties(keyFields, excludeFields)
return this.parseReconChanges(artifact, table, fileSource, reconFields, fileColumnNames, updateTimeColumn)
}
private fun getUniqueIndexColumnNames(artifact: Change, table: DaTable, fileColumnNames: Set<String>): List<String> {
val doesIndexColumnExistInCsv = { column: DaColumn -> fileColumnNames.contains(dbPlatform.convertDbObjectName().valueOf(column.name)) }
val artifactCandidate = getArtifactColumns(artifact)
val eligibleUniqueIndexes = getEligibleUniqueIndexes(table)
val indexCandidate = eligibleUniqueIndexes.firstOrNull { it.columns.all(doesIndexColumnExistInCsv) }
if (artifactCandidate != null) {
if (indexCandidate == null) {
return artifactCandidate
} else {
throw IllegalStateException("Cannot specify primary key and override tag on table ${table.name} to support CSV-based static data support")
}
} else if (indexCandidate != null) {
return indexCandidate.columns.map(DaNamedObject::getName).map(this.dbPlatform.convertDbObjectName()::valueOf)
} else {
val indexMessages = eligibleUniqueIndexes.map { index ->
val columnDisplay = { column: DaColumn ->
if (doesIndexColumnExistInCsv(column)) column.name else column.name + " (missing)"
}
index.name + "-[" + index.columns.joinToString(transform = columnDisplay) + "]"
}.sorted()
val messageSuffix = if (indexMessages.isEmpty()) "but none found" else "but existing ${indexMessages.size} indices did not have all columns defined in CSV: ${indexMessages.joinToString("; ")}}"
throw IllegalStateException("CSV-based static data loads require primary key or unique index on table " + table.name + ", " + messageSuffix)
}
}
private fun getArtifactColumns(artifact: Change): List<String>? {
return artifact.getMetadataAttribute(TextMarkupDocumentReader.ATTR_PRIMARY_KEYS)?.split(",")
}
private fun getEligibleUniqueIndexes(table: DaTable): List<DaIndex> {
return listOfNotNull(table.primaryKey)
.plus(table.indices.filter { it.isUnique })
}
private fun parseReconChanges(artifact: Change, table: DaTable,
fileSource: CatoDataSource,
reconFields: CatoProperties, fileColumnNames: Set<String>, updateTimeColumn: String?): StaticDataChangeRows {
val dbSource = this.getQueryDataSource(artifact.getPhysicalSchema(env), table)
val recon = CatoBaseUtil.compare("name", fileSource, dbSource, reconFields)
val inserts = Lists.mutable.empty<StaticDataInsertRow>()
val updates = Lists.mutable.empty<StaticDataUpdateRow>()
val deletes = Lists.mutable.empty<StaticDataDeleteRow>()
// must be java.sql.Timestamp, not Date, as that is correct JDBC (and Sybase ASE isn't forgiving of taking in
// Date for jdbc batch updates)
val updateTime = Timestamp(Date().time)
for (reconBreak in recon.breaks) {
if (reconBreak is FieldBreak) {
LOG.debug("Found as diff {}", reconBreak)
val params = UnifiedMap.newMap<String, Any>()
val whereParams = UnifiedMap.newMap<String, Any>()
UnifiedMap.newMap(reconBreak.fieldBreaks).forEachKey(Procedure { field ->
// same as for updates
val fieldToCompare = [email protected]().valueOf(field)
if (!fileColumnNames.contains(fieldToCompare)) {
return@Procedure
}
val value = reconBreak.dataObject.getValue(field)
params[field] = value
})
if (params.isEmpty) {
// nothing to do - only diff was in a default column
// see the "DEFAULT_FIELD TIMESTAMP NOT NULL DEFAULT CURRENT TIMESTAMP," use case
continue
}
if (updateTimeColumn != null) {
params[updateTimeColumn] = updateTime
}
for (keyField in recon.keyFields) {
whereParams[keyField] = reconBreak.getDataObject().getValue(keyField)
}
updates.add(StaticDataUpdateRow(params.toImmutable(), whereParams.toImmutable()))
} else if (reconBreak is DataObjectBreak) {
when (reconBreak.dataSide) {
CatoDataSide.LEFT -> {
// file source should be an insert
LOG.debug("Found as insert {}", reconBreak)
val params = UnifiedMap.newMap<String, Any>()
for (field in reconBreak.dataObject.fields) {
val fieldToCompare = this.dbPlatform.convertDbObjectName().valueOf(field)
if (!fileColumnNames.contains(fieldToCompare)) {
continue
}
params[field] = reconBreak.dataObject.getValue(field)
}
if (updateTimeColumn != null) {
params[updateTimeColumn] = updateTime
}
val rowNumber = reconBreak.dataObject.getValue(CsvReaderDataSource.ROW_NUMBER_FIELD) as Int
inserts.add(StaticDataInsertRow(rowNumber, params.toImmutable()))
}
CatoDataSide.RIGHT -> {
// db source should be a delete
LOG.debug("Found as delete {}", reconBreak)
val whereParams = UnifiedMap.newMap<String, Any>()
for (keyField in recon.keyFields) {
whereParams[keyField] = reconBreak.getDataObject().getValue(keyField)
}
deletes.add(StaticDataDeleteRow(whereParams.toImmutable()))
}
else -> throw IllegalArgumentException("Invalid enum specified here: " + reconBreak.dataSide + " on " + reconBreak)
}
} else {
throw IllegalStateException(
"Cannot have group breaks or any breaks other than Field or DataObject - is your primary key defined correctly? $reconBreak")
}
}
// sort this by the row number to assure that the insertion row from the CSV file remains preserved
inserts.sortThisBy { it.rowNumber }
return StaticDataChangeRows(artifact.getPhysicalSchema(env), table, inserts.toImmutable(), updates.toImmutable(), deletes.toImmutable())
}
/**
* Note - we still need the PhysicalSchema object, as the schema coming from sybase may still have "dbo" there.
* Until we abstract this in the metadata API, we go w/ the signature as is
*
* Also - this can be overridable in case we want to support bulk-inserts for specific database types,
* e.g. Sybase IQ
*
* We only use batching for "executeInserts" as that is the 90% case of the performance
* (updates may vary the kinds of sqls that are needed, and deletes I'd assume are rare)
*/
protected open fun executeInserts(conn: Connection, changeRows: StaticDataChangeRows) {
if (changeRows.insertRows.isEmpty) {
return
}
val changeFormat = changeRows.insertRows.first
val paramValMarkers = arrayOfNulls<String>(changeFormat.insertColumns.size())
Arrays.fill(paramValMarkers, "?")
val insertValues = Lists.mutable.with<String>(*paramValMarkers)
val sql = "INSERT INTO " + dbPlatform.getSchemaPrefix(changeRows.schema) + changeRows.table.name +
changeFormat.insertColumns.makeString("(", ", ", ")") +
" VALUES " + insertValues.makeString("(", ", ", ")")
LOG.info("Executing the insert $sql")
for (chunkInsertRows in changeRows.insertRows.chunk(INSERT_BATCH_SIZE)) {
val paramArrays = arrayOfNulls<Array<Any>>(chunkInsertRows.size())
chunkInsertRows.forEachWithIndex { insert, i -> paramArrays[i] = insert.params.valuesView().toList().toTypedArray() }
if (LOG.isDebugEnabled) {
LOG.debug("for " + paramArrays.size + " rows with params: " + Arrays.deepToString(paramArrays))
}
this.jdbcTemplate.batchUpdate(conn, sql, paramArrays)
}
}
/**
* See executeInserts javadoc for why we don't leverage batching here
*/
private fun executeUpdates(conn: Connection, changeRows: StaticDataChangeRows) {
for (update in changeRows.updateRows) {
val updatePieces = Lists.mutable.empty<String>()
val whereClauseParts = Lists.mutable.empty<String>()
val paramVals = Lists.mutable.empty<Any>()
for (stringObjectPair in update.params.keyValuesView()) {
updatePieces.add(stringObjectPair.one + " = ?")
paramVals.add(stringObjectPair.two)
}
for (stringObjectPair in update.whereParams.keyValuesView()) {
whereClauseParts.add(stringObjectPair.one + " = ?")
paramVals.add(stringObjectPair.two)
}
val sql = "UPDATE " + dbPlatform.getSchemaPrefix(changeRows.schema) + changeRows.table.name +
" SET " + updatePieces.makeString(", ") +
" WHERE " + whereClauseParts.makeString(" AND ")
LOG.info("Executing this break: [$sql] with params [$paramVals]")
this.jdbcTemplate.update(conn, sql, *paramVals.toArray())
}
}
/**
* See executeInserts javadoc for why we don't leverage batching here
*/
private fun executeDeletes(conn: Connection, changeRows: StaticDataChangeRows) {
for (delete in changeRows.deleteRows) {
val paramVals = Lists.mutable.empty<Any>()
val whereClauseParts = Lists.mutable.empty<String>()
for (stringObjectPair in delete.whereParams.keyValuesView()) {
val column = stringObjectPair.one
val value = stringObjectPair.two
whereClauseParts.add("$column = ?")
paramVals.add(value)
}
val sql = "DELETE FROM " + dbPlatform.getSchemaPrefix(changeRows.schema) + changeRows.table.name +
" WHERE " + whereClauseParts.makeString(" AND ")
LOG.info("DELETING: " + sql + ":" + paramVals.makeString(", "))
this.jdbcTemplate.update(conn, sql, *paramVals.toArray())
}
}
private fun getQueryDataSource(physicalSchema: PhysicalSchema, table: DaTable): CatoDataSource {
val cols = table.columns
val colNameStr = cols.collect(DaNamedObject.TO_NAME).collect(this.dbPlatform.convertDbObjectName()).makeString(", ")
val query = "select " + colNameStr + " from " + this.dbPlatform.getSchemaPrefix(physicalSchema) + table.name
try {
val conn = this.dataSource.connection
// Here, we need to execute the query using jdbcTemplate so that we can retry exceptions where applicable (e.g. DB2 reorgs)
return QueryDataSource("dbSource", conn, object : QueryExecutor {
private var stmt: Statement? = null
@Throws(Exception::class)
override fun getResultSet(connection: Connection): ResultSet {
val stmtRsPair = jdbcTemplate.queryAndLeaveStatementOpen(conn, query)
this.stmt = stmtRsPair.one
return stmtRsPair.two
}
@Throws(Exception::class)
override fun close() {
this.stmt!!.close()
}
})
} catch (e: SQLException) {
throw DeployerRuntimeException(e)
}
}
companion object {
private val LOG = LoggerFactory.getLogger(CsvStaticDataDeployer::class.java)
private val INSERT_BATCH_SIZE = 25
}
}
| apache-2.0 | 3aa790d6db8fd83dca4545775e523e30 | 47.870229 | 205 | 0.642508 | 4.746911 | false | false | false | false |
rosenpin/QuickDrawEverywhere | app/src/main/java/com/tomer/draw/windows/HolderService.kt | 1 | 933 | package com.tomer.draw.windows
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.tomer.draw.windows.bubble.DraggableView
import java.io.File
/**
* DrawEverywhere
* Created by Tomer Rosenfeld on 7/28/17.
*/
class HolderService : Service() {
companion object {
var file: File? = null
}
lateinit var draggable: DraggableView
override fun onBind(intent: Intent?): IBinder? = null
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val image: Boolean = intent?.getBooleanExtra("loadBitmap", false) ?: false
if (image) {
if (file != null)
draggable.loadBitmap(file!!)
}
return super.onStartCommand(intent, flags, startId)
}
override fun onCreate() {
super.onCreate()
draggable = DraggableView(this)
draggable.addToWindow()
}
override fun onDestroy() {
super.onDestroy()
draggable.removeFromWindow()
file = null
}
}
| gpl-3.0 | f06545181d68cb2f64f524b75beb74e3 | 21.214286 | 78 | 0.719185 | 3.468401 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | system/src/main/kotlin/com/commonsense/android/kotlin/system/extensions/ActivityExtensions.kt | 1 | 4064 | @file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate")
package com.commonsense.android.kotlin.system.extensions
import android.app.*
import android.content.*
import android.support.annotation.*
import android.support.v4.app.*
import android.support.v4.app.Fragment
import android.support.v4.widget.*
import android.support.v7.app.*
import android.support.v7.app.ActionBar
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.*
import android.view.*
import com.commonsense.android.kotlin.base.*
import kotlin.reflect.*
/**
*
* @receiver AppCompatActivity
* @param drawer DrawerLayout
* @param toolbar Toolbar
* @param openTitle Int
* @param closeTitle Int
* @return ActionBarDrawerToggle
*/
@UiThread
fun AppCompatActivity.setupToolbarAppDrawer(drawer: DrawerLayout,
toolbar: Toolbar,
@StringRes openTitle: Int,
@StringRes closeTitle: Int): ActionBarDrawerToggle {
setSupportActionBar(toolbar)
val toggle = ActionBarDrawerToggle(this, drawer, toolbar, openTitle, closeTitle)
drawer.addDrawerListener(toggle)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
return toggle
}
/**
*
* @receiver Activity
* @param toStart Class<T>
* @param flags Int?
*/
@UiThread
fun <T : Activity> Activity.startActivity(toStart: Class<T>, flags: Int? = null) {
startActivity(Intent(this, toStart).apply {
if (flags != null) {
this.flags = flags
}
})
}
/**
*
* @receiver Activity
* @param toStart KClass<T>
* @param flags Int?
*/
@UiThread
fun <T : Activity> Activity.startActivity(toStart: KClass<T>, flags: Int? = null) {
startActivity(toStart.java, flags)
}
/**
*
* @receiver AppCompatActivity
* @param toolbar Toolbar
* @param actionToApply (ActionBar.() -> Unit)
*/
@UiThread
inline fun AppCompatActivity.setSupportActionBarAndApply(toolbar: Toolbar,
crossinline actionToApply: (ActionBar.() -> Unit)) {
setSupportActionBar(toolbar)
supportActionBar?.apply(actionToApply)
}
/**
* Pops all fragments from the current FragmentManager, except the bottom fragment
* Logs if the operation fails (does not throw)
* @receiver FragmentActivity
*/
@UiThread
fun FragmentActivity.popToFirstFragment() = runOnUiThread {
supportFragmentManager?.popToFirstFragment()
}
@UiThread
fun FragmentActivity.replaceFragment(@IdRes container: Int, fragment: Fragment) {
supportFragmentManager?.replaceFragment(container, fragment)
}
@UiThread
fun FragmentActivity.pushNewFragmentTo(@IdRes container: Int, fragment: Fragment) {
supportFragmentManager?.pushNewFragmentTo(container, fragment)
}
@UiThread
fun FragmentActivity.pushNewFragmentsTo(@IdRes container: Int, fragments: List<Fragment>) {
supportFragmentManager?.pushNewFragmentsTo(container, fragments)
}
/**
* Safe finish call, so wrapping it in runOnUiThread is not required.
*/
@AnyThread
fun Activity.safeFinish() = runOnUiThread(this::finish)
/**
* starts the given intent and finishes this activity
* @receiver Activity
* @param intent Intent
*/
@AnyThread
fun Activity.startAndFinish(intent: Intent) = runOnUiAndFinish {
startActivity(intent)
}
@AnyThread
fun Activity.startAndFinish(kClass: KClass<Activity>, flags: Int? = null) = runOnUiAndFinish {
startActivity(kClass, flags)
}
@AnyThread
fun Activity.startAndFinish(jClass: Class<Activity>, flags: Int? = null) = runOnUiAndFinish {
startActivity(jClass, flags)
}
/**
*
* @receiver Activity
*/
@Suppress("NOTHING_TO_INLINE")
@AnyThread
private inline fun Activity.runOnUiAndFinish(@UiThread crossinline action: EmptyFunction) = runOnUiThread {
action()
finish()
}
/**
* The root view of an activity
*/
inline val Activity.rootView: View?
@UiThread
get() = window?.decorView?.rootView ?: findViewById(android.R.id.content) | mit | 011d828d008094ffca469a4fab8a9db5 | 25.92053 | 109 | 0.712106 | 4.273396 | false | false | false | false |
inorichi/tachiyomi-extensions | src/en/pururin/src/eu/kanade/tachiyomi/extension/en/pururin/Pururin.kt | 1 | 8597 | package eu.kanade.tachiyomi.extension.en.pururin
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import eu.kanade.tachiyomi.util.asJsoup
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
@Nsfw
class Pururin : ParsedHttpSource() {
override val name = "Pururin"
override val baseUrl = "https://pururin.io"
override val lang = "en"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
override fun latestUpdatesSelector() = "div.container div.row-gallery a"
override fun latestUpdatesRequest(page: Int): Request {
return if (page == 1) {
GET(baseUrl, headers)
} else {
GET("$baseUrl/browse/newest?page=$page", headers)
}
}
override fun latestUpdatesFromElement(element: Element): SManga {
val manga = SManga.create()
manga.setUrlWithoutDomain(element.attr("href"))
manga.title = element.select("div.title").text()
manga.thumbnail_url = element.select("img.card-img-top").attr("abs:data-src")
return manga
}
override fun latestUpdatesNextPageSelector() = "ul.pagination a.page-link[rel=next]"
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select("div.box.box-gallery")
val manga = SManga.create()
val genres = mutableListOf<String>()
document.select("tr:has(td:contains(Contents)) li").forEach { element ->
val genre = element.text()
genres.add(genre)
}
manga.title = infoElement.select("h1").text()
manga.author = infoElement.select("tr:has(td:contains(Artist)) a").attr("title")
manga.artist = infoElement.select("tr:has(td:contains(Circle)) a").text()
manga.status = SManga.COMPLETED
manga.genre = genres.joinToString(", ")
manga.thumbnail_url = document.select("div.cover-wrapper v-lazy-image").attr("abs:src")
manga.description = getDesc(document)
return manga
}
private fun getDesc(document: Document): String {
val infoElement = document.select("div.box.box-gallery")
val uploader = infoElement.select("tr:has(td:contains(Uploader)) .user-link")?.text()
val pages = infoElement.select("tr:has(td:contains(Pages)) td:eq(1)").text()
val ratingCount = infoElement.select("tr:has(td:contains(Ratings)) span[itemprop=\"ratingCount\"]")?.attr("content")
val rating = infoElement.select("tr:has(td:contains(Ratings)) gallery-rating").attr(":rating")?.toFloatOrNull()?.let {
if (it > 5.0f) minOf(it, 5.0f) // cap rating to 5.0 for rare cases where value exceeds 5.0f
else it
}
val multiDescriptions = listOf(
"Convention",
"Parody",
"Circle",
"Category",
"Character",
"Language"
).map { it to infoElement.select("tr:has(td:contains($it)) a").map { v -> v.text() } }
.filter { !it.second.isNullOrEmpty() }
.map { "${it.first}: ${it.second.joinToString()}" }
val descriptions = listOf(
multiDescriptions.joinToString("\n\n"),
uploader?.let { "Uploader: $it" },
pages?.let { "Pages: $it" },
rating?.let { "Ratings: $it" + (ratingCount?.let { c -> " ($c ratings)" } ?: "") }
)
return descriptions.joinToString("\n\n")
}
override fun chapterListParse(response: Response) = with(response.asJsoup()) {
val mangaInfoElements = this.select(".table-gallery-info tr td:first-child").map {
it.text() to it.nextElementSibling()
}.toMap()
val chapters = this.select(".table-collection tbody tr")
if (!chapters.isNullOrEmpty())
chapters.map {
val details = it.select("td")
SChapter.create().apply {
chapter_number = details[0].text().removePrefix("#").toFloat()
name = details[1].select("a").text()
setUrlWithoutDomain(details[1].select("a").attr("href"))
if (it.hasClass("active") && mangaInfoElements.containsKey("Scanlator"))
scanlator = mangaInfoElements.getValue("Scanlator").select("li a")?.joinToString { s -> s.text() }
}
}
else
listOf(
SChapter.create().apply {
name = "Chapter"
setUrlWithoutDomain(response.request.url.toString())
if (mangaInfoElements.containsKey("Scanlator"))
scanlator = mangaInfoElements.getValue("Scanlator").select("li a")?.joinToString { s -> s.text() }
}
)
}
override fun pageListRequest(chapter: SChapter): Request = GET(
"$baseUrl${chapter.url.let {
it.substringAfterLast("/").let { titleUri ->
it.replace(titleUri, "01/$titleUri")
}.replace("gallery", "read")
}}"
)
override fun chapterListSelector(): String = throw UnsupportedOperationException("Not used")
override fun chapterFromElement(element: Element): SChapter = throw UnsupportedOperationException("Not used")
override fun pageListParse(document: Document): List<Page> {
val pages = mutableListOf<Page>()
val galleryInfo = document.select("gallery-read").toString().substringAfter('{').substringBefore('}')
val id = galleryInfo.substringAfter("id":").substringBefore(',')
val total: Int = (galleryInfo.substringAfter("total_pages":").substringBefore(',')).toInt()
for (i in 1..total) {
pages.add(Page(i, "", "https://cdn.pururin.io/assets/images/data/$id/$i.jpg"))
}
return pages
}
override fun imageUrlParse(document: Document): String = throw UnsupportedOperationException("Not used")
override fun popularMangaRequest(page: Int): Request = GET("$baseUrl/browse/most-popular?page=$page", headers)
override fun popularMangaFromElement(element: Element) = latestUpdatesFromElement(element)
override fun popularMangaSelector() = latestUpdatesSelector()
override fun popularMangaNextPageSelector() = latestUpdatesNextPageSelector()
private lateinit var tagUrl: String
// TODO: Additional filter options, specifically the type[] parameter
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
var url = "$baseUrl/search?q=$query&page=$page"
if (query.isBlank()) {
filters.forEach { filter ->
when (filter) {
is Tag -> {
url = if (page == 1) {
"$baseUrl/search/tag?q=${filter.state}&type[]=3" // "Contents" tag
} else {
"$tagUrl?page=$page"
}
}
}
}
}
return GET(url, headers)
}
override fun searchMangaParse(response: Response): MangasPage {
return if (response.request.url.toString().contains("tag?")) {
response.asJsoup().select("table.table tbody tr a:first-of-type").attr("abs:href").let {
if (it.isNotEmpty()) {
tagUrl = it
super.searchMangaParse(client.newCall(GET(tagUrl, headers)).execute())
} else {
MangasPage(emptyList(), false)
}
}
} else {
super.searchMangaParse(response)
}
}
override fun searchMangaSelector() = latestUpdatesSelector()
override fun searchMangaFromElement(element: Element) = latestUpdatesFromElement(element)
override fun searchMangaNextPageSelector() = latestUpdatesNextPageSelector()
override fun getFilterList() = FilterList(
Filter.Header("NOTE: Ignored if using text search!"),
Filter.Separator(),
Tag("Tag")
)
private class Tag(name: String) : Filter.Text(name)
}
| apache-2.0 | 58c87322066856d591e76ef17049d377 | 37.208889 | 126 | 0.607654 | 4.597326 | false | false | false | false |
thienan93/phdiff | src/main/kotlin/io/nthienan/phdiff/differential/Diff.kt | 1 | 399 | package io.nthienan.phdiff.differential
import java.util.Date
/**
* Created on 18/07/2017.
* @author nthienan
*/
class Diff {
var id: String = ""
var revisionId: String = ""
var dateCreated: Date? = null
var dateModified: Date? = null
var branch: String = ""
var unitStatus: Int = 0
var lintStatus: Int = 0
fun getFormatedRevisionID(): String {
return "D$revisionId"
}
}
| apache-2.0 | 7aee55aa4236a1ec85e510f8ae507633 | 18 | 39 | 0.661654 | 3.325 | false | false | false | false |
kaskasi/VocabularyTrainer | app/src/test/java/de/fluchtwege/vocabulary/QuestionsViewModelTest.kt | 1 | 3785 | package de.fluchtwege.vocabulary
import de.fluchtwege.vocabulary.lessons.LessonsRepository
import de.fluchtwege.vocabulary.models.Lesson
import de.fluchtwege.vocabulary.models.Question
import de.fluchtwege.vocabulary.questions.QuestionsViewModel
import io.reactivex.Flowable
import org.junit.Assert.*
import org.junit.Test
import org.mockito.Mockito.*
import java.lang.Exception
class QuestionsViewModelTest {
val lessonName = "name"
val description = "description"
val information = "information"
val answer = "answer"
@Test
fun `Given repository When questions are loaded successfully Then view is notified`() {
val lessonsRepository = mock(LessonsRepository::class.java)
val lesson = Lesson(lessonName, description, emptyList())
doReturn(Flowable.just(lesson)).`when`(lessonsRepository).getLesson(lessonName)
val viewModel = QuestionsViewModel(lessonName, lessonsRepository)
var questionsLoaded = false
viewModel.loadQuestions { questionsLoaded = true }
assertTrue(questionsLoaded)
}
@Test
fun `Given repository When questions are being loaded Then progress is shown`() {
val lessonsRepository = mock(LessonsRepository::class.java)
doReturn(Flowable.never<List<Lesson>>()).`when`(lessonsRepository).getLesson(lessonName)
val viewModel = QuestionsViewModel(lessonName, lessonsRepository)
viewModel.loadQuestions { }
assertTrue(viewModel.isProgressVisible())
}
@Test
fun `Given repository When questions are loaded successfully Then progress is not shown`() {
val lessonsRepository = mock(LessonsRepository::class.java)
val lesson = Lesson(lessonName, description, emptyList())
doReturn(Flowable.just(lesson)).`when`(lessonsRepository).getLesson(lessonName)
val viewModel = QuestionsViewModel(lessonName, lessonsRepository)
viewModel.loadQuestions { }
assertFalse(viewModel.isProgressVisible())
}
@Test
fun `Given repository When questions can not be loaded Then progress is not shown`() {
val lessonsRepository = mock(LessonsRepository::class.java)
doReturn(Flowable.error<Exception>(Exception(""))).`when`(lessonsRepository).getLesson(lessonName)
val viewModel = QuestionsViewModel(lessonName, lessonsRepository)
viewModel.loadQuestions { }
assertFalse(viewModel.isProgressVisible())
}
@Test
fun `Given repository When questions are loaded successfully Then number of questions is returned`() {
val lessonsRepository = mock(LessonsRepository::class.java)
val questions = listOf(Question("", ""), Question("", ""))
val lesson = Lesson(lessonName, description, questions)
doReturn(Flowable.just(lesson)).`when`(lessonsRepository).getLesson(lessonName)
val viewModel = QuestionsViewModel(lessonName, lessonsRepository)
viewModel.loadQuestions { }
assertEquals(viewModel.getNumberOfQuestions(), questions.size)
}
@Test
fun `Given repository When questions are loaded successfully Then viewModel is created for question`() {
val lessonsRepository = mock(LessonsRepository::class.java)
val questions = listOf(Question(information, answer), Question("", ""))
val lesson = Lesson(lessonName, description, questions)
doReturn(Flowable.just(lesson)).`when`(lessonsRepository).getLesson(lessonName)
val viewModel = QuestionsViewModel(lessonName, lessonsRepository)
viewModel.loadQuestions { }
val questionViewModel = viewModel.getQuestionViewModel(0)
assertEquals(questionViewModel.getInformation(), information)
assertEquals(questionViewModel.getAnswer(), answer)
}
} | mit | 2741466781b35fd7e2bff21b28f29dad | 38.4375 | 108 | 0.722589 | 5.094213 | false | true | false | false |
TimLavers/IndoFlashKotlin | app/src/main/java/org/grandtestauto/indoflash/spec/WordListSpec.kt | 1 | 568 | package org.grandtestauto.indoflash.spec
import org.w3c.dom.Element
val WORD_LIST = "WordList"
/**
* Title and filename for a word list. Read from XML.
* @author Tim Lavers
*/
class WordListSpec : Spec {
private val FILE_TAG = "File"
val fileName: String
internal constructor(title: String, fileName: String) : super(title) {
this.fileName = fileName
}
internal constructor(node: Element) : super(node) {
val childNodes = node.getElementsByTagName(FILE_TAG)
fileName = childNodes.item(0).textContent.trim()
}
} | mit | e1dc5dab8f8391a79dff8c9d4613442b | 21.76 | 74 | 0.677817 | 3.863946 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/lang/editor/folding/XPathFoldingBuilder.kt | 1 | 3562 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.lang.editor.folding
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.FoldingBuilderEx
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.elementType
import uk.co.reecedunn.intellij.plugin.core.sequences.walkTree
import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginContextItemFunctionExpr
import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginLambdaFunctionExpr
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathComment
import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathElementType
import uk.co.reecedunn.intellij.plugin.xpath.psi.enclosedExpressionBlocks
class XPathFoldingBuilder : FoldingBuilderEx() {
override fun buildFoldRegions(root: PsiElement, document: Document, quick: Boolean): Array<FoldingDescriptor> {
val descriptors = ArrayList<FoldingDescriptor>()
root.walkTree().forEach { child ->
val range = getSingleFoldingRange(child)
if (range?.isEmpty == false && child.textContains('\n')) {
descriptors.add(FoldingDescriptor(child, range))
}
getEnclosedExprContainer(child)?.enclosedExpressionBlocks?.forEach { block ->
if (block.isMultiLine) {
descriptors.add(FoldingDescriptor(child, block.textRange))
}
}
}
return descriptors.toTypedArray()
}
override fun getPlaceholderText(node: ASTNode): String? = when (node.elementType) {
XPathElementType.COMMENT -> "(:...:)"
XPathElementType.CONTEXT_ITEM_FUNCTION_EXPR -> ".{...}"
XPathElementType.LAMBDA_FUNCTION_EXPR -> "_{...}"
in ENCLOSED_EXPR_CONTAINER -> "{...}"
else -> null
}
override fun isCollapsedByDefault(node: ASTNode): Boolean = false
private fun getEnclosedExprContainer(element: PsiElement): PsiElement? = when (element.elementType) {
in ENCLOSED_EXPR_CONTAINER -> element
else -> null
}
private fun getSingleFoldingRange(element: PsiElement): TextRange? = when (element) {
is PluginContextItemFunctionExpr -> element.textRange
is PluginLambdaFunctionExpr -> element.textRange
is XPathComment -> element.textRange
else -> null
}
companion object {
private val ENCLOSED_EXPR_CONTAINER = TokenSet.create(
XPathElementType.ARROW_INLINE_FUNCTION_CALL,
XPathElementType.CURLY_ARRAY_CONSTRUCTOR,
XPathElementType.FT_EXTENSION_SELECTION,
XPathElementType.FT_WEIGHT,
XPathElementType.FT_WORDS_VALUE,
XPathElementType.INLINE_FUNCTION_EXPR,
XPathElementType.MAP_CONSTRUCTOR,
XPathElementType.WITH_EXPR
)
}
}
| apache-2.0 | 4344d99450427164f6db251b22e717f5 | 41.404762 | 115 | 0.705222 | 4.520305 | false | false | false | false |
PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt | 3 | 16907 | package info.nightscout.androidaps.dialogs
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.view.Window
import android.view.WindowManager
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.CompoundButton
import androidx.fragment.app.DialogFragment
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.DatabaseHelper
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.dialog_wizard.*
import org.slf4j.LoggerFactory
import java.text.DecimalFormat
import java.util.*
import kotlin.math.abs
class WizardDialog : DialogFragment() {
private val log = LoggerFactory.getLogger(WizardDialog::class.java)
private var wizard: BolusWizard? = null
//one shot guards
private var okClicked: Boolean = false
private val textWatcher = 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) {
calculateInsulin()
}
}
private var disposable: CompositeDisposable = CompositeDisposable()
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putDouble("treatments_wizard_bg_input", treatments_wizard_bg_input.value)
savedInstanceState.putDouble("treatments_wizard_carbs_input", treatments_wizard_carbs_input.value)
savedInstanceState.putDouble("treatments_wizard_correction_input", treatments_wizard_correction_input.value)
savedInstanceState.putDouble("treatments_wizard_carb_time_input", treatments_wizard_carb_time_input.value)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
isCancelable = true
dialog?.setCanceledOnTouchOutside(false)
return inflater.inflate(R.layout.dialog_wizard, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
loadCheckedStates()
processCobCheckBox()
treatments_wizard_sbcheckbox.visibility = SP.getBoolean(R.string.key_usesuperbolus, false).toVisibility()
treatments_wizard_notes_layout.visibility = SP.getBoolean(R.string.key_show_notes_entry_dialogs, false).toVisibility()
val maxCarbs = MainApp.getConstraintChecker().maxCarbsAllowed.value()
val maxCorrection = MainApp.getConstraintChecker().maxBolusAllowed.value()
treatments_wizard_bg_input.setParams(savedInstanceState?.getDouble("treatments_wizard_bg_input")
?: 0.0, 0.0, 500.0, 0.1, DecimalFormat("0.0"), false, ok, textWatcher)
treatments_wizard_carbs_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carbs_input")
?: 0.0, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false, ok, textWatcher)
val bolusStep = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription?.bolusStep
?: 0.1
treatments_wizard_correction_input.setParams(savedInstanceState?.getDouble("treatments_wizard_correction_input")
?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
treatments_wizard_carb_time_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carb_time_input")
?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher)
initDialog()
treatments_wizard_percent_used.text = MainApp.gs(R.string.format_percent, SP.getInt(R.string.key_boluswizard_percentage, 100))
// ok button
ok.setOnClickListener {
if (okClicked) {
log.debug("guarding: ok already clicked")
} else {
okClicked = true
calculateInsulin()
context?.let { context ->
wizard?.confirmAndExecute(context)
}
}
dismiss()
}
// cancel button
cancel.setOnClickListener { dismiss() }
// checkboxes
treatments_wizard_bgcheckbox.setOnCheckedChangeListener(::onCheckedChanged)
treatments_wizard_ttcheckbox.setOnCheckedChangeListener(::onCheckedChanged)
treatments_wizard_cobcheckbox.setOnCheckedChangeListener(::onCheckedChanged)
treatments_wizard_basaliobcheckbox.setOnCheckedChangeListener(::onCheckedChanged)
treatments_wizard_bolusiobcheckbox.setOnCheckedChangeListener(::onCheckedChanged)
treatments_wizard_bgtrendcheckbox.setOnCheckedChangeListener(::onCheckedChanged)
treatments_wizard_sbcheckbox.setOnCheckedChangeListener(::onCheckedChanged)
val showCalc = SP.getBoolean(MainApp.gs(R.string.key_wizard_calculation_visible), false)
treatments_wizard_delimiter.visibility = showCalc.toVisibility()
treatments_wizard_resulttable.visibility = showCalc.toVisibility()
treatments_wizard_calculationcheckbox.isChecked = showCalc
treatments_wizard_calculationcheckbox.setOnCheckedChangeListener { _, isChecked ->
run {
SP.putBoolean(MainApp.gs(R.string.key_wizard_calculation_visible), isChecked)
treatments_wizard_delimiter.visibility = isChecked.toVisibility()
treatments_wizard_resulttable.visibility = isChecked.toVisibility()
}
}
// profile spinner
treatments_wizard_profile.onItemSelectedListener = object : OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.noprofileselected))
ok.visibility = View.GONE
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
calculateInsulin()
ok.visibility = View.VISIBLE
}
}
// bus
disposable.add(RxBus
.toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
activity?.runOnUiThread { calculateInsulin() }
}, {
FabricPrivacy.logException(it)
})
)
}
override fun onDestroyView() {
super.onDestroyView()
disposable.clear()
}
private fun onCheckedChanged(buttonView: CompoundButton, @Suppress("UNUSED_PARAMETER") state: Boolean) {
saveCheckedStates()
treatments_wizard_ttcheckbox.isEnabled = treatments_wizard_bgcheckbox.isChecked && TreatmentsPlugin.getPlugin().tempTargetFromHistory != null
if (buttonView.id == treatments_wizard_cobcheckbox.id)
processCobCheckBox()
calculateInsulin()
}
private fun processCobCheckBox() {
if (treatments_wizard_cobcheckbox.isChecked) {
treatments_wizard_bolusiobcheckbox.isEnabled = false
treatments_wizard_basaliobcheckbox.isEnabled = false
treatments_wizard_bolusiobcheckbox.isChecked = true
treatments_wizard_basaliobcheckbox.isChecked = true
} else {
treatments_wizard_bolusiobcheckbox.isEnabled = true
treatments_wizard_basaliobcheckbox.isEnabled = true
}
}
private fun saveCheckedStates() {
SP.putBoolean(MainApp.gs(R.string.key_wizard_include_cob), treatments_wizard_cobcheckbox.isChecked)
SP.putBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), treatments_wizard_bgtrendcheckbox.isChecked)
}
private fun loadCheckedStates() {
treatments_wizard_bgtrendcheckbox.isChecked = SP.getBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), false)
treatments_wizard_cobcheckbox.isChecked = SP.getBoolean(MainApp.gs(R.string.key_wizard_include_cob), false)
}
private fun initDialog() {
val profile = ProfileFunctions.getInstance().profile
val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile
if (profile == null || profileStore == null) {
ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.noprofile))
dismiss()
return
}
val profileList: ArrayList<CharSequence>
profileList = profileStore.getProfileList()
profileList.add(0, MainApp.gs(R.string.active))
context?.let { context ->
val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList)
treatments_wizard_profile.adapter = adapter
} ?: return
val units = ProfileFunctions.getSystemUnits()
treatments_wizard_bgunits.text = units
if (units == Constants.MGDL)
treatments_wizard_bg_input.setStep(1.0)
else
treatments_wizard_bg_input.setStep(0.1)
// Set BG if not old
val lastBg = DatabaseHelper.actualBg()
if (lastBg != null) {
treatments_wizard_bg_input.value = lastBg.valueToUnits(units)
} else {
treatments_wizard_bg_input.value = 0.0
}
treatments_wizard_ttcheckbox.isEnabled = TreatmentsPlugin.getPlugin().tempTargetFromHistory != null
// IOB calculation
TreatmentsPlugin.getPlugin().updateTotalIOBTreatments()
val bolusIob = TreatmentsPlugin.getPlugin().lastCalculationTreatments.round()
TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals()
val basalIob = TreatmentsPlugin.getPlugin().lastCalculationTempBasals.round()
treatments_wizard_bolusiobinsulin.text = StringUtils.formatInsulin(-bolusIob.iob)
treatments_wizard_basaliobinsulin.text = StringUtils.formatInsulin(-basalIob.basaliob)
calculateInsulin()
treatments_wizard_percent_used.visibility = (SP.getInt(R.string.key_boluswizard_percentage, 100) != 100).toVisibility()
}
private fun calculateInsulin() {
val profileStore = ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile
if (treatments_wizard_profile.selectedItem == null || profileStore == null)
return // not initialized yet
var profileName = treatments_wizard_profile.selectedItem.toString()
val specificProfile: Profile?
if (profileName == MainApp.gs(R.string.active)) {
specificProfile = ProfileFunctions.getInstance().profile
profileName = ProfileFunctions.getInstance().profileName
} else
specificProfile = profileStore.getSpecificProfile(profileName)
if (specificProfile == null) return
// Entered values
var bg = SafeParse.stringToDouble(treatments_wizard_bg_input.text)
val carbs = SafeParse.stringToInt(treatments_wizard_carbs_input.text)
val correction = SafeParse.stringToDouble(treatments_wizard_correction_input.text)
val carbsAfterConstraint = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(carbs)).value()
if (abs(carbs - carbsAfterConstraint) > 0.01) {
treatments_wizard_carbs_input.value = 0.0
ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.carbsconstraintapplied))
return
}
bg = if (treatments_wizard_bgcheckbox.isChecked) bg else 0.0
val tempTarget = if (treatments_wizard_ttcheckbox.isChecked) TreatmentsPlugin.getPlugin().tempTargetFromHistory else null
// COB
var cob = 0.0
if (treatments_wizard_cobcheckbox.isChecked) {
val cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "Wizard COB")
cobInfo.displayCob?.let { cob = it }
}
val carbTime = SafeParse.stringToInt(treatments_wizard_carb_time_input.text)
wizard = BolusWizard(specificProfile, profileName, tempTarget, carbsAfterConstraint, cob, bg, correction,
SP.getInt(R.string.key_boluswizard_percentage, 100).toDouble(),
treatments_wizard_bgcheckbox.isChecked,
treatments_wizard_cobcheckbox.isChecked,
treatments_wizard_bolusiobcheckbox.isChecked,
treatments_wizard_basaliobcheckbox.isChecked,
treatments_wizard_sbcheckbox.isChecked,
treatments_wizard_ttcheckbox.isChecked,
treatments_wizard_bgtrendcheckbox.isChecked,
treatment_wizard_notes.text.toString(), carbTime)
wizard?.let { wizard ->
treatments_wizard_bg.text = String.format(MainApp.gs(R.string.format_bg_isf), BgReading().value(Profile.toMgdl(bg, ProfileFunctions.getSystemUnits())).valueToUnitsToString(ProfileFunctions.getSystemUnits()), wizard.sens)
treatments_wizard_bginsulin.text = StringUtils.formatInsulin(wizard.insulinFromBG)
treatments_wizard_carbs.text = String.format(MainApp.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic)
treatments_wizard_carbsinsulin.text = StringUtils.formatInsulin(wizard.insulinFromCarbs)
treatments_wizard_bolusiobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromBolusIOB)
treatments_wizard_basaliobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromBasalsIOB)
treatments_wizard_correctioninsulin.text = StringUtils.formatInsulin(wizard.insulinFromCorrection)
// Superbolus
treatments_wizard_sb.text = if (treatments_wizard_sbcheckbox.isChecked) MainApp.gs(R.string.twohours) else ""
treatments_wizard_sbinsulin.text = StringUtils.formatInsulin(wizard.insulinFromSuperBolus)
// Trend
if (treatments_wizard_bgtrendcheckbox.isChecked && wizard.glucoseStatus != null) {
treatments_wizard_bgtrend.text = ((if (wizard.trend > 0) "+" else "")
+ Profile.toUnitsString(wizard.trend * 3, wizard.trend * 3 / Constants.MMOLL_TO_MGDL, ProfileFunctions.getSystemUnits())
+ " " + ProfileFunctions.getSystemUnits())
} else {
treatments_wizard_bgtrend.text = ""
}
treatments_wizard_bgtrendinsulin.text = StringUtils.formatInsulin(wizard.insulinFromTrend)
// COB
if (treatments_wizard_cobcheckbox.isChecked) {
treatments_wizard_cob.text = String.format(MainApp.gs(R.string.format_cob_ic), cob, wizard.ic)
treatments_wizard_cobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromCOB)
} else {
treatments_wizard_cob.text = ""
treatments_wizard_cobinsulin.text = ""
}
if (wizard.calculatedTotalInsulin > 0.0 || carbsAfterConstraint > 0.0) {
val insulinText = if (wizard.calculatedTotalInsulin > 0.0) MainApp.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else ""
val carbsText = if (carbsAfterConstraint > 0.0) MainApp.gs(R.string.format_carbs, carbsAfterConstraint) else ""
treatments_wizard_total.text = MainApp.gs(R.string.result_insulin_carbs, insulinText, carbsText)
ok.visibility = View.VISIBLE
} else {
treatments_wizard_total.text = MainApp.gs(R.string.missing_carbs, wizard.carbsEquivalent.toInt())
ok.visibility = View.INVISIBLE
}
}
}
}
| agpl-3.0 | 2d6a5aba55c03dc168df52d328a73fb6 | 48.726471 | 232 | 0.695511 | 4.640955 | false | false | false | false |
Cognifide/APM | app/aem/core/src/main/kotlin/com/cognifide/apm/core/grammar/common/Functions.kt | 1 | 1258 | /*
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* 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.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.grammar.common
import com.cognifide.apm.core.grammar.ScriptExecutionException
fun getIdentifier(ctx: com.cognifide.apm.core.grammar.antlr.ApmLangParser.IdentifierContext) = when {
ctx.IDENTIFIER() != null -> ctx.IDENTIFIER().toString()
ctx.EXTENDED_IDENTIFIER() != null -> ctx.EXTENDED_IDENTIFIER().toString()
else -> throw ScriptExecutionException("Cannot resolve identifier")
} | apache-2.0 | fba2a08a2df9baab94dd9a23a18eb077 | 41.448276 | 101 | 0.658983 | 4.625 | false | false | false | false |
andrewoma/kwery | example/src/main/kotlin/com/github/andrewoma/kwery/example/film/resources/Resource.kt | 1 | 1844 | /*
* Copyright (c) 2015 Andrew O'Malley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.andrewoma.kwery.example.film.resources
import com.github.andrewoma.kwery.fetcher.GraphFetcher
import com.github.andrewoma.kwery.fetcher.Node
import com.github.andrewoma.kwery.mapper.Column
interface Resource {
val fetcher: GraphFetcher
fun <T> parameters(vararg parameters: Pair<Column<T, *>, Any?>): Map<Column<T, *>, Any?> {
return parameters.toList().toMap().filter { it.value != null }
}
fun <T> List<T>.fetch(root: String?): List<T> {
if (root == null) return this
return fetcher.fetch(this, Node.parse(root))
}
fun <T> T.fetch(root: String?): T {
if (root == null) return this
return fetcher.fetch(this, Node.parse(root))
}
} | mit | b9c48c6b02708738d4bfe6fa4bc82db9 | 40 | 94 | 0.722343 | 4.14382 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/universal/ScopedFacebookModule.kt | 2 | 1821 | package abi43_0_0.host.exp.exponent.modules.universal
import android.content.Context
import com.facebook.FacebookSdk
import abi43_0_0.expo.modules.core.Promise
import abi43_0_0.expo.modules.core.arguments.ReadableArguments
import abi43_0_0.expo.modules.core.interfaces.LifecycleEventListener
import abi43_0_0.expo.modules.facebook.FacebookModule
private const val ERR_FACEBOOK_UNINITIALIZED = "ERR_FACEBOOK_UNINITIALIZED"
class ScopedFacebookModule(context: Context) : FacebookModule(context), LifecycleEventListener {
private var isInitialized = false
override fun onHostResume() {
if (mAppId != null) {
FacebookSdk.setApplicationId(mAppId)
}
if (mAppName != null) {
FacebookSdk.setApplicationName(mAppName)
}
}
override fun initializeAsync(options: ReadableArguments, promise: Promise) {
isInitialized = true
super.initializeAsync(options, promise)
}
override fun logInWithReadPermissionsAsync(config: ReadableArguments, promise: Promise) {
if (!isInitialized) {
promise.reject(ERR_FACEBOOK_UNINITIALIZED, "Facebook SDK has not been initialized yet.")
}
super.logInWithReadPermissionsAsync(config, promise)
}
override fun getAuthenticationCredentialAsync(promise: Promise) {
if (!isInitialized) {
promise.reject(ERR_FACEBOOK_UNINITIALIZED, "Facebook SDK has not been initialized yet.")
}
super.getAuthenticationCredentialAsync(promise)
}
override fun logOutAsync(promise: Promise) {
if (!isInitialized) {
promise.reject(ERR_FACEBOOK_UNINITIALIZED, "Facebook SDK has not been initialized yet.")
}
super.logOutAsync(promise)
}
override fun onHostPause() {
FacebookSdk.setApplicationId(null)
FacebookSdk.setApplicationName(null)
}
override fun onHostDestroy() {
// do nothing
}
}
| bsd-3-clause | b057542c86ca406989ec3d3e0ada89d4 | 30.396552 | 96 | 0.750137 | 4.186207 | false | false | false | false |
auth0/Auth0.Android | auth0/src/main/java/com/auth0/android/Auth0Exception.kt | 1 | 592 | package com.auth0.android
/**
* Base Exception for any error found during a request to Auth0's API
*/
public open class Auth0Exception(message: String, cause: Throwable? = null) :
RuntimeException(message, cause) {
public companion object {
public const val UNKNOWN_ERROR: String = "a0.sdk.internal_error.unknown"
public const val NON_JSON_ERROR: String = "a0.sdk.internal_error.plain"
public const val EMPTY_BODY_ERROR: String = "a0.sdk.internal_error.empty"
public const val EMPTY_RESPONSE_BODY_DESCRIPTION: String = "Empty response body"
}
} | mit | 5cf4672e67655a420313d7d4224557b5 | 38.533333 | 88 | 0.70777 | 3.844156 | false | false | false | false |
cyclestreets/android | libraries/cyclestreets-view/src/main/java/net/cyclestreets/iconics/IconicsHelper.kt | 1 | 2776 | package net.cyclestreets.iconics
import android.content.Context
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.IIcon
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import com.mikepenz.iconics.utils.colorInt
import com.mikepenz.iconics.utils.sizeDp
import net.cyclestreets.util.Logging
private val TAG = Logging.getTag(IconicsHelper::class.java)
object IconicsHelper {
fun materialIcon(context: Context, iconId: IIcon, color: Int? = null, size: Int = 24): IconicsDrawable {
return materialIcons(context, listOf(iconId), color, size).first()
}
fun materialIcons(context: Context, iconIds: List<IIcon>, color: Int? = null, size: Int = 24): List<IconicsDrawable> {
return iconIds.map {
iconId -> IconicsDrawable(context, iconId)
.apply {
sizeDp = size
color?.let { this.colorInt = color}
}
}
}
// Derive Context from the inflater, and then delegate to the Iconics inflater.
fun inflate(inflater: MenuInflater, menuId: Int, menu: Menu) {
inflate(inflater, menuId, menu, true)
}
// Derive Context from the inflater, and then delegate to the Iconics inflater.
fun inflate(inflater: MenuInflater, menuId: Int, menu: Menu, checkSubMenus: Boolean) {
val context = getContext(inflater)
if (context != null) {
IconicsMenuInflaterUtil.inflate(inflater, context, menuId, menu, checkSubMenus)
} else {
// In the worst case (e.g. on Google implementation change), we fall back to the default
// inflater; we'll lose the icons but won't fall over.
inflater.inflate(menuId, menu)
}
}
// Derive the Context from a MenuInflater (using reflection).
//
// In some fragment transitions, menu inflation is performed before the fragment's context
// is initialised, so we can't just do a `getContext()`; the internal `mContext` field is used
// in this scope by the native inflater.inflate(), so we should be safe.
private fun getContext(inflater: MenuInflater): Context? {
return try {
val f = inflater.javaClass.getDeclaredField("mContext")
f.isAccessible = true
f.get(inflater) as Context
} catch (e: IllegalAccessException) {
Log.w(TAG, "IllegalAccessException: Failed to find mContext on ${inflater.javaClass.canonicalName}")
null
} catch (e: NoSuchFieldException) {
Log.w(TAG, "NoSuchFieldException: Failed to find mContext on ${inflater.javaClass.canonicalName}")
null
}
}
}
| gpl-3.0 | c7c22374f95e2bf1099aa16cc6a56ab2 | 38.098592 | 122 | 0.664625 | 4.55082 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/storage/ReferenceModeStore.kt | 1 | 33421 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage
import arcs.core.analytics.Analytics
import arcs.core.common.Referencable
import arcs.core.common.ReferenceId
import arcs.core.crdt.CrdtData
import arcs.core.crdt.CrdtEntity
import arcs.core.crdt.CrdtException
import arcs.core.crdt.CrdtModel
import arcs.core.crdt.CrdtModelType
import arcs.core.crdt.CrdtOperation
import arcs.core.crdt.CrdtSet
import arcs.core.crdt.CrdtSingleton
import arcs.core.crdt.VersionMap
import arcs.core.data.CollectionType
import arcs.core.data.FieldName
import arcs.core.data.RawEntity
import arcs.core.data.ReferenceType
import arcs.core.data.SingletonType
import arcs.core.data.util.ReferencableList
import arcs.core.storage.referencemode.RefModeStoreData
import arcs.core.storage.referencemode.RefModeStoreOp
import arcs.core.storage.referencemode.RefModeStoreOutput
import arcs.core.storage.referencemode.ReferenceModeStorageKey
import arcs.core.storage.referencemode.sanitizeForRefModeStore
import arcs.core.storage.referencemode.toBridgingData
import arcs.core.storage.referencemode.toBridgingOp
import arcs.core.storage.referencemode.toBridgingOps
import arcs.core.storage.util.HoldQueue
import arcs.core.storage.util.OperationQueue
import arcs.core.storage.util.SimpleQueue
import arcs.core.storage.util.callbackManager
import arcs.core.type.Type
import arcs.core.util.Random
import arcs.core.util.Result
import arcs.core.util.TaggedLog
import arcs.core.util.Time
import arcs.core.util.computeNotNull
import arcs.core.util.nextVersionMapSafeString
import kotlin.properties.Delegates
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
/** This is a convenience for the parameter type of [handleContainerMessage]. */
internal typealias ContainerProxyMessage = ProxyMessage<CrdtData, CrdtOperation, Referencable>
/** This is a convenience for the parameter type of [handleBackingStoreMessage]. */
internal typealias BackingStoreProxyMessage =
ProxyMessage<CrdtEntity.Data, CrdtEntity.Operation, CrdtEntity>
/** This is a convenience for the parameter type of [handleProxyMessage]. */
internal typealias RefModeProxyMessage =
ProxyMessage<RefModeStoreData, RefModeStoreOp, RefModeStoreOutput>
/**
* [ReferenceModeStore]s adapt between a collection ([CrdtSet] or [CrdtSingleton]) of entities from
* the perspective of their public API, and a collection of references + a backing store of entity
* CRDTs from an internal storage perspective.
*
* [ReferenceModeStore]s maintain a queue of incoming updates (the receiveQueue) and process them
* one at a time. When possible, the results of this processing are immediately sent upwards (to
* connected StorageProxies) and downwards (to storage). However, there are a few caveats:
* * incoming operations and models from StorageProxies may require several writes to storage - one
* for each modified entity, and one to the container store. These are processed serially, so that
* a container doesn't get updated if backing store modifications fail.
* * updates from the container store need to be blocked on ensuring the required data is also
* available in the backing store. The holdQueue ensures that these blocks are tracked and
* processed appropriately.
* * updates should always be sent in order, so a blocked send should block subsequent sends too.
* The pendingSends queue ensures that all outgoing updates are sent in the correct order.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class ReferenceModeStore private constructor(
options: StoreOptions,
/* internal */
val containerStore: DirectStore<CrdtData, CrdtOperation, Any?>,
/* internal */
val backingStore: DirectStoreMuxer<CrdtEntity.Data, CrdtEntity.Operation, CrdtEntity>,
private val scope: CoroutineScope,
private val devTools: DevToolsForRefModeStore?,
private val time: Time,
private val analytics: Analytics
) : ActiveStore<RefModeStoreData, RefModeStoreOp, RefModeStoreOutput>(options) {
// TODO(#5551): Consider including a hash of the storage key in log prefix.
private val log = TaggedLog { "ReferenceModeStore" }
/**
* A queue of incoming updates from the backing store, container store, and connected proxies.
*/
private val receiveQueue: OperationQueue = SimpleQueue(
onEmpty = {
if (callbacks.hasBecomeEmpty()) {
backingStore.clearStoresCache()
}
}
)
/**
* Registered callbacks to Storage Proxies.
*/
private val callbacks =
callbackManager<ProxyMessage<RefModeStoreData, RefModeStoreOp, RefModeStoreOutput>>(
"reference",
Random
)
/**
* A queue of functions that will trigger callback executions.
*/
private val sendQueue: OperationQueue = SimpleQueue()
/**
* References that need to be resolved and the completion jobs to trigger once they are.
*
* Actions will be dispatched on the [sendQueue] provided here at construction.
*/
private val holdQueue = HoldQueue(sendQueue)
/**
* [Type] of data managed by the [backingStore] and tracked in the [containerStore].
*/
private val crdtType: CrdtModelType<CrdtData, CrdtOperation, Referencable>
/**
* A randomly generated key that is used for synthesized entity CRDT modifications.
*
* When entity updates are received by instances of [ReferenceModeStore], they're non-CRDT blobs
* of data. The [ReferenceModeStore] needs to convert them to tracked CRDTs, which means it
* needs to synthesize updates. This key is used as the unique write key and
* [arcs.core.crdt.internal.Actor] for those updates.
*/
/* internal */ val crdtKey = Random.nextVersionMapSafeString(10)
/**
* The [versions] map transitively tracks the maximum write version for each contained entity's
* fields, to ensure synthesized updates can be correctly applied downstream.
*
* All access to this map should be synchronized.
*/
private var versions = mutableMapOf<ReferenceId, MutableMap<FieldName, Int>>()
/**
* Callback Id of the callback that the [ReferenceModeStore] registered with the backing store.
*
* This is visible only for tests. Do not use outside of [ReferenceModeStore] other than for
* tests.
*/
var backingStoreId by Delegates.notNull<Int>()
/**
* Callback Id of the callback that the [ReferenceModeStore] registered with the container store.
*
* This is visible only for tests. Do not use outside of [ReferenceModeStore] other than for
* tests.
*/
var containerStoreId by Delegates.notNull<Int>()
/** VisibleForTesting */
val holdQueueEmpty get() = holdQueue.queue.size == 0
init {
@Suppress("UNCHECKED_CAST")
crdtType = requireNotNull(
type as? Type.TypeContainer<CrdtModelType<CrdtData, CrdtOperation, Referencable>>
) { "Provided type must contain CrdtModelType" }.containedType
}
override suspend fun idle() {
backingStore.idle()
containerStore.idle()
receiveQueue.idle()
}
override suspend fun on(
callback: ProxyCallback<RefModeStoreData, RefModeStoreOp, RefModeStoreOutput>
): CallbackToken = callbacks.register(callback::invoke)
override suspend fun off(callbackToken: CallbackToken) {
callbacks.unregister(callbackToken)
// Enqueue something, in case the queue was already empty, since queue transitioning
// to empty is what triggers potential cleanup.
receiveQueue.enqueue { }
}
override fun close() {
scope.launch {
receiveQueue.enqueue {
containerStore.close()
backingStore.clearStoresCache()
}
}
}
/*
* Messages are enqueued onto an object-wide queue and processed in order.
* Internally, each handler (handleContainerStore, handleBackingStore, handleProxyMessage)
* should not return until the response relevant to the message has been received.
*
* When handling proxy messages, this implies 2 rounds of update - first the backing
* store needs to be updated, and once that has completed then the container store needs
* to be updated.
*/
@Suppress("UNCHECKED_CAST")
override suspend fun onProxyMessage(
message: ProxyMessage<RefModeStoreData, RefModeStoreOp, RefModeStoreOutput>
) {
log.verbose { "onProxyMessage: $message" }
val refModeMessage = message.sanitizeForRefModeStore(type)
devTools?.onRefModeStoreProxyMessage(message as UntypedProxyMessage)
receiveQueue.enqueueAndWait {
handleProxyMessage(refModeMessage)
}
}
/**
* Handle an update from an upstream StorageProxy.
*
* Model and Operation updates apply first to the backing store, then to the container store.
* Backing store updates should never fail as updates are locally generated.
*
* For Operations:
* * If the container store update succeeds, then the update is mirrored to non-sending
* StorageProxies.
* * If the container store update fails, then a `false` return value ensures that the upstream
* proxy will request a sync.
*
* Model updates should not fail.
*
* Sync requests are handled by directly constructing and sending a model.
*/
@Suppress("UNCHECKED_CAST")
private suspend fun handleProxyMessage(proxyMessage: RefModeProxyMessage) {
log.verbose { "handleProxyMessage: $proxyMessage" }
suspend fun itemVersionGetter(item: RawEntity): VersionMap {
val localBackingVersion = getLocalData(item.id).versionMap
check(localBackingVersion.isNotEmpty()) { "Local backing version map is empty." }
return localBackingVersion
}
when (proxyMessage) {
is ProxyMessage.Operations -> {
val containerOps = mutableListOf<CrdtOperation>()
val upstreamOps = mutableListOf<RefModeStoreOp>()
// Update the backing store
proxyMessage.operations.forEach { op ->
handleOpForBackingStore(op)
}
// Create bridging operations.
val ops = proxyMessage.operations.toBridgingOps(
backingStore.storageKey,
::itemVersionGetter
)
ops.forEach { op ->
// Update container store and other clients.
containerOps.add(op.containerOp)
upstreamOps.add(op.refModeOp)
}
containerStore.onProxyMessage(
ProxyMessage.Operations(containerOps, containerStoreId)
)
sendQueue.enqueue {
callbacks.allCallbacksExcept(proxyMessage.id).forEach { callback ->
callback(
ProxyMessage.Operations(upstreamOps, id = proxyMessage.id)
)
}
}
}
is ProxyMessage.ModelUpdate -> {
// Update the backing store
handleModelForBackingStore(proxyMessage.model)
// Create bridging data.
val newModelsResult = proxyMessage.model.toBridgingData(
backingStore.storageKey,
::itemVersionGetter
)
when (newModelsResult) {
is Result.Ok -> {
// Update container store and other clients.
containerStore.onProxyMessage(
ProxyMessage.ModelUpdate(
newModelsResult.value.collectionModel.data,
id = containerStoreId
)
)
sendQueue.enqueue {
callbacks.allCallbacksExcept(proxyMessage.id).forEach { callback ->
callback(proxyMessage)
}
}
}
else -> return
}
}
is ProxyMessage.SyncRequest -> {
val (pendingIds, model) =
constructPendingIdsAndModel(containerStore.getLocalData())
suspend fun sender() {
callbacks.getCallback(requireNotNull(proxyMessage.id))
?.invoke(
ProxyMessage.ModelUpdate(model() as RefModeStoreData, proxyMessage.id)
)
}
if (pendingIds.isEmpty()) {
sendQueue.enqueue(::sender)
} else {
addToHoldQueueFromReferences(
pendingIds,
onTimeout = { handlePendingReferenceTimeout(proxyMessage) }
) {
sender()
}
}
}
}
}
private suspend fun handlePendingReferenceTimeout(proxyMessage: RefModeProxyMessage) {
analytics.logPendingReferenceTimeout()
// If the queued+blocked send item times out (likely due to missing data in
// the backing-store), assume that the backing store is corrupted and
// clear-out the collection store before re-attempting the sync.
val ops = buildClearContainerStoreOps()
log.info {
"SyncRequest timed out after $BLOCKING_QUEUE_TIMEOUT_MILLIS " +
"milliseconds, backing store is likely corrupted - sending " +
"clear operations to container store."
}
log.verbose { "Clear ops = $ops" }
containerStore.onProxyMessage(ProxyMessage.Operations(ops, containerStoreId))
onProxyMessage(proxyMessage)
}
/**
* Handles an update from the [backingStore].
*
* Model and Operation updates are routed directly to the [sendQueue], where they may unblock
* pending sends but will not have any other action.
*
* Syncs should never occur as operation/model updates to the backing store are generated
* by this [ReferenceModeStore] object and hence should never be out-of-order.
*/
private suspend fun handleBackingStoreMessage(
proxyMessage: BackingStoreProxyMessage,
muxId: String
): Boolean {
when (proxyMessage) {
is ProxyMessage.ModelUpdate ->
holdQueue.processReferenceId(muxId, proxyMessage.model.versionMap)
// TODO(b/161912425) Verify the versionMap checking logic here.
is ProxyMessage.Operations -> if (proxyMessage.operations.isNotEmpty()) {
holdQueue.processReferenceId(muxId, proxyMessage.operations.last().versionMap)
}
is ProxyMessage.SyncRequest ->
throw IllegalArgumentException("Unexpected SyncRequest from the backing store")
}
return true
}
/**
* Handles an update from the [containerStore].
*
* Operations and Models either enqueue an immediate send (if all referenced entities are
* available in the backing store) or enqueue a blocked send (if some referenced entities are
* not yet present or are at the incorrect version).
*
* Sync requests are propagated upwards to the storage proxy.
*/
private suspend fun handleContainerMessage(proxyMessage: ContainerProxyMessage): Boolean {
when (proxyMessage) {
is ProxyMessage.Operations -> {
val containerOps = proxyMessage.operations
opLoop@ for (op in containerOps) {
val reference = when (op) {
is CrdtSet.Operation.Add<*> -> op.added as RawReference
is CrdtSingleton.Operation.Update<*> -> op.value as RawReference
else -> null
}
val getEntity = if (reference != null) {
val entityCrdt = getLocalData(reference.id) as? CrdtEntity.Data
if (entityCrdt == null) {
addToHoldQueueFromReferences(
listOf(reference),
onTimeout = {}
) {
val updated =
getLocalData(reference.id) as? CrdtEntity.Data
// Bridge the op from the collection using the RawEntity from the
// backing store, and use the refModeOp for sending back to the
// proxy.
val upstreamOps = listOf(
op.toBridgingOp(updated?.toRawEntity(reference.id)).refModeOp
)
callbacks.allCallbacksExcept(proxyMessage.id).forEach { callback ->
callback(
ProxyMessage.Operations(
operations = upstreamOps,
id = proxyMessage.id
)
)
}
}
continue@opLoop
}
suspend { entityCrdt.toRawEntity(reference.id) }
} else {
suspend { null }
}
sendQueue.enqueue {
val upstream = listOf(op.toBridgingOp(getEntity()).refModeOp)
callbacks.allCallbacksExcept(proxyMessage.id).forEach { callback ->
callback(
ProxyMessage.Operations(upstream, id = proxyMessage.id)
)
}
}
}
}
is ProxyMessage.ModelUpdate -> {
val data = proxyMessage.model
val (pendingIds, model) = constructPendingIdsAndModel(data)
suspend fun sender() {
// TODO? Typescript doesn't pass an id.
callbacks.callbacks.forEach { callback ->
callback(ProxyMessage.ModelUpdate(model() as RefModeStoreData, id = proxyMessage.id))
}
}
if (pendingIds.isEmpty()) {
sendQueue.enqueue(::sender)
} else {
addToHoldQueueFromReferences(
pendingIds,
onTimeout = {},
::sender
)
}
}
is ProxyMessage.SyncRequest -> sendQueue.enqueue {
// TODO? Typescript doesn't pass an id.
callbacks.callbacks.forEach { callback ->
callback(ProxyMessage.SyncRequest(id = proxyMessage.id))
}
}
}
removeUnusedEntityVersions(proxyMessage)
return true
}
/* Removes entries from the entities versions, if they were removed from the container store. */
private fun removeUnusedEntityVersions(proxyMessage: ContainerProxyMessage) =
synchronized(versions) {
when (proxyMessage) {
is ProxyMessage.Operations ->
proxyMessage.operations.forEach { op ->
when (op) {
is CrdtSet.Operation.Remove<*> -> versions.remove(op.removed)
is CrdtSet.Operation.Clear<*> -> versions.clear()
is CrdtSet.Operation.FastForward<*> ->
versions.keys.removeAll(op.removed.map { it.id })
}
}
is ProxyMessage.ModelUpdate -> {
if (proxyMessage.model is CrdtSet.Data<*>) {
val keys =
(proxyMessage.model as CrdtSet.Data<*>).values.keys.filter { versions.contains(it) }
versions = keys.associateWithTo(mutableMapOf()) { versions[it]!! }
}
}
is ProxyMessage.SyncRequest -> return
}
}
private fun newBackingInstance(): CrdtModel<CrdtData, CrdtOperation, Referencable> =
crdtType.createCrdtModel()
/**
* Gets data from the Backing Store with the corresponding [referenceId]
*
* This is visible for tests. Do not otherwise use outside of [ReferenceModeStore]
*/
suspend fun getLocalData(referenceId: String) =
backingStore.getLocalData(referenceId, backingStoreId)
/** Write the provided entity to the backing store. */
private suspend fun updateBackingStore(referencable: RawEntity) {
val model = entityToModel(referencable)
backingStore.onProxyMessage(
MuxedProxyMessage(referencable.id, ProxyMessage.ModelUpdate(model, id = backingStoreId))
)
}
private suspend fun handleOpForBackingStore(op: RefModeStoreOp) {
when (op) {
is RefModeStoreOp.SingletonUpdate -> {
backingStore.clearStoresCache()
updateBackingStore(op.value)
}
is RefModeStoreOp.SingletonClear -> {
backingStore.clearStoresCache()
}
is RefModeStoreOp.SetAdd -> {
updateBackingStore(op.added)
}
is RefModeStoreOp.SetRemove -> {
clearEntityInBackingStore(op.removed)
}
is RefModeStoreOp.SetClear -> {
clearAllEntitiesInBackingStore()
}
}
}
private suspend fun handleModelForBackingStore(model: RefModeStoreData) {
model.values.values.map { updateBackingStore(it.value) }
}
/** Clear the provided entity in the backing store. */
private suspend fun clearEntityInBackingStore(referencableId: ReferenceId) {
val op = listOf(CrdtEntity.Operation.ClearAll(crdtKey, entityVersionMap(referencableId)))
backingStore.onProxyMessage(
MuxedProxyMessage<CrdtEntity.Data, CrdtEntity.Operation, CrdtEntity>(
referencableId,
ProxyMessage.Operations(op, id = backingStoreId)
)
)
}
/** Clear all entities from the backing store, using the container store to retrieve the ids. */
private suspend fun clearAllEntitiesInBackingStore() {
val containerModel = containerStore.getLocalData()
if (containerModel !is CrdtSet.Data<*>) {
throw UnsupportedOperationException()
}
containerModel.values.forEach { (refId, data) ->
val clearOp = listOf(CrdtEntity.Operation.ClearAll(crdtKey, data.versionMap))
backingStore.onProxyMessage(
MuxedProxyMessage<CrdtEntity.Data, CrdtEntity.Operation, CrdtEntity>(
refId,
ProxyMessage.Operations(clearOp, id = backingStoreId)
)
)
}
}
/**
* Returns a function that can construct a [RefModeStoreData] object of a Container of Entities
* based off the provided Container of References or a container of references from a provided
* [RefModeStoreData].
*
* Any referenced IDs that are not yet available in the backing store are returned in the list
* of pending [RawReference]s. The returned function should not be invoked until all references in
* pendingIds have valid backing in the backing store.
*
* [RawEntity] objects come from the storage proxy, and [RawReference] objects come from the
* [containerStore].
*/
@Suppress("UNCHECKED_CAST")
private suspend fun constructPendingIdsAndModel(
data: CrdtData
): Pair<List<RawReference>, suspend () -> CrdtData> {
val pendingIds = mutableListOf<RawReference>()
// We can use one mechanism to calculate pending values because both CrdtSet.Data and
// CrdtSingleton.Data's `values` param are maps of ReferenceIds to CrdtSet.DataValue
// objects.
suspend fun calculatePendingIds(
dataValues: Map<ReferenceId, CrdtSet.DataValue<out Referencable>>
) {
// Find any pending ids given the reference ids of the data values.
dataValues.forEach { (refId, dataValue) ->
val version = (dataValue.value as? RawReference)?.version ?: dataValue.versionMap
// This object is requested at an empty version, which means that it's new and
// can be directly constructed rather than waiting for an update.
if (version.isEmpty()) return@forEach
val backingModel = getLocalData(refId)
// if the backing store version is not newer than the version that was requested, consider
// it pending.
if (backingModel.versionMap doesNotDominate version) {
pendingIds += RawReference(refId, backingStore.storageKey, version)
}
}
}
// Loads a CrdtSingleton/CrdtSet.Data object's values map with RawEntities, when that object
// is intended to be sent to the storage proxy.
suspend fun proxyFromCollection(
incoming: Map<ReferenceId, CrdtSet.DataValue<out Referencable>>
): MutableMap<ReferenceId, CrdtSet.DataValue<RawEntity>> {
val outgoing = mutableMapOf<ReferenceId, CrdtSet.DataValue<RawEntity>>()
incoming.forEach { (refId, value) ->
val version = value.versionMap
val entity = if (version.isEmpty()) {
newBackingInstance().data as CrdtEntity.Data
} else {
getLocalData(refId)
}
outgoing[refId] = CrdtSet.DataValue(version.copy(), entity.toRawEntity(refId))
}
return outgoing
}
// Loads a CrdtSingleton/CrdtSet.Data object's values map with References, when that object
// is intended to be sent to the collectionStore.
fun collectionFromProxy(
incoming: Map<ReferenceId, CrdtSet.DataValue<out Referencable>>
): MutableMap<ReferenceId, CrdtSet.DataValue<RawReference>> {
val outgoing = mutableMapOf<ReferenceId, CrdtSet.DataValue<RawReference>>()
incoming.forEach { (refId, value) ->
val version = value.versionMap
outgoing[refId] = CrdtSet.DataValue(
version.copy(),
RawReference(refId, backingStore.storageKey, version.copy())
)
}
return outgoing
}
// Incoming `data` is either CrdtSet.Data or CrdtSingleton.Data
val dataVersionCopy = data.versionMap.copy()
val modelGetter = when (data) {
is CrdtSingleton.Data<*> -> {
calculatePendingIds(data.values)
val containerData = data as? CrdtSingleton.Data<RawReference>
val proxyData = data as? CrdtSingleton.Data<RawEntity>
when {
// If its type is `Reference` it must be coming from the container, so generate
// a function which returns a RawEntity-based Data that can be sent to the
// storage proxy.
containerData != null -> {
val valuesCopy = HashMap(data.values)
suspend {
RefModeStoreData.Singleton(
dataVersionCopy, proxyFromCollection(valuesCopy)
)
}
}
// If its type is `RawEntity`, it must be coming from the proxy, so generate a
// Reference-based data that can be sent to the container store.
proxyData != null -> {
val valuesCopy = HashMap(data.values)
suspend {
CrdtSingleton.DataImpl(dataVersionCopy, collectionFromProxy(valuesCopy))
}
}
else -> throw CrdtException("Invalid data type for constructPendingIdsAndModel")
}
}
is CrdtSet.Data<*> -> {
calculatePendingIds(data.values)
val containerData = data as? CrdtSet.Data<RawReference>
val proxyData = data as? CrdtSet.Data<RawEntity>
when {
// If its type is `Reference` it must be coming from the container, so generate
// a function which returns a RawEntity-based Data that can be sent to the
// storage proxy.
containerData != null -> {
val valuesCopy = HashMap(data.values)
suspend {
RefModeStoreData.Set(
dataVersionCopy, proxyFromCollection(valuesCopy)
)
}
}
// If its type is `RawEntity`, it must be coming from the proxy, so generate a
// Reference-based data that can be sent to the container store.
proxyData != null -> {
val valuesCopy = HashMap(data.values)
suspend {
CrdtSet.DataImpl(dataVersionCopy, collectionFromProxy(valuesCopy))
}
}
else -> throw CrdtException("Invalid data type for constructPendingIdsAndModel")
}
}
else -> throw CrdtException("Invalid data type for constructPendingIdsAndModel")
}
return pendingIds to modelGetter
}
private fun entityVersionMap(entityId: ReferenceId): VersionMap {
val version = versions[entityId]?.values?.maxOrNull()
return version?.let { VersionMap(crdtKey to it) } ?: VersionMap()
}
/**
* Convert the provided entity to a CRDT Model of the entity. This requires synthesizing
* a version map for the CRDT model, which is also provided as an output.
*/
private fun entityToModel(entity: RawEntity): CrdtEntity.Data = synchronized(versions) {
val entityVersions = versions.getOrPut(entity.id) { mutableMapOf() }
var maxVersion = 0
val fieldVersionProvider = { fieldName: FieldName ->
VersionMap(crdtKey to requireNotNull(entityVersions[fieldName]))
}
entity.singletons.forEach { (fieldName, _) ->
val fieldVersion =
entityVersions.computeNotNull(fieldName) { _, version -> (version ?: 0) + 1 }
maxVersion = maxOf(maxVersion, fieldVersion)
}
entity.collections.forEach { (fieldName, _) ->
val fieldVersion =
entityVersions.computeNotNull(fieldName) { _, version -> (version ?: 0) + 1 }
maxVersion = maxOf(maxVersion, fieldVersion)
}
return CrdtEntity.Data(
entity,
VersionMap(crdtKey to maxVersion),
fieldVersionProvider
) {
when (it) {
is RawReference -> it
is RawEntity -> CrdtEntity.Reference.wrapReferencable(it)
is ReferencableList<*> -> CrdtEntity.Reference.wrapReferencable(it)
else -> CrdtEntity.Reference.buildReference(it)
}
}
}
private fun buildClearContainerStoreOps(): List<CrdtOperation> {
val containerModel = containerStore.getLocalData()
val actor = "ReferenceModeStore(${hashCode()})"
val containerVersion = containerModel.versionMap.copy()
return listOf(
when (containerModel) {
is CrdtSet.Data<*> ->
CrdtSet.Operation.Clear<RawReference>(actor, containerVersion)
is CrdtSingleton.Data<*> ->
CrdtSingleton.Operation.Clear<RawReference>(actor, containerVersion)
else -> throw UnsupportedOperationException()
}
)
}
private suspend fun addToHoldQueueFromReferences(
refs: Collection<RawReference>,
onTimeout: suspend () -> Unit,
onRelease: suspend () -> Unit
): Int {
// Start a job that delays for the configured timeout amount, and if still active by the
// time the deadline is reached, runs that clears the store to remove potentially stale
// references.
val timeoutJob = scope.launch {
delay(BLOCKING_QUEUE_TIMEOUT_MILLIS)
holdQueue.removePendingIds(refs.map { it.id })
onTimeout()
}
return holdQueue.enqueue(
refs.map {
HoldQueue.Entity(it.id, it.version?.copy())
},
{
try {
onRelease()
} finally {
timeoutJob.cancel()
}
}
)
}
companion object {
/**
* Timeout duration in milliseconds we are allowed to wait for results from the
* [BackingStore] during a [SyncRequest].
*
* If this timeout is exceeded, we will assume the backing store is corrupt and will log a
* warning and clear the container store.
*
* This timeout value is high because we don't want to be too aggressive with clearing the
* container store, while also avoiding a scenario where the [ReferenceModeStore] is hung
* up forever.
*/
/* internal */ var BLOCKING_QUEUE_TIMEOUT_MILLIS = 30000L
@Suppress("UNCHECKED_CAST")
suspend fun create(
options: StoreOptions,
scope: CoroutineScope,
driverFactory: DriverFactory,
writeBackProvider: WriteBackProvider,
devTools: DevToolsForStorage?,
time: Time,
analytics: Analytics
): ReferenceModeStore {
val refableOptions =
requireNotNull(
/* ktlint-disable max-line-length */
options as? StoreOptions
/* ktlint-enable max-line-length */
) { "ReferenceMode stores only manage singletons/collections of Entities." }
val (type, _) = requireNotNull(
options.type as? Type.TypeContainer<*>
) { "Type ${options.type} does not implement TypeContainer" }.let {
/* ktlint-disable max-line-length */
it to requireNotNull(it.containedType as? CrdtModelType<*, *, *>).crdtModelDataClass
/* ktlint-enable max-line-length */
}
val storageKey = requireNotNull(options.storageKey as? ReferenceModeStorageKey) {
"StorageKey ${options.storageKey} is not a ReferenceModeStorageKey"
}
val refType = if (options.type is CollectionType<*>) {
CollectionType(ReferenceType(type.containedType))
} else {
SingletonType(ReferenceType(type.containedType))
}
val containerStore = DirectStore.create<CrdtData, CrdtOperation, Any?>(
StoreOptions(
storageKey = storageKey.storageKey,
type = refType,
versionToken = options.versionToken
),
scope = scope,
driverFactory = driverFactory,
writeBackProvider = writeBackProvider,
devTools = devTools
)
val backingStore = DirectStoreMuxerImpl<CrdtEntity.Data, CrdtEntity.Operation, CrdtEntity>(
storageKey = storageKey.backingKey,
backingType = type.containedType,
scope = scope,
driverFactory = driverFactory,
writeBackProvider = writeBackProvider,
devTools = devTools,
time = time
)
return ReferenceModeStore(
refableOptions,
containerStore,
backingStore,
scope,
devTools?.forRefModeStore(options),
time,
analytics
).also { refModeStore ->
// Since `on` is a suspending method, we need to setup both the container store callback and
// the backing store callback here in this create method, which is inside of a coroutine.
refModeStore.containerStoreId = containerStore.on {
refModeStore.receiveQueue.enqueue {
refModeStore.handleContainerMessage(it as ContainerProxyMessage)
}
}
refModeStore.backingStoreId = refModeStore.backingStore.on {
refModeStore.receiveQueue.enqueue {
refModeStore.handleBackingStoreMessage(it.message, it.muxId)
}
}
}
}
}
}
| bsd-3-clause | 3f030da07de9da916616677331c56194 | 36.50954 | 100 | 0.671584 | 4.783312 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/core/Utils.kt | 4 | 9670 | // 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.idea.core
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.caches.resolve.computeTypeInContext
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.idea.util.getImplicitReceiversWithInstanceToExpression
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.lexer.KtModifierKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DelegatingBindingTrace
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.CallResolver
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.components.isVararg
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.context.CheckArgumentTypesMode
import org.jetbrains.kotlin.resolve.calls.context.ContextDependency
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.results.ResolutionStatus
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.calls.util.getDispatchReceiverWithSmartCast
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import java.util.*
/**
* See `ArgumentsToParametersMapper` class in the compiler.
*/
fun Call.mapArgumentsToParameters(targetDescriptor: CallableDescriptor): Map<ValueArgument, ValueParameterDescriptor> {
val parameters = targetDescriptor.valueParameters
if (parameters.isEmpty()) return emptyMap()
val map = HashMap<ValueArgument, ValueParameterDescriptor>()
val parametersByName = if (targetDescriptor.hasStableParameterNames()) parameters.associateBy { it.name } else emptyMap()
var positionalArgumentIndex: Int? = 0
for (argument in valueArguments) {
if (argument is LambdaArgument) {
map[argument] = parameters.last()
} else {
val argumentName = argument.getArgumentName()?.asName
if (argumentName != null) {
val parameter = parametersByName[argumentName]
if (parameter != null) {
map[argument] = parameter
if (parameter.index == positionalArgumentIndex) {
positionalArgumentIndex++
continue
}
}
positionalArgumentIndex = null
} else {
if (positionalArgumentIndex != null && positionalArgumentIndex < parameters.size) {
val parameter = parameters[positionalArgumentIndex]
map[argument] = parameter
if (!parameter.isVararg) {
positionalArgumentIndex++
}
}
}
}
}
return map
}
fun ImplicitReceiver.asExpression(resolutionScope: LexicalScope, psiFactory: KtPsiFactory): KtExpression? {
val expressionFactory = resolutionScope.getImplicitReceiversWithInstanceToExpression()
.entries
.firstOrNull { it.key.containingDeclaration == this.declarationDescriptor }
?.value ?: return null
return expressionFactory.createExpression(psiFactory)
}
fun KtImportDirective.targetDescriptors(resolutionFacade: ResolutionFacade = this.getResolutionFacade()): Collection<DeclarationDescriptor> {
// For codeFragments imports are created in dummy file
if (this.containingKtFile.doNotAnalyze != null) return emptyList()
val nameExpression = importedReference?.getQualifiedElementSelector() as? KtSimpleNameExpression ?: return emptyList()
return nameExpression.mainReference.resolveToDescriptors(resolutionFacade.analyze(nameExpression))
}
fun Call.resolveCandidates(
bindingContext: BindingContext,
resolutionFacade: ResolutionFacade,
expectedType: KotlinType = expectedType(this, bindingContext),
filterOutWrongReceiver: Boolean = true,
filterOutByVisibility: Boolean = true
): Collection<ResolvedCall<FunctionDescriptor>> {
val resolutionScope = callElement.getResolutionScope(bindingContext, resolutionFacade)
val inDescriptor = resolutionScope.ownerDescriptor
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(callElement)
val bindingTrace = DelegatingBindingTrace(bindingContext, "Temporary trace")
val callResolutionContext = BasicCallResolutionContext.create(
bindingTrace, resolutionScope, this, expectedType, dataFlowInfo,
ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS,
false, resolutionFacade.languageVersionSettings,
resolutionFacade.dataFlowValueFactory
).replaceCollectAllCandidates(true)
@OptIn(FrontendInternals::class)
val callResolver = resolutionFacade.frontendService<CallResolver>()
val results = callResolver.resolveFunctionCall(callResolutionContext)
var candidates = results.allCandidates!!
if (callElement is KtConstructorDelegationCall) { // for "this(...)" delegation call exclude caller from candidates
inDescriptor as ConstructorDescriptor
candidates = candidates.filter { it.resultingDescriptor.original != inDescriptor.original }
}
if (filterOutWrongReceiver) {
candidates = candidates.filter {
it.status != ResolutionStatus.RECEIVER_TYPE_ERROR && it.status != ResolutionStatus.RECEIVER_PRESENCE_ERROR
}
}
if (filterOutByVisibility) {
candidates = candidates.filter {
DescriptorVisibilityUtils.isVisible(
it.getDispatchReceiverWithSmartCast(),
it.resultingDescriptor,
inDescriptor,
resolutionFacade.languageVersionSettings
)
}
}
return candidates
}
private fun expectedType(call: Call, bindingContext: BindingContext): KotlinType {
return (call.callElement as? KtExpression)?.let {
bindingContext[BindingContext.EXPECTED_EXPRESSION_TYPE, it.getQualifiedExpressionForSelectorOrThis()]
} ?: TypeUtils.NO_EXPECTED_TYPE
}
fun KtCallableDeclaration.canOmitDeclaredType(initializerOrBodyExpression: KtExpression, canChangeTypeToSubtype: Boolean): Boolean {
val declaredType = (unsafeResolveToDescriptor() as? CallableDescriptor)?.returnType ?: return false
val bindingContext = initializerOrBodyExpression.analyze()
val scope = initializerOrBodyExpression.getResolutionScope(bindingContext, initializerOrBodyExpression.getResolutionFacade())
val expressionType = initializerOrBodyExpression.computeTypeInContext(scope) ?: return false
if (KotlinTypeChecker.DEFAULT.equalTypes(expressionType, declaredType)) return true
return canChangeTypeToSubtype && expressionType.isSubtypeOf(declaredType)
}
fun FqName.quoteSegmentsIfNeeded(): String {
return quoteIfNeeded().asString()
}
fun isEnumCompanionPropertyWithEntryConflict(element: PsiElement, expectedName: String): Boolean {
if (element !is KtProperty) return false
val propertyClass = element.containingClassOrObject as? KtObjectDeclaration ?: return false
if (!propertyClass.isCompanion()) return false
val outerClass = propertyClass.containingClassOrObject as? KtClass ?: return false
if (!outerClass.isEnum()) return false
return outerClass.declarations.any { it is KtEnumEntry && it.name == expectedName }
}
fun KtCallExpression.receiverValue(): ReceiverValue? {
val resolvedCall = getResolvedCall(safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)) ?: return null
return resolvedCall.dispatchReceiver ?: resolvedCall.extensionReceiver
}
fun KtCallExpression.receiverType(): KotlinType? = receiverValue()?.type
fun KtExpression.resolveType(): KotlinType? = this.analyze(BodyResolveMode.PARTIAL).getType(this)
fun KtModifierKeywordToken.toVisibility(): DescriptorVisibility {
return when (this) {
KtTokens.PUBLIC_KEYWORD -> DescriptorVisibilities.PUBLIC
KtTokens.PRIVATE_KEYWORD -> DescriptorVisibilities.PRIVATE
KtTokens.PROTECTED_KEYWORD -> DescriptorVisibilities.PROTECTED
KtTokens.INTERNAL_KEYWORD -> DescriptorVisibilities.INTERNAL
else -> throw IllegalArgumentException("Unknown visibility modifier:$this")
}
} | apache-2.0 | 1047741113a0a1d8238ec5dffdbb5560 | 45.719807 | 141 | 0.76484 | 5.399218 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/test/java/org/wordpress/android/ui/deeplinks/UriTestHelper.kt | 1 | 967 | package org.wordpress.android.ui.deeplinks
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.wordpress.android.util.UriWrapper
fun buildUri(host: String?, vararg path: String): UriWrapper {
val uri = mock<UriWrapper>()
if (host != null) {
whenever(uri.host).thenReturn(host)
}
if (path.isNotEmpty()) {
whenever(uri.pathSegments).thenReturn(path.toList())
}
return uri
}
fun buildUri(
host: String? = null,
queryParam1: Pair<String, String>? = null,
queryParam2: Pair<String, String>? = null
): UriWrapper {
val uri = mock<UriWrapper>()
if (host != null) {
whenever(uri.host).thenReturn(host)
}
if (queryParam1 != null) {
whenever(uri.getQueryParameter(queryParam1.first)).thenReturn(queryParam1.second)
}
if (queryParam2 != null) {
whenever(uri.getQueryParameter(queryParam2.first)).thenReturn(queryParam2.second)
}
return uri
}
| gpl-2.0 | 2b7120ad12e8e34e18b13788e395acfc | 27.441176 | 89 | 0.66908 | 3.868 | false | false | false | false |
mdaniel/intellij-community | plugins/gradle/java/src/service/resolve/GradleTaskContainerContributor.kt | 3 | 2720 | // 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.plugins.gradle.service.resolve
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.GRADLE_API_TASK_CONTAINER
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createType
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE
import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor
import org.jetbrains.plugins.groovy.lang.resolve.getName
import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessMethods
import org.jetbrains.plugins.groovy.lang.resolve.shouldProcessProperties
class GradleTaskContainerContributor : NonCodeMembersContributor() {
override fun getParentClassName(): String = GRADLE_API_TASK_CONTAINER
override fun processDynamicElements(qualifierType: PsiType,
aClass: PsiClass?,
processor: PsiScopeProcessor,
place: PsiElement,
state: ResolveState) {
if (qualifierType !is GradleProjectAwareType) return
val processProperties = processor.shouldProcessProperties()
val processMethods = processor.shouldProcessMethods()
if (!processProperties && !processMethods) {
return
}
val file = place.containingFile ?: return
val data = GradleExtensionsContributor.getExtensionsFor(file) ?: return
val name = processor.getName(state)
val gradleProjectType = JavaPsiFacade.getInstance(place.project).findClass(GradleCommonClassNames.GRADLE_API_PROJECT, place.resolveScope)
if (name in (gradleProjectType?.methods?.map(PsiMethod::getName) ?: emptyList())) {
return
}
val tasks = if (name == null) data.tasksMap.values else listOf(data.tasksMap[name] ?: return)
if (tasks.isEmpty()) return
val manager = file.manager
val closureType = createType(GROOVY_LANG_CLOSURE, file)
for (task in tasks) {
val taskType = createType(task.typeFqn, file)
if (processProperties) {
val property = GradleTaskProperty(task, file)
if (!processor.execute(property, state)) return
}
if (processMethods) {
val method = GrLightMethodBuilder(manager, task.name).apply {
returnType = taskType
addParameter("configuration", closureType)
}
if (!processor.execute(method, state)) return
}
}
}
}
| apache-2.0 | 451b0fca23e1e19e79183bb7d9cabfcf | 43.590164 | 141 | 0.716176 | 4.780316 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/hsl/HSLTransaction.kt | 1 | 7917 | /*
* HSLTransaction.kt
*
* 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.multi.FormattedString
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.transit.en1545.*
import au.id.micolous.metrodroid.util.ImmutableByteArray
@Parcelize
data class HSLTransaction internal constructor(
override val parsed: En1545Parsed,
private val walttiRegion: Int?,
private val ultralightCity: Int? = null): En1545Transaction() {
private val isArvo: Boolean?
get() = parsed.getInt(IS_ARVO).let {
when (it) {
null -> null
0 -> false
else -> true
}
}
private val expireTimestamp
get() = parsed.getTimeStamp(TRANSFER_END, lookup.timeZone)
override fun getAgencyName(isShort: Boolean): FormattedString? {
if (isArvo != true) {
// isArvo is set to 0 also on Arvo transfers, so 0 doesn't imply anything
return null
}
val end = (this.expireTimestamp as? TimestampFull)?.timeInMillis
val start = (this.timestamp as? TimestampFull)?.timeInMillis
val mins = if (start != null && end != null) Localizer.localizeFormatted(R.string.hsl_mins_format,
((end - start) / 60000L).toString()) else null
val type = Localizer.localizeFormatted(R.string.hsl_balance_ticket)
return (if (mins != null) type + ", " + mins else type)
}
override val lookup: En1545Lookup
get() = HSLLookup
override val station: Station?
get() = HSLLookup.getArea(parsed, AREA_PREFIX, isValidity = false,
walttiRegion=walttiRegion, ultralightCity=ultralightCity)?.let { Station.nameOnly(it) }
override val mode: Trip.Mode
get() = when (parsed.getInt(LOCATION_NUMBER)) {
null -> Trip.Mode.BUS
1300 -> Trip.Mode.METRO
1019 -> Trip.Mode.FERRY
in 1000..1010 -> Trip.Mode.TRAM
in 3000..3999 -> Trip.Mode.TRAIN
else -> Trip.Mode.BUS
}
override val routeNumber: Int?
get() = parsed.getInt(LOCATION_NUMBER)
override val routeNames: List<FormattedString>?
get() = listOfNotNull(parsed.getInt(LOCATION_NUMBER)?.let { FormattedString((it % 1000).toString()) })
companion object {
private const val AREA_PREFIX = "EventBoarding"
private const val LOCATION_TYPE = "BoardingLocationNumberType"
private const val LOCATION_NUMBER = "BoardingLocationNumber"
private val EMBED_FIELDS_WALTTI_ARVO = En1545Container(
En1545FixedInteger.date(EVENT),
En1545FixedInteger.timeLocal(EVENT),
En1545FixedInteger(EVENT_VEHICLE_ID, 14),
En1545FixedInteger("BoardingDirection", 1),
En1545FixedInteger(HSLLookup.contractWalttiZoneName(AREA_PREFIX), 4)
)
private val EMBED_FIELDS_WALTTI_KAUSI = En1545Container(
En1545FixedInteger.date(EVENT),
En1545FixedInteger.timeLocal(EVENT),
En1545FixedInteger(EVENT_VEHICLE_ID, 14),
En1545FixedInteger(HSLLookup.contractWalttiRegionName(AREA_PREFIX), 8),
En1545FixedInteger("BoardingDirection", 1),
En1545FixedInteger(HSLLookup.contractWalttiZoneName(AREA_PREFIX), 4)
)
private val EMBED_FIELDS_V1 = En1545Container(
En1545FixedInteger.date(EVENT),
En1545FixedInteger.timeLocal(EVENT),
En1545FixedInteger(EVENT_VEHICLE_ID, 14),
En1545FixedInteger(LOCATION_TYPE, 2),
En1545FixedInteger(LOCATION_NUMBER, 14),
En1545FixedInteger("BoardingDirection", 1),
En1545FixedInteger(HSLLookup.contractAreaName(AREA_PREFIX), 4),
En1545FixedInteger("reserved", 4)
)
private val EMBED_FIELDS_V2 = En1545Container(
En1545FixedInteger.date(EVENT),
En1545FixedInteger.timeLocal(EVENT),
En1545FixedInteger(EVENT_VEHICLE_ID, 14),
En1545FixedInteger(LOCATION_TYPE, 2),
En1545FixedInteger(LOCATION_NUMBER, 14),
En1545FixedInteger("BoardingDirection", 1),
En1545FixedInteger(HSLLookup.contractAreaTypeName(AREA_PREFIX), 2),
En1545FixedInteger(HSLLookup.contractAreaName(AREA_PREFIX), 6)
)
private const val IS_ARVO = "IsArvo"
private const val TRANSFER_END = "TransferEnd"
private val LOG_FIELDS_V1 = En1545Container(
En1545FixedInteger(IS_ARVO, 1),
En1545FixedInteger.date(EVENT),
En1545FixedInteger.timeLocal(EVENT),
En1545FixedInteger.date(TRANSFER_END),
En1545FixedInteger.timeLocal(TRANSFER_END),
En1545FixedInteger(EVENT_PRICE_AMOUNT, 14),
En1545FixedInteger(EVENT_PASSENGER_COUNT,5),
En1545FixedInteger("RemainingValue", 20)
)
private val LOG_FIELDS_V2 = En1545Container(
En1545FixedInteger(IS_ARVO, 1),
En1545FixedInteger.date(EVENT),
En1545FixedInteger.timeLocal(EVENT),
En1545FixedInteger.date(TRANSFER_END),
En1545FixedInteger.timeLocal(TRANSFER_END),
En1545FixedInteger(EVENT_PRICE_AMOUNT, 14),
En1545FixedInteger(EVENT_PASSENGER_COUNT, 6),
En1545FixedInteger("RemainingValue", 20)
)
fun parseEmbed(raw: ImmutableByteArray, offset: Int, version: HSLTransitData.Variant,
walttiArvoRegion: Int? = null, ultralightCity: Int? = null): HSLTransaction? {
val fields = when(version) {
HSLTransitData.Variant.HSL_V2 -> EMBED_FIELDS_V2
HSLTransitData.Variant.HSL_V1 -> EMBED_FIELDS_V1
HSLTransitData.Variant.WALTTI -> if (walttiArvoRegion == null) EMBED_FIELDS_WALTTI_KAUSI else EMBED_FIELDS_WALTTI_ARVO
}
val parsed = En1545Parser.parse(raw, offset, fields)
if (parsed.getTimeStamp(EVENT, HSLLookup.timeZone) == null)
return null
return HSLTransaction(parsed, walttiRegion=walttiArvoRegion, ultralightCity=ultralightCity)
}
fun parseLog(raw: ImmutableByteArray, version: HSLTransitData.Variant): HSLTransaction? {
if (raw.isAllZero())
return null
val fields = when (version) {
HSLTransitData.Variant.HSL_V2 -> LOG_FIELDS_V2
HSLTransitData.Variant.HSL_V1, HSLTransitData.Variant.WALTTI -> LOG_FIELDS_V1
}
return HSLTransaction(En1545Parser.parse(raw, fields), walttiRegion=null)
}
fun merge(a: HSLTransaction, b: HSLTransaction): HSLTransaction =
HSLTransaction(a.parsed + b.parsed, walttiRegion=a.walttiRegion ?: b.walttiRegion)
}
}
| gpl-3.0 | 8fdafec98bf1efc51b2877809ccbaae4 | 43.728814 | 134 | 0.643173 | 4.134204 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/events/CallParticipant.kt | 1 | 4193 | package org.thoughtcrime.securesms.events
import android.content.Context
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.webrtc.BroadcastVideoSink
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.ringrtc.CameraState
import org.whispersystems.libsignal.IdentityKey
data class CallParticipant constructor(
val callParticipantId: CallParticipantId = CallParticipantId(Recipient.UNKNOWN),
val recipient: Recipient = Recipient.UNKNOWN,
val identityKey: IdentityKey? = null,
val videoSink: BroadcastVideoSink = BroadcastVideoSink(),
val cameraState: CameraState = CameraState.UNKNOWN,
val isVideoEnabled: Boolean = false,
val isMicrophoneEnabled: Boolean = false,
val lastSpoke: Long = 0,
val isMediaKeysReceived: Boolean = true,
val addedToCallTime: Long = 0,
val isScreenSharing: Boolean = false,
private val deviceOrdinal: DeviceOrdinal = DeviceOrdinal.PRIMARY
) {
val cameraDirection: CameraState.Direction
get() = if (cameraState.activeDirection == CameraState.Direction.BACK) cameraState.activeDirection else CameraState.Direction.FRONT
val isMoreThanOneCameraAvailable: Boolean
get() = cameraState.cameraCount > 1
val isPrimary: Boolean
get() = deviceOrdinal == DeviceOrdinal.PRIMARY
val isSelf: Boolean
get() = recipient.isSelf
fun getRecipientDisplayName(context: Context): String {
return if (recipient.isSelf && isPrimary) {
context.getString(R.string.CallParticipant__you)
} else if (recipient.isSelf) {
context.getString(R.string.CallParticipant__you_on_another_device)
} else if (isPrimary) {
recipient.getDisplayName(context)
} else {
context.getString(R.string.CallParticipant__s_on_another_device, recipient.getDisplayName(context))
}
}
fun getShortRecipientDisplayName(context: Context): String {
return if (recipient.isSelf && isPrimary) {
context.getString(R.string.CallParticipant__you)
} else if (recipient.isSelf) {
context.getString(R.string.CallParticipant__you_on_another_device)
} else if (isPrimary) {
recipient.getShortDisplayName(context)
} else {
context.getString(R.string.CallParticipant__s_on_another_device, recipient.getShortDisplayName(context))
}
}
fun withIdentityKey(identityKey: IdentityKey?): CallParticipant {
return copy(identityKey = identityKey)
}
fun withVideoEnabled(videoEnabled: Boolean): CallParticipant {
return copy(isVideoEnabled = videoEnabled)
}
fun withScreenSharingEnabled(enable: Boolean): CallParticipant {
return copy(isScreenSharing = enable)
}
enum class DeviceOrdinal {
PRIMARY, SECONDARY
}
companion object {
@JvmField
val EMPTY: CallParticipant = CallParticipant()
@JvmStatic
fun createLocal(
cameraState: CameraState,
renderer: BroadcastVideoSink,
microphoneEnabled: Boolean
): CallParticipant {
return CallParticipant(
callParticipantId = CallParticipantId(Recipient.self()),
recipient = Recipient.self(),
videoSink = renderer,
cameraState = cameraState,
isVideoEnabled = cameraState.isEnabled && cameraState.cameraCount > 0,
isMicrophoneEnabled = microphoneEnabled
)
}
@JvmStatic
fun createRemote(
callParticipantId: CallParticipantId,
recipient: Recipient,
identityKey: IdentityKey?,
renderer: BroadcastVideoSink,
audioEnabled: Boolean,
videoEnabled: Boolean,
lastSpoke: Long,
mediaKeysReceived: Boolean,
addedToCallTime: Long,
isScreenSharing: Boolean,
deviceOrdinal: DeviceOrdinal
): CallParticipant {
return CallParticipant(
callParticipantId = callParticipantId,
recipient = recipient,
identityKey = identityKey,
videoSink = renderer,
isVideoEnabled = videoEnabled,
isMicrophoneEnabled = audioEnabled,
lastSpoke = lastSpoke,
isMediaKeysReceived = mediaKeysReceived,
addedToCallTime = addedToCallTime,
isScreenSharing = isScreenSharing,
deviceOrdinal = deviceOrdinal
)
}
}
}
| gpl-3.0 | b9cdbc735dd5faf34981018eb63fa559 | 32.544 | 135 | 0.725018 | 4.638274 | false | false | false | false |
dmeybohm/chocolate-cakephp | src/main/kotlin/com/daveme/chocolateCakePHP/classes.kt | 1 | 6944 | package com.daveme.chocolateCakePHP
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.jetbrains.php.PhpIndex
import com.jetbrains.php.lang.psi.elements.PhpClass
import com.jetbrains.php.lang.psi.resolve.types.PhpType
private const val VIEW_HELPER_CAKE2_PARENT_CLASS = "\\AppHelper"
private const val VIEW_HELPER_CAKE3_PARENT_CLASS = "\\Cake\\View\\Helper"
private const val MODEL_CAKE2_PARENT_CLASS = "\\AppModel"
private const val COMPONENT_CAKE2_PARENT_CLASS = "\\AppComponent"
private const val COMPONENT_CAKE3_PARENT_CLASS = "\\Cake\\Controller\\Component"
private val cake2HelperBlackList = hashSetOf(
"Html5TestHelper",
"OtherHelperHelper",
"OptionEngineHelper",
"PluggedHelperHelper",
"HtmlAliasHelper",
"TestHtmlHelper",
"TestPluginAppHelper",
"TimeHelperTestObject",
"NumberHelperTestObject",
"TextHelperTestObject"
)
fun PhpIndex.getAllViewHelperSubclasses(settings: Settings): Collection<PhpClass> {
val result = arrayListOf<PhpClass>()
if (settings.cake2Enabled) {
result += getAllSubclasses(VIEW_HELPER_CAKE2_PARENT_CLASS).filter {
!cake2HelperBlackList.contains(it.name)
}
}
if (settings.cake3Enabled) {
result += getAllSubclasses(VIEW_HELPER_CAKE3_PARENT_CLASS)
}
return result
}
fun PhpIndex.getAllModelSubclasses(settings: Settings): Collection<PhpClass> {
val result = arrayListOf<PhpClass>()
if (settings.cake2Enabled) {
result += getAllSubclasses(MODEL_CAKE2_PARENT_CLASS)
}
// val cake3Subclasses = phpIndex.getAllSubclasses(MODEL_CAKE3_PARENT_CLASS)
return result
}
fun PhpIndex.getAllComponentSubclasses(settings: Settings): Collection<PhpClass> {
val result = arrayListOf<PhpClass>()
if (settings.cake2Enabled) {
result += getAllSubclasses(COMPONENT_CAKE2_PARENT_CLASS)
}
if (settings.cake3Enabled) {
result += getAllSubclasses(COMPONENT_CAKE3_PARENT_CLASS)
}
return result
}
fun PhpIndex.getAllAncestorTypesFromFQNs(classes: List<String>): List<PhpClass> {
val result = ArrayList<PhpClass>()
classes.map {
val directClasses = getClassesByFQN(it)
//
// Add parent classes, traits, and interfaces:
//
val superClasses = ArrayList<PhpClass>()
directClasses.map directSubclasses@ {
val superClass = it.superClass ?: return@directSubclasses
superClasses.add(superClass)
}
val interfaces = ArrayList<PhpClass>()
directClasses.map {
interfaces += it.implementedInterfaces
}
val traits = ArrayList<PhpClass>()
directClasses.map {
traits += it.traits
}
result += directClasses + superClasses + traits
}
return result
}
fun PhpIndex.viewHelperClassesFromFieldName(settings: Settings, fieldName: String): Collection<PhpClass> {
val result = arrayListOf<PhpClass>()
if (settings.cake2Enabled) {
result += getClassesByFQN("\\${fieldName}Helper")
}
if (settings.cake3Enabled) {
result += getClassesByFQN(
"\\Cake\\View\\Helper\\${fieldName}Helper"
)
result += getClassesByFQN(
"${settings.appNamespace}\\View\\Helper\\${fieldName}Helper"
)
for (pluginEntry in settings.pluginEntries) {
result += getClassesByFQN("${pluginEntry.namespace}\\View\\Helper\\${fieldName}Helper")
}
}
return result
}
fun PhpIndex.componentAndModelClassesFromFieldName(settings: Settings, fieldName: String): Collection<PhpClass> =
this.componentFieldClassesFromFieldName(settings, fieldName) +
this.modelFieldClassesFromFieldName(settings, fieldName)
fun PhpIndex.componentFieldClassesFromFieldName(settings: Settings, fieldName: String): Collection<PhpClass> {
val result = arrayListOf<PhpClass>()
if (settings.cake2Enabled) {
result += getClassesByFQN("\\${fieldName}Component")
}
if (settings.cake3Enabled) {
result += getClassesByFQN(
"\\Cake\\Controller\\Component\\${fieldName}Component"
)
result += getClassesByFQN(
"${settings.appNamespace}\\Controller\\Component\\${fieldName}Component"
)
for (pluginEntry in settings.pluginEntries) {
result += getClassesByFQN("${pluginEntry.namespace}\\Controller\\Component\\${fieldName}Component")
}
}
return result
}
fun PhpIndex.modelFieldClassesFromFieldName(settings: Settings, fieldName: String): Collection<PhpClass> {
val result = arrayListOf<PhpClass>()
if (settings.cake2Enabled) {
result += getClassesByFQN("\\$fieldName")
}
if (settings.cake3Enabled) {
result += getClassesByFQN(
"${settings.appNamespace}\\Model\\Table\\$fieldName"
)
for (pluginEntry in settings.pluginEntries) {
result += getClassesByFQN("${pluginEntry.namespace}\\Model\\Table\\${fieldName}")
}
}
return result
}
fun viewHelperTypeFromFieldName(settings: Settings, fieldName: String): PhpType {
var result = PhpType()
if (settings.cake2Enabled) {
result = result.add("\\${fieldName}Helper")
}
if (settings.cake3Enabled) {
result = result.add("\\Cake\\View\\Helper\\${fieldName}Helper")
.add("${settings.appNamespace}\\View\\Helper\\${fieldName}Helper")
for (pluginEntry in settings.pluginEntries) {
result = result.add("${pluginEntry.namespace}\\View\\Helper\\${fieldName}Helper")
}
}
return result
}
fun componentOrModelTypeFromFieldName(settings: Settings, fieldName: String): PhpType {
var result = PhpType()
if (settings.cake2Enabled) {
result = result .add("\\" + fieldName)
.add("\\" + fieldName + "Component")
}
if (settings.cake3Enabled) {
result = result.add("\\Cake\\Controller\\Component\\${fieldName}Component")
.add("${settings.appNamespace}\\Controller\\Component\\${fieldName}Component")
for (pluginEntry in settings.pluginEntries) {
result = result.add("${pluginEntry.namespace}\\Controller\\Component\\${fieldName}Component")
}
}
return result
}
fun viewType(settings: Settings): PhpType {
var result = PhpType()
if (settings.cake2Enabled) {
result = result.add("\\AppView")
}
if (settings.cake3Enabled) {
result = result.add("${settings.appNamespace}\\View\\AppView")
}
return result
}
fun findParentWithClass(element: PsiElement, clazz: Class<out PsiElement>): PsiElement? {
var iterationElement = element
while (true) {
val parent = iterationElement.parent ?: break
if (PlatformPatterns.psiElement(clazz).accepts(parent)) {
return parent
}
iterationElement = parent
}
return null
} | mit | b766db4df0a7922ef4da57afe9c97d48 | 33.044118 | 113 | 0.664747 | 4.356336 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/internal/KotlinUElementWithComments.kt | 2 | 3856 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin.internal
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.KtPropertyAccessor
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.uast.*
@ApiStatus.Internal
interface KotlinUElementWithComments : UElement {
override val comments: List<UComment>
get() {
val psi = sourcePsi ?: return emptyList()
val childrenComments = commentsOnPsiElement(psi)
// Default constructor or synthetic members whose source PSI point to its containing class or object
if (this !is UClass && psi is KtClassOrObject) {
// Don't regard class's comments as synthetic members' comments
return emptyList()
}
// Default property accessors
if (this is UMethod && psi is KtProperty) {
// Don't regard property's comments as accessor's comments,
// unless that property won't be materialized (e.g., property in interface)
val backingField = (uastParent as? UClass)?.fields?.find { it.sourcePsi == psi }
return if (backingField != null)
emptyList()
else
childrenComments
}
// Property accessor w/o its own comments
if (psi is KtPropertyAccessor && childrenComments.isEmpty()) {
// If the containing property does not have a backing field,
// comments on the property won't appear on any elements, so we should keep them here.
val propertyPsi = psi.parent as? KtProperty ?: return childrenComments
val backingField = (uastParent as? UClass)?.fields?.find { it.sourcePsi == propertyPsi }
return if (backingField != null)
childrenComments
else
commentsOnPsiElement(propertyPsi)
} // Property accessor w/ its own comments fall through and return those comments.
if (this !is UExpression &&
this !is UParameter // fun (/* prior */ a: Int) <-- /* prior */ is on the level of VALUE_PARAM_LIST
)
return childrenComments
val childrenAndSiblingComments = childrenComments +
psi.nearestCommentSibling(forward = true)?.let { listOf(UComment(it, this)) }.orEmpty() +
psi.nearestCommentSibling(forward = false)?.let { listOf(UComment(it, this)) }.orEmpty()
val parent = psi.parent as? KtValueArgument ?: return childrenAndSiblingComments
return childrenAndSiblingComments +
parent.nearestCommentSibling(forward = true)?.let { listOf(UComment(it, this)) }.orEmpty() +
parent.nearestCommentSibling(forward = false)?.let { listOf(UComment(it, this)) }.orEmpty()
}
private fun commentsOnPsiElement(psi: PsiElement): List<UComment> {
return psi.allChildren.filterIsInstance<PsiComment>().map { UComment(it, this) }.toList()
}
private fun PsiElement.nearestCommentSibling(forward: Boolean): PsiComment? {
var sibling = if (forward) nextSibling else prevSibling
while (sibling is PsiWhiteSpace && !sibling.text.contains('\n')) {
sibling = if (forward) sibling.nextSibling else sibling.prevSibling
}
return sibling as? PsiComment
}
}
| apache-2.0 | 35d4f95f4fa5771f1b17a3b530c56cdb | 50.413333 | 158 | 0.640301 | 5.148198 | false | false | false | false |
jk1/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerPathToFileManager.kt | 3 | 7374 | package org.jetbrains.builtInWebServer
import com.google.common.base.Function
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.intellij.ProjectTopics
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.SmartList
import com.intellij.util.containers.computeIfAny
import com.intellij.util.io.exists
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
private val cacheSize: Long = 4096 * 4
/**
* Implement [WebServerRootsProvider] to add your provider
*/
class WebServerPathToFileManager(application: Application, private val project: Project) {
val pathToInfoCache: Cache<String, PathInfo> = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, PathInfo>()!!
// time to expire should be greater than pathToFileCache
private val virtualFileToPathInfo = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(11, TimeUnit.MINUTES).build<VirtualFile, PathInfo>()
internal val pathToExistShortTermCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(5, TimeUnit.SECONDS).build<String, Boolean>()!!
/**
* https://youtrack.jetbrains.com/issue/WEB-25900
*
* Compute suitable roots for oldest parent (web/foo/my/file.dart -> oldest is web and we compute all suitable roots for it in advance) to avoid linear search
* (i.e. to avoid two queries for root if files web/foo and web/bar requested if root doesn't have web dir)
*/
internal val parentToSuitableRoot = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, List<SuitableRoot>>(
CacheLoader.from(Function { path ->
val suitableRoots = SmartList<SuitableRoot>()
var moduleQualifier: String? = null
val modules = runReadAction { ModuleManager.getInstance(project).modules }
for (rootProvider in RootProvider.values()) {
for (module in modules) {
if (module.isDisposed) {
continue
}
for (root in rootProvider.getRoots(module.rootManager)) {
if (root.findChild(path!!) != null) {
if (moduleQualifier == null) {
moduleQualifier = getModuleNameQualifier(project, module)
}
suitableRoots.add(SuitableRoot(root, moduleQualifier))
}
}
}
}
suitableRoots
}))!!
init {
application.messageBus.connect(project).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
for (event in events) {
if (event is VFileContentChangeEvent) {
val file = event.file
for (rootsProvider in WebServerRootsProvider.EP_NAME.extensions) {
if (rootsProvider.isClearCacheOnFileContentChanged(file)) {
clearCache()
break
}
}
}
else {
clearCache()
break
}
}
}
})
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
clearCache()
}
})
}
companion object {
@JvmStatic fun getInstance(project: Project): WebServerPathToFileManager = ServiceManager.getService(project, WebServerPathToFileManager::class.java)!!
}
private fun clearCache() {
pathToInfoCache.invalidateAll()
virtualFileToPathInfo.invalidateAll()
pathToExistShortTermCache.invalidateAll()
parentToSuitableRoot.invalidateAll()
}
@JvmOverloads fun findVirtualFile(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): VirtualFile? {
return getPathInfo(path, cacheResult, pathQuery)?.getOrResolveVirtualFile()
}
@JvmOverloads fun getPathInfo(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): PathInfo? {
var pathInfo = pathToInfoCache.getIfPresent(path)
if (pathInfo == null || !pathInfo.isValid) {
if (pathToExistShortTermCache.getIfPresent(path) == false) {
return null
}
pathInfo = doFindByRelativePath(path, pathQuery)
if (cacheResult) {
if (pathInfo != null && pathInfo.isValid) {
pathToInfoCache.put(path, pathInfo)
}
else {
pathToExistShortTermCache.put(path, false)
}
}
}
return pathInfo
}
fun getPath(file: VirtualFile): String? = getPathInfo(file)?.path
fun getPathInfo(child: VirtualFile): PathInfo? {
var result = virtualFileToPathInfo.getIfPresent(child)
if (result == null) {
result = WebServerRootsProvider.EP_NAME.extensions.computeIfAny { it.getPathInfo(child, project) }
if (result != null) {
virtualFileToPathInfo.put(child, result)
}
}
return result
}
internal fun doFindByRelativePath(path: String, pathQuery: PathQuery): PathInfo? {
val result = WebServerRootsProvider.EP_NAME.extensions.computeIfAny { it.resolve(path, project, pathQuery) } ?: return null
result.file?.let {
virtualFileToPathInfo.put(it, result)
}
return result
}
fun getResolver(path: String): FileResolver = if (path.isEmpty()) EMPTY_PATH_RESOLVER else RELATIVE_PATH_RESOLVER
}
interface FileResolver {
fun resolve(path: String, root: VirtualFile, moduleName: String? = null, isLibrary: Boolean = false, pathQuery: PathQuery): PathInfo?
}
private val RELATIVE_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
// WEB-17691 built-in server doesn't serve files it doesn't have in the project tree
// temp:// reports isInLocalFileSystem == true, but it is not true
if (pathQuery.useVfs || root.fileSystem != LocalFileSystem.getInstance() || path == ".htaccess" || path == "config.json") {
return root.findFileByRelativePath(path)?.let { PathInfo(null, it, root, moduleName, isLibrary) }
}
val file = Paths.get(root.path, path)
return if (file.exists()) {
PathInfo(file, null, root, moduleName, isLibrary)
}
else {
null
}
}
}
private val EMPTY_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
val file = findIndexFile(root) ?: return null
return PathInfo(null, file, root, moduleName, isLibrary)
}
}
internal val defaultPathQuery = PathQuery() | apache-2.0 | 125b5df7a29111a56ca5b5bf74243776 | 38.864865 | 165 | 0.709656 | 4.754352 | false | false | false | false |
pjozsef/KotlinExtensionsCore | src/main/kotlin/examples/Demo.kt | 1 | 1317 | package examples
import com.github.pjozsef.extension.core.bool.*
import com.github.pjozsef.extension.core.integer.*
import com.github.pjozsef.extension.core.longdate.*
import java.text.SimpleDateFormat
import java.util.*
fun booleanDemo(result: Boolean) {
result {
print("yay")
} otherwise {
print("meh")
}
//instead of
if (result) {
print("yay")
} else {
print("meh")
}
}
fun ifNotDemo(failed: Boolean){
ifNot(failed){
print("yay, it succeeded")
}
}
fun integerDemo(number: Int) {
number.times {
println("Counting: $it")
}
//instead of
for (i in 0..number - 1) {
println("Counting: $i")
}
}
fun longAsCalendaDemo(long: Long) {
val cal = long.asCalendar()
//instead of
val cal2 = Calendar.getInstance()
cal.timeInMillis = long
}
fun longAsDateDemo(long: Long) {
val date = long.asDate()
//instead of
val date2 = Date(long)
}
fun longDateFormatDemo(long: Long, customFormatString: String) {
val custom: String = long.format(customFormatString)
val dateTime: String = long.formatAsDateTime()
val date: String = long.formatAsDate()
//instead of
val formatter = SimpleDateFormat(customFormatString)
val custom2 = formatter.format(Date(long))
} | mit | fc256b27ddbd4a4be1a62ee8469eefd4 | 18.969697 | 64 | 0.639332 | 3.540323 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/net/NodePublisher.kt | 1 | 4524 | package graphics.scenery.net
import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.Output
import com.esotericsoftware.kryo.util.DefaultInstantiatorStrategy
import de.javakaffee.kryoserializers.UUIDSerializer
import graphics.scenery.*
import graphics.scenery.serialization.*
import graphics.scenery.utils.LazyLogger
import graphics.scenery.utils.Statistics
import graphics.scenery.volumes.BufferedVolume
import graphics.scenery.volumes.RAIVolume
import graphics.scenery.volumes.Volume
import graphics.scenery.volumes.VolumeManager
import net.imglib2.img.basictypeaccess.array.ByteArray
import org.joml.Vector3f
import org.objenesis.strategy.StdInstantiatorStrategy
import org.zeromq.ZContext
import org.zeromq.ZMQ
import org.zeromq.ZMQException
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.nio.ByteBuffer
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.zip.Inflater
/**
* Created by ulrik on 4/4/2017.
*/
class NodePublisher(override var hub: Hub?, val address: String = "tcp://127.0.0.1:6666", val context: ZContext = ZContext(4)): Hubable {
private val logger by LazyLogger()
var nodes: ConcurrentHashMap<Int, Node> = ConcurrentHashMap()
private var publishedAt = ConcurrentHashMap<Int, Long>()
private var publisher: ZMQ.Socket = context.createSocket(ZMQ.PUB)
val kryo = freeze()
var port: Int = try {
publisher.bind(address)
address.substringAfterLast(":").toInt()
} catch (e: ZMQException) {
logger.warn("Binding failed, trying random port: $e")
publisher.bindToRandomPort(address.substringBeforeLast(":"))
}
fun publish() {
nodes.forEach { (guid, node) ->
val lastSeen = publishedAt[guid] ?: 0L
if(lastSeen >= node.modifiedAt) {
return@forEach
}
var payloadSize = 0L
val start = System.nanoTime()
publishedAt[guid] = start
try {
val bos = ByteArrayOutputStream()
val output = Output(bos)
kryo.writeClassAndObject(output, node)
output.flush()
val payload = bos.toByteArray()
publisher.sendMore(guid.toString())
publisher.send(payload)
Thread.sleep(1)
payloadSize = payload.size.toLong()
output.close()
bos.close()
} catch(e: IOException) {
logger.warn("in ${node.name}: ${e}")
} catch(e: AssertionError) {
logger.warn("assertion: ${node.name}: ${e}")
}
val duration = (System.nanoTime() - start).toFloat()
(hub?.get(SceneryElement.Statistics) as Statistics).add("Serialise.duration", duration)
(hub?.get(SceneryElement.Statistics) as Statistics).add("Serialise.payloadSize", payloadSize, isTime = false)
}
}
fun close() {
context.destroySocket(publisher)
context.close()
}
companion object {
fun freeze(): Kryo {
val kryo = Kryo()
kryo.instantiatorStrategy = DefaultInstantiatorStrategy(StdInstantiatorStrategy())
kryo.isRegistrationRequired = false
kryo.references = true
kryo.setCopyReferences(true)
kryo.register(UUID::class.java, UUIDSerializer())
kryo.register(OrientedBoundingBox::class.java, OrientedBoundingBoxSerializer())
kryo.register(Triple::class.java, TripleSerializer())
kryo.register(ByteBuffer::class.java, ByteBufferSerializer())
// A little trick here, because DirectByteBuffer is package-private
val tmp = ByteBuffer.allocateDirect(1)
kryo.register(tmp.javaClass, ByteBufferSerializer())
kryo.register(ByteArray::class.java, Imglib2ByteArraySerializer())
kryo.register(ShaderMaterial::class.java, ShaderMaterialSerializer())
kryo.register(java.util.zip.Inflater::class.java, IgnoreSerializer<Inflater>())
kryo.register(VolumeManager::class.java, IgnoreSerializer<VolumeManager>())
kryo.register(Vector3f::class.java, Vector3fSerializer())
kryo.register(Volume::class.java, VolumeSerializer())
kryo.register(RAIVolume::class.java, VolumeSerializer())
kryo.register(BufferedVolume::class.java, VolumeSerializer())
return kryo
}
}
}
| lgpl-3.0 | a8cfbda1792a8c1d46decf4818dc2145 | 37.666667 | 137 | 0.656941 | 4.488095 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/random/RandomFragment.kt | 1 | 11241 | package org.wikipedia.random
import android.graphics.drawable.Animatable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityOptionsCompat
import androidx.core.os.bundleOf
import androidx.core.util.Pair
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.functions.Consumer
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.RandomizerFunnel
import org.wikipedia.databinding.FragmentRandomBinding
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.events.ArticleSavedOrDeletedEvent
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.PageActivity
import org.wikipedia.page.PageTitle
import org.wikipedia.readinglist.AddToReadingListDialog
import org.wikipedia.readinglist.LongPressMenu
import org.wikipedia.readinglist.MoveToReadingListDialog
import org.wikipedia.readinglist.ReadingListBehaviorsUtil
import org.wikipedia.readinglist.ReadingListBehaviorsUtil.AddToDefaultListCallback
import org.wikipedia.readinglist.ReadingListBehaviorsUtil.addToDefaultList
import org.wikipedia.readinglist.database.ReadingListDbHelper
import org.wikipedia.readinglist.database.ReadingListPage
import org.wikipedia.util.AnimationUtil.PagerTransformer
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.log.L
import org.wikipedia.views.PositionAwareFragmentStateAdapter
class RandomFragment : Fragment() {
companion object {
fun newInstance(wikiSite: WikiSite, invokeSource: InvokeSource) = RandomFragment().apply {
arguments = bundleOf(
RandomActivity.INTENT_EXTRA_WIKISITE to wikiSite,
Constants.INTENT_EXTRA_INVOKE_SOURCE to invokeSource
)
}
}
private var _binding: FragmentRandomBinding? = null
private val binding get() = _binding!!
private val disposables = CompositeDisposable()
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
private lateinit var funnel: RandomizerFunnel
private val viewPagerListener: ViewPagerListener = ViewPagerListener()
private lateinit var wikiSite: WikiSite
private val topTitle get() = getTopChild()?.title
private var saveButtonState = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentRandomBinding.inflate(inflater, container, false)
val view = binding.root
FeedbackUtil.setButtonLongPressToast(binding.randomNextButton, binding.randomSaveButton)
wikiSite = requireArguments().getParcelable(RandomActivity.INTENT_EXTRA_WIKISITE)!!
binding.randomItemPager.offscreenPageLimit = 2
binding.randomItemPager.adapter = RandomItemAdapter(this)
binding.randomItemPager.setPageTransformer(PagerTransformer(resources.configuration.layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL))
binding.randomItemPager.registerOnPageChangeCallback(viewPagerListener)
binding.randomNextButton.setOnClickListener { onNextClick() }
binding.randomBackButton.setOnClickListener { onBackClick() }
binding.randomSaveButton.setOnClickListener { onSaveShareClick() }
disposables.add(WikipediaApp.getInstance().bus.subscribe(EventBusConsumer()))
updateSaveShareButton()
updateBackButton(0)
if (savedInstanceState != null && binding.randomItemPager.currentItem == 0 && topTitle != null) {
updateSaveShareButton(topTitle)
}
funnel = RandomizerFunnel(WikipediaApp.getInstance(), wikiSite,
(arguments?.getSerializable(Constants.INTENT_EXTRA_INVOKE_SOURCE) as? InvokeSource)!!)
return view
}
override fun onResume() {
super.onResume()
updateSaveShareButton(topTitle)
}
override fun onDestroyView() {
disposables.clear()
binding.randomItemPager.unregisterOnPageChangeCallback(viewPagerListener)
funnel.done()
_binding = null
super.onDestroyView()
}
private fun onNextClick() {
if (binding.randomNextButton.drawable is Animatable) {
(binding.randomNextButton.drawable as Animatable).start()
}
viewPagerListener.setNextPageSelectedAutomatic()
binding.randomItemPager.setCurrentItem(binding.randomItemPager.currentItem + 1, true)
funnel.clickedForward()
}
private fun onBackClick() {
viewPagerListener.setNextPageSelectedAutomatic()
if (binding.randomItemPager.currentItem > 0) {
binding.randomItemPager.setCurrentItem(binding.randomItemPager.currentItem - 1, true)
funnel.clickedBack()
}
}
private fun onSaveShareClick() {
val title = topTitle ?: return
if (saveButtonState) {
LongPressMenu(binding.randomSaveButton, object : LongPressMenu.Callback {
override fun onOpenLink(entry: HistoryEntry) {
// ignore
}
override fun onOpenInNewTab(entry: HistoryEntry) {
// ignore
}
override fun onAddRequest(entry: HistoryEntry, addToDefault: Boolean) {
onAddPageToList(title, addToDefault)
}
override fun onMoveRequest(page: ReadingListPage?, entry: HistoryEntry) {
onMovePageToList(page!!.listId, title)
}
}).show(HistoryEntry(title, HistoryEntry.SOURCE_RANDOM))
} else {
onAddPageToList(title, true)
}
}
fun onSelectPage(title: PageTitle, sharedElements: Array<Pair<View, String>>) {
val options = ActivityOptionsCompat.makeSceneTransitionAnimation(requireActivity(), *sharedElements)
val intent = PageActivity.newIntentForNewTab(requireContext(),
HistoryEntry(title, HistoryEntry.SOURCE_RANDOM), title)
if (sharedElements.isNotEmpty()) {
intent.putExtra(Constants.INTENT_EXTRA_HAS_TRANSITION_ANIM, true)
}
startActivity(intent, if (DimenUtil.isLandscape(requireContext()) || sharedElements.isEmpty()) null else options.toBundle())
}
fun onAddPageToList(title: PageTitle, addToDefault: Boolean) {
if (addToDefault) {
addToDefaultList(requireActivity(), title, InvokeSource.RANDOM_ACTIVITY,
object : AddToDefaultListCallback {
override fun onMoveClicked(readingListId: Long) {
onMovePageToList(readingListId, title)
}
},
object : ReadingListBehaviorsUtil.Callback {
override fun onCompleted() {
updateSaveShareButton(title)
}
}
)
} else {
bottomSheetPresenter.show(childFragmentManager,
AddToReadingListDialog.newInstance(title, InvokeSource.RANDOM_ACTIVITY) {
updateSaveShareButton(title)
})
}
}
fun onMovePageToList(sourceReadingListId: Long, title: PageTitle) {
bottomSheetPresenter.show(childFragmentManager,
MoveToReadingListDialog.newInstance(sourceReadingListId, listOf(title), InvokeSource.RANDOM_ACTIVITY, true) {
updateSaveShareButton(title)
})
}
private fun updateBackButton(pagerPosition: Int) {
binding.randomBackButton.isClickable = pagerPosition != 0
binding.randomBackButton.alpha = if (pagerPosition == 0) 0.5f else 1f
}
private fun updateSaveShareButton(title: PageTitle?) {
if (title == null) {
return
}
val d = Observable.fromCallable { ReadingListDbHelper.findPageInAnyList(title) != null }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ exists: Boolean ->
saveButtonState = exists
val img = if (saveButtonState) R.drawable.ic_bookmark_white_24dp else R.drawable.ic_bookmark_border_white_24dp
binding.randomSaveButton.setImageResource(img)
}, { t ->
L.w(t)
})
disposables.add(d)
}
private fun updateSaveShareButton() {
val enable = getTopChild()?.isLoadComplete ?: false
binding.randomSaveButton.isClickable = enable
binding.randomSaveButton.alpha = if (enable) 1f else 0.5f
}
fun onChildLoaded() {
updateSaveShareButton()
}
private fun getTopChild(): RandomItemFragment? {
val adapter = binding.randomItemPager.adapter as? RandomItemAdapter
return adapter?.getFragmentAt(binding.randomItemPager.currentItem) as? RandomItemFragment
}
private inner class RandomItemAdapter(fragment: Fragment) : PositionAwareFragmentStateAdapter(fragment) {
override fun getItemCount(): Int {
return Int.MAX_VALUE
}
override fun createFragment(position: Int): Fragment {
return RandomItemFragment.newInstance(wikiSite)
}
}
private inner class ViewPagerListener : OnPageChangeCallback() {
private var prevPosition = 0
private var nextPageSelectedAutomatic = false
fun setNextPageSelectedAutomatic() {
nextPageSelectedAutomatic = true
}
override fun onPageSelected(position: Int) {
updateBackButton(position)
updateSaveShareButton(topTitle)
if (!nextPageSelectedAutomatic) {
if (position > prevPosition) {
funnel.swipedForward()
} else if (position < prevPosition) {
funnel.swipedBack()
}
}
nextPageSelectedAutomatic = false
prevPosition = position
updateSaveShareButton()
}
}
private inner class EventBusConsumer : Consumer<Any> {
override fun accept(event: Any?) {
if (event is ArticleSavedOrDeletedEvent) {
if (!isAdded || topTitle == null) {
return
}
for (page in event.pages) {
if (page.apiTitle == topTitle?.prefixedText && page.wiki.languageCode() == topTitle?.wikiSite?.languageCode()) {
updateSaveShareButton(topTitle)
}
}
}
}
}
}
| apache-2.0 | da6cd2f9fd463c0886717ecf52ac9e60 | 37.234694 | 144 | 0.668179 | 5.294866 | false | false | false | false |
songful/PocketHub | app/src/main/java/com/github/pockethub/android/core/repo/RepositoryUtils.kt | 1 | 2212 | /*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.android.core.repo
import com.meisolsson.githubsdk.model.Repository
/**
* Utilities for working with [Repository] objects
*/
object RepositoryUtils {
/**
* Does the repository have details denoting it was loaded from an API call?
*
*
* This uses a simple heuristic of either being private, being a fork, or
* having a non-zero amount of forks or watchers, or has issues enable;
* meaning it came back from an API call providing those details and more.
*
* @return true if complete, false otherwise
*/
@JvmStatic
fun Repository.isComplete() = isPrivate == true || isFork == true || hasIssues() == true
|| forksCount() != null && forksCount()!! > 0
|| watchersCount() != null && watchersCount()!! > 0
/**
* Is the given owner name valid?
*
* @param name
* @return true if valid, false otherwise
*/
@JvmStatic
fun isValidOwner(name: String?) = name !in listOf(
"about", "account", "admin", "api", "blog", "camo", "contact", "dashboard", "downloads",
"edu", "explore", "features", "home", "inbox", "languages", "login", "logout", "new",
"notifications", "organizations", "orgs", "repositories", "search", "security",
"settings", "stars", "styleguide", "timeline", "training", "users", "watching")
/**
* Is the given repo name valid?
*
* @param name
* @return true if valid, false otherwise
*/
@JvmStatic
fun isValidRepo(name: String?) = name !in listOf("followers", "following")
}
| apache-2.0 | f435169335e3ce96fb352596ad4337e2 | 35.262295 | 100 | 0.640145 | 4.189394 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/OrderCreateFinishAdapter.kt | 1 | 1950 | package com.tungnui.dalatlaptop.ux.adapters
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.travijuu.numberpicker.library.Enums.ActionEnum
import com.travijuu.numberpicker.library.Interface.ValueChangedListener
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.interfaces.CartRecyclerInterface
import com.tungnui.dalatlaptop.listeners.OnSingleClickListener
import com.tungnui.dalatlaptop.models.Cart
import com.tungnui.dalatlaptop.utils.formatPrice
import com.tungnui.dalatlaptop.utils.inflate
import com.tungnui.dalatlaptop.utils.loadImg
import kotlinx.android.synthetic.main.list_item_order_finish.view.*
import java.util.ArrayList
/**
* Adapter handling list of cart items.
*/
class OrderCreateFinishAdapter() : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val cartItems = ArrayList<Cart>()
override fun getItemCount(): Int {
return cartItems.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
ViewHolderProduct(parent.inflate(R.layout.list_item_order_finish))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as ViewHolderProduct).blind(cartItems[position])
}
fun refreshItems(carts: List<Cart>) {
cartItems.clear()
cartItems.addAll(carts)
notifyDataSetChanged()
}
fun cleatCart() {
cartItems.clear()
notifyDataSetChanged()
}
class ViewHolderProduct(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun blind(cart: Cart) = with(itemView){
order_finish_item_image.loadImg(cart.image);
order_finish_item_name.text = cart.productName
order_finish_item_price.text = cart.price.toString().formatPrice()
order_finish_item_quantity.text = "${cart.quantity}"
}
}
} | mit | 6a107719006267db74a72b4f19deb453 | 32.637931 | 96 | 0.732821 | 4.352679 | false | false | false | false |
dahlstrom-g/intellij-community | platform/execution-impl/src/com/intellij/execution/runToolbar/RunToolbarMainSlotInfoAction.kt | 1 | 7377 | // 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.execution.runToolbar
import com.intellij.execution.runToolbar.components.MouseListenerHelper
import com.intellij.execution.runToolbar.components.ProcessesByType
import com.intellij.execution.runToolbar.data.RWActiveProcesses
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomAction
import com.intellij.openapi.actionSystem.impl.segmentedActionBar.SegmentedCustomPanel
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Key
import com.intellij.util.ui.JBDimension
import net.miginfocom.swing.MigLayout
import java.awt.Color
import java.beans.PropertyChangeEvent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.UIManager
internal class RunToolbarMainSlotInfoAction : SegmentedCustomAction(),
RTRunConfiguration {
companion object {
private val LOG = Logger.getInstance(RunToolbarMainSlotInfoAction::class.java)
private val PROP_ACTIVE_PROCESS_COLOR = Key<Color>("ACTIVE_PROCESS_COLOR")
private val PROP_ACTIVE_PROCESSES_COUNT = Key<Int>("PROP_ACTIVE_PROCESSES_COUNT")
private val PROP_ACTIVE_PROCESSES = Key<RWActiveProcesses>("PROP_ACTIVE_PROCESSES")
}
override fun getRightSideType(): RTBarAction.Type = RTBarAction.Type.FLEXIBLE
override fun actionPerformed(e: AnActionEvent) {
}
override fun checkMainSlotVisibility(state: RunToolbarMainSlotState): Boolean {
return state == RunToolbarMainSlotState.INFO
}
override fun update(e: AnActionEvent) {
val presentation = e.presentation
presentation.isVisible = e.project?.let { project ->
val manager = RunToolbarSlotManager.getInstance(project)
val activeProcesses = manager.activeProcesses
manager.getMainOrFirstActiveProcess()?.let {
presentation.putClientProperty(PROP_ACTIVE_PROCESS_COLOR, it.pillColor)
}
presentation.putClientProperty(RunToolbarMainSlotActive.ARROW_DATA, e.arrowIcon())
presentation.putClientProperty(PROP_ACTIVE_PROCESSES_COUNT, activeProcesses.getActiveCount())
presentation.putClientProperty(PROP_ACTIVE_PROCESSES, activeProcesses)
activeProcesses.processes.isNotEmpty()
} ?: false
if (!RunToolbarProcess.isExperimentalUpdatingEnabled) {
e.mainState()?.let {
presentation.isVisible = presentation.isVisible && checkMainSlotVisibility(it)
}
}
traceLog(LOG, e)
}
override fun createCustomComponent(presentation: Presentation, place: String): SegmentedCustomPanel {
return RunToolbarMainSlotInfo(presentation)
}
private class RunToolbarMainSlotInfo(presentation: Presentation) : SegmentedCustomPanel(presentation), PopupControllerComponent {
private val arrow = JLabel()
private val dragArea = DraggablePane()
private val processComponents = mutableListOf<ProcessesByType>()
private val migLayout = MigLayout("fill, hidemode 3, ins 0, novisualpadding, ay center, flowx, gapx 0")
private val info = JPanel(migLayout)
private val one = ProcessesByType()
init {
layout = MigLayout("ins 0, fill, ay center")
val pane = JPanel(MigLayout("ins 0, fill, novisualpadding, ay center, gap 0", "[pref!][min!]5[fill]5")).apply {
add(JPanel().apply {
isOpaque = false
add(arrow)
val d = preferredSize
d.width = FixWidthSegmentedActionToolbarComponent.ARROW_WIDTH
preferredSize = d
})
add(JPanel().apply {
preferredSize = JBDimension(1, 12)
minimumSize = JBDimension(1, 12)
background = UIManager.getColor("Separator.separatorColor")
})
add(JPanel(MigLayout("ins 0, fill, novisualpadding, ay center, gap 0, hidemode 3")).apply {
add(info, "growx")
add(one, "growx")
isOpaque = false
}, "pushx, ay center, wmin 0")
isOpaque = false
}
add(dragArea, "pos 0 0")
add(pane, "growx, wmin 10")
info.isOpaque = false
MouseListenerHelper.addListener(pane, { doClick() }, { doShiftClick() }, { doRightClick() })
}
fun doRightClick() {
RunToolbarRunConfigurationsAction.doRightClick(ActionToolbar.getDataContextFor(this))
}
private fun doClick() {
val list = mutableListOf<PopupControllerComponentListener>()
list.addAll(listeners)
list.forEach { it.actionPerformedHandler() }
}
private fun doShiftClick() {
}
private val listeners = mutableListOf<PopupControllerComponentListener>()
override fun addListener(listener: PopupControllerComponentListener) {
listeners.add(listener)
}
override fun removeListener(listener: PopupControllerComponentListener) {
listeners.remove(listener)
}
override fun updateIconImmediately(isOpened: Boolean) {
arrow.icon = if (isOpened) AllIcons.Toolbar.Collapse
else AllIcons.Toolbar.Expand
}
override fun presentationChanged(event: PropertyChangeEvent) {
updateState()
}
private fun updateState() {
updateArrow()
presentation.getClientProperty(PROP_ACTIVE_PROCESS_COLOR)?.let {
background = it
} ?: kotlin.run {
isOpaque = false
}
updateActiveProcesses()
}
private fun updateActiveProcesses() {
presentation.getClientProperty(PROP_ACTIVE_PROCESSES)?.let { activeProcesses ->
val processes = activeProcesses.processes
val keys = processes.keys.toList()
if (activeProcesses.getActiveCount() == 1) {
info.isVisible = false
one.isVisible = processes.keys.firstOrNull()?.let { process ->
processes[process]?.let {
one.update(process, it, false)
true
}
} ?: false
return
}
else {
info.isVisible = true
one.isVisible = false
for (i in processComponents.size..processes.size) {
val component = ProcessesByType()
processComponents.add(component)
info.add(component, "w pref!")
}
var constraint = ""
for (i in 0 until processComponents.size) {
constraint += "[]"
val component = processComponents[i]
if (i < keys.size) {
val key = keys[i]
processes[key]?.let {
component.isVisible = true
component.update(key, it, true)
}
}
else {
component.isVisible = false
}
}
constraint += "push"
migLayout.columnConstraints = constraint
}
}
}
private fun updateArrow() {
presentation.getClientProperty(RunToolbarMainSlotActive.ARROW_DATA)?.let {
arrow.icon = it
toolTipText = ActionsBundle.message("action.RunToolbarShowHidePopupAction.click.to.show.popup.text")
} ?: run {
arrow.icon = null
toolTipText = null
}
}
}
}
| apache-2.0 | e2888792f91ca004d83fff27aeb62819 | 33.471963 | 131 | 0.675749 | 4.878968 | false | false | false | false |
martijn-heil/wac-core | src/main/kotlin/tk/martijn_heil/wac_core/craft/util/BlockProtector.kt | 1 | 3636 | /*
* wac-core
* Copyright (C) 2016 Martijn Heil
*
* 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 tk.martijn_heil.wac_core.craft.util
import org.bukkit.Location
import org.bukkit.World
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority.HIGHEST
import org.bukkit.event.HandlerList
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockBreakEvent
import org.bukkit.event.block.BlockPhysicsEvent
import org.bukkit.event.entity.EntityBreakDoorEvent
import org.bukkit.event.entity.EntityExplodeEvent
import org.bukkit.material.Door
import org.bukkit.plugin.Plugin
import tk.martijn_heil.wac_core.craft.Rotation
import java.io.Closeable
import java.util.*
class BlockProtector(private val plugin: Plugin) : Closeable {
var protectedBlocks: MutableCollection<Location> = ArrayList()
private val protectedBlocksListener = object : Listener {
@EventHandler(ignoreCancelled = true, priority = HIGHEST)
fun onEntityBreakDoor(e: EntityBreakDoorEvent) {
val b = e.block
val state = e.block.state
val data = state.data as? Door ?: return
val topHalf = (if(data.isTopHalf) b else b.world.getBlockAt(b.x, b.y + 1, b.z))
val bottomHalf = (if(!data.isTopHalf) b else b.world.getBlockAt(b.x, b.y - 1, b.z))
protectedBlocks.forEach {
val itBlock = it.block
e.isCancelled = itBlock == topHalf || itBlock == bottomHalf
}
}
@EventHandler(ignoreCancelled = true, priority = HIGHEST)
fun onEntityExplode(e: EntityExplodeEvent) {
protectedBlocks.forEach { e.blockList().remove(it.block) }
}
@EventHandler(ignoreCancelled = true, priority = HIGHEST)
fun onBlockBreak(e: BlockBreakEvent) {
protectedBlocks.forEach { if(e.block == it.block) e.isCancelled = true }
}
@EventHandler(ignoreCancelled = true, priority = HIGHEST)
fun onBlockPhysics(e: BlockPhysicsEvent) {
protectedBlocks.forEach { if(e.block == it.block) e.isCancelled = true }
}
}
init {
plugin.server.pluginManager.registerEvents(protectedBlocksListener, plugin)
}
fun updateAllLocations(world: World, relativeX: Int, relativeY: Int, relativeZ: Int) {
protectedBlocks.forEach {
it.world = world
it.x += relativeX
it.y += relativeY
it.z += relativeZ
}
}
fun updateAllLocationsRotated(rotation: Rotation, rotationPoint: Location) {
protectedBlocks.forEach {
val newLoc = getRotatedLocation(rotationPoint, rotation, rotationPoint)
it.x = newLoc.x
it.y = newLoc.y
it.z = newLoc.z
}
}
override fun close() {
HandlerList.unregisterAll(protectedBlocksListener)
}
} | gpl-3.0 | 493919c7a8e4e2ef63515599a61b6ff8 | 35.505155 | 95 | 0.647415 | 4.17931 | false | false | false | false |
cdietze/klay | tripleklay/tripleklay-demo/src/main/kotlin/tripleklay/demo/core/ui/TabsDemo.kt | 1 | 3825 | package tripleklay.demo.core.ui
import klay.core.Color
import klay.core.Keyboard
import react.UnitSlot
import tripleklay.demo.core.DemoScreen
import tripleklay.ui.*
import tripleklay.ui.layout.AxisLayout
import tripleklay.util.Colors
import klay.core.Random
class TabsDemo : DemoScreen() {
override fun name(): String {
return "Tabs"
}
override fun title(): String {
return "UI: Tabs"
}
override fun createIface(root: Root): Group {
val lastTab = intArrayOf(0)
val tabs = Tabs().addStyles(Style.BACKGROUND.`is`(
Background.bordered(Colors.WHITE, Colors.BLACK, 1f).inset(1f)))
val moveRight = Button("Move Right").onClick({
val tab = tabs.selected.get()
if (movable(tab)) {
tabs.repositionTab(tab!!, tab.index() + 1)
}
}).setEnabled(false)
val hide = Button("Hide").onClick({
val tab = tabs.selected.get()
if (tab != null) {
tab.isVisible = false
}
}).setEnabled(false)
tabs.selected.connect({ tab: Tabs.Tab? ->
moveRight.setEnabled(movable(tab))
hide.setEnabled(tab != null)
})
return Group(AxisLayout.vertical().offStretch()).add(
Group(AxisLayout.horizontal()).add(
Button("Add").onClick({
val label = _prefix + ++lastTab[0]
tabs.add(label, tabContent(label))
}),
Button("Remove...").onClick(object : TabSelector(tabs) {
override fun handle(tab: Tabs.Tab) {
tabs.destroyTab(tab)
}
}),
Button("Highlight...").onClick(object : TabSelector(tabs) {
override fun handle(tab: Tabs.Tab) {
tabs.highlighter().highlight(tab, true)
}
}), moveRight, hide, Button("Show All").onClick({
for (ii in 0..tabs.tabCount() - 1) {
tabs.tabAt(ii)!!.isVisible = true
}
})),
tabs.setConstraint(AxisLayout.stretched()))
}
protected fun number(tab: Tabs.Tab): Int {
return tab.button.text.get()!!.substring(_prefix.length).toInt()
}
protected fun movable(tab: Tabs.Tab?): Boolean {
val index = tab?.index() ?: -1
return index >= 0 && index + 1 < tab!!.parent().tabCount()
}
protected fun randColor(): Int {
return Color.rgb(128 + _rnd.nextInt(127), 128 + _rnd.nextInt(127), 128 + _rnd.nextInt(127))
}
protected fun tabContent(label: String): Group {
return Group(AxisLayout.vertical().offStretch().stretchByDefault()).add(
Label(label).addStyles(Style.BACKGROUND.`is`(Background.solid(randColor()))))
}
protected abstract inner class TabSelector(var tabs: Tabs) : UnitSlot {
override fun invoke(unit: Any?) {
var init = ""
if (tabs.tabCount() > 0) {
val tab = tabs.tabAt(_rnd.nextInt(tabs.tabCount()))
init = "" + number(tab!!)
}
input().getText(Keyboard.TextType.NUMBER, "Enter tab number", init).onSuccess({ result: String ->
for (ii in 0..tabs.tabCount() - 1) {
if (result == "" + number(tabs.tabAt(ii)!!)) {
handle(tabs.tabAt(ii)!!)
break
}
}
})
}
abstract fun handle(tab: Tabs.Tab)
}
protected var _prefix = "Tab "
protected var _rnd = Random()
}
| apache-2.0 | 668f633afd14fdd8954864ace06a951d | 35.428571 | 109 | 0.504837 | 4.489437 | false | false | false | false |
TheMrMilchmann/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_debug_output.kt | 4 | 18774 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val ARB_debug_output = "ARBDebugOutput".nativeClassGL("ARB_debug_output", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows the GL to notify applications when various events occur that may be useful during application development and debugging.
These events are represented in the form of enumerable messages with a human-readable string representation. Examples of debug events include incorrect
use of the GL, warnings of undefined behavior, and performance warnings.
A message is uniquely identified by a source, a type and an implementation-dependent ID within the source and type pair.
A message's source identifies the origin of the message and can either describe components of the GL, the window system, third-party external sources
such as external debuggers, or even the application itself.
The type of the message roughly identifies the nature of the event that caused the message. Examples include errors, performance warnings, or warnings
about undefined behavior.
A message's ID for a given source and type further distinguishes messages within those groups. For example, an error caused by a negative parameter
value or an invalid internal texture format are both errors generated by the API, but would likely have different message IDs.
Each message is also assigned to a severity level that denotes roughly how "important" that message is in comparison to other messages across all
sources and types. For example, notification of a GL error would likely have a higher severity than a performance warning due to redundant state
changes.
Finally, every message contains an implementation-dependent string representation that provides a useful description of the event.
Messages are communicated to the application through an application-defined callback function that is called by the GL implementation on each debug
message. The motivation for the callback routine is to free application developers from actively having to query whether a GL error, or any other
debuggable event has happened after each call to a GL function. With a callback, developers can keep their code free of debug checks, and only have to
react to messages as they occur. In situations where using a callback is not possible, a message log is also provided that stores copies of recent
messages until they are actively queried.
To control the volume of debug output, messages can be disabled either individually by ID, or entire groups of messages can be turned off based on
combination of source and type.
The only requirement on the minimum quantity and type of messages that implementations of this extension must support is that some sort of message must
be sent notifying the application whenever any GL error occurs. Any further messages are left to the implementation. Implementations do not have to
output messages from all sources nor do they have to use all types of messages listed by this extension, and both new sources and types can be added by
other extensions.
For performance reasons it is recommended, but not required, that implementations restrict supporting this extension only to contexts created using the
debug flag as provided by ${WGL_ARB_create_context.link} or ${GLX_ARB_create_context.link}. This extension places no limits on any other functionality
provided by debug contexts through other extensions.
"""
IntConstant(
"""
Tokens accepted by the {@code target} parameters of Enable, Disable, and IsEnabled.
The behavior of how and when the GL driver is allowed to generate debug messages, and subsequently either call back to the application or place the
message in the debug message log, is affected by the state DEBUG_OUTPUT_SYNCHRONOUS_ARB. This state can be modified by the GL11#glEnable() and
GL11#glDisable() commands. Its initial value is #FALSE.
When DEBUG_OUTPUT_SYNCHRONOUS_ARB is disabled, the driver is optionally allowed to concurrently call the debug callback routine from potentially
multiple threads, including threads that the context that generated the message is not currently bound to. The implementation may also call the callback
routine asynchronously after the GL command that generated the message has already returned. The application is fully responsible for ensuring thread
safety due to debug callbacks under these circumstances. In this situation the {@code userParam} value may be helpful in identifying which application
thread's command originally generated the debug callback.
When DEBUG_OUTPUT_SYNCHRONOUS_ARB is enabled, the driver guarantees synchronous calls to the callback routine by the context. When synchronous callbacks
are enabled, all calls to the callback routine will be made by the thread that owns the current context; all such calls will be made serially by the
current context; and each call will be made before the GL command that generated the debug message is allowed to return.
When no callback is specified and DEBUG_OUTPUT_SYNCHRONOUS_ARB is disabled, the driver can still asynchronously place messages in the debug message log,
even after the context thread has returned from the GL function that generated those messages. When DEBUG_OUTPUT_SYNCHRONOUS_ARB is enabled, the driver
guarantees that all messages are added to the log before the GL function returns.
Enabling synchronous debug output greatly simplifies the responsibilities of the application for making its callback functions thread-safe, but may
potentially result in drastically reduced driver performance.
The DEBUG_OUTPUT_SYNCHRONOUS_ARB only guarantees intra-context synchronization for the callbacks of messages generated by that context, and does not
guarantee synchronization across multiple contexts. If multiple contexts are concurrently used by the application, it is allowed for those contexts to
also concurrently call their designated callbacks, and the application is responsible for handling thread safety in that situation even if
DEBUG_OUTPUT_SYNCHRONOUS_ARB is enabled in all contexts.
""",
"DEBUG_OUTPUT_SYNCHRONOUS_ARB"..0x8242
)
IntConstant(
"Tokens accepted by the {@code value} parameters of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"MAX_DEBUG_MESSAGE_LENGTH_ARB"..0x9143,
"MAX_DEBUG_LOGGED_MESSAGES_ARB"..0x9144,
"DEBUG_LOGGED_MESSAGES_ARB"..0x9145,
"DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB"..0x8243
)
IntConstant(
"Tokens accepted by the {@code pname} parameter of GetPointerv.",
"DEBUG_CALLBACK_FUNCTION_ARB"..0x8244,
"DEBUG_CALLBACK_USER_PARAM_ARB"..0x8245
)
val Sources = IntConstant(
"""
Tokens accepted or provided by the {@code source} parameters of DebugMessageControlARB, DebugMessageInsertARB and DEBUGPROCARB, and the {@code sources}
parameter of GetDebugMessageLogARB.
""",
"DEBUG_SOURCE_API_ARB"..0x8246,
"DEBUG_SOURCE_WINDOW_SYSTEM_ARB"..0x8247,
"DEBUG_SOURCE_SHADER_COMPILER_ARB"..0x8248,
"DEBUG_SOURCE_THIRD_PARTY_ARB"..0x8249,
"DEBUG_SOURCE_APPLICATION_ARB"..0x824A,
"DEBUG_SOURCE_OTHER_ARB"..0x824B
).javaDocLinks
val Types = IntConstant(
"""
Tokens accepted or provided by the {@code type} parameters of DebugMessageControlARB, DebugMessageInsertARB and DEBUGPROCARB, and the {@code types}
parameter of GetDebugMessageLogARB.
""",
"DEBUG_TYPE_ERROR_ARB"..0x824C,
"DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB"..0x824D,
"DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB"..0x824E,
"DEBUG_TYPE_PORTABILITY_ARB"..0x824F,
"DEBUG_TYPE_PERFORMANCE_ARB"..0x8250,
"DEBUG_TYPE_OTHER_ARB"..0x8251
).javaDocLinks
val Severities = IntConstant(
"""
Tokens accepted or provided by the {@code severity} parameters of DebugMessageControlARB, DebugMessageInsertARB and DEBUGPROCARB callback functions, and
the {@code severities} parameter of GetDebugMessageLogARB.
""",
"DEBUG_SEVERITY_HIGH_ARB"..0x9146,
"DEBUG_SEVERITY_MEDIUM_ARB"..0x9147,
"DEBUG_SEVERITY_LOW_ARB"..0x9148
).javaDocLinks
void(
"DebugMessageControlARB",
"""
Controls the volume of debug output by disabling specific or groups of messages.
If {@code enabled} is #TRUE, the referenced subset of messages will be enabled. If #FALSE, then those messages will be disabled.
This command can reference different subsets of messages by first considering the set of all messages, and filtering out messages based on the following
ways:
${ul(
"If {@code source} is not #DONT_CARE, then all messages whose source does not match {@code source} will not be referenced.",
"If {@code type} is not #DONT_CARE, then all messages whose type does not match {@code type} will not be referenced.",
"If {@code severity} is not #DONT_CARE, then all messages whose severity level does not match {@code severity} will not be referenced.",
"""
If {@code count} is greater than zero, then {@code ids} is an array of {@code count} message IDs for the specified combination of {@code source} and
{@code type}. In this case, if {@code source} or {@code type} is #DONT_CARE, or {@code severity} is not #DONT_CARE, the error
#INVALID_OPERATION is generated. If {@code count} is zero, the value if {@code ids} is ignored.
"""
)}
Although messages are grouped into an implicit hierarchy by their sources and types, there is no explicit per-source, per-type or per-severity enabled
state. Instead, the enabled state is stored individually for each message. There is no difference between disabling all messages from one source in a
single call, and individually disabling all messages from that source using their types and IDs.
""",
GLenum("source", "the message source", Sources),
GLenum("type", "the message type", Types),
GLenum("severity", "the message severity level", Severities),
AutoSize("ids")..GLsizei("count", "the number of message IDs in {@code ids}"),
SingleValue("id")..nullable..GLuint.const.p("ids", "the message IDs to enable or disable"),
GLboolean("enabled", "whether to enable or disable the references subset of messages")
)
void(
"DebugMessageInsertARB",
"""
This function can be called by applications and third-party libraries to generate their own messages, such as ones containing timestamp information or
signals about specific render system events.
The error #INVALID_VALUE will be generated if the number of characters in {@code buf}, excluding the null terminator when {@code length} is
negative, is not less than #MAX_DEBUG_MESSAGE_LENGTH_ARB.
""",
GLenum("source", "the message source", "#DEBUG_SOURCE_THIRD_PARTY_ARB #DEBUG_SOURCE_APPLICATION_ARB"),
GLenum("type", "the message type", Types),
GLuint("id", "the message ID"),
GLenum("severity", "the message severity level", Severities),
AutoSize("buf")..GLsizei(
"length",
"the number of characters in {@code buf}. If negative, it is implied that {@code buf} contains a null terminated string."
),
GLcharUTF8.const.p("buf", "the string representation of the message")
)
void(
"DebugMessageCallbackARB",
"""
Specifies a callback function for receiving debug messages.
This function's prototype must follow the type definition of DEBUGPROCARB including its platform-dependent calling convention. Anything else will result
in undefined behavior. Only one debug callback can be specified for the current context, and further calls overwrite the previous callback. Specifying
#NULL as the value of {@code callback} clears the current callback and disables message output through callbacks. Applications can provide
user-specified data through the pointer {@code userParam}. The context will store this pointer and will include it as one of the parameters in each call
to the callback function.
If the application has specified a callback function for receiving debug output, the implementation will call that function whenever any enabled message
is generated. The source, type, ID, and severity of the message are specified by the DEBUGPROCARB parameters {@code source}, {@code type}, {@code id},
and {@code severity}, respectively. The string representation of the message is stored in {@code message} and its length (excluding the null-terminator)
is stored in {@code length}. The parameter {@code userParam} is the user-specified parameter that was given when calling DebugMessageCallbackARB.
Applications can query the current callback function and the current user-specified parameter by obtaining the values of #DEBUG_CALLBACK_FUNCTION_ARB
and #DEBUG_CALLBACK_USER_PARAM_ARB, respectively.
Applications that specify a callback function must be aware of certain special conditions when executing code inside a callback when it is called by the
GL, regardless of the debug source.
The memory for {@code message} is owned and managed by the GL, and should only be considered valid for the duration of the function call.
The behavior of calling any GL or window system function from within the callback function is undefined and may lead to program termination.
Care must also be taken in securing debug callbacks for use with asynchronous debug output by multi-threaded GL implementations.
If #DEBUG_CALLBACK_FUNCTION_ARB is #NULL, then debug messages are instead stored in an internal message log up to some maximum number of messages as
defined by the value of #MAX_DEBUG_LOGGED_MESSAGES_ARB.
Each context stores its own message log and will only store messages generated by commands operating in that context. If the message log fills up, then
any subsequently generated messages will not be placed in the log until the message log is cleared, and will instead be discarded.
Applications can query the number of messages currently in the log by obtaining the value of #DEBUG_LOGGED_MESSAGES_ARB, and the string length
(including its null terminator) of the oldest message in the log through the value of #DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB.
""",
nullable..GLDEBUGPROCARB("callback", "a callback function that will be called when a debug message is generated"),
nullable..opaque_const_p(
"userParam",
"a user supplied pointer that will be passed on each invocation of {@code callback}"
)
)
GLuint(
"GetDebugMessageLogARB",
"""
When no debug callback is set, debug messages are stored in a debug message log. Messages can be queried from the log by calling this function.
This function fetches a maximum of {@code count} messages from the message log, and will return the number of messages successfully fetched.
Messages will be fetched from the log in order of oldest to newest. Those messages that were fetched will be removed from the log.
The sources, types, severities, IDs, and string lengths of fetched messages will be stored in the application-provided arrays {@code sources},
{@code types}, {@code severities}, {@code ids}, and {@code lengths}, respectively. The application is responsible for allocating enough space for each
array to hold up to {@code count} elements. The string representations of all fetched messages are stored in the {@code messageLog} array. If multiple
messages are fetched, their strings are concatenated into the same {@code messageLog} array and will be separated by single null terminators. The last
string in the array will also be null-terminated. The maximum size of {@code messageLog}, including the space used by all null terminators, is given by
{@code bufSize}. If {@code bufSize} is less than zero, the error #INVALID_VALUE will be generated. If a message's string, including its null
terminator, can not fully fit within the {@code messageLog} array's remaining space, then that message and any subsequent messages will not be fetched
and will remain in the log. The string lengths stored in the array {@code lengths} include the space for the null terminator of each string.
Any or all of the arrays {@code sources}, {@code types}, {@code ids}, {@code severities}, {@code lengths} and {@code messageLog} can also be null
pointers, which causes the attributes for such arrays to be discarded when messages are fetched, however those messages will still be removed from the
log. Thus to simply delete up to {@code count} messages from the message log while ignoring their attributes, the application can call the function with
null pointers for all attribute arrays. If {@code messageLog} is #NULL, the value of {@code bufSize} is ignored.
""",
GLuint("count", "the number of debug messages to retrieve from the log"),
AutoSize("messageLog")..GLsizei("bufSize", "the maximum number of characters that can be written in the {@code messageLog} array"),
Check("count")..nullable..GLenum.p("sources", "a buffer in which to place the returned message sources"),
Check("count")..nullable..GLenum.p("types", "a buffer in which to place the returned message typesd"),
Check("count")..nullable..GLuint.p("ids", "a buffer in which to place the returned message IDs"),
Check("count")..nullable..GLenum.p("severities", "a buffer in which to place the returned message severity levels"),
Check("count")..nullable..GLsizei.p("lengths", "a buffer in which to place the returned message lengths"),
nullable..GLcharUTF8.p("messageLog", "a buffer in which to place the returned messages")
)
} | bsd-3-clause | f429fbdefb99938b15d2a9e191fb1360 | 67.025362 | 160 | 0.720038 | 4.94443 | false | false | false | false |
paplorinc/intellij-community | plugins/devkit/devkit-core/src/inspections/missingApi/SinceUntilRange.kt | 3 | 743 | // 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.idea.devkit.inspections.missingApi
import com.intellij.openapi.util.BuildNumber
/**
* Holds compatibility range of a plugin, consisting of [[sinceBuild]; [untilBuild]] build numbers.
*/
data class SinceUntilRange(val sinceBuild: BuildNumber?, val untilBuild: BuildNumber?) {
fun asString() = when {
sinceBuild != null && untilBuild != null -> sinceBuild.asString() + " - " + untilBuild.asString()
sinceBuild != null -> sinceBuild.asString() + "+"
untilBuild != null -> "1.0 - $untilBuild"
else -> "all builds"
}
override fun toString() = asString()
}
| apache-2.0 | 2481424e611ef8735185030991e4ef7e | 36.15 | 140 | 0.702557 | 3.931217 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/shadow/ShadowTargetInspection.kt | 1 | 2109 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.shadow
import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection
import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.SHADOW
import com.demonwav.mcdev.platform.mixin.util.mixinTargets
import com.demonwav.mcdev.platform.mixin.util.resolveShadowTargets
import com.demonwav.mcdev.util.ifEmpty
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.codeInspection.RemoveAnnotationQuickFix
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiModifierList
class ShadowTargetInspection : MixinInspection() {
override fun getStaticDescription() = "Validates targets of @Shadow members"
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitAnnotation(annotation: PsiAnnotation) {
if (annotation.qualifiedName != SHADOW) {
return
}
val modifierList = annotation.owner as? PsiModifierList ?: return
val member = modifierList.parent as? PsiMember ?: return
val psiClass = member.containingClass ?: return
val targetClasses = psiClass.mixinTargets.ifEmpty { return }
val targets = resolveShadowTargets(annotation, targetClasses, member) ?: return
if (targets.size >= targetClasses.size) {
// Everything is fine, bye
return
}
// TODO Write quick fix and apply it for OverwriteTargetInspection and ShadowTargetInspection
holder.registerProblem(
annotation, "Cannot resolve member '${member.name}' in target class",
RemoveAnnotationQuickFix(annotation, member)
)
}
}
}
| mit | af6dbdc73f2c071dbdc9eee41b41da8d | 36 | 105 | 0.71266 | 5.081928 | false | false | false | false |
paplorinc/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/ui/GuiScriptEditor.kt | 7 | 2425 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.LightVirtualFile
import com.intellij.ui.EditorTextField
import javax.swing.JComponent
import kotlin.with
/**
* @author Sergey Karashevich
*/
class GuiScriptEditor : Disposable {
val myEditor: EditorEx
fun getPanel(): JComponent = myEditor.component
init {
val editorFactory = EditorFactory.getInstance()
val editorDocument = editorFactory.createDocument("")
myEditor = editorFactory.createEditor(editorDocument, ProjectManager.getInstance().defaultProject) as EditorEx
Disposer.register(ProjectManager.getInstance().defaultProject,this)
EditorTextField.SUPPLEMENTARY_KEY.set(myEditor, true)
myEditor.colorsScheme = EditorColorsManager.getInstance().globalScheme
with(myEditor.settings) {
isLineNumbersShown = true
isWhitespacesShown = true
isLineMarkerAreaShown = false
isIndentGuidesShown = false
isFoldingOutlineShown = false
additionalColumnsCount = 0
additionalLinesCount = 0
isRightMarginShown = true
}
val pos = LogicalPosition(0, 0)
myEditor.caretModel.moveToLogicalPosition(pos)
myEditor.highlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(LightVirtualFile("a.kt"), myEditor.colorsScheme, null)
}
override fun dispose() {
EditorFactory.getInstance().releaseEditor(myEditor)
}
} | apache-2.0 | 36f9f0144c59a1a65926853edb8d1145 | 35.757576 | 144 | 0.778969 | 4.681467 | false | false | false | false |
paplorinc/intellij-community | platform/platform-tests/testSrc/com/intellij/ide/updates/UpdateInfoParsingTest.kt | 2 | 4711 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.updates
import com.intellij.openapi.updateSettings.impl.ChannelStatus
import com.intellij.openapi.updateSettings.impl.UpdateChannel
import com.intellij.openapi.updateSettings.impl.UpdatesInfo
import com.intellij.openapi.util.JDOMUtil
import com.intellij.testFramework.fixtures.BareTestFixtureTestCase
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.IOException
import java.net.URL
import java.text.SimpleDateFormat
class UpdateInfoParsingTest : BareTestFixtureTestCase() {
@Test fun liveJetbrainsUpdateFile() {
try {
val info = load(URL("https://www.jetbrains.com/updates/updates.xml").readText())
assertNotNull(info["IC"])
}
catch (e: IOException) {
assumeTrue(e.toString(), false)
}
}
@Test fun liveAndroidUpdateFile() {
try {
val info = load(URL("https://dl.google.com/android/studio/patches/updates.xml").readText())
assertNotNull(info["AI"])
}
catch (e: IOException) {
assumeTrue(e.toString(), false)
}
}
@Test fun emptyChannels() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<code>IC</code>
</product>
</products>""".trimIndent())
val product = info["IU"]!!
assertEquals("IntelliJ IDEA", product.name)
assertEquals(0, product.channels.size)
assertEquals(product, info["IC"])
}
@Test fun oneProductOnly() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="idea90" name="IntelliJ IDEA 9 updates" status="release" url="https://www.jetbrains.com/idea/whatsnew">
<build number="95.627" version="9.0.4">
<message>IntelliJ IDEA 9.0.4 is available. Please visit https://www.jetbrains.com/idea to learn more and download it.</message>
<patch from="95.429" size="2"/>
</build>
</channel>
<channel id="IDEA10EAP" name="IntelliJ IDEA X EAP" status="eap" licensing="eap" url="http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP">
<build number="98.520" version="10" releaseDate="20110403">
<message>IntelliJ IDEA X RC is available. Please visit http://confluence.jetbrains.net/display/IDEADEV/IDEA+X+EAP to learn more.</message>
<button name="Download" url="http://www.jetbrains.com/idea" download="true"/>
</build>
</channel>
</product>
</products>""".trimIndent())
val product = info["IU"]!!
assertEquals("IntelliJ IDEA", product.name)
assertEquals(2, product.channels.size)
val channel = product.channels.find { it.id == "IDEA10EAP" }!!
assertEquals(ChannelStatus.EAP, channel.status)
assertEquals(UpdateChannel.LICENSING_EAP, channel.licensing)
assertEquals(1, channel.builds.size)
val build = channel.builds[0]
assertEquals("98.520", build.number.asStringWithoutProductCode())
assertEquals("2011-04-03", SimpleDateFormat("yyyy-MM-dd").format(build.releaseDate))
assertNotNull(build.downloadUrl)
assertEquals(0, build.patches.size)
assertEquals(1, product.channels.find { it.id == "idea90" }!!.builds[0].patches.size)
}
@Test fun targetRanges() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="IDEA_EAP" status="eap">
<build number="2016.2.123" version="2016.2" targetSince="0" targetUntil="145.*"/>
<build number="2016.2.123" version="2016.2" targetSince="2016.1" targetUntil="2016.1.*"/>
<build number="2016.1.11" version="2016.1"/>
</channel>
</product>
</products>""".trimIndent())
assertEquals(2, info["IU"]!!.channels[0].builds.count { it.target != null })
}
@Test fun fullBuildNumbers() {
val info = load("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
<channel id="IDEA_EAP" status="eap">
<build number="162.100" fullNumber="162.100.1" version="2016.2">
<patch from="162.99" fullFrom="162.99.2" size="1"/>
</build>
</channel>
</product>
</products>""".trimIndent())
val buildInfo = info["IU"]!!.channels[0].builds[0]
assertEquals("162.100.1", buildInfo.number.asStringWithoutProductCode())
assertEquals("162.99.2", buildInfo.patches[0].fromBuild.asStringWithoutProductCode())
}
private fun load(text: String) = UpdatesInfo(JDOMUtil.load(text))
} | apache-2.0 | 73808749c0dbf0682968b0323d958c9e | 37.308943 | 155 | 0.643176 | 3.952181 | false | true | false | false |
google/intellij-community | plugins/gradle/java/src/codeInspection/fix/GradleTaskToRegisterFix.kt | 3 | 3054 | // 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.plugins.gradle.codeInspection.fix
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.util.castSafelyTo
import org.jetbrains.plugins.gradle.codeInspection.GradleInspectionBundle
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.stringValue
class GradleTaskToRegisterFix : LocalQuickFix {
override fun getFamilyName(): String {
return GroovyBundle.message("intention.family.name.replace.keywords")
}
override fun getName(): String {
return GradleInspectionBundle.message("intention.name.use.tasks.register")
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callParent = descriptor.psiElement.parentOfType<GrMethodCall>() ?: return
val firstArgument = inferFirstArgument(callParent) ?: return
val secondArgument = inferSecondArgument(callParent)
val representation = "tasks.register" + when (secondArgument) {
null -> "('$firstArgument')"
is GrClosableBlock -> "('$firstArgument') ${secondArgument.text}"
else -> "('$firstArgument', ${secondArgument.text})"
}
val newCall = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(representation)
callParent.replace(newCall)
}
private fun inferFirstArgument(callParent: GrMethodCall) : String? {
val argument = callParent.expressionArguments.firstOrNull() ?: return null
return when (argument) {
is GrMethodCallExpression -> argument.invokedExpression.text
is GrLiteral -> argument.stringValue()
is GrReferenceExpression -> argument.text
else -> null
}
}
private fun inferSecondArgument(callParent: GrMethodCall, inspectFirstArg: Boolean = true) : PsiElement? {
val closureArgument = callParent.closureArguments.firstOrNull()
if (closureArgument != null) {
return closureArgument
}
val argument = callParent.expressionArguments.getOrNull(1)
if (argument != null) {
return argument
}
if (inspectFirstArg) {
val firstArgument = callParent.expressionArguments.firstOrNull()?.castSafelyTo<GrMethodCall>() ?: return null
return inferSecondArgument(firstArgument, false)
}
return null
}
} | apache-2.0 | f554959afe53e1494803b8992c842bb2 | 44.597015 | 120 | 0.776686 | 4.734884 | false | false | false | false |
dkhmelenko/draw2fashion | app/src/main/java/org/hackzurich2017/draw2fashion/RecognizedImagesActivity.kt | 1 | 1258 | package org.hackzurich2017.draw2fashion
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_products.*
import kotlinx.android.synthetic.main.activity_recognized_images.*
import org.hackzurich2017.draw2fashion.draw2fashion.R
class RecognizedImagesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recognized_images)
initToolbar()
val images = intent.getStringArrayListExtra("RECOGNIZED_IMAGES")
recognizedImages.layoutManager = GridLayoutManager(this, 3)
recognizedImages.itemAnimator = DefaultItemAnimator()
recognizedImages.adapter = RecognizedImagesAdapter(images)
}
private fun initToolbar() {
val actionBar = getSupportActionBar()
actionBar?.setDisplayHomeAsUpEnabled(true)
actionBar?.setDisplayShowHomeEnabled(true)
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
}
| apache-2.0 | 6d7d92961fbfcda036b6b318a7310d99 | 33 | 72 | 0.763116 | 4.857143 | false | false | false | false |
google/iosched | shared/src/main/java/com/google/samples/apps/iosched/shared/util/TimeUtils.kt | 3 | 7359 | /*
* Copyright 2018 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
*
* 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.samples.apps.iosched.shared.util
import androidx.annotation.StringRes
import com.google.samples.apps.iosched.model.ConferenceDay
import com.google.samples.apps.iosched.model.Session
import com.google.samples.apps.iosched.shared.BuildConfig
import com.google.samples.apps.iosched.shared.R
import com.google.samples.apps.iosched.shared.time.DefaultTimeProvider.now
import org.threeten.bp.ZoneId
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter
object TimeUtils {
val CONFERENCE_TIMEZONE: ZoneId = ZoneId.of(BuildConfig.CONFERENCE_TIMEZONE)
val ConferenceDays = listOf(
ConferenceDay(
ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY1_START),
ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY1_END)
),
ConferenceDay(
ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY2_START),
ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY2_END)
),
ConferenceDay(
ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY3_START),
ZonedDateTime.parse(BuildConfig.CONFERENCE_DAY3_END)
)
)
enum class SessionRelativeTimeState { BEFORE, DURING, AFTER, UNKNOWN }
/** Determine whether the current time is before, during, or after a Session's time slot **/
fun getSessionState(
session: Session?,
currentTime: ZonedDateTime = ZonedDateTime.now()
): SessionRelativeTimeState {
return when {
session == null -> SessionRelativeTimeState.UNKNOWN
currentTime < session.startTime -> SessionRelativeTimeState.BEFORE
currentTime > session.endTime -> SessionRelativeTimeState.AFTER
else -> SessionRelativeTimeState.DURING
}
}
/** Return a string resource to use for the label of this day, e.g. "Tuesday, May 7". */
@StringRes
fun getLabelResForDay(day: ConferenceDay, inConferenceTimeZone: Boolean = true): Int {
return when (day) {
ConferenceDays[0] -> if (inConferenceTimeZone) R.string.day1_day_date else R.string.day1
ConferenceDays[1] -> if (inConferenceTimeZone) R.string.day2_day_date else R.string.day2
ConferenceDays[2] -> if (inConferenceTimeZone) R.string.day3_day_date else R.string.day3
else -> throw IllegalArgumentException("Unknown ConferenceDay")
}
}
/** Return a short string resource to use for the label of this day, e.g. "May 7". */
@StringRes
fun getShortLabelResForDay(day: ConferenceDay, inConferenceTimeZone: Boolean = true): Int {
return when (day) {
ConferenceDays[0] -> if (inConferenceTimeZone) R.string.day1_date else R.string.day1
ConferenceDays[1] -> if (inConferenceTimeZone) R.string.day2_date else R.string.day2
ConferenceDays[2] -> if (inConferenceTimeZone) R.string.day3_date else R.string.day3
else -> throw IllegalArgumentException("Unknown ConferenceDay")
}
}
/** Return a string resource to use for the nearest day to the given time. */
@StringRes
fun getLabelResForTime(time: ZonedDateTime, inConferenceTimeZone: Boolean = true): Int {
return when {
time.isBefore(ConferenceDays[0].start) ->
if (inConferenceTimeZone) R.string.day0_day_date else R.string.day0
time.isBefore(ConferenceDays[1].start) ->
if (inConferenceTimeZone) R.string.day1_day_date else R.string.day1
time.isBefore(ConferenceDays[2].start) ->
if (inConferenceTimeZone) R.string.day2_day_date else R.string.day2
else -> if (inConferenceTimeZone) R.string.day3_day_date else R.string.day3
}
}
fun zonedTime(time: ZonedDateTime, zoneId: ZoneId = ZoneId.systemDefault()): ZonedDateTime {
return ZonedDateTime.ofInstant(time.toInstant(), zoneId)
}
fun isConferenceTimeZone(zoneId: ZoneId = ZoneId.systemDefault()): Boolean {
return zoneId == CONFERENCE_TIMEZONE
}
fun abbreviatedTimeString(startTime: ZonedDateTime): String {
return DateTimeFormatter.ofPattern("EEE, MMM d").format(startTime)
}
/** Format a time to show month and day, e.g. "May 7" */
fun dateString(startTime: ZonedDateTime): String {
return DateTimeFormatter.ofPattern("MMM d").format(startTime)
}
/** Format a time to show month, day, and time, e.g. "May 7, 10:00 AM" */
fun dateTimeString(startTime: ZonedDateTime): String {
return DateTimeFormatter.ofPattern("MMM d, h:mm a").format(startTime)
}
fun timeString(
startTime: ZonedDateTime,
endTime: ZonedDateTime,
withDate: Boolean = true
): String {
val sb = StringBuilder()
val dateFormat = if (withDate) "EEE, MMM d, h:mm " else "h:mm "
sb.append(DateTimeFormatter.ofPattern(dateFormat).format(startTime))
val startTimeMeridiem: String = DateTimeFormatter.ofPattern("a").format(startTime)
val endTimeMeridiem: String = DateTimeFormatter.ofPattern("a").format(endTime)
if (startTimeMeridiem != endTimeMeridiem) {
sb.append(startTimeMeridiem).append(" ")
}
sb.append(DateTimeFormatter.ofPattern("- h:mm a").format(endTime))
return sb.toString()
}
fun abbreviatedDayForAr(startTime: ZonedDateTime): String {
return DateTimeFormatter.ofPattern("MM/dd").format(startTime)
}
fun abbreviatedTimeForAr(startTime: ZonedDateTime): String {
return DateTimeFormatter.ofPattern("HH:mm").format(startTime)
}
fun abbreviatedTimeForAnnouncements(startTime: ZonedDateTime): String {
val now = ZonedDateTime.now(startTime.zone)
val dateFormat = if (startTime.dayOfMonth == now.dayOfMonth) "h:mm a" else "MMM d, h:mm a"
return DateTimeFormatter.ofPattern(dateFormat).format(startTime)
}
fun conferenceHasStarted(): Boolean {
return ZonedDateTime.now().isAfter(ConferenceDays.first().start)
}
fun conferenceHasEnded(): Boolean {
return ZonedDateTime.now().isAfter(ConferenceDays.last().end)
}
// TODO(b/132697497) replace with a UseCase
fun getKeynoteStartTime(): ZonedDateTime {
return ConferenceDays.first().start.plusHours(3L)
}
/**
* @return the current day of the conference. Returns null if the conference is yet to start or
* has ended.
*/
fun getCurrentConferenceDay(): ConferenceDay? {
val now = ZonedDateTime.now()
if (now.isBefore(ConferenceDays.first().start)) {
return null
}
return ConferenceDays.firstOrNull { now.isBefore(it.end) }
}
fun getConferenceEndTime() = ConferenceDays.last().end
}
| apache-2.0 | 9135720b7068b86030a9fcf7995197cf | 39.657459 | 100 | 0.681478 | 4.364769 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.