content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.ee
import android.app.Activity
import androidx.annotation.AnyThread
import androidx.annotation.UiThread
/**
* Created by Zinge on 6/1/16.
*/
interface IPlugin {
/**
* Called when the main activity has been created.
*/
@UiThread
fun onCreate(activity: Activity)
/**
* Called when the main activity has been started.
*/
@UiThread
fun onStart()
/**
* Called when the main activity has been stopped.
*/
@UiThread
fun onStop()
/**
* Called when the main activity has been resumed.
*/
@UiThread
fun onResume()
/**
* Called when the main activity has been paused.
*/
@UiThread
fun onPause()
/**
* Called when the main activity has been destroyed.
*/
@UiThread
fun onDestroy()
/**
* Called when the application has been destroyed.
*/
@AnyThread
fun destroy()
} | src/android/core/src/main/java/com/ee/IPlugin.kt | 585548851 |
package nl.rsdt.japp.jotial.maps.wrapper
import android.graphics.Bitmap
import com.google.android.gms.maps.model.LatLng
import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier
/**
* Created by mattijn on 08/08/17.
*/
interface IMarker {
var title: String
var position: LatLng
var isVisible: Boolean
val id: String
fun showInfoWindow()
fun remove()
fun setOnClickListener(onClickListener: IMarker.OnClickListener?)
fun setIcon(drawableHunt: Int)
fun setIcon(bitmap: Bitmap?)
fun setRotation(rotation: Float)
interface OnClickListener {
fun OnClick(m: IMarker): Boolean
}
val identifier: MarkerIdentifier?
}
| app/src/main/java/nl/rsdt/japp/jotial/maps/wrapper/IMarker.kt | 3555628186 |
package com.applivery.base.di
import android.content.Context
import android.content.SharedPreferences
import com.applivery.base.util.AppliveryContentProvider
internal object InjectorUtils {
fun provideSharedPreferences(): SharedPreferences {
return AppliveryContentProvider.context
.getSharedPreferences("applivery-data", Context.MODE_PRIVATE)
}
}
| applivery-base/src/main/java/com/applivery/base/di/InjectorUtils.kt | 2279426392 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.layout
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.layout.IntrinsicMeasurable
import androidx.compose.ui.layout.IntrinsicMeasureScope
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasurePolicy
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.node.Ref
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.InspectableValue
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.ValueElement
import androidx.compose.ui.platform.isDebugInspectorInfoEnabled
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.constrain
import androidx.compose.ui.unit.dp
import com.google.common.truth.Truth.assertThat
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.FlakyTest
import androidx.test.filters.MediumTest
import org.junit.Assert.assertNotEquals
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt
@MediumTest
@RunWith(AndroidJUnit4::class)
class SizeTest : LayoutTest() {
@Before
fun before() {
isDebugInspectorInfoEnabled = true
}
@After
fun after() {
isDebugInspectorInfoEnabled = false
}
@Test
fun testPreferredSize_withWidthSizeModifiers() = with(density) {
val sizeDp = 50.toDp()
val sizeIpx = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(6)
val size = MutableList(6) { Ref<IntSize>() }
val position = MutableList(6) { Ref<Offset>() }
show {
Box {
Column {
Container(
Modifier.widthIn(min = sizeDp, max = sizeDp * 2)
.height(sizeDp)
.saveLayoutInfo(size[0], position[0], positionedLatch)
) {
}
Container(
Modifier.widthIn(max = sizeDp * 2)
.height(sizeDp)
.saveLayoutInfo(size[1], position[1], positionedLatch)
) {
}
Container(
Modifier.widthIn(min = sizeDp)
.height(sizeDp)
.saveLayoutInfo(size[2], position[2], positionedLatch)
) {
}
Container(
Modifier.widthIn(max = sizeDp)
.widthIn(min = sizeDp * 2)
.height(sizeDp)
.saveLayoutInfo(size[3], position[3], positionedLatch)
) {
}
Container(
Modifier.widthIn(min = sizeDp * 2)
.widthIn(max = sizeDp)
.height(sizeDp)
.saveLayoutInfo(size[4], position[4], positionedLatch)
) {
}
Container(
Modifier.size(sizeDp)
.saveLayoutInfo(size[5], position[5], positionedLatch)
) {
}
}
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(sizeIpx, sizeIpx), size[0].value)
assertEquals(Offset.Zero, position[0].value)
assertEquals(IntSize(0, sizeIpx), size[1].value)
assertEquals(Offset(0f, sizeIpx.toFloat()), position[1].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[2].value)
assertEquals(Offset(0f, (sizeIpx * 2).toFloat()), position[2].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[3].value)
assertEquals(Offset(0f, (sizeIpx * 3).toFloat()), position[3].value)
assertEquals(IntSize((sizeDp * 2).roundToPx(), sizeIpx), size[4].value)
assertEquals(Offset(0f, (sizeIpx * 4).toFloat()), position[4].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[5].value)
assertEquals(Offset(0f, (sizeIpx * 5).toFloat()), position[5].value)
}
@Test
fun testPreferredSize_withHeightSizeModifiers() = with(density) {
val sizeDp = 10.toDp()
val sizeIpx = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(6)
val size = MutableList(6) { Ref<IntSize>() }
val position = MutableList(6) { Ref<Offset>() }
show {
Box {
Row {
Container(
Modifier.heightIn(min = sizeDp, max = sizeDp * 2)
.width(sizeDp)
.saveLayoutInfo(size[0], position[0], positionedLatch)
) {
}
Container(
Modifier.heightIn(max = sizeDp * 2)
.width(sizeDp)
.saveLayoutInfo(size[1], position[1], positionedLatch)
) {
}
Container(
Modifier.heightIn(min = sizeDp)
.width(sizeDp)
.saveLayoutInfo(size[2], position[2], positionedLatch)
) {
}
Container(
Modifier.heightIn(max = sizeDp)
.heightIn(min = sizeDp * 2)
.width(sizeDp)
.saveLayoutInfo(size[3], position[3], positionedLatch)
) {
}
Container(
Modifier.heightIn(min = sizeDp * 2)
.heightIn(max = sizeDp)
.width(sizeDp)
.saveLayoutInfo(size[4], position[4], positionedLatch)
) {
}
Container(
Modifier.height(sizeDp).then(Modifier.width(sizeDp)).then(
Modifier.saveLayoutInfo(size[5], position[5], positionedLatch)
)
) {
}
}
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(sizeIpx, sizeIpx), size[0].value)
assertEquals(Offset.Zero, position[0].value)
assertEquals(IntSize(sizeIpx, 0), size[1].value)
assertEquals(Offset(sizeIpx.toFloat(), 0f), position[1].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[2].value)
assertEquals(Offset((sizeIpx * 2).toFloat(), 0f), position[2].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[3].value)
assertEquals(Offset((sizeIpx * 3).toFloat(), 0f), position[3].value)
assertEquals(IntSize(sizeIpx, (sizeDp * 2).roundToPx()), size[4].value)
assertEquals(Offset((sizeIpx * 4).toFloat(), 0f), position[4].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[5].value)
assertEquals(Offset((sizeIpx * 5).toFloat(), 0f), position[5].value)
}
@Test
fun testPreferredSize_withSizeModifiers() = with(density) {
val sizeDp = 50.toDp()
val sizeIpx = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(5)
val size = MutableList(5) { Ref<IntSize>() }
val position = MutableList(5) { Ref<Offset>() }
show {
Box {
Row {
val maxSize = sizeDp * 2
Container(
Modifier.sizeIn(maxWidth = maxSize, maxHeight = maxSize)
.sizeIn(minWidth = sizeDp, minHeight = sizeDp)
.saveLayoutInfo(size[0], position[0], positionedLatch)
) {
}
Container(
Modifier.sizeIn(maxWidth = sizeDp, maxHeight = sizeDp)
.sizeIn(minWidth = sizeDp * 2, minHeight = sizeDp)
.saveLayoutInfo(size[1], position[1], positionedLatch)
) {
}
val maxSize1 = sizeDp * 2
Container(
Modifier.sizeIn(minWidth = sizeDp, minHeight = sizeDp)
.sizeIn(maxWidth = maxSize1, maxHeight = maxSize1)
.saveLayoutInfo(size[2], position[2], positionedLatch)
) {
}
val minSize = sizeDp * 2
Container(
Modifier.sizeIn(minWidth = minSize, minHeight = minSize)
.sizeIn(maxWidth = sizeDp, maxHeight = sizeDp)
.saveLayoutInfo(size[3], position[3], positionedLatch)
) {
}
Container(
Modifier.size(sizeDp)
.saveLayoutInfo(size[4], position[4], positionedLatch)
) {
}
}
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(sizeIpx, sizeIpx), size[0].value)
assertEquals(Offset.Zero, position[0].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[1].value)
assertEquals(Offset(sizeIpx.toFloat(), 0f), position[1].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[2].value)
assertEquals(Offset((sizeIpx * 2).toFloat(), 0f), position[2].value)
assertEquals(IntSize(sizeIpx * 2, sizeIpx * 2), size[3].value)
assertEquals(Offset((sizeIpx * 3).toFloat(), 0f), position[3].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[4].value)
assertEquals(Offset((sizeIpx * 5).toFloat(), 0f), position[4].value)
}
@Test
fun testPreferredSizeModifiers_respectMaxConstraint() = with(density) {
val sizeDp = 100.toDp()
val size = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(2)
val constrainedBoxSize = Ref<IntSize>()
val childSize = Ref<IntSize>()
val childPosition = Ref<Offset>()
show {
Box {
Container(width = sizeDp, height = sizeDp) {
Container(
Modifier.width(sizeDp * 2)
.height(sizeDp * 3)
.onGloballyPositioned { coordinates: LayoutCoordinates ->
constrainedBoxSize.value = coordinates.size
positionedLatch.countDown()
}
) {
Container(
expanded = true,
modifier = Modifier.saveLayoutInfo(
size = childSize,
position = childPosition,
positionedLatch = positionedLatch
)
) {
}
}
}
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(size, size), constrainedBoxSize.value)
assertEquals(IntSize(size, size), childSize.value)
assertEquals(Offset.Zero, childPosition.value)
}
@Test
fun testMaxModifiers_withInfiniteValue() = with(density) {
val sizeDp = 20.toDp()
val sizeIpx = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(4)
val size = MutableList(4) { Ref<IntSize>() }
val position = MutableList(4) { Ref<Offset>() }
show {
Box {
Row {
Container(Modifier.widthIn(max = Dp.Infinity)) {
Container(
width = sizeDp, height = sizeDp,
modifier = Modifier.saveLayoutInfo(
size[0], position[0],
positionedLatch
)
) {
}
}
Container(Modifier.heightIn(max = Dp.Infinity)) {
Container(
width = sizeDp, height = sizeDp,
modifier = Modifier.saveLayoutInfo(
size[1],
position[1],
positionedLatch
)
) {
}
}
Container(
Modifier.width(sizeDp)
.height(sizeDp)
.widthIn(max = Dp.Infinity)
.heightIn(max = Dp.Infinity)
.saveLayoutInfo(size[2], position[2], positionedLatch)
) {
}
Container(
Modifier.sizeIn(
maxWidth = Dp.Infinity,
maxHeight = Dp.Infinity
)
) {
Container(
width = sizeDp,
height = sizeDp,
modifier = Modifier.saveLayoutInfo(
size[3],
position[3],
positionedLatch
)
) {
}
}
}
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(sizeIpx, sizeIpx), size[0].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[1].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[2].value)
assertEquals(IntSize(sizeIpx, sizeIpx), size[3].value)
}
@Test
fun testSize_smallerInLarger() = with(density) {
val sizeIpx = 64
val sizeDp = sizeIpx.toDp()
val positionedLatch = CountDownLatch(1)
val boxSize = Ref<IntSize>()
val boxPosition = Ref<Offset>()
show {
Box(
Modifier.wrapContentSize(Alignment.TopStart)
.requiredSize(sizeDp * 2)
.requiredSize(sizeDp)
.saveLayoutInfo(boxSize, boxPosition, positionedLatch)
)
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(sizeIpx, sizeIpx), boxSize.value)
assertEquals(
Offset(
(sizeIpx / 2).toFloat(),
(sizeIpx / 2).toFloat()
),
boxPosition.value
)
}
@Test
fun testSize_smallerBoxInLargerBox() = with(density) {
val sizeIpx = 64
val sizeDp = sizeIpx.toDp()
val positionedLatch = CountDownLatch(1)
val boxSize = Ref<IntSize>()
val boxPosition = Ref<Offset>()
show {
Box(
Modifier.wrapContentSize(Alignment.TopStart).requiredSize(sizeDp * 2),
propagateMinConstraints = true
) {
Box(
Modifier.requiredSize(sizeDp)
.onGloballyPositioned {
boxSize.value = it.size
boxPosition.value = it.positionInRoot()
positionedLatch.countDown()
}
)
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(sizeIpx, sizeIpx), boxSize.value)
assertEquals(
Offset(
(sizeIpx / 2).toFloat(),
(sizeIpx / 2).toFloat()
),
boxPosition.value
)
}
@Test
fun testSize_largerInSmaller() = with(density) {
val sizeIpx = 64
val sizeDp = sizeIpx.toDp()
val positionedLatch = CountDownLatch(1)
val boxSize = Ref<IntSize>()
val boxPosition = Ref<Offset>()
show {
Box(
Modifier.wrapContentSize(Alignment.TopStart)
.requiredSize(sizeDp)
.requiredSize(sizeDp * 2)
.saveLayoutInfo(boxSize, boxPosition, positionedLatch)
)
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(sizeIpx * 2, sizeIpx * 2), boxSize.value)
assertEquals(
Offset((-sizeIpx / 2).toFloat(), (-sizeIpx / 2).toFloat()),
boxPosition.value
)
}
@Test
fun testMeasurementConstraints_preferredSatisfiable() = with(density) {
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.width(20.toDp()),
Constraints(20, 20, 15, 35)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.height(20.toDp()),
Constraints(10, 30, 20, 20)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.size(20.toDp()),
Constraints(20, 20, 20, 20)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.widthIn(20.toDp(), 25.toDp()),
Constraints(20, 25, 15, 35)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.heightIn(20.toDp(), 25.toDp()),
Constraints(10, 30, 20, 25)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.sizeIn(20.toDp(), 20.toDp(), 25.toDp(), 25.toDp()),
Constraints(20, 25, 20, 25)
)
}
@Test
fun testMeasurementConstraints_preferredUnsatisfiable() = with(density) {
assertConstraints(
Constraints(20, 40, 15, 35),
Modifier.width(15.toDp()),
Constraints(20, 20, 15, 35)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.height(10.toDp()),
Constraints(10, 30, 15, 15)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.size(40.toDp()),
Constraints(30, 30, 35, 35)
)
assertConstraints(
Constraints(20, 30, 15, 35),
Modifier.widthIn(10.toDp(), 15.toDp()),
Constraints(20, 20, 15, 35)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.heightIn(5.toDp(), 10.toDp()),
Constraints(10, 30, 15, 15)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.sizeIn(40.toDp(), 50.toDp(), 45.toDp(), 55.toDp()),
Constraints(30, 30, 35, 35)
)
}
@Test
fun testMeasurementConstraints_compulsorySatisfiable() = with(density) {
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredWidth(20.toDp()),
Constraints(20, 20, 15, 35)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredHeight(20.toDp()),
Constraints(10, 30, 20, 20)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredSize(20.toDp()),
Constraints(20, 20, 20, 20)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredWidthIn(20.toDp(), 25.toDp()),
Constraints(20, 25, 15, 35)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredHeightIn(20.toDp(), 25.toDp()),
Constraints(10, 30, 20, 25)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredSizeIn(20.toDp(), 20.toDp(), 25.toDp(), 25.toDp()),
Constraints(20, 25, 20, 25)
)
}
@Test
fun testMeasurementConstraints_compulsoryUnsatisfiable() = with(density) {
assertConstraints(
Constraints(20, 40, 15, 35),
Modifier.requiredWidth(15.toDp()),
Constraints(15, 15, 15, 35)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredHeight(10.toDp()),
Constraints(10, 30, 10, 10)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredSize(40.toDp()),
Constraints(40, 40, 40, 40)
)
assertConstraints(
Constraints(20, 30, 15, 35),
Modifier.requiredWidthIn(10.toDp(), 15.toDp()),
Constraints(10, 15, 15, 35)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredHeightIn(5.toDp(), 10.toDp()),
Constraints(10, 30, 5, 10)
)
assertConstraints(
Constraints(10, 30, 15, 35),
Modifier.requiredSizeIn(40.toDp(), 50.toDp(), 45.toDp(), 55.toDp()),
Constraints(40, 45, 50, 55)
)
// When one dimension is unspecified and the other contradicts the incoming constraint.
assertConstraints(
Constraints(10, 10, 10, 10),
Modifier.requiredSizeIn(20.toDp(), 30.toDp(), Dp.Unspecified, Dp.Unspecified),
Constraints(20, 20, 30, 30)
)
assertConstraints(
Constraints(40, 40, 40, 40),
Modifier.requiredSizeIn(Dp.Unspecified, Dp.Unspecified, 20.toDp(), 30.toDp()),
Constraints(20, 20, 30, 30)
)
}
@Test
fun testDefaultMinSize() = with(density) {
val latch = CountDownLatch(3)
show {
// Constraints are applied.
Layout(
{},
Modifier.wrapContentSize()
.requiredSizeIn(maxWidth = 30.toDp(), maxHeight = 40.toDp())
.defaultMinSize(minWidth = 10.toDp(), minHeight = 20.toDp())
) { _, constraints ->
assertEquals(10, constraints.minWidth)
assertEquals(20, constraints.minHeight)
assertEquals(30, constraints.maxWidth)
assertEquals(40, constraints.maxHeight)
latch.countDown()
layout(0, 0) {}
}
// Constraints are not applied.
Layout(
{},
Modifier.requiredSizeIn(
minWidth = 10.toDp(),
minHeight = 20.toDp(),
maxWidth = 100.toDp(),
maxHeight = 110.toDp()
).defaultMinSize(
minWidth = 50.toDp(),
minHeight = 50.toDp()
)
) { _, constraints ->
assertEquals(10, constraints.minWidth)
assertEquals(20, constraints.minHeight)
assertEquals(100, constraints.maxWidth)
assertEquals(110, constraints.maxHeight)
latch.countDown()
layout(0, 0) {}
}
// Defaults values are not changing.
Layout(
{},
Modifier.requiredSizeIn(
minWidth = 10.toDp(),
minHeight = 20.toDp(),
maxWidth = 100.toDp(),
maxHeight = 110.toDp()
).defaultMinSize()
) { _, constraints ->
assertEquals(10, constraints.minWidth)
assertEquals(20, constraints.minHeight)
assertEquals(100, constraints.maxWidth)
assertEquals(110, constraints.maxHeight)
latch.countDown()
layout(0, 0) {}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
}
@Test
fun testDefaultMinSize_withCoercingMaxConstraints() = with(density) {
val latch = CountDownLatch(1)
show {
Layout(
{},
Modifier.wrapContentSize()
.requiredSizeIn(maxWidth = 30.toDp(), maxHeight = 40.toDp())
.defaultMinSize(minWidth = 70.toDp(), minHeight = 80.toDp())
) { _, constraints ->
assertEquals(30, constraints.minWidth)
assertEquals(40, constraints.minHeight)
assertEquals(30, constraints.maxWidth)
assertEquals(40, constraints.maxHeight)
latch.countDown()
layout(0, 0) {}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
}
@Test
fun testMinWidthModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.widthIn(min = 10.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(10, minIntrinsicWidth(0))
assertEquals(10, minIntrinsicWidth(5))
assertEquals(50, minIntrinsicWidth(50))
assertEquals(10, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(0, minIntrinsicHeight(0))
assertEquals(35, minIntrinsicHeight(35))
assertEquals(50, minIntrinsicHeight(50))
assertEquals(0, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(10, maxIntrinsicWidth(0))
assertEquals(10, maxIntrinsicWidth(5))
assertEquals(50, maxIntrinsicWidth(50))
assertEquals(10, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(0, maxIntrinsicHeight(0))
assertEquals(35, maxIntrinsicHeight(35))
assertEquals(50, maxIntrinsicHeight(50))
assertEquals(0, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testMaxWidthModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.widthIn(max = 20.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(15, minIntrinsicWidth(15))
assertEquals(20, minIntrinsicWidth(50))
assertEquals(0, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(0, minIntrinsicHeight(0))
assertEquals(15, minIntrinsicHeight(15))
assertEquals(50, minIntrinsicHeight(50))
assertEquals(0, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(0, maxIntrinsicWidth(0))
assertEquals(15, maxIntrinsicWidth(15))
assertEquals(20, maxIntrinsicWidth(50))
assertEquals(0, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(0, maxIntrinsicHeight(0))
assertEquals(15, maxIntrinsicHeight(15))
assertEquals(50, maxIntrinsicHeight(50))
assertEquals(0, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testMinHeightModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.heightIn(min = 30.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(15, minIntrinsicWidth(15))
assertEquals(50, minIntrinsicWidth(50))
assertEquals(0, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(30, minIntrinsicHeight(0))
assertEquals(30, minIntrinsicHeight(15))
assertEquals(50, minIntrinsicHeight(50))
assertEquals(30, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(0, maxIntrinsicWidth(0))
assertEquals(15, maxIntrinsicWidth(15))
assertEquals(50, maxIntrinsicWidth(50))
assertEquals(0, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(30, maxIntrinsicHeight(0))
assertEquals(30, maxIntrinsicHeight(15))
assertEquals(50, maxIntrinsicHeight(50))
assertEquals(30, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testMaxHeightModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.heightIn(max = 40.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(15, minIntrinsicWidth(15))
assertEquals(50, minIntrinsicWidth(50))
assertEquals(0, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(0, minIntrinsicHeight(0))
assertEquals(15, minIntrinsicHeight(15))
assertEquals(40, minIntrinsicHeight(50))
assertEquals(0, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(0, maxIntrinsicWidth(0))
assertEquals(15, maxIntrinsicWidth(15))
assertEquals(50, maxIntrinsicWidth(50))
assertEquals(0, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(0, maxIntrinsicHeight(0))
assertEquals(15, maxIntrinsicHeight(15))
assertEquals(40, maxIntrinsicHeight(50))
assertEquals(0, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testWidthModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.width(10.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(10, minIntrinsicWidth(0))
assertEquals(10, minIntrinsicWidth(10))
assertEquals(10, minIntrinsicWidth(75))
assertEquals(10, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(0, minIntrinsicHeight(0))
assertEquals(35, minIntrinsicHeight(35))
assertEquals(70, minIntrinsicHeight(70))
assertEquals(0, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(10, maxIntrinsicWidth(0))
assertEquals(10, maxIntrinsicWidth(15))
assertEquals(10, maxIntrinsicWidth(75))
assertEquals(10, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(0, maxIntrinsicHeight(0))
assertEquals(35, maxIntrinsicHeight(35))
assertEquals(70, maxIntrinsicHeight(70))
assertEquals(0, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testHeightModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.height(10.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(15, minIntrinsicWidth(15))
assertEquals(75, minIntrinsicWidth(75))
assertEquals(0, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(10, minIntrinsicHeight(0))
assertEquals(10, minIntrinsicHeight(35))
assertEquals(10, minIntrinsicHeight(70))
assertEquals(10, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(0, maxIntrinsicWidth(0))
assertEquals(15, maxIntrinsicWidth(15))
assertEquals(75, maxIntrinsicWidth(75))
assertEquals(0, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(10, maxIntrinsicHeight(0))
assertEquals(10, maxIntrinsicHeight(35))
assertEquals(10, maxIntrinsicHeight(70))
assertEquals(10, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testWidthHeightModifiers_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(
Modifier.sizeIn(
minWidth = 10.toDp(),
maxWidth = 20.toDp(),
minHeight = 30.toDp(),
maxHeight = 40.toDp()
)
) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(10, minIntrinsicWidth(0))
assertEquals(15, minIntrinsicWidth(15))
assertEquals(20, minIntrinsicWidth(50))
assertEquals(10, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(30, minIntrinsicHeight(0))
assertEquals(35, minIntrinsicHeight(35))
assertEquals(40, minIntrinsicHeight(50))
assertEquals(30, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(10, maxIntrinsicWidth(0))
assertEquals(15, maxIntrinsicWidth(15))
assertEquals(20, maxIntrinsicWidth(50))
assertEquals(10, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(30, maxIntrinsicHeight(0))
assertEquals(35, maxIntrinsicHeight(35))
assertEquals(40, maxIntrinsicHeight(50))
assertEquals(30, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testMinSizeModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.sizeIn(minWidth = 20.toDp(), minHeight = 30.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(20, minIntrinsicWidth(0))
assertEquals(20, minIntrinsicWidth(10))
assertEquals(50, minIntrinsicWidth(50))
assertEquals(20, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(30, minIntrinsicHeight(0))
assertEquals(30, minIntrinsicHeight(10))
assertEquals(50, minIntrinsicHeight(50))
assertEquals(30, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(20, maxIntrinsicWidth(0))
assertEquals(20, maxIntrinsicWidth(10))
assertEquals(50, maxIntrinsicWidth(50))
assertEquals(20, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(30, maxIntrinsicHeight(0))
assertEquals(30, maxIntrinsicHeight(10))
assertEquals(50, maxIntrinsicHeight(50))
assertEquals(30, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testMaxSizeModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.sizeIn(maxWidth = 40.toDp(), maxHeight = 50.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(15, minIntrinsicWidth(15))
assertEquals(40, minIntrinsicWidth(50))
assertEquals(0, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(0, minIntrinsicHeight(0))
assertEquals(15, minIntrinsicHeight(15))
assertEquals(50, minIntrinsicHeight(75))
assertEquals(0, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(0, maxIntrinsicWidth(0))
assertEquals(15, maxIntrinsicWidth(15))
assertEquals(40, maxIntrinsicWidth(50))
assertEquals(0, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(0, maxIntrinsicHeight(0))
assertEquals(15, maxIntrinsicHeight(15))
assertEquals(50, maxIntrinsicHeight(75))
assertEquals(0, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testPreferredSizeModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.size(40.toDp(), 50.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(40, minIntrinsicWidth(0))
assertEquals(40, minIntrinsicWidth(35))
assertEquals(40, minIntrinsicWidth(75))
assertEquals(40, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(50, minIntrinsicHeight(0))
assertEquals(50, minIntrinsicHeight(35))
assertEquals(50, minIntrinsicHeight(70))
assertEquals(50, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(40, maxIntrinsicWidth(0))
assertEquals(40, maxIntrinsicWidth(35))
assertEquals(40, maxIntrinsicWidth(75))
assertEquals(40, maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(50, maxIntrinsicHeight(0))
assertEquals(50, maxIntrinsicHeight(35))
assertEquals(50, maxIntrinsicHeight(70))
assertEquals(50, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testFillModifier_correctSize() = with(density) {
val parentWidth = 100
val parentHeight = 80
val parentModifier = Modifier.requiredSize(parentWidth.toDp(), parentHeight.toDp())
val childWidth = 40
val childHeight = 30
val childModifier = Modifier.size(childWidth.toDp(), childHeight.toDp())
assertEquals(
IntSize(childWidth, childHeight),
calculateSizeFor(parentModifier, childModifier)
)
assertEquals(
IntSize(parentWidth, childHeight),
calculateSizeFor(parentModifier, Modifier.fillMaxWidth().then(childModifier))
)
assertEquals(
IntSize(childWidth, parentHeight),
calculateSizeFor(parentModifier, Modifier.fillMaxHeight().then(childModifier))
)
assertEquals(
IntSize(parentWidth, parentHeight),
calculateSizeFor(parentModifier, Modifier.fillMaxSize().then(childModifier))
)
}
@Test
fun testFillModifier_correctDpSize() = with(density) {
val parentWidth = 100
val parentHeight = 80
val parentModifier = Modifier.requiredSize(DpSize(parentWidth.toDp(), parentHeight.toDp()))
val childWidth = 40
val childHeight = 30
val childModifier = Modifier.size(DpSize(childWidth.toDp(), childHeight.toDp()))
assertEquals(
IntSize(childWidth, childHeight),
calculateSizeFor(parentModifier, childModifier)
)
assertEquals(
IntSize(parentWidth, childHeight),
calculateSizeFor(parentModifier, Modifier.fillMaxWidth().then(childModifier))
)
assertEquals(
IntSize(childWidth, parentHeight),
calculateSizeFor(parentModifier, Modifier.fillMaxHeight().then(childModifier))
)
assertEquals(
IntSize(parentWidth, parentHeight),
calculateSizeFor(parentModifier, Modifier.fillMaxSize().then(childModifier))
)
}
@Test
fun testFractionalFillModifier_correctSize_whenSmallerChild() = with(density) {
val parentWidth = 100
val parentHeight = 80
val parentModifier = Modifier.requiredSize(parentWidth.toDp(), parentHeight.toDp())
val childWidth = 40
val childHeight = 30
val childModifier = Modifier.size(childWidth.toDp(), childHeight.toDp())
assertEquals(
IntSize(childWidth, childHeight),
calculateSizeFor(parentModifier, childModifier)
)
assertEquals(
IntSize(parentWidth / 2, childHeight),
calculateSizeFor(parentModifier, Modifier.fillMaxWidth(0.5f).then(childModifier))
)
assertEquals(
IntSize(childWidth, parentHeight / 2),
calculateSizeFor(parentModifier, Modifier.fillMaxHeight(0.5f).then(childModifier))
)
assertEquals(
IntSize(parentWidth / 2, parentHeight / 2),
calculateSizeFor(parentModifier, Modifier.fillMaxSize(0.5f).then(childModifier))
)
}
@Test
fun testFractionalFillModifier_correctSize_whenLargerChild() = with(density) {
val parentWidth = 100
val parentHeight = 80
val parentModifier = Modifier.requiredSize(parentWidth.toDp(), parentHeight.toDp())
val childWidth = 70
val childHeight = 50
val childModifier = Modifier.size(childWidth.toDp(), childHeight.toDp())
assertEquals(
IntSize(childWidth, childHeight),
calculateSizeFor(parentModifier, childModifier)
)
assertEquals(
IntSize(parentWidth / 2, childHeight),
calculateSizeFor(parentModifier, Modifier.fillMaxWidth(0.5f).then(childModifier))
)
assertEquals(
IntSize(childWidth, parentHeight / 2),
calculateSizeFor(parentModifier, Modifier.fillMaxHeight(0.5f).then(childModifier))
)
assertEquals(
IntSize(parentWidth / 2, parentHeight / 2),
calculateSizeFor(parentModifier, Modifier.fillMaxSize(0.5f).then(childModifier))
)
}
@Test
fun testFractionalFillModifier_coerced() = with(density) {
val childMinWidth = 40
val childMinHeight = 30
val childMaxWidth = 60
val childMaxHeight = 50
val childModifier = Modifier.requiredSizeIn(
childMinWidth.toDp(),
childMinHeight.toDp(),
childMaxWidth.toDp(),
childMaxHeight.toDp()
)
assertEquals(
IntSize(childMinWidth, childMinHeight),
calculateSizeFor(Modifier, childModifier.then(Modifier.fillMaxSize(-0.1f)))
)
assertEquals(
IntSize(childMinWidth, childMinHeight),
calculateSizeFor(Modifier, childModifier.then(Modifier.fillMaxSize(0.1f)))
)
assertEquals(
IntSize(childMaxWidth, childMaxHeight),
calculateSizeFor(Modifier, childModifier.then(Modifier.fillMaxSize(1.2f)))
)
}
@Test
fun testFillModifier_noChangeIntrinsicMeasurements() = with(density) {
verifyIntrinsicMeasurements(Modifier.fillMaxWidth())
verifyIntrinsicMeasurements(Modifier.fillMaxHeight())
verifyIntrinsicMeasurements(Modifier.fillMaxSize())
}
@Test
fun testDefaultMinSizeModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.defaultMinSize(40.toDp(), 50.toDp())) {
Container(Modifier.aspectRatio(1f)) { }
}
}
) { minIntrinsicWidth, minIntrinsicHeight, _, _ ->
// Min width.
assertEquals(40, minIntrinsicWidth(0))
assertEquals(40, minIntrinsicWidth(35))
assertEquals(55, minIntrinsicWidth(55))
assertEquals(40, minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(50, minIntrinsicHeight(0))
assertEquals(50, minIntrinsicHeight(35))
assertEquals(55, minIntrinsicHeight(55))
assertEquals(50, minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(40, minIntrinsicWidth(0))
assertEquals(40, minIntrinsicWidth(35))
assertEquals(55, minIntrinsicWidth(55))
assertEquals(40, minIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(50, minIntrinsicHeight(0))
assertEquals(50, minIntrinsicHeight(35))
assertEquals(55, minIntrinsicHeight(55))
assertEquals(50, minIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testInspectableParameter() {
checkModifier(Modifier.requiredWidth(200.0.dp), "requiredWidth", 200.0.dp, listOf())
checkModifier(Modifier.requiredHeight(300.0.dp), "requiredHeight", 300.0.dp, listOf())
checkModifier(Modifier.requiredSize(400.0.dp), "requiredSize", 400.0.dp, listOf())
checkModifier(
Modifier.requiredSize(100.0.dp, 200.0.dp), "requiredSize", null,
listOf(
ValueElement("width", 100.0.dp),
ValueElement("height", 200.0.dp)
)
)
checkModifier(
Modifier.requiredWidthIn(100.0.dp, 200.0.dp), "requiredWidthIn", null,
listOf(ValueElement("min", 100.0.dp), ValueElement("max", 200.0.dp))
)
checkModifier(
Modifier.requiredHeightIn(10.0.dp, 200.0.dp), "requiredHeightIn", null,
listOf(ValueElement("min", 10.0.dp), ValueElement("max", 200.0.dp))
)
checkModifier(
Modifier.requiredSizeIn(10.dp, 20.dp, 30.dp, 40.dp), "requiredSizeIn", null,
listOf(
ValueElement("minWidth", 10.dp), ValueElement("minHeight", 20.dp),
ValueElement("maxWidth", 30.dp), ValueElement("maxHeight", 40.dp)
)
)
checkModifier(Modifier.width(200.0.dp), "width", 200.0.dp, listOf())
checkModifier(Modifier.height(300.0.dp), "height", 300.0.dp, listOf())
checkModifier(Modifier.size(400.0.dp), "size", 400.0.dp, listOf())
checkModifier(
Modifier.size(100.0.dp, 200.0.dp), "size", null,
listOf(ValueElement("width", 100.0.dp), ValueElement("height", 200.0.dp))
)
checkModifier(
Modifier.widthIn(100.0.dp, 200.0.dp), "widthIn", null,
listOf(ValueElement("min", 100.0.dp), ValueElement("max", 200.0.dp))
)
checkModifier(
Modifier.heightIn(10.0.dp, 200.0.dp), "heightIn", null,
listOf(ValueElement("min", 10.0.dp), ValueElement("max", 200.0.dp))
)
checkModifier(
Modifier.sizeIn(10.dp, 20.dp, 30.dp, 40.dp), "sizeIn", null,
listOf(
ValueElement("minWidth", 10.dp), ValueElement("minHeight", 20.dp),
ValueElement("maxWidth", 30.dp), ValueElement("maxHeight", 40.dp)
)
)
checkModifier(
Modifier.fillMaxWidth(), "fillMaxWidth", null,
listOf(ValueElement("fraction", 1.0f))
)
checkModifier(
Modifier.fillMaxWidth(0.7f), "fillMaxWidth", null,
listOf(ValueElement("fraction", 0.7f))
)
checkModifier(
Modifier.fillMaxHeight(), "fillMaxHeight", null,
listOf(ValueElement("fraction", 1.0f))
)
checkModifier(
Modifier.fillMaxHeight(0.15f), "fillMaxHeight", null,
listOf(ValueElement("fraction", 0.15f))
)
checkModifier(
Modifier.fillMaxSize(), "fillMaxSize", null,
listOf(ValueElement("fraction", 1.0f))
)
checkModifier(
Modifier.fillMaxSize(0.25f), "fillMaxSize", null,
listOf(ValueElement("fraction", 0.25f))
)
checkModifier(
Modifier.wrapContentWidth(), "wrapContentWidth", null,
listOf(
ValueElement("align", Alignment.CenterHorizontally),
ValueElement("unbounded", false)
)
)
checkModifier(
Modifier.wrapContentWidth(Alignment.End, true), "wrapContentWidth", null,
listOf(
ValueElement("align", Alignment.End),
ValueElement("unbounded", true)
)
)
checkModifier(
Modifier.wrapContentHeight(), "wrapContentHeight", null,
listOf(
ValueElement("align", Alignment.CenterVertically),
ValueElement("unbounded", false)
)
)
checkModifier(
Modifier.wrapContentHeight(Alignment.Bottom, true), "wrapContentHeight", null,
listOf(
ValueElement("align", Alignment.Bottom),
ValueElement("unbounded", true)
)
)
checkModifier(
Modifier.wrapContentSize(), "wrapContentSize", null,
listOf(
ValueElement("align", Alignment.Center),
ValueElement("unbounded", false)
)
)
checkModifier(
Modifier.wrapContentSize(Alignment.BottomCenter, true), "wrapContentSize", null,
listOf(
ValueElement("align", Alignment.BottomCenter),
ValueElement("unbounded", true)
)
)
checkModifier(
Modifier.defaultMinSize(10.0.dp, 20.0.dp),
"defaultMinSize", null,
listOf(ValueElement("minWidth", 10.dp), ValueElement("minHeight", 20.dp))
)
}
private fun checkModifier(
modifier: Modifier,
expectedName: String,
expectedValue: Any?,
expectedElements: List<ValueElement>
) {
assertThat(modifier).isInstanceOf(InspectableValue::class.java)
val parameter = modifier as InspectableValue
assertThat(parameter.nameFallback).isEqualTo(expectedName)
assertThat(parameter.valueOverride).isEqualTo(expectedValue)
assertThat(parameter.inspectableElements.toList()).isEqualTo(expectedElements)
}
private fun calculateSizeFor(parentModifier: Modifier, modifier: Modifier): IntSize {
val positionedLatch = CountDownLatch(1)
val size = Ref<IntSize>()
val position = Ref<Offset>()
show {
Box(parentModifier) {
Box(modifier.saveLayoutInfo(size, position, positionedLatch))
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
return size.value!!
}
private fun assertConstraints(
incomingConstraints: Constraints,
modifier: Modifier,
expectedConstraints: Constraints
) {
val latch = CountDownLatch(1)
// Capture constraints and assert on test thread
var actualConstraints: Constraints? = null
// Clear contents before each test so that we don't recompose the BoxWithConstraints call;
// doing so would recompose the old subcomposition with old constraints in the presence of
// new content before the measurement performs explicit composition the new constraints.
show({})
show {
Layout({
BoxWithConstraints(modifier) {
actualConstraints = constraints
latch.countDown()
}
}) { measurables, _ ->
measurables[0].measure(incomingConstraints)
layout(0, 0) { }
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertEquals(expectedConstraints, actualConstraints)
}
private fun verifyIntrinsicMeasurements(expandedModifier: Modifier) = with(density) {
// intrinsic measurements do not change with the ExpandedModifier
testIntrinsics(
@Composable {
Container(
expandedModifier.then(Modifier.aspectRatio(2f)),
width = 30.toDp(), height = 40.toDp()
) { }
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Width
assertEquals(40, minIntrinsicWidth(20))
assertEquals(30, minIntrinsicWidth(Constraints.Infinity))
assertEquals(40, maxIntrinsicWidth(20))
assertEquals(30, maxIntrinsicWidth(Constraints.Infinity))
// Height
assertEquals(20, minIntrinsicHeight(40))
assertEquals(40, minIntrinsicHeight(Constraints.Infinity))
assertEquals(20, maxIntrinsicHeight(40))
assertEquals(40, maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun test2DWrapContentSize() = with(density) {
val sizeDp = 50.dp
val size = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(2)
val alignSize = Ref<IntSize>()
val alignPosition = Ref<Offset>()
val childSize = Ref<IntSize>()
val childPosition = Ref<Offset>()
show {
Container(Modifier.saveLayoutInfo(alignSize, alignPosition, positionedLatch)) {
Container(
Modifier.fillMaxSize()
.wrapContentSize(Alignment.BottomEnd)
.size(sizeDp)
.saveLayoutInfo(childSize, childPosition, positionedLatch)
) {
}
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
val root = findComposeView()
waitForDraw(root)
assertEquals(IntSize(root.width, root.height), alignSize.value)
assertEquals(Offset(0f, 0f), alignPosition.value)
assertEquals(IntSize(size, size), childSize.value)
assertEquals(
Offset(root.width - size.toFloat(), root.height - size.toFloat()),
childPosition.value
)
}
@Test
fun test1DWrapContentSize() = with(density) {
val sizeDp = 50.dp
val size = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(2)
val alignSize = Ref<IntSize>()
val alignPosition = Ref<Offset>()
val childSize = Ref<IntSize>()
val childPosition = Ref<Offset>()
show {
Container(
Modifier.saveLayoutInfo(
size = alignSize,
position = alignPosition,
positionedLatch = positionedLatch
)
) {
Container(
Modifier.fillMaxSize()
.wrapContentWidth(Alignment.End)
.width(sizeDp)
.saveLayoutInfo(childSize, childPosition, positionedLatch)
) {
}
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
val root = findComposeView()
waitForDraw(root)
assertEquals(IntSize(root.width, root.height), alignSize.value)
assertEquals(Offset(0f, 0f), alignPosition.value)
assertEquals(IntSize(size, root.height), childSize.value)
assertEquals(Offset(root.width - size.toFloat(), 0f), childPosition.value)
}
@Test
fun testWrapContentSize_rtl() = with(density) {
val sizeDp = 200.toDp()
val size = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(3)
val childSize = Array(3) { Ref<IntSize>() }
val childPosition = Array(3) { Ref<Offset>() }
show {
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
Box(Modifier.fillMaxSize()) {
Box(Modifier.fillMaxSize().wrapContentSize(Alignment.TopStart)) {
Box(
Modifier.size(sizeDp)
.saveLayoutInfo(childSize[0], childPosition[0], positionedLatch)
) {
}
}
Box(Modifier.fillMaxSize().wrapContentHeight(Alignment.CenterVertically)) {
Box(
Modifier.size(sizeDp)
.saveLayoutInfo(childSize[1], childPosition[1], positionedLatch)
) {
}
}
Box(Modifier.fillMaxSize().wrapContentSize(Alignment.BottomEnd)) {
Box(
Modifier.size(sizeDp)
.saveLayoutInfo(childSize[2], childPosition[2], positionedLatch)
) {
}
}
}
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
val root = findComposeView()
waitForDraw(root)
assertEquals(
Offset((root.width - size).toFloat(), 0f),
childPosition[0].value
)
assertEquals(
Offset(
(root.width - size).toFloat(),
((root.height - size) / 2).toFloat()
),
childPosition[1].value
)
assertEquals(
Offset(0f, (root.height - size).toFloat()),
childPosition[2].value
)
}
@Test
fun testModifier_wrapsContent() = with(density) {
val contentSize = 50.dp
val size = Ref<IntSize>()
val latch = CountDownLatch(1)
show {
Container {
Container(Modifier.saveLayoutInfo(size, Ref(), latch)) {
Container(
Modifier.wrapContentSize(Alignment.TopStart)
.size(contentSize)
) {}
}
}
}
assertTrue(latch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(contentSize.roundToPx(), contentSize.roundToPx()), size.value)
}
@Test
fun testWrapContentSize_wrapsContent_whenMeasuredWithInfiniteConstraints() = with(density) {
val sizeDp = 50.dp
val size = sizeDp.roundToPx()
val positionedLatch = CountDownLatch(2)
val alignSize = Ref<IntSize>()
val alignPosition = Ref<Offset>()
val childSize = Ref<IntSize>()
val childPosition = Ref<Offset>()
show {
Layout(
content = {
Container(
Modifier.saveLayoutInfo(alignSize, alignPosition, positionedLatch)
) {
Container(
Modifier.wrapContentSize(Alignment.BottomEnd)
.size(sizeDp)
.saveLayoutInfo(childSize, childPosition, positionedLatch)
) {
}
}
},
measurePolicy = { measurables, constraints ->
val placeable = measurables.first().measure(Constraints())
layout(constraints.maxWidth, constraints.maxHeight) {
placeable.placeRelative(0, 0)
}
}
)
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
val root = findComposeView()
waitForDraw(root)
assertEquals(IntSize(size, size), alignSize.value)
assertEquals(Offset(0f, 0f), alignPosition.value)
assertEquals(IntSize(size, size), childSize.value)
assertEquals(Offset(0f, 0f), childPosition.value)
}
@Test
fun testWrapContentSize_respectsMinConstraints() = with(density) {
val sizeDp = 50.dp
val size = sizeDp.roundToPx()
val doubleSizeDp = sizeDp * 2
val doubleSize = doubleSizeDp.roundToPx()
val positionedLatch = CountDownLatch(2)
val wrapSize = Ref<IntSize>()
val childSize = Ref<IntSize>()
val childPosition = Ref<Offset>()
show {
Container(Modifier.wrapContentSize(Alignment.TopStart)) {
Layout(
modifier = Modifier.onGloballyPositioned { coordinates: LayoutCoordinates ->
wrapSize.value = coordinates.size
positionedLatch.countDown()
},
content = {
Container(
Modifier.wrapContentSize(Alignment.Center)
.size(sizeDp)
.saveLayoutInfo(childSize, childPosition, positionedLatch)
) {
}
},
measurePolicy = { measurables, incomingConstraints ->
val measurable = measurables.first()
val constraints = incomingConstraints.constrain(
Constraints(
minWidth = doubleSizeDp.roundToPx(),
minHeight = doubleSizeDp.roundToPx()
)
)
val placeable = measurable.measure(constraints)
layout(placeable.width, placeable.height) {
placeable.placeRelative(IntOffset.Zero)
}
}
)
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
assertEquals(IntSize(doubleSize, doubleSize), wrapSize.value)
assertEquals(IntSize(size, size), childSize.value)
assertEquals(
Offset(
((doubleSize - size) / 2f).roundToInt().toFloat(),
((doubleSize - size) / 2f).roundToInt().toFloat()
),
childPosition.value
)
}
@Test
fun testWrapContentSize_unbounded() = with(density) {
val outerSize = 10f
val innerSize = 20f
val positionedLatch = CountDownLatch(4)
show {
Box(
Modifier.requiredSize(outerSize.toDp())
.onGloballyPositioned {
assertEquals(outerSize, it.size.width.toFloat())
positionedLatch.countDown()
}
) {
Box(
Modifier.wrapContentSize(Alignment.BottomEnd, unbounded = true)
.requiredSize(innerSize.toDp())
.onGloballyPositioned {
assertEquals(
Offset(outerSize - innerSize, outerSize - innerSize),
it.positionInParent()
)
positionedLatch.countDown()
}
)
Box(
Modifier.wrapContentWidth(Alignment.End, unbounded = true)
.requiredSize(innerSize.toDp())
.onGloballyPositioned {
assertEquals(outerSize - innerSize, it.positionInParent().x)
positionedLatch.countDown()
}
)
Box(
Modifier.wrapContentHeight(Alignment.Bottom, unbounded = true)
.requiredSize(innerSize.toDp())
.onGloballyPositioned {
assertEquals(outerSize - innerSize, it.positionInParent().y)
positionedLatch.countDown()
}
)
}
}
assertTrue(positionedLatch.await(1, TimeUnit.SECONDS))
}
@Test
fun test2DAlignedModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics(
@Composable {
Container(Modifier.wrapContentSize(Alignment.TopStart).aspectRatio(2f)) { }
}
) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(25.dp.roundToPx() * 2, minIntrinsicWidth(25.dp.roundToPx()))
assertEquals(0.dp.roundToPx(), minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(
(50.dp.roundToPx() / 2f).roundToInt(),
minIntrinsicHeight(50.dp.roundToPx())
)
assertEquals(0.dp.roundToPx(), minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(25.dp.roundToPx() * 2, maxIntrinsicWidth(25.dp.roundToPx()))
assertEquals(0.dp.roundToPx(), maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(
(50.dp.roundToPx() / 2f).roundToInt(),
maxIntrinsicHeight(50.dp.roundToPx())
)
assertEquals(0.dp.roundToPx(), maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun test1DAlignedModifier_hasCorrectIntrinsicMeasurements() = with(density) {
testIntrinsics({
Container(
Modifier.wrapContentHeight(Alignment.CenterVertically)
.aspectRatio(2f)
) { }
}) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight ->
// Min width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(25.dp.roundToPx() * 2, minIntrinsicWidth(25.dp.roundToPx()))
assertEquals(0.dp.roundToPx(), minIntrinsicWidth(Constraints.Infinity))
// Min height.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(
(50.dp.roundToPx() / 2f).roundToInt(),
minIntrinsicHeight(50.dp.roundToPx())
)
assertEquals(0.dp.roundToPx(), minIntrinsicHeight(Constraints.Infinity))
// Max width.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(25.dp.roundToPx() * 2, maxIntrinsicWidth(25.dp.roundToPx()))
assertEquals(0.dp.roundToPx(), maxIntrinsicWidth(Constraints.Infinity))
// Max height.
assertEquals(0, minIntrinsicWidth(0))
assertEquals(
(50.dp.roundToPx() / 2f).roundToInt(),
maxIntrinsicHeight(50.dp.roundToPx())
)
assertEquals(0.dp.roundToPx(), maxIntrinsicHeight(Constraints.Infinity))
}
}
@Test
fun testAlignedModifier_alignsCorrectly_whenOddDimensions_endAligned() = with(density) {
// Given a 100 x 100 pixel container, we want to make sure that when aligning a 1 x 1 pixel
// child to both ends (bottom, and right) we correctly position children at the last
// possible pixel, and avoid rounding issues. Previously we first centered the coordinates,
// and then aligned after, so the maths would actually be (99 / 2) * 2, which incorrectly
// ends up at 100 (Int rounds up) - so the last pixels in both directions just wouldn't
// be visible.
val parentSize = 100.toDp()
val childSizeDp = 1.toDp()
val childSizeIpx = childSizeDp.roundToPx()
val positionedLatch = CountDownLatch(2)
val alignSize = Ref<IntSize>()
val alignPosition = Ref<Offset>()
val childSize = Ref<IntSize>()
val childPosition = Ref<Offset>()
show {
Layout(
content = {
Container(
Modifier.size(parentSize)
.saveLayoutInfo(alignSize, alignPosition, positionedLatch)
) {
Container(
Modifier.fillMaxSize()
.wrapContentSize(Alignment.BottomEnd)
.size(childSizeDp)
.saveLayoutInfo(childSize, childPosition, positionedLatch)
) {
}
}
},
measurePolicy = { measurables, constraints ->
val placeable = measurables.first().measure(Constraints())
layout(constraints.maxWidth, constraints.maxHeight) {
placeable.placeRelative(0, 0)
}
}
)
}
positionedLatch.await(1, TimeUnit.SECONDS)
val root = findComposeView()
waitForDraw(root)
assertEquals(IntSize(childSizeIpx, childSizeIpx), childSize.value)
assertEquals(
Offset(
(alignSize.value!!.width - childSizeIpx).toFloat(),
(alignSize.value!!.height - childSizeIpx).toFloat()
),
childPosition.value
)
}
@Test
@FlakyTest(bugId = 183713100)
fun testModifiers_doNotCauseUnnecessaryRemeasure() {
var first by mutableStateOf(true)
var totalMeasures = 0
@Composable fun CountMeasures(modifier: Modifier) {
Layout(
content = {},
modifier = modifier,
measurePolicy = { _, _ ->
++totalMeasures
layout(0, 0) {}
}
)
}
show {
Box {
if (first) Box {} else Row {}
CountMeasures(Modifier.size(10.dp))
CountMeasures(Modifier.requiredSize(10.dp))
CountMeasures(Modifier.wrapContentSize(Alignment.BottomEnd))
CountMeasures(Modifier.fillMaxSize(0.8f))
CountMeasures(Modifier.defaultMinSize(10.dp, 20.dp))
}
}
val root = findComposeView()
waitForDraw(root)
activityTestRule.runOnUiThread {
assertEquals(5, totalMeasures)
first = false
}
activityTestRule.runOnUiThread {
assertEquals(5, totalMeasures)
}
}
@Test
fun testModifiers_equals() {
assertEquals(Modifier.size(10.dp, 20.dp), Modifier.size(10.dp, 20.dp))
assertEquals(Modifier.requiredSize(10.dp, 20.dp), Modifier.requiredSize(10.dp, 20.dp))
assertEquals(
Modifier.wrapContentSize(Alignment.BottomEnd),
Modifier.wrapContentSize(Alignment.BottomEnd)
)
assertEquals(Modifier.fillMaxSize(0.8f), Modifier.fillMaxSize(0.8f))
assertEquals(Modifier.defaultMinSize(10.dp, 20.dp), Modifier.defaultMinSize(10.dp, 20.dp))
assertNotEquals(Modifier.size(10.dp, 20.dp), Modifier.size(20.dp, 10.dp))
assertNotEquals(Modifier.requiredSize(10.dp, 20.dp), Modifier.requiredSize(20.dp, 10.dp))
assertNotEquals(
Modifier.wrapContentSize(Alignment.BottomEnd),
Modifier.wrapContentSize(Alignment.BottomCenter)
)
assertNotEquals(Modifier.fillMaxSize(0.8f), Modifier.fillMaxSize())
assertNotEquals(
Modifier.defaultMinSize(10.dp, 20.dp),
Modifier.defaultMinSize(20.dp, 10.dp)
)
}
@Test
fun testIntrinsicMeasurements_notQueriedWhenConstraintsAreFixed() {
@Composable fun ErrorIntrinsicsLayout(modifier: Modifier) {
Layout(
{},
modifier,
object : MeasurePolicy {
override fun MeasureScope.measure(
measurables: List<Measurable>,
constraints: Constraints
): MeasureResult {
return layout(0, 0) {}
}
override fun IntrinsicMeasureScope.minIntrinsicWidth(
measurables: List<IntrinsicMeasurable>,
height: Int
) = error("Error intrinsic")
override fun IntrinsicMeasureScope.minIntrinsicHeight(
measurables: List<IntrinsicMeasurable>,
width: Int
) = error("Error intrinsic")
override fun IntrinsicMeasureScope.maxIntrinsicWidth(
measurables: List<IntrinsicMeasurable>,
height: Int
) = error("Error intrinsic")
override fun IntrinsicMeasureScope.maxIntrinsicHeight(
measurables: List<IntrinsicMeasurable>,
width: Int
) = error("Error intrinsic")
}
)
}
show {
Box(Modifier.width(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) }
Box(Modifier.width(IntrinsicSize.Min)) {
ErrorIntrinsicsLayout(Modifier.width(1.dp))
}
Box(Modifier.width(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) }
Box(Modifier.width(IntrinsicSize.Max)) {
ErrorIntrinsicsLayout(Modifier.width(1.dp))
}
Box(Modifier.requiredWidth(IntrinsicSize.Min)) {
ErrorIntrinsicsLayout(Modifier.width(1.dp))
}
Box(Modifier.requiredWidth(IntrinsicSize.Min)) {
ErrorIntrinsicsLayout(Modifier.width(1.dp))
}
Box(Modifier.requiredWidth(IntrinsicSize.Max)) {
ErrorIntrinsicsLayout(Modifier.width(1.dp))
}
Box(Modifier.requiredWidth(IntrinsicSize.Max)) {
ErrorIntrinsicsLayout(Modifier.width(1.dp))
}
Box(Modifier.height(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) }
Box(Modifier.height(IntrinsicSize.Min)) {
ErrorIntrinsicsLayout(Modifier.height(1.dp))
}
Box(Modifier.height(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) }
Box(Modifier.height(IntrinsicSize.Max)) {
ErrorIntrinsicsLayout(Modifier.height(1.dp))
}
Box(Modifier.requiredHeight(IntrinsicSize.Min)) {
ErrorIntrinsicsLayout(Modifier.height(1.dp))
}
Box(Modifier.requiredHeight(IntrinsicSize.Min)) {
ErrorIntrinsicsLayout(Modifier.height(1.dp))
}
Box(Modifier.requiredHeight(IntrinsicSize.Max)) {
ErrorIntrinsicsLayout(Modifier.height(1.dp))
}
Box(Modifier.requiredHeight(IntrinsicSize.Max)) {
ErrorIntrinsicsLayout(Modifier.height(1.dp))
}
}
// The test tests that the measure pass should not crash.
val root = findComposeView()
waitForDraw(root)
}
@Test
fun sizeModifiers_doNotCauseCrashesWhenCreatingConstraints() {
show {
Box(Modifier.sizeIn(minWidth = -1.dp))
Box(Modifier.sizeIn(minWidth = 10.dp, maxWidth = 5.dp))
Box(Modifier.sizeIn(minHeight = -1.dp))
Box(Modifier.sizeIn(minHeight = 10.dp, maxHeight = 5.dp))
Box(
Modifier.sizeIn(
minWidth = Dp.Infinity,
maxWidth = Dp.Infinity,
minHeight = Dp.Infinity,
maxHeight = Dp.Infinity
)
)
Box(Modifier.defaultMinSize(minWidth = -1.dp, minHeight = -1.dp))
}
val root = findComposeView()
waitForDraw(root)
}
} | compose/foundation/foundation-layout/src/androidAndroidTest/kotlin/androidx/compose/foundation/layout/SizeTest.kt | 2067153777 |
/*
* 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.camera.integration.view
import android.graphics.SurfaceTexture
import android.graphics.SurfaceTexture.OnFrameAvailableListener
import android.os.Handler
import android.os.Looper
import android.view.Surface
import androidx.annotation.VisibleForTesting
import androidx.camera.core.SurfaceOutput
import androidx.camera.core.SurfaceProcessor
import androidx.camera.core.SurfaceRequest
import androidx.camera.core.impl.utils.Threads.checkMainThread
import androidx.camera.core.impl.utils.executor.CameraXExecutors.mainThreadExecutor
import androidx.camera.core.processing.OpenGlRenderer
import androidx.camera.core.processing.ShaderProvider
/**
* A processor that applies tone mapping on camera output.
*
* <p>The thread safety is guaranteed by using the main thread.
*/
class ToneMappingSurfaceProcessor : SurfaceProcessor, OnFrameAvailableListener {
companion object {
// A fragment shader that applies a yellow hue.
private val TONE_MAPPING_SHADER_PROVIDER = object : ShaderProvider {
override fun createFragmentShader(sampler: String, fragCoords: String): String {
return """
#extension GL_OES_EGL_image_external : require
precision mediump float;
uniform samplerExternalOES $sampler;
varying vec2 $fragCoords;
void main() {
vec4 sampleColor = texture2D($sampler, $fragCoords);
gl_FragColor = vec4(
sampleColor.r * 0.5 + sampleColor.g * 0.8 + sampleColor.b * 0.3,
sampleColor.r * 0.4 + sampleColor.g * 0.7 + sampleColor.b * 0.2,
sampleColor.r * 0.3 + sampleColor.g * 0.5 + sampleColor.b * 0.1,
1.0);
}
"""
}
}
}
private val mainThreadHandler: Handler = Handler(Looper.getMainLooper())
private val glRenderer: OpenGlRenderer = OpenGlRenderer()
private val outputSurfaces: MutableMap<SurfaceOutput, Surface> = mutableMapOf()
private val textureTransform: FloatArray = FloatArray(16)
private val surfaceTransform: FloatArray = FloatArray(16)
private var isReleased = false
// For testing.
private var surfaceRequested = false
// For testing.
private var outputSurfaceProvided = false
init {
mainThreadExecutor().execute {
glRenderer.init(TONE_MAPPING_SHADER_PROVIDER)
}
}
override fun onInputSurface(surfaceRequest: SurfaceRequest) {
checkMainThread()
if (isReleased) {
surfaceRequest.willNotProvideSurface()
return
}
surfaceRequested = true
val surfaceTexture = SurfaceTexture(glRenderer.textureName)
surfaceTexture.setDefaultBufferSize(
surfaceRequest.resolution.width, surfaceRequest.resolution.height
)
val surface = Surface(surfaceTexture)
surfaceRequest.provideSurface(surface, mainThreadExecutor()) {
surfaceTexture.setOnFrameAvailableListener(null)
surfaceTexture.release()
surface.release()
}
surfaceTexture.setOnFrameAvailableListener(this, mainThreadHandler)
}
override fun onOutputSurface(surfaceOutput: SurfaceOutput) {
checkMainThread()
outputSurfaceProvided = true
if (isReleased) {
surfaceOutput.close()
return
}
val surface = surfaceOutput.getSurface(mainThreadExecutor()) {
surfaceOutput.close()
outputSurfaces.remove(surfaceOutput)?.let { removedSurface ->
glRenderer.unregisterOutputSurface(removedSurface)
}
}
glRenderer.registerOutputSurface(surface)
outputSurfaces[surfaceOutput] = surface
}
@VisibleForTesting
fun isSurfaceRequestedAndProvided(): Boolean {
return surfaceRequested && outputSurfaceProvided
}
fun release() {
checkMainThread()
if (isReleased) {
return
}
// Once release is called, we can stop sending frame to output surfaces.
for (surfaceOutput in outputSurfaces.keys) {
surfaceOutput.close()
}
outputSurfaces.clear()
glRenderer.release()
isReleased = true
}
override fun onFrameAvailable(surfaceTexture: SurfaceTexture) {
checkMainThread()
if (isReleased) {
return
}
surfaceTexture.updateTexImage()
surfaceTexture.getTransformMatrix(textureTransform)
for (entry in outputSurfaces.entries.iterator()) {
val surface = entry.value
val surfaceOutput = entry.key
surfaceOutput.updateTransformMatrix(surfaceTransform, textureTransform)
glRenderer.render(surfaceTexture.timestamp, surfaceTransform, surface)
}
}
} | camera/integration-tests/viewtestapp/src/main/java/androidx/camera/integration/view/ToneMappingSurfaceProcessor.kt | 900281403 |
package taiwan.no1.app.ssfm.misc.widgets
import android.content.Context
import android.graphics.Typeface
import android.util.AttributeSet
import android.widget.TextView
import taiwan.no1.app.ssfm.R
/**
* For inputting customize special font.
*
* @author jieyi
* @since 6/14/17
*/
class FontTextView @JvmOverloads constructor(context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) :
TextView(context, attrs, defStyleAttr) {
init {
context.obtainStyledAttributes(attrs, R.styleable.FontTextView, defStyleAttr, 0).also {
it.getString(R.styleable.FontTextView_textFont).let {
typeface = Typeface.createFromAsset(context.assets, "fonts/$it")
}
}.recycle()
}
}
| app/src/main/kotlin/taiwan/no1/app/ssfm/misc/widgets/FontTextView.kt | 2294842131 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.demos.gestures
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
/**
* Simple [detectTapGestures] demo.
*/
@Composable
fun DetectTapGesturesDemo() {
val color = remember { mutableStateOf(Colors.random()) }
val onTap: (Offset) -> Unit = {
color.value = color.value.anotherRandomColor()
}
Column {
Text("The box changes color when you tap it.")
Box(
Modifier.fillMaxSize()
.wrapContentSize(Alignment.Center)
.size(192.dp)
.pointerInput(Unit) { detectTapGestures(onTap = onTap) }
.clipToBounds()
.background(color.value)
.border(BorderStroke(2.dp, BorderColor))
)
}
}
| compose/ui/ui/integration-tests/ui-demos/src/main/java/androidx/compose/ui/demos/gestures/TapGestureDetectorDemo.kt | 356664059 |
package com.lytefast.flexinput.model
import android.content.ContentResolver
import android.content.ContentUris
import android.net.Uri
import android.os.AsyncTask
import android.os.Parcel
import android.os.Parcelable
import android.provider.MediaStore
import android.util.Log
/**
* Represents a photo obtained from the [MediaStore.Images.Media.EXTERNAL_CONTENT_URI] store.
*
* @author Sam Shih
*/
class Photo : Attachment<String> {
constructor(id: Long, uri: Uri, displayName: String, photoDataLocation: String?)
: super(id, uri, displayName, photoDataLocation)
constructor(parcelIn: Parcel) : super(parcelIn)
fun getThumbnailUri(contentResolver: ContentResolver): Uri? {
val cursor = contentResolver.query(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Images.Thumbnails._ID),
"${MediaStore.Images.Thumbnails.IMAGE_ID} = ? AND KIND = ?",
arrayOf(id.toString(), Integer.toString(MediaStore.Images.Thumbnails.MINI_KIND)), null)
if (cursor == null || !cursor.moveToFirst()) {
asyncGenerateThumbnail(contentResolver)
cursor?.close()
return uri // Slow due to photo size and manipulation but better than nothing
}
cursor.use {
val thumbId = it.getLong(0)
return ContentUris.withAppendedId(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, thumbId)
}
}
/**
* Generate thumbnail for next time.
*/
private fun asyncGenerateThumbnail(contentResolver: ContentResolver) {
AsyncTask.execute {
try {
MediaStore.Images.Thumbnails.getThumbnail(
contentResolver, id, MediaStore.Images.Thumbnails.MINI_KIND, null)
} catch (e: Exception) {
Log.v(Photo::class.java.name, "Error generating thumbnail for photo $id.")
}
}
}
companion object {
@Suppress("unused") // Used as part of Parcellable
@JvmField
val CREATOR = object : Parcelable.Creator<Photo> {
override fun createFromParcel(parcel: Parcel): Photo = Photo(parcel)
override fun newArray(size: Int): Array<Photo?> = arrayOfNulls(size)
}
}
}
| flexinput/src/main/java/com/lytefast/flexinput/model/Photo.kt | 813208310 |
package diff.patch.accessors
import diff.patch.Setter
/**
* @author sebasjm <smarchano></smarchano>@primary.com.ar>
*/
class SetSetter<Element: Any>(internal val set: MutableSet<Element>, internal val element: Element?) : Setter<Element> {
override fun set(value: Element) {
if (element != null) {
if (value == null) {
set.remove(element)
} else {
set.add(element)
}
}
}
}
| src/main/kotlin/diff/patch/accessors/SetSetter.kt | 1981588884 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opencl.templates
import org.lwjgl.generator.*
import org.lwjgl.opencl.*
val amd_device_topology = "AMDDeviceTopology".nativeClassCL("amd_device_topology", AMD) {
documentation =
"""
Native bindings to the $extensionName extension.
This extension enables the developer to get a description of the topology used to connect the device to the host.
"""
IntConstant(
"""
Accepted as the {@code param_name} parameter of CL10#GetDeviceInfo(). Returns a description of the topology used to connect the device to the
host, using the following 32-bytes union of structures:
${codeBlock("""
typedef union
{
struct { cl_uint type; cl_uint data[5]; } raw;
struct { cl_uint type; cl_char unused[17]; cl_char bus; cl_char device; cl_char function; } pcie;
} cl_device_topology_amd;
""")}
The type of the structure returned can be queried by reading the first unsigned int of the returned data. The developer can use this type to cast the
returned union into the right structure type.
Currently, the only supported type in the structure above is #DEVICE_TOPOLOGY_TYPE_PCIE_AMD. The information returned contains the PCI
Bus/Device/Function of the device, and is similar to the result of the lspci command in Linux. It enables the developer to match between the OpenCL
device ID and the physical PCI connection of the card.
""",
"DEVICE_TOPOLOGY_AMD"..0x4037
)
IntConstant(
"Indicates the type of the struct returned by #DEVICE_TOPOLOGY_AMD.",
"DEVICE_TOPOLOGY_TYPE_PCIE_AMD".."1"
)
} | modules/templates/src/main/kotlin/org/lwjgl/opencl/templates/amd_device_topology.kt | 3496938584 |
package net.yested.utils
import jquery.JQuery
import org.w3c.dom.Element
import org.w3c.dom.HTMLElement
import org.w3c.dom.Window
class Position(val top:Int, val left:Int)
class JSArray(val length:Int)
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.sortable(options: dynamic):Unit = asDynamic().sortable(options)
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.each(noinline func:(index:Int, element:HTMLElement)->Unit):Unit = asDynamic().each(func)
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.disableSelection():Unit = asDynamic().disableSelection()
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.on(event:String, noinline handler:(dynamic)->Unit): Unit = asDynamic().on(event, handler)
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.off(event:String): Unit = asDynamic().off(event)
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.keypress(noinline handler: (event:dynamic) -> Unit): Unit = asDynamic().keypress(handler)
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.css(property:String):String = asDynamic().css(property)
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.css(property:String, value:String):String = asDynamic().css(property, value)
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.offset():Position = asDynamic().offset()
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.scrollLeft():Int = asDynamic().scrollLeft()
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.scrollTop():Int = asDynamic().scrollTop()
@Suppress("NOTHING_TO_INLINE")
inline fun JQuery.closest(element: Element):JSArray = asDynamic().closest(element)
@JsName("$")
external fun jq(window: Window): JQuery = definedExternally
external interface JQStatic {
//throttle: https://github.com/cowboy/jquery-throttle-debounce
fun <EVENT> throttle(duration:Int, handler:(event:EVENT) -> Unit): Function1<EVENT, Unit>
}
@JsName("$")
external var jqStatic: JQStatic
fun <M> throttle(duration:Int, handler:(event:M) -> Unit): Function1<M, Unit> = jqStatic.throttle(duration, handler) | src/main/kotlin/net/yested/utils/jquery.kt | 3006291921 |
package net.jselby.escapists.data.chunks
import net.jselby.escapists.data.Chunk
import net.jselby.escapists.util.ByteReader
class GlobalStrings : Chunk() {
lateinit var data: Array<String?>
override fun init(buffer: ByteReader, length: Int) {
val l = buffer.unsignedInt.toInt()
data = arrayOfNulls<String>(l)
for (i in 0..l - 1) {
data[i] = buffer.string
}
}
}
class GlobalValues : Chunk() {
lateinit var values: Array<Number?>
override fun init(buffer: ByteReader, length: Int) {
val numberOfItems = buffer.unsignedShort
val tempList = arrayOfNulls<ByteReader?>(numberOfItems);
for (i in 0..numberOfItems - 1) {
tempList[i] = ByteReader(buffer.getBytes(4));
}
values = arrayOfNulls<Number?>(numberOfItems)
for (i in 0..numberOfItems - 1) {
val reader = tempList[i]!!;
val value : Number;
val type = buffer.unsignedByte.toInt()
if (type == 2) { // Float/Double
value = reader.float
} else if (type == 0) { // Int
value = reader.int
} else {
throw IllegalArgumentException("Invalid GlobalValue type $type.");
}
values[i] = value
}
}
}
| core/src/main/java/net/jselby/escapists/data/chunks/Globals.kt | 4162043809 |
/**
* 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.changeauditdao
import com.gs.obevo.api.appdata.Change
import com.gs.obevo.api.appdata.ChangeIncremental
import com.gs.obevo.api.appdata.ChangeKey
import com.gs.obevo.api.appdata.ChangeRerunnable
import com.gs.obevo.api.appdata.DeployExecution
import com.gs.obevo.api.appdata.DeployExecutionImpl
import com.gs.obevo.api.appdata.DeployExecutionStatus
import com.gs.obevo.api.appdata.PhysicalSchema
import com.gs.obevo.api.platform.AuditLock
import com.gs.obevo.api.platform.ChangeAuditDao
import com.gs.obevo.api.platform.ChangeType
import com.gs.obevo.db.api.appdata.DbEnvironment
import com.gs.obevo.db.api.appdata.Grant
import com.gs.obevo.db.api.appdata.GrantTargetType
import com.gs.obevo.db.api.appdata.Permission
import com.gs.obevo.db.api.platform.DbChangeTypeBehavior
import com.gs.obevo.db.api.platform.SqlExecutor
import com.gs.obevo.dbmetadata.api.DaSchemaInfoLevel
import com.gs.obevo.dbmetadata.api.DaTable
import com.gs.obevo.dbmetadata.api.DbMetadataManager
import com.gs.obevo.impl.ChangeTypeBehaviorRegistry
import com.gs.obevo.util.VisibleForTesting
import com.gs.obevo.util.knex.InternMap
import org.apache.commons.dbutils.handlers.MapListHandler
import org.eclipse.collections.api.list.ImmutableList
import org.eclipse.collections.impl.block.function.checked.ThrowingFunction
import org.eclipse.collections.impl.factory.Lists
import org.eclipse.collections.impl.factory.Multimaps
import org.eclipse.collections.impl.factory.Sets
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.slf4j.LoggerFactory
import java.sql.Connection
import java.sql.Timestamp
/**
* AuditDao that will write the audit to the same db schema as the Change audit
*/
class SameSchemaChangeAuditDao(private val env: DbEnvironment, private val sqlExecutor: SqlExecutor, private val dbMetadataManager: DbMetadataManager,
private val deployUserId: String, private val deployExecutionDao: SameSchemaDeployExecutionDao, private val changeTypeBehaviorRegistry: ChangeTypeBehaviorRegistry) : ChangeAuditDao {
private val dbChangeTable: String
private val changeNameColumn: String
private val changeTypeColumn: String
private val deployUserIdColumn: String
private val timeInsertedColumn: String
private val timeUpdatedColumn: String
private val rollbackContentColumn: String
private val insertDeployExecutionIdColumn: String
private val updateDeployExecutionIdColumn: String
private val currentTimestamp: Timestamp
get() = Timestamp(DateTime().millis)
init {
val convertDbObjectName = env.platform.convertDbObjectName()
this.dbChangeTable = convertDbObjectName.valueOf(ChangeAuditDao.CHANGE_AUDIT_TABLE_NAME) // for backwards-compatibility, the dbChange table is named "ARTIFACTDEPLOYMENT". We hope to migrate existing tables eventually
this.changeNameColumn = convertDbObjectName.valueOf("ARTIFACTPATH") // for backwards-compatibility, the changeName column is named "ArtifactPath". We hope to migrate existing tables eventually
this.changeTypeColumn = convertDbObjectName.valueOf("CHANGETYPE")
this.deployUserIdColumn = convertDbObjectName.valueOf("DEPLOY_USER_ID")
this.timeInsertedColumn = convertDbObjectName.valueOf("TIME_INSERTED")
this.timeUpdatedColumn = convertDbObjectName.valueOf("TIME_UPDATED")
this.rollbackContentColumn = convertDbObjectName.valueOf("ROLLBACKCONTENT")
this.insertDeployExecutionIdColumn = convertDbObjectName.valueOf("INSERTDEPLOYID")
this.updateDeployExecutionIdColumn = convertDbObjectName.valueOf("UPDATEDEPLOYID")
}
override fun getAuditContainerName(): String {
return dbChangeTable
}
override fun init() {
for (schema in env.schemaNames) {
val physicalSchema = env.getPhysicalSchema(schema)
sqlExecutor.executeWithinContext(physicalSchema) { conn -> init(conn, schema) }
}
}
private fun init(conn: Connection, schema: String) {
val physicalSchema = env.getPhysicalSchema(schema)
val artifactTable = queryAuditTable(physicalSchema)
val jdbc = sqlExecutor.jdbcTemplate
if (artifactTable == null) {
val auditTableSql = get5_1Sql(physicalSchema)
jdbc.execute(conn, auditTableSql)
// We only grant SELECT access to PUBLIC so that folks can read the audit table without DBO permission
// (we don't grant R/W access, as we assume whatever login that executes deployments already has DBO access,
// and so can modify this table)
val tableChangeType = changeTypeBehaviorRegistry.getChangeTypeBehavior(ChangeType.TABLE_STR) as DbChangeTypeBehavior
if (env.platform.isPublicSchemaSupported) {
tableChangeType.applyGrants(conn, physicalSchema, dbChangeTable, Lists.immutable.with(Permission("artifacTable",
Lists.immutable.with(Grant(Lists.immutable.with("SELECT"), Multimaps.immutable.list.with(GrantTargetType.PUBLIC, "PUBLIC"))))))
}
} else {
// We will still grant this here to make up for the existing DBs that did not have the grants given
val tableChangeType = changeTypeBehaviorRegistry.getChangeTypeBehavior(ChangeType.TABLE_STR) as DbChangeTypeBehavior
val schemaPlusTable = env.platform.getSubschemaPrefix(physicalSchema) + dbChangeTable
// Here, we detect if we are on an older version of the table due to missing columns (added for version
// 3.9.0). If we find the
// columns are missing, we will add them and backfill
if (artifactTable.getColumn(deployUserIdColumn) == null) {
jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable,
deployUserIdColumn, "VARCHAR(32)", env.platform.nullMarkerForCreateTable))
jdbc.execute(conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable,
deployUserIdColumn, "'backfill'"))
}
if (artifactTable.getColumn(timeUpdatedColumn) == null) {
jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable,
timeUpdatedColumn, env.platform.timestampType, env.platform
.nullMarkerForCreateTable))
jdbc.execute(
conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, timeUpdatedColumn, "'"
+ TIMESTAMP_FORMAT.print(DateTime()) + "'"))
}
if (artifactTable.getColumn(timeInsertedColumn) == null) {
jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable,
timeInsertedColumn, env.platform.timestampType, env.platform
.nullMarkerForCreateTable))
jdbc.execute(conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, timeInsertedColumn, timeUpdatedColumn))
}
if (artifactTable.getColumn(rollbackContentColumn) == null) {
jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable,
rollbackContentColumn, env.platform.textType, env.platform.nullMarkerForCreateTable))
// for the 3.12.0 release, we will also update the METADATA changeType value to STATICDATA
jdbc.execute(conn, String.format("UPDATE %1\$s SET %2\$s='%3\$s' WHERE %2\$s='%4\$s'",
schemaPlusTable, changeTypeColumn, ChangeType.STATICDATA_STR,
OLD_STATICDATA_CHANGETYPE))
}
if (artifactTable.getColumn(insertDeployExecutionIdColumn) == null) {
jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable,
insertDeployExecutionIdColumn, env.platform.bigIntType, env.platform.nullMarkerForCreateTable))
// If this column doesn't exist, it means we've just moved to the version w/ the DeployExecution table.
// Let's add a row here to backfill the data.
val deployExecution = DeployExecutionImpl("backfill", "backfill", schema, "0.0.0", currentTimestamp, false, false, null, "backfill", Sets.immutable.empty())
deployExecution.status = DeployExecutionStatus.SUCCEEDED
deployExecutionDao.persistNewSameContext(conn, deployExecution, physicalSchema)
jdbc.execute(conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, insertDeployExecutionIdColumn, deployExecution.id))
}
if (artifactTable.getColumn(updateDeployExecutionIdColumn) == null) {
jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable,
updateDeployExecutionIdColumn, env.platform.bigIntType, env.platform.nullMarkerForCreateTable))
jdbc.execute(conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, updateDeployExecutionIdColumn, insertDeployExecutionIdColumn))
}
}
}
private fun queryAuditTable(physicalSchema: PhysicalSchema): DaTable? {
return this.dbMetadataManager.getTableInfo(physicalSchema, dbChangeTable, DaSchemaInfoLevel().setRetrieveTableColumns(true))
}
/**
* SQL for the 5.0.x upgrade.
* We keep in separate methods to allow for easy testing of the upgrades in SameSchemaChangeAuditDaoTest for different DBMSs
*/
@VisibleForTesting
fun get5_0Sql(physicalSchema: PhysicalSchema): String {
return if (env.auditTableSql != null)
env.auditTableSql
else
String.format("CREATE TABLE " + env.platform.getSchemaPrefix(physicalSchema) + dbChangeTable + " ( \n" +
" ARTFTYPE \tVARCHAR(31) NOT NULL,\n" +
" " + changeNameColumn + "\tVARCHAR(255) NOT NULL,\n" +
" OBJECTNAME \tVARCHAR(255) NOT NULL,\n" +
" ACTIVE \tINTEGER %1\$s,\n" +
" " + changeTypeColumn + " \tVARCHAR(255) %1\$s,\n" +
" CONTENTHASH \tVARCHAR(255) %1\$s,\n" +
" DBSCHEMA \tVARCHAR(255) %1\$s,\n" +
" " + deployUserIdColumn + " \tVARCHAR(32) %1\$s,\n" +
" " + timeInsertedColumn + " \t" + env.platform.timestampType + " %1\$s,\n" +
" " + timeUpdatedColumn + " \t" + env.platform.timestampType + " %1\$s,\n" +
" " + rollbackContentColumn + "\t" + env.platform.textType + " %1\$s,\n" +
" CONSTRAINT ARTDEFPK PRIMARY KEY(" + changeNameColumn + ",OBJECTNAME)\n" +
") %2\$s\n", env.platform.nullMarkerForCreateTable, env.platform.getTableSuffixSql(env))
}
/**
* SQL for the 5.1.x upgrade.
* We keep in separate methods to allow for easy testing of the upgrades in SameSchemaChangeAuditDaoTest for different DBMSs
*/
@VisibleForTesting
fun get5_1Sql(physicalSchema: PhysicalSchema): String {
return if (env.auditTableSql != null)
env.auditTableSql
else
String.format("CREATE TABLE " + env.platform.getSchemaPrefix(physicalSchema) + dbChangeTable + " ( \n" +
" ARTFTYPE \tVARCHAR(31) NOT NULL,\n" +
" " + changeNameColumn + "\tVARCHAR(255) NOT NULL,\n" +
" OBJECTNAME \tVARCHAR(255) NOT NULL,\n" +
" ACTIVE \tINTEGER %1\$s,\n" +
" " + changeTypeColumn + " \tVARCHAR(255) %1\$s,\n" +
" CONTENTHASH \tVARCHAR(255) %1\$s,\n" +
" DBSCHEMA \tVARCHAR(255) %1\$s,\n" +
" " + deployUserIdColumn + " \tVARCHAR(32) %1\$s,\n" +
" " + timeInsertedColumn + " \t" + env.platform.timestampType + " %1\$s,\n" +
" " + timeUpdatedColumn + " \t" + env.platform.timestampType + " %1\$s,\n" +
" " + rollbackContentColumn + "\t" + env.platform.textType + " %1\$s,\n" +
" " + insertDeployExecutionIdColumn + "\t" + env.platform.bigIntType + " %1\$s,\n" +
" " + updateDeployExecutionIdColumn + "\t" + env.platform.bigIntType + " %1\$s,\n" +
" CONSTRAINT ARTDEFPK PRIMARY KEY(" + changeNameColumn + ",OBJECTNAME)\n" +
") %2\$s\n", env.platform.nullMarkerForCreateTable, env.platform.getTableSuffixSql(env))
}
override fun insertNewChange(change: Change, deployExecution: DeployExecution) {
sqlExecutor.executeWithinContext(change.getPhysicalSchema(env)) { conn -> insertNewChangeInternal(conn, change, deployExecution) }
}
private fun insertNewChangeInternal(conn: Connection, change: Change, deployExecution: DeployExecution) {
val jdbcTemplate = sqlExecutor.jdbcTemplate
val currentTimestamp = currentTimestamp
jdbcTemplate.update(
conn, "INSERT INTO " + env.platform.getSchemaPrefix(change.getPhysicalSchema(env))
+ dbChangeTable +
" (ARTFTYPE, DBSCHEMA, ACTIVE, CHANGETYPE, CONTENTHASH, " + changeNameColumn + ", OBJECTNAME, "
+ rollbackContentColumn + ", " + deployUserIdColumn + ", " + timeInsertedColumn + ", " + timeUpdatedColumn + ", " + insertDeployExecutionIdColumn + ", " + updateDeployExecutionIdColumn + ") " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", if (change is ChangeIncremental) "I" else "R", change.schema, if (change.isActive) 1 else 0, change.changeType.name, change.contentHash, change.changeName, change.objectName, change.rollbackContent, deployUserId, currentTimestamp, currentTimestamp, deployExecution.id, deployExecution.id
)
}
override fun updateOrInsertChange(change: Change, deployExecution: DeployExecution) {
sqlExecutor.executeWithinContext(change.getPhysicalSchema(env)) { conn ->
val numRowsUpdated = updateInternal(conn, change, deployExecution)
if (numRowsUpdated == 0) {
insertNewChangeInternal(conn, change, deployExecution)
}
}
}
override fun getDeployedChanges(): ImmutableList<Change> {
val convertDbObjectName = env.platform.convertDbObjectName()
val artfs = env.schemaNames.flatMap { schema ->
val deployExecutionsById = deployExecutionDao.getDeployExecutions(schema).associateBy(DeployExecution::getId)
val physicalSchema = env.getPhysicalSchema(schema)
sqlExecutor.executeWithinContext(physicalSchema, ThrowingFunction<Connection, List<Change>> { conn ->
val jdbcTemplate = sqlExecutor.jdbcTemplate
val artifactTable = queryAuditTable(physicalSchema)
?: return@ThrowingFunction emptyList() // If the artifact tables does not exist, then return empty list for that schema
return@ThrowingFunction jdbcTemplate.query(
conn, "SELECT * FROM " + env.platform.getSchemaPrefix(physicalSchema) + dbChangeTable
+ " WHERE DBSCHEMA = '" + schema + "'", MapListHandler()).map { resultSet ->
val artfType = resultSet[convertDbObjectName.valueOf("ARTFTYPE")] as String
val artf: Change
if (artfType == "I") {
artf = ChangeIncremental()
} else if (artfType == "R") {
artf = ChangeRerunnable()
} else {
throw IllegalArgumentException("This type does not exist $artfType")
}
var changeType = resultSet[changeTypeColumn] as String
changeType = if (changeType == OLD_STATICDATA_CHANGETYPE) ChangeType.STATICDATA_STR else changeType
artf.changeKey = ChangeKey(
InternMap.instance().intern(resultSet[convertDbObjectName.valueOf("DBSCHEMA")] as String),
env.platform.getChangeType(changeType),
InternMap.instance().intern(resultSet[convertDbObjectName.valueOf("OBJECTNAME")] as String),
resultSet[convertDbObjectName.valueOf(changeNameColumn)] as String
)
artf.isActive = env.platform.getIntegerValue(resultSet[convertDbObjectName.valueOf("ACTIVE")]) == 1
// change METADATA to STATICDATA for backward compatability
artf.contentHash = resultSet[convertDbObjectName.valueOf("CONTENTHASH")] as String?
// these are repeated often
artf.timeInserted = env.platform.getTimestampValue(resultSet[convertDbObjectName.valueOf(timeInsertedColumn)])
artf.timeUpdated = env.platform.getTimestampValue(resultSet[convertDbObjectName.valueOf(timeUpdatedColumn)])
artf.deployExecution = deployExecutionsById[env.platform.getLongValue(resultSet[updateDeployExecutionIdColumn])]
// for backward compatibility, make sure the ROLLBACKCONTENT column exists
if (artifactTable.getColumn(rollbackContentColumn) != null) {
artf.rollbackContent = resultSet[rollbackContentColumn] as String?
}
artf
}
})
}
// This block is to aim to backfill the "orderWithinObject" field, since we don't persist it in the database
val incrementalChanges = artfs.filterNot { it.changeType.isRerunnable }
val incrementalChangeMap = incrementalChanges.groupBy(Change::getObjectKey)
incrementalChangeMap.values.forEach { objectChanges ->
val sortedObjectChanges = objectChanges.sortedBy(Change::getTimeInserted)
sortedObjectChanges.forEachIndexed { index, each -> each.orderWithinObject = 5000 + index }
}
return Lists.immutable.ofAll(artfs.toSet().toList().filter { env.schemaNames.contains(it.schema) })
}
override fun deleteChange(change: Change) {
sqlExecutor.executeWithinContext(change.getPhysicalSchema(env)) { conn ->
sqlExecutor.jdbcTemplate.update(
conn, "DELETE FROM " + env.platform.getSchemaPrefix(change.getPhysicalSchema(env))
+ dbChangeTable + " WHERE " + changeNameColumn + " = ? AND OBJECTNAME = ?", change.changeName, change.objectName)
}
}
override fun deleteObjectChanges(change: Change) {
sqlExecutor.executeWithinContext(change.getPhysicalSchema(env)) { conn ->
sqlExecutor.jdbcTemplate.update(
conn, "DELETE FROM " + env.platform.getSchemaPrefix(change.getPhysicalSchema(env))
+ dbChangeTable + " WHERE OBJECTNAME = ? AND CHANGETYPE = ?",
change.objectName,
change.changeType.name
)
// TODO delete this eventually
sqlExecutor.jdbcTemplate.update(
conn, "DELETE FROM " + env.platform.getSchemaPrefix(change.getPhysicalSchema(env))
+ dbChangeTable + " WHERE OBJECTNAME = ? AND CHANGETYPE = ?",
change.objectName,
"GRANT"
)
}
}
private fun updateInternal(conn: Connection, artifact: Change, deployExecution: DeployExecution): Int {
return sqlExecutor.jdbcTemplate.update(
conn, "UPDATE " + env.platform.getSchemaPrefix(artifact.getPhysicalSchema(env)) + dbChangeTable
+ " SET " +
"ARTFTYPE = ?, " +
"DBSCHEMA = ?, " +
"ACTIVE = ?, " +
"CHANGETYPE = ?, " +
"CONTENTHASH = ?, " +
rollbackContentColumn + " = ?, " +
deployUserIdColumn + " = ?, " +
timeUpdatedColumn + " = ?, " +
updateDeployExecutionIdColumn + " = ? " +
"WHERE " + changeNameColumn + " = ? AND OBJECTNAME = ?", if (artifact is ChangeIncremental) "I" else "R", artifact.schema, if (artifact.isActive) 1 else 0, artifact.changeType.name, artifact.contentHash, artifact.rollbackContent, deployUserId, currentTimestamp, deployExecution.id, artifact.changeName, artifact.objectName
)
}
override fun acquireLock(): AuditLock {
return sqlExecutor.executeWithinContext(env.physicalSchemas.first, ThrowingFunction { sqlExecutor.lock(it) })
}
companion object {
private val LOG = LoggerFactory.getLogger(SameSchemaChangeAuditDao::class.java)
private val TIMESTAMP_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS")
// older version of static data
private val OLD_STATICDATA_CHANGETYPE = "METADATA"
}
}
| obevo-db/src/main/java/com/gs/obevo/db/impl/core/changeauditdao/SameSchemaChangeAuditDao.kt | 2825740542 |
/*
* This file is part of CurrentActivity.
*
* Copyright (C) 2022 Omico
*
* CurrentActivity 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.
*
* CurrentActivity 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 CurrentActivity. If not, see <https://www.gnu.org/licenses/>.
*/
package me.omico.currentactivity.utility
import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
val Context.installedPackages: List<PackageInfo>
get() = when {
Build.VERSION.SDK_INT >= 33 ->
packageManager.getInstalledPackages(PackageManager.PackageInfoFlags.of(0L))
else -> @Suppress("DEPRECATION") packageManager.getInstalledPackages(0)
}
fun Context.isPackageInstalled(packageName: String): Boolean =
installedPackages.find { it.packageName == packageName } != null
| core/common/src/main/kotlin/me/omico/currentactivity/utility/PackageManager.kt | 1518335201 |
fun main(args : Array<String>) {
for (i in 1..100) {
when {
i%3 == 0 -> {print("Fizz"); continue;}
i%5 == 0 -> {print("Buzz"); continue;}
(i%3 != 0 && i%5 != 0) -> {print(i); continue;}
else -> println()
}
}
}
fun foo() : Unit {
<selection>println() {
println()
pr<caret>intln()
println()
}</selection>
println(array(1, 2, 3))
println()
} | kotlin-eclipse-ui-test/testData/wordSelection/selectEnclosing/Statements/5.kt | 2309575934 |
package io.mockk.it
import io.mockk.*
import kotlin.test.Test
import kotlin.test.assertEquals
class AnswersTest {
class MockCls {
fun op(a: Int, b: Int, c: Int = 10, d: Int = 25) = a + b + c + d
fun lambdaOp(a: Int, b: () -> Int) = a + b()
}
val spy = spyk(MockCls())
@Test
fun answerFirstArg() {
every { spy.op(any(), 5) } answers { if (firstArg<Int>() == 1) 1 else 2 }
assertEquals(1, spy.op(1, 5))
assertEquals(2, spy.op(2, 5))
}
@Test
fun answerSecondArg() {
every { spy.op(6, any()) } answers { if (secondArg<Int>() == 2) 3 else 4 }
assertEquals(3, spy.op(6, 2))
assertEquals(4, spy.op(6, 3))
}
@Test
fun answerThirdArg() {
every { spy.op(any(), 7, any()) } answers { if (thirdArg<Int>() == 9) 5 else 6 }
assertEquals(5, spy.op(2, 7, 9))
assertEquals(6, spy.op(3, 7, 10))
}
@Test
fun answerLastArg() {
every { spy.op(any(), 7, d = any()) } answers { if (lastArg<Int>() == 11) 7 else 8 }
assertEquals(7, spy.op(2, 7, d = 11))
assertEquals(8, spy.op(3, 7, d = 12))
}
@Test
fun answerNArgs() {
every { spy.op(any(), 1) } answers { nArgs }
assertEquals(4, spy.op(2, 1))
}
@Test
fun answerParamTypesCount() {
every { spy.op(any(), 2) } answers { method.paramTypes.size }
assertEquals(4, spy.op(2, 2))
}
@Test
fun answerCaptureList() {
val lstNonNull = mutableListOf<Int>()
every { spy.op(1, 2, d = capture(lstNonNull)) } answers { lstNonNull.captured() }
assertEquals(22, spy.op(1, 2, d = 22))
}
@Test
fun answerCaptureListNullable() {
val lst = mutableListOf<Int?>()
every { spy.op(3, 4, d = captureNullable(lst)) } answers { lst.captured()!! }
assertEquals(33, spy.op(3, 4, d = 33))
}
@Test
fun answerCaptureSlot() {
val slot = slot<Int>()
every { spy.op(3, 4, d = capture(slot)) } answers { slot.captured }
assertEquals(44, spy.op(3, 4, d = 44))
}
@Test
fun answerCaptureLambda() {
val slot = slot<() -> Int>()
every { spy.lambdaOp(1, capture(slot)) } answers { 2 + slot.invoke() }
assertEquals(5, spy.lambdaOp(1, { 3 }))
verify { spy.lambdaOp(1, any()) }
}
@Test
fun answersNthArg() {
every { spy.lambdaOp(any(), any()) } returnsArgument 0
assertEquals(1, spy.lambdaOp(1) { 3 })
assertEquals(2, spy.lambdaOp(2) { 3 })
assertEquals(5, spy.lambdaOp(5) { 3 })
verify { spy.lambdaOp(1, any()) }
}
} | mockk/common/src/test/kotlin/io/mockk/it/AnswersTest.kt | 3469424843 |
package org.jetbrains.kotlin.ui.tests.editors.completion
import org.jetbrains.kotlin.testframework.editor.KotlinProjectTestCase
import org.junit.Before
import org.jetbrains.kotlin.testframework.utils.KotlinTestUtils
import org.jetbrains.kotlin.ui.editors.KotlinFileEditor
import org.jetbrains.kotlin.ui.editors.codeassist.KotlinCompletionProcessor
import org.jetbrains.kotlin.core.builder.KotlinPsiManager
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.testframework.editor.TextEditorTest
import org.junit.Assert
open public class KotlinFunctionParameterInfoTestCase : KotlinProjectTestCase() {
@Before
fun before() {
configureProject()
}
protected fun doTest(testPath: String) {
val fileText = KotlinTestUtils.getText(testPath)
val testEditor = configureEditor(KotlinTestUtils.getNameByPath(testPath), fileText)
val actualResult = getContextInformation(testEditor.getEditor() as KotlinFileEditor)
val expectedResult = getExpectedResult(testEditor)
val agreement = actualResult.size == expectedResult.size &&
actualResult.all { actualResult ->
expectedResult.any { expectedResult ->
actualResult == expectedResult
}
}
Assert.assertTrue("$expectedResult are not equals to $actualResult", agreement)
}
private fun getExpectedResult(testEditor: TextEditorTest): List<String> {
val jetFile = KotlinPsiManager.getParsedFile(testEditor.getEditingFile())
val lastChild = jetFile.getLastChild()
val expectedText = if (lastChild.getNode().getElementType() == KtTokens.BLOCK_COMMENT) {
val lastChildText = lastChild.getText()
lastChildText.substring(2, lastChildText.length - 2).trim()
} else { // EOL_COMMENT
lastChild.getText().substring(2).trim()
}
val regex = "\\((.*)\\)".toRegex()
val beginHighlightRegex = "<highlight>".toRegex()
val endHighlightRegex = "</highlight>".toRegex()
val noParametersRegex = "<no parameters>".toRegex()
return expectedText.split("\n")
.map { line ->
val match = regex.find(line)
val displayString = match!!.groups[1]!!.value
displayString
.replace(beginHighlightRegex, "")
.replace(endHighlightRegex, "")
.replace(noParametersRegex, "")
}
.filter { it.isNotBlank() }
}
private fun getContextInformation(editor: KotlinFileEditor): List<String> {
val completionProcessor = KotlinCompletionProcessor(editor)
val contextInformation = completionProcessor.computeContextInformation(editor.getViewer(),
KotlinTestUtils.getCaret(editor))
return contextInformation.map { it.getInformationDisplayString() }
}
} | kotlin-eclipse-ui-test/src/org/jetbrains/kotlin/ui/tests/editors/completion/KotlinFunctionParameterInfoTestCase.kt | 2678358311 |
/*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 Aleksey Kladov, Evgeny Kurbatsky, Alexey Kudinkin and contributors
Copyright (c) 2016 JetBrains
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.elm.utils
import kotlin.system.measureTimeMillis
class Timings(
private val valuesTotal: LinkedHashMap<String, Long> = LinkedHashMap(),
private val invokes: MutableMap<String, Long> = mutableMapOf()
) {
fun <T> measure(name: String, f: () -> T): T {
check(name !in valuesTotal)
return measureInternal(name, f)
}
fun <T> measureAverage(name: String, f: () -> T): T = measureInternal(name, f)
fun merge(other: Timings): Timings {
val values = values()
val otherValues = other.values()
check(values.isEmpty() || otherValues.isEmpty() || values.size == otherValues.size)
val result = Timings()
for (k in values.keys.union(otherValues.keys)) {
result.valuesTotal[k] =
// https://www.youtube.com/watch?v=vrfYLlR8X8k&feature=youtu.be&t=25m17s
minOf(values.getOrDefault(k, Long.MAX_VALUE), otherValues.getOrDefault(k, Long.MAX_VALUE))
result.invokes[k] = 1
}
return result
}
fun report() {
val values = values()
if (values.isEmpty()) {
println("No metrics recorder")
return
}
val width = values.keys.map { it.length }.maxByOrNull { i: Int -> i }!!
for ((k, v) in values) {
println("${k.padEnd(width)}: $v ms")
}
val total = values.values.sum()
println("$total ms total.")
println()
}
private fun <T> measureInternal(name: String, f: () -> T): T {
var result: T? = null
val time = measureTimeMillis { result = f() }
valuesTotal.merge(name, time, Long::plus)
invokes.merge(name, 1, Long::plus)
@Suppress("UNCHECKED_CAST")
return result as T
}
private fun values(): Map<String, Long> {
val result = LinkedHashMap<String, Long>()
for ((k, sum) in valuesTotal) {
result[k] = (sum.toDouble() / invokes[k]!!).toLong()
}
return result
}
}
| src/main/kotlin/org/elm/utils/Timings.kt | 76402832 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.psi.mixins.impl
import com.demonwav.mcdev.nbt.lang.psi.mixins.NbttByteMixin
import com.demonwav.mcdev.nbt.tags.TagByte
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import org.apache.commons.lang3.StringUtils
abstract class NbttByteImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), NbttByteMixin {
override fun getByteTag(): TagByte {
return when (text) {
"false" -> TagByte(0)
"true" -> TagByte(1)
else -> TagByte(StringUtils.replaceChars(text.trim(), "bB", null).toByte())
}
}
}
| src/main/kotlin/nbt/lang/psi/mixins/impl/NbttByteImplMixin.kt | 3618345026 |
package com.teo.ttasks
@Target(AnnotationTarget.CLASS)
annotation class OpenClassOnDebug
| t-tasks/src/release/java/com/teo/ttasks/OpenClassOnDebug.kt | 3763644704 |
/*
* Copyright (c) 2017 stfalcon.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stfalcon.new_uaroads_android.features.places.adapter
import android.content.Context
import android.view.View
import com.stfalcon.new_uaroads_android.common.network.models.response.GeoPlacePrediction
import com.stfalcon.new_uaroads_android.common.ui.list.BaseListAdapter
import com.stfalcon.new_uaroads_android.common.ui.list.BaseViewHolder
import javax.inject.Inject
/*
* Created by Anton Bevza on 4/12/17.
*/
class PlacesListAdapter @Inject constructor() : BaseListAdapter<GeoPlacePrediction>() {
var onClickItem: ((view: View, item: GeoPlacePrediction) -> Unit)? = null
override fun getListItemView(context: Context): BaseViewHolder<GeoPlacePrediction> {
return PlaceViewHolder(context, onClickItem)
}
} | app/src/main/java/com/stfalcon/new_uaroads_android/features/places/adapter/PlacesListAdapter.kt | 696137610 |
package reagent.rxjava2
import io.reactivex.disposables.Disposable
import kotlinx.coroutines.experimental.CoroutineStart.UNDISPATCHED
import kotlinx.coroutines.experimental.Unconfined
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.suspendCancellableCoroutine
import reagent.Emitter
import reagent.Observable
import io.reactivex.Observable as RxObservable
import io.reactivex.Observer as RxObserver
internal class ObservableRxToReagent<I>(private val upstream: RxObservable<I>) : Observable<I>() {
override suspend fun subscribe(emit: Emitter<I>) {
suspendCancellableCoroutine<Unit> { continuation ->
upstream.subscribe(object : RxObserver<I> {
override fun onSubscribe(d: Disposable) {
continuation.invokeOnCompletion {
if (continuation.isCancelled) {
d.dispose()
}
}
}
override fun onNext(item: I) {
launch(Unconfined, UNDISPATCHED, parent = continuation) {
emit(item)
}
}
override fun onComplete() {
continuation.resume(Unit)
}
override fun onError(e: Throwable) {
continuation.resumeWithException(e)
}
})
}
}
}
| reagent-rxjava2/src/main/kotlin/reagent/rxjava2/ObservableRxToReagent.kt | 3136558233 |
package com.intfocus.template.subject.one
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import com.intfocus.template.ConfigConstants
import com.intfocus.template.constant.Params
import com.intfocus.template.constant.Params.USER_BEAN
import com.intfocus.template.general.net.ApiException
import com.intfocus.template.general.net.CodeHandledSubscriber
import com.intfocus.template.general.net.RetrofitUtil
import com.intfocus.template.model.response.BaseResult
import com.intfocus.template.model.response.mine_page.UserInfoResult
import com.intfocus.template.util.*
import com.taobao.accs.utl.UtilityImpl
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONException
import org.json.JSONObject
import rx.Subscription
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
/**
* ****************************************************
* @author jameswong
* created on: 17/10/25 下午5:11
* e-mail: [email protected]
* name:
* desc: 模板一 Model 层
* ****************************************************
*/
class UserImpl : UserModel {
companion object {
private val TAG = "UserImpl"
private var INSTANCE: UserImpl? = null
private var observable: Subscription? = null
/**
* Returns the single instance of this class, creating it if necessary.
*/
@JvmStatic
fun getInstance(): UserImpl {
return INSTANCE ?: UserImpl()
.apply { INSTANCE = this }
}
/**
* Used to force [getInstance] to create a new instance
* next time it's called.
*/
@JvmStatic
fun destroyInstance() {
unSubscribe()
INSTANCE = null
}
/**
* 取消订阅
*/
private fun unSubscribe() {
observable?.unsubscribe() ?: return
}
}
override fun getData(ctx: Context, callBack: UserModel.LoadDataCallback) {
val mUserSP = ctx.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE)
RetrofitUtil.getHttpService(ctx).getUserInfo(mUserSP.getString(Params.USER_NUM, ""))
.compose(RetrofitUtil.CommonOptions<UserInfoResult>())
.subscribe(object : CodeHandledSubscriber<UserInfoResult>() {
override fun onBusinessNext(data: UserInfoResult?) {
data?.let { callBack.onDataLoaded(it) }
}
override fun onError(apiException: ApiException?) {
apiException?.let { callBack.onDataNotAvailable(it.displayMessage) }
}
override fun onCompleted() {
}
})
}
@SuppressLint("SimpleDateFormat")
override fun uploadUserIcon(ctx: Context, bitmap: Bitmap, imgPath: String, callBack: UserModel.ShowMsgCallback) {
val mUserSP = ctx.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE)
val format = SimpleDateFormat("yyyyMMddHHmmss")
val date = Date(System.currentTimeMillis())
File(imgPath).delete()
val gravatarImgPath = FileUtil.dirPath(ctx, K.K_CONFIG_DIR_NAME, ConfigConstants.kAppCode + "_" + mUserSP.getString(Params.USER_NUM, "") + "_" + format.format(date) + ".jpg")
FileUtil.saveImage(gravatarImgPath, bitmap)
val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), File(gravatarImgPath))
val multiPartBody = MultipartBody.Part.createFormData("gravatar", mUserSP.getString(K.K_USER_ID, "0") + "icon", requestBody)
RetrofitUtil.getHttpService(ctx).userIconUpload(mUserSP.getString(K.K_USER_DEVICE_ID, "0"), mUserSP.getString(Params.USER_NUM, "0"), multiPartBody)
.compose(RetrofitUtil.CommonOptions<BaseResult>())
.subscribe(object : CodeHandledSubscriber<BaseResult>() {
override fun onBusinessNext(data: BaseResult?) {
callBack.showSuccessMsg("头像已上传")
}
override fun onError(apiException: ApiException?) {
apiException?.let { callBack.showErrorMsg(it.displayMessage) }
}
override fun onCompleted() {
}
})
}
override fun logout(ctx: Context, callBack: UserModel.LogoutCallback) {
val mUserSP = ctx.getSharedPreferences(USER_BEAN, Context.MODE_PRIVATE)
// 判断有无网络
if (!UtilityImpl.isNetworkConnected(ctx)) {
callBack.logoutFailure("未连接网络, 无法退出")
return
}
val mEditor = ctx.getSharedPreferences("SettingPreference", Context.MODE_PRIVATE).edit()
mEditor.putBoolean("ScreenLock", false).apply()
// 退出登录 POST 请求
RetrofitUtil.getHttpService(ctx).userLogout(mUserSP.getString(K.K_USER_DEVICE_ID, "0"))
.compose(RetrofitUtil.CommonOptions<BaseResult>())
.subscribe(object : CodeHandledSubscriber<BaseResult>() {
override fun onBusinessNext(data: BaseResult?) {
if (data!!.code == "200") {
mUserSP.edit().putBoolean(Params.IS_LOGIN, false).apply()
ActionLogUtil.actionLog("退出登录")
modifiedUserConfig(ctx, false)
callBack.logoutSuccess()
} else {
callBack.logoutFailure(data.message!!)
}
}
override fun onCompleted() {
}
override fun onError(apiException: ApiException?) {
ToastUtils.show(ctx, apiException!!.message!!)
}
})
}
fun modifiedUserConfig(ctx: Context, isLogin: Boolean) {
try {
val configJSON = JSONObject()
configJSON.put("is_login", isLogin)
val userConfigPath = String.format("%s/%s", FileUtil.basePath(ctx), K.K_USER_CONFIG_FILE_NAME)
var userJSON = FileUtil.readConfigFile(userConfigPath)
userJSON = ApiHelper.mergeJson(userJSON, configJSON)
FileUtil.writeFile(userConfigPath, userJSON.toString())
val settingsConfigPath = FileUtil.dirPath(ctx, K.K_CONFIG_DIR_NAME, K.K_SETTING_CONFIG_FILE_NAME)
FileUtil.writeFile(settingsConfigPath, userJSON.toString())
} catch (e: IOException) {
e.printStackTrace()
} catch (e: JSONException) {
e.printStackTrace()
}
}
}
| app/src/main/java/com/intfocus/template/dashboard/user/UserImpl.kt | 970405261 |
package org.jetbrains.kotlinx.jupyter
import org.jetbrains.kotlinx.jupyter.api.arrayRenderer
import org.jetbrains.kotlinx.jupyter.api.bufferedImageRenderer
import org.jetbrains.kotlinx.jupyter.codegen.ResultsRenderersProcessor
import org.jetbrains.kotlinx.jupyter.compiler.util.CodeInterval
import org.jetbrains.kotlinx.jupyter.compiler.util.SourceCodeImpl
import org.jetbrains.kotlinx.jupyter.config.catchAll
import org.jetbrains.kotlinx.jupyter.libraries.KERNEL_LIBRARIES
import org.jetbrains.kotlinx.jupyter.libraries.parseLibraryDescriptor
import java.io.File
import java.util.Optional
import java.util.concurrent.ConcurrentHashMap
import kotlin.script.experimental.api.ScriptDiagnostic
import kotlin.script.experimental.api.SourceCode
import kotlin.script.experimental.jvm.util.determineSep
import kotlin.script.experimental.jvm.util.toSourceCodePosition
fun List<String>.joinToLines() = joinToString("\n")
fun generateDiagnostic(fromLine: Int, fromCol: Int, toLine: Int, toCol: Int, message: String, severity: String) =
ScriptDiagnostic(
ScriptDiagnostic.unspecifiedError,
message,
ScriptDiagnostic.Severity.valueOf(severity),
null,
SourceCode.Location(SourceCode.Position(fromLine, fromCol), SourceCode.Position(toLine, toCol))
)
fun generateDiagnosticFromAbsolute(code: String, from: Int, to: Int, message: String, severity: ScriptDiagnostic.Severity): ScriptDiagnostic {
val snippet = SourceCodeImpl(0, code)
return ScriptDiagnostic(
ScriptDiagnostic.unspecifiedError,
message,
severity,
null,
SourceCode.Location(from.toSourceCodePosition(snippet), to.toSourceCodePosition(snippet))
)
}
fun CodeInterval.diagnostic(code: String, message: String, severity: ScriptDiagnostic.Severity = ScriptDiagnostic.Severity.ERROR): ScriptDiagnostic {
return generateDiagnosticFromAbsolute(code, from, to, message, severity)
}
fun generateDiagnosticFromAbsolute(code: String, from: Int, to: Int, message: String, severity: String): ScriptDiagnostic {
return generateDiagnosticFromAbsolute(code, from, to, message, ScriptDiagnostic.Severity.valueOf(severity))
}
fun withPath(path: String?, diagnostics: List<ScriptDiagnostic>): List<ScriptDiagnostic> =
diagnostics.map { it.copy(sourcePath = path) }
fun String.findNthSubstring(s: String, n: Int, start: Int = 0): Int {
if (n < 1 || start == -1) return -1
var i = start
for (k in 1..n) {
i = indexOf(s, i)
if (i == -1) return -1
i += s.length
}
return i - s.length
}
fun SourceCode.Position.withNewAbsolute(code: SourceCode, newCode: SourceCode): SourceCode.Position? {
val sep = code.text.determineSep()
val absLineStart =
if (line == 1) 0
else newCode.text.findNthSubstring(sep, line - 1) + sep.length
var nextNewLinePos = newCode.text.indexOf(sep, absLineStart)
if (nextNewLinePos == -1) nextNewLinePos = newCode.text.length
val abs = absLineStart + col - 1
if (abs > nextNewLinePos) {
return null
}
return SourceCode.Position(line, col, abs)
}
fun Int.toSourceCodePositionWithNewAbsolute(code: SourceCode, newCode: SourceCode): SourceCode.Position? {
return toSourceCodePosition(code).withNewAbsolute(code, newCode)
}
fun ResultsRenderersProcessor.registerDefaultRenderers() {
register(bufferedImageRenderer)
register(arrayRenderer)
}
/**
* Stores info about where a variable Y was declared and info about what are they at the address X.
* K: key, stands for a way of addressing variables, e.g. address.
* V: value, from Variable, choose any suitable type for your variable reference.
* Default: T=Int, V=String
*/
class VariablesUsagesPerCellWatcher<K : Any, V : Any> {
val cellVariables = mutableMapOf<K, MutableSet<V>>()
/**
* Tells in which cell a variable was declared
*/
private val variablesDeclarationInfo: MutableMap<V, K> = mutableMapOf()
fun addDeclaration(address: K, variableRef: V) {
ensureStorageCreation(address)
// redeclaration of any type
if (variablesDeclarationInfo.containsKey(variableRef)) {
val oldCellId = variablesDeclarationInfo[variableRef]
if (oldCellId != address) {
cellVariables[oldCellId]?.remove(variableRef)
}
}
variablesDeclarationInfo[variableRef] = address
cellVariables[address]?.add(variableRef)
}
fun addUsage(address: K, variableRef: V) = cellVariables[address]?.add(variableRef)
fun removeOldUsages(newAddress: K) {
// remove known modifying usages in this cell
cellVariables[newAddress]?.removeIf {
variablesDeclarationInfo[it] != newAddress
}
}
fun ensureStorageCreation(address: K) = cellVariables.putIfAbsent(address, mutableSetOf())
}
fun <A, V> createCachedFun(calculate: (A) -> V): (A) -> V {
return createCachedFun({ it }, calculate)
}
fun <A, K, V> createCachedFun(calculateKey: (A) -> K, calculate: (A) -> V): (A) -> V {
val cache = ConcurrentHashMap<K, Optional<V>>()
return { argument ->
val key = calculateKey(argument)
cache.getOrPut(key) {
when (val value = calculate(argument)) {
null -> Optional.empty<V>()
else -> Optional.of(value)
} as Optional<V>
}.orElse(null)
}
}
val libraryDescriptors = createCachedFun(calculateKey = { file: File -> file.absolutePath }) { homeDir ->
val libraryFiles = KERNEL_LIBRARIES
.homeLibrariesDir(homeDir)
.listFiles(KERNEL_LIBRARIES::isLibraryDescriptor)
.orEmpty()
libraryFiles.toList().mapNotNull { file ->
val libraryName = file.nameWithoutExtension
log.info("Parsing descriptor for library '$libraryName'")
log.catchAll(msg = "Parsing descriptor for library '$libraryName' failed") {
libraryName to parseLibraryDescriptor(file.readText())
}
}.toMap()
}
| src/main/kotlin/org/jetbrains/kotlinx/jupyter/util.kt | 1308618110 |
package com.intfocus.template.subject.nine.collectionlist.adapter
import android.widget.Toast
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.intfocus.template.R
import com.intfocus.template.model.entity.Collection
import com.intfocus.template.util.TimeUtils
/**
* ****************************************************
* author jameswong
* created on: 17/12/29 下午0:01
* e-mail: [email protected]
* name:
* desc:
* ****************************************************
*/
class CollectionListAdapter : BaseQuickAdapter<Collection, BaseViewHolder>(R.layout.item_collection_list) {
override fun convert(helper: BaseViewHolder, item: Collection) {
val status = when {
item.status == 1 -> ""
item.status == 0 -> "上传中"
else -> "草稿"
}
helper.setText(R.id.tv_item_collection_list_status, status)
.setText(R.id.tv_item_collection_list_title, item.h1 ?: "")
.setText(R.id.tv_item_collection_list_content, item.h2 ?: "")
.setText(R.id.tv_item_collection_list_title_label, item.h3 ?: "")
.setGone(R.id.right_menu_sync, item.status != 1)
.setOnClickListener(R.id.rl_item_collection_list_container, { view ->
Toast.makeText(mContext, "onItemClick" + data.indexOf(item), Toast.LENGTH_SHORT).show()
})
.setOnClickListener(R.id.right_menu_delete, { view ->
remove(data.indexOf(item))
})
.setOnClickListener(R.id.right_menu_sync, { view ->
Toast.makeText(mContext, "onItemClick" + data.indexOf(item), Toast.LENGTH_SHORT).show()
})
item.updated_at?.let {
helper.setText(R.id.tv_item_collection_list_time, TimeUtils.getStandardDate(it))
}
}
} | app/src/main/java/com/intfocus/template/subject/nine/collectionlist/adapter/CollectionListAdapter.kt | 1695045462 |
package org.grandtestauto.indoflash.functiontest
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
/**
* See Issue #2.
* @author Tim Lavers
*/
@RunWith(AndroidJUnit4::class)
class AddSameWordTwiceToFavourites : TestBase() {
@Test
fun doIt() {
ui.checkCurrentWordIs("you")//Sanity check.
ui.addToOrRemoveFromFavourites()
ui.checkCurrentWordIs("you")//Sanity check that we are about to add the same word again to the favourites.
ui.addToOrRemoveFromFavourites()
ui.showDefinitionOfCurrentWord()
ui.activateNextButton()
ui.checkCurrentWordIs("what")//Sanity check that we added "you/anda" twice as a favourite.
ui.addToOrRemoveFromFavourites()//So that two distinct words have been added as favourites.
showFavourites()
ui.checkCurrentWordIs("you")
ui.checkTranslationIsEmpty()
ui.showDefinitionOfCurrentWord()
ui.checkTranslationIs("anda")
ui.activateNextButton()
ui.checkCurrentWordIs("what")//Not "you/anda" even though it was added twice.
}
} | app/src/androidTest/java/org/grandtestauto/indoflash/functiontest/AddSameWordTwiceToFavourites.kt | 983398848 |
package com.habitrpg.android.habitica.ui.viewHolders
import android.graphics.PorterDuff
import android.graphics.drawable.BitmapDrawable
import android.view.View
import android.view.ViewGroup
import androidx.core.graphics.drawable.toBitmap
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.PetDetailItemBinding
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.inventory.Animal
import com.habitrpg.android.habitica.models.inventory.Egg
import com.habitrpg.android.habitica.models.inventory.Food
import com.habitrpg.android.habitica.models.inventory.HatchingPotion
import com.habitrpg.android.habitica.models.inventory.Pet
import com.habitrpg.common.habitica.extensions.DataBindingUtils
import com.habitrpg.android.habitica.ui.menu.BottomSheetMenu
import com.habitrpg.android.habitica.ui.menu.BottomSheetMenuItem
import com.habitrpg.android.habitica.ui.views.dialogs.PetSuggestHatchDialog
import io.reactivex.rxjava3.subjects.PublishSubject
class PetViewHolder(
parent: ViewGroup,
private val equipEvents: PublishSubject<String>,
private val feedEvents: PublishSubject<Pair<Pet, Food?>>,
private val ingredientsReceiver: ((Animal, ((Pair<Egg?, HatchingPotion?>) -> Unit)) -> Unit)?
) : androidx.recyclerview.widget.RecyclerView.ViewHolder(parent.inflate(R.layout.pet_detail_item)),
View.OnClickListener {
private var hasMount: Boolean = false
private var hasUnlockedPotion: Boolean = false
private var hasUnlockedEgg: Boolean = false
private var eggCount: Int = 0
private var potionCount: Int = 0
private var ownsSaddles = false
private var animal: Pet? = null
private var currentPet: String? = null
private var binding: PetDetailItemBinding = PetDetailItemBinding.bind(itemView)
private var isOwned: Boolean = false
private var canRaiseToMount: Boolean = false
init {
itemView.setOnClickListener(this)
}
fun bind(
item: Pet,
trained: Int,
eggCount: Int,
potionCount: Int,
canRaiseToMount: Boolean,
ownsSaddles: Boolean,
hasUnlockedEgg: Boolean,
hasUnlockedPotion: Boolean,
hasMount: Boolean,
currentPet: String?
) {
this.animal = item
isOwned = trained > 0
binding.imageView.alpha = 1.0f
this.canRaiseToMount = canRaiseToMount
this.eggCount = eggCount
this.potionCount = potionCount
this.ownsSaddles = ownsSaddles
this.hasUnlockedEgg = hasUnlockedEgg
this.hasUnlockedPotion = hasUnlockedPotion
this.hasMount = hasMount
this.currentPet = currentPet
binding.imageView.visibility = View.VISIBLE
binding.itemWrapper.visibility = View.GONE
binding.checkmarkView.visibility = View.GONE
binding.titleTextView.visibility = View.GONE
binding.root.contentDescription = item.text
val imageName = "stable_Pet-${item.animal}-${item.color}"
if (trained > 0) {
if (this.canRaiseToMount) {
binding.trainedProgressBar.visibility = View.VISIBLE
binding.trainedProgressBar.progress = trained
} else {
binding.trainedProgressBar.visibility = View.GONE
}
} else {
binding.trainedProgressBar.visibility = View.GONE
binding.imageView.alpha = 0.2f
}
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
binding.trainedProgressBar.progressBackgroundTintMode = PorterDuff.Mode.SRC_OVER
}
binding.imageView.background = null
binding.activeIndicator.visibility =
if (currentPet.equals(animal?.key)) View.VISIBLE else View.GONE
binding.imageView.tag = imageName
DataBindingUtils.loadImage(itemView.context, imageName) {
val resources = itemView.context.resources ?: return@loadImage
val drawable =
if (trained == 0) BitmapDrawable(resources, it.toBitmap().extractAlpha()) else it
if (binding.imageView.tag == imageName) {
binding.imageView.bitmap = drawable.toBitmap()
}
}
}
override fun onClick(v: View) {
if (!isOwned) {
showRequirementsDialog()
return
}
val context = itemView.context
val menu = BottomSheetMenu(context)
menu.setTitle(animal?.text)
menu.setImage("stable_Pet-${animal?.animal}-${animal?.color}")
val hasCurrentPet = currentPet.equals(animal?.key)
val labelId = if (hasCurrentPet) R.string.unequip else R.string.equip
menu.addMenuItem(BottomSheetMenuItem(itemView.resources.getString(labelId)))
if (canRaiseToMount) {
menu.addMenuItem(BottomSheetMenuItem(itemView.resources.getString(R.string.feed)))
if (ownsSaddles) {
menu.addMenuItem(BottomSheetMenuItem(itemView.resources.getString(R.string.use_saddle)))
}
}
menu.setSelectionRunnable { index ->
val pet = animal ?: return@setSelectionRunnable
when (index) {
0 -> {
animal?.let {
equipEvents.onNext(it.key ?: "")
}
}
1 -> {
feedEvents.onNext(Pair(pet, null))
}
2 -> {
val saddle = Food()
saddle.key = "Saddle"
feedEvents.onNext(Pair(pet, saddle))
}
}
}
menu.show()
}
private fun showRequirementsDialog() {
val context = itemView.context
val dialog = PetSuggestHatchDialog(context)
animal?.let {
ingredientsReceiver?.invoke(it) { ingredients ->
dialog.configure(
it,
ingredients.first,
ingredients.second,
eggCount,
potionCount,
hasUnlockedEgg,
hasUnlockedPotion,
hasMount
)
dialog.show()
}
}
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/PetViewHolder.kt | 3612123677 |
package com.openlattice.rhizome.hazelcast.entryprocessors
import com.hazelcast.core.ReadOnly
import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor
abstract class AbstractReadOnlyRhizomeEntryProcessor<K, V, R> : AbstractRhizomeEntryProcessor<K, V, R>(false), ReadOnly
| src/main/kotlin/com/openlattice/rhizome/hazelcast/entryprocessors/AbstractReadOnlyRhizomeEntryProcessor.kt | 2378530380 |
package org.stepik.android.presentation.course_list
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course_list.model.CourseListQuery
import org.stepik.android.presentation.course_continue.CourseContinueView
interface CourseListQueryView : CourseContinueView {
sealed class State {
object Idle : State()
data class Data(
val courseListQuery: CourseListQuery,
val courseListViewState: CourseListView.State,
/**
* @null is for not fetched from REMOTE with error
*/
val sourceType: DataSourceType? = null
) : State()
}
fun setState(state: State)
fun showNetworkError()
} | app/src/main/java/org/stepik/android/presentation/course_list/CourseListQueryView.kt | 2705089486 |
package wangdaye.com.geometricweather.common.basic.models
import wangdaye.com.geometricweather.common.basic.models.options.provider.WeatherSource
import java.util.*
data class ChineseCity(
val cityId: String,
val province: String,
val city: String,
val district: String,
val latitude: String,
val longitude: String
) {
fun toLocation() = Location(
cityId = cityId,
latitude = latitude.toFloat(),
longitude = longitude.toFloat(),
timeZone = TimeZone.getTimeZone("Asia/Shanghai"),
country = "中国",
province = province,
city = city,
district = if (district == "无") "" else district,
weather = null,
weatherSource = WeatherSource.CAIYUN,
isCurrentPosition = false,
isResidentPosition = false,
isChina = true
)
} | app/src/main/java/wangdaye/com/geometricweather/common/basic/models/ChineseCity.kt | 1506492265 |
package org.koin.dsl
import org.koin.core.instance.FactoryInstanceFactory
import org.koin.core.instance.ScopedInstanceFactory
import org.koin.core.instance.SingleInstanceFactory
import org.koin.core.module.dsl.*
import org.koin.core.qualifier.named
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
class ClassA : IClassA
class ClassA2 : IClassA
class ClassB(val a : IClassA)
interface IClassA
class NewDSLTest {
@Test
fun singleof_options(){
val module = module {
singleOf(::ClassA) {
named("_name_")
createdAtStart()
bind<IClassA>()
}
}
assertEquals(2,module.mappings.size)
val factory = module.mappings.values.iterator().next()
assertTrue {
factory is SingleInstanceFactory<*> && factory.beanDefinition._createdAtStart
}
assertEquals(0,module.scopes.size)
assertEquals(1,module.eagerInstances.size)
}
@Test
fun factory_options(){
val module = module {
factoryOf(::ClassA) {
named("_name_")
bind<IClassA>()
}
}
assertEquals(2,module.mappings.size)
val factory = module.mappings.values.iterator().next()
assertTrue {
factory is FactoryInstanceFactory<*> && !factory.beanDefinition._createdAtStart
}
assertEquals(0,module.scopes.size)
assertEquals(0,module.eagerInstances.size)
}
@Test
fun scoped_options(){
val module = module {
scope(named("_scope_")) {
scopedOf(::ClassA) { bind<IClassA>() }
}
}
assertEquals(2,module.mappings.size)
val factory = module.mappings.values.iterator().next()
assertTrue("factory type") {
factory is ScopedInstanceFactory<*> && !factory.beanDefinition._createdAtStart
}
assertEquals(1,module.scopes.size)
assertEquals(0,module.eagerInstances.size)
}
@Test
fun factory_options_run(){
val module = module {
factoryOf(::ClassA) { bind<IClassA>() }
}
val koin = koinApplication { modules(module) }.koin
assertTrue { koin.get<IClassA>() != koin.get<IClassA>() }
}
@Test
fun singleof_nodsl(){
val module = module {
singleOf(::ClassA) bind IClassA::class
singleOf(::ClassB)
}
val koin = koinApplication { modules(module) }.koin
assertNotNull(koin.getOrNull<ClassB>())
}
@Test
fun singleof_deps(){
val module = module {
singleOf(::ClassA) { bind<IClassA>() }
singleOf(::ClassB)
}
val koin = koinApplication { modules(module) }.koin
assertNotNull(koin.getOrNull<ClassB>())
}
@Test
fun singleof_get_options(){
val module = module {
singleOf(::ClassA) {
named("_name_")
bind<IClassA>()
}
single { ClassB(get(named("_name_"))) } withOptions {
createdAtStart()
}
}
assertEquals(1,module.eagerInstances.size)
assertEquals(3,module.mappings.size)
}
} | core/koin-core/src/commonTest/kotlin/org/koin/dsl/NewDSLTest.kt | 1529739187 |
package com.vmenon.mpo.login.presentation
import android.util.Patterns
import androidx.databinding.Observable
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.vmenon.mpo.login.presentation.BR
import com.vmenon.mpo.login.presentation.R
import com.vmenon.mpo.login.presentation.model.RegistrationObservable
import com.vmenon.mpo.login.presentation.model.RegistrationValid
class RegistrationFormValidator : Observable.OnPropertyChangedCallback() {
private val registrationValid = MutableLiveData(INITIAL_VALID_STATE)
fun registrationValid(): LiveData<RegistrationValid> = registrationValid
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
if (sender !is RegistrationObservable) return
when (propertyId) {
BR.firstName -> {
val firstNameError =
if (sender.getFirstName().isNotBlank()) null else R.string.first_name_invalid
registrationValid.postValue(
registrationValid.value?.copy(
firstNameValid = firstNameError == null,
firstNameError = firstNameError
) ?: INITIAL_VALID_STATE
)
}
BR.lastName -> {
val lastNameError =
if (sender.getLastName().isNotBlank()) null else R.string.last_name_invalid
registrationValid.postValue(
registrationValid.value?.copy(
lastNameValid = lastNameError == null,
lastNameError = lastNameError
) ?: INITIAL_VALID_STATE
)
}
BR.email -> {
val emailError =
if (sender.getEmail().isNotBlank()
&& Patterns.EMAIL_ADDRESS.matcher(
sender.getEmail()
).matches()
) null else R.string.email_invalid
registrationValid.postValue(
registrationValid.value?.copy(
emailValid = emailError == null,
emailError = emailError
) ?: INITIAL_VALID_STATE
)
}
BR.password -> {
val passwordError =
if (sender.getPassword().isNotBlank()) null else R.string.password_invalid
registrationValid.postValue(
registrationValid.value?.copy(
passwordValid = passwordError == null,
passwordError = passwordError
) ?: INITIAL_VALID_STATE
)
}
BR.confirmPassword -> {
val confirmPasswordError =
if (sender.getConfirmPassword().isNotBlank()) {
if (sender.getConfirmPassword() ==
sender.getPassword()
) {
null
} else {
R.string.confirm_password_does_not_match
}
} else {
R.string.confirm_password_invalid
}
registrationValid.postValue(
registrationValid.value?.copy(
confirmPasswordValid = confirmPasswordError == null,
confirmPasswordError = confirmPasswordError
) ?: INITIAL_VALID_STATE
)
}
}
}
companion object {
private val INITIAL_VALID_STATE = RegistrationValid()
}
} | login_presentation/src/main/java/com/vmenon/mpo/login/presentation/RegistrationFormValidator.kt | 111551592 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.filament.textured
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.google.android.filament.Engine
import com.google.android.filament.Texture
import com.google.android.filament.android.TextureHelper
import java.lang.IllegalArgumentException
import java.nio.ByteBuffer
const val SKIP_BITMAP_COPY = true
enum class TextureType {
COLOR,
NORMAL,
DATA
}
fun loadTexture(engine: Engine, resources: Resources, resourceId: Int, type: TextureType): Texture {
val options = BitmapFactory.Options()
// Color is the only type of texture we want to pre-multiply with the alpha channel
// Pre-multiplication is the default behavior, so we need to turn it off here
options.inPremultiplied = type == TextureType.COLOR
val bitmap = BitmapFactory.decodeResource(resources, resourceId, options)
val texture = Texture.Builder()
.width(bitmap.width)
.height(bitmap.height)
.sampler(Texture.Sampler.SAMPLER_2D)
.format(internalFormat(type))
// This tells Filament to figure out the number of mip levels
.levels(0xff)
.build(engine)
// TextureHelper offers a method that skips the copy of the bitmap into a ByteBuffer
if (SKIP_BITMAP_COPY) {
TextureHelper.setBitmap(engine, texture, 0, bitmap)
} else {
val buffer = ByteBuffer.allocateDirect(bitmap.byteCount)
bitmap.copyPixelsToBuffer(buffer)
// Do not forget to rewind the buffer!
buffer.flip()
val descriptor = Texture.PixelBufferDescriptor(
buffer,
format(bitmap),
type(bitmap))
texture.setImage(engine, 0, descriptor)
}
texture.generateMipmaps(engine)
return texture
}
private fun internalFormat(type: TextureType) = when (type) {
TextureType.COLOR -> Texture.InternalFormat.SRGB8_A8
TextureType.NORMAL -> Texture.InternalFormat.RGBA8
TextureType.DATA -> Texture.InternalFormat.RGBA8
}
// Not required when SKIP_BITMAP_COPY is true
// Use String representation for compatibility across API levels
private fun format(bitmap: Bitmap) = when (bitmap.config.name) {
"ALPHA_8" -> Texture.Format.ALPHA
"RGB_565" -> Texture.Format.RGB
"ARGB_8888" -> Texture.Format.RGBA
"RGBA_F16" -> Texture.Format.RGBA
else -> throw IllegalArgumentException("Unknown bitmap configuration")
}
// Not required when SKIP_BITMAP_COPY is true
private fun type(bitmap: Bitmap) = when (bitmap.config.name) {
"ALPHA_8" -> Texture.Type.USHORT
"RGB_565" -> Texture.Type.USHORT_565
"ARGB_8888" -> Texture.Type.UBYTE
"RGBA_F16" -> Texture.Type.HALF
else -> throw IllegalArgumentException("Unsupported bitmap configuration")
}
| android/filament-utils-android/src/main/java/com/google/android/filament/utils/TextureLoader.kt | 3133636750 |
package com.apollographql.apollo3.compiler
import com.apollographql.apollo3.graphql.ast.GQLDocument
import com.apollographql.apollo3.graphql.ast.GQLEnumTypeDefinition
import com.apollographql.apollo3.graphql.ast.GQLInputObjectTypeDefinition
import com.apollographql.apollo3.graphql.ast.GQLScalarTypeDefinition
import com.apollographql.apollo3.graphql.ast.Schema
import com.apollographql.apollo3.graphql.ast.usedTypeNames
internal class TypesToGenerate(
/**
* The enums to generate
*/
val generateScalarMapping: Boolean,
/**
* The enums to generate
*/
val enumsToGenerate: Set<String>,
/**
* The enums to generate
*/
val inputObjectsToGenerate: Set<String>,
)
internal fun computeTypesToGenerate(
documents: List<GQLDocument>,
schema: Schema,
metadataEnums: Set<String>,
metadataInputObjects: Set<String>,
metadataCustomScalars: Boolean,
alwaysGenerateTypesMatching: Set<String>
): TypesToGenerate {
val regexes = alwaysGenerateTypesMatching.map { Regex(it) }
val extraTypes = schema.typeDefinitions.values.filter { typeDefinition ->
(typeDefinition is GQLInputObjectTypeDefinition || typeDefinition is GQLEnumTypeDefinition)
&& regexes.indexOfFirst { it.matches(typeDefinition.name) } >= 0
}.map { it.name }
.toSet()
val incomingTypes = metadataEnums.plus(metadataInputObjects)
val usedTypes = ((documents.flatMap { it.definitions }.usedTypeNames(schema)) + extraTypes).map {
schema.typeDefinitions[it]!!
}.filter {
when (it) {
is GQLEnumTypeDefinition,
is GQLInputObjectTypeDefinition,
is GQLScalarTypeDefinition
-> true
else -> false
}
}
val enumsToGenerate = usedTypes.filterIsInstance<GQLEnumTypeDefinition>()
.map { it.name }
.filter { !incomingTypes.contains(it) }
val inputObjectsToGenerate = usedTypes.filterIsInstance<GQLInputObjectTypeDefinition>()
.map { it.name }
.filter { !incomingTypes.contains(it) }
return TypesToGenerate(
enumsToGenerate = enumsToGenerate.toSet(),
inputObjectsToGenerate = inputObjectsToGenerate.toSet(),
generateScalarMapping = !metadataCustomScalars,
)
}
| apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/TypesToGenerate.kt | 671086277 |
package expo.modules
import android.content.Context
import android.content.Intent
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.google.common.truth.Truth.assertThat
import expo.modules.core.interfaces.Package
import expo.modules.core.interfaces.ReactActivityHandler
import expo.modules.core.interfaces.ReactActivityLifecycleListener
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.RelaxedMockK
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import org.junit.After
import org.junit.Before
import org.junit.Test
internal class ReactActivityDelegateWrapperTest {
lateinit var mockPackage0: MockPackage
lateinit var mockPackage1: MockPackage
@RelaxedMockK
lateinit var activity: ReactActivity
@RelaxedMockK
lateinit var delegate: ReactActivityDelegate
@Before
fun setUp() {
mockPackage0 = MockPackage()
mockPackage1 = MockPackage()
MockKAnnotations.init(this)
mockkObject(ExpoModulesPackage.Companion)
every { ExpoModulesPackage.Companion.packageList } returns listOf(mockPackage0, mockPackage1)
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun `onBackPressed should call each handler's callback just once`() {
val delegateWrapper = ReactActivityDelegateWrapper(activity, delegate)
every { mockPackage0.reactActivityLifecycleListener.onBackPressed() } returns true
delegateWrapper.onBackPressed()
verify(exactly = 1) { mockPackage0.reactActivityLifecycleListener.onBackPressed() }
verify(exactly = 1) { mockPackage1.reactActivityLifecycleListener.onBackPressed() }
verify(exactly = 1) { delegate.onBackPressed() }
}
@Test
fun `onBackPressed should return true if someone returns true`() {
val delegateWrapper = ReactActivityDelegateWrapper(activity, delegate)
every { mockPackage0.reactActivityLifecycleListener.onBackPressed() } returns false
every { mockPackage1.reactActivityLifecycleListener.onBackPressed() } returns true
every { delegate.onBackPressed() } returns false
val result = delegateWrapper.onBackPressed()
assertThat(result).isTrue()
}
@Test
fun `onNewIntent should call each handler's callback just once`() {
val intent = mockk<Intent>()
val delegateWrapper = ReactActivityDelegateWrapper(activity, delegate)
every { mockPackage0.reactActivityLifecycleListener.onNewIntent(intent) } returns false
every { mockPackage1.reactActivityLifecycleListener.onNewIntent(intent) } returns true
every { delegate.onNewIntent(intent) } returns false
delegateWrapper.onNewIntent(intent)
verify(exactly = 1) { mockPackage0.reactActivityLifecycleListener.onNewIntent(any()) }
verify(exactly = 1) { mockPackage1.reactActivityLifecycleListener.onNewIntent(any()) }
verify(exactly = 1) { delegate.onNewIntent(any()) }
}
@Test
fun `onNewIntent should return true if someone returns true`() {
val intent = mockk<Intent>()
val delegateWrapper = ReactActivityDelegateWrapper(activity, delegate)
every { mockPackage0.reactActivityLifecycleListener.onNewIntent(intent) } returns false
every { mockPackage1.reactActivityLifecycleListener.onNewIntent(intent) } returns true
every { delegate.onNewIntent(intent) } returns false
val result = delegateWrapper.onNewIntent(intent)
assertThat(result).isTrue()
}
}
internal class MockPackage : Package {
val reactActivityLifecycleListener = mockk<ReactActivityLifecycleListener>(relaxed = true)
val reactActivityHandler = mockk<ReactActivityHandler>(relaxed = true)
override fun createReactActivityLifecycleListeners(activityContext: Context?): List<ReactActivityLifecycleListener> {
return listOf(reactActivityLifecycleListener)
}
override fun createReactActivityHandlers(activityContext: Context?): List<ReactActivityHandler> {
return listOf(reactActivityHandler)
}
}
| packages/expo/android/src/test/java/expo/modules/ReactActivityDelegateWrapperTest.kt | 3747604935 |
package info.nightscout.androidaps.activities
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.annotation.RawRes
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction
import info.nightscout.androidaps.dialogs.ErrorDialog
import info.nightscout.shared.sharedPreferences.SP
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import javax.inject.Inject
class ErrorHelperActivity : DialogAppCompatActivity() {
@Inject lateinit var sp: SP
@Inject lateinit var repository: AppRepository
private val disposable = CompositeDisposable()
@Override
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val errorDialog = ErrorDialog()
errorDialog.helperActivity = this
errorDialog.status = intent.getStringExtra(STATUS) ?: ""
errorDialog.sound = intent.getIntExtra(SOUND_ID, R.raw.error)
errorDialog.title = intent.getStringExtra(TITLE)?: ""
errorDialog.show(supportFragmentManager, "Error")
if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true))
disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(intent.getStringExtra(STATUS) ?: "")).subscribe()
}
companion object {
const val SOUND_ID = "soundId"
const val STATUS = "status"
const val TITLE = "title"
fun runAlarm(ctx: Context, status: String, title: String, @RawRes soundId: Int = 0) {
val i = Intent(ctx, ErrorHelperActivity::class.java)
i.putExtra(SOUND_ID, soundId)
i.putExtra(STATUS, status)
i.putExtra(TITLE, title)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
ctx.startActivity(i)
}
}
}
| core/src/main/java/info/nightscout/androidaps/activities/ErrorHelperActivity.kt | 1359338540 |
/*
* Copyright © 2020 Paul Ambrose ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction")
package io.prometheus.common
import com.github.pambrose.common.util.EMPTY_BYTE_ARRAY
import io.ktor.http.*
internal class ScrapeResults(
val agentId: String,
val scrapeId: Long,
var validResponse: Boolean = false,
var statusCode: Int = HttpStatusCode.NotFound.value,
var contentType: String = "",
var zipped: Boolean = false,
var contentAsText: String = "",
var contentAsZipped: ByteArray = EMPTY_BYTE_ARRAY,
var failureReason: String = "",
var url: String = ""
) {
fun setDebugInfo(url: String, failureReason: String = "") {
this.url = url
this.failureReason = failureReason
}
} | src/main/kotlin/io/prometheus/common/ScrapeResults.kt | 3460737263 |
package net.paslavsky.msm
import java.io.Closeable
/**
* Try block for the [[java.io.Closeable]] like in Java 8
* @author Andrey Paslavsky
* @version 1.0
*/
public inline fun <T> `try`(closeable: Closeable, body: () -> T): T =
try {
body()
} finally {
closeable.close()
} | msm-server/src/main/kotlin/net/paslavsky/msm/CloseableTry.kt | 2141348544 |
package io.github.zebrateam
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.test.context.junit.jupiter.SpringExtension
@ExtendWith(SpringExtension::class)
@IntegrationTest
class BackendApplicationTests {
@Test
fun contextLoads() {
}
}
| src/test/kotlin/io/github/zebrateam/BackendApplicationTests.kt | 1305965864 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.mainnavigation
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.app.Fragment
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import com.evernote.android.job.util.JobUtil
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.base.BaseActivity
import io.github.feelfreelinux.wykopmobilny.base.BaseNavigationFragment
import io.github.feelfreelinux.wykopmobilny.ui.dialogs.AppExitConfirmationDialog
import io.github.feelfreelinux.wykopmobilny.ui.modules.NavigatorApi
import io.github.feelfreelinux.wykopmobilny.ui.modules.settings.SettingsActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen.LoginScreenActivity
import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.hot.HotFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.notifications.notificationsservice.WykopNotificationsJob
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.hashtags.HashTagsNotificationsListFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.notification.NotificationsListFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversationslist.ConversationsListFragment
import io.github.feelfreelinux.wykopmobilny.utils.SettingsPreferencesApi
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import kotlinx.android.synthetic.main.activity_navigation.*
import kotlinx.android.synthetic.main.drawer_header_view_layout.view.*
import kotlinx.android.synthetic.main.navigation_header.view.*
import kotlinx.android.synthetic.main.toolbar.*
import javax.inject.Inject
fun Context.launchNavigationActivity(targetFragment : String? = null) {
val intent = Intent(this, NavigationActivity::class.java)
targetFragment?.let {
intent.putExtra(NavigationActivity.TARGET_FRAGMENT_KEY, targetFragment)
}
startActivity(intent)
}
interface MainNavigationInterface {
val activityToolbar : Toolbar
fun openFragment(fragment: Fragment)
fun showErrorDialog(e: Throwable)
}
class NavigationActivity : BaseActivity(), MainNavigationView, NavigationView.OnNavigationItemSelectedListener, MainNavigationInterface {
override val activityToolbar: Toolbar get() = toolbar
companion object {
val LOGIN_REQUEST_CODE = 142
val TARGET_FRAGMENT_KEY = "TARGET_FRAGMENT"
val TARGET_NOTIFICATIONS = "TARGET_NOTIFICATIONS"
fun getIntent(context: Context, targetFragment: String? = null): Intent {
val intent = Intent(context, NavigationActivity::class.java)
targetFragment?.let {
intent.putExtra(NavigationActivity.TARGET_FRAGMENT_KEY, targetFragment)
}
return intent
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_mikroblog -> openFragment(HotFragment.newInstance())
R.id.login -> { navigator.openLoginScreen(this, LOGIN_REQUEST_CODE) }
R.id.messages -> { openFragment(ConversationsListFragment.newInstance()) }
R.id.nav_settings -> { navigator.openSettingsActivity(this) }
else -> presenter.navigationItemClicked(item.itemId)
}
item.isChecked = true
drawer_layout.closeDrawers()
return true
}
@Inject lateinit var presenter : MainNavigationPresenter
@Inject lateinit var settingsApi : SettingsPreferencesApi
@Inject lateinit var navigator : NavigatorApi
private val navHeader by lazy { navigationView.getHeaderView(0) }
private val actionBarToggle by lazy {
ActionBarDrawerToggle(this,
drawer_layout,
toolbar,
R.string.nav_drawer_open,
R.string.nav_drawer_closed)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_navigation)
setSupportActionBar(toolbar)
WykopApp.uiInjector.inject(this)
JobUtil.hasBootPermission(this)
// Schedules notification service
WykopNotificationsJob.shedule(settingsApi)
toolbar.tag = toolbar.overflowIcon // We want to save original overflow icon drawable into memory.
setupNavigation()
if (savedInstanceState == null) {
if (intent.hasExtra(TARGET_FRAGMENT_KEY)) {
when (intent.getStringExtra(TARGET_FRAGMENT_KEY)) {
TARGET_NOTIFICATIONS -> openFragment(NotificationsListFragment.newInstance())
}
} else openMainFragment()
}
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
actionBarToggle.syncState()
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
actionBarToggle.onConfigurationChanged(newConfig)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (actionBarToggle.onOptionsItemSelected(item))
return true
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
super.onDestroy()
presenter.unsubscribe()
}
private fun setupNavigation() {
drawer_layout.addDrawerListener(actionBarToggle)
navigationView.setNavigationItemSelectedListener(this)
presenter.subscribe(this)
}
override fun showUsersMenu(value : Boolean) {
navigationView.menu.apply {
findItem(R.id.nav_user).isVisible = value
findItem(R.id.nav_mojwykop).isVisible = value
findItem(R.id.login).isVisible = !value
findItem(R.id.logout).isVisible = value
}
navHeader.view_container.apply {
checkIsUserLoggedIn()
nav_notifications_tag.setOnClickListener {
openFragment(HashTagsNotificationsListFragment.newInstance())
deselectItems()
}
nav_notifications.setOnClickListener {
openFragment(NotificationsListFragment.newInstance())
deselectItems()
}
}
}
fun openMainFragment() {
// @TODO Handle settings here
openFragment(HotFragment())
}
override fun openFragment(fragment: Fragment) {
fab.isVisible = false
fab.setOnClickListener(null)
if (fragment is BaseNavigationFragment) fragment.fab = fab
supportFragmentManager.beginTransaction().replace(R.id.contentView,
fragment).commit()
closeDrawer()
}
fun closeDrawer() =
drawer_layout.closeDrawers()
fun deselectItems() {
val menu = navigationView.menu
for (i in 0 until menu.size()) {
menu.getItem(i).isChecked = false
}
}
override fun onBackPressed() {
if(drawer_layout.isDrawerOpen(GravityCompat.START)) closeDrawer()
else AppExitConfirmationDialog(this, { finish() }).show()
}
override fun restartActivity() {
navigator.openMainActivity(this)
finish()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) {
LOGIN_REQUEST_CODE -> {
if (resultCode == LoginScreenActivity.USER_LOGGED_IN) {
restartActivity()
}
}
else -> {
if (resultCode == SettingsActivity.THEME_CHANGED_RESULT) {
restartActivity()
}
}
}
}
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mainnavigation/MainNavigationActivity.kt | 1135876438 |
package com.auth0.android.authentication
import com.auth0.android.Auth0Exception
import com.auth0.android.NetworkErrorException
import com.auth0.android.request.internal.GsonProvider
import com.google.gson.reflect.TypeToken
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.io.FileReader
import java.io.IOException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.*
@RunWith(RobolectricTestRunner::class)
public class AuthenticationExceptionTest {
@get:Rule
public val exception: ExpectedException = ExpectedException.none()
private lateinit var values: MutableMap<String, Any>
@Before
public fun setUp() {
values = HashMap()
}
@Test
public fun shouldGetUnknownCode() {
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getCode(),
CoreMatchers.`is`(CoreMatchers.equalTo(Auth0Exception.UNKNOWN_ERROR))
)
}
@Test
public fun shouldGetPreferErrorOverCode() {
values[ERROR_KEY] = "a_valid_error"
values[CODE_KEY] = "a_valid_code"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getCode(),
CoreMatchers.`is`(CoreMatchers.equalTo("a_valid_error"))
)
}
@Test
public fun shouldGetValidCode() {
values[CODE_KEY] = "a_valid_code"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getCode(),
CoreMatchers.`is`(CoreMatchers.equalTo("a_valid_code"))
)
}
@Test
public fun shouldGetValidError() {
values[ERROR_KEY] = "a_valid_error"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getCode(),
CoreMatchers.`is`(CoreMatchers.equalTo("a_valid_error"))
)
}
@Test
public fun shouldGetPreferDescriptionOverErrorDescription() {
values[ERROR_DESCRIPTION_KEY] = "a_valid_error_description"
values[DESCRIPTION_KEY] = "a_valid_description"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getDescription(),
CoreMatchers.`is`(CoreMatchers.equalTo("a_valid_description"))
)
}
@Test
public fun shouldGetValidDescription() {
values[DESCRIPTION_KEY] = "a_valid_error_description"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getDescription(),
CoreMatchers.`is`(CoreMatchers.equalTo("a_valid_error_description"))
)
}
@Test
public fun shouldGetValidErrorDescription() {
values[ERROR_DESCRIPTION_KEY] = "a_valid_error_description"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getDescription(),
CoreMatchers.`is`(CoreMatchers.equalTo("a_valid_error_description"))
)
}
@Test
public fun shouldGetPlainTextAsDescription() {
val ex = AuthenticationException("Payload", 404)
MatcherAssert.assertThat(
ex.getDescription(),
CoreMatchers.`is`(CoreMatchers.equalTo("Payload"))
)
}
@Test
public fun shouldGetMessageWithUnknownCodeIfNullDescription() {
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getDescription(),
CoreMatchers.`is`(
CoreMatchers.equalTo(
String.format(
"Received error with code %s",
Auth0Exception.UNKNOWN_ERROR
)
)
)
)
}
@Test
public fun shouldNotGetEmptyDescription() {
values[CODE_KEY] = "a_valid_code"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(
ex.getDescription(),
CoreMatchers.`is`(CoreMatchers.equalTo("Failed with unknown error"))
)
}
@Test
public fun shouldGetValuesFromTheMap() {
values["key"] = "value"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.getValue("key"), CoreMatchers.`is`(CoreMatchers.notNullValue()))
MatcherAssert.assertThat(
ex.getValue("key"), CoreMatchers.`is`(
CoreMatchers.instanceOf(
String::class.java
)
)
)
MatcherAssert.assertThat(
ex.getValue("key") as String?,
CoreMatchers.`is`(CoreMatchers.equalTo("value"))
)
}
@Test
public fun shouldReturnNullIfMapDoesNotExist() {
val ex1 = AuthenticationException("code", "description")
val ex2 = AuthenticationException("message")
val ex3 = AuthenticationException("code", Auth0Exception("message"))
val ex4 = AuthenticationException("credentials", 1)
MatcherAssert.assertThat(ex1.getValue("key"), CoreMatchers.`is`(CoreMatchers.nullValue()))
MatcherAssert.assertThat(ex2.getValue("key"), CoreMatchers.`is`(CoreMatchers.nullValue()))
MatcherAssert.assertThat(ex3.getValue("key"), CoreMatchers.`is`(CoreMatchers.nullValue()))
MatcherAssert.assertThat(ex4.getValue("key"), CoreMatchers.`is`(CoreMatchers.nullValue()))
}
@Test
public fun shouldNotHaveNetworkError() {
val ex = AuthenticationException("Something else happened")
MatcherAssert.assertThat(ex.isNetworkError, CoreMatchers.`is`(false))
}
@Test
public fun shouldHaveNetworkError() {
val ex = AuthenticationException(
"Request has definitely failed", NetworkErrorException(
IOException()
)
)
MatcherAssert.assertThat(ex.isNetworkError, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveNetworkErrorForSocketTimeout() {
val ex = AuthenticationException(
"Request has definitely failed", Auth0Exception("",
SocketTimeoutException()
)
)
MatcherAssert.assertThat(ex.isNetworkError, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveNetworkErrorForUnknownHost() {
val ex = AuthenticationException(
"Request has definitely failed", NetworkErrorException(
UnknownHostException()
)
)
MatcherAssert.assertThat(ex.isNetworkError, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveRequestVerificationError() {
values[CODE_KEY] = "requires_verification"
values[ERROR_DESCRIPTION_KEY] = "Suspicious request requires verification"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isVerificationRequired, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveExpiredMultifactorTokenOnOIDCMode() {
values[ERROR_KEY] = "expired_token"
values[ERROR_DESCRIPTION_KEY] = "mfa_token is expired"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isMultifactorTokenInvalid, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveMalformedMultifactorTokenOnOIDCMode() {
values[ERROR_KEY] = "invalid_grant"
values[ERROR_DESCRIPTION_KEY] = "Malformed mfa_token"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isMultifactorTokenInvalid, CoreMatchers.`is`(true))
}
@Test
public fun shouldRequireMultifactorOnOIDCMode() {
values[ERROR_KEY] = "mfa_required"
values["mfa_token"] = "some-random-token"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isMultifactorRequired, CoreMatchers.`is`(true))
MatcherAssert.assertThat(
ex.getValue("mfa_token") as String?,
CoreMatchers.`is`("some-random-token")
)
}
@Test
public fun shouldRequireMultifactor() {
values[CODE_KEY] = "a0.mfa_required"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isMultifactorRequired, CoreMatchers.`is`(true))
}
@Test
public fun shouldRequireMultifactorEnrollOnOIDCMode() {
values[ERROR_KEY] = "unsupported_challenge_type"
values[ERROR_DESCRIPTION_KEY] = "User is not enrolled with guardian"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isMultifactorEnrollRequired, CoreMatchers.`is`(true))
}
@Test
public fun shouldRequireMultifactorEnroll() {
values[CODE_KEY] = "a0.mfa_registration_required"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isMultifactorEnrollRequired, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveInvalidMultifactorCodeOnOIDCMode() {
values[ERROR_KEY] = "invalid_grant"
values[ERROR_DESCRIPTION_KEY] = "Invalid otp_code."
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isMultifactorCodeInvalid, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveInvalidMultifactorCode() {
values[CODE_KEY] = "a0.mfa_invalid_code"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isMultifactorCodeInvalid, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveNotStrongPassword() {
values[CODE_KEY] = "invalid_password"
values[NAME_KEY] = "PasswordStrengthError"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isPasswordNotStrongEnough, CoreMatchers.`is`(true))
}
@Test
@Throws(Exception::class)
public fun shouldHaveNotStrongPasswordWithDetailedDescription() {
val fr = FileReader(PASSWORD_STRENGTH_ERROR_RESPONSE)
val mapType = object : TypeToken<Map<String, Any>>() {}
val mapPayload: Map<String, Any> = GsonProvider.gson.getAdapter(mapType).fromJson(fr)
val ex = AuthenticationException(mapPayload)
MatcherAssert.assertThat(ex.isPasswordNotStrongEnough, CoreMatchers.`is`(true))
val expectedDescription =
"At least 10 characters in length; Contain at least 3 of the following 4 types of characters: lower case letters (a-z), upper case letters (A-Z), numbers (i.e. 0-9), special characters (e.g. !@#$%^&*); Should contain: lower case letters (a-z), upper case letters (A-Z), numbers (i.e. 0-9), special characters (e.g. !@#$%^&*); No more than 2 identical characters in a row (e.g., \"aaa\" not allowed)"
MatcherAssert.assertThat(ex.getDescription(), CoreMatchers.`is`(expectedDescription))
}
@Test
public fun shouldHaveAlreadyUsedPassword() {
values[CODE_KEY] = "invalid_password"
values[NAME_KEY] = "PasswordHistoryError"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isPasswordAlreadyUsed, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveRuleError() {
values[CODE_KEY] = "unauthorized"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isRuleError, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveInvalidCredentials() {
values[CODE_KEY] = "invalid_user_password"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isInvalidCredentials, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveOIDCInvalidCredentials() {
values[CODE_KEY] = "invalid_grant"
values[ERROR_DESCRIPTION_KEY] = "Wrong email or password."
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isInvalidCredentials, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveInvalidCredentialsOnPhonePasswordless() {
values[ERROR_KEY] = "invalid_grant"
values[ERROR_DESCRIPTION_KEY] = "Wrong phone number or verification code."
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isInvalidCredentials, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveInvalidCredentialsOnEmailPasswordless() {
values[ERROR_KEY] = "invalid_grant"
values[ERROR_DESCRIPTION_KEY] = "Wrong email or verification code."
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isInvalidCredentials, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveAccessDenied() {
values[CODE_KEY] = "access_denied"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isAccessDenied, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveInvalidAuthorizeUrl() {
values[CODE_KEY] = "a0.invalid_authorize_url"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isInvalidAuthorizeURL, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveInvalidConfiguration() {
values[CODE_KEY] = "a0.invalid_configuration"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isInvalidConfiguration, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveAuthenticationCanceled() {
values[CODE_KEY] = "a0.authentication_canceled"
val ex = AuthenticationException(
values
)
@Suppress("DEPRECATION")
MatcherAssert.assertThat(ex.isAuthenticationCanceled, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveCanceled() {
values[CODE_KEY] = "a0.authentication_canceled"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isCanceled, CoreMatchers.`is`(true))
}
@Test
public fun shouldHavePasswordLeaked() {
values[CODE_KEY] = "password_leaked"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isPasswordLeaked, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveLoginRequired() {
values[CODE_KEY] = "login_required"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isLoginRequired, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveMissingBrowserApp() {
values[CODE_KEY] = "a0.browser_not_available"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isBrowserAppNotAvailable, CoreMatchers.`is`(true))
}
@Test
public fun shouldHavePKCENotAvailable() {
values[CODE_KEY] = "a0.pkce_not_available"
val ex = AuthenticationException(
values
)
MatcherAssert.assertThat(ex.isPKCENotAvailable, CoreMatchers.`is`(true))
}
@Test
public fun shouldHaveRefreshTokenDeleted() {
values[ERROR_KEY] = "invalid_grant"
values[ERROR_DESCRIPTION_KEY] =
"The refresh_token was generated for a user who doesn't exist anymore."
val ex = AuthenticationException(values, 403)
MatcherAssert.assertThat(ex.isRefreshTokenDeleted, CoreMatchers.`is`(true))
}
private companion object {
private const val PASSWORD_STRENGTH_ERROR_RESPONSE =
"src/test/resources/password_strength_error.json"
private const val CODE_KEY = "code"
private const val NAME_KEY = "name"
private const val ERROR_KEY = "error"
private const val ERROR_DESCRIPTION_KEY = "error_description"
private const val DESCRIPTION_KEY = "description"
}
} | auth0/src/test/java/com/auth0/android/authentication/AuthenticationExceptionTest.kt | 3556206391 |
package com.sjn.stamp.ui.fragment.media
import android.content.Context
import android.os.Bundle
import android.support.v4.media.MediaBrowserCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.sjn.stamp.R
import com.sjn.stamp.ui.MediaBrowsable
import com.sjn.stamp.ui.observer.MediaBrowserObserver
import com.sjn.stamp.utils.LogHelper
import com.sjn.stamp.utils.MediaIDHelper
abstract class MediaBrowserListFragment : ListFragment(), MediaBrowserObserver.Listener {
var mediaBrowsable: MediaBrowsable? = null
var mediaId: String?
get() {
return arguments?.getString(ARG_MEDIA_ID)
}
set(mediaId) {
arguments = Bundle(1).apply { putString(MediaBrowserListFragment.ARG_MEDIA_ID, mediaId) }
}
private val subscriptionCallback: MediaBrowserCompat.SubscriptionCallback = object : MediaBrowserCompat.SubscriptionCallback() {
override fun onChildrenLoaded(parentId: String,
children: List<MediaBrowserCompat.MediaItem>) {
LogHelper.d(TAG, "onChildrenLoaded START")
LogHelper.d(TAG, "onChildrenLoaded parentId: $parentId")
LogHelper.d(TAG, "onChildrenLoaded children: " + children.size)
onMediaBrowserChildrenLoaded(parentId, children)
LogHelper.d(TAG, "onChildrenLoaded END")
}
override fun onError(id: String) {
LogHelper.d(TAG, "onError START")
onMediaBrowserError(id)
LogHelper.d(TAG, "onError END")
}
}
internal abstract fun onMediaBrowserChildrenLoaded(parentId: String, children: List<MediaBrowserCompat.MediaItem>)
internal abstract fun onMediaBrowserError(parentId: String)
override fun onAttach(context: Context?) {
LogHelper.d(TAG, "onAttach START")
super.onAttach(context)
if (context is MediaBrowsable) {
mediaBrowsable = context
}
LogHelper.d(TAG, "fragment.onAttach, mediaId=", mediaId)
if (mediaBrowsable?.mediaBrowser?.isConnected == true) {
onMediaBrowserConnected()
}
LogHelper.d(TAG, "onAttach END")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
LogHelper.d(TAG, "onCreateView START")
val view = super.onCreateView(inflater, container, savedInstanceState)
LogHelper.d(TAG, "onCreateView END")
return view
}
override fun onStart() {
LogHelper.d(TAG, "onStart START")
super.onStart()
updateTitle()
MediaBrowserObserver.addListener(this)
LogHelper.d(TAG, "onStart END")
}
override fun onResume() {
LogHelper.d(TAG, "onResume START")
super.onResume()
LogHelper.d(TAG, "onResume END")
}
override fun onPause() {
LogHelper.d(TAG, "onPause START")
super.onPause()
LogHelper.d(TAG, "onPause END")
}
override fun onStop() {
LogHelper.d(TAG, "onStop START")
super.onStop()
MediaBrowserObserver.removeListener(this)
LogHelper.d(TAG, "onStop END")
}
override fun onDetach() {
LogHelper.d(TAG, "onDetach START")
super.onDetach()
if (mediaBrowsable?.mediaBrowser?.isConnected == true) {
mediaId?.let { mediaBrowsable?.mediaBrowser?.unsubscribe(it) }
}
mediaBrowsable = null
LogHelper.d(TAG, "onDetach END")
}
// Called when the MediaBrowser is connected. This method is either called by the
// fragment.onStart() or explicitly by the activity in the case where the connection
// completes after the onStart()
override fun onMediaBrowserConnected() {
LogHelper.d(TAG, "onMediaControllerConnected START")
if (isDetached || mediaBrowsable == null) {
LogHelper.d(TAG, "onMediaControllerConnected SKIP")
return
}
LogHelper.d(TAG, "onMediaControllerConnected mediaId: " + mediaId)
// Unsubscribing before subscribing is required if this mediaId already has a subscriber
// on this MediaBrowser instance. Subscribing to an already subscribed mediaId will replace
// the callback, but won't trigger the initial callback.onChildrenLoaded.
//
// This is temporary: A bug is being fixed that will make subscribe
// consistently call onChildrenLoaded initially, no matter if it is replacing an existing
// subscriber or not. Currently this only happens if the mediaID has no previous
// subscriber or if the media content changes on the service side, so we need to
// unsubscribe first.
mediaId?.let {
mediaBrowsable?.mediaBrowser?.unsubscribe(it)
mediaBrowsable?.mediaBrowser?.subscribe(it, subscriptionCallback)
}
// Add MediaController callback so we can redraw the list when metadata changes:
// MediaControllerObserver.getInstance().addListener(this);
LogHelper.d(TAG, "onMediaControllerConnected END")
}
protected fun reloadList() {
LogHelper.d(TAG, "reloadList START")
mediaId?.let {
mediaBrowsable?.mediaBrowser?.unsubscribe(it)
mediaBrowsable?.mediaBrowser?.subscribe(it, subscriptionCallback)
}
LogHelper.d(TAG, "reloadList END")
}
private fun updateTitle() {
LogHelper.d(TAG, "updateTitle START")
mediaId?.let {
mediaBrowsable?.mediaBrowser?.getItem(it, object : MediaBrowserCompat.ItemCallback() {
override fun onItemLoaded(item: MediaBrowserCompat.MediaItem?) {
item?.description?.title?.let { listener?.setToolbarTitle(it) }
}
override fun onError(itemId: String) {
val title = MediaIDHelper.extractBrowseCategoryValueFromMediaID(it)
?: context?.getString(R.string.app_name)
listener?.setToolbarTitle(title)
}
})
}
LogHelper.d(TAG, "updateTitle END")
}
companion object {
private val TAG = LogHelper.makeLogTag(MediaBrowserListFragment::class.java)
private const val ARG_MEDIA_ID = "media_id"
}
}
| app/src/main/java/com/sjn/stamp/ui/fragment/media/MediaBrowserListFragment.kt | 4275560327 |
// Code generated by Wire protocol buffer compiler, do not edit.
// Source: squareup.protos.packed_encoding.OuterMessage in packed_encoding.proto
package squareup.protos.packed_encoding
import com.squareup.wire.FieldEncoding
import com.squareup.wire.Message
import com.squareup.wire.ProtoAdapter
import com.squareup.wire.ProtoReader
import com.squareup.wire.ProtoWriter
import com.squareup.wire.ReverseProtoWriter
import com.squareup.wire.Syntax.PROTO_2
import com.squareup.wire.WireField
import kotlin.Any
import kotlin.AssertionError
import kotlin.Boolean
import kotlin.Deprecated
import kotlin.DeprecationLevel
import kotlin.Int
import kotlin.Long
import kotlin.Nothing
import kotlin.String
import kotlin.Unit
import kotlin.jvm.JvmField
import okio.ByteString
public class OuterMessage(
@field:WireField(
tag = 1,
adapter = "com.squareup.wire.ProtoAdapter#INT32",
)
public val outer_number_before: Int? = null,
@field:WireField(
tag = 2,
adapter = "squareup.protos.packed_encoding.EmbeddedMessage#ADAPTER",
)
public val embedded_message: EmbeddedMessage? = null,
unknownFields: ByteString = ByteString.EMPTY,
) : Message<OuterMessage, Nothing>(ADAPTER, unknownFields) {
@Deprecated(
message = "Shouldn't be used in Kotlin",
level = DeprecationLevel.HIDDEN,
)
public override fun newBuilder(): Nothing = throw
AssertionError("Builders are deprecated and only available in a javaInterop build; see https://square.github.io/wire/wire_compiler/#kotlin")
public override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other !is OuterMessage) return false
if (unknownFields != other.unknownFields) return false
if (outer_number_before != other.outer_number_before) return false
if (embedded_message != other.embedded_message) return false
return true
}
public override fun hashCode(): Int {
var result = super.hashCode
if (result == 0) {
result = unknownFields.hashCode()
result = result * 37 + (outer_number_before?.hashCode() ?: 0)
result = result * 37 + (embedded_message?.hashCode() ?: 0)
super.hashCode = result
}
return result
}
public override fun toString(): String {
val result = mutableListOf<String>()
if (outer_number_before != null) result += """outer_number_before=$outer_number_before"""
if (embedded_message != null) result += """embedded_message=$embedded_message"""
return result.joinToString(prefix = "OuterMessage{", separator = ", ", postfix = "}")
}
public fun copy(
outer_number_before: Int? = this.outer_number_before,
embedded_message: EmbeddedMessage? = this.embedded_message,
unknownFields: ByteString = this.unknownFields,
): OuterMessage = OuterMessage(outer_number_before, embedded_message, unknownFields)
public companion object {
@JvmField
public val ADAPTER: ProtoAdapter<OuterMessage> = object : ProtoAdapter<OuterMessage>(
FieldEncoding.LENGTH_DELIMITED,
OuterMessage::class,
"type.googleapis.com/squareup.protos.packed_encoding.OuterMessage",
PROTO_2,
null,
"packed_encoding.proto"
) {
public override fun encodedSize(`value`: OuterMessage): Int {
var size = value.unknownFields.size
size += ProtoAdapter.INT32.encodedSizeWithTag(1, value.outer_number_before)
size += EmbeddedMessage.ADAPTER.encodedSizeWithTag(2, value.embedded_message)
return size
}
public override fun encode(writer: ProtoWriter, `value`: OuterMessage): Unit {
ProtoAdapter.INT32.encodeWithTag(writer, 1, value.outer_number_before)
EmbeddedMessage.ADAPTER.encodeWithTag(writer, 2, value.embedded_message)
writer.writeBytes(value.unknownFields)
}
public override fun encode(writer: ReverseProtoWriter, `value`: OuterMessage): Unit {
writer.writeBytes(value.unknownFields)
EmbeddedMessage.ADAPTER.encodeWithTag(writer, 2, value.embedded_message)
ProtoAdapter.INT32.encodeWithTag(writer, 1, value.outer_number_before)
}
public override fun decode(reader: ProtoReader): OuterMessage {
var outer_number_before: Int? = null
var embedded_message: EmbeddedMessage? = null
val unknownFields = reader.forEachTag { tag ->
when (tag) {
1 -> outer_number_before = ProtoAdapter.INT32.decode(reader)
2 -> embedded_message = EmbeddedMessage.ADAPTER.decode(reader)
else -> reader.readUnknownField(tag)
}
}
return OuterMessage(
outer_number_before = outer_number_before,
embedded_message = embedded_message,
unknownFields = unknownFields
)
}
public override fun redact(`value`: OuterMessage): OuterMessage = value.copy(
embedded_message = value.embedded_message?.let(EmbeddedMessage.ADAPTER::redact),
unknownFields = ByteString.EMPTY
)
}
private const val serialVersionUID: Long = 0L
}
}
| wire-library/wire-tests/src/commonTest/proto-kotlin/squareup/protos/packed_encoding/OuterMessage.kt | 2383245817 |
/*
* Copyright (c) 2019 MarkLogic Corporation
*
* 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.marklogic.client.tools.gradle
import com.marklogic.client.tools.proxy.Generator
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
open class EndpointProxiesGenTask : DefaultTask() {
private val generator = Generator()
@Input
var serviceDeclarationFile: String = ""
@Input
var javaBaseDirectory: String = ""
@TaskAction
fun serviceBundleToJava() {
val proxiesConfig = project.property("endpointProxiesConfig") as EndpointProxiesConfig
if (serviceDeclarationFile == "") {
serviceDeclarationFile = when {
proxiesConfig.serviceDeclarationFile != "" -> proxiesConfig.serviceDeclarationFile
project.hasProperty("serviceDeclarationFile") -> project.property("serviceDeclarationFile") as String
else -> throw IllegalArgumentException("serviceDeclarationFile not specified")
}
}
if (javaBaseDirectory == "") {
javaBaseDirectory = when {
proxiesConfig.javaBaseDirectory != "" -> proxiesConfig.javaBaseDirectory
project.hasProperty("javaBaseDirectory") -> project.property("javaBaseDirectory") as String
else -> project.projectDir.resolve("src/main/java").path
}
}
generator.serviceBundleToJava(serviceDeclarationFile, javaBaseDirectory)
}
} | ml-development-tools/src/main/kotlin/com/marklogic/client/tools/gradle/EndpointProxiesGenTask.kt | 1789081977 |
package arcs.tools
import arcs.core.data.CountType
import arcs.core.data.CreatableStorageKey
import arcs.core.data.EntityType
import arcs.core.data.FieldName
import arcs.core.data.FieldType
import arcs.core.data.Plan
import arcs.core.data.Recipe
import arcs.core.data.Schema
import arcs.core.data.SchemaFields
import arcs.core.data.SchemaName
import arcs.core.data.TupleType
import arcs.core.data.TypeVariable
import arcs.core.storage.StorageKeyManager
import arcs.core.type.Type
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.buildCodeBlock
/**
* Adds a code-generated [Plan] to a [FileSpec].
*
* Will also add code-generated [Plan.Handle] properties to the file.
*
* @param recipe [Recipe] source for [Plan] conversion.
* @return self, with code-generated [Plan] and [Plan.Handle]s.
*/
fun FileSpec.Builder.addRecipe(recipe: Recipe): FileSpec.Builder {
val handles = recipe.handles.values.map {
PropertySpec.builder("${recipe.name}_${it.name}", Plan.Handle::class)
.initializer(buildHandleBlock(it))
.build()
}
val ctx = mapOf(
"plan" to Plan::class,
"handles" to buildCollectionBlock(handles, "%N"),
// TODO(161940699) Generate particles
"particles" to buildCollectionBlock(listOf<Recipe.Particle>()),
// TODO(161940729) Generate Annotations
"annotations" to buildCollectionBlock(listOf<Annotation>())
)
val plan = PropertySpec.builder("${recipe.name}Plan", Plan::class)
.initializer(
buildCodeBlock {
addNamed(
"""
%plan:T(
particles = %particles:L,
handles = %handles:L,
annotations = %annotations:L
)
""".trimIndent(),
ctx
)
}
)
.build()
handles.forEach { this.addProperty(it) }
this.addProperty(plan)
return this
}
/**
* Adds a code-generated [Plan.Handle] to a [CodeBlock].
*
* @param handle a source [Recipe.Handle] for conversion.
* @return self, with a code-generated [Plan.Handle] instance.
*/
fun CodeBlock.Builder.addHandle(handle: Recipe.Handle): CodeBlock.Builder = with(handle) {
val ctx = mapOf(
"handle" to Plan.Handle::class,
// TODO(161941222) verify join handles work
"storageKeyManager" to StorageKeyManager::class,
"key" to storageKey,
"type" to buildTypeBlock(type),
"annotations" to buildCollectionBlock(emptyList<Annotation>()),
"creatable" to CreatableStorageKey::class,
"name" to name
)
val storageKeyTemplate = storageKey
?.let { "storageKey = %storageKeyManager:T.GLOBAL_INSTANCE.parse(%key:S)," }
?: "storageKey = %creatable:T(%name:S),"
[email protected](
"""
%handle:T(
$storageKeyTemplate
type = %type:L,
annotations = %annotations:L
)
""".trimIndent(),
ctx
)
}
/** Shorthand for building a [CodeBlock] with a code-generated [Plan.Handle]. */
fun buildHandleBlock(handle: Recipe.Handle): CodeBlock = buildCodeBlock { addHandle(handle) }
/** Code-generates a [Type] within a [CodeBlock]. */
fun CodeBlock.Builder.addType(type: Type): CodeBlock.Builder = when (type) {
is EntityType -> add("%T(%L)", EntityType::class, buildSchemaBlock(type.entitySchema))
is Type.TypeContainer<*> -> add("%T(%L)", type::class, buildTypeBlock(type.containedType))
is CountType -> add("%T()", CountType::class)
is TupleType -> add(
"%T(%L)",
TupleType::class,
buildCollectionBlock(type.elementTypes) { builder, item ->
builder.add(buildTypeBlock(item))
}
)
is TypeVariable -> add(
"%T(%S, %L, %L)",
TypeVariable::class,
type.name,
type.constraint?.let { buildTypeBlock(it) },
type.maxAccess
)
else -> throw IllegalArgumentException("[Type] $type is not supported.")
}
/** Shorthand for building a [CodeBlock] with a code-generated [Type]. */
fun buildTypeBlock(type: Type): CodeBlock = buildCodeBlock { addType(type) }
/** Code-generates a [Schema] within a [CodeBlock]. */
fun CodeBlock.Builder.addSchema(schema: Schema): CodeBlock.Builder {
if (Schema.EMPTY == schema) {
add("%T.EMPTY", Schema::class)
return this
}
val ctx = mapOf(
"schema" to Schema::class,
"names" to buildCollectionBlock(schema.names) { builder, item ->
builder.add("%T(%S)", SchemaName::class, item.name)
},
"fields" to buildSchemaFieldsBlock(schema.fields),
"hash" to schema.hash
)
addNamed(
"""
%schema:T(
names = %names:L,
fields = %fields:L,
hash = %hash:S
)
""".trimIndent(),
ctx
)
return this
}
/** Shorthand for building a [CodeBlock] with a code-generated [Schema]. */
fun buildSchemaBlock(schema: Schema): CodeBlock = buildCodeBlock { addSchema(schema) }
/** Code-generates [SchemaFields] within a [CodeBlock]. */
fun CodeBlock.Builder.addSchemaFields(fields: SchemaFields): CodeBlock.Builder {
val toSchemaField = { builder: CodeBlock.Builder, entry: Map.Entry<FieldName, FieldType> ->
builder.add("%S to %L", entry.key, buildFieldTypeBlock(entry.value))
Unit
}
val ctx = mapOf(
"fields" to SchemaFields::class,
"singletons" to buildCollectionBlock(fields.singletons, toSchemaField),
"collections" to buildCollectionBlock(fields.collections, toSchemaField)
)
addNamed(
"""
%fields:T(
singletons = %singletons:L,
collections = %collections:L
)
""".trimIndent(),
ctx
)
return this
}
/** Shorthand for building a [CodeBlock] with code-generated [SchemaFields]. */
fun buildSchemaFieldsBlock(schemaFields: SchemaFields): CodeBlock = buildCodeBlock {
addSchemaFields(schemaFields)
}
/** Code-generates [FieldType] within a [CodeBlock]. */
fun CodeBlock.Builder.addFieldType(field: FieldType): CodeBlock.Builder = when (field) {
is FieldType.Primitive -> add("%T.%L", FieldType::class, field.primitiveType)
is FieldType.EntityRef -> add("%T(%S)", field::class, field.schemaHash)
is FieldType.InlineEntity -> add("%T(%S)", field::class, field.schemaHash)
is FieldType.Tuple -> add(
"%T(%L)",
FieldType.Tuple::class,
buildCollectionBlock(field.types) { builder, item -> builder.addFieldType(item) }
)
is FieldType.ListOf -> add(
"%T(%L)",
FieldType.ListOf::class,
buildFieldTypeBlock(field.primitiveType)
)
is FieldType.NullableOf -> add(
"%T(%L)",
FieldType.NullableOf::class,
buildFieldTypeBlock(field.innerType)
)
}
/** Shorthand for building a [CodeBlock] with a code-generated [FieldType]. */
fun buildFieldTypeBlock(field: FieldType): CodeBlock = buildCodeBlock { addFieldType(field) }
| java/arcs/tools/PlanGenerator.kt | 816188106 |
package bz.stewart.bracken.web.view.bootstrap
interface NavItem {
val isActive: Boolean
val href: String
val label: String
val classes: String?
}
class StdNavItem(override val label: String, override val href: String, isActive: Boolean, override val classes: String? = null) : NavItem {
override val isActive: Boolean = isActive
} | web/src/main/kotlin/bz/stewart/bracken/web/view/bootstrap/NavItem.kt | 2778991580 |
package com.task.utils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
fun <T> LifecycleOwner.observe(liveData: LiveData<T>, action: (t: T) -> Unit) {
liveData.observe(this, Observer { it?.let { t -> action(t) } })
}
fun <T> LifecycleOwner.observeEvent(liveData: LiveData<SingleEvent<T>>, action: (t: SingleEvent<T>) -> Unit) {
liveData.observe(this, Observer { it?.let { t -> action(t) } })
}
| app/src/main/java/com/task/utils/ArchComponentExt.kt | 4270488107 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.editorconfig.language.messages
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.encoding.ChangeFileEncodingAction
import com.intellij.openapi.vfs.encoding.EncodingUtil
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.util.ArrayUtil
import org.editorconfig.language.filetype.EditorConfigFileConstants
import java.util.*
class EditorConfigWrongFileEncodingNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>(), DumbAware {
override fun getKey() = KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (fileEditor !is TextEditor) return null
val editor = fileEditor.editor
if (editor.getUserData(HIDDEN_KEY) != null) return null
if (PropertiesComponent.getInstance().isTrueValue(DISABLE_KEY)) return null
if (file.extension != EditorConfigFileConstants.FILE_EXTENSION) return null
if (file.charset == Charsets.UTF_8) return null
return buildPanel(project, editor, file)
}
private fun buildPanel(project: Project, editor: Editor, file: VirtualFile): EditorNotificationPanel {
val result = EditorNotificationPanel(editor, null, null)
result.text(EditorConfigBundle.get("notification.encoding.message"))
val convert = EditorConfigBundle["notification.action.convert"]
result.createActionLabel(convert) {
val text = editor.document.text
val isSafeToConvert = isSafeToConvertTo(file, text)
val isSafeToReload = isSafeToReloadIn(file, text)
ChangeFileEncodingAction.changeTo(project, editor.document, editor, file, Charsets.UTF_8, isSafeToConvert, isSafeToReload)
}
val hide = EditorConfigBundle["notification.action.hide.once"]
result.createActionLabel(hide) {
editor.putUserData<Boolean>(HIDDEN_KEY, true)
update(file, project)
}
val hideForever = EditorConfigBundle["notification.action.hide.forever"]
result.createActionLabel(hideForever) {
PropertiesComponent.getInstance().setValue(DISABLE_KEY, true)
update(file, project)
}
return result
}
private fun update(file: VirtualFile, project: Project) = EditorNotifications.getInstance(project).updateNotifications(file)
private fun isSafeToReloadIn(file: VirtualFile, text: CharSequence): EncodingUtil.Magic8 {
val bytes = file.contentsToByteArray()
// file has BOM but the charset hasn't
val bom = file.bom
if (bom != null && !CharsetToolkit.canHaveBom(Charsets.UTF_8, bom)) return EncodingUtil.Magic8.NO_WAY
// the charset has mandatory BOM (e.g. UTF-xx) but the file hasn't or has wrong
val mandatoryBom = CharsetToolkit.getMandatoryBom(Charsets.UTF_8)
if (mandatoryBom != null && !ArrayUtil.startsWith(bytes, mandatoryBom)) return EncodingUtil.Magic8.NO_WAY
val loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, Charsets.UTF_8).toString()
var bytesToSave: ByteArray = try {
val separator = FileDocumentManager.getInstance().getLineSeparator(file, null)
StringUtil.convertLineSeparators(loaded, separator).toByteArray(Charsets.UTF_8)
}
catch (e: UnsupportedOperationException) {
return EncodingUtil.Magic8.NO_WAY
}
catch (e: NullPointerException) {
return EncodingUtil.Magic8.NO_WAY
}
// turned out some crazy charsets have incorrectly implemented .newEncoder() returning null
if (bom != null && !ArrayUtil.startsWith(bytesToSave, bom)) {
bytesToSave = ArrayUtil.mergeArrays(bom, bytesToSave) // for 2-byte encodings String.getBytes(Charset) adds BOM automatically
}
return if (!Arrays.equals(bytesToSave, bytes)) EncodingUtil.Magic8.NO_WAY
else if (StringUtil.equals(loaded, text)) EncodingUtil.Magic8.ABSOLUTELY
else EncodingUtil.Magic8.WELL_IF_YOU_INSIST
}
private fun isSafeToConvertTo(file: VirtualFile, text: CharSequence) = try {
val bytesOnDisk = file.contentsToByteArray()
val lineSeparator = FileDocumentManager.getInstance().getLineSeparator(file, null)
val textToSave = if (lineSeparator == "\n") text else StringUtilRt.convertLineSeparators(text, lineSeparator)
val saved = LoadTextUtil.chooseMostlyHarmlessCharset(file.charset, Charsets.UTF_8, textToSave.toString()).second
val textLoadedBack = LoadTextUtil.getTextByBinaryPresentation(saved, Charsets.UTF_8)
when {
!StringUtil.equals(text, textLoadedBack) -> EncodingUtil.Magic8.NO_WAY
Arrays.equals(saved, bytesOnDisk) -> EncodingUtil.Magic8.ABSOLUTELY
else -> EncodingUtil.Magic8.WELL_IF_YOU_INSIST
}
}
catch (e: UnsupportedOperationException) { // unsupported encoding
EncodingUtil.Magic8.NO_WAY
}
private companion object {
private val KEY = Key.create<EditorNotificationPanel>("editorconfig.wrong.encoding.notification")
private val HIDDEN_KEY = Key.create<Boolean>("editorconfig.wrong.encoding.notification.hidden")
private const val DISABLE_KEY = "editorconfig.wrong.encoding.notification.disabled"
}
}
| plugins/editorconfig/src/org/editorconfig/language/messages/EditorConfigWrongFileEncodingNotificationProvider.kt | 763332892 |
// 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.overrideImplement
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyze
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassKind
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.KtIconProvider.getIcon
import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.psi.KtClassOrObject
internal open class KtOverrideMembersHandler : KtGenerateMembersHandler(false) {
@OptIn(KtAllowAnalysisOnEdt::class)
override fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<KtClassMember> {
return allowAnalysisOnEdt {
analyze(classOrObject) {
collectMembers(classOrObject)
}
}
}
fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject): List<KtClassMember> {
val classOrObjectSymbol = classOrObject.getClassOrObjectSymbol()
return getOverridableMembers(classOrObjectSymbol).map { (symbol, bodyType, containingSymbol) ->
KtClassMember(
KtClassMemberInfo(
symbol,
symbol.render(renderOption),
getIcon(symbol),
containingSymbol?.classIdIfNonLocal?.asSingleFqName()?.toString() ?: containingSymbol?.name?.asString(),
containingSymbol?.let { getIcon(it) }
),
bodyType,
preferConstructorParameter = false
)
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.getOverridableMembers(classOrObjectSymbol: KtClassOrObjectSymbol): List<OverrideMember> {
return buildList {
classOrObjectSymbol.getMemberScope().getCallableSymbols().forEach { symbol ->
if (!symbol.isVisibleInClass(classOrObjectSymbol)) return@forEach
val implementationStatus = symbol.getImplementationStatus(classOrObjectSymbol) ?: return@forEach
if (!implementationStatus.isOverridable) return@forEach
val intersectionSymbols = symbol.getIntersectionOverriddenSymbols()
val symbolsToProcess = if (intersectionSymbols.size <= 1) {
listOf(symbol)
} else {
val nonAbstractMembers = intersectionSymbols.filter { (it as? KtSymbolWithModality)?.modality != Modality.ABSTRACT }
// If there are non-abstract members, we only want to show override for these non-abstract members. Otherwise, show any
// abstract member to override.
nonAbstractMembers.ifEmpty {
listOf(intersectionSymbols.first())
}
}
val hasNoSuperTypesExceptAny = classOrObjectSymbol.superTypes.singleOrNull()?.isAny == true
for (symbolToProcess in symbolsToProcess) {
val originalOverriddenSymbol = symbolToProcess.originalOverriddenSymbol
val containingSymbol = originalOverriddenSymbol?.originalContainingClassForOverride
val bodyType = when {
classOrObjectSymbol.classKind == KtClassKind.INTERFACE && containingSymbol?.classIdIfNonLocal == StandardClassIds.Any -> {
if (hasNoSuperTypesExceptAny) {
// If an interface does not extends any other interfaces, FE1.0 simply skips members of `Any`. So we mimic
// the same behavior. See idea/testData/codeInsight/overrideImplement/noAnyMembersInInterface.kt
continue
} else {
BodyType.NO_BODY
}
}
(originalOverriddenSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT ->
BodyType.FROM_TEMPLATE
symbolsToProcess.size > 1 ->
BodyType.QUALIFIED_SUPER
else ->
BodyType.SUPER
}
// Ideally, we should simply create `KtClassMember` here and remove the intermediate `OverrideMember` data class. But
// that doesn't work because this callback function is holding a read lock and `symbol.render(renderOption)` requires
// the write lock.
// Hence, we store the data in an intermediate `OverrideMember` data class and do the rendering later in the `map` call.
add(OverrideMember(symbolToProcess, bodyType, containingSymbol))
}
}
}
}
private data class OverrideMember(val symbol: KtCallableSymbol, val bodyType: BodyType, val containingSymbol: KtClassOrObjectSymbol?)
override fun getChooserTitle() = KotlinIdeaCoreBundle.message("override.members.handler.title")
override fun getNoMembersFoundHint() = KotlinIdeaCoreBundle.message("override.members.handler.no.members.hint")
} | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/core/overrideImplement/KtOverrideMembersHandler.kt | 3829363160 |
package kebab.support.page
import kebab.NavigatorFactory
import kebab.core.Page
/**
* Created by yy_yank on 2016/10/02.
*/
class DefaultPageContentSupport(page: Page, contentTemplates: Any, navigatorFactory: NavigatorFactory) : PageContentSupport {} | src/main/kotlin/support/page/DefaultPageContentSupport.kt | 683038918 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package org.jetbrains.plugins.ideavim.action.change.delete
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.VimStateMachine
import com.maddyhome.idea.vim.group.visual.IdeaSelectionControl
import org.jetbrains.plugins.ideavim.SkipNeovimReason
import org.jetbrains.plugins.ideavim.TestWithoutNeovim
import org.jetbrains.plugins.ideavim.VimTestCase
import org.jetbrains.plugins.ideavim.waitAndAssertMode
/**
* @author Alex Plate
*/
class DeleteVisualActionTest : VimTestCase() {
fun `test delete block SE direction`() {
val keys = listOf("<C-V>e2j", "d")
val before = """
A Discovery
I |${c}found| it in a legendary land
al|l roc|ks and lavender and tufted grass,
wh|ere i|t was settled on some sodden sand
hard by the torrent of a mountain pass.
""".trimIndent()
val after = """
A Discovery
I |$c| it in a legendary land
al||ks and lavender and tufted grass,
wh||t was settled on some sodden sand
hard by the torrent of a mountain pass.
""".trimIndent()
doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE)
}
fun `test delete block SW direction`() {
val keys = listOf("<C-V>b2j", "d")
val before = """
A Discovery
I |foun${c}d| it in a legendary land
al|l roc|ks and lavender and tufted grass,
wh|ere i|t was settled on some sodden sand
hard by the torrent of a mountain pass.
""".trimIndent()
val after = """
A Discovery
I |$c| it in a legendary land
al||ks and lavender and tufted grass,
wh||t was settled on some sodden sand
hard by the torrent of a mountain pass.
""".trimIndent()
doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE)
}
fun `test delete block NW direction`() {
val keys = listOf("<C-V>b2k", "d")
val before = """
A Discovery
I |found| it in a legendary land
al|l roc|ks and lavender and tufted grass,
wh|ere ${c}i|t was settled on some sodden sand
hard by the torrent of a mountain pass.
""".trimIndent()
val after = """
A Discovery
I |$c| it in a legendary land
al||ks and lavender and tufted grass,
wh||t was settled on some sodden sand
hard by the torrent of a mountain pass.
""".trimIndent()
doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE)
}
fun `test delete block NE direction`() {
val keys = listOf("<C-V>2e2k", "d")
val before = """
A Discovery
I |found| it in a legendary land
al|l roc|ks and lavender and tufted grass,
wh|${c}ere i|t was settled on some sodden sand
hard by the torrent of a mountain pass.
""".trimIndent()
val after = """
A Discovery
I |$c| it in a legendary land
al||ks and lavender and tufted grass,
wh||t was settled on some sodden sand
hard by the torrent of a mountain pass.
""".trimIndent()
doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE)
}
@TestWithoutNeovim(SkipNeovimReason.DIFFERENT)
fun `test delete after extend selection`() {
// This test emulates deletion after structural selection
// In short, when caret is not on the selection end
configureByText(
"""
A Discovery
${s}I found it in a legendary land
all rocks ${c}and lavender and tufted grass,
where it was settled on some sodden sand
${se}hard by the torrent of a mountain pass.
""".trimIndent()
)
IdeaSelectionControl.controlNonVimSelectionChange(myFixture.editor)
waitAndAssertMode(myFixture, VimStateMachine.Mode.VISUAL)
typeText(injector.parser.parseKeys("d"))
assertState(
"""
A Discovery
hard by the torrent of a mountain pass.
""".trimIndent()
)
assertState(VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE)
}
fun `test delete with dollar motion`() {
val keys = listOf("<C-V>3j$", "d")
val before = """
A Discovery
I |${c}found it in a legendary land
al|l rocks and lavender and tufted grass,[ additional symbols]
wh|ere it was settled on some sodden sand
ha|rd by the torrent of a mountain pass.
""".trimIndent()
val after = """
A Discovery
I |
al|
wh|
ha|
""".trimIndent()
doTest(keys, before, after, VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE)
}
}
| src/test/java/org/jetbrains/plugins/ideavim/action/change/delete/DeleteVisualActionTest.kt | 3946231042 |
package au.com.dius.pact.consumer.junit
import au.com.dius.pact.core.model.annotations.Pact
import au.com.dius.pact.consumer.PactMismatchesException
import au.com.dius.pact.consumer.PactVerificationResult
import au.com.dius.pact.consumer.PactVerificationResult.Ok
import au.com.dius.pact.core.model.RequestResponsePact
import au.com.dius.pact.core.model.messaging.MessagePact
import java.lang.reflect.Method
object JUnitTestSupport {
/**
* validates method signature as described at [Pact]
*/
@JvmStatic
fun conformsToSignature(m: Method): Boolean {
val pact = m.getAnnotation(Pact::class.java)
val conforms = (pact != null &&
RequestResponsePact::class.java.isAssignableFrom(m.returnType) &&
m.parameterTypes.size == 1 &&
m.parameterTypes[0].isAssignableFrom(Class.forName("au.com.dius.pact.consumer.dsl.PactDslWithProvider")))
if (!conforms && pact != null) {
throw UnsupportedOperationException("Method ${m.name} does not conform required method signature " +
"'public RequestResponsePact xxx(PactDslWithProvider builder)'")
}
return conforms
}
/**
* validates method signature for a Message Pact test
*/
@JvmStatic
fun conformsToMessagePactSignature(m: Method): Boolean {
val pact = m.getAnnotation(Pact::class.java)
val hasValidPactSignature = MessagePact::class.java.isAssignableFrom(m.returnType) &&
m.parameterTypes.size == 1 &&
m.parameterTypes[0].isAssignableFrom(Class.forName("au.com.dius.pact.consumer.MessagePactBuilder"))
if (!hasValidPactSignature && pact != null) {
throw UnsupportedOperationException("Method ${m.name} does not conform required method signature " +
"'public MessagePact xxx(MessagePactBuilder builder)'")
}
return hasValidPactSignature
}
@JvmStatic
fun validateMockServerResult(result: PactVerificationResult) {
if (result !is Ok) {
if (result is PactVerificationResult.Error) {
if (result.mockServerState !is Ok) {
throw AssertionError("Pact Test function failed with an exception, possibly due to " + result.mockServerState, result.error)
} else {
throw AssertionError("Pact Test function failed with an exception: " + result.error.message, result.error)
}
} else {
throw PactMismatchesException(result)
}
}
}
}
| consumer/src/main/kotlin/au/com/dius/pact/consumer/junit/JUnitTestSupport.kt | 2901801416 |
package com.github.oliveiradev.lib.shared
/**
* Created by Genius on 03.12.2017.
*/
enum class TypeRequest(value: Int) {
CAMERA(1), GALLERY(2), COMBINE(3), COMBINE_MULTIPLE(4);
} | lib/src/main/java/com/github/oliveiradev/lib/shared/TypeRequest.kt | 89795555 |
package forpdateam.ru.forpda.presentation.announce
import moxy.viewstate.strategy.AddToEndSingleStrategy
import moxy.viewstate.strategy.StateStrategyType
import forpdateam.ru.forpda.common.mvp.IBaseView
import forpdateam.ru.forpda.entity.remote.forum.Announce
/**
* Created by radiationx on 02.01.18.
*/
@StateStrategyType(AddToEndSingleStrategy::class)
interface AnnounceView : IBaseView {
fun showData(data: Announce)
fun setStyleType(type: String)
}
| app/src/main/java/forpdateam/ru/forpda/presentation/announce/AnnounceView.kt | 1320372264 |
package com.edwardharker.aircraftrecognition.search
import org.junit.Test
import org.mockito.Mockito
import rx.Observable
import rx.observers.TestSubscriber
class SearchStoreTest {
private val testSubscriber = TestSubscriber<SearchState>()
private val actionSubject = rx.subjects.PublishSubject.create<SearchAction>()
@Test
fun usesSearchFunctionForQueryChangedActions() {
val mockedSearchUseCase = Mockito.mock(MockSearchUseCase::class.java)
val store = SearchStore(mockedSearchUseCase::search, noOpReducer)
store.dispatch(actionSubject)
store.subscribe().subscribe(testSubscriber)
actionSubject.onNext(queryChangedAction)
Mockito.verify(mockedSearchUseCase).search(queryChangedAction)
}
@Test
fun startsWithEmptyState() {
val expected = SearchState.empty()
val store = SearchStore(noOpSearchUseCase, noOpReducer)
store.dispatch(actionSubject)
store.subscribe().subscribe(testSubscriber)
actionSubject.onNext(SearchResultsAction(emptyList()))
testSubscriber.assertValues(expected)
}
@Test
fun returnsOutputOfReducer() {
val expected = SearchState.error()
val fakeReducer = fun(_: SearchState, _: SearchAction): SearchState = expected
val fakeSearchUseCase = fun(_: QueryChangedAction): Observable<SearchAction> =
Observable.just(SearchResultsAction(emptyList()))
val store = SearchStore(fakeSearchUseCase, fakeReducer)
store.dispatch(actionSubject)
store.subscribe().subscribe(testSubscriber)
actionSubject.onNext(queryChangedAction)
testSubscriber.assertValues(SearchState.empty(), expected)
}
private interface MockSearchUseCase {
fun search(action: QueryChangedAction): Observable<SearchAction>
}
private companion object {
private val queryChangedAction = QueryChangedAction("query")
private val noOpReducer =
fun(oldState: SearchState, _: SearchAction): SearchState {
return oldState
}
private val noOpSearchUseCase =
fun(_: QueryChangedAction): Observable<SearchAction> {
return Observable.never()
}
}
} | recognition/src/test/kotlin/com/edwardharker/aircraftrecognition/search/SearchStoreTest.kt | 2685366241 |
package org.wordpress.android.localcontentmigration
import android.database.Cursor
import android.net.Uri
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import org.wordpress.android.localcontentmigration.LocalContentEntity.AccessToken
import org.wordpress.android.localcontentmigration.LocalContentEntity.BloggingReminders
import org.wordpress.android.localcontentmigration.LocalContentEntity.EligibilityStatus
import org.wordpress.android.localcontentmigration.LocalContentEntity.Post
import org.wordpress.android.localcontentmigration.LocalContentEntity.ReaderPosts
import org.wordpress.android.localcontentmigration.LocalContentEntity.Sites
import org.wordpress.android.localcontentmigration.LocalContentEntity.UserFlags
import org.wordpress.android.provider.query.QueryResult
import java.lang.Integer.parseInt
class LocalMigrationContentProvider: TrustedQueryContentProvider() {
@EntryPoint
@InstallIn(SingletonComponent::class)
interface LocalMigrationContentProviderEntryPoint {
fun queryResult(): QueryResult
fun localSiteProviderHelper(): LocalSiteProviderHelper
fun localPostProviderHelper(): LocalPostProviderHelper
fun localEligibilityStatusProviderHelper(): LocalEligibilityStatusProviderHelper
fun localAccessTokenProviderHelper(): LocalAccessTokenProviderHelper
fun userFlagsProviderHelper(): UserFlagsProviderHelper
fun readeSavedPostsProviderHelper(): ReaderSavedPostsProviderHelper
fun bloggingRemindersProviderHelper(): BloggingRemindersProviderHelper
}
override fun query(uri: Uri): Cursor {
val path = checkNotNull(uri.path) { "This provider does not support queries without a path." }
// Find the matching entity and its captured groups
val (entity, groups) = LocalContentEntity.values().firstNotNullOf { entity ->
entity.contentIdCapturePattern.find(path)?.let { match ->
return@firstNotNullOf Pair(entity, match.groups)
}
}
val localEntityId = extractEntityId(groups)
return query(entity, localEntityId)
}
// The first group is the entire match, so we drop that and parse the next captured group as an integer
private fun extractEntityId(groups: MatchGroupCollection) = groups.drop(1).firstOrNull()?.let {
parseInt(it.value)
}
private fun query(entity: LocalContentEntity, localEntityId: Int?): Cursor {
val context = checkNotNull(context) { "Cannot find context from the provider." }
with(EntryPointAccessors.fromApplication(context.applicationContext,
LocalMigrationContentProviderEntryPoint::class.java)) {
val response = when (entity) {
EligibilityStatus -> localEligibilityStatusProviderHelper().getData()
AccessToken -> localAccessTokenProviderHelper().getData()
UserFlags -> userFlagsProviderHelper().getData()
ReaderPosts -> readeSavedPostsProviderHelper().getData()
BloggingReminders -> bloggingRemindersProviderHelper().getData()
Sites -> localSiteProviderHelper().getData()
Post -> localPostProviderHelper().getData(localEntityId)
}
return queryResult().createCursor(response)
}
}
}
interface LocalDataProviderHelper {
fun getData(localEntityId: Int? = null): LocalContentEntityData
}
| WordPress/src/main/java/org/wordpress/android/localcontentmigration/LocalMigrationContentProvider.kt | 399048035 |
package ru.siksmfp.network.harness.implementation.nio.simple.server
import ru.siksmfp.network.harness.implementation.nio.ssl.server.NioSSLServerContext
import java.nio.ByteBuffer
import java.nio.channels.SelectionKey
import java.nio.channels.SelectionKey.OP_READ
import java.nio.channels.SocketChannel
class SSLWriteHandler(
private val clients: MutableSet<SocketChannel>
) : SelectionHandler {
override fun handle(selectionKey: SelectionKey) {
val context = selectionKey.attachment() as NioSSLServerContext
val written = context.tlsChannel.write(ByteBuffer.wrap("OK".toByteArray()))
println("NioServer: sending response OK")
if (written == -1) {
context.tlsChannel.close()
println("Disconnected from in write")
return
}
selectionKey.interestOps(OP_READ)
}
override fun close() {
//no shared state
}
} | src/main/kotlin/ru/siksmfp/network/harness/implementation/nio/ssl/server/SSLWriteHandler.kt | 1036730826 |
package test
val o = Obj | plugins/kotlin/idea/tests/testData/refactoring/safeDeleteMultiModule/byExpectObject/after/JVM/src/test/test.kt | 1663132710 |
// 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.refactoring.move.moveFilesOrDirectories
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesHelper
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.Function
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.refactoring.invokeOnceOnCommandFinish
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsProcessor
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.analyzeConflictsInFile
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
class KotlinMoveDirectoryWithClassesHelper : MoveDirectoryWithClassesHelper() {
private data class FileUsagesWrapper(
val psiFile: KtFile,
val usages: List<UsageInfo>,
val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor?
) : UsageInfo(psiFile)
private class MoveContext(
val newParent: PsiDirectory,
val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor?
)
private val fileHandler = MoveKotlinFileHandler()
private var fileToMoveContext: MutableMap<PsiFile, MoveContext>? = null
private fun getOrCreateMoveContextMap(): MutableMap<PsiFile, MoveContext> {
return fileToMoveContext ?: HashMap<PsiFile, MoveContext>().apply {
fileToMoveContext = this
invokeOnceOnCommandFinish { fileToMoveContext = null }
}
}
override fun findUsages(
filesToMove: MutableCollection<PsiFile>,
directoriesToMove: Array<out PsiDirectory>,
result: MutableCollection<UsageInfo>,
searchInComments: Boolean,
searchInNonJavaFiles: Boolean,
project: Project
) {
filesToMove
.filterIsInstance<KtFile>()
.mapTo(result) { FileUsagesWrapper(it, fileHandler.findUsages(it, null, false), null) }
}
override fun preprocessUsages(
project: Project,
files: MutableSet<PsiFile>,
infos: Array<UsageInfo>,
directory: PsiDirectory?,
conflicts: MultiMap<PsiElement, String>
) {
val psiPackage = directory?.getPackage() ?: return
val moveTarget = KotlinDirectoryMoveTarget(FqName(psiPackage.qualifiedName), directory.virtualFile)
for ((index, usageInfo) in infos.withIndex()) {
if (usageInfo !is FileUsagesWrapper) continue
ProgressManager.getInstance().progressIndicator?.text2 = KotlinBundle.message("text.processing.file.0", usageInfo.psiFile.name)
runReadAction {
analyzeConflictsInFile(usageInfo.psiFile, usageInfo.usages, moveTarget, files, conflicts) {
infos[index] = usageInfo.copy(usages = it)
}
}
}
}
override fun beforeMove(psiFile: PsiFile) {
}
// Actual move logic is implemented in postProcessUsages since usages are not available here
override fun move(
file: PsiFile,
moveDestination: PsiDirectory,
oldToNewElementsMapping: MutableMap<PsiElement, PsiElement>,
movedFiles: MutableList<PsiFile>,
listener: RefactoringElementListener?
): Boolean {
if (file !is KtFile) return false
val moveDeclarationsProcessor = fileHandler.initMoveProcessor(file, moveDestination, false)
val moveContextMap = getOrCreateMoveContextMap()
moveContextMap[file] = MoveContext(moveDestination, moveDeclarationsProcessor)
if (moveDeclarationsProcessor != null) {
moveDestination.getFqNameWithImplicitPrefix()?.quoteIfNeeded()?.let {
file.packageDirective?.fqName = it
}
}
return true
}
override fun afterMove(newElement: PsiElement) {
}
override fun postProcessUsages(usages: Array<out UsageInfo>, newDirMapper: Function<in PsiDirectory, out PsiDirectory>) {
val fileToMoveContext = fileToMoveContext ?: return
try {
val usagesToProcess = ArrayList<FileUsagesWrapper>()
usages
.filterIsInstance<FileUsagesWrapper>()
.forEach body@{
val file = it.psiFile
val moveContext = fileToMoveContext[file] ?: return@body
MoveFilesOrDirectoriesUtil.doMoveFile(file, moveContext.newParent)
val moveDeclarationsProcessor = moveContext.moveDeclarationsProcessor ?: return@body
val movedFile = moveContext.newParent.findFile(file.name) ?: return@body
usagesToProcess += FileUsagesWrapper(movedFile as KtFile, it.usages, moveDeclarationsProcessor)
}
usagesToProcess.forEach { fileHandler.retargetUsages(it.usages, it.moveDeclarationsProcessor!!) }
} finally {
this.fileToMoveContext = null
}
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/KotlinMoveDirectoryWithClassesHelper.kt | 712661354 |
package org.snakeskin.utility.value
import kotlin.reflect.KProperty
/**
* @author Cameron Earle
* @version 8/7/2019
*
*/
class AsyncBoolean(initialValue: Boolean) {
private val lock = Any()
private var value = initialValue
operator fun getValue(thisRef: Any?, property: KProperty<*>): Boolean {
synchronized(lock) {
return value
}
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) {
synchronized(lock) {
this.value = value
}
}
} | SnakeSkin-Core/src/main/kotlin/org/snakeskin/utility/value/AsyncBoolean.kt | 2633195496 |
package com.sys1yagi.longeststreakandroid.dagger.module
import android.content.Context
import com.sys1yagi.longeststreakandroid.db.OrmaDatabase
import com.sys1yagi.longeststreakandroid.tool.LongestStreakCounter
import javax.inject.Singleton
import dagger.Module
import dagger.Provides
@Singleton
@Module
class IoModule(val context: Context) {
@Provides
fun provideLongestStreakCounter(): LongestStreakCounter {
return LongestStreakCounter()
}
}
| app/src/main/java/com/sys1yagi/longeststreakandroid/dagger/module/IoModule.kt | 1349748331 |
package <%= appPackage %>.remote
import io.reactivex.Single
import <%= appPackage %>.data.model.BufferooEntity
import <%= appPackage %>.data.repository.BufferooRemote
import <%= appPackage %>.remote.mapper.BufferooEntityMapper
import javax.inject.Inject
/**
* Remote implementation for retrieving Bufferoo instances. This class implements the
* [BufferooRemote] from the Data layer as it is that layers responsibility for defining the
* operations in which data store implementation layers can carry out.
*/
class BufferooRemoteImpl @Inject constructor(private val bufferooService: BufferooService,
private val entityMapper: BufferooEntityMapper) :
BufferooRemote {
/**
* Retrieve a list of [BufferooEntity] instances from the [BufferooService].
*/
override fun getBufferoos(): Single<List<BufferooEntity>> {
return bufferooService.getBufferoos()
.map {
it.team.map { listItem ->
entityMapper.mapFromRemote(listItem)
}
}
}
} | templates/buffer-clean-kotlin/remote/src/main/java/org/buffer/android/boilerplate/remote/BufferooRemoteImpl.kt | 75256084 |
package azadev.backt.webserver.utils
private val REX_HTML_TAGS = "</?[a-z][^<]*?>".toRegex(RegexOption.IGNORE_CASE)
fun String.removeHtmlTags() = replace(REX_HTML_TAGS, "")
private val REX_HTML_BR = "<br/?>".toRegex(RegexOption.IGNORE_CASE)
fun String.replaceBrWithNl() = replace(REX_HTML_BR, "\n")
private val REX_WS = "[\\s\\p{Z}]+".toRegex()
fun String.splitByWhitespaces() = split(REX_WS)
fun String.collapseWs(collapseTo: String = " ") = replace(REX_WS, collapseTo)
| src/main/kotlin/azadev/backt/webserver/utils/text.kt | 431285143 |
// "Add 'JUnit4' to classpath" "true"
// ERROR: Unresolved reference: Before
// ERROR: Unresolved reference: junit
// WITH_STDLIB
// Do not apply quickfix as platform can't handle open maven download dialog in unit test mode
// APPLY_QUICKFIX: false
package some
import org.<caret>junit.Before
open class KBase {
@Before
fun setUp() {
throw UnsupportedOperationException()
}
} | plugins/kotlin/idea/tests/testData/quickfix/libraries/junit.kt | 192816292 |
// 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.application.options.editor
import com.intellij.ide.ui.UISettings
import com.intellij.ide.ui.UISettingsState
import com.intellij.openapi.application.ApplicationBundle.message
import com.intellij.ui.ExperimentalUI
import com.intellij.ui.layout.*
internal const val EDITOR_TABS_OPTIONS_ID = "editor.preferences.tabs"
private val ui: UISettingsState
get() = UISettings.getInstance().state
internal val showDirectoryForNonUniqueFilenames
get() = CheckboxDescriptor(message("checkbox.show.directory.for.non.unique.files"), ui::showDirectoryForNonUniqueFilenames)
internal val markModifiedTabsWithAsterisk: CheckboxDescriptor
get() {
val text = if (ExperimentalUI.isNewUI()) {
message("checkbox.mark.modified.tabs")
}
else message("checkbox.mark.modified.tabs.with.asterisk")
return CheckboxDescriptor(text, ui::markModifiedTabsWithAsterisk)
}
internal val showTabsTooltips
get() = CheckboxDescriptor(message("checkbox.show.tabs.tooltips"), ui::showTabsTooltips)
internal val showFileIcon
get() = CheckboxDescriptor(message("checkbox.show.file.icon.in.editor.tabs"), ui::showFileIconInTabs)
internal val showFileExtension
get() = CheckboxDescriptor(message("checkbox.show.file.extension.in.editor.tabs"), PropertyBinding({ !ui.hideKnownExtensionInTabs }, { ui.hideKnownExtensionInTabs = !it }))
internal val hideTabsIfNeeded
get() = CheckboxDescriptor(message("checkbox.editor.scroll.if.need"), ui::hideTabsIfNeeded)
internal val showPinnedTabsInASeparateRow
get() = CheckboxDescriptor(message("checkbox.show.pinned.tabs.in.a.separate.row"), ui::showPinnedTabsInASeparateRow)
internal val sortTabsAlphabetically
get() = CheckboxDescriptor(message("checkbox.sort.tabs.alphabetically"), ui::sortTabsAlphabetically)
internal val openTabsAtTheEnd
get() = CheckboxDescriptor(message("checkbox.open.new.tabs.at.the.end"), ui::openTabsAtTheEnd)
internal val showTabsInOneRow
get() = CheckboxDescriptor(message("checkbox.editor.tabs.in.single.row"), ui::scrollTabLayoutInEditor)
internal val openInPreviewTabIfPossible
get() = CheckboxDescriptor(message("checkbox.smart.tab.preview"), ui::openInPreviewTabIfPossible,
message("checkbox.smart.tab.preview.inline.help"))
internal val useSmallFont
get() = CheckboxDescriptor(message("checkbox.use.small.font.for.labels"), ui::useSmallLabelsOnTabs)
| platform/platform-impl/src/com/intellij/application/options/editor/EditorTabsOptionsModel.kt | 3692706161 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.editorconfig.language.messages
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.fileEditor.impl.LoadTextUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.util.text.StringUtilRt
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.encoding.ChangeFileEncodingAction
import com.intellij.openapi.vfs.encoding.EncodingUtil
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.util.ArrayUtil
import org.editorconfig.language.filetype.EditorConfigFileConstants
import java.util.*
class EditorConfigWrongFileEncodingNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>(), DumbAware {
override fun getKey() = KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (fileEditor !is TextEditor) return null
val editor = fileEditor.editor
if (editor.getUserData(HIDDEN_KEY) != null) return null
if (PropertiesComponent.getInstance().isTrueValue(DISABLE_KEY)) return null
if (file.extension != EditorConfigFileConstants.FILE_EXTENSION) return null
if (file.charset == Charsets.UTF_8) return null
return buildPanel(project, editor, file)
}
private fun buildPanel(project: Project, editor: Editor, file: VirtualFile): EditorNotificationPanel {
val result = EditorNotificationPanel(editor, null, null, EditorNotificationPanel.Status.Warning)
result.text(EditorConfigBundle.get("notification.encoding.message"))
val convert = EditorConfigBundle["notification.action.convert"]
result.createActionLabel(convert) {
val text = editor.document.text
val isSafeToConvert = isSafeToConvertTo(file, text)
val isSafeToReload = isSafeToReloadIn(file, text)
ChangeFileEncodingAction.changeTo(project, editor.document, editor, file, Charsets.UTF_8, isSafeToConvert, isSafeToReload)
}
val hide = EditorConfigBundle["notification.action.hide.once"]
result.createActionLabel(hide) {
editor.putUserData<Boolean>(HIDDEN_KEY, true)
update(file, project)
}
val hideForever = EditorConfigBundle["notification.action.hide.forever"]
result.createActionLabel(hideForever) {
PropertiesComponent.getInstance().setValue(DISABLE_KEY, true)
update(file, project)
}
return result
}
private fun update(file: VirtualFile, project: Project) = EditorNotifications.getInstance(project).updateNotifications(file)
private fun isSafeToReloadIn(file: VirtualFile, text: CharSequence): EncodingUtil.Magic8 {
val bytes = file.contentsToByteArray()
// file has BOM but the charset hasn't
val bom = file.bom
if (bom != null && !CharsetToolkit.canHaveBom(Charsets.UTF_8, bom)) return EncodingUtil.Magic8.NO_WAY
// the charset has mandatory BOM (e.g. UTF-xx) but the file hasn't or has wrong
val mandatoryBom = CharsetToolkit.getMandatoryBom(Charsets.UTF_8)
if (mandatoryBom != null && !ArrayUtil.startsWith(bytes, mandatoryBom)) return EncodingUtil.Magic8.NO_WAY
val loaded = LoadTextUtil.getTextByBinaryPresentation(bytes, Charsets.UTF_8).toString()
var bytesToSave: ByteArray = try {
val separator = FileDocumentManager.getInstance().getLineSeparator(file, null)
StringUtil.convertLineSeparators(loaded, separator).toByteArray(Charsets.UTF_8)
}
catch (e: UnsupportedOperationException) {
return EncodingUtil.Magic8.NO_WAY
}
catch (e: NullPointerException) {
return EncodingUtil.Magic8.NO_WAY
}
// turned out some crazy charsets have incorrectly implemented .newEncoder() returning null
if (bom != null && !ArrayUtil.startsWith(bytesToSave, bom)) {
bytesToSave = ArrayUtil.mergeArrays(bom, bytesToSave) // for 2-byte encodings String.getBytes(Charset) adds BOM automatically
}
return if (!Arrays.equals(bytesToSave, bytes)) EncodingUtil.Magic8.NO_WAY
else if (StringUtil.equals(loaded, text)) EncodingUtil.Magic8.ABSOLUTELY
else EncodingUtil.Magic8.WELL_IF_YOU_INSIST
}
private fun isSafeToConvertTo(file: VirtualFile, text: CharSequence) = try {
val bytesOnDisk = file.contentsToByteArray()
val lineSeparator = FileDocumentManager.getInstance().getLineSeparator(file, null)
val textToSave = if (lineSeparator == "\n") text else StringUtilRt.convertLineSeparators(text, lineSeparator)
val saved = LoadTextUtil.chooseMostlyHarmlessCharset(file.charset, Charsets.UTF_8, textToSave.toString()).second
val textLoadedBack = LoadTextUtil.getTextByBinaryPresentation(saved, Charsets.UTF_8)
when {
!StringUtil.equals(text, textLoadedBack) -> EncodingUtil.Magic8.NO_WAY
Arrays.equals(saved, bytesOnDisk) -> EncodingUtil.Magic8.ABSOLUTELY
else -> EncodingUtil.Magic8.WELL_IF_YOU_INSIST
}
}
catch (e: UnsupportedOperationException) { // unsupported encoding
EncodingUtil.Magic8.NO_WAY
}
private companion object {
private val KEY = Key.create<EditorNotificationPanel>("editorconfig.wrong.encoding.notification")
private val HIDDEN_KEY = Key.create<Boolean>("editorconfig.wrong.encoding.notification.hidden")
private const val DISABLE_KEY = "editorconfig.wrong.encoding.notification.disabled"
}
}
| plugins/editorconfig/src/org/editorconfig/language/messages/EditorConfigWrongFileEncodingNotificationProvider.kt | 4257533165 |
// 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.caches.project
import com.intellij.openapi.module.Module
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.config.KotlinSourceRootType
import org.jetbrains.kotlin.config.SourceKotlinRootType
import org.jetbrains.kotlin.config.TestSourceKotlinRootType
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.idea.base.facet.implementingModules
import org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule
import org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule
import org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType
import org.jetbrains.kotlin.idea.base.projectStructure.kotlinSourceRootType
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull
import org.jetbrains.kotlin.idea.base.projectStructure.productionSourceInfo
import org.jetbrains.kotlin.idea.base.projectStructure.testSourceInfo
import org.jetbrains.kotlin.idea.base.facet.implementingModules as implementingModulesNew
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.isCommon
import org.jetbrains.kotlin.types.typeUtil.closure
@Deprecated(
"Use 'org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule' instead.",
ReplaceWith("this.isNewMultiPlatformModule", imports = ["org.jetbrains.kotlin.idea.base.facet"]),
level = DeprecationLevel.ERROR
)
@Suppress("unused")
val Module.isNewMPPModule: Boolean
get() = isNewMultiPlatformModule
@Deprecated(
"Use 'org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType' instead.",
ReplaceWith("sourceType", imports = ["org.jetbrains.kotlin.idea.base.facet"]),
level = DeprecationLevel.ERROR
)
@Suppress("unused")
val Module.sourceType: SourceType?
get() = when (kotlinSourceRootType) {
TestSourceKotlinRootType -> @Suppress("DEPRECATION") SourceType.TEST
SourceKotlinRootType -> @Suppress("DEPRECATION") SourceType.PRODUCTION
else -> null
}
@Deprecated(
"Use 'org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule' instead.",
ReplaceWith("isMultiPlatformModule", imports = ["org.jetbrains.kotlin.idea.base.facet"]),
level = DeprecationLevel.ERROR
)
@Suppress("unused")
val Module.isMPPModule: Boolean
get() = isMultiPlatformModule
@Deprecated(
"Use 'org.jetbrains.kotlin.idea.base.facet.implementingModules' instead.",
ReplaceWith("implementingModules", imports = ["org.jetbrains.kotlin.idea.base.facet"]),
level = DeprecationLevel.ERROR
)
@Suppress("unused")
val Module.implementingModules: List<Module>
get() = implementingModulesNew
val ModuleDescriptor.implementingDescriptors: List<ModuleDescriptor>
get() {
val moduleInfo = getCapability(ModuleInfo.Capability)
if (moduleInfo is PlatformModuleInfo) {
return listOf(this)
}
val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList()
val implementingModuleInfos = moduleSourceInfo.module.implementingModules
.mapNotNull { module ->
val sourceRootType = moduleSourceInfo.kotlinSourceRootType ?: return@mapNotNull null
module.getModuleInfo(sourceRootType)
}
return implementingModuleInfos.mapNotNull { it.toDescriptor() }
}
val ModuleDescriptor.allImplementingDescriptors: Collection<ModuleDescriptor>
get() = implementingDescriptors.closure(preserveOrder = true) { it.implementingDescriptors }
fun Module.getModuleInfo(sourceRootType: KotlinSourceRootType): ModuleSourceInfo? {
return when (sourceRootType) {
SourceKotlinRootType -> productionSourceInfo
TestSourceKotlinRootType -> testSourceInfo
}
}
/**
* This function returns immediate parents in dependsOn graph
*/
val ModuleDescriptor.implementedDescriptors: List<ModuleDescriptor>
get() {
val moduleInfo = getCapability(ModuleInfo.Capability)
if (moduleInfo is PlatformModuleInfo) return listOf(this)
val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList()
return moduleSourceInfo.expectedBy.mapNotNull { it.toDescriptor() }
}
fun Module.toDescriptor() = (productionSourceInfo ?: testSourceInfo)?.toDescriptor()
fun ModuleSourceInfo.toDescriptor() = KotlinCacheService.getInstance(module.project)
.getResolutionFacadeByModuleInfo(this, platform)?.moduleDescriptor
fun PsiElement.getPlatformModuleInfo(desiredPlatform: TargetPlatform): PlatformModuleInfo? {
assert(!desiredPlatform.isCommon()) { "Platform module cannot have Common platform" }
val moduleInfo = this.moduleInfoOrNull as? ModuleSourceInfo ?: return null
return doGetPlatformModuleInfo(moduleInfo, desiredPlatform)
}
fun getPlatformModuleInfo(moduleInfo: ModuleSourceInfo, desiredPlatform: TargetPlatform): PlatformModuleInfo? {
assert(!desiredPlatform.isCommon()) { "Platform module cannot have Common platform" }
return doGetPlatformModuleInfo(moduleInfo, desiredPlatform)
}
private fun doGetPlatformModuleInfo(moduleInfo: ModuleSourceInfo, desiredPlatform: TargetPlatform): PlatformModuleInfo? {
val platform = moduleInfo.platform
return when {
platform.isCommon() -> {
val correspondingImplementingModule = moduleInfo.module.implementingModules
.map { module ->
val sourceRootType = moduleInfo.kotlinSourceRootType ?: return@map null
module.getModuleInfo(sourceRootType)
}
.firstOrNull { it?.platform == desiredPlatform } ?: return null
PlatformModuleInfo(correspondingImplementingModule, correspondingImplementingModule.expectedBy)
}
platform == desiredPlatform -> {
val expectedBy = moduleInfo.expectedBy.takeIf { it.isNotEmpty() } ?: return null
PlatformModuleInfo(moduleInfo, expectedBy)
}
else -> null
}
} | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/project/multiplatformUtil.kt | 3113433039 |
package com.intellij.cce.core
class CodeToken(val text: String,
val offset: Int,
val length: Int,
val properties: TokenProperties = TokenProperties.UNKNOWN
) | plugins/evaluation-plugin/core/src/com/intellij/cce/core/CodeToken.kt | 2315773161 |
// 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.slicer
import com.intellij.slicer.SliceUsage
import com.intellij.util.Processor
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
data class KotlinSliceAnalysisMode(val behaviourStack: List<Behaviour>, val inlineCallStack: List<InlineFunctionCall>) {
fun withBehaviour(behaviour: Behaviour) = copy(behaviourStack = behaviourStack + behaviour)
fun withInlineFunctionCall(
callElement: KtElement,
function: KtNamedFunction
) = copy(inlineCallStack = inlineCallStack + InlineFunctionCall(callElement, function))
fun dropBehaviour(): KotlinSliceAnalysisMode {
check(behaviourStack.isNotEmpty())
return copy(behaviourStack = behaviourStack.dropLast(1))
}
fun popInlineFunctionCall(function: KtNamedFunction): Pair<KotlinSliceAnalysisMode?, KtElement?> {
val last = inlineCallStack.lastOrNull()
if (last?.function != function) return null to null
val newMode = copy(inlineCallStack = inlineCallStack.dropLast(1))
return newMode to last.callElement
}
val currentBehaviour: Behaviour?
get() = behaviourStack.lastOrNull()
interface Behaviour {
fun processUsages(
element: KtElement,
parent: KotlinSliceUsage,
uniqueProcessor: Processor<in SliceUsage>
)
val slicePresentationPrefix: String
val testPresentationPrefix: String
override fun equals(other: Any?): Boolean
override fun hashCode(): Int
}
class InlineFunctionCall(callElement: KtElement, function: KtNamedFunction) {
private val callElementPointer = callElement.createSmartPointer()
private val functionPointer = function.createSmartPointer()
val callElement: KtElement?
get() = callElementPointer.element
val function: KtNamedFunction?
get() = functionPointer.element
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is InlineFunctionCall && other.callElement == callElement && other.function == function
}
override fun hashCode() = 0
}
companion object {
val Default = KotlinSliceAnalysisMode(emptyList(), emptyList())
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceAnalysisMode.kt | 2261268161 |
package org.jetbrains.completion.full.line.python.features
import org.jetbrains.completion.full.line.platform.FullLineLookupElement
import org.jetbrains.completion.full.line.python.tests.FullLinePythonCompletionTestCase
class TransformedSuggestions : FullLinePythonCompletionTestCase() {
private val context = "\n<caret>"
fun `test empty lookup shown`() {
myFixture.configureByText("fragment.py", context)
clearFLCompletionCache()
myFixture.completeBasic()
assertNotNull(myFixture.lookup)
assertTrue(myFixture.fullLineElement().isEmpty())
}
fun `test not showing BOS`() = doTestNotShowing("BOS", "<BOS", "<BOS>")
fun `test not showing nonsense`() = doTestNotShowing("-+|", "():", "!", ".", "()")
fun `test not showing empty`() = doTestNotShowing(" ", "\t\n", "")
fun `test not showing repetition`() = doTestNotShowing(
"model.model.model.",
"varvarvarvar",
"000",
)
fun `test transformed uncompleted var`() = doTestTransform("not completed_one_", "not")
fun `test transformed uncompleted fun`() = doTestTransform("a = my.func.not_completed_one_", "a = my.func.")
// Test that check if suggestions are not filtered/transformed
fun `test showing equations`() = doTestKeepShowing("1 + 2", "1+2", "1, 2", ", 1):")
fun `test showing correct samples`() = doTestKeepShowing("a", "from i import j", "a = b", "def a(1, 2, 'str'):")
private fun doTestTransform(initial: String, expected: String) {
myFixture.configureByText("fragment.py", context)
clearFLCompletionCache()
myFixture.completeFullLine(initial)
assertNotNull(myFixture.lookup)
val elements = myFixture.lookupElements!!.filterIsInstance<FullLineLookupElement>().map { it.lookupString }
assertContainsElements(elements, expected)
assertDoesntContain(elements, initial)
}
private fun doTestNotShowing(vararg suggestions: String) = doTestFilter(emptyList(), *suggestions)
private fun doTestKeepShowing(vararg suggestions: String) = doTestFilter(suggestions.toList(), *suggestions)
private fun doTestFilter(expected: List<String>, vararg suggestions: String) {
myFixture.configureByText("fragment.py", context)
clearFLCompletionCache()
myFixture.completeFullLine(*suggestions)
assertNotNull(myFixture.lookup)
assertEquals(
expected.sorted(),
myFixture.lookupElements!!.filterIsInstance<FullLineLookupElement>().map { it.lookupString }.sorted()
)
}
}
| plugins/full-line/python/test/org/jetbrains/completion/full/line/python/features/TransformedSuggestions.kt | 1045282461 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.impl
import com.intellij.ProjectTopics
import com.intellij.configurationStore.*
import com.intellij.execution.*
import com.intellij.execution.configurations.*
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.options.SchemeManager
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.IndexNotReadyException
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.UnknownFeaturesCollector
import com.intellij.openapi.util.ClearableLazyValue
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.project.isDirectoryBased
import com.intellij.util.*
import com.intellij.util.containers.*
import com.intellij.util.text.UniqueNameGenerator
import gnu.trove.THashMap
import org.jdom.Element
import org.jetbrains.annotations.TestOnly
import java.util.*
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.ReentrantReadWriteLock
import javax.swing.Icon
import kotlin.concurrent.read
import kotlin.concurrent.write
private const val SELECTED_ATTR = "selected"
internal const val METHOD = "method"
private const val OPTION = "option"
private const val RECENT = "recent_temporary"
// open for Upsource (UpsourceRunManager overrides to disable loadState (empty impl))
@State(name = "RunManager", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE, useSaveThreshold = ThreeState.NO))])
open class RunManagerImpl(internal val project: Project) : RunManagerEx(), PersistentStateComponent<Element>, Disposable {
companion object {
const val CONFIGURATION: String = "configuration"
const val NAME_ATTR: String = "name"
internal val LOG = logger<RunManagerImpl>()
@JvmStatic
fun getInstanceImpl(project: Project): RunManagerImpl = RunManager.getInstance(project) as RunManagerImpl
@JvmStatic
fun canRunConfiguration(environment: ExecutionEnvironment): Boolean {
return environment.runnerAndConfigurationSettings?.let { canRunConfiguration(it, environment.executor) } ?: false
}
@JvmStatic
fun canRunConfiguration(configuration: RunnerAndConfigurationSettings, executor: Executor): Boolean {
try {
configuration.checkSettings(executor)
}
catch (ignored: IndexNotReadyException) {
return false
}
catch (ignored: RuntimeConfigurationError) {
return false
}
catch (ignored: RuntimeConfigurationException) {
}
return true
}
}
private val lock = ReentrantReadWriteLock()
private val idToType = LinkedHashMap<String, ConfigurationType>()
@Suppress("LeakingThis")
private val listManager = RunConfigurationListManagerHelper(this)
private val templateIdToConfiguration = THashMap<String, RunnerAndConfigurationSettingsImpl>()
// template configurations are not included here
private val idToSettings: LinkedHashMap<String, RunnerAndConfigurationSettings>
get() = listManager.idToSettings
// When readExternal not all configuration may be loaded, so we need to remember the selected configuration
// so that when it is eventually loaded, we can mark is as a selected.
private var selectedConfigurationId: String? = null
private val iconCache = TimedIconCache()
private val _config by lazy { RunManagerConfig(PropertiesComponent.getInstance(project)) }
private val recentlyUsedTemporaries = ArrayList<RunnerAndConfigurationSettings>()
// templates should be first because to migrate old before run list to effective, we need to get template before run task
private val workspaceSchemeManagerProvider = SchemeManagerIprProvider("configuration", Comparator { n1, n2 ->
val w1 = getNameWeight(n1)
val w2 = getNameWeight(n2)
if (w1 == w2) {
n1.compareTo(n2)
}
else {
w1 - w2
}
})
internal val schemeManagerIprProvider = if (project.isDirectoryBased) null else SchemeManagerIprProvider("configuration")
@Suppress("LeakingThis")
private val templateDifferenceHelper = TemplateDifferenceHelper(this)
@Suppress("LeakingThis")
private val workspaceSchemeManager = SchemeManagerFactory.getInstance(project).create("workspace",
RunConfigurationSchemeManager(this, templateDifferenceHelper,
isShared = false,
isWrapSchemeIntoComponentElement = false),
streamProvider = workspaceSchemeManagerProvider,
isAutoSave = false)
@Suppress("LeakingThis")
private var projectSchemeManager = SchemeManagerFactory.getInstance(project).create("runConfigurations",
RunConfigurationSchemeManager(this, templateDifferenceHelper,
isShared = true,
isWrapSchemeIntoComponentElement = schemeManagerIprProvider == null),
schemeNameToFileName = OLD_NAME_CONVERTER,
streamProvider = schemeManagerIprProvider)
private val isFirstLoadState = AtomicBoolean(true)
private val stringIdToBeforeRunProvider = object : ClearableLazyValue<ConcurrentMap<String, BeforeRunTaskProvider<*>>>() {
override fun compute(): ConcurrentMap<String, BeforeRunTaskProvider<*>> {
val result = ContainerUtil.newConcurrentMap<String, BeforeRunTaskProvider<*>>()
for (provider in BeforeRunTaskProvider.EXTENSION_POINT_NAME.getExtensions(project)) {
result.put(provider.id.toString(), provider)
}
return result
}
}
internal val eventPublisher: RunManagerListener
get() = project.messageBus.syncPublisher(RunManagerListener.TOPIC)
init {
initializeConfigurationTypes(ConfigurationType.CONFIGURATION_TYPE_EP.extensions)
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
selectedConfiguration?.let {
iconCache.remove(it.uniqueID)
}
}
})
}
// separate method needed for tests
fun initializeConfigurationTypes(factories: Array<ConfigurationType>) {
val types = factories.toMutableList()
types.sortBy { it.displayName }
types.add(UnknownConfigurationType.INSTANCE)
lock.write {
idToType.clear()
for (type in types) {
idToType.put(type.id, type)
}
}
}
override fun createConfiguration(name: String, factory: ConfigurationFactory): RunnerAndConfigurationSettings {
val template = getConfigurationTemplate(factory)
return createConfiguration(factory.createConfiguration(name, template.configuration), template)
}
override fun createConfiguration(runConfiguration: RunConfiguration, factory: ConfigurationFactory): RunnerAndConfigurationSettings {
return createConfiguration(runConfiguration, getConfigurationTemplate(factory))
}
private fun createConfiguration(configuration: RunConfiguration, template: RunnerAndConfigurationSettingsImpl): RunnerAndConfigurationSettings {
val settings = RunnerAndConfigurationSettingsImpl(this, configuration)
settings.importRunnerAndConfigurationSettings(template)
if (!settings.isShared) {
shareConfiguration(settings, template.isShared)
}
configuration.beforeRunTasks = template.configuration.beforeRunTasks
return settings
}
override fun dispose() {
lock.write {
iconCache.clear()
templateIdToConfiguration.clear()
}
}
override fun getConfig(): RunManagerConfig = _config
override val configurationFactories: Array<ConfigurationType> by lazy { idToType.values.toTypedArray() }
override val configurationFactoriesWithoutUnknown: List<ConfigurationType>
get() = idToType.values.filterSmart { it.isManaged }
/**
* Template configuration is not included
*/
override fun getConfigurationsList(type: ConfigurationType): List<RunConfiguration> {
var result: MutableList<RunConfiguration>? = null
for (settings in allSettings) {
val configuration = settings.configuration
if (type.id == configuration.type.id) {
if (result == null) {
result = SmartList<RunConfiguration>()
}
result.add(configuration)
}
}
return result ?: emptyList()
}
override val allConfigurationsList: List<RunConfiguration>
get() = allSettings.mapSmart { it.configuration }
fun getSettings(configuration: RunConfiguration): RunnerAndConfigurationSettingsImpl? = allSettings.firstOrNull { it.configuration === configuration } as? RunnerAndConfigurationSettingsImpl
override fun getConfigurationSettingsList(type: ConfigurationType): List<RunnerAndConfigurationSettings> = allSettings.filterSmart { it.type.id == type.id }
override fun getStructure(type: ConfigurationType): Map<String, List<RunnerAndConfigurationSettings>> {
val result = LinkedHashMap<String?, MutableList<RunnerAndConfigurationSettings>>()
val typeList = SmartList<RunnerAndConfigurationSettings>()
val settings = getConfigurationSettingsList(type)
for (setting in settings) {
val folderName = setting.folderName
if (folderName == null) {
typeList.add(setting)
}
else {
result.getOrPut(folderName) { SmartList() }.add(setting)
}
}
result.put(null, Collections.unmodifiableList(typeList))
return Collections.unmodifiableMap(result)
}
override fun getConfigurationTemplate(factory: ConfigurationFactory): RunnerAndConfigurationSettingsImpl {
val key = "${factory.type.id}.${factory.id}"
return lock.read { templateIdToConfiguration.get(key) } ?: lock.write {
templateIdToConfiguration.getOrPut(key) {
val template = createTemplateSettings(factory)
workspaceSchemeManager.addScheme(template)
template
}
}
}
internal fun createTemplateSettings(factory: ConfigurationFactory): RunnerAndConfigurationSettingsImpl {
val configuration = factory.createTemplateConfiguration(project, this)
val template = RunnerAndConfigurationSettingsImpl(this, configuration,
isTemplate = true,
isSingleton = factory.isConfigurationSingletonByDefault)
if (configuration is UnknownRunConfiguration) {
configuration.isDoNotStore = true
}
configuration.beforeRunTasks = getHardcodedBeforeRunTasks(configuration, factory)
return template
}
override fun addConfiguration(settings: RunnerAndConfigurationSettings) {
doAddConfiguration(settings, isCheckRecentsLimit = true)
}
private fun doAddConfiguration(settings: RunnerAndConfigurationSettings, isCheckRecentsLimit: Boolean) {
val newId = settings.uniqueID
var existingId: String? = null
lock.write {
listManager.immutableSortedSettingsList = null
// https://youtrack.jetbrains.com/issue/IDEA-112821
// we should check by instance, not by id (todo is it still relevant?)
existingId = if (idToSettings.get(newId) === settings) newId else findExistingConfigurationId(settings)
existingId?.let {
if (newId != it) {
idToSettings.remove(it)
if (selectedConfigurationId == it) {
selectedConfigurationId = newId
}
}
}
idToSettings.put(newId, settings)
if (existingId == null) {
refreshUsagesList(settings)
}
else {
(if (settings.isShared) workspaceSchemeManager else projectSchemeManager).removeScheme(
settings as RunnerAndConfigurationSettingsImpl)
}
// scheme level can be changed (workspace -> project), so, ensure that scheme is added to corresponding scheme manager (if exists, doesn't harm)
settings.schemeManager?.addScheme(settings as RunnerAndConfigurationSettingsImpl)
}
if (existingId == null) {
if (isCheckRecentsLimit && settings.isTemporary) {
checkRecentsLimit()
}
eventPublisher.runConfigurationAdded(settings)
}
else {
eventPublisher.runConfigurationChanged(settings, existingId)
}
}
private val RunnerAndConfigurationSettings.schemeManager: SchemeManager<RunnerAndConfigurationSettingsImpl>?
get() = if (isShared) projectSchemeManager else workspaceSchemeManager
override fun refreshUsagesList(profile: RunProfile) {
if (profile !is RunConfiguration) {
return
}
getSettings(profile)?.let {
refreshUsagesList(it)
}
}
private fun refreshUsagesList(settings: RunnerAndConfigurationSettings) {
if (settings.isTemporary) {
lock.write {
recentlyUsedTemporaries.remove(settings)
recentlyUsedTemporaries.add(0, settings)
trimUsagesListToLimit()
}
}
}
// call only under write lock
private fun trimUsagesListToLimit() {
while (recentlyUsedTemporaries.size > config.recentsLimit) {
recentlyUsedTemporaries.removeAt(recentlyUsedTemporaries.size - 1)
}
}
fun checkRecentsLimit() {
var removed: MutableList<RunnerAndConfigurationSettings>? = null
lock.write {
trimUsagesListToLimit()
var excess = idToSettings.values.count { it.isTemporary } - config.recentsLimit
if (excess <= 0) {
return
}
for (settings in idToSettings.values) {
if (settings.isTemporary && !recentlyUsedTemporaries.contains(settings)) {
if (removed == null) {
removed = SmartList<RunnerAndConfigurationSettings>()
}
removed!!.add(settings)
if (--excess <= 0) {
break
}
}
}
}
removed?.let { removeConfigurations(it) }
}
fun setOrder(comparator: Comparator<RunnerAndConfigurationSettings>) {
lock.write {
listManager.setOrder(comparator)
}
}
override var selectedConfiguration: RunnerAndConfigurationSettings?
get() = selectedConfigurationId?.let { lock.read { idToSettings.get(it) } }
set(value) {
if (value?.uniqueID == selectedConfigurationId) {
return
}
selectedConfigurationId = value?.uniqueID
eventPublisher.runConfigurationSelected()
}
fun requestSort() {
lock.write {
listManager.requestSort()
allSettings
}
}
override val allSettings: List<RunnerAndConfigurationSettings>
get() {
listManager.immutableSortedSettingsList?.let {
return it
}
lock.write {
return listManager.buildImmutableSortedSettingsList()
}
}
override fun getState(): Element {
if (!isFirstLoadState.get()) {
lock.read {
val list = idToSettings.values.toList()
list.forEachManaged {
listManager.checkIfDependenciesAreStable(it.configuration, list)
}
}
}
val element = Element("state")
workspaceSchemeManager.save()
lock.read {
workspaceSchemeManagerProvider.writeState(element)
if (idToSettings.size > 1) {
selectedConfiguration?.let {
element.setAttribute(SELECTED_ATTR, it.uniqueID)
}
val listElement = Element("list")
idToSettings.values.forEachManaged {
listElement.addContent(Element("item").setAttribute("itemvalue", it.uniqueID))
}
if (!listElement.isEmpty()) {
element.addContent(listElement)
}
}
val recentList = SmartList<String>()
recentlyUsedTemporaries.forEachManaged {
recentList.add(it.uniqueID)
}
if (!recentList.isEmpty()) {
val recent = Element(RECENT)
element.addContent(recent)
val listElement = recent.element("list")
for (id in recentList) {
listElement.addContent(Element("item").setAttribute("itemvalue", id))
}
}
}
return element
}
fun writeContext(element: Element) {
for (setting in allSettings) {
if (setting.isTemporary) {
element.addContent((setting as RunnerAndConfigurationSettingsImpl).writeScheme())
}
}
selectedConfiguration?.let {
element.setAttribute(SELECTED_ATTR, it.uniqueID)
}
}
fun writeConfigurations(parentNode: Element, settings: Collection<RunnerAndConfigurationSettings>) {
settings.forEach { parentNode.addContent((it as RunnerAndConfigurationSettingsImpl).writeScheme()) }
}
internal fun writeBeforeRunTasks(configuration: RunConfiguration): Element? {
val tasks = configuration.beforeRunTasks
val methodElement = Element(METHOD)
methodElement.attribute("v", "2")
for (task in tasks) {
val child = Element(OPTION)
child.setAttribute(NAME_ATTR, task.providerId.toString())
if (task is PersistentStateComponent<*>) {
if (!task.isEnabled) {
child.setAttribute("enabled", "false")
}
task.serializeStateInto(child)
}
else {
@Suppress("DEPRECATION")
task.writeExternal(child)
}
methodElement.addContent(child)
}
return methodElement
}
@Suppress("unused")
/**
* used by MPS. Do not use if not approved.
*/
fun reloadSchemes() {
lock.write {
// not really required, but hot swap friendly - 1) factory is used a key, 2) developer can change some defaults.
templateDifferenceHelper.clearCache()
templateIdToConfiguration.clear()
listManager.idToSettings.clear()
recentlyUsedTemporaries.clear()
stringIdToBeforeRunProvider.drop()
}
workspaceSchemeManager.reload()
projectSchemeManager.reload()
}
override fun noStateLoaded() {
isFirstLoadState.set(false)
loadSharedRunConfigurations()
runConfigurationFirstLoaded()
eventPublisher.stateLoaded()
}
override fun loadState(parentNode: Element) {
val oldSelectedConfigurationId: String?
val isFirstLoadState = isFirstLoadState.compareAndSet(true, false)
if (isFirstLoadState) {
oldSelectedConfigurationId = null
}
else {
oldSelectedConfigurationId = selectedConfigurationId
clear(false)
}
val nameGenerator = UniqueNameGenerator()
workspaceSchemeManagerProvider.load(parentNode) {
var schemeKey: String? = it.getAttributeValue("name")
if (schemeKey == "<template>" || schemeKey == null) {
// scheme name must be unique
it.getAttributeValue("type")?.let {
if (schemeKey == null) {
schemeKey = "<template>"
}
schemeKey += ", type: ${it}"
}
}
else if (schemeKey != null) {
val typeId = it.getAttributeValue("type")
if (typeId == null) {
LOG.warn("typeId is null for '${schemeKey}'")
}
schemeKey = "${typeId ?: "unknown"}-${schemeKey}"
}
// in case if broken configuration, do not fail, just generate name
if (schemeKey == null) {
schemeKey = nameGenerator.generateUniqueName("Unnamed")
}
else {
schemeKey = "${schemeKey!!}, factoryName: ${it.getAttributeValue("factoryName", "")}"
nameGenerator.addExistingName(schemeKey!!)
}
schemeKey!!
}
workspaceSchemeManager.reload()
lock.write {
recentlyUsedTemporaries.clear()
val recentListElement = parentNode.getChild(RECENT)?.getChild("list")
if (recentListElement != null) {
for (id in recentListElement.getChildren("item").mapNotNull { it.getAttributeValue("itemvalue") }) {
idToSettings.get(id)?.let {
recentlyUsedTemporaries.add(it)
}
}
}
selectedConfigurationId = parentNode.getAttributeValue(SELECTED_ATTR)
}
if (isFirstLoadState) {
loadSharedRunConfigurations()
}
// apply order after loading shared RC
lock.write {
parentNode.getChild("list")?.let { listElement ->
listManager.setCustomOrder(listElement.getChildren("item").mapNotNull { it.getAttributeValue("itemvalue") })
}
listManager.immutableSortedSettingsList = null
}
runConfigurationFirstLoaded()
fireBeforeRunTasksUpdated()
if (!isFirstLoadState && oldSelectedConfigurationId != null && oldSelectedConfigurationId != selectedConfigurationId) {
eventPublisher.runConfigurationSelected()
}
eventPublisher.stateLoaded()
}
private fun loadSharedRunConfigurations() {
if (schemeManagerIprProvider == null) {
projectSchemeManager.loadSchemes()
return
}
else {
project.service<IprRunManagerImpl>().lastLoadedState.getAndSet(null)?.let { data ->
schemeManagerIprProvider.load(data)
projectSchemeManager.reload()
}
}
}
private fun runConfigurationFirstLoaded() {
requestSort()
if (selectedConfiguration == null) {
selectedConfiguration = allSettings.firstOrNull { it.type !is UnknownRunConfiguration }
}
}
fun readContext(parentNode: Element) {
var selectedConfigurationId = parentNode.getAttributeValue(SELECTED_ATTR)
for (element in parentNode.children) {
val config = loadConfiguration(element, false)
if (selectedConfigurationId == null && element.getAttributeBooleanValue(SELECTED_ATTR)) {
selectedConfigurationId = config.uniqueID
}
}
this.selectedConfigurationId = selectedConfigurationId
eventPublisher.runConfigurationSelected()
}
override fun hasSettings(settings: RunnerAndConfigurationSettings): Boolean = lock.read { idToSettings.get(settings.uniqueID) == settings }
private fun findExistingConfigurationId(settings: RunnerAndConfigurationSettings): String? {
for ((key, value) in idToSettings) {
if (value === settings) {
return key
}
}
return null
}
// used by MPS, don't delete
fun clearAll() {
clear(true)
idToType.clear()
initializeConfigurationTypes(emptyArray())
}
private fun clear(allConfigurations: Boolean) {
val removedConfigurations = lock.write {
listManager.immutableSortedSettingsList = null
val configurations = if (allConfigurations) {
val configurations = idToSettings.values.toList()
idToSettings.clear()
selectedConfigurationId = null
configurations
}
else {
val configurations = SmartList<RunnerAndConfigurationSettings>()
val iterator = idToSettings.values.iterator()
for (configuration in iterator) {
if (configuration.isTemporary || !configuration.isShared) {
iterator.remove()
configurations.add(configuration)
}
}
selectedConfigurationId?.let {
if (idToSettings.containsKey(it)) {
selectedConfigurationId = null
}
}
configurations
}
templateIdToConfiguration.clear()
recentlyUsedTemporaries.clear()
configurations
}
iconCache.clear()
val eventPublisher = eventPublisher
removedConfigurations.forEach { eventPublisher.runConfigurationRemoved(it) }
}
fun loadConfiguration(element: Element, isShared: Boolean): RunnerAndConfigurationSettings {
val settings = RunnerAndConfigurationSettingsImpl(this)
LOG.runAndLogException {
settings.readExternal(element, isShared)
}
addConfiguration(element, settings)
return settings
}
internal fun addConfiguration(element: Element, settings: RunnerAndConfigurationSettingsImpl, isCheckRecentsLimit: Boolean = true) {
if (settings.isTemplate) {
val factory = settings.factory
lock.write {
templateIdToConfiguration.put("${factory.type.id}.${factory.id}", settings)
}
}
else {
doAddConfiguration(settings, isCheckRecentsLimit)
if (element.getAttributeBooleanValue(SELECTED_ATTR)) {
// to support old style
selectedConfiguration = settings
}
}
}
internal fun readBeforeRunTasks(element: Element?, settings: RunnerAndConfigurationSettings, configuration: RunConfiguration) {
var result: MutableList<BeforeRunTask<*>>? = null
if (element != null) {
for (methodElement in element.getChildren(OPTION)) {
val key = methodElement.getAttributeValue(NAME_ATTR)
val provider = stringIdToBeforeRunProvider.value.getOrPut(key) { UnknownBeforeRunTaskProvider(key) }
val beforeRunTask = provider.createTask(configuration) ?: continue
if (beforeRunTask is PersistentStateComponent<*>) {
// for PersistentStateComponent we don't write default value for enabled, so, set it to true explicitly
beforeRunTask.isEnabled = true
beforeRunTask.deserializeAndLoadState(methodElement)
}
else {
@Suppress("DEPRECATION")
beforeRunTask.readExternal(methodElement)
}
if (result == null) {
result = SmartList()
}
result.add(beforeRunTask)
}
}
if (element?.getAttributeValue("v") == null) {
if (settings.isTemplate) {
if (result.isNullOrEmpty()) {
configuration.beforeRunTasks = getHardcodedBeforeRunTasks(configuration, configuration.factory!!)
return
}
}
else {
configuration.beforeRunTasks = getEffectiveBeforeRunTaskList(result ?: emptyList(), getConfigurationTemplate(configuration.factory!!).configuration.beforeRunTasks, true, false)
return
}
}
configuration.beforeRunTasks = result ?: emptyList()
}
override fun getConfigurationType(typeName: String): ConfigurationType? = idToType.get(typeName)
@JvmOverloads
fun getFactory(typeId: String?, factoryId: String?, checkUnknown: Boolean = false): ConfigurationFactory? {
val type = idToType.get(typeId)
if (type == null) {
if (checkUnknown && typeId != null) {
UnknownFeaturesCollector.getInstance(project).registerUnknownRunConfiguration(typeId, factoryId)
}
return UnknownConfigurationType.getFactory()
}
if (type is UnknownConfigurationType) {
return type.configurationFactories.firstOrNull()
}
return type.configurationFactories.firstOrNull {
factoryId == null || it.id == factoryId
}
}
override fun setTemporaryConfiguration(tempConfiguration: RunnerAndConfigurationSettings?) {
if (tempConfiguration == null) {
return
}
tempConfiguration.isTemporary = true
addConfiguration(tempConfiguration)
if (Registry.`is`("select.run.configuration.from.context")) {
selectedConfiguration = tempConfiguration
}
}
override val tempConfigurationsList: List<RunnerAndConfigurationSettings>
get() = allSettings.filterSmart { it.isTemporary }
override fun makeStable(settings: RunnerAndConfigurationSettings) {
settings.isTemporary = false
doMakeStable(settings)
fireRunConfigurationChanged(settings)
}
private fun doMakeStable(settings: RunnerAndConfigurationSettings) {
lock.write {
recentlyUsedTemporaries.remove(settings)
listManager.afterMakeStable()
}
}
override fun <T : BeforeRunTask<*>> getBeforeRunTasks(taskProviderId: Key<T>): List<T> {
val tasks = SmartList<T>()
val checkedTemplates = SmartList<RunnerAndConfigurationSettings>()
lock.read {
for (settings in allSettings) {
val configuration = settings.configuration
for (task in getBeforeRunTasks(configuration)) {
if (task.isEnabled && task.providerId === taskProviderId) {
@Suppress("UNCHECKED_CAST")
tasks.add(task as T)
}
else {
val template = getConfigurationTemplate(configuration.factory!!)
if (!checkedTemplates.contains(template)) {
checkedTemplates.add(template)
for (templateTask in getBeforeRunTasks(template.configuration)) {
if (templateTask.isEnabled && templateTask.providerId === taskProviderId) {
@Suppress("UNCHECKED_CAST")
tasks.add(templateTask as T)
}
}
}
}
}
}
}
return tasks
}
override fun getConfigurationIcon(settings: RunnerAndConfigurationSettings, withLiveIndicator: Boolean): Icon {
val uniqueId = settings.uniqueID
if (selectedConfiguration?.uniqueID == uniqueId) {
iconCache.checkValidity(uniqueId)
}
var icon = iconCache.get(uniqueId, settings, project)
if (withLiveIndicator) {
val runningDescriptors = ExecutionManagerImpl.getInstance(project).getRunningDescriptors { it === settings }
when {
runningDescriptors.size == 1 -> icon = ExecutionUtil.getLiveIndicator(icon)
runningDescriptors.size > 1 -> icon = IconUtil.addText(icon, runningDescriptors.size.toString())
}
}
return icon
}
fun getConfigurationById(id: String): RunnerAndConfigurationSettings? = lock.read { idToSettings.get(id) }
override fun findConfigurationByName(name: String?): RunnerAndConfigurationSettings? {
if (name == null) {
return null
}
return allSettings.firstOrNull { it.name == name }
}
override fun findSettings(configuration: RunConfiguration): RunnerAndConfigurationSettings? {
return allSettings.firstOrNull { it.configuration === configuration } ?: findConfigurationByName(configuration.name)
}
override fun <T : BeforeRunTask<*>> getBeforeRunTasks(settings: RunConfiguration, taskProviderId: Key<T>): List<T> {
if (settings is WrappingRunConfiguration<*>) {
return getBeforeRunTasks(settings.peer, taskProviderId)
}
var result: MutableList<T>? = null
for (task in getBeforeRunTasks(settings)) {
if (task.providerId === taskProviderId) {
if (result == null) {
result = SmartList<T>()
}
@Suppress("UNCHECKED_CAST")
result.add(task as T)
}
}
return result ?: emptyList()
}
override fun getBeforeRunTasks(configuration: RunConfiguration): List<BeforeRunTask<*>> {
return when (configuration) {
is WrappingRunConfiguration<*> -> getBeforeRunTasks(configuration.peer)
else -> configuration.beforeRunTasks
}
}
fun shareConfiguration(settings: RunnerAndConfigurationSettings, value: Boolean) {
if (settings.isShared == value) {
return
}
if (value && settings.isTemporary) {
doMakeStable(settings)
}
settings.isShared = value
fireRunConfigurationChanged(settings)
}
override fun setBeforeRunTasks(configuration: RunConfiguration, tasks: List<BeforeRunTask<*>>, addEnabledTemplateTasksIfAbsent: Boolean) {
setBeforeRunTasks(configuration, tasks)
}
override fun setBeforeRunTasks(configuration: RunConfiguration, tasks: List<BeforeRunTask<*>>) {
if (configuration is UnknownRunConfiguration) {
return
}
configuration.beforeRunTasks = tasks
fireBeforeRunTasksUpdated()
}
fun fireBeginUpdate() {
eventPublisher.beginUpdate()
}
fun fireEndUpdate() {
eventPublisher.endUpdate()
}
fun fireRunConfigurationChanged(settings: RunnerAndConfigurationSettings) {
eventPublisher.runConfigurationChanged(settings, null)
}
@Suppress("OverridingDeprecatedMember")
override fun addRunManagerListener(listener: RunManagerListener) {
project.messageBus.connect().subscribe(RunManagerListener.TOPIC, listener)
}
fun fireBeforeRunTasksUpdated() {
eventPublisher.beforeRunTasksChanged()
}
override fun removeConfiguration(settings: RunnerAndConfigurationSettings?) {
if (settings != null) {
removeConfigurations(listOf(settings))
}
}
fun removeConfigurations(toRemove: Collection<RunnerAndConfigurationSettings>) {
if (toRemove.isEmpty()) {
return
}
val changedSettings = SmartList<RunnerAndConfigurationSettings>()
val removed = SmartList<RunnerAndConfigurationSettings>()
var selectedConfigurationWasRemoved = false
lock.write {
listManager.immutableSortedSettingsList = null
val iterator = idToSettings.values.iterator()
for (settings in iterator) {
if (toRemove.contains(settings)) {
if (selectedConfigurationId == settings.uniqueID) {
selectedConfigurationWasRemoved = true
}
iterator.remove()
settings.schemeManager?.removeScheme(settings as RunnerAndConfigurationSettingsImpl)
recentlyUsedTemporaries.remove(settings)
removed.add(settings)
iconCache.remove(settings.uniqueID)
}
else {
var isChanged = false
val otherConfiguration = settings.configuration
val newList = otherConfiguration.beforeRunTasks.nullize()?.toMutableSmartList() ?: continue
val beforeRunTaskIterator = newList.iterator()
for (task in beforeRunTaskIterator) {
if (task is RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask && toRemove.firstOrNull {
task.isMySettings(it)
} != null) {
beforeRunTaskIterator.remove()
isChanged = true
changedSettings.add(settings)
}
}
if (isChanged) {
otherConfiguration.beforeRunTasks = newList
}
}
}
}
if (selectedConfigurationWasRemoved) {
selectedConfiguration = null
}
removed.forEach { eventPublisher.runConfigurationRemoved(it) }
changedSettings.forEach { eventPublisher.runConfigurationChanged(it, null) }
}
@TestOnly
fun getTemplateIdToConfiguration(): Map<String, RunnerAndConfigurationSettingsImpl> {
if (!ApplicationManager.getApplication().isUnitTestMode) {
throw IllegalStateException("test only")
}
return templateIdToConfiguration
}
}
@State(name = "ProjectRunConfigurationManager")
internal class IprRunManagerImpl(private val project: Project) : PersistentStateComponent<Element> {
val lastLoadedState = AtomicReference<Element>()
override fun getState(): Element? {
val iprProvider = RunManagerImpl.getInstanceImpl(project).schemeManagerIprProvider ?: return null
val result = Element("state")
iprProvider.writeState(result)
return result
}
override fun loadState(state: Element) {
lastLoadedState.set(state)
}
}
private fun getNameWeight(n1: String) = if (n1.startsWith("<template> of ") || n1.startsWith("_template__ ")) 0 else 1
private inline fun Collection<RunnerAndConfigurationSettings>.forEachManaged(handler: (settings: RunnerAndConfigurationSettings) -> Unit) {
for (settings in this) {
if (settings.type.isManaged) {
handler(settings)
}
}
}
fun getBeforeRunTasks(configuration: RunConfiguration): List<BeforeRunTask<*>> {
return when (configuration) {
is WrappingRunConfiguration<*> -> getBeforeRunTasks(configuration.peer)
else -> configuration.beforeRunTasks
}
} | platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.kt | 2055371815 |
package org.thoughtcrime.securesms.stories.viewer.reply
import android.view.View
interface BottomSheetBehaviorDelegate {
fun onSlide(bottomSheet: View)
}
| app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/BottomSheetBehaviorDelegate.kt | 1574038270 |
// 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.plugins.groovy.lang.resolve.delegatesTo
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiMethod
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import com.intellij.util.ArrayUtil
import groovy.lang.Closure
import org.jetbrains.plugins.groovy.lang.psi.api.EmptyGroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.getArgumentTypes
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
@JvmField val DELEGATES_TO_KEY: Key<String> = Key.create<String>("groovy.closure.delegatesTo.type")
@JvmField val DELEGATES_TO_STRATEGY_KEY: Key<Int> = Key.create<Int>("groovy.closure.delegatesTo.strategy")
val defaultDelegatesToInfo: DelegatesToInfo = DelegatesToInfo(null, Closure.OWNER_ONLY)
fun getDelegatesToInfo(closure: GrClosableBlock): DelegatesToInfo? = CachedValuesManager.getCachedValue(closure) {
Result.create(doGetDelegatesToInfo(closure), PsiModificationTracker.MODIFICATION_COUNT)
}
private fun doGetDelegatesToInfo(closure: GrClosableBlock): DelegatesToInfo? {
return GrDelegatesToProvider.EP_NAME.extensions.asSequence().mapNotNull { it.getDelegatesToInfo(closure) }.firstOrNull()
}
fun getContainingCall(closableBlock: GrClosableBlock): GrCall? {
val parent = closableBlock.parent
if (parent is GrCall && ArrayUtil.contains(closableBlock, *parent.closureArguments)) {
return parent
}
if (parent is GrArgumentList) {
val grandParent = parent.parent
return grandParent as? GrCall
}
return null
}
fun resolveActualCall(call: GrCall): GroovyResolveResult = when (call) {
is GrMethodCall -> CachedValuesManager.getCachedValue(call) {
Result.create(doResolveActualCall(call), PsiModificationTracker.MODIFICATION_COUNT)
}
else -> call.advancedResolve()
}
private fun doResolveActualCall(call: GrMethodCall): GroovyResolveResult {
val result = call.advancedResolve()
if (result.element is PsiMethod && !result.isInvokedOnProperty) return result
val expression = call.invokedExpression
val type = expression.type ?: return result
val calls = ResolveUtil.getMethodCandidates(type, "call", expression, *getArgumentTypes(expression, false))
return calls.singleOrNull() ?: EmptyGroovyResolveResult
}
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/delegatesTo/grDelegatesToUtil.kt | 822515310 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.impl
import com.intellij.execution.BeforeRunTask
import com.intellij.execution.BeforeRunTaskProvider
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.extensions.Extensions
import com.intellij.util.SmartList
import com.intellij.util.containers.filterSmartMutable
import com.intellij.util.containers.mapSmartSet
internal fun getEffectiveBeforeRunTaskList(ownTasks: List<BeforeRunTask<*>>, templateTasks: List<BeforeRunTask<*>>, ownIsOnlyEnabled: Boolean, isDisableTemplateTasks: Boolean): List<BeforeRunTask<*>> {
val idToSet = ownTasks.mapSmartSet { it.providerId }
val result = ownTasks.filterSmartMutable { !ownIsOnlyEnabled || it.isEnabled }
var i = 0
for (templateTask in templateTasks) {
if (templateTask.isEnabled && !idToSet.contains(templateTask.providerId)) {
val effectiveTemplateTask = if (isDisableTemplateTasks) {
val clone = templateTask.clone()
clone.isEnabled = false
clone
}
else {
templateTask
}
result.add(i, effectiveTemplateTask)
i++
}
}
return result
}
internal fun getHardcodedBeforeRunTasks(configuration: RunConfiguration, factory: ConfigurationFactory): List<BeforeRunTask<*>> {
var result: MutableList<BeforeRunTask<*>>? = null
for (provider in Extensions.getExtensions(BeforeRunTaskProvider.EXTENSION_POINT_NAME, configuration.project)) {
val task = provider.createTask(configuration) ?: continue
if (task.isEnabled) {
factory.configureBeforeRunTaskDefaults(provider.id, task)
if (task.isEnabled) {
if (result == null) {
result = SmartList<BeforeRunTask<*>>()
}
result.add(task)
}
}
}
return result.orEmpty()
} | platform/lang-impl/src/com/intellij/execution/impl/BeforeRunTaskHelper.kt | 3255536203 |
package lt.markmerkk.validators
import lt.markmerkk.TimeProviderTest
import lt.markmerkk.entities.TimeGap
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class TimeChangeValidatorShrinkFromEndTest {
private val timeProvider = TimeProviderTest()
private val validator = TimeChangeValidator
@Test
fun simple() {
// Assemble
val start = timeProvider.now()
.withHourOfDay(10)
.withMinuteOfHour(0)
val end = timeProvider.now()
.withHourOfDay(10)
.withMinuteOfHour(10)
// Act
val resultTimeGap = validator.shrinkFromEnd(
timeGap = TimeGap.from(
start,
end
),
minutes = 1
)
// Assert
assertThat(resultTimeGap.start).isEqualTo(
timeProvider.now()
.withHourOfDay(10)
.withMinuteOfHour(0))
assertThat(resultTimeGap.end).isEqualTo(
timeProvider.now()
.withHourOfDay(10)
.withMinuteOfHour(9))
}
@Test
fun shrinkMoreThanStart() {
// Assemble
val start = timeProvider.now()
.withHourOfDay(10)
.withMinuteOfHour(0)
val end = timeProvider.now()
.withHourOfDay(10)
.withMinuteOfHour(10)
// Act
val resultTimeGap = validator.shrinkFromEnd(
timeGap = TimeGap.from(
start,
end
),
minutes = 20
)
// Assert
assertThat(resultTimeGap.start).isEqualTo(
timeProvider.now()
.withHourOfDay(9)
.withMinuteOfHour(50))
assertThat(resultTimeGap.end).isEqualTo(
timeProvider.now()
.withHourOfDay(9)
.withMinuteOfHour(50))
}
} | components/src/test/java/lt/markmerkk/validators/TimeChangeValidatorShrinkFromEndTest.kt | 1430395977 |
package lt.markmerkk.events
/**
* Ticket filter has changed
*/
class EventTicketFilterChange : EventsBusEvent | models/src/main/java/lt/markmerkk/events/EventTicketFilterChange.kt | 2823046738 |
/*
* Copyright 2015-2020 the original author or authors.
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v2.0 which
* accompanies this distribution and is available at
*
* https://www.eclipse.org/legal/epl-v20.html
*/
package org.junit.jupiter.engine.kotlin
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class InstancePerMethodKotlinTestCase {
companion object {
@JvmField
val TEST_INSTANCES: MutableMap<Any, MutableMap<String, Int>> = LinkedHashMap()
@JvmStatic
@BeforeAll
fun beforeAll() {
increment(this, "beforeAll")
}
@JvmStatic
@AfterAll
fun afterAll() {
increment(this, "afterAll")
}
private fun increment(instance: Any, name: String) {
TEST_INSTANCES.computeIfAbsent(instance, { _ -> LinkedHashMap() })
.compute(name, { _, oldValue -> (oldValue ?: 0) + 1 })
}
}
@BeforeEach
fun beforeEach() {
increment(this, "beforeEach")
}
@AfterEach
fun afterEach() {
increment(this, "afterEach")
}
@Test
fun firstTest() {
increment(this, "test")
}
@Test
fun secondTest() {
increment(this, "test")
}
}
| junit-jupiter-engine/src/test/kotlin/org/junit/jupiter/engine/kotlin/InstancePerMethodKotlinTestCase.kt | 3741468195 |
/*
* Copyright 2016, 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.architecture.blueprints.todoapp.tasks
import android.content.Context
import android.support.v4.widget.SwipeRefreshLayout
import android.util.AttributeSet
import android.view.View
/**
* Extends [SwipeRefreshLayout] to support non-direct descendant scrolling views.
*
* [SwipeRefreshLayout] works as expected when a scroll view is a direct child: it triggers
* the refresh only when the view is on top. This class adds a way (@link #setScrollUpChild} to
* define which view controls this behavior.
*/
class ScrollChildSwipeRefreshLayout : SwipeRefreshLayout {
private var scrollUpChild: View? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun canChildScrollUp(): Boolean {
return scrollUpChild?.canScrollVertically(-1) ?: super.canChildScrollUp()
}
fun setScrollUpChild(view: View) {
scrollUpChild = view
}
}
| app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/ScrollChildSwipeRefreshLayout.kt | 2116398133 |
package blue.aodev.animeultimetv.data.converters
import blue.aodev.animeultimetv.domain.model.AnimeSummary
import blue.aodev.animeultimetv.domain.model.AnimeType
import org.jsoup.Jsoup
import okhttp3.ResponseBody
import org.jsoup.nodes.Element
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
internal class AnimeSummaryAdapter : Converter<ResponseBody, List<AnimeSummary>> {
companion object {
val FACTORY: Converter.Factory = object : Converter.Factory() {
override fun responseBodyConverter(type: Type, annotations: Array<Annotation>,
retrofit: Retrofit): Converter<ResponseBody, *>? {
if (type is ParameterizedType
&& getRawType(type) === List::class.java
&& getParameterUpperBound(0, type) === AnimeSummary::class.java) {
return AnimeSummaryAdapter()
}
return null
}
}
private val idRegex = Regex("""(?<=/)(.+?)(?=-)""")
private val imageRegex = Regex("""[^=]+$""")
}
override fun convert(responseBody: ResponseBody): List<AnimeSummary> {
val result = Jsoup.parse(responseBody.string())
.select(".jtable tr:not(:first-child)")
.map { convertAnimeElement(it) }
return result
}
private fun convertAnimeElement(animeElement: Element): AnimeSummary {
val aImageElement = animeElement.child(0).child(0)
val rawId = aImageElement.attr("href")
val id = idRegex.find(rawId)?.value?.toInt() ?: -1
val imageElement = aImageElement.child(0)
val title = imageElement.attr("title")
val rawImageUrl = imageElement.attr("data-href")
val imageUrl = imageRegex.find(rawImageUrl)?.value
?.let { "http://www.anime-ultime.net/" + it }
val rawType = animeElement.child(2).text()
val type = when (rawType) {
"Episode" -> AnimeType.ANIME
"OAV" -> AnimeType.OAV
"Film" -> AnimeType.MOVIE
else -> AnimeType.ANIME
}
val rawCount = animeElement.child(3).text()
val splitCount = rawCount.split("/")
val availableCount = splitCount.first().toDoubleOrNull()?.toInt() ?: 0
val totalCount = splitCount.last().toDoubleOrNull()?.toInt() ?: 0
val rawRating = animeElement.child(4).text()
val rating = rawRating.split("/").firstOrNull()?.toFloatOrNull() ?: 0f
return AnimeSummary(id, title, imageUrl, type, availableCount, totalCount, rating)
}
} | app/src/main/java/blue/aodev/animeultimetv/data/converters/AnimeSummaryAdapter.kt | 1825559634 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2018 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.lang.format
import com.demonwav.mcdev.nbt.lang.NbttLanguage
import com.intellij.application.options.CodeStyleAbstractConfigurable
import com.intellij.application.options.TabbedLanguageCodeStylePanel
import com.intellij.psi.codeStyle.CodeStyleConfigurable
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.codeStyle.CodeStyleSettingsProvider
class NbttCodeStyleSettingsProvider : CodeStyleSettingsProvider() {
override fun createConfigurable(settings: CodeStyleSettings, modelSettings: CodeStyleSettings) =
object : CodeStyleAbstractConfigurable(settings, modelSettings, configurableDisplayName) {
override fun createPanel(settings: CodeStyleSettings) = NbttCodeStyleMainPanel(currentSettings, settings)
override fun getHelpTopic(): String? = null
}
override fun getConfigurableDisplayName() = "NBT Text"
override fun createCustomSettings(settings: CodeStyleSettings) = NbttCodeStyleSettings(settings)
private class NbttCodeStyleMainPanel(currentSettings: CodeStyleSettings, settings: CodeStyleSettings) :
TabbedLanguageCodeStylePanel(NbttLanguage, currentSettings, settings) {
override fun initTabs(settings: CodeStyleSettings?) {
addIndentOptionsTab(settings)
addWrappingAndBracesTab(settings)
addSpacesTab(settings)
}
}
}
| src/main/kotlin/com/demonwav/mcdev/nbt/lang/format/NbttCodeStyleSettingsProvider.kt | 1491970390 |
package org.fountainmc.api.chat.values
/**
* This catch-all interface represents objects that may be used as a component
* value. For instance, [Text] is a component value that represents plain
* text.
*/
interface ComponentValue {
fun toPlainText(): String = toPlainText(StringBuilder()).toString()
fun toPlainText(buffer: StringBuilder): StringBuilder
}
| src/main/kotlin/org/fountainmc/api/chat/values/ComponentValue.kt | 2323706972 |
package graphics.scenery.effectors
import org.joml.Vector3f
import graphics.scenery.Node
import graphics.scenery.primitives.Plane
/**
* Slicing volume effector
*
* @author Ulrik Guenther <[email protected]>
*/
class SlicingVolumeEffector : VolumeEffector() {
/** Proxy plane for slicing */
override var proxy: Node = Plane(Vector3f(1.0f, 1.0f, 1.0f))
}
| src/main/kotlin/graphics/scenery/effectors/SlicingVolumeEffector.kt | 386903459 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengles.templates
import org.lwjgl.generator.*
import opengles.*
import opengles.BufferType.*
val EXT_instanced_arrays = "EXTInstancedArrays".nativeClassGLES("EXT_instanced_arrays", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
A common use case in GL for some applications is to be able to draw the same object, or groups of similar objects that share vertex data, primitive
count and type, multiple times. This extension provides a means of accelerating such use cases while reducing the number of API calls, and keeping the
amount of duplicate data to a minimum.
This extension introduces an array "divisor" for generic vertex array attributes, which when non-zero specifies that the attribute is "instanced." An
instanced attribute does not advance per-vertex as usual, but rather after every {@code divisor} conceptual draw calls.
(Attributes which aren't instanced are repeated in their entirety for every conceptual draw call.)
By specifying transform data in an instanced attribute or series of instanced attributes, vertex shaders can, in concert with the instancing draw
calls, draw multiple instances of an object with one draw call.
Requires ${GLES20.core}.
"""
IntConstant(
"Accepted by the {@code pname} parameters of GetVertexAttribfv and GetVertexAttribiv.",
"VERTEX_ATTRIB_ARRAY_DIVISOR_EXT"..0x88FE
)
void(
"DrawArraysInstancedEXT",
"",
GLenum("mode", ""),
GLint("start", ""),
GLsizei("count", ""),
GLsizei("primcount", "")
)
void(
"DrawElementsInstancedEXT",
"",
GLenum("mode", ""),
AutoSizeShr("GLESChecks.typeToByteShift(type)", "indices")..GLsizei("count", ""),
AutoType("indices", GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT, GL_UNSIGNED_INT)..GLenum("type", ""),
RawPointer..void.const.p("indices", ""),
GLsizei("primcount", "")
)
void(
"VertexAttribDivisorEXT",
"",
GLuint("index", ""),
GLuint("divisor", "")
)
} | modules/lwjgl/opengles/src/templates/kotlin/opengles/templates/EXT_instanced_arrays.kt | 1895998153 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val ARB_multitexture = "ARBMultitexture".nativeClassGL("ARB_multitexture", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension allows application of multiple textures to a fragment in one rendering pass.
${GL13.promoted}
"""
IntConstant(
"Accepted by the {@code texture} parameter of ActiveTexture and MultiTexCoord.",
"TEXTURE0_ARB"..0x84C0,
"TEXTURE1_ARB"..0x84C1,
"TEXTURE2_ARB"..0x84C2,
"TEXTURE3_ARB"..0x84C3,
"TEXTURE4_ARB"..0x84C4,
"TEXTURE5_ARB"..0x84C5,
"TEXTURE6_ARB"..0x84C6,
"TEXTURE7_ARB"..0x84C7,
"TEXTURE8_ARB"..0x84C8,
"TEXTURE9_ARB"..0x84C9,
"TEXTURE10_ARB"..0x84CA,
"TEXTURE11_ARB"..0x84CB,
"TEXTURE12_ARB"..0x84CC,
"TEXTURE13_ARB"..0x84CD,
"TEXTURE14_ARB"..0x84CE,
"TEXTURE15_ARB"..0x84CF,
"TEXTURE16_ARB"..0x84D0,
"TEXTURE17_ARB"..0x84D1,
"TEXTURE18_ARB"..0x84D2,
"TEXTURE19_ARB"..0x84D3,
"TEXTURE20_ARB"..0x84D4,
"TEXTURE21_ARB"..0x84D5,
"TEXTURE22_ARB"..0x84D6,
"TEXTURE23_ARB"..0x84D7,
"TEXTURE24_ARB"..0x84D8,
"TEXTURE25_ARB"..0x84D9,
"TEXTURE26_ARB"..0x84DA,
"TEXTURE27_ARB"..0x84DB,
"TEXTURE28_ARB"..0x84DC,
"TEXTURE29_ARB"..0x84DD,
"TEXTURE30_ARB"..0x84DE,
"TEXTURE31_ARB"..0x84DF
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"ACTIVE_TEXTURE_ARB"..0x84E0,
"CLIENT_ACTIVE_TEXTURE_ARB"..0x84E1,
"MAX_TEXTURE_UNITS_ARB"..0x84E2
)
void(
"ActiveTextureARB",
"""
Selects which texture unit subsequent texture state calls will affect. The number of texture units an implementation supports is implementation
dependent.
""",
GLenum("texture", "which texture unit to make active", "#TEXTURE0_ARB GL_TEXTURE[1-31]")
)
void(
"ClientActiveTextureARB",
"""
Selects the vertex array client state parameters to be modified by the TexCoordPointer command and the array affected by EnableClientState and
DisableClientState with parameter TEXTURE_COORD_ARRAY.
""",
GLenum("texture", "which texture coordinate array to make active", "#TEXTURE0_ARB GL_TEXTURE[1-31]")
)
// MultiTexCoord functions javadoc
val texCoordTex = "the coordinate set to be modified"
val texCoordS = "the s component of the current texture coordinates"
val texCoordT = "the t component of the current texture coordinates"
val texCoordR = "the r component of the current texture coordinates"
val texCoordQ = "the q component of the current texture coordinates"
val texCoordBuffer = "the texture coordinate buffer"
void(
"MultiTexCoord1fARB",
"Sets the current one-dimensional texture coordinate for the specified texture coordinate set. {@code t} and {@code r} are implicitly set to 0 and {@code q} to 1.",
GLenum("texture", texCoordTex),
GLfloat("s", texCoordS)
)
void("MultiTexCoord1sARB", "Short version of #MultiTexCoord1fARB().", GLenum("texture", texCoordTex), GLshort("s", texCoordS))
void("MultiTexCoord1iARB", "Integer version of #MultiTexCoord1fARB().", GLenum("texture", texCoordTex), GLint("s", texCoordS))
void("MultiTexCoord1dARB", "Double version of #MultiTexCoord1fARB().", GLenum("texture", texCoordTex), GLdouble("s", texCoordS))
void("MultiTexCoord1fvARB", "Pointer version of #MultiTexCoord1fARB().", GLenum("texture", texCoordTex), Check(1)..GLfloat.const.p("v", texCoordBuffer))
void("MultiTexCoord1svARB", "Pointer version of #MultiTexCoord1sARB().", GLenum("texture", texCoordTex), Check(1)..GLshort.const.p("v", texCoordBuffer))
void("MultiTexCoord1ivARB", "Pointer version of #MultiTexCoord1iARB().", GLenum("texture", texCoordTex), Check(1)..GLint.const.p("v", texCoordBuffer))
void("MultiTexCoord1dvARB", "Pointer version of #MultiTexCoord1dARB().", GLenum("texture", texCoordTex), Check(1)..GLdouble.const.p("v", texCoordBuffer))
void(
"MultiTexCoord2fARB",
"Sets the current two-dimensional texture coordinate for the specified texture coordinate set. {@code r} is implicitly set to 0 and {@code q} to 1.",
GLenum("texture", texCoordTex),
GLfloat("s", texCoordS),
GLfloat("t", texCoordT)
)
void("MultiTexCoord2sARB", "Short version of #MultiTexCoord2fARB().", GLenum("texture", texCoordTex), GLshort("s", texCoordS), GLshort("t", texCoordT))
void("MultiTexCoord2iARB", "Integer version of #MultiTexCoord2fARB().", GLenum("texture", texCoordTex), GLint("s", texCoordS), GLint("t", texCoordT))
void("MultiTexCoord2dARB", "Double version of #MultiTexCoord2fARB().", GLenum("texture", texCoordTex), GLdouble("s", texCoordS), GLdouble("t", texCoordT))
void("MultiTexCoord2fvARB", "Pointer version of #MultiTexCoord2fARB().", GLenum("texture", texCoordTex), Check(2)..GLfloat.const.p("v", texCoordBuffer))
void("MultiTexCoord2svARB", "Pointer version of #MultiTexCoord2sARB().", GLenum("texture", texCoordTex), Check(2)..GLshort.const.p("v", texCoordBuffer))
void("MultiTexCoord2ivARB", "Pointer version of #MultiTexCoord2iARB().", GLenum("texture", texCoordTex), Check(2)..GLint.const.p("v", texCoordBuffer))
void("MultiTexCoord2dvARB", "Pointer version of #MultiTexCoord2dARB().", GLenum("texture", texCoordTex), Check(2)..GLdouble.const.p("v", texCoordBuffer))
void(
"MultiTexCoord3fARB",
"Sets the current three-dimensional texture coordinate for the specified texture coordinate set. {@code q} is implicitly set to 1.",
GLenum("texture", texCoordTex),
GLfloat("s", texCoordS),
GLfloat("t", texCoordT),
GLfloat("r", texCoordR)
)
void("MultiTexCoord3sARB", "Short version of #MultiTexCoord3fARB().", GLenum("texture", texCoordTex), GLshort("s", texCoordS), GLshort("t", texCoordT), GLshort("r", texCoordR))
void("MultiTexCoord3iARB", "Integer version of #MultiTexCoord3fARB().", GLenum("texture", texCoordTex), GLint("s", texCoordS), GLint("t", texCoordT), GLint("r", texCoordR))
void("MultiTexCoord3dARB", "Double version of #MultiTexCoord3fARB().", GLenum("texture", texCoordTex), GLdouble("s", texCoordS), GLdouble("t", texCoordT), GLdouble("r", texCoordR))
void("MultiTexCoord3fvARB", "Pointer version of #MultiTexCoord3fARB().", GLenum("texture", texCoordTex), Check(3)..GLfloat.const.p("v", texCoordBuffer))
void("MultiTexCoord3svARB", "Pointer version of #MultiTexCoord3sARB().", GLenum("texture", texCoordTex), Check(3)..GLshort.const.p("v", texCoordBuffer))
void("MultiTexCoord3ivARB", "Pointer version of #MultiTexCoord3iARB().", GLenum("texture", texCoordTex), Check(3)..GLint.const.p("v", texCoordBuffer))
void("MultiTexCoord3dvARB", "Pointer version of #MultiTexCoord3dARB().", GLenum("texture", texCoordTex), Check(3)..GLdouble.const.p("v", texCoordBuffer))
void(
"MultiTexCoord4fARB",
"Sets the current four-dimensional texture coordinate for the specified texture coordinate set.",
GLenum("texture", texCoordTex),
GLfloat("s", texCoordS),
GLfloat("t", texCoordT),
GLfloat("r", texCoordR),
GLfloat("q", texCoordQ)
)
void("MultiTexCoord4sARB", "Short version of #MultiTexCoord4fARB().", GLenum("texture", texCoordTex), GLshort("s", texCoordS), GLshort("t", texCoordT), GLshort("r", texCoordR), GLshort("q", texCoordQ))
void("MultiTexCoord4iARB", "Integer version of #MultiTexCoord4fARB().", GLenum("texture", texCoordTex), GLint("s", texCoordS), GLint("t", texCoordT), GLint("r", texCoordR), GLint("q", texCoordQ))
void("MultiTexCoord4dARB", "Double version of #MultiTexCoord4fARB().", GLenum("texture", texCoordTex), GLdouble("s", texCoordS), GLdouble("t", texCoordT), GLdouble("r", texCoordR), GLdouble("q", texCoordQ))
void("MultiTexCoord4fvARB", "Pointer version of #MultiTexCoord4fARB().", GLenum("texture", texCoordTex), Check(4)..GLfloat.const.p("v", texCoordBuffer))
void("MultiTexCoord4svARB", "Pointer version of #MultiTexCoord4sARB().", GLenum("texture", texCoordTex), Check(4)..GLshort.const.p("v", texCoordBuffer))
void("MultiTexCoord4ivARB", "Pointer version of #MultiTexCoord4iARB().", GLenum("texture", texCoordTex), Check(4)..GLint.const.p("v", texCoordBuffer))
void("MultiTexCoord4dvARB", "Pointer version of #MultiTexCoord4dARB().", GLenum("texture", texCoordTex), Check(4)..GLdouble.const.p("v", texCoordBuffer))
} | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_multitexture.kt | 3315419806 |
/*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.texter.main
import android.content.Context
import android.content.Intent
import android.os.Build
import pl.org.seva.texter.movement.activityRecognition
import pl.org.seva.texter.movement.location
val bootstrap: Bootstrap by instance()
class Bootstrap(private val ctx: Context) {
private var isServiceRunning = false
fun boot() {
location.initPreferences(ctx)
activityRecognition.initWithContext(ctx)
}
fun startService() {
if (isServiceRunning) {
return
}
startService(Intent(ctx, TexterService::class.java))
isServiceRunning = true
}
private fun startService(intent: Intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ctx.startForegroundService(intent)
} else {
ctx.startService(intent)
}
}
fun stopService() {
if (!isServiceRunning) {
return
}
ctx.stopService(Intent(ctx, TexterService::class.java))
isServiceRunning = false
}
}
| texter/src/main/kotlin/pl/org/seva/texter/main/Bootstrap.kt | 3466562648 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val MESA_framebuffer_flip_x = "MESAFramebufferFlipX".nativeClassGL("MESA_framebuffer_flip_x", postfix = MESA) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension defines a new framebuffer parameter, #FRAMEBUFFER_FLIP_X_MESA, that changes the behavior of the reads and writes to the framebuffer
attachment points. When {@code GL_FRAMEBUFFER_FLIP_X_MESA} is #TRUE, render commands and pixel transfer operations access the backing store of each
attachment point with an x-inverted coordinate system. This x-inversion is relative to the coordinate system set when
{@code GL_FRAMEBUFFER_FLIP_X_MESA} is #FALSE.
Access through #TexSubImage2D() and similar calls will notice the effect of the flip when they are not attached to framebuffer objects because
{@code GL_FRAMEBUFFER_FLIP_X_MESA} is associated with the framebuffer object and not the attachment points.
This extension is mainly for pre-rotation and recommended to use it with {@code MESA_framebuffer_flip_y} and {@code MESA_framebuffer_swap_xy} to have
rotated result.
Requires ${GL43.core}.
"""
IntConstant(
"Accepted by the {@code pname} argument of #FramebufferParameteri() and #GetFramebufferParameteriv().",
"FRAMEBUFFER_FLIP_X_MESA"..0x8BBC
)
} | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/MESA_framebuffer_flip_x.kt | 971715600 |
/*
* Copyright (C) 2015 Andriy Druk
*
* 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.druk.rtools
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.NavUtils
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_qualifier_detail.*
/**
* An activity representing a single Qualifier detail screen. This
* activity is only used on handset devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a [MainActivity].
*
*
* This activity is mostly just a 'shell' activity containing nothing
* more than a [QualifierDetailFragment].
*/
class QualifierDetailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_qualifier_detail)
// Show the Up button in the action bar.
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
val qualifier = Qualifier.getQualifier(intent.getIntExtra(QualifierDetailFragment.ARG_ITEM_ID, -1))
setTitle(qualifier.nameResource)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction().add(R.id.qualifier_detail_container,
QualifierDetailFragment.newInstance(qualifier.ordinal)).commit()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, Intent(this, MainActivity::class.java))
return true
}
return super.onOptionsItemSelected(item)
}
}
| app/src/main/kotlin/com/druk/rtools/QualifierDetailActivity.kt | 3488322327 |
/*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.texter.stats
import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.os.Bundle
import android.preference.PreferenceManager
import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.gms.maps.*
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import kotlinx.android.synthetic.main.fragment_stats.*
import java.util.Calendar
import pl.org.seva.texter.R
import pl.org.seva.texter.main.Permissions
import pl.org.seva.texter.data.SmsLocation
import pl.org.seva.texter.main.permissions
import pl.org.seva.texter.movement.activityRecognition
import pl.org.seva.texter.movement.location
import pl.org.seva.texter.sms.smsSender
class StatsFragment : Fragment() {
private var distance: Double = 0.0
private var speed: Double = 0.0
private var isStationary: Boolean = false
private var mapFragment: SupportMapFragment? = null
private var map: GoogleMap? = null
private var locationPermissionGranted = false
private var zoom = 0.0f
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
createSubscriptions()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
distance = location.distance
speed = location.speed
zoom = PreferenceManager.getDefaultSharedPreferences(activity)
.getFloat(ZOOM_PROPERTY_NAME, DEFAULT_ZOOM)
homeString = getString(R.string.home)
hourString = requireActivity().getString(R.string.hour)
speedUnitStr = getString(R.string.speed_unit)
return inflater.inflate(R.layout.fragment_stats, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
send_now_button.setOnClickListener { onSendNowClicked() }
send_now_button.isEnabled = smsSender.isTextingEnabled &&
distance != 0.0 &&
distance != smsSender.lastSentDistance
showStats()
MapsInitializer.initialize(requireActivity().applicationContext)
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync { it.onReady() }
}
@SuppressLint("MissingPermission")
private fun GoogleMap.onReady() {
map = this
processLocationPermission()
val homeLatLng = location.homeLatLng
updateHomeLocation(homeLatLng)
val cameraPosition = CameraPosition.Builder()
.target(homeLatLng).zoom(zoom).build()
checkNotNull(map).moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
if (locationPermissionGranted) {
checkNotNull(map).isMyLocationEnabled = true
}
checkNotNull(map).setOnCameraIdleListener { onCameraIdle() }
}
private fun onCameraIdle() {
zoom = checkNotNull(map).cameraPosition.zoom
PreferenceManager.getDefaultSharedPreferences(activity).edit().putFloat(ZOOM_PROPERTY_NAME, zoom).apply()
}
private fun updateHomeLocation(homeLocation: LatLng?) {
if (map == null || homeLocation == null) {
return
}
val marker = MarkerOptions().position(homeLocation).title(homeString)
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
// adding marker
checkNotNull(map).clear()
checkNotNull(map).addMarker(marker)
}
@SuppressLint("CheckResult")
private fun processLocationPermission() {
if (ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationPermissionGranted = true
map?.isMyLocationEnabled = true
onLocationPermissionGranted()
} else {
permissions.permissionGrantedListener()
.filter { it.first == Permissions.LOCATION_PERMISSION_REQUEST_ID }
.filter { it.second == Manifest.permission.ACCESS_FINE_LOCATION }
.subscribe { onLocationPermissionGranted() }
}
}
@SuppressLint("MissingPermission")
private fun onLocationPermissionGranted() {
locationPermissionGranted = true
map?.isMyLocationEnabled = true
}
private fun createSubscriptions() {
location.addDistanceChangedListenerUi(lifecycle) { onDistanceChanged() }
location.addHomeChangedListener(lifecycle) { onHomeChanged() }
timer.addTimerListenerUi(lifecycle) { showStats() }
smsSender.addSmsSendingListenerUi(lifecycle) { onSendingSms() }
activityRecognition.addActivityRecognitionListener(
lifecycle,
stationary = ::onDeviceStationary,
moving = ::onDeviceMoving)
}
override fun onSaveInstanceState(outState: Bundle) {
deleteMapFragment()
super.onSaveInstanceState(outState)
}
override fun onStop() {
deleteMapFragment()
super.onStop()
}
private fun deleteMapFragment() {
mapFragment?.let {
checkNotNull(fragmentManager).beginTransaction().remove(it).commitAllowingStateLoss()
mapFragment = null
}
}
private fun onDeviceStationary() {
isStationary = true
}
private fun onDeviceMoving() {
isStationary = false
}
private fun showStats() {
distance_value.text = if (distance == 0.0) {
"0 km"
} else {
formattedDistanceStr
}
stationary.visibility = if (isStationary) View.VISIBLE else View.INVISIBLE
update_interval_value.text = formattedTimeStr
if (speed == 0.0 || distance == 0.0) {
speed_value.visibility = View.INVISIBLE
} else {
speed_value.visibility = View.VISIBLE
speed_value.text = formattedSpeedStr
}
}
private val formattedDistanceStr : String
get() = String.format("%.3f km", distance)
private val formattedSpeedStr: String
get() {
@SuppressLint("DefaultLocale")
var result = String.format("%.1f", if (isStationary) 0.0 else speed) + " " + speedUnitStr
if (result.contains(".0")) {
result = result.replace(".0", "")
} else if (result.contains(",0")) {
result = result.replace(",0", "")
}
return result
}
private val formattedTimeStr: String
get() {
var seconds = (System.currentTimeMillis() - timer.resetTime).toInt() / 1000
var minutes = seconds / 60
seconds %= 60
val hours = minutes / 60
minutes %= 60
val timeStrBuilder = StringBuilder()
if (hours > 0) {
timeStrBuilder.append(hours).append(" ").append(hourString)
if (minutes > 0 || seconds > 0) {
timeStrBuilder.append(" ")
}
}
if (minutes > 0) {
timeStrBuilder.append(minutes).append(" m")
if (seconds > 0) {
timeStrBuilder.append(" ")
}
}
if (seconds > 0) {
timeStrBuilder.append(seconds).append(" s")
} else if (minutes == 0 && hours == 0) {
timeStrBuilder.setLength(0)
timeStrBuilder.append("0 s")
}
return timeStrBuilder.toString()
}
private fun onDistanceChanged() {
if (distance != smsSender.lastSentDistance) {
send_now_button.isEnabled = smsSender.isTextingEnabled
}
val threeHoursPassed = System.currentTimeMillis() - timer.resetTime > 3 * 3600 * 1000
if (threeHoursPassed) {
this.speed = 0.0
this.distance = 0.0
} else {
this.distance = location.distance
this.speed = location.speed
}
showStats()
}
@SuppressLint("WrongConstant")
private fun onSendNowClicked() {
send_now_button.isEnabled = false
val calendar = Calendar.getInstance()
calendar.timeInMillis = timer.resetTime
val minutes = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE)
val location = SmsLocation()
location.distance = distance
location.direction = 0
location.setTime(minutes)
location.speed = speed
smsSender.send(location)
}
private fun onSendingSms() {
send_now_button.isEnabled = false
}
private fun onHomeChanged() {
distance = location.distance
showStats()
}
companion object {
private const val ZOOM_PROPERTY_NAME = "stats_map_zoom"
private const val DEFAULT_ZOOM = 7.5f
var homeString: String? = null
private lateinit var hourString: String
private lateinit var speedUnitStr: String
fun newInstance() = StatsFragment()
}
}
| texter/src/main/kotlin/pl/org/seva/texter/stats/StatsFragment.kt | 472719324 |
package net.winsion.cohttp
import kotlinx.coroutines.experimental.CommonPool
import kotlinx.coroutines.experimental.launch
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.junit.Test
class TestCache {
@Test
fun test() {
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor())
.build()
val cohttp = CoHttp.builder()
.baseUrl("https://api.douban.com")
.client(client)
.addConverterFactory(GsonConverterFactory())
.build()
launch(CommonPool) {
val book = cohttp.create(API::class.java).book("1220562")
println(book.pubdate)
}
Thread.sleep(5000)
}
@Test
fun testCancelableRequest() {
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor())
.build()
val cohttp = CoHttp.builder()
.baseUrl("https://api.douban.com")
.client(client)
.addConverterFactory(GsonConverterFactory())
.build()
launch(CommonPool) {
val request = cohttp.create(API::class.java).bookCancelableRequest("1220562")
Thread(Runnable {
Thread.sleep(10)
request.cancel()
}).start()
try {
val book = request.call()
println(book)
} catch (e: Exception) {
println(e.message)
}
}
Thread.sleep(5000)
}
@Test
fun testException() {
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor())
.build()
val cohttp = CoHttp.builder()
.baseUrl("https://api.douba123123n.com")
.client(client)
.addConverterFactory(GsonConverterFactory())
.build()
launch(CommonPool) {
try {
val book = cohttp.create(API::class.java).book("1220562")
println(book.pubdate)
} catch (e: Exception) {
println(e.message)
}
}
Thread.sleep(5000)
}
@Test
fun testResponseData() {
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor())
.build()
val cohttp = CoHttp.builder()
.baseUrl("http://mobile-api.tlbl.winsion.net")
.client(client)
.addConverterFactory(GsonConverterFactory())
.build()
launch(CommonPool) {
val request = cohttp.create(API::class.java).getCurrentTrainMessageV3Cancelable()
val result = request.call()
println(result!!.success)
println(result!!.code)
println(result!!.message)
}
Thread.sleep(5000)
}
} | src/test/java/net/winsion/cohttp/TestCache.kt | 582539482 |
import org.gradle.internal.os.OperatingSystem
enum class OS {
LINUX,
MACOS,
WINDOWS
}
val currentOS: OS by lazy {
val current = OperatingSystem.current()
when {
current.isLinux -> OS.LINUX
current.isMacOsX -> OS.MACOS
current.isWindows -> OS.WINDOWS
else -> throw AssertionError("Unsupported os: ${current.name}")
}
}
| buildSrc/src/main/kotlin/os.kt | 3170507378 |
package org.wikipedia.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.withStyledAttributes
import org.wikipedia.R
import org.wikipedia.databinding.ViewWikitextKeyboardButtonBinding
import org.wikipedia.util.FeedbackUtil.setButtonLongPressToast
import org.wikipedia.util.ResourceUtil.getThemedAttributeId
import org.wikipedia.util.ResourceUtil.getThemedColor
class WikitextKeyboardButtonView constructor(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) {
init {
val binding = ViewWikitextKeyboardButtonBinding.inflate(LayoutInflater.from(context), this)
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
attrs?.let {
context.withStyledAttributes(it, R.styleable.WikitextKeyboardButtonView) {
val drawableId = getResourceId(R.styleable.WikitextKeyboardButtonView_buttonImage, 0)
val buttonText = getString(R.styleable.WikitextKeyboardButtonView_buttonText)
val buttonHint = getString(R.styleable.WikitextKeyboardButtonView_buttonHint)
val buttonTextColor = getColor(R.styleable.WikitextKeyboardButtonView_buttonTextColor,
getThemedColor(context, R.attr.material_theme_secondary_color))
if (drawableId != 0) {
binding.wikitextButtonText.visibility = GONE
binding.wikitextButtonHint.visibility = GONE
binding.wikitextButtonImage.visibility = VISIBLE
binding.wikitextButtonImage.setImageResource(drawableId)
} else {
binding.wikitextButtonText.visibility = VISIBLE
binding.wikitextButtonHint.visibility = VISIBLE
binding.wikitextButtonImage.visibility = GONE
if (!buttonHint.isNullOrEmpty()) {
binding.wikitextButtonText.text = buttonText
}
binding.wikitextButtonText.setTextColor(buttonTextColor)
if (!buttonHint.isNullOrEmpty()) {
binding.wikitextButtonHint.text = buttonHint
}
}
if (!buttonHint.isNullOrEmpty()) {
contentDescription = buttonHint
setButtonLongPressToast(this@WikitextKeyboardButtonView)
}
}
}
isClickable = true
isFocusable = true
background = AppCompatResources.getDrawable(context,
getThemedAttributeId(context, android.R.attr.selectableItemBackground))
}
}
| app/src/main/java/org/wikipedia/views/WikitextKeyboardButtonView.kt | 1781531833 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.codeinsight.linemarker
import com.intellij.codeHighlighting.Pass
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator
import com.intellij.icons.AllIcons
import com.intellij.ide.util.DefaultPsiElementCellRenderer
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.psi.PsiElement
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigFlatOptionKey
import java.awt.event.MouseEvent
class EditorConfigOverriddenKeyLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? = null
override fun collectSlowLineMarkers(elements: List<PsiElement>, result: MutableCollection<LineMarkerInfo<PsiElement>>) {
for (element in elements) {
if (element !is EditorConfigFlatOptionKey) continue
val identifier = element.firstChild ?: continue
if (identifier.firstChild != null) continue
val reference = element.reference
val children = reference
.findChildren()
.toTypedArray()
if (children.isEmpty()) continue
val marker = LineMarkerInfo(
identifier,
identifier.textRange,
AllIcons.Gutter.OverridenMethod,
Pass.LINE_MARKERS,
createTooltipProvider(children),
createNavigationHandler(children, element),
GutterIconRenderer.Alignment.RIGHT
)
result.add(marker)
}
}
private fun createNavigationHandler(children: Array<EditorConfigFlatOptionKey>, optionKey: EditorConfigFlatOptionKey) =
{ event: MouseEvent, _: PsiElement ->
val title = EditorConfigBundle["message.overridden.title"]
val findUsagesTitle = EditorConfigBundle.get("message.overridden.find-usages-title", optionKey.text, optionKey.declarationSite)
val renderer = DefaultPsiElementCellRenderer()
PsiElementListNavigator.openTargets(event, children, title, findUsagesTitle, renderer)
}
private fun createTooltipProvider(children: Array<EditorConfigFlatOptionKey>): (PsiElement) -> String = {
if (children.size == 1) {
val site = children.single().declarationSite
EditorConfigBundle.get("message.overridden.element", site)
}
else {
EditorConfigBundle["message.overridden.multiple"]
}
}
}
| plugins/editorconfig/src/org/editorconfig/language/codeinsight/linemarker/EditorConfigOverriddenKeyLineMarkerProvider.kt | 1746594445 |
// WITH_STDLIB
fun test() {
for (x in "abc") {
if (x != 'a') {
<caret>if (x == 'b') continue
println("else")
}
}
} | plugins/kotlin/idea/tests/testData/intentions/invertIfCondition/unnecessaryContinue2.kt | 2177056259 |
// "Make private and implements 'getName'" "true"
// DISABLE-ERRORS
class A(<caret>protected val name: String) : JavaInterface {
} | plugins/kotlin/idea/tests/testData/quickfix/makePrivateAndOverrideMember/parameterHasProtected.before.Main.kt | 976357322 |
package com.tungnui.dalatlaptop.ux.adapters
import android.graphics.Paint
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.tungnui.dalatlaptop.models.Product
import java.util.ArrayList
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.views.ResizableImageViewHeight
import com.tungnui.dalatlaptop.utils.getFeaturedImage
import com.tungnui.dalatlaptop.utils.inflate
import com.tungnui.dalatlaptop.utils.loadImg
import kotlinx.android.synthetic.main.list_item_recommended_products.view.*
class RelatedProductsRecyclerAdapter(val listener: (Product)->Unit) : RecyclerView.Adapter<RelatedProductsRecyclerAdapter.ViewHolder>() {
private val relatedProducts: MutableList<Product>
init {
relatedProducts = ArrayList()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RelatedProductsRecyclerAdapter.ViewHolder {
return ViewHolder(parent.inflate(R.layout.list_item_recommended_products))
}
override fun onBindViewHolder(holder: RelatedProductsRecyclerAdapter.ViewHolder, position: Int) {
holder.blind(relatedProducts[position],listener)
}
private fun getItem(position: Int): Product? {
return relatedProducts[position]
}
override fun getItemCount(): Int {
return relatedProducts.size
}
fun add(position: Int, product: Product) {
relatedProducts.add(position, product)
notifyItemInserted(position)
}
fun addProducts(items:List<Product>){
relatedProducts.addAll(items)
notifyDataSetChanged()
}
fun addLast(product: Product) {
relatedProducts.add(relatedProducts.size, product)
notifyItemInserted(relatedProducts.size)
}
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
internal var position: Int = 0
fun blind(item:Product,listener: (Product) -> Unit)=with(itemView){
(list_item_recommended_products_image as ResizableImageViewHeight).loadImg(item.images?.getFeaturedImage()?.src)
list_item_recommended_products_name.text = item.name
val pr = item.price
val dis = item.salePrice
if (pr == dis) {
list_item_recommended_products_price.visibility = View.VISIBLE
list_item_recommended_products_discount.visibility = View.GONE
list_item_recommended_products_price.setText(item.priceHtml)
//list_item_recommended_products_price.paintFlags = item
list_item_recommended_products_price.setTextColor(ContextCompat.getColor(context, R.color.textPrimary))
} else {
list_item_recommended_products_price.visibility = View.VISIBLE
list_item_recommended_products_discount.visibility = View.VISIBLE
list_item_recommended_products_price.setText(item.priceHtml)
list_item_recommended_products_price.paintFlags = Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
list_item_recommended_products_price.setTextColor(ContextCompat.getColor(context, R.color.textSecondary))
list_item_recommended_products_discount.setText(item.salePrice)
}
setOnClickListener { listener(item) }
}
fun setPosition(position: Int) {
this.position = position
}
}
}
| app/src/main/java/com/tungnui/dalatlaptop/ux/adapters/RelatedProductsRecyclerAdapter.kt | 2839166419 |
package com.intellij.grazie.ide.inspection.detection.problem
import ai.grazie.nlp.langs.Language
import ai.grazie.nlp.langs.utils.englishName
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.grazie.GrazieBundle
import com.intellij.grazie.detection.toLang
import com.intellij.grazie.ide.inspection.detection.quickfix.DownloadLanguageQuickFix
import com.intellij.grazie.ide.inspection.detection.quickfix.GrazieGoToSettingsQuickFix
import com.intellij.grazie.ide.inspection.detection.quickfix.NeverSuggestLanguageQuickFix
import com.intellij.grazie.utils.toPointer
import com.intellij.psi.PsiFile
object LanguageDetectionProblemDescriptor {
fun create(manager: InspectionManager,
isOnTheFly: Boolean,
file: PsiFile,
languages: Set<Language>): ProblemDescriptor {
val langs = languages.map { it.toLang() }
val text = when {
langs.size in 1..3 && langs.all { it.isAvailable() } -> {
GrazieBundle.message("grazie.detection.problem.enable.several.text", languages.joinToString { it.englishName })
}
langs.size in 1..3 && langs.any { !it.isAvailable() } -> {
GrazieBundle.message("grazie.detection.problem.download.several.text", languages.joinToString { it.englishName })
}
langs.size > 3 && langs.all { it.isAvailable() } -> GrazieBundle.message("grazie.detection.problem.enable.many.text")
langs.size > 3 && langs.any { !it.isAvailable() } -> GrazieBundle.message("grazie.detection.problem.download.many.text")
else -> error("Unexpected text during create of language detection problem descriptor")
}
val fixes = when (langs.size) {
1 -> arrayOf(DownloadLanguageQuickFix(languages), NeverSuggestLanguageQuickFix(file.toPointer(), languages))
2, 3 -> arrayOf(DownloadLanguageQuickFix(languages), GrazieGoToSettingsQuickFix(),
NeverSuggestLanguageQuickFix(file.toPointer(), languages))
else -> arrayOf(GrazieGoToSettingsQuickFix(), NeverSuggestLanguageQuickFix(file.toPointer(), languages))
}
return manager.createProblemDescriptor(file, text, isOnTheFly, fixes, ProblemHighlightType.WARNING)
}
}
| plugins/grazie/src/main/kotlin/com/intellij/grazie/ide/inspection/detection/problem/LanguageDetectionProblemDescriptor.kt | 1058578301 |
package fr.openium.auvergnewebcams.utils
import android.content.Context
import fr.openium.auvergnewebcams.R
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.*
/**
* Created by Openium on 19/02/2019.
*/
class DateUtils(context: Context) {
companion object {
const val DELAY_VALUE_BEFORE_OUTDATED = 2 * 24 * 60 * 60 * 1000L
}
private var dateFullFormat: SimpleDateFormat =
SimpleDateFormat(context.getString(R.string.date_full_format), Locale.getDefault())
private var dateFormatGMT: SimpleDateFormat =
SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }
fun getDateInFullFormat(date: Long): String = dateFullFormat.format(Date(date))
fun isUpToDate(lastUpdateTime: Long?): Boolean {
val time = lastUpdateTime ?: 0L
return if (time == 0L) true else System.currentTimeMillis() - time <= DELAY_VALUE_BEFORE_OUTDATED
}
fun parseDateGMT(date: String): Long? = try {
dateFormatGMT.parse(date)?.time
} catch (e: Exception) {
Timber.e(e, "date $date")
null
}
} | app/src/main/java/fr/openium/auvergnewebcams/utils/DateUtils.kt | 2328665850 |
package org.amshove.kluent.tests.assertions.time.localdatetime
import org.amshove.kluent.after
import org.amshove.kluent.days
import org.amshove.kluent.shouldBeAtLeast
import java.time.LocalDateTime
import kotlin.test.Test
import kotlin.test.assertFails
class ShouldBeAtLeastXDaysAfterShould {
val orderDate = LocalDateTime.of(2017, 6, 5, 10, 0)
@Test
fun passWhenThePassedDateIsExactlyXDaysAfter() {
val shippingDate = LocalDateTime.of(2017, 6, 10, 10, 0)
shippingDate shouldBeAtLeast 5.days() after orderDate
}
@Test
fun passWhenThePassedDateIsMoreThanXDaysAfter() {
val shippingDate = LocalDateTime.of(2017, 6, 15, 10, 0)
shippingDate shouldBeAtLeast 5.days() after orderDate
}
@Test
fun failWhenADateIsLessThanXDaysAfter() {
val shippingDate = LocalDateTime.of(2017, 6, 7, 10, 0)
assertFails { shippingDate shouldBeAtLeast 5.days() after orderDate }
}
} | jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/time/localdatetime/ShouldBeAtLeastXDaysAfterShould.kt | 3099306044 |
package org.pixelndice.table.pixelserver.connection.main
import com.google.common.eventbus.Subscribe
import org.apache.logging.log4j.LogManager
import java.net.InetAddress
import java.time.Instant
import org.pixelndice.table.pixelprotocol.*
import org.pixelndice.table.pixelserver.Bus
import org.pixelndice.table.pixelserver.connection.main.state04hostgame.State07LobbyUnreachable
import org.pixelndice.table.pixelserver.connection.main.state04hostgame.State08LobbyReachable
import org.pixelndice.table.pixelserverhibernate.Account
import org.pixelndice.table.pixelserverhibernate.Game
private val logger = LogManager.getLogger(Context::class.java)
class Context(address: InetAddress) {
val h = BusHandler()
var state: State = State00Start()
var channel: Channel = Channel(address)
var account: Account = Account()
var game: Game? = null
init {
Bus.register(h)
}
fun process() {
try {
// sending keep alive before state processing
if (Instant.now().isAfter(channel.instant.plusSeconds(keepaliveSeconds))) {
logger.trace("Sending keep-alive")
val resp = Protobuf.Packet.newBuilder()
val tkKeepAlive = Protobuf.Keepalive.newBuilder()
resp.setKeepalive(tkKeepAlive)
channel.packet = resp.build()
}
// state processing
state.process(this)
} catch (e: ChannelCanceledException) {
logger.trace("Channel in invalid state. Waiting to be disposed.")
}
}
inner class BusHandler{
@Subscribe
fun handleLobbyReachable(ev: Bus.LobbyReachable){
if( [email protected](ev.game.gm)){
[email protected] = ev.game
[email protected] = State08LobbyReachable()
}
}
@Subscribe
fun handleLobbyUnreachable(ev: Bus.LobbyUnreachable){
if( [email protected](ev.ping.gm)){
[email protected] = State07LobbyUnreachable()
}
}
}
companion object Connection {
// keep alive interval in seconds
var keepaliveSeconds: Long = 60L
}
}
| src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/Context.kt | 3331710084 |
package org.zanata.arquillian
import org.jboss.shrinkwrap.api.asset.ClassAsset
import org.jboss.shrinkwrap.api.asset.StringAsset
import org.jboss.shrinkwrap.api.container.ClassContainer
import org.jboss.shrinkwrap.api.container.ResourceContainer
import org.jboss.shrinkwrap.api.spec.WebArchive
import org.jboss.shrinkwrap.descriptor.api.Descriptor
import org.jboss.shrinkwrap.impl.base.path.BasicPath
import org.slf4j.LoggerFactory
/**
* This object contains extension methods for Arquillian ClassContainer
* (including WebArchive).
* @author Sean Flanigan <a href="mailto:[email protected]">[email protected]</a>
*/
object ArquillianUtil {
private val log = LoggerFactory.getLogger(ArquillianUtil::class.java)
private val TOP_PACKAGE = "org.zanata"
private fun inAZanataPackage(className: String): Boolean = className.startsWith(TOP_PACKAGE)
val IN_ZANATA: ClassNameFilter = ArquillianUtil::inAZanataPackage
private fun notInPlatform(className: String): Boolean {
// TODO listing the packages which will be provided by the platform is a losing battle
val blacklist = arrayOf("org.jboss", "org.hibernate", "java", "com.sun", "sun", "org.w3c", "org.xml", "org.codehaus.jackson", "org.apache.log4j", "org.wildfly", "org.picket", "org.infinispan")
// return !(className.startsWith("org.jboss") || className.startsWith("org.hibernate") || className.startsWith("java") || className.startsWith("com.sun") || className.startsWith("sun") || className.startsWith("org.w3c") || className.startsWith("org.xml") || className.startsWith("org.codehaus.jackson") || className.startsWith("org.apache.log4j") || className.startsWith("org.wildfly") || className.startsWith("org.picket") || className.startsWith("org.infinispan"))
blacklist.forEach {
if (className.startsWith(it)) return false
}
return true
}
val NOT_IN_PLATFORM: ClassNameFilter = ArquillianUtil::notInPlatform
@JvmOverloads
@JvmStatic
fun <T: ClassContainer<T>> T.addClassesWithSupertypes(vararg classes: Class<*>, filter: ClassNameFilter = IN_ZANATA): T {
classes
.filter { filter(it.name) }
.forEach { clazz ->
addClass(clazz)
clazz.superclass?.let { addClassesWithSupertypes(it, filter = filter) }
clazz.interfaces.forEach { addClassesWithSupertypes(it, filter = filter) }
}
return this
}
/**
* ClassContainer extension method which can add a list of classes and
* the transitive set of classes they reference (based on analysis of
* byte code). This includes supertypes, annotations, fields, method
* signature types and method bodies.
*/
@JvmOverloads
@JvmStatic
fun <T: ClassContainer<T>> T.addClassesWithDependencies(classes: List<Class<*>>, filter: ClassNameFilter = IN_ZANATA): T {
val allClasses = findAllClassDependencyChains(classes, filter = filter) //.toTypedArray()
log.info("Adding classes with dependencies: {} ({} total)", classes, allClasses.size)
// uncomment if you want to see the classes and how they were referenced
// allClasses.values.forEach{
// println(it.reverse().map { it.simpleName }.joinToString("/"))
// }
allClasses.keys.forEach { clazz ->
val asset = ClassAsset(clazz)
val filename = clazz.name.replace('.','/')
addAsResource(asset, BasicPath("$filename.class"))
}
return this
}
@JvmStatic
fun <T: ResourceContainer<T>> T.addPersistenceConfig(): T {
addAsResource("arquillian/persistence.xml", "META-INF/persistence.xml")
addAsResource("META-INF/orm.xml")
addAsResource("import.sql")
return this
}
@JvmStatic
fun WebArchive.addWebInfXml(xmlDescriptor: Descriptor): WebArchive {
// contents of XML file
val stringAsset = StringAsset(xmlDescriptor.exportAsString())
// eg beans.xml, jboss-deployment-structure.xml:
val path = xmlDescriptor.descriptorName
addAsWebInfResource(stringAsset, path)
return this
}
}
| server/services/src/test/java/org/zanata/arquillian/ArquillianUtil.kt | 1474776706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.