repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/accompanist | sample/src/main/java/com/google/accompanist/sample/insets/DocsSamples.kt | 1 | 3263 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION")
package com.google.accompanist.sample.insets
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import com.google.accompanist.insets.LocalWindowInsets
import com.google.accompanist.insets.navigationBarsPadding
import com.google.accompanist.insets.rememberInsetsPaddingValues
import com.google.accompanist.insets.statusBarsHeight
import com.google.accompanist.insets.ui.BottomNavigation
@Composable
fun ImeAvoidingBox() {
val insets = LocalWindowInsets.current
val imeBottom = with(LocalDensity.current) { insets.ime.bottom.toDp() }
Box(Modifier.padding(bottom = imeBottom))
}
@Composable
fun Sample_fab() = Box {
FloatingActionButton(
onClick = { /* TODO */ },
modifier = Modifier
.align(Alignment.BottomEnd)
.padding(16.dp) // normal 16dp of padding for FABs
.navigationBarsPadding() // Move it out from under the nav bar
) {
Icon(imageVector = Icons.Default.Add, contentDescription = null)
}
}
@Composable
fun Sample_spacer() {
Spacer(
Modifier
.background(Color.Black.copy(alpha = 0.7f))
.statusBarsHeight() // Match the height of the status bar
.fillMaxWidth()
)
}
@Composable
fun Sample_lazycolumn() {
LazyColumn(
contentPadding = rememberInsetsPaddingValues(
insets = LocalWindowInsets.current.systemBars,
)
) {
// content
}
}
@Composable
fun BottomNavigation_Insets() {
BottomNavigation(
contentPadding = rememberInsetsPaddingValues(
insets = LocalWindowInsets.current.navigationBars,
)
) {
// content
}
}
@Composable
fun TopAppBar_Insets() {
TopAppBar(
contentPadding = rememberInsetsPaddingValues(
insets = LocalWindowInsets.current.systemBars,
applyBottom = false,
)
) {
// content
}
}
| apache-2.0 | a4eff48c9f7386022559f09b8241e816 | 29.495327 | 75 | 0.725713 | 4.439456 | false | false | false | false |
Philip-Trettner/GlmKt | GlmKt/src/glm/vec/Short/ShortVec4.kt | 1 | 38498 | package glm
data class ShortVec4(val x: Short, val y: Short, val z: Short, val w: Short) {
// Initializes each element by evaluating init from 0 until 3
constructor(init: (Int) -> Short) : this(init(0), init(1), init(2), init(3))
operator fun get(idx: Int): Short = when (idx) {
0 -> x
1 -> y
2 -> z
3 -> w
else -> throw IndexOutOfBoundsException("index $idx is out of bounds")
}
// Operators
operator fun inc(): ShortVec4 = ShortVec4(x.inc(), y.inc(), z.inc(), w.inc())
operator fun dec(): ShortVec4 = ShortVec4(x.dec(), y.dec(), z.dec(), w.dec())
operator fun unaryPlus(): IntVec4 = IntVec4(+x, +y, +z, +w)
operator fun unaryMinus(): IntVec4 = IntVec4(-x, -y, -z, -w)
operator fun plus(rhs: ShortVec4): IntVec4 = IntVec4(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w)
operator fun minus(rhs: ShortVec4): IntVec4 = IntVec4(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w)
operator fun times(rhs: ShortVec4): IntVec4 = IntVec4(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w)
operator fun div(rhs: ShortVec4): IntVec4 = IntVec4(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w)
operator fun rem(rhs: ShortVec4): IntVec4 = IntVec4(x % rhs.x, y % rhs.y, z % rhs.z, w % rhs.w)
operator fun plus(rhs: Short): IntVec4 = IntVec4(x + rhs, y + rhs, z + rhs, w + rhs)
operator fun minus(rhs: Short): IntVec4 = IntVec4(x - rhs, y - rhs, z - rhs, w - rhs)
operator fun times(rhs: Short): IntVec4 = IntVec4(x * rhs, y * rhs, z * rhs, w * rhs)
operator fun div(rhs: Short): IntVec4 = IntVec4(x / rhs, y / rhs, z / rhs, w / rhs)
operator fun rem(rhs: Short): IntVec4 = IntVec4(x % rhs, y % rhs, z % rhs, w % rhs)
inline fun map(func: (Short) -> Short): ShortVec4 = ShortVec4(func(x), func(y), func(z), func(w))
fun toList(): List<Short> = listOf(x, y, z, w)
// Predefined vector constants
companion object Constants {
val zero: ShortVec4 = ShortVec4(0.toShort(), 0.toShort(), 0.toShort(), 0.toShort())
val ones: ShortVec4 = ShortVec4(1.toShort(), 1.toShort(), 1.toShort(), 1.toShort())
val unitX: ShortVec4 = ShortVec4(1.toShort(), 0.toShort(), 0.toShort(), 0.toShort())
val unitY: ShortVec4 = ShortVec4(0.toShort(), 1.toShort(), 0.toShort(), 0.toShort())
val unitZ: ShortVec4 = ShortVec4(0.toShort(), 0.toShort(), 1.toShort(), 0.toShort())
val unitW: ShortVec4 = ShortVec4(0.toShort(), 0.toShort(), 0.toShort(), 1.toShort())
}
// Conversions to Float
fun toVec(): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toVec(conv: (Short) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w))
fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat())
inline fun toVec2(conv: (Short) -> Float): Vec2 = Vec2(conv(x), conv(y))
fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toVec3(conv: (Short) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z))
fun toVec4(): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toVec4(conv: (Short) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Float
fun toMutableVec(): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toMutableVec(conv: (Short) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat())
inline fun toMutableVec2(conv: (Short) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y))
fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat())
inline fun toMutableVec3(conv: (Short) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z))
fun toMutableVec4(): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w.toFloat())
inline fun toMutableVec4(conv: (Short) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Double
fun toDoubleVec(): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toDoubleVec(conv: (Short) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w))
fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble())
inline fun toDoubleVec2(conv: (Short) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y))
fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toDoubleVec3(conv: (Short) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z))
fun toDoubleVec4(): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toDoubleVec4(conv: (Short) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Double
fun toMutableDoubleVec(): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toMutableDoubleVec(conv: (Short) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble())
inline fun toMutableDoubleVec2(conv: (Short) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y))
fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble())
inline fun toMutableDoubleVec3(conv: (Short) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z))
fun toMutableDoubleVec4(): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w.toDouble())
inline fun toMutableDoubleVec4(conv: (Short) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Int
fun toIntVec(): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toIntVec(conv: (Short) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w))
fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt())
inline fun toIntVec2(conv: (Short) -> Int): IntVec2 = IntVec2(conv(x), conv(y))
fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toIntVec3(conv: (Short) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z))
fun toIntVec4(): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toIntVec4(conv: (Short) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Int
fun toMutableIntVec(): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toMutableIntVec(conv: (Short) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt())
inline fun toMutableIntVec2(conv: (Short) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y))
fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt())
inline fun toMutableIntVec3(conv: (Short) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z))
fun toMutableIntVec4(): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w.toInt())
inline fun toMutableIntVec4(conv: (Short) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Long
fun toLongVec(): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toLongVec(conv: (Short) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w))
fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong())
inline fun toLongVec2(conv: (Short) -> Long): LongVec2 = LongVec2(conv(x), conv(y))
fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toLongVec3(conv: (Short) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z))
fun toLongVec4(): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toLongVec4(conv: (Short) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Long
fun toMutableLongVec(): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toMutableLongVec(conv: (Short) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong())
inline fun toMutableLongVec2(conv: (Short) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y))
fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong())
inline fun toMutableLongVec3(conv: (Short) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z))
fun toMutableLongVec4(): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w.toLong())
inline fun toMutableLongVec4(conv: (Short) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Short
fun toShortVec(): ShortVec4 = ShortVec4(x, y, z, w)
inline fun toShortVec(conv: (Short) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w))
fun toShortVec2(): ShortVec2 = ShortVec2(x, y)
inline fun toShortVec2(conv: (Short) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y))
fun toShortVec3(): ShortVec3 = ShortVec3(x, y, z)
inline fun toShortVec3(conv: (Short) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z))
fun toShortVec4(): ShortVec4 = ShortVec4(x, y, z, w)
inline fun toShortVec4(conv: (Short) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Short
fun toMutableShortVec(): MutableShortVec4 = MutableShortVec4(x, y, z, w)
inline fun toMutableShortVec(conv: (Short) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x, y)
inline fun toMutableShortVec2(conv: (Short) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y))
fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x, y, z)
inline fun toMutableShortVec3(conv: (Short) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z))
fun toMutableShortVec4(): MutableShortVec4 = MutableShortVec4(x, y, z, w)
inline fun toMutableShortVec4(conv: (Short) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Byte
fun toByteVec(): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w.toByte())
inline fun toByteVec(conv: (Short) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w))
fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte())
inline fun toByteVec2(conv: (Short) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y))
fun toByteVec3(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toByteVec3(conv: (Short) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z))
fun toByteVec4(): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w.toByte())
inline fun toByteVec4(conv: (Short) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Byte
fun toMutableByteVec(): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w.toByte())
inline fun toMutableByteVec(conv: (Short) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte())
inline fun toMutableByteVec2(conv: (Short) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y))
fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte())
inline fun toMutableByteVec3(conv: (Short) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z))
fun toMutableByteVec4(): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w.toByte())
inline fun toMutableByteVec4(conv: (Short) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Char
fun toCharVec(): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toCharVec(conv: (Short) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w))
fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar())
inline fun toCharVec2(conv: (Short) -> Char): CharVec2 = CharVec2(conv(x), conv(y))
fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toCharVec3(conv: (Short) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z))
fun toCharVec4(): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toCharVec4(conv: (Short) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Char
fun toMutableCharVec(): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toMutableCharVec(conv: (Short) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar())
inline fun toMutableCharVec2(conv: (Short) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y))
fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar())
inline fun toMutableCharVec3(conv: (Short) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z))
fun toMutableCharVec4(): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w.toChar())
inline fun toMutableCharVec4(conv: (Short) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Boolean
fun toBoolVec(): BoolVec4 = BoolVec4(x != 0.toShort(), y != 0.toShort(), z != 0.toShort(), w != 0.toShort())
inline fun toBoolVec(conv: (Short) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w))
fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.toShort(), y != 0.toShort())
inline fun toBoolVec2(conv: (Short) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y))
fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.toShort(), y != 0.toShort(), z != 0.toShort())
inline fun toBoolVec3(conv: (Short) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z))
fun toBoolVec4(): BoolVec4 = BoolVec4(x != 0.toShort(), y != 0.toShort(), z != 0.toShort(), w != 0.toShort())
inline fun toBoolVec4(conv: (Short) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to Boolean
fun toMutableBoolVec(): MutableBoolVec4 = MutableBoolVec4(x != 0.toShort(), y != 0.toShort(), z != 0.toShort(), w != 0.toShort())
inline fun toMutableBoolVec(conv: (Short) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.toShort(), y != 0.toShort())
inline fun toMutableBoolVec2(conv: (Short) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y))
fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.toShort(), y != 0.toShort(), z != 0.toShort())
inline fun toMutableBoolVec3(conv: (Short) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z))
fun toMutableBoolVec4(): MutableBoolVec4 = MutableBoolVec4(x != 0.toShort(), y != 0.toShort(), z != 0.toShort(), w != 0.toShort())
inline fun toMutableBoolVec4(conv: (Short) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to String
fun toStringVec(): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toStringVec(conv: (Short) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w))
fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString())
inline fun toStringVec2(conv: (Short) -> String): StringVec2 = StringVec2(conv(x), conv(y))
fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString())
inline fun toStringVec3(conv: (Short) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z))
fun toStringVec4(): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toStringVec4(conv: (Short) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to String
fun toMutableStringVec(): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toMutableStringVec(conv: (Short) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w))
fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString())
inline fun toMutableStringVec2(conv: (Short) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y))
fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString())
inline fun toMutableStringVec3(conv: (Short) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z))
fun toMutableStringVec4(): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w.toString())
inline fun toMutableStringVec4(conv: (Short) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), conv(w))
// Conversions to T2
inline fun <T2> toTVec(conv: (Short) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w))
inline fun <T2> toTVec2(conv: (Short) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y))
inline fun <T2> toTVec3(conv: (Short) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toTVec4(conv: (Short) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), conv(w))
// Conversions to T2
inline fun <T2> toMutableTVec(conv: (Short) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w))
inline fun <T2> toMutableTVec2(conv: (Short) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y))
inline fun <T2> toMutableTVec3(conv: (Short) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z))
inline fun <T2> toMutableTVec4(conv: (Short) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), conv(w))
// Allows for swizzling, e.g. v.swizzle.xzx
inner class Swizzle {
val xx: ShortVec2 get() = ShortVec2(x, x)
val xy: ShortVec2 get() = ShortVec2(x, y)
val xz: ShortVec2 get() = ShortVec2(x, z)
val xw: ShortVec2 get() = ShortVec2(x, w)
val yx: ShortVec2 get() = ShortVec2(y, x)
val yy: ShortVec2 get() = ShortVec2(y, y)
val yz: ShortVec2 get() = ShortVec2(y, z)
val yw: ShortVec2 get() = ShortVec2(y, w)
val zx: ShortVec2 get() = ShortVec2(z, x)
val zy: ShortVec2 get() = ShortVec2(z, y)
val zz: ShortVec2 get() = ShortVec2(z, z)
val zw: ShortVec2 get() = ShortVec2(z, w)
val wx: ShortVec2 get() = ShortVec2(w, x)
val wy: ShortVec2 get() = ShortVec2(w, y)
val wz: ShortVec2 get() = ShortVec2(w, z)
val ww: ShortVec2 get() = ShortVec2(w, w)
val xxx: ShortVec3 get() = ShortVec3(x, x, x)
val xxy: ShortVec3 get() = ShortVec3(x, x, y)
val xxz: ShortVec3 get() = ShortVec3(x, x, z)
val xxw: ShortVec3 get() = ShortVec3(x, x, w)
val xyx: ShortVec3 get() = ShortVec3(x, y, x)
val xyy: ShortVec3 get() = ShortVec3(x, y, y)
val xyz: ShortVec3 get() = ShortVec3(x, y, z)
val xyw: ShortVec3 get() = ShortVec3(x, y, w)
val xzx: ShortVec3 get() = ShortVec3(x, z, x)
val xzy: ShortVec3 get() = ShortVec3(x, z, y)
val xzz: ShortVec3 get() = ShortVec3(x, z, z)
val xzw: ShortVec3 get() = ShortVec3(x, z, w)
val xwx: ShortVec3 get() = ShortVec3(x, w, x)
val xwy: ShortVec3 get() = ShortVec3(x, w, y)
val xwz: ShortVec3 get() = ShortVec3(x, w, z)
val xww: ShortVec3 get() = ShortVec3(x, w, w)
val yxx: ShortVec3 get() = ShortVec3(y, x, x)
val yxy: ShortVec3 get() = ShortVec3(y, x, y)
val yxz: ShortVec3 get() = ShortVec3(y, x, z)
val yxw: ShortVec3 get() = ShortVec3(y, x, w)
val yyx: ShortVec3 get() = ShortVec3(y, y, x)
val yyy: ShortVec3 get() = ShortVec3(y, y, y)
val yyz: ShortVec3 get() = ShortVec3(y, y, z)
val yyw: ShortVec3 get() = ShortVec3(y, y, w)
val yzx: ShortVec3 get() = ShortVec3(y, z, x)
val yzy: ShortVec3 get() = ShortVec3(y, z, y)
val yzz: ShortVec3 get() = ShortVec3(y, z, z)
val yzw: ShortVec3 get() = ShortVec3(y, z, w)
val ywx: ShortVec3 get() = ShortVec3(y, w, x)
val ywy: ShortVec3 get() = ShortVec3(y, w, y)
val ywz: ShortVec3 get() = ShortVec3(y, w, z)
val yww: ShortVec3 get() = ShortVec3(y, w, w)
val zxx: ShortVec3 get() = ShortVec3(z, x, x)
val zxy: ShortVec3 get() = ShortVec3(z, x, y)
val zxz: ShortVec3 get() = ShortVec3(z, x, z)
val zxw: ShortVec3 get() = ShortVec3(z, x, w)
val zyx: ShortVec3 get() = ShortVec3(z, y, x)
val zyy: ShortVec3 get() = ShortVec3(z, y, y)
val zyz: ShortVec3 get() = ShortVec3(z, y, z)
val zyw: ShortVec3 get() = ShortVec3(z, y, w)
val zzx: ShortVec3 get() = ShortVec3(z, z, x)
val zzy: ShortVec3 get() = ShortVec3(z, z, y)
val zzz: ShortVec3 get() = ShortVec3(z, z, z)
val zzw: ShortVec3 get() = ShortVec3(z, z, w)
val zwx: ShortVec3 get() = ShortVec3(z, w, x)
val zwy: ShortVec3 get() = ShortVec3(z, w, y)
val zwz: ShortVec3 get() = ShortVec3(z, w, z)
val zww: ShortVec3 get() = ShortVec3(z, w, w)
val wxx: ShortVec3 get() = ShortVec3(w, x, x)
val wxy: ShortVec3 get() = ShortVec3(w, x, y)
val wxz: ShortVec3 get() = ShortVec3(w, x, z)
val wxw: ShortVec3 get() = ShortVec3(w, x, w)
val wyx: ShortVec3 get() = ShortVec3(w, y, x)
val wyy: ShortVec3 get() = ShortVec3(w, y, y)
val wyz: ShortVec3 get() = ShortVec3(w, y, z)
val wyw: ShortVec3 get() = ShortVec3(w, y, w)
val wzx: ShortVec3 get() = ShortVec3(w, z, x)
val wzy: ShortVec3 get() = ShortVec3(w, z, y)
val wzz: ShortVec3 get() = ShortVec3(w, z, z)
val wzw: ShortVec3 get() = ShortVec3(w, z, w)
val wwx: ShortVec3 get() = ShortVec3(w, w, x)
val wwy: ShortVec3 get() = ShortVec3(w, w, y)
val wwz: ShortVec3 get() = ShortVec3(w, w, z)
val www: ShortVec3 get() = ShortVec3(w, w, w)
val xxxx: ShortVec4 get() = ShortVec4(x, x, x, x)
val xxxy: ShortVec4 get() = ShortVec4(x, x, x, y)
val xxxz: ShortVec4 get() = ShortVec4(x, x, x, z)
val xxxw: ShortVec4 get() = ShortVec4(x, x, x, w)
val xxyx: ShortVec4 get() = ShortVec4(x, x, y, x)
val xxyy: ShortVec4 get() = ShortVec4(x, x, y, y)
val xxyz: ShortVec4 get() = ShortVec4(x, x, y, z)
val xxyw: ShortVec4 get() = ShortVec4(x, x, y, w)
val xxzx: ShortVec4 get() = ShortVec4(x, x, z, x)
val xxzy: ShortVec4 get() = ShortVec4(x, x, z, y)
val xxzz: ShortVec4 get() = ShortVec4(x, x, z, z)
val xxzw: ShortVec4 get() = ShortVec4(x, x, z, w)
val xxwx: ShortVec4 get() = ShortVec4(x, x, w, x)
val xxwy: ShortVec4 get() = ShortVec4(x, x, w, y)
val xxwz: ShortVec4 get() = ShortVec4(x, x, w, z)
val xxww: ShortVec4 get() = ShortVec4(x, x, w, w)
val xyxx: ShortVec4 get() = ShortVec4(x, y, x, x)
val xyxy: ShortVec4 get() = ShortVec4(x, y, x, y)
val xyxz: ShortVec4 get() = ShortVec4(x, y, x, z)
val xyxw: ShortVec4 get() = ShortVec4(x, y, x, w)
val xyyx: ShortVec4 get() = ShortVec4(x, y, y, x)
val xyyy: ShortVec4 get() = ShortVec4(x, y, y, y)
val xyyz: ShortVec4 get() = ShortVec4(x, y, y, z)
val xyyw: ShortVec4 get() = ShortVec4(x, y, y, w)
val xyzx: ShortVec4 get() = ShortVec4(x, y, z, x)
val xyzy: ShortVec4 get() = ShortVec4(x, y, z, y)
val xyzz: ShortVec4 get() = ShortVec4(x, y, z, z)
val xyzw: ShortVec4 get() = ShortVec4(x, y, z, w)
val xywx: ShortVec4 get() = ShortVec4(x, y, w, x)
val xywy: ShortVec4 get() = ShortVec4(x, y, w, y)
val xywz: ShortVec4 get() = ShortVec4(x, y, w, z)
val xyww: ShortVec4 get() = ShortVec4(x, y, w, w)
val xzxx: ShortVec4 get() = ShortVec4(x, z, x, x)
val xzxy: ShortVec4 get() = ShortVec4(x, z, x, y)
val xzxz: ShortVec4 get() = ShortVec4(x, z, x, z)
val xzxw: ShortVec4 get() = ShortVec4(x, z, x, w)
val xzyx: ShortVec4 get() = ShortVec4(x, z, y, x)
val xzyy: ShortVec4 get() = ShortVec4(x, z, y, y)
val xzyz: ShortVec4 get() = ShortVec4(x, z, y, z)
val xzyw: ShortVec4 get() = ShortVec4(x, z, y, w)
val xzzx: ShortVec4 get() = ShortVec4(x, z, z, x)
val xzzy: ShortVec4 get() = ShortVec4(x, z, z, y)
val xzzz: ShortVec4 get() = ShortVec4(x, z, z, z)
val xzzw: ShortVec4 get() = ShortVec4(x, z, z, w)
val xzwx: ShortVec4 get() = ShortVec4(x, z, w, x)
val xzwy: ShortVec4 get() = ShortVec4(x, z, w, y)
val xzwz: ShortVec4 get() = ShortVec4(x, z, w, z)
val xzww: ShortVec4 get() = ShortVec4(x, z, w, w)
val xwxx: ShortVec4 get() = ShortVec4(x, w, x, x)
val xwxy: ShortVec4 get() = ShortVec4(x, w, x, y)
val xwxz: ShortVec4 get() = ShortVec4(x, w, x, z)
val xwxw: ShortVec4 get() = ShortVec4(x, w, x, w)
val xwyx: ShortVec4 get() = ShortVec4(x, w, y, x)
val xwyy: ShortVec4 get() = ShortVec4(x, w, y, y)
val xwyz: ShortVec4 get() = ShortVec4(x, w, y, z)
val xwyw: ShortVec4 get() = ShortVec4(x, w, y, w)
val xwzx: ShortVec4 get() = ShortVec4(x, w, z, x)
val xwzy: ShortVec4 get() = ShortVec4(x, w, z, y)
val xwzz: ShortVec4 get() = ShortVec4(x, w, z, z)
val xwzw: ShortVec4 get() = ShortVec4(x, w, z, w)
val xwwx: ShortVec4 get() = ShortVec4(x, w, w, x)
val xwwy: ShortVec4 get() = ShortVec4(x, w, w, y)
val xwwz: ShortVec4 get() = ShortVec4(x, w, w, z)
val xwww: ShortVec4 get() = ShortVec4(x, w, w, w)
val yxxx: ShortVec4 get() = ShortVec4(y, x, x, x)
val yxxy: ShortVec4 get() = ShortVec4(y, x, x, y)
val yxxz: ShortVec4 get() = ShortVec4(y, x, x, z)
val yxxw: ShortVec4 get() = ShortVec4(y, x, x, w)
val yxyx: ShortVec4 get() = ShortVec4(y, x, y, x)
val yxyy: ShortVec4 get() = ShortVec4(y, x, y, y)
val yxyz: ShortVec4 get() = ShortVec4(y, x, y, z)
val yxyw: ShortVec4 get() = ShortVec4(y, x, y, w)
val yxzx: ShortVec4 get() = ShortVec4(y, x, z, x)
val yxzy: ShortVec4 get() = ShortVec4(y, x, z, y)
val yxzz: ShortVec4 get() = ShortVec4(y, x, z, z)
val yxzw: ShortVec4 get() = ShortVec4(y, x, z, w)
val yxwx: ShortVec4 get() = ShortVec4(y, x, w, x)
val yxwy: ShortVec4 get() = ShortVec4(y, x, w, y)
val yxwz: ShortVec4 get() = ShortVec4(y, x, w, z)
val yxww: ShortVec4 get() = ShortVec4(y, x, w, w)
val yyxx: ShortVec4 get() = ShortVec4(y, y, x, x)
val yyxy: ShortVec4 get() = ShortVec4(y, y, x, y)
val yyxz: ShortVec4 get() = ShortVec4(y, y, x, z)
val yyxw: ShortVec4 get() = ShortVec4(y, y, x, w)
val yyyx: ShortVec4 get() = ShortVec4(y, y, y, x)
val yyyy: ShortVec4 get() = ShortVec4(y, y, y, y)
val yyyz: ShortVec4 get() = ShortVec4(y, y, y, z)
val yyyw: ShortVec4 get() = ShortVec4(y, y, y, w)
val yyzx: ShortVec4 get() = ShortVec4(y, y, z, x)
val yyzy: ShortVec4 get() = ShortVec4(y, y, z, y)
val yyzz: ShortVec4 get() = ShortVec4(y, y, z, z)
val yyzw: ShortVec4 get() = ShortVec4(y, y, z, w)
val yywx: ShortVec4 get() = ShortVec4(y, y, w, x)
val yywy: ShortVec4 get() = ShortVec4(y, y, w, y)
val yywz: ShortVec4 get() = ShortVec4(y, y, w, z)
val yyww: ShortVec4 get() = ShortVec4(y, y, w, w)
val yzxx: ShortVec4 get() = ShortVec4(y, z, x, x)
val yzxy: ShortVec4 get() = ShortVec4(y, z, x, y)
val yzxz: ShortVec4 get() = ShortVec4(y, z, x, z)
val yzxw: ShortVec4 get() = ShortVec4(y, z, x, w)
val yzyx: ShortVec4 get() = ShortVec4(y, z, y, x)
val yzyy: ShortVec4 get() = ShortVec4(y, z, y, y)
val yzyz: ShortVec4 get() = ShortVec4(y, z, y, z)
val yzyw: ShortVec4 get() = ShortVec4(y, z, y, w)
val yzzx: ShortVec4 get() = ShortVec4(y, z, z, x)
val yzzy: ShortVec4 get() = ShortVec4(y, z, z, y)
val yzzz: ShortVec4 get() = ShortVec4(y, z, z, z)
val yzzw: ShortVec4 get() = ShortVec4(y, z, z, w)
val yzwx: ShortVec4 get() = ShortVec4(y, z, w, x)
val yzwy: ShortVec4 get() = ShortVec4(y, z, w, y)
val yzwz: ShortVec4 get() = ShortVec4(y, z, w, z)
val yzww: ShortVec4 get() = ShortVec4(y, z, w, w)
val ywxx: ShortVec4 get() = ShortVec4(y, w, x, x)
val ywxy: ShortVec4 get() = ShortVec4(y, w, x, y)
val ywxz: ShortVec4 get() = ShortVec4(y, w, x, z)
val ywxw: ShortVec4 get() = ShortVec4(y, w, x, w)
val ywyx: ShortVec4 get() = ShortVec4(y, w, y, x)
val ywyy: ShortVec4 get() = ShortVec4(y, w, y, y)
val ywyz: ShortVec4 get() = ShortVec4(y, w, y, z)
val ywyw: ShortVec4 get() = ShortVec4(y, w, y, w)
val ywzx: ShortVec4 get() = ShortVec4(y, w, z, x)
val ywzy: ShortVec4 get() = ShortVec4(y, w, z, y)
val ywzz: ShortVec4 get() = ShortVec4(y, w, z, z)
val ywzw: ShortVec4 get() = ShortVec4(y, w, z, w)
val ywwx: ShortVec4 get() = ShortVec4(y, w, w, x)
val ywwy: ShortVec4 get() = ShortVec4(y, w, w, y)
val ywwz: ShortVec4 get() = ShortVec4(y, w, w, z)
val ywww: ShortVec4 get() = ShortVec4(y, w, w, w)
val zxxx: ShortVec4 get() = ShortVec4(z, x, x, x)
val zxxy: ShortVec4 get() = ShortVec4(z, x, x, y)
val zxxz: ShortVec4 get() = ShortVec4(z, x, x, z)
val zxxw: ShortVec4 get() = ShortVec4(z, x, x, w)
val zxyx: ShortVec4 get() = ShortVec4(z, x, y, x)
val zxyy: ShortVec4 get() = ShortVec4(z, x, y, y)
val zxyz: ShortVec4 get() = ShortVec4(z, x, y, z)
val zxyw: ShortVec4 get() = ShortVec4(z, x, y, w)
val zxzx: ShortVec4 get() = ShortVec4(z, x, z, x)
val zxzy: ShortVec4 get() = ShortVec4(z, x, z, y)
val zxzz: ShortVec4 get() = ShortVec4(z, x, z, z)
val zxzw: ShortVec4 get() = ShortVec4(z, x, z, w)
val zxwx: ShortVec4 get() = ShortVec4(z, x, w, x)
val zxwy: ShortVec4 get() = ShortVec4(z, x, w, y)
val zxwz: ShortVec4 get() = ShortVec4(z, x, w, z)
val zxww: ShortVec4 get() = ShortVec4(z, x, w, w)
val zyxx: ShortVec4 get() = ShortVec4(z, y, x, x)
val zyxy: ShortVec4 get() = ShortVec4(z, y, x, y)
val zyxz: ShortVec4 get() = ShortVec4(z, y, x, z)
val zyxw: ShortVec4 get() = ShortVec4(z, y, x, w)
val zyyx: ShortVec4 get() = ShortVec4(z, y, y, x)
val zyyy: ShortVec4 get() = ShortVec4(z, y, y, y)
val zyyz: ShortVec4 get() = ShortVec4(z, y, y, z)
val zyyw: ShortVec4 get() = ShortVec4(z, y, y, w)
val zyzx: ShortVec4 get() = ShortVec4(z, y, z, x)
val zyzy: ShortVec4 get() = ShortVec4(z, y, z, y)
val zyzz: ShortVec4 get() = ShortVec4(z, y, z, z)
val zyzw: ShortVec4 get() = ShortVec4(z, y, z, w)
val zywx: ShortVec4 get() = ShortVec4(z, y, w, x)
val zywy: ShortVec4 get() = ShortVec4(z, y, w, y)
val zywz: ShortVec4 get() = ShortVec4(z, y, w, z)
val zyww: ShortVec4 get() = ShortVec4(z, y, w, w)
val zzxx: ShortVec4 get() = ShortVec4(z, z, x, x)
val zzxy: ShortVec4 get() = ShortVec4(z, z, x, y)
val zzxz: ShortVec4 get() = ShortVec4(z, z, x, z)
val zzxw: ShortVec4 get() = ShortVec4(z, z, x, w)
val zzyx: ShortVec4 get() = ShortVec4(z, z, y, x)
val zzyy: ShortVec4 get() = ShortVec4(z, z, y, y)
val zzyz: ShortVec4 get() = ShortVec4(z, z, y, z)
val zzyw: ShortVec4 get() = ShortVec4(z, z, y, w)
val zzzx: ShortVec4 get() = ShortVec4(z, z, z, x)
val zzzy: ShortVec4 get() = ShortVec4(z, z, z, y)
val zzzz: ShortVec4 get() = ShortVec4(z, z, z, z)
val zzzw: ShortVec4 get() = ShortVec4(z, z, z, w)
val zzwx: ShortVec4 get() = ShortVec4(z, z, w, x)
val zzwy: ShortVec4 get() = ShortVec4(z, z, w, y)
val zzwz: ShortVec4 get() = ShortVec4(z, z, w, z)
val zzww: ShortVec4 get() = ShortVec4(z, z, w, w)
val zwxx: ShortVec4 get() = ShortVec4(z, w, x, x)
val zwxy: ShortVec4 get() = ShortVec4(z, w, x, y)
val zwxz: ShortVec4 get() = ShortVec4(z, w, x, z)
val zwxw: ShortVec4 get() = ShortVec4(z, w, x, w)
val zwyx: ShortVec4 get() = ShortVec4(z, w, y, x)
val zwyy: ShortVec4 get() = ShortVec4(z, w, y, y)
val zwyz: ShortVec4 get() = ShortVec4(z, w, y, z)
val zwyw: ShortVec4 get() = ShortVec4(z, w, y, w)
val zwzx: ShortVec4 get() = ShortVec4(z, w, z, x)
val zwzy: ShortVec4 get() = ShortVec4(z, w, z, y)
val zwzz: ShortVec4 get() = ShortVec4(z, w, z, z)
val zwzw: ShortVec4 get() = ShortVec4(z, w, z, w)
val zwwx: ShortVec4 get() = ShortVec4(z, w, w, x)
val zwwy: ShortVec4 get() = ShortVec4(z, w, w, y)
val zwwz: ShortVec4 get() = ShortVec4(z, w, w, z)
val zwww: ShortVec4 get() = ShortVec4(z, w, w, w)
val wxxx: ShortVec4 get() = ShortVec4(w, x, x, x)
val wxxy: ShortVec4 get() = ShortVec4(w, x, x, y)
val wxxz: ShortVec4 get() = ShortVec4(w, x, x, z)
val wxxw: ShortVec4 get() = ShortVec4(w, x, x, w)
val wxyx: ShortVec4 get() = ShortVec4(w, x, y, x)
val wxyy: ShortVec4 get() = ShortVec4(w, x, y, y)
val wxyz: ShortVec4 get() = ShortVec4(w, x, y, z)
val wxyw: ShortVec4 get() = ShortVec4(w, x, y, w)
val wxzx: ShortVec4 get() = ShortVec4(w, x, z, x)
val wxzy: ShortVec4 get() = ShortVec4(w, x, z, y)
val wxzz: ShortVec4 get() = ShortVec4(w, x, z, z)
val wxzw: ShortVec4 get() = ShortVec4(w, x, z, w)
val wxwx: ShortVec4 get() = ShortVec4(w, x, w, x)
val wxwy: ShortVec4 get() = ShortVec4(w, x, w, y)
val wxwz: ShortVec4 get() = ShortVec4(w, x, w, z)
val wxww: ShortVec4 get() = ShortVec4(w, x, w, w)
val wyxx: ShortVec4 get() = ShortVec4(w, y, x, x)
val wyxy: ShortVec4 get() = ShortVec4(w, y, x, y)
val wyxz: ShortVec4 get() = ShortVec4(w, y, x, z)
val wyxw: ShortVec4 get() = ShortVec4(w, y, x, w)
val wyyx: ShortVec4 get() = ShortVec4(w, y, y, x)
val wyyy: ShortVec4 get() = ShortVec4(w, y, y, y)
val wyyz: ShortVec4 get() = ShortVec4(w, y, y, z)
val wyyw: ShortVec4 get() = ShortVec4(w, y, y, w)
val wyzx: ShortVec4 get() = ShortVec4(w, y, z, x)
val wyzy: ShortVec4 get() = ShortVec4(w, y, z, y)
val wyzz: ShortVec4 get() = ShortVec4(w, y, z, z)
val wyzw: ShortVec4 get() = ShortVec4(w, y, z, w)
val wywx: ShortVec4 get() = ShortVec4(w, y, w, x)
val wywy: ShortVec4 get() = ShortVec4(w, y, w, y)
val wywz: ShortVec4 get() = ShortVec4(w, y, w, z)
val wyww: ShortVec4 get() = ShortVec4(w, y, w, w)
val wzxx: ShortVec4 get() = ShortVec4(w, z, x, x)
val wzxy: ShortVec4 get() = ShortVec4(w, z, x, y)
val wzxz: ShortVec4 get() = ShortVec4(w, z, x, z)
val wzxw: ShortVec4 get() = ShortVec4(w, z, x, w)
val wzyx: ShortVec4 get() = ShortVec4(w, z, y, x)
val wzyy: ShortVec4 get() = ShortVec4(w, z, y, y)
val wzyz: ShortVec4 get() = ShortVec4(w, z, y, z)
val wzyw: ShortVec4 get() = ShortVec4(w, z, y, w)
val wzzx: ShortVec4 get() = ShortVec4(w, z, z, x)
val wzzy: ShortVec4 get() = ShortVec4(w, z, z, y)
val wzzz: ShortVec4 get() = ShortVec4(w, z, z, z)
val wzzw: ShortVec4 get() = ShortVec4(w, z, z, w)
val wzwx: ShortVec4 get() = ShortVec4(w, z, w, x)
val wzwy: ShortVec4 get() = ShortVec4(w, z, w, y)
val wzwz: ShortVec4 get() = ShortVec4(w, z, w, z)
val wzww: ShortVec4 get() = ShortVec4(w, z, w, w)
val wwxx: ShortVec4 get() = ShortVec4(w, w, x, x)
val wwxy: ShortVec4 get() = ShortVec4(w, w, x, y)
val wwxz: ShortVec4 get() = ShortVec4(w, w, x, z)
val wwxw: ShortVec4 get() = ShortVec4(w, w, x, w)
val wwyx: ShortVec4 get() = ShortVec4(w, w, y, x)
val wwyy: ShortVec4 get() = ShortVec4(w, w, y, y)
val wwyz: ShortVec4 get() = ShortVec4(w, w, y, z)
val wwyw: ShortVec4 get() = ShortVec4(w, w, y, w)
val wwzx: ShortVec4 get() = ShortVec4(w, w, z, x)
val wwzy: ShortVec4 get() = ShortVec4(w, w, z, y)
val wwzz: ShortVec4 get() = ShortVec4(w, w, z, z)
val wwzw: ShortVec4 get() = ShortVec4(w, w, z, w)
val wwwx: ShortVec4 get() = ShortVec4(w, w, w, x)
val wwwy: ShortVec4 get() = ShortVec4(w, w, w, y)
val wwwz: ShortVec4 get() = ShortVec4(w, w, w, z)
val wwww: ShortVec4 get() = ShortVec4(w, w, w, w)
}
val swizzle: Swizzle get() = Swizzle()
}
fun vecOf(x: Short, y: Short, z: Short, w: Short): ShortVec4 = ShortVec4(x, y, z, w)
operator fun Short.plus(rhs: ShortVec4): IntVec4 = IntVec4(this + rhs.x, this + rhs.y, this + rhs.z, this + rhs.w)
operator fun Short.minus(rhs: ShortVec4): IntVec4 = IntVec4(this - rhs.x, this - rhs.y, this - rhs.z, this - rhs.w)
operator fun Short.times(rhs: ShortVec4): IntVec4 = IntVec4(this * rhs.x, this * rhs.y, this * rhs.z, this * rhs.w)
operator fun Short.div(rhs: ShortVec4): IntVec4 = IntVec4(this / rhs.x, this / rhs.y, this / rhs.z, this / rhs.w)
operator fun Short.rem(rhs: ShortVec4): IntVec4 = IntVec4(this % rhs.x, this % rhs.y, this % rhs.z, this % rhs.w)
| mit | 214caf9d0b888104705236f3e528fc01 | 64.250847 | 134 | 0.607122 | 3.119268 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/database/tables/CategoryTable.kt | 2 | 514 | package eu.kanade.tachiyomi.data.database.tables
object CategoryTable {
const val TABLE = "categories"
const val COL_ID = "_id"
const val COL_NAME = "name"
const val COL_ORDER = "sort"
const val COL_FLAGS = "flags"
val createTableQuery: String
get() =
"""CREATE TABLE $TABLE(
$COL_ID INTEGER NOT NULL PRIMARY KEY,
$COL_NAME TEXT NOT NULL,
$COL_ORDER INTEGER NOT NULL,
$COL_FLAGS INTEGER NOT NULL
)"""
}
| apache-2.0 | dd6c30cd13431ba97f2ceb523a2b54b3 | 21.347826 | 49 | 0.571984 | 4.145161 | false | false | false | false |
octarine-noise/BetterFoliage | src/main/kotlin/mods/betterfoliage/client/chunk/Overlay.kt | 1 | 5470 | package mods.betterfoliage.client.chunk
import mods.betterfoliage.client.Client
import net.minecraft.block.state.IBlockState
import net.minecraft.client.multiplayer.WorldClient
import net.minecraft.entity.Entity
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.SoundCategory
import net.minecraft.util.SoundEvent
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.ChunkPos
import net.minecraft.world.IBlockAccess
import net.minecraft.world.IWorldEventListener
import net.minecraft.world.World
import net.minecraft.world.chunk.EmptyChunk
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.event.world.ChunkEvent
import net.minecraftforge.event.world.WorldEvent
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
import org.apache.logging.log4j.Level
/**
* Represents some form of arbitrary non-persistent data that can be calculated and cached for each block position
*/
interface ChunkOverlayLayer<T> {
abstract fun calculate(world: IBlockAccess, pos: BlockPos): T
abstract fun onBlockUpdate(world: IBlockAccess, pos: BlockPos)
}
/**
* Query, lazy calculation and lifecycle management of multiple layers of chunk overlay data.
*/
object ChunkOverlayManager : IBlockUpdateListener {
init {
Client.log(Level.INFO, "Initializing client overlay manager")
MinecraftForge.EVENT_BUS.register(this)
}
val chunkData = mutableMapOf<ChunkPos, ChunkOverlayData>()
val layers = mutableListOf<ChunkOverlayLayer<*>>()
/**
* Get the overlay data for a given layer and position
*
* @param layer Overlay layer to query
* @param world World to use if calculation of overlay value is necessary
* @param pos Block position
*/
fun <T> get(layer: ChunkOverlayLayer<T>, world: IBlockAccess, pos: BlockPos): T? {
val data = chunkData[ChunkPos(pos)] ?: return null
data.get(layer, pos).let { value ->
if (value !== ChunkOverlayData.UNCALCULATED) return value
val newValue = layer.calculate(world, pos)
data.set(layer, pos, newValue)
return newValue
}
}
/**
* Clear the overlay data for a given layer and position
*
* @param layer Overlay layer to clear
* @param pos Block position
*/
fun <T> clear(layer: ChunkOverlayLayer<T>, pos: BlockPos) {
chunkData[ChunkPos(pos)]?.clear(layer, pos)
}
override fun notifyBlockUpdate(world: World, pos: BlockPos, oldState: IBlockState, newState: IBlockState, flags: Int) {
if (chunkData.containsKey(ChunkPos(pos))) layers.forEach { layer -> layer.onBlockUpdate(world, pos) }
}
@SubscribeEvent
fun handleLoadWorld(event: WorldEvent.Load) {
if (event.world is WorldClient) {
event.world.addEventListener(this)
}
}
@SubscribeEvent
fun handleLoadChunk(event: ChunkEvent.Load) {
if (event.world is WorldClient && event.chunk !is EmptyChunk) {
chunkData[event.chunk.pos] = ChunkOverlayData(layers)
}
}
@SubscribeEvent
fun handleUnloadChunk(event: ChunkEvent.Unload) {
if (event.world is WorldClient) {
chunkData.remove(event.chunk.pos)
}
}
}
class ChunkOverlayData(layers: List<ChunkOverlayLayer<*>>) {
val BlockPos.isValid: Boolean get() = y in validYRange
val rawData = layers.associateWith { emptyOverlay() }
fun <T> get(layer: ChunkOverlayLayer<T>, pos: BlockPos): T? = if (pos.isValid) rawData[layer]?.get(pos.x and 15)?.get(pos.z and 15)?.get(pos.y) as T? else null
fun <T> set(layer: ChunkOverlayLayer<T>, pos: BlockPos, data: T) = if (pos.isValid) rawData[layer]?.get(pos.x and 15)?.get(pos.z and 15)?.set(pos.y, data) else null
fun <T> clear(layer: ChunkOverlayLayer<T>, pos: BlockPos) = if (pos.isValid) rawData[layer]?.get(pos.x and 15)?.get(pos.z and 15)?.set(pos.y, UNCALCULATED) else null
companion object {
val UNCALCULATED = object {}
fun emptyOverlay() = Array(16) { Array(16) { Array<Any?>(256) { UNCALCULATED }}}
val validYRange = 0 until 256
}
}
/**
* IWorldEventListener helper subclass
* No-op for everything except notifyBlockUpdate()
*/
interface IBlockUpdateListener : IWorldEventListener {
override fun playSoundToAllNearExcept(player: EntityPlayer?, soundIn: SoundEvent, category: SoundCategory, x: Double, y: Double, z: Double, volume: Float, pitch: Float) {}
override fun onEntityAdded(entityIn: Entity) {}
override fun broadcastSound(soundID: Int, pos: BlockPos, data: Int) {}
override fun playEvent(player: EntityPlayer?, type: Int, blockPosIn: BlockPos, data: Int) {}
override fun onEntityRemoved(entityIn: Entity) {}
override fun notifyLightSet(pos: BlockPos) {}
override fun spawnParticle(particleID: Int, ignoreRange: Boolean, xCoord: Double, yCoord: Double, zCoord: Double, xSpeed: Double, ySpeed: Double, zSpeed: Double, vararg parameters: Int) {}
override fun spawnParticle(id: Int, ignoreRange: Boolean, minimiseParticleLevel: Boolean, x: Double, y: Double, z: Double, xSpeed: Double, ySpeed: Double, zSpeed: Double, vararg parameters: Int) {}
override fun playRecord(soundIn: SoundEvent?, pos: BlockPos) {}
override fun sendBlockBreakProgress(breakerId: Int, pos: BlockPos, progress: Int) {}
override fun markBlockRangeForRenderUpdate(x1: Int, y1: Int, z1: Int, x2: Int, y2: Int, z2: Int) {}
}
| mit | d1036f5848e1fe8db434e0d87fb9f693 | 43.112903 | 201 | 0.709324 | 4.007326 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/egl/src/templates/kotlin/egl/templates/EXT_device_openwf.kt | 4 | 3459 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package egl.templates
import egl.*
import org.lwjgl.generator.*
val EXT_device_openwf = "EXTDeviceOpenWF".nativeClassEGL("EXT_device_openwf", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
Increasingly, EGL and its client APIs are being used in place of "native" rendering APIs to implement the basic graphics functionality of native
windowing systems. This creates demand for a method to initialize EGL displays and surfaces directly on top of native GPU or device objects rather than
native window system objects. The mechanics of enumerating the underlying native devices and constructing EGL displays and surfaces from them have been
solved in various platform and implementation- specific ways. The EGL device family of extensions offers a standardized framework for bootstrapping EGL
without the use of any underlying "native" APIs or functionality.
These extensions define how to map device and output handles between EGL and OpenWF Display. An EGL implementation which provides these extensions must
have access to sufficient knowledge of the OpenWF implementation to be able to perform these mappings. No requirements are imposed on how this
information is obtained, nor does this support have any implications for how EGL devices and outputs are implemented. An implementation which supports
these extensions may support other low level device interfaces, such as DRM/KMS, as well.
Requires ${EXT_device_base.link}.
"""
IntConstant(
"",
"OPENWF_DEVICE_ID_EXT"..0x3237,
"OPENWF_DEVICE_EXT"..0x333D
)
}
val EXT_output_openwf = "EXTOutputOpenWF".nativeClassEGL("EXT_output_openwf", postfix = EXT) {
documentation =
"""
Native bindings to the ${registryLink("EXT", "EGL_EXT_device_openwf")} extension.
Increasingly, EGL and its client APIs are being used in place of "native" rendering APIs to implement the basic graphics functionality of native
windowing systems. This creates demand for a method to initialize EGL displays and surfaces directly on top of native GPU or device objects rather than
native window system objects. The mechanics of enumerating the underlying native devices and constructing EGL displays and surfaces from them have been
solved in various platform and implementation- specific ways. The EGL device family of extensions offers a standardized framework for bootstrapping EGL
without the use of any underlying "native" APIs or functionality.
These extensions define how to map device and output handles between EGL and OpenWF Display. An EGL implementation which provides these extensions must
have access to sufficient knowledge of the OpenWF implementation to be able to perform these mappings. No requirements are imposed on how this
information is obtained, nor does this support have any implications for how EGL devices and outputs are implemented. An implementation which supports
these extensions may support other low level device interfaces, such as DRM/KMS, as well.
Requires ${EXT_output_base.link}.
"""
IntConstant(
"",
"OPENWF_PIPELINE_ID_EXT"..0x3238,
"OPENWF_PORT_ID_EXT"..0x3239
)
} | bsd-3-clause | 4a9af0f9e0d0ace57c559565d98f5d6b | 54.806452 | 159 | 0.738364 | 5.109306 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/onthisday/OnThisDayCardView.kt | 1 | 8063 | package org.wikipedia.feed.onthisday
import android.app.Activity
import android.content.Context
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.FeedFunnel
import org.wikipedia.databinding.ViewCardOnThisDayBinding
import org.wikipedia.feed.model.CardType
import org.wikipedia.feed.view.CardFooterView
import org.wikipedia.feed.view.DefaultFeedCardView
import org.wikipedia.feed.view.FeedAdapter
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.readinglist.AddToReadingListDialog
import org.wikipedia.readinglist.LongPressMenu
import org.wikipedia.readinglist.MoveToReadingListDialog
import org.wikipedia.readinglist.ReadingListBehaviorsUtil
import org.wikipedia.readinglist.database.ReadingListPage
import org.wikipedia.util.DateUtil
import org.wikipedia.util.StringUtil
import org.wikipedia.util.TransitionUtil
class OnThisDayCardView(context: Context) : DefaultFeedCardView<OnThisDayCard>(context), CardFooterView.Callback {
private val binding = ViewCardOnThisDayBinding.inflate(LayoutInflater.from(context), this, true)
private val funnel = FeedFunnel(WikipediaApp.getInstance())
private val bottomSheetPresenter = ExclusiveBottomSheetPresenter()
private var age = 0
init {
binding.clickContainer.setOnClickListener { view -> onCardClicked(view) }
binding.eventLayout.year.setOnClickListener { view -> onCardClicked(view) }
}
override fun onFooterClicked() {
card?.let {
funnel.cardClicked(CardType.ON_THIS_DAY, it.wikiSite().languageCode())
val options = ActivityOptionsCompat.makeSceneTransitionAnimation((context as Activity),
binding.cardHeader.titleView, context.getString(R.string.transition_on_this_day))
context.startActivity(OnThisDayActivity.newIntent(context, age, -1,
it.wikiSite(), InvokeSource.ON_THIS_DAY_CARD_FOOTER), options.toBundle())
}
}
override var callback: FeedAdapter.Callback? = null
set(value) {
field = value
binding.cardHeader.setCallback(value)
}
override var card: OnThisDayCard? = null
set(value) {
field = value
value?.let {
age = it.age
setLayoutDirectionByWikiSite(it.wikiSite(), binding.rtlContainer)
binding.eventLayout.yearsText.text = DateUtil.getYearDifferenceString(it.year())
updateOtdEventUI(it)
header(it)
footer(it)
}
}
private fun header(card: OnThisDayCard) {
binding.cardHeader
.setTitle(card.title())
.setLangCode(card.wikiSite().languageCode())
.setCard(card)
.setCallback(callback)
binding.eventLayout.text.text = card.text()
binding.eventLayout.year.text = DateUtil.yearToStringWithEra(card.year())
}
private fun footer(card: OnThisDayCard) {
binding.eventLayout.pagesIndicator.visibility = GONE
binding.cardFooterView.setFooterActionText(
card.footerActionText(),
card.wikiSite().languageCode()
)
binding.cardFooterView.callback = this
}
private fun onCardClicked(view: View) {
card?.let {
val isYearClicked = view.id == R.id.year
funnel.cardClicked(CardType.ON_THIS_DAY, it.wikiSite().languageCode())
val options = ActivityOptionsCompat.makeSceneTransitionAnimation((context as Activity),
binding.cardHeader.titleView, context.getString(R.string.transition_on_this_day))
context.startActivity(OnThisDayActivity.newIntent(context, age, if (isYearClicked) it.year() else -1, it.wikiSite(),
if (isYearClicked) InvokeSource.ON_THIS_DAY_CARD_YEAR else InvokeSource.ON_THIS_DAY_CARD_BODY), options.toBundle()
)
}
}
private fun updateOtdEventUI(card: OnThisDayCard) {
binding.eventLayout.pagesPager.visibility = GONE
card.pages()?.let { pages ->
binding.eventLayout.page.root.visibility = VISIBLE
val chosenPage = pages.find { it.thumbnailUrl != null }
chosenPage?.let { page ->
if (page.thumbnailUrl.isNullOrEmpty()) {
binding.eventLayout.page.image.visibility = GONE
} else {
binding.eventLayout.page.image.visibility = VISIBLE
binding.eventLayout.page.image.loadImage(Uri.parse(page.thumbnailUrl))
}
binding.eventLayout.page.description.text = page.description
binding.eventLayout.page.description.visibility =
if (page.description.isNullOrEmpty()) GONE else VISIBLE
binding.eventLayout.page.title.maxLines =
if (page.description.isNullOrEmpty()) 2 else 1
binding.eventLayout.page.title.text = StringUtil.fromHtml(page.displayTitle)
binding.eventLayout.page.root.setOnClickListener {
callback?.onSelectPage(card,
HistoryEntry(page.getPageTitle(card.wikiSite()), HistoryEntry.SOURCE_ON_THIS_DAY_CARD),
TransitionUtil.getSharedElements(context, binding.eventLayout.page.image)
)
}
binding.eventLayout.page.root.setOnLongClickListener { view ->
val pageTitle = page.getPageTitle(card.wikiSite())
val entry = HistoryEntry(pageTitle, HistoryEntry.SOURCE_ON_THIS_DAY_CARD)
LongPressMenu(view, true, object : LongPressMenu.Callback {
override fun onOpenLink(entry: HistoryEntry) {
callback?.onSelectPage(card, entry, TransitionUtil.getSharedElements(context, binding.eventLayout.page.image))
}
override fun onOpenInNewTab(entry: HistoryEntry) {
callback?.onSelectPage(card, entry, true)
}
override fun onAddRequest(entry: HistoryEntry, addToDefault: Boolean) {
if (addToDefault) {
ReadingListBehaviorsUtil.addToDefaultList(context as AppCompatActivity, entry.title,
InvokeSource.ON_THIS_DAY_CARD_BODY) { readingListId ->
bottomSheetPresenter.show((context as AppCompatActivity).supportFragmentManager,
MoveToReadingListDialog.newInstance(readingListId, entry.title, InvokeSource.ON_THIS_DAY_CARD_BODY))
}
} else {
bottomSheetPresenter.show((context as AppCompatActivity).supportFragmentManager,
AddToReadingListDialog.newInstance(entry.title, InvokeSource.ON_THIS_DAY_CARD_BODY)
)
}
}
override fun onMoveRequest(page: ReadingListPage?, entry: HistoryEntry) {
page?.let {
bottomSheetPresenter.show((context as AppCompatActivity).supportFragmentManager,
MoveToReadingListDialog.newInstance(it.listId, entry.title, InvokeSource.ON_THIS_DAY_CARD_BODY)
)
}
}
}).show(entry)
true
}
}
} ?: run {
binding.eventLayout.page.root.visibility = GONE
}
}
}
| apache-2.0 | 9eca854639e9e7ada36d61b959895f01 | 47.281437 | 144 | 0.621977 | 5.276832 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/androidTest/java/org/hisp/dhis/android/core/arch/db/access/internal/DatabaseFromMigrationsIntegrationShould.kt | 1 | 4237 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.db.access.internal
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth.assertThat
import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter
import org.hisp.dhis.android.core.arch.db.cursors.internal.CursorExecutorImpl
import org.hisp.dhis.android.core.arch.storage.internal.InMemorySecureStore
import org.junit.AfterClass
import org.junit.BeforeClass
import org.junit.Test
class DatabaseFromMigrationsIntegrationShould {
companion object {
private const val DB_NAME_1 = "database-from-migrations-integration-should-1.db"
private const val DB_NAME_2 = "database-from-migrations-integration-should-2.db"
private lateinit var databaseAdapterFactory: DatabaseAdapterFactory
private val context = InstrumentationRegistry.getInstrumentation().context
@BeforeClass
@JvmStatic
fun setUpClass() {
deleteDatabases()
databaseAdapterFactory = DatabaseAdapterFactory.create(context, InMemorySecureStore())
}
@AfterClass
@JvmStatic
fun tearDownClass() {
deleteDatabases()
}
private fun deleteDatabases() {
context.deleteDatabase(DB_NAME_1)
context.deleteDatabase(DB_NAME_2)
}
}
@Test
fun ensure_db_from_snapshots_and_from_migrations_have_the_same_schema() {
val databaseAdapter = databaseAdapterFactory.newParentDatabaseAdapter()
createDb(databaseAdapter, DB_NAME_1)
val schema1 = getSchema(databaseAdapter)
DatabaseMigrationExecutor.USE_SNAPSHOT = false
createDb(databaseAdapter, DB_NAME_2)
val schema2 = getSchema(databaseAdapter)
databaseAdapter.close()
val diff1 = schema1 - schema2
val diff2 = schema2 - schema1
assertThat(diff1).isEmpty()
assertThat(diff2).isEmpty()
}
private fun createDb(databaseAdapter: DatabaseAdapter, name: String) {
databaseAdapterFactory.createOrOpenDatabase(databaseAdapter, name, false)
}
private fun getSchema(databaseAdapter: DatabaseAdapter): List<SchemaRow> {
val cursor = databaseAdapter.rawQuery("SELECT name, sql FROM sqlite_master ORDER BY name")
val list = mutableListOf<SchemaRow>()
val cursorExecutor = CursorExecutorImpl { c -> SchemaRow(c.getString(0), c.getString(1)) }
cursorExecutor.addObjectsToCollection(cursor, list)
return list.toList().map { row -> row.copy(sql = row.sql?.replace("\"", "")) }
}
private data class SchemaRow(val name: String, val sql: String?)
}
| bsd-3-clause | ce232661fe1df2f5a813b022d4ed73ae | 40.950495 | 98 | 0.726221 | 4.620502 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/multiFileIntentions/moveToCompanion/moveInnerClass/before/test.kt | 13 | 967 | package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class X {
}
inner class OuterY
fun outerFoo(n: Int) {}
val outerBar = 1
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
inner class <caret>B {
fun test() {
X()
Y()
foo(bar)
1.extFoo(1.extBar)
OuterY()
outerFoo(outerBar)
[email protected]()
[email protected]([email protected])
O.Y()
O.foo(O.bar)
with (O) {
Y()
foo(bar)
1.extFoo(1.extBar)
}
}
}
} | apache-2.0 | 612844c2a41a457738d8825b278a911e | 14.125 | 75 | 0.402275 | 3.662879 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/training/standardround/StandardRoundListFragment.kt | 1 | 9886 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.features.training.standardround
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.EditText
import android.widget.ImageView
import androidx.appcompat.widget.SearchView
import androidx.collection.LongSparseArray
import androidx.databinding.DataBindingUtil
import com.afollestad.materialdialogs.MaterialDialog
import com.evernote.android.state.State
import de.dreier.mytargets.R
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.base.adapters.header.HeaderListAdapter
import de.dreier.mytargets.base.db.StandardRoundFactory
import de.dreier.mytargets.base.fragments.LoaderUICallback
import de.dreier.mytargets.base.fragments.SelectItemFragmentBase
import de.dreier.mytargets.base.navigation.NavigationController.Companion.ITEM
import de.dreier.mytargets.databinding.FragmentListBinding
import de.dreier.mytargets.databinding.ItemStandardRoundBinding
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.shared.models.augmented.AugmentedStandardRound
import de.dreier.mytargets.utils.SlideInItemAnimator
import de.dreier.mytargets.utils.ToolbarUtils
import de.dreier.mytargets.utils.contains
import de.dreier.mytargets.utils.multiselector.OnItemLongClickListener
import de.dreier.mytargets.utils.multiselector.SelectableViewHolder
class StandardRoundListFragment :
SelectItemFragmentBase<AugmentedStandardRound, HeaderListAdapter<AugmentedStandardRound>>(),
SearchView.OnQueryTextListener, OnItemLongClickListener<AugmentedStandardRound> {
@State
var currentSelection: AugmentedStandardRound? = null
private var searchView: SearchView? = null
private lateinit var binding: FragmentListBinding
private val standardRoundDAO = ApplicationInstance.db.standardRoundDAO()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
currentSelection = arguments!!.getParcelable(ITEM)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_list, container, false)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.itemAnimator = SlideInItemAnimator()
val usedRounds = SettingsManager.standardRoundsLastUsed
adapter = StandardRoundListAdapter(context!!, usedRounds)
binding.recyclerView.adapter = adapter
binding.fab.visibility = View.GONE
ToolbarUtils.showUpAsX(this)
binding.fab.visibility = View.VISIBLE
binding.fab.setOnClickListener {
navigationController.navigateToCreateStandardRound()
.fromFab(binding.fab).forResult(NEW_STANDARD_ROUND)
.start()
}
useDoubleClickSelection = true
setHasOptionsMenu(true)
return binding.root
}
override fun onLoad(args: Bundle?): LoaderUICallback {
val data = if (args != null && args.containsKey(KEY_QUERY)) {
val query = args.getString(KEY_QUERY)
standardRoundDAO.getAllSearch("%${query!!.replace(' ', '%')}%")
} else {
standardRoundDAO.loadStandardRounds()
}.map {
AugmentedStandardRound(
it,
standardRoundDAO.loadRoundTemplates(it.id).toMutableList()
)
}
return {
adapter.setList(data)
selectItem(binding.recyclerView, currentSelection!!)
}
}
override fun onResume() {
super.onResume()
if (searchView != null) {
val args = Bundle()
args.putString(KEY_QUERY, searchView!!.query.toString())
reloadData(args)
} else {
reloadData()
}
}
override fun onClick(
holder: SelectableViewHolder<AugmentedStandardRound>,
item: AugmentedStandardRound?
) {
currentSelection = item
super.onClick(holder, item)
}
override fun onLongClick(holder: SelectableViewHolder<AugmentedStandardRound>) {
val item = holder.item!!
if (item.standardRound.club == StandardRoundFactory.CUSTOM) {
navigationController.navigateToEditStandardRound(item)
.forResult(EDIT_STANDARD_ROUND)
.start()
} else {
MaterialDialog.Builder(context!!)
.title(R.string.use_as_template)
.content(R.string.create_copy)
.positiveText(android.R.string.yes)
.negativeText(android.R.string.cancel)
.onPositive { _, _ ->
navigationController
.navigateToEditStandardRound(item)
.forResult(NEW_STANDARD_ROUND)
.start()
}
.show()
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.search, menu)
val searchItem = menu.findItem(R.id.action_search)
searchView = searchItem.actionView as SearchView
searchView!!.setOnQueryTextListener(this)
val closeButton = searchView!!.findViewById<ImageView>(R.id.search_close_btn)
// Set on click listener
closeButton.setOnClickListener {
val et = searchView!!.findViewById<EditText>(R.id.search_src_text)
et.setText("")
searchView!!.setQuery("", false)
searchView!!.onActionViewCollapsed()
searchItem.collapseActionView()
}
}
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(query: String): Boolean {
val args = Bundle()
args.putString(KEY_QUERY, query)
reloadData(args)
return false
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == NEW_STANDARD_ROUND && data != null) {
persistSelection(data.getParcelableExtra(ITEM))
navigationController.setResultSuccess(data)
navigationController.finish()
} else if (requestCode == EDIT_STANDARD_ROUND && data != null) {
if (resultCode == RESULT_OK) {
currentSelection = data.getParcelableExtra(ITEM)
reloadData()
} else if (resultCode == EditStandardRoundFragment.RESULT_STANDARD_ROUND_DELETED) {
currentSelection = standardRoundDAO.loadAugmentedStandardRound(32L)
saveItem()
reloadData()
}
}
}
override fun onSave(): AugmentedStandardRound {
persistSelection(currentSelection!!)
return currentSelection!!
}
private fun persistSelection(standardRound: AugmentedStandardRound) {
val map = SettingsManager.standardRoundsLastUsed
val counter = map.get(standardRound.id)
if (counter == null) {
map.put(standardRound.id, 1)
} else {
map.put(standardRound.id, counter + 1)
}
SettingsManager.standardRoundsLastUsed = map
}
private inner class StandardRoundListAdapter internal constructor(
context: Context,
usedIds: LongSparseArray<Int>
) : HeaderListAdapter<AugmentedStandardRound>(
{ id ->
if (usedIds.contains(id.id)) {
HeaderListAdapter.SimpleHeader(0L, context.getString(R.string.recently_used))
} else {
HeaderListAdapter.SimpleHeader(1L, "")
}
},
compareBy({ usedIds.get(it.standardRound.id) ?: 0 },
{ it.standardRound.name },
{ it.standardRound.id })
) {
override fun getSecondLevelViewHolder(parent: ViewGroup): ViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.item_standard_round, parent, false)
return ViewHolder(itemView)
}
}
private inner class ViewHolder(itemView: View) : SelectableViewHolder<AugmentedStandardRound>(
itemView,
selector, this@StandardRoundListFragment, this@StandardRoundListFragment
) {
private val binding = ItemStandardRoundBinding.bind(itemView)
override fun bindItem(item: AugmentedStandardRound) {
binding.name.text = item.standardRound.name
if (item.id == currentSelection!!.id) {
binding.image.visibility = View.VISIBLE
binding.details.visibility = View.VISIBLE
binding.details.text = item.getDescription(activity!!)
binding.image.setImageDrawable(item.targetDrawable)
} else {
binding.image.visibility = View.GONE
binding.details.visibility = View.GONE
}
}
}
companion object {
private const val NEW_STANDARD_ROUND = 1
private const val EDIT_STANDARD_ROUND = 2
private const val KEY_QUERY = "query"
}
}
| gpl-2.0 | b8f5ac76d8aacc531eb85c3641941f1a | 37.023077 | 98 | 0.659822 | 5.151641 | false | false | false | false |
cbeust/klaxon | klaxon/src/main/kotlin/com/beust/klaxon/DefaultConverter.kt | 1 | 10743 | @file:Suppress("UnnecessaryVariable")
package com.beust.klaxon
import java.lang.reflect.ParameterizedType
import java.lang.reflect.TypeVariable
import java.math.BigDecimal
import java.math.BigInteger
import kotlin.reflect.jvm.jvmErasure
/**
* The default Klaxon converter, which attempts to convert the given value as an enum first and if this fails,
* using reflection to enumerate the fields of the passed object and assign them values.
*/
class DefaultConverter(private val klaxon: Klaxon, private val allPaths: HashMap<String, Any>) : Converter {
override fun canConvert(cls: Class<*>) = true
override fun fromJson(jv: JsonValue): Any? {
val value = jv.inside
val propertyType = jv.propertyClass
val classifier = jv.propertyKClass?.classifier
val result =
when(value) {
is Boolean, is String -> value
is Int -> fromInt(value, propertyType)
is BigInteger, is BigDecimal -> value
is Double ->
if (classifier == Float::class) fromFloat(value.toFloat(), propertyType)
else fromDouble(value, propertyType)
is Float ->
if (classifier == Double::class) fromDouble(value.toDouble(), propertyType)
else fromFloat(value, propertyType)
is Long ->
when (classifier) {
Double::class -> fromDouble(value.toDouble(), propertyType)
Float::class -> fromFloat(value.toFloat(), propertyType)
else -> value
}
is Collection<*> -> fromCollection(value, jv)
is JsonObject -> fromJsonObject(value, jv)
null -> null
else -> {
throw KlaxonException("Don't know how to convert $value")
}
}
return result
}
override fun toJson(value: Any): String {
fun joinToString(list: Collection<*>, open: String, close: String)
= open + list.joinToString(", ") + close
val result = when (value) {
is String, is Enum<*> -> "\"" + Render.escapeString(value.toString()) + "\""
is Double, is Float, is Int, is Boolean, is Long -> value.toString()
is Array<*> -> {
val elements = value.map { klaxon.toJsonString(it) }
joinToString(elements, "[", "]")
}
is Collection<*> -> {
val elements = value.map { klaxon.toJsonString(it) }
joinToString(elements, "[", "]")
}
is Map<*, *> -> {
val valueList = arrayListOf<String>()
value.entries.forEach { entry ->
val jsonValue =
if (entry.value == null) "null"
else klaxon.toJsonString(entry.value as Any)
valueList.add("\"${entry.key}\": $jsonValue")
}
joinToString(valueList, "{", "}")
}
is BigInteger -> value.toString()
else -> {
val valueList = arrayListOf<String>()
val properties = Annotations.findNonIgnoredProperties(value::class, klaxon.propertyStrategies)
properties.forEach { prop ->
val getValue = prop.getter.call(value)
val getAnnotation = Annotations.findJsonAnnotation(value::class, prop.name)
// Use instance settings only when no local settings exist
if (getValue != null
|| (getAnnotation?.serializeNull == true) // Local settings have precedence to instance settings
|| (getAnnotation == null && klaxon.instanceSettings.serializeNull)
) {
val jsonValue = klaxon.toJsonString(getValue, prop)
val fieldName = Annotations.retrieveJsonFieldName(klaxon, value::class, prop)
valueList.add("\"$fieldName\" : $jsonValue")
}
}
joinToString(valueList, "{", "}")
}
}
return result
}
private fun fromInt(value: Int, propertyType: java.lang.reflect.Type?): Any {
// If the value is an Int and the property is a Long, widen it
val isLong = java.lang.Long::class.java == propertyType || Long::class.java == propertyType
val result: Any = when {
isLong -> value.toLong()
propertyType == BigDecimal::class.java -> BigDecimal(value)
else -> value
}
return result
}
private fun fromDouble(value: Double, propertyType: java.lang.reflect.Type?): Any {
return if (propertyType == BigDecimal::class.java) {
BigDecimal(value)
} else {
value
}
}
private fun fromFloat(value: Float, propertyType: java.lang.reflect.Type?): Any {
return if (propertyType == BigDecimal::class.java) {
BigDecimal(value.toDouble())
} else {
value
}
}
private fun fromCollection(value: Collection<*>, jv: JsonValue): Any {
val kt = jv.propertyKClass
val jt = jv.propertyClass
val convertedCollection = value.map {
// Try to find a converter for the element type of the collection
if (jt is ParameterizedType) {
val typeArgument = jt.actualTypeArguments[0]
val converter =
when (typeArgument) {
is Class<*> -> klaxon.findConverterFromClass(typeArgument, null)
is ParameterizedType -> {
when (val ta = typeArgument.actualTypeArguments[0]) {
is Class<*> -> klaxon.findConverterFromClass(ta, null)
is ParameterizedType -> klaxon.findConverterFromClass(ta.rawType.javaClass, null)
else -> throw KlaxonException("SHOULD NEVER HAPPEN")
}
}
else -> throw IllegalArgumentException("Should never happen")
}
val kTypeArgument = kt?.arguments!![0].type
converter.fromJson(JsonValue(it, typeArgument, kTypeArgument, klaxon))
} else {
if (it != null) {
val converter = klaxon.findConverter(it)
converter.fromJson(JsonValue(it, jt, kt, klaxon))
} else {
throw KlaxonException("Don't know how to convert null value in array $jv")
}
}
}
val result =
when {
Annotations.isSet(jt) -> {
convertedCollection.toSet()
}
Annotations.isArray(kt) -> {
val componentType = (jt as Class<*>).componentType
val array = java.lang.reflect.Array.newInstance(componentType, convertedCollection.size)
convertedCollection.indices.forEach { i ->
java.lang.reflect.Array.set(array, i, convertedCollection[i])
}
array
}
else -> {
convertedCollection
}
}
return result
}
private fun fromJsonObject(value: JsonObject, jv: JsonValue): Any {
val jt = jv.propertyClass
val result =
if (jt is ParameterizedType) {
val isMap = Map::class.java.isAssignableFrom(jt.rawType as Class<*>)
val isCollection = List::class.java.isAssignableFrom(jt.rawType as Class<*>)
when {
isMap -> {
// Map
val result = linkedMapOf<String, Any?>()
value.entries.forEach { kv ->
val key = kv.key
kv.value?.let { mv ->
val typeValue = jt.actualTypeArguments[1]
val converter = klaxon.findConverterFromClass(
typeValue.javaClass, null)
val convertedValue = converter.fromJson(
JsonValue(mv, typeValue, jv.propertyKClass!!.arguments[1].type,
klaxon))
result[key] = convertedValue
}
}
result
}
isCollection -> {
when(val type =jt.actualTypeArguments[0]) {
is Class<*> -> {
val cls = jt.actualTypeArguments[0] as Class<*>
klaxon.fromJsonObject(value, cls, cls.kotlin)
}
is ParameterizedType -> {
val result2 = JsonObjectConverter(klaxon, HashMap()).fromJson(value,
jv.propertyKClass!!.jvmErasure)
result2
}
else -> {
throw IllegalArgumentException("Couldn't interpret type $type")
}
}
}
else -> throw KlaxonException("Don't know how to convert the JsonObject with the following keys" +
":\n $value")
}
} else {
if (jt is Class<*>) {
if (jt.isArray) {
val typeValue = jt.componentType
klaxon.fromJsonObject(value, typeValue, typeValue.kotlin)
} else {
JsonObjectConverter(klaxon, allPaths).fromJson(jv.obj!!, jv.propertyKClass!!.jvmErasure)
}
} else {
val typeName: Any? =
if (jt is TypeVariable<*>) {
jt.genericDeclaration
} else {
jt
}
throw IllegalArgumentException("Generic type not supported: $typeName")
}
}
return result
}
}
| apache-2.0 | 9ab7a254e971f8f4936b09bf5b2e2769 | 43.028689 | 120 | 0.477986 | 5.991634 | false | false | false | false |
auricgoldfinger/Memento-Namedays | android_mobile/src/main/java/com/alexstyl/specialdates/addevent/ui/DeviceContactsFilter.kt | 3 | 1359 | package com.alexstyl.specialdates.addevent.ui
import android.widget.Filter
import com.alexstyl.specialdates.addevent.ContactsSearch
import com.alexstyl.specialdates.contact.Contact
import java.util.ArrayList
internal abstract class DeviceContactsFilter(private val contactsSearch: ContactsSearch) : Filter() {
override fun performFiltering(constraint: CharSequence?): Filter.FilterResults {
if (constraint == null || constraint.isEmpty()) {
return emptyResults()
}
val searchQuery = constraint.trim { it <= ' ' }.toString()
val contacts = contactsSearch.searchForContacts(searchQuery, LOAD_A_SINGLE_CONTACT)
val filterResults = Filter.FilterResults()
filterResults.values = contacts
filterResults.count = contacts.size
return filterResults
}
private fun emptyResults(): Filter.FilterResults {
val filterResults = Filter.FilterResults()
filterResults.values = ArrayList<Any>()
filterResults.count = 0
return filterResults
}
override fun publishResults(constraint: CharSequence?, results: Filter.FilterResults) {
onContactsFiltered(results.values as List<Contact>)
}
abstract fun onContactsFiltered(contacts: List<Contact>)
companion object {
private const val LOAD_A_SINGLE_CONTACT = 1
}
}
| mit | 282c7b7a9626145bafe4b68f05413234 | 32.146341 | 101 | 0.710081 | 5.052045 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/ext/spock/interactions.kt | 2 | 2474 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.ext.spock
import com.intellij.psi.util.parents
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.RIGHT_SHIFT_SIGN
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementTypes.RIGHT_SHIFT_UNSIGNED_SIGN
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.isExpressionStatement
fun GrExpression.isInteractionPart(): Boolean {
return isInteractionDown() &&
isInteractionUp() ||
isInteractionCallUp()
}
private fun GrExpression.isInteractionDown(): Boolean {
return this is GrBinaryExpression &&
isInteractionDown()
}
private fun GrBinaryExpression.isInteractionDown(): Boolean {
return isInteractionWithResponseDown() ||
isInteractionWithCardinalityDown()
}
private fun GrBinaryExpression.isInteractionWithResponseDown(): Boolean {
return isRightShift() &&
(leftOperand.isInteractionDown() ||
leftOperand.isInteractionCall())
}
private fun GrBinaryExpression.isInteractionWithCardinalityDown(): Boolean {
return isMultiplication() &&
rightOperand.isInteractionCall()
}
/**
* org.spockframework.compiler.InteractionRewriter#parseCall
*/
private fun GrExpression?.isInteractionCall(): Boolean {
return this is GrReferenceExpression || this is GrMethodCall || this is GrNewExpression
}
private fun GrExpression.isInteractionUp(): Boolean {
for ((lastParent, parent) in parents().zipWithNext()) {
if (parent is GrBinaryExpression) {
if (parent.leftOperand !== lastParent || !parent.isRightShift()) {
return false
}
else {
continue
}
}
else {
return isExpressionStatement(lastParent)
}
}
return false
}
private fun GrExpression.isInteractionCallUp(): Boolean {
return isInteractionCall() && parent.let {
it is GrBinaryExpression && it.rightOperand === this && it.isMultiplication() && it.isInteractionUp()
}
}
private fun GrBinaryExpression.isRightShift(): Boolean = operationTokenType.let {
it === RIGHT_SHIFT_SIGN ||
it === RIGHT_SHIFT_UNSIGNED_SIGN
}
private fun GrBinaryExpression.isMultiplication(): Boolean {
return operationTokenType === GroovyElementTypes.T_STAR
}
| apache-2.0 | 9cdd8237d87a74db5518751dd7f61b25 | 31.986667 | 140 | 0.745352 | 4.598513 | false | false | false | false |
paplorinc/intellij-community | java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/inference/ParameterNullityInference.kt | 6 | 8922 | // 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.codeInspection.dataFlow.inference
import com.intellij.lang.LighterAST
import com.intellij.lang.LighterASTNode
import com.intellij.psi.CommonClassNames
import com.intellij.psi.JavaTokenType
import com.intellij.psi.impl.source.JavaLightTreeUtil
import com.intellij.psi.impl.source.tree.ElementType
import com.intellij.psi.impl.source.tree.JavaElementType.*
import com.intellij.psi.impl.source.tree.LightTreeUtil
import com.intellij.psi.tree.TokenSet
import java.util.*
fun inferNotNullParameters(tree: LighterAST, method: LighterASTNode, statements: List<LighterASTNode>): BitSet {
val parameterNames = getParameterNames(tree, method)
return inferNotNullParameters(tree, parameterNames, statements)
}
private fun inferNotNullParameters(tree: LighterAST, parameterNames: List<String?>, statements: List<LighterASTNode>): BitSet {
val canBeNulls = parameterNames.filterNotNullTo(HashSet())
if (canBeNulls.isEmpty()) return BitSet()
val notNulls = HashSet<String>()
val queue = ArrayDeque<LighterASTNode>(statements)
while (queue.isNotEmpty() && canBeNulls.isNotEmpty()) {
val element = queue.removeFirst()
val type = element.tokenType
when (type) {
CONDITIONAL_EXPRESSION, EXPRESSION_STATEMENT -> JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
RETURN_STATEMENT -> {
queue.clear()
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
FOR_STATEMENT -> {
val condition = JavaLightTreeUtil.findExpressionChild(tree, element)
queue.clear()
if (condition != null) {
queue.addFirst(condition)
LightTreeUtil.firstChildOfType(tree, element, ElementType.JAVA_STATEMENT_BIT_SET)?.let(queue::addFirst)
}
else {
// no condition == endless loop: we may analyze body (at least until break/return/if/etc.)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
WHILE_STATEMENT -> {
queue.clear()
val expression = JavaLightTreeUtil.findExpressionChild(tree, element)
if (expression?.tokenType == LITERAL_EXPRESSION &&
LightTreeUtil.firstChildOfType(tree, expression, JavaTokenType.TRUE_KEYWORD) != null) {
// while(true) == endless loop: we may analyze body (at least until break/return/if/etc.)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
} else {
dereference(tree, expression, canBeNulls, notNulls, queue)
}
}
FOREACH_STATEMENT, SWITCH_STATEMENT, IF_STATEMENT, THROW_STATEMENT -> {
queue.clear()
val expression = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, expression, canBeNulls, notNulls, queue)
}
BINARY_EXPRESSION, POLYADIC_EXPRESSION -> {
if (LightTreeUtil.firstChildOfType(tree, element, TokenSet.create(JavaTokenType.ANDAND, JavaTokenType.OROR)) != null) {
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
else {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
EMPTY_STATEMENT, ASSERT_STATEMENT, DO_WHILE_STATEMENT, DECLARATION_STATEMENT, BLOCK_STATEMENT -> {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
SYNCHRONIZED_STATEMENT -> {
val sync = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, sync, canBeNulls, notNulls, queue)
LightTreeUtil.firstChildOfType(tree, element, CODE_BLOCK)?.let(queue::addFirst)
}
FIELD, PARAMETER, LOCAL_VARIABLE -> {
canBeNulls.remove(JavaLightTreeUtil.getNameIdentifierText(tree, element))
JavaLightTreeUtil.findExpressionChild(tree, element)?.let(queue::addFirst)
}
EXPRESSION_LIST -> {
val children = JavaLightTreeUtil.getExpressionChildren(tree, element)
// When parameter is passed to another method, that method may have "null -> fail" contract,
// so without knowing this we cannot continue inference for the parameter
children.forEach { ignore(tree, it, canBeNulls) }
children.asReversed().forEach(queue::addFirst)
}
ASSIGNMENT_EXPRESSION -> {
val lvalue = JavaLightTreeUtil.findExpressionChild(tree, element)
ignore(tree, lvalue, canBeNulls)
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
ARRAY_ACCESS_EXPRESSION -> JavaLightTreeUtil.getExpressionChildren(tree, element).forEach {
dereference(tree, it, canBeNulls, notNulls, queue)
}
METHOD_REF_EXPRESSION, REFERENCE_EXPRESSION -> {
val qualifier = JavaLightTreeUtil.findExpressionChild(tree, element)
dereference(tree, qualifier, canBeNulls, notNulls, queue)
}
CLASS, METHOD, LAMBDA_EXPRESSION -> {
// Ignore classes, methods and lambda expression bodies as it's not known whether they will be instantiated/executed.
// For anonymous classes argument list, field initializers and instance initialization sections are checked.
}
TRY_STATEMENT -> {
queue.clear()
val canCatchNpe = LightTreeUtil.getChildrenOfType(tree, element, CATCH_SECTION)
.asSequence()
.map { LightTreeUtil.firstChildOfType(tree, it, PARAMETER) }
.filterNotNull()
.map { parameter -> LightTreeUtil.firstChildOfType(tree, parameter, TYPE) }
.any { canCatchNpe(tree, it) }
if (!canCatchNpe) {
LightTreeUtil.getChildrenOfType(tree, element, RESOURCE_LIST).forEach(queue::addFirst)
LightTreeUtil.firstChildOfType(tree, element, CODE_BLOCK)?.let(queue::addFirst)
// stop analysis after first try as we are not sure how execution goes further:
// whether or not it visit catch blocks, etc.
}
}
else -> {
if (ElementType.JAVA_STATEMENT_BIT_SET.contains(type)) {
// Unknown/unprocessed statement: just stop processing the rest of the method
queue.clear()
}
else {
tree.getChildren(element).asReversed().forEach(queue::addFirst)
}
}
}
}
val notNullParameters = BitSet()
parameterNames.forEachIndexed { index, s -> if (notNulls.contains(s)) notNullParameters.set(index) }
return notNullParameters
}
private val NPE_CATCHERS = setOf("Throwable", "Exception", "RuntimeException", "NullPointerException",
CommonClassNames.JAVA_LANG_THROWABLE, CommonClassNames.JAVA_LANG_EXCEPTION,
CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION, CommonClassNames.JAVA_LANG_NULL_POINTER_EXCEPTION)
fun canCatchNpe(tree: LighterAST, type: LighterASTNode?): Boolean {
if (type == null) return false
val codeRef = LightTreeUtil.firstChildOfType(tree, type, JAVA_CODE_REFERENCE)
val name = JavaLightTreeUtil.getNameIdentifierText(tree, codeRef)
if (name == null) {
// Multicatch
return LightTreeUtil.getChildrenOfType(tree, type, TYPE).any { canCatchNpe(tree, it) }
}
return NPE_CATCHERS.contains(name)
}
private fun ignore(tree: LighterAST,
expression: LighterASTNode?,
canBeNulls: HashSet<String>) {
if (expression != null &&
expression.tokenType == REFERENCE_EXPRESSION && JavaLightTreeUtil.findExpressionChild(tree, expression) == null) {
canBeNulls.remove(JavaLightTreeUtil.getNameIdentifierText(tree, expression))
}
}
private fun dereference(tree: LighterAST,
expression: LighterASTNode?,
canBeNulls: HashSet<String>,
notNulls: HashSet<String>,
queue: ArrayDeque<LighterASTNode>) {
if (expression == null) return
if (expression.tokenType == REFERENCE_EXPRESSION && JavaLightTreeUtil.findExpressionChild(tree, expression) == null) {
JavaLightTreeUtil.getNameIdentifierText(tree, expression)?.takeIf(canBeNulls::remove)?.let(notNulls::add)
}
else {
queue.addFirst(expression)
}
}
/**
* Returns list of parameter names. A null in returned list means that either parameter name
* is absent in the source or it's a primitive type (thus nullity inference does not apply).
*/
private fun getParameterNames(tree: LighterAST, method: LighterASTNode): List<String?> {
val parameterList = LightTreeUtil.firstChildOfType(tree, method, PARAMETER_LIST) ?: return emptyList()
val parameters = LightTreeUtil.getChildrenOfType(tree, parameterList, PARAMETER)
return parameters.map {
if (LightTreeUtil.firstChildOfType(tree, it, ElementType.PRIMITIVE_TYPE_BIT_SET) != null) null
else JavaLightTreeUtil.getNameIdentifierText(tree, it)
}
}
| apache-2.0 | af731009f4097442683b345e78f51f22 | 47.227027 | 140 | 0.694239 | 4.820097 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/formatting/visualLayer/VisualFormattingLayerHighlightingPass.kt | 2 | 2250 | // 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.formatting.visualLayer
import com.intellij.codeHighlighting.EditorBoundHighlightingPass
import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory
import com.intellij.codeHighlighting.TextEditorHighlightingPassFactoryRegistrar
import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
class VisualFormattingLayerHighlightingPassFactory : TextEditorHighlightingPassFactory, TextEditorHighlightingPassFactoryRegistrar {
override fun createHighlightingPass(file: PsiFile, editor: Editor) = VisualFormattingLayerHighlightingPass(editor, file)
override fun registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project) {
registrar.registerTextEditorHighlightingPass(this, null, null, false, -1)
}
}
class VisualFormattingLayerHighlightingPass(editor: Editor, file: PsiFile) : EditorBoundHighlightingPass(editor, file, true) {
val service: VisualFormattingLayerService by lazy { VisualFormattingLayerService.getInstance() }
var myVisualFormattingLayerElements: List<VisualFormattingLayerElement>? = null
override fun doCollectInformation(progress: ProgressIndicator) {
//progress.start()
myVisualFormattingLayerElements = service.getVisualFormattingLayerElements(myEditor)
//progress.stop()
}
override fun doApplyInformationToEditor() {
myEditor.inlayModel
.getInlineElementsInRange(0, Int.MAX_VALUE, InlayPresentation::class.java)
.forEach { it.dispose() }
myEditor.inlayModel
.getBlockElementsInRange(0, Int.MAX_VALUE, InlayPresentation::class.java)
.forEach { it.dispose() }
myEditor.foldingModel.runBatchFoldingOperation({
myEditor.foldingModel
.allFoldRegions
.filter { it.getUserData(visualFormattingElementKey) == true }
.forEach { it.dispose() }
}, true, false)
myVisualFormattingLayerElements?.forEach {
it.applyToEditor(myEditor)
}
}
}
| apache-2.0 | cb9405f7727974c1c00c386bdfdf0854 | 39.178571 | 132 | 0.799111 | 5.184332 | false | false | false | false |
google/intellij-community | plugins/stats-collector/src/com/intellij/stats/completion/tracker/CompletionLoggerInitializer.kt | 2 | 6463 | // Copyright 2000-2022 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.stats.completion.tracker
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.completion.ml.experiment.ExperimentInfo
import com.intellij.completion.ml.experiment.ExperimentStatus
import com.intellij.completion.ml.storage.MutableLookupStorage
import com.intellij.completion.ml.tracker.LookupTracker
import com.intellij.internal.statistic.utils.StatisticsUploadAssistant
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.diagnostic.runAndLogException
import com.intellij.openapi.project.Project
import com.intellij.stats.completion.CompletionStatsPolicy
import com.intellij.stats.completion.sender.isCompletionLogsSendAllowed
import kotlin.random.Random
class CompletionLoggerInitializer : LookupTracker() {
companion object {
private const val COMPLETION_EVALUATION_HEADLESS = "completion.evaluation.headless"
private fun shouldInitialize(): Boolean {
val app = ApplicationManager.getApplication()
return app.isEAP && StatisticsUploadAssistant.isSendAllowed()
|| app.isHeadlessEnvironment && java.lang.Boolean.getBoolean(COMPLETION_EVALUATION_HEADLESS)
|| app.isUnitTestMode
}
private val LOGGED_SESSIONS_RATIO: Map<String, Double> = mapOf(
"python" to 0.5,
"scala" to 0.3,
"php" to 0.2,
"kotlin" to 0.2,
"java" to 0.1,
"javascript" to 0.2,
"typescript" to 0.5,
"c/c++" to 0.5,
"c#" to 0.1,
"go" to 0.4
)
}
private val actionListener: LookupActionsListener by lazy { LookupActionsListener.getInstance() }
override fun lookupClosed() {
ApplicationManager.getApplication().assertIsDispatchThread()
actionListener.listener = CompletionPopupListener.DISABLED
}
override fun lookupCreated(lookup: LookupImpl,
storage: MutableLookupStorage) {
ApplicationManager.getApplication().assertIsDispatchThread()
if (!shouldInitialize()) return
val experimentInfo = ExperimentStatus.getInstance().forLanguage(storage.language)
if (sessionShouldBeLogged(experimentInfo, storage.language, lookup.project)) {
val tracker = actionsTracker(lookup, storage, experimentInfo)
actionListener.listener = tracker
lookup.addLookupListener(tracker)
lookup.setPrefixChangeListener(tracker)
storage.markLoggingEnabled()
}
else {
actionListener.listener = CompletionPopupListener.DISABLED
}
}
private fun actionsTracker(lookup: LookupImpl,
storage: MutableLookupStorage,
experimentInfo: ExperimentInfo): CompletionActionsListener {
val logger = CompletionLoggerProvider.getInstance().newCompletionLogger(getLoggingLanguageName(storage.language),
shouldLogElementFeatures(storage.language, lookup.project))
val actionsTracker = CompletionActionsTracker(lookup, storage, logger, experimentInfo)
return LoggerPerformanceTracker(actionsTracker, storage.performanceTracker)
}
private fun shouldLogElementFeatures(language: Language, project: Project): Boolean =
ExperimentStatus.getInstance().forLanguage(language).shouldLogElementFeatures(project)
private fun sessionShouldBeLogged(experimentInfo: ExperimentInfo, language: Language, project: Project): Boolean {
if (CompletionStatsPolicy.isStatsLogDisabled(language) || !getPluginInfo(language::class.java).isSafeToReport()) return false
val application = ApplicationManager.getApplication()
if (application.isUnitTestMode || experimentInfo.shouldLogSessions(project)) return true
if (!isCompletionLogsSendAllowed()) {
return false
}
val logSessionChance = LOGGED_SESSIONS_RATIO.getOrDefault(getLoggingLanguageName(language).toLowerCase(), 1.0)
return Random.nextDouble() < logSessionChance
}
private fun getLoggingLanguageName(language: Language): String {
Language.findLanguageByID("JavaScript")?.let { js ->
if (language.isKindOf(js) && !language.displayName.contains("TypeScript", ignoreCase = true)) {
return "JavaScript"
}
}
Language.findLanguageByID("SQL")?.let { sql ->
if (language.isKindOf(sql)) {
return sql.displayName
}
}
return language.displayName
}
private class LookupActionsListener private constructor(): AnActionListener {
companion object {
private val LOG = logger<LookupActionsListener>()
private val instance = LookupActionsListener()
private var subscribed = false
fun getInstance(): LookupActionsListener {
if (!subscribed) {
ApplicationManager.getApplication().messageBus.connect().subscribe(AnActionListener.TOPIC, instance)
subscribed = true
}
return instance
}
}
private val down by lazy { ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN) }
private val up by lazy { ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP) }
private val backspace by lazy { ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_BACKSPACE) }
var listener: CompletionPopupListener = CompletionPopupListener.DISABLED
override fun afterActionPerformed(action: AnAction, event: AnActionEvent, result: AnActionResult) {
LOG.runAndLogException {
when (action) {
down -> listener.downPressed()
up -> listener.upPressed()
backspace -> listener.afterBackspacePressed()
}
}
}
override fun beforeActionPerformed(action: AnAction, event: AnActionEvent) {
LOG.runAndLogException {
when (action) {
down -> listener.beforeDownPressed()
up -> listener.beforeUpPressed()
backspace -> listener.beforeBackspacePressed()
}
}
}
override fun beforeEditorTyping(c: Char, dataContext: DataContext) {
LOG.runAndLogException {
listener.beforeCharTyped(c)
}
}
}
}
| apache-2.0 | 4e78735eb32d8be9dd2ed51bf1dd7e72 | 40.165605 | 140 | 0.72211 | 5.072998 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/DoubleBangToIfThenIntention.kt | 1 | 4844 | // 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.intentions.branchedTransformations.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.utils.ChooseStringExpression
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.convertToIfNotNullExpression
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.convertToIfNullExpression
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.introduceValueForCondition
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isStableSimpleExpression
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsStatement
class DoubleBangToIfThenIntention : SelfTargetingRangeIntention<KtPostfixExpression>(
KtPostfixExpression::class.java,
KotlinBundle.lazyMessage("replace.expression.with.if.expression")
), LowPriorityAction {
override fun applicabilityRange(element: KtPostfixExpression): TextRange? =
if (element.operationToken == KtTokens.EXCLEXCL && element.baseExpression != null)
element.operationReference.textRange
else
null
override fun applyTo(element: KtPostfixExpression, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val base = KtPsiUtil.safeDeparenthesize(element.baseExpression!!, true)
val expressionText = formatForUseInExceptionArgument(base.text!!)
val psiFactory = KtPsiFactory(element.project)
val defaultException = psiFactory.createExpression("throw NullPointerException()")
val isStatement = element.isUsedAsStatement(element.analyze())
val isStable = base.isStableSimpleExpression()
val ifStatement = if (isStatement)
element.convertToIfNullExpression(base, defaultException)
else {
val qualifiedExpressionForReceiver = element.getQualifiedExpressionForReceiver()
val selectorExpression = qualifiedExpressionForReceiver?.selectorExpression
val thenClause = selectorExpression?.let { psiFactory.createExpressionByPattern("$0.$1", base, it) } ?: base
(qualifiedExpressionForReceiver ?: element).convertToIfNotNullExpression(base, thenClause, defaultException)
}
val thrownExpression = ((if (isStatement) ifStatement.then else ifStatement.`else`) as KtThrowExpression).thrownExpression ?: return
val message = StringUtil.escapeStringCharacters("Expression '$expressionText' must not be null")
val nullPtrExceptionText = "NullPointerException(\"$message\")"
val kotlinNullPtrExceptionText = "KotlinNullPointerException()"
val exceptionLookupExpression = ChooseStringExpression(listOf(nullPtrExceptionText, kotlinNullPtrExceptionText))
val project = element.project
val builder = TemplateBuilderImpl(thrownExpression)
builder.replaceElement(thrownExpression, exceptionLookupExpression)
PsiDocumentManager.getInstance(project).commitDocument(editor.document)
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
editor.caretModel.moveToOffset(thrownExpression.node!!.startOffset)
TemplateManager.getInstance(project).startTemplate(editor, builder.buildInlineTemplate(), object : TemplateEditingAdapter() {
override fun templateFinished(template: Template, brokenOff: Boolean) {
if (!isStable && !isStatement) {
ifStatement.introduceValueForCondition(ifStatement.then!!, editor)
}
}
})
}
private fun formatForUseInExceptionArgument(expressionText: String): String {
val lines = expressionText.split('\n')
return if (lines.size > 1)
lines.first().trim() + " ..."
else
expressionText.trim()
}
}
| apache-2.0 | 1e4c95313e48b5ed45db89f0745daa16 | 54.045455 | 158 | 0.769405 | 5.593533 | false | false | false | false |
apollographql/apollo-android | apollo-gradle-plugin/src/main/kotlin/com/apollographql/apollo3/gradle/internal/DefaultApolloExtension.kt | 1 | 25359 | package com.apollographql.apollo3.gradle.internal
import com.apollographql.apollo3.annotations.ApolloExperimental
import com.apollographql.apollo3.compiler.OperationIdGenerator
import com.apollographql.apollo3.compiler.OperationOutputGenerator
import com.apollographql.apollo3.compiler.PackageNameGenerator
import com.apollographql.apollo3.compiler.TargetLanguage
import com.apollographql.apollo3.compiler.capitalizeFirstLetter
import com.apollographql.apollo3.gradle.api.AndroidProject
import com.apollographql.apollo3.gradle.api.ApolloAttributes
import com.apollographql.apollo3.gradle.api.ApolloExtension
import com.apollographql.apollo3.gradle.api.Service
import com.apollographql.apollo3.gradle.api.androidExtension
import com.apollographql.apollo3.gradle.api.isKotlinMultiplatform
import com.apollographql.apollo3.gradle.api.javaConvention
import com.apollographql.apollo3.gradle.api.kotlinMultiplatformExtension
import com.apollographql.apollo3.gradle.api.kotlinProjectExtension
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.ConfigurationContainer
import org.gradle.api.attributes.Usage
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.provider.Property
import org.gradle.api.tasks.TaskProvider
import org.gradle.util.GradleVersion
import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension
import java.io.File
import java.util.concurrent.Callable
abstract class DefaultApolloExtension(
private val project: Project,
private val defaultService: DefaultService,
) : ApolloExtension, Service by defaultService {
private val services = mutableListOf<DefaultService>()
private val checkVersionsTask: TaskProvider<Task>
private val apolloConfiguration: Configuration
private val rootProvider: TaskProvider<Task>
private var registerDefaultService = true
// Called when the plugin is applied
init {
require(GradleVersion.current() >= GradleVersion.version(MIN_GRADLE_VERSION)) {
"apollo-android requires Gradle version $MIN_GRADLE_VERSION or greater"
}
apolloConfiguration = project.configurations.create(ModelNames.apolloConfiguration()) {
it.isCanBeConsumed = false
it.isCanBeResolved = false
it.attributes {
it.attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class.java, USAGE_APOLLO_METADATA))
}
}
checkVersionsTask = registerCheckVersionsTask()
/**
* An aggregate task to easily generate all models
*/
rootProvider = project.tasks.register(ModelNames.generateApolloSources()) {
it.group = TASK_GROUP
it.description = "Generate Apollo models for all services"
}
/**
* A simple task to be used from the command line to ease the schema download
*/
project.tasks.register(ModelNames.downloadApolloSchema(), ApolloDownloadSchemaTask::class.java) { task ->
task.group = TASK_GROUP
}
/**
* A simple task to be used from the command line to ease the schema upload
*/
project.tasks.register(ModelNames.pushApolloSchema(), ApolloPushSchemaTask::class.java) { task ->
task.group = TASK_GROUP
}
/**
* A simple task to be used from the command line to ease schema conversion
*/
project.tasks.register(ModelNames.convertApolloSchema(), ApolloConvertSchemaTask::class.java) { task ->
task.group = TASK_GROUP
}
project.afterEvaluate {
if (registerDefaultService) {
registerService(defaultService)
} else {
@Suppress("DEPRECATION")
check(defaultService.graphqlSourceDirectorySet.isEmpty
&& defaultService.schemaFile.isPresent.not()
&& defaultService.schemaFiles.isEmpty
&& defaultService.alwaysGenerateTypesMatching.isPresent.not()
&& defaultService.customScalarsMapping.isPresent.not()
&& defaultService.customTypeMapping.isPresent.not()
&& defaultService.excludes.isPresent.not()
&& defaultService.includes.isPresent.not()
&& defaultService.failOnWarnings.isPresent.not()
&& defaultService.generateApolloMetadata.isPresent.not()
&& defaultService.generateAsInternal.isPresent.not()
&& defaultService.codegenModels.isPresent.not()
&& defaultService.generateFragmentImplementations.isPresent.not()
) {
"""
Configuring the default service is ignored if you specify other services, remove your configuration from the root of the apollo {} block:
apollo {
// remove everything at the top level
// add individual services
service("service1") {
// ...
}
service("service2") {
// ...
}
}
""".trimIndent()
}
}
maybeLinkSqlite()
}
}
private fun maybeLinkSqlite() {
val doLink = when (linkSqlite.orNull) {
false -> return // explicit opt-out
true -> true // explicit opt-in
null -> { // default: automatic detection
project.configurations.any {
it.dependencies.any {
// Try to detect if a native version of apollo-normalized-cache-sqlite is in the classpath
it.name.contains("apollo-normalized-cache-sqlite")
&& !it.name.contains("jvm")
&& !it.name.contains("android")
}
}
}
}
if (doLink) {
linkSqlite(project)
}
}
/**
* Call from users to explicitly register a service or by the plugin to register the implicit service
*/
override fun service(name: String, action: Action<Service>) {
registerDefaultService = false
val service = project.objects.newInstance(DefaultService::class.java, project, name)
action.execute(service)
registerService(service)
}
// Gradle will consider the task never UP-TO-DATE if we pass a lambda to doLast()
@Suppress("ObjectLiteralToLambda")
private fun registerCheckVersionsTask(): TaskProvider<Task> {
return project.tasks.register(ModelNames.checkApolloVersions()) {
val outputFile = BuildDirLayout.versionCheck(project)
it.inputs.property("allVersions", Callable {
val allDeps = (
getDeps(project.rootProject.buildscript.configurations) +
getDeps(project.buildscript.configurations) +
getDeps(project.configurations)
)
allDeps.mapNotNull { it.version }.distinct().sorted()
})
it.outputs.file(outputFile)
it.doLast(object : Action<Task> {
override fun execute(t: Task) {
val allVersions = it.inputs.properties["allVersions"] as List<*>
check(allVersions.size <= 1) {
"Apollo: All apollo versions should be the same. Found:\n$allVersions"
}
val version = allVersions.firstOrNull()
outputFile.get().asFile.parentFile.mkdirs()
outputFile.get().asFile.writeText("All versions are consistent: $version")
}
})
}
}
private fun registerService(service: DefaultService) {
check(services.find { it.name == service.name } == null) {
"There is already a service named $name, please use another name"
}
services.add(service)
val producerConfigurationName = ModelNames.producerConfiguration(service)
project.configurations.create(producerConfigurationName) {
it.isCanBeConsumed = true
it.isCanBeResolved = false
/**
* Expose transitive dependencies to downstream consumers
*/
it.extendsFrom(apolloConfiguration)
it.attributes {
it.attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class.java, USAGE_APOLLO_METADATA))
it.attribute(ApolloAttributes.APOLLO_SERVICE_ATTRIBUTE, project.objects.named(ApolloAttributes.Service::class.java, service.name))
}
}
val consumerConfiguration = project.configurations.create(ModelNames.consumerConfiguration(service)) {
it.isCanBeResolved = true
it.isCanBeConsumed = false
it.extendsFrom(apolloConfiguration)
it.attributes {
it.attribute(Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class.java, USAGE_APOLLO_METADATA))
it.attribute(ApolloAttributes.APOLLO_SERVICE_ATTRIBUTE, project.objects.named(ApolloAttributes.Service::class.java, service.name))
}
}
val codegenProvider = registerCodeGenTask(project, service, consumerConfiguration)
project.afterEvaluate {
if (shouldGenerateMetadata(service)) {
project.artifacts {
it.add(producerConfigurationName, codegenProvider.flatMap { it.metadataOutputFile })
}
}
}
codegenProvider.configure {
it.dependsOn(checkVersionsTask)
it.dependsOn(consumerConfiguration)
}
val checkApolloDuplicates = maybeRegisterCheckDuplicates(project.rootProject, service)
// Add project dependency on root project to this project, with our new configurations
project.rootProject.dependencies.apply {
add(
ModelNames.duplicatesConsumerConfiguration(service),
project(mapOf("path" to project.path))
)
}
codegenProvider.configure {
it.finalizedBy(checkApolloDuplicates)
}
if (service.operationOutputAction != null) {
val operationOutputConnection = Service.OperationOutputConnection(
task = codegenProvider,
operationOutputFile = codegenProvider.flatMap { it.operationOutputFile }
)
service.operationOutputAction!!.execute(operationOutputConnection)
}
if (service.outputDirAction == null) {
service.outputDirAction = defaultOutputDirAction
}
service.outputDirAction!!.execute(
DefaultDirectoryConnection(
project = project,
task = codegenProvider,
outputDir = codegenProvider.flatMap { it.outputDir }
)
)
if (service.testDirAction == null) {
service.testDirAction = defaultTestDirAction
}
service.testDirAction!!.execute(
DefaultDirectoryConnection(
project = project,
task = codegenProvider,
outputDir = codegenProvider.flatMap { it.testDir }
)
)
rootProvider.configure {
it.dependsOn(codegenProvider)
}
registerDownloadSchemaTasks(service)
maybeRegisterRegisterOperationsTasks(project, service, codegenProvider)
}
private fun maybeRegisterRegisterOperationsTasks(project: Project, service: DefaultService, codegenProvider: TaskProvider<ApolloGenerateSourcesTask>) {
val registerOperationsConfig = service.registerOperationsConfig
if (registerOperationsConfig != null) {
project.tasks.register(ModelNames.registerApolloOperations(service), ApolloRegisterOperationsTask::class.java) { task ->
task.group = TASK_GROUP
task.graph.set(registerOperationsConfig.graph)
task.graphVariant.set(registerOperationsConfig.graphVariant)
task.key.set(registerOperationsConfig.key)
task.operationOutput.set(codegenProvider.flatMap { it.operationOutputFile })
}
}
}
/**
* Generate metadata
* - if the user opted in
* - or if this project belongs to a multi-module build
* The last case is needed to check for potential duplicate types
*/
private fun shouldGenerateMetadata(service: DefaultService): Boolean {
return service.generateApolloMetadata.getOrElse(false)
|| apolloConfiguration.dependencies.isNotEmpty()
}
/**
* The default wiring.
*/
private val defaultOutputDirAction = Action<Service.DirectoryConnection> { connection ->
when {
project.kotlinMultiplatformExtension != null -> {
connection.connectToKotlinSourceSet("commonMain")
}
project.androidExtension != null -> {
connection.connectToAndroidSourceSet("main")
}
project.kotlinProjectExtension != null -> {
connection.connectToKotlinSourceSet("main")
}
project.javaConvention != null -> {
connection.connectToJavaSourceSet("main")
}
else -> throw IllegalStateException("Cannot find a Java/Kotlin extension, please apply the kotlin or java plugin")
}
}
private val defaultTestDirAction = Action<Service.DirectoryConnection> { connection ->
when {
project.kotlinMultiplatformExtension != null -> {
connection.connectToKotlinSourceSet("commonTest")
}
project.androidExtension != null -> {
connection.connectToAndroidSourceSet("test")
connection.connectToAndroidSourceSet("androidTest")
}
project.kotlinProjectExtension != null -> {
connection.connectToKotlinSourceSet("test")
}
project.javaConvention != null -> {
connection.connectToJavaSourceSet("test")
}
else -> throw IllegalStateException("Cannot find a Java/Kotlin extension, please apply the kotlin or java plugin")
}
}
private fun maybeRegisterCheckDuplicates(rootProject: Project, service: Service): TaskProvider<ApolloCheckDuplicatesTask> {
val taskName = ModelNames.checkApolloDuplicates(service)
return try {
@Suppress("UNCHECKED_CAST")
rootProject.tasks.named(taskName) as TaskProvider<ApolloCheckDuplicatesTask>
} catch (e: Exception) {
val configuration = rootProject.configurations.create(ModelNames.duplicatesConsumerConfiguration(service)) {
it.isCanBeResolved = true
it.isCanBeConsumed = false
it.attributes {
it.attribute(Usage.USAGE_ATTRIBUTE, rootProject.objects.named(Usage::class.java, USAGE_APOLLO_METADATA))
it.attribute(ApolloAttributes.APOLLO_SERVICE_ATTRIBUTE, rootProject.objects.named(ApolloAttributes.Service::class.java, service.name))
}
}
rootProject.tasks.register(taskName, ApolloCheckDuplicatesTask::class.java) {
it.outputFile.set(BuildDirLayout.duplicatesCheck(rootProject, service))
it.metadataFiles.from(configuration)
}
}
}
private fun Project.hasJavaPlugin() = project.extensions.findByName("java") != null
private fun Project.hasKotlinPlugin() = project.extensions.findByName("kotlin") != null
private fun registerCodeGenTask(
project: Project,
service: DefaultService,
consumerConfiguration: Configuration,
): TaskProvider<ApolloGenerateSourcesTask> {
return project.tasks.register(ModelNames.generateApolloSources(service), ApolloGenerateSourcesTask::class.java) { task ->
task.group = TASK_GROUP
task.description = "Generate Apollo models for ${service.name} GraphQL queries"
if (service.graphqlSourceDirectorySet.isReallyEmpty) {
val sourceFolder = service.sourceFolder.getOrElse("")
val dir = File(project.projectDir, "src/${mainSourceSet(project)}/graphql/$sourceFolder")
service.graphqlSourceDirectorySet.srcDir(dir)
}
service.graphqlSourceDirectorySet.include(service.includes.getOrElse(listOf("**/*.graphql", "**/*.gql")))
service.graphqlSourceDirectorySet.exclude(service.excludes.getOrElse(emptyList()))
task.graphqlFiles.setFrom(service.graphqlSourceDirectorySet)
// Since this is stored as a list of string, the order matter hence the sorting
task.rootFolders.set(project.provider { service.graphqlSourceDirectorySet.srcDirs.map { it.relativeTo(project.projectDir).path }.sorted() })
// This has to be lazy in case the schema is not written yet during configuration
// See the `graphql files can be generated by another task` test
task.schemaFiles.from(project.provider { service.lazySchemaFiles(project) })
task.operationOutputGenerator = service.operationOutputGenerator.getOrElse(
OperationOutputGenerator.Default(
service.operationIdGenerator.orElse(OperationIdGenerator.Sha256).get()
)
)
if (project.hasKotlinPlugin()) {
checkKotlinPluginVersion(project)
}
val generateKotlinModels: Boolean
when {
service.generateKotlinModels.isPresent -> {
generateKotlinModels = service.generateKotlinModels.get()
if (generateKotlinModels) {
check(project.hasKotlinPlugin()) {
"Apollo: generateKotlinModels.set(true) requires to apply a Kotlin plugin"
}
} else {
check(project.hasJavaPlugin()) {
"Apollo: generateKotlinModels.set(false) requires to apply the Java plugin"
}
}
}
project.hasKotlinPlugin() -> {
generateKotlinModels = true
}
project.hasJavaPlugin() -> {
generateKotlinModels = false
}
else -> {
error("Apollo: No Java or Kotlin plugin found")
}
}
val targetLanguage = if (generateKotlinModels) {
getKotlinTargetLanguage(project, languageVersion.orNull)
} else {
TargetLanguage.JAVA
}
task.useSemanticNaming.set(service.useSemanticNaming)
task.targetLanguage.set(targetLanguage)
task.warnOnDeprecatedUsages.set(service.warnOnDeprecatedUsages)
task.failOnWarnings.set(service.failOnWarnings)
@Suppress("DEPRECATION")
task.customScalarsMapping.set(service.customScalarsMapping.orElse(service.customTypeMapping))
task.outputDir.apply {
set(service.outputDir.orElse(BuildDirLayout.outputDir(project, service)).get())
disallowChanges()
}
task.testDir.apply {
set(service.testDir.orElse(BuildDirLayout.testDir(project, service)).get())
disallowChanges()
}
task.debugDir.apply {
set(service.debugDir)
disallowChanges()
}
if (service.generateOperationOutput.getOrElse(false)) {
task.operationOutputFile.apply {
set(service.operationOutputFile.orElse(BuildDirLayout.operationOutput(project, service)))
disallowChanges()
}
}
if (shouldGenerateMetadata(service)) {
task.metadataOutputFile.apply {
set(BuildDirLayout.metadata(project, service))
disallowChanges()
}
}
task.metadataFiles.from(consumerConfiguration)
check(!(service.packageName.isPresent && service.packageNameGenerator.isPresent)) {
"Apollo: it is an error to specify both 'packageName' and 'packageNameGenerator' " +
"(either directly or indirectly through useVersion2Compat())"
}
var packageNameGenerator = service.packageNameGenerator.orNull
if (packageNameGenerator == null) {
packageNameGenerator = PackageNameGenerator.Flat(service.packageName.orNull ?: error("""
|Apollo: specify 'packageName':
|apollo {
| packageName.set("com.example")
|
| // Alternatively, if you're migrating from 2.x, you can keep the 2.x
| // behaviour with `packageNamesFromFilePaths()`:
| packageNamesFromFilePaths()
|}
""".trimMargin()))
}
task.packageNameGenerator = packageNameGenerator
task.generateAsInternal.set(service.generateAsInternal)
task.generateFilterNotNull.set(project.isKotlinMultiplatform)
task.alwaysGenerateTypesMatching.set(service.alwaysGenerateTypesMatching)
task.projectName.set(project.name)
task.generateFragmentImplementations.set(service.generateFragmentImplementations)
task.generateQueryDocument.set(service.generateQueryDocument)
task.generateSchema.set(service.generateSchema)
task.codegenModels.set(service.codegenModels)
task.flattenModels.set(service.flattenModels)
@OptIn(ApolloExperimental::class)
task.generateTestBuilders.set(service.generateTestBuilders)
task.sealedClassesForEnumsMatching.set(service.sealedClassesForEnumsMatching)
task.generateOptionalOperationVariables.set(service.generateOptionalOperationVariables)
task.languageVersion.set(service.languageVersion)
}
}
private fun lazySchemaFileForDownload(service: DefaultService, schemaFile: RegularFileProperty): String {
if (schemaFile.isPresent) {
return schemaFile.get().asFile.absolutePath
}
val candidates = service.lazySchemaFiles(project)
check(candidates.isNotEmpty()) {
"No schema files found. Specify introspection.schemaFile or registry.schemaFile"
}
check(candidates.size == 1) {
"Multiple schema files found:\n${candidates.joinToString("\n")}\n\nSpecify introspection.schemaFile or registry.schemaFile"
}
return candidates.single().absolutePath
}
private fun registerDownloadSchemaTasks(service: DefaultService) {
val introspection = service.introspection
if (introspection != null) {
project.tasks.register(ModelNames.downloadApolloSchemaIntrospection(service), ApolloDownloadSchemaTask::class.java) { task ->
task.group = TASK_GROUP
task.endpoint.set(introspection.endpointUrl)
task.header = introspection.headers.get().map { "${it.key}: ${it.value}" }
task.schema.set(project.provider { lazySchemaFileForDownload(service, introspection.schemaFile) })
}
}
val registry = service.registry
if (registry != null) {
project.tasks.register(ModelNames.downloadApolloSchemaRegistry(service), ApolloDownloadSchemaTask::class.java) { task ->
task.group = TASK_GROUP
task.graph.set(registry.graph)
task.key.set(registry.key)
task.graphVariant.set(registry.graphVariant)
task.schema.set(project.provider { lazySchemaFileForDownload(service, registry.schemaFile) })
}
}
}
override fun createAllAndroidVariantServices(
sourceFolder: String,
nameSuffix: String,
action: Action<Service>,
) {
/**
* The android plugin will call us back when the variants are ready but before `afterEvaluate`,
* disable the default service
*/
registerDefaultService = false
check(!File(sourceFolder).isRooted && !sourceFolder.startsWith("../..")) {
"""
Apollo: using 'sourceFolder = "$sourceFolder"' makes no sense with Android variants as the same generated models will be used in all variants.
""".trimIndent()
}
AndroidProject.onEachVariant(project, true) { variant ->
val name = "${variant.name}${nameSuffix.capitalizeFirstLetter()}"
service(name) { service ->
action.execute(service)
check(!service.sourceFolder.isPresent) {
"Apollo: service.sourceFolder is not used when calling createAllAndroidVariantServices. Use the parameter instead"
}
variant.sourceSets.forEach { sourceProvider ->
service.srcDir("src/${sourceProvider.name}/graphql/$sourceFolder")
}
(service as DefaultService).outputDirAction = Action<Service.DirectoryConnection> { connection ->
connection.connectToAndroidVariant(variant)
}
}
}
}
override fun createAllKotlinSourceSetServices(sourceFolder: String, nameSuffix: String, action: Action<Service>) {
registerDefaultService = false
check(!File(sourceFolder).isRooted && !sourceFolder.startsWith("../..")) {
"""Apollo: using 'sourceFolder = "$sourceFolder"' makes no sense with Kotlin source sets as the same generated models will be used in all source sets.
""".trimMargin()
}
createAllKotlinSourceSetServices(this, project, sourceFolder, nameSuffix, action)
}
abstract override val linkSqlite: Property<Boolean>
companion object {
private const val TASK_GROUP = "apollo"
const val MIN_GRADLE_VERSION = "5.6"
private const val USAGE_APOLLO_METADATA = "apollo-metadata"
private data class Dep(val name: String, val version: String?)
private fun getDeps(configurations: ConfigurationContainer): List<Dep> {
return configurations.flatMap { configuration ->
configuration.dependencies
.filter {
it.group == "com.apollographql.apollo3"
}.map { dependency ->
Dep(dependency.name, dependency.version)
}
}
}
// Don't use `graphqlSourceDirectorySet.isEmpty` here, it doesn't work for some reason
private val SourceDirectorySet.isReallyEmpty
get() = sourceDirectories.isEmpty
private fun mainSourceSet(project: Project): String {
val kotlinExtension = project.extensions.findByName("kotlin")
return when (kotlinExtension) {
is KotlinMultiplatformExtension -> "commonMain"
else -> "main"
}
}
fun DefaultService.lazySchemaFiles(project: Project): Set<File> {
val files = if (schemaFile.isPresent) {
check(schemaFiles.isEmpty) {
"Specifying both schemaFile and schemaFiles is an error"
}
project.files(schemaFile)
} else {
schemaFiles
}
if (!files.isEmpty) {
return files.files
}
return graphqlSourceDirectorySet.srcDirs.flatMap { srcDir ->
srcDir.walkTopDown().filter { it.extension in listOf("json", "sdl", "graphqls") }.toList()
}.toSet()
}
}
}
| mit | 65809fa3b63e6c30541c98c6d1b25a47 | 37.364599 | 156 | 0.691273 | 4.970404 | false | true | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/stage/bg/BTSDSBackground.kt | 2 | 5570 | package io.github.chrislo27.rhre3.stage.bg
import com.badlogic.gdx.graphics.Color
@Suppress("PropertyName")
class BTSDSBackground(id: String, val floorColor: Color = Color.valueOf("3DFD46FF")) : BlockBasedBackground(id) {
override val map: Map = Map(21, 6, 23)
private val floorFace = Face(0, 0, floorColor)
private val floor2Face = Face(0, 0, floorColor.cpy().sub(6f / 255f, 23f / 255f, 7f / 255f, 0f))
private val floor3Face = Face(0, 0, floorColor.cpy().sub(17f / 255f, 74f / 255f, 20f / 255f, 0f))
private val floor4Face = Face(0, 0, floorColor.cpy().sub(24f / 255f, 100f / 255f, 26f / 255f, 0f))
private val floor5Face = Face(0, 0, floorColor.cpy().sub(29f / 255f, 124f / 255f, 34f / 255f, 0f))
private val conveyorFace = Face(0, 2, floor5Face.tint.cpy(), 1f, 0, 3)
private val whitePlatformFace = Face(0, 0)
private val redStripesTopFace = Face(1, 0)
private val redStripesSideFace = Face(2, 0)
val FLOOR: Block = Block("floor", floorFace, floorFace, floorFace)
val FLOOR2: Block = Block("floor2", floor2Face, floor2Face, floor2Face)
val FLOOR3: Block = Block("floor3", floor3Face, floor3Face, floor3Face)
val FLOOR4: Block = Block("floor4", floor4Face, floor4Face, floor4Face)
val FLOOR5: Block = Block("floor5", floor5Face, floor5Face, floor5Face)
val CONVEYOR: Block = Block("conveyor", floor5Face, conveyorFace, floor5Face)
val FLOOR_LIST: List<Block> = listOf(FLOOR, FLOOR2, FLOOR3, FLOOR4, FLOOR5)
val PLATFORM: Block = Block("platform", floor2Face, whitePlatformFace, floor2Face)
val PLATFORM_CENTRE: Block = Block("platform_centre", redStripesSideFace, redStripesTopFace, redStripesSideFace)
override fun buildMap() {
camera.apply {
position.y = 15f
position.x = 4f
update()
}
flashEnabled = true
map.iterateSorted { _, x, y, z ->
map.setBlock(FLOOR_LIST.getOrElse(map.sizeY - y - 1) { FLOOR }, x, y, z)
map.setMetadata(0.toByte(), x, y, z)
}
val trenchZStart = 4
for (x in -4..4) {
for (z in trenchZStart until map.sizeZ) {
map.setBlock(Block.NOTHING, x + map.sizeX / 2, map.sizeY - 1, z)
if (x in -3..3) {
map.setBlock(Block.NOTHING, x + map.sizeX / 2, map.sizeY - 2, z)
}
if (x in -2..2) {
map.setBlock(Block.NOTHING, x + map.sizeX / 2, map.sizeY - 3, z)
}
if (x in -1..1) {
map.setBlock(Block.NOTHING, x + map.sizeX / 2, map.sizeY - 4, z)
}
map.setBlock(CONVEYOR, map.sizeX / 2, map.sizeY - 5, z)
}
}
val platform = 9
for (zi in 0..1) {
for (x in 0 until map.sizeX) {
map.setBlock(Block.NOTHING, x, map.sizeY - 2, trenchZStart + platform + zi)
if (x == map.sizeX / 2) {
map.setBlock(PLATFORM_CENTRE, x, map.sizeY - 3, trenchZStart + platform + zi)
} else {
map.setBlock(PLATFORM, x, map.sizeY - 3, trenchZStart + platform + zi)
map.setBlock(FLOOR4, x, map.sizeY - 4, trenchZStart + platform + zi)
}
map.setBlock(FLOOR3, x, map.sizeY - 3, trenchZStart + platform - 5 + zi)
}
}
// Flash metadata
map.setMetadata(1.toByte(), map.sizeX / 2 + 3, map.sizeY - 3, trenchZStart + 8)
map.setMetadata(1.toByte(), map.sizeX / 2 + 3, map.sizeY - 3, trenchZStart + 6)
map.setMetadata(1.toByte(), map.sizeX / 2 + 3, map.sizeY - 3, trenchZStart + 3)
map.setMetadata(1.toByte(), map.sizeX / 2 - 3, map.sizeY - 3, trenchZStart + 8)
map.setMetadata(1.toByte(), map.sizeX / 2 - 3, map.sizeY - 3, trenchZStart + 6)
map.setMetadata(1.toByte(), map.sizeX / 2 - 3, map.sizeY - 3, trenchZStart + 3)
map.setMetadata(1.toByte(), map.sizeX / 2 - 5, map.sizeY - 1, trenchZStart + 7)
map.setMetadata(1.toByte(), map.sizeX / 2 - 5, map.sizeY - 1, trenchZStart + 3)
map.setMetadata(1.toByte(), map.sizeX / 2 + 5, map.sizeY - 1, trenchZStart + 7)
map.setMetadata(1.toByte(), map.sizeX / 2 + 5, map.sizeY - 1, trenchZStart + 3)
map.setMetadata(1.toByte(), map.sizeX / 2 + 1, map.sizeY - 5, trenchZStart + 15)
map.setMetadata(1.toByte(), map.sizeX / 2 - 1, map.sizeY - 5, trenchZStart + 17)
map.setMetadata(1.toByte(), map.sizeX / 2 + 3, map.sizeY - 3, trenchZStart + 15)
map.setMetadata(2.toByte(), map.sizeX / 2 + 2, map.sizeY - 4, trenchZStart + 8)
map.setMetadata(2.toByte(), map.sizeX / 2 - 2, map.sizeY - 4, trenchZStart + 7)
map.setMetadata(2.toByte(), map.sizeX / 2 - 2, map.sizeY - 4, trenchZStart + 13)
map.setMetadata(2.toByte(), map.sizeX / 2 + 2, map.sizeY - 4, trenchZStart + 14)
map.setMetadata(2.toByte(), map.sizeX / 2 - 4, map.sizeY - 2, trenchZStart + 8)
map.setMetadata(2.toByte(), map.sizeX / 2 - 4, map.sizeY - 2, trenchZStart + 2)
map.setMetadata(2.toByte(), map.sizeX / 2 + 6, map.sizeY - 1, trenchZStart + 8)
map.setMetadata(2.toByte(), map.sizeX / 2 + 7, map.sizeY - 1, trenchZStart + 4)
map.setMetadata(2.toByte(), map.sizeX / 2 - 7, map.sizeY - 1, trenchZStart + 1)
map.setMetadata(2.toByte(), map.sizeX / 2 - 6, map.sizeY - 1, trenchZStart + 4)
map.setMetadata(2.toByte(), map.sizeX / 2 + 4, map.sizeY - 2, trenchZStart + 4)
}
} | gpl-3.0 | 342f376c6d56c0fceb8f4e838e982b01 | 54.71 | 116 | 0.584022 | 3.386018 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.kt | 2 | 14067 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.ui
import com.intellij.application.options.RegistryManager
import com.intellij.ide.ui.UISettings.Companion.setupAntialiasing
import com.intellij.jdkEx.JdkEx
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.CommonShortcuts
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.actionSystem.impl.MouseGestureManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.ui.popup.util.PopupUtil
import com.intellij.openapi.util.*
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.wm.*
import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy
import com.intellij.openapi.wm.ex.IdeFrameEx
import com.intellij.openapi.wm.ex.WindowManagerEx
import com.intellij.openapi.wm.impl.*
import com.intellij.openapi.wm.impl.LinuxIdeMenuBar.Companion.doBindAppMenuOfParent
import com.intellij.openapi.wm.impl.ProjectFrameHelper.appendTitlePart
import com.intellij.openapi.wm.impl.customFrameDecorations.header.CustomFrameDialogContent
import com.intellij.ui.AppUIUtil
import com.intellij.ui.BalloonLayout
import com.intellij.ui.ComponentUtil
import com.intellij.ui.FrameState
import com.intellij.util.SystemProperties
import com.intellij.util.ui.ImageUtil
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.NonNls
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.resolvedPromise
import java.awt.*
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.nio.file.Path
import javax.swing.*
open class FrameWrapper @JvmOverloads constructor(project: Project?,
@param:NonNls protected open val dimensionKey: String? = null,
private val isDialog: Boolean = false,
@NlsContexts.DialogTitle var title: String = "",
open var component: JComponent? = null) : Disposable, DataProvider {
open var preferredFocusedComponent: JComponent? = null
private var images: List<Image> = emptyList()
private var isCloseOnEsc = false
private var onCloseHandler: BooleanGetter? = null
private var frame: Window? = null
private var project: Project? = null
private var focusWatcher: FocusWatcher? = null
private var isDisposing = false
var isDisposed = false
private set
protected var statusBar: StatusBar? = null
set(value) {
field?.let {
Disposer.dispose(it)
}
field = value
}
init {
project?.let { setProject(it) }
}
fun setProject(project: Project) {
this.project = project
ApplicationManager.getApplication().messageBus.connect(this).subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
override fun projectClosing(project: Project) {
if (project === [email protected]) {
close()
}
}
})
}
open fun show() {
show(true)
}
fun createContents() {
val frame = getFrame()
if (frame is JFrame) {
frame.defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE
}
else {
(frame as JDialog).defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE
}
frame.addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent) {
close()
}
})
UIUtil.decorateWindowHeader((frame as RootPaneContainer).rootPane)
if (frame is JFrame) {
UIUtil.setCustomTitleBar(frame, frame.rootPane) { runnable ->
Disposer.register(this, Disposable { runnable.run() })
}
}
val focusListener = object : WindowAdapter() {
override fun windowOpened(e: WindowEvent) {
val focusManager = IdeFocusManager.getInstance(project)
val toFocus = preferredFocusedComponent ?: focusManager.getFocusTargetFor(component!!)
if (toFocus != null) {
focusManager.requestFocus(toFocus, true)
}
}
}
frame.addWindowListener(focusListener)
if (RegistryManager.getInstance().`is`("ide.perProjectModality")) {
frame.isAlwaysOnTop = true
}
Disposer.register(this, Disposable {
frame.removeWindowListener(focusListener)
})
if (isCloseOnEsc) {
addCloseOnEsc(frame as RootPaneContainer)
}
if (IdeFrameDecorator.isCustomDecorationActive()) {
component?.let {
component = /*UIUtil.findComponentOfType(it, EditorsSplitters::class.java)?.let {
if(frame !is JFrame) null else {
val header = CustomHeader.createMainFrameHeader(frame, IdeMenuBar.createMenuBar())
getCustomContentHolder(frame, it, header)
}
} ?:*/
CustomFrameDialogContent.getCustomContentHolder(frame, it)
}
}
frame.contentPane.add(component!!, BorderLayout.CENTER)
if (frame is JFrame) {
frame.title = title
}
else {
(frame as JDialog).title = title
}
if (images.isEmpty()) {
AppUIUtil.updateWindowIcon(frame)
}
else {
// unwrap the image before setting as frame's icon
frame.iconImages = images.map { ImageUtil.toBufferedImage(it) }
}
if (SystemInfo.isLinux && frame is JFrame && GlobalMenuLinux.isAvailable()) {
val parentFrame = WindowManager.getInstance().getFrame(project)
if (parentFrame != null) {
doBindAppMenuOfParent(frame, parentFrame)
}
}
focusWatcher = FocusWatcher()
focusWatcher!!.install(component!!)
}
fun show(restoreBounds: Boolean) {
createContents()
val frame = getFrame()
val state = dimensionKey?.let { getWindowStateService(project).getState(it, frame) }
if (restoreBounds) {
loadFrameState(state)
}
frame.isVisible = true
}
fun close() {
if (isDisposed || (onCloseHandler != null && !onCloseHandler!!.get())) {
return
}
// if you remove this line problems will start happen on Mac OS X
// 2 projects opened, call Cmd+D on the second opened project and then Esc.
// Weird situation: 2nd IdeFrame will be active, but focus will be somewhere inside the 1st IdeFrame
// App is unusable until Cmd+Tab, Cmd+tab
frame?.isVisible = false
Disposer.dispose(this)
}
override fun dispose() {
if (isDisposed) {
return
}
val frame = frame
val statusBar = statusBar
this.frame = null
preferredFocusedComponent = null
project = null
if (component != null && focusWatcher != null) {
focusWatcher!!.deinstall(component)
}
focusWatcher = null
component = null
images = emptyList()
isDisposed = true
if (statusBar != null) {
Disposer.dispose(statusBar)
}
if (frame != null) {
frame.isVisible = false
val rootPane = (frame as RootPaneContainer).rootPane
frame.removeAll()
DialogWrapper.cleanupRootPane(rootPane)
if (frame is IdeFrame) {
MouseGestureManager.getInstance().remove(frame)
}
frame.dispose()
DialogWrapper.cleanupWindowListeners(frame)
}
}
private fun addCloseOnEsc(frame: RootPaneContainer) {
val rootPane = frame.rootPane
val closeAction = ActionListener {
if (!PopupUtil.handleEscKeyEvent()) {
close()
}
}
rootPane.registerKeyboardAction(closeAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW)
ActionUtil.registerForEveryKeyboardShortcut(rootPane, closeAction, CommonShortcuts.getCloseActiveWindow())
}
fun getFrame(): Window {
assert(!isDisposed) { "Already disposed!" }
var result = frame
if (result == null) {
val parent = WindowManager.getInstance().getIdeFrame(project)!!
result = if (isDialog) createJDialog(parent) else createJFrame(parent)
frame = result
}
return result
}
val isActive: Boolean
get() = frame?.isActive == true
protected open fun createJFrame(parent: IdeFrame): JFrame = MyJFrame(this, parent)
protected open fun createJDialog(parent: IdeFrame): JDialog = MyJDialog(this, parent)
protected open fun getNorthExtension(key: String?): IdeRootPaneNorthExtension? = null
override fun getData(@NonNls dataId: String): Any? {
return if (CommonDataKeys.PROJECT.`is`(dataId)) project else null
}
private fun getDataInner(@NonNls dataId: String): Any? {
return when {
CommonDataKeys.PROJECT.`is`(dataId) -> project
else -> getData(dataId)
}
}
fun closeOnEsc() {
isCloseOnEsc = true
}
fun setImage(image: Image?) {
setImages(listOfNotNull(image))
}
fun setImages(value: List<Image>?) {
images = value ?: emptyList()
}
fun setOnCloseHandler(value: BooleanGetter?) {
onCloseHandler = value
}
protected open fun loadFrameState(state: WindowState?) {
val frame = getFrame()
if (state == null) {
val ideFrame = WindowManagerEx.getInstanceEx().getIdeFrame(project)
if (ideFrame != null) {
frame.bounds = ideFrame.suggestChildFrameBounds()
}
}
else {
state.applyTo(frame)
}
(frame as RootPaneContainer).rootPane.revalidate()
}
private class MyJFrame(private var owner: FrameWrapper, private val parent: IdeFrame) : JFrame(), DataProvider, IdeFrame.Child, IdeFrameEx {
private var frameTitle: String? = null
private var fileTitle: String? = null
private var file: Path? = null
init {
FrameState.setFrameStateListener(this)
glassPane = IdeGlassPaneImpl(getRootPane(), true)
if (SystemInfo.isMac && !(SystemInfo.isMacSystemMenu && SystemProperties.`is`("mac.system.menu.singleton"))) {
jMenuBar = IdeMenuBar.createMenuBar()
}
MouseGestureManager.getInstance().add(this)
focusTraversalPolicy = IdeFocusTraversalPolicy()
}
override fun isInFullScreen() = false
override fun toggleFullScreen(state: Boolean): Promise<*> = resolvedPromise<Any>()
override fun addNotify() {
if (IdeFrameDecorator.isCustomDecorationActive()) {
JdkEx.setHasCustomDecoration(this)
}
super.addNotify()
}
override fun getComponent(): JComponent = getRootPane()
override fun getStatusBar(): StatusBar? {
return (if (owner.isDisposing) null else owner.statusBar) ?: parent.statusBar
}
override fun suggestChildFrameBounds(): Rectangle = parent.suggestChildFrameBounds()
override fun getProject() = parent.project
override fun setFrameTitle(title: String) {
frameTitle = title
updateTitle()
}
override fun setFileTitle(fileTitle: String?, ioFile: Path?) {
this.fileTitle = fileTitle
file = ioFile
updateTitle()
}
override fun getNorthExtension(key: String): IdeRootPaneNorthExtension? {
return owner.getNorthExtension(key)
}
override fun getBalloonLayout(): BalloonLayout? {
return null
}
private fun updateTitle() {
if (Registry.`is`("ide.show.fileType.icon.in.titleBar")) {
// this property requires java.io.File
rootPane.putClientProperty("Window.documentFile", file?.toFile())
}
val builder = StringBuilder()
appendTitlePart(builder, frameTitle)
appendTitlePart(builder, fileTitle)
title = builder.toString()
}
override fun dispose() {
val owner = owner
if (owner.isDisposing) {
return
}
owner.isDisposing = true
Disposer.dispose(owner)
super.dispose()
rootPane = null
menuBar = null
}
override fun getData(dataId: String): Any? {
return when {
IdeFrame.KEY.`is`(dataId) -> this
owner.isDisposing -> null
else -> owner.getDataInner(dataId)
}
}
override fun paint(g: Graphics) {
setupAntialiasing(g)
super.paint(g)
}
}
fun setLocation(location: Point) {
getFrame().location = location
}
fun setSize(size: Dimension?) {
getFrame().size = size
}
private class MyJDialog(private val owner: FrameWrapper, private val parent: IdeFrame) : JDialog(ComponentUtil.getWindow(parent.component)), DataProvider, IdeFrame.Child {
override fun getComponent(): JComponent = getRootPane()
override fun getStatusBar(): StatusBar? = null
override fun getBalloonLayout(): BalloonLayout? = null
override fun suggestChildFrameBounds(): Rectangle = parent.suggestChildFrameBounds()
override fun getProject(): Project? = parent.project
init {
glassPane = IdeGlassPaneImpl(getRootPane())
getRootPane().putClientProperty("Window.style", "small")
background = UIUtil.getPanelBackground()
MouseGestureManager.getInstance().add(this)
focusTraversalPolicy = IdeFocusTraversalPolicy()
}
override fun setFrameTitle(title: String) {
setTitle(title)
}
override fun dispose() {
if (owner.isDisposing) {
return
}
owner.isDisposing = true
Disposer.dispose(owner)
super.dispose()
rootPane = null
}
override fun getData(dataId: String): Any? {
return when {
IdeFrame.KEY.`is`(dataId) -> this
owner.isDisposing -> null
else -> owner.getDataInner(dataId)
}
}
override fun paint(g: Graphics) {
setupAntialiasing(g)
super.paint(g)
}
}
}
private fun getWindowStateService(project: Project?): WindowStateService {
return if (project == null) WindowStateService.getInstance() else WindowStateService.getInstance(project)
} | apache-2.0 | d9ef86282efe997f8889c936e61b5a12 | 29.516269 | 173 | 0.682093 | 4.810876 | false | false | false | false |
Homes-MinecraftServerMod/Homes | src/main/kotlin/com/masahirosaito/spigot/homes/commands/maincommands/homecommands/HomeCommand.kt | 1 | 4503 | package com.masahirosaito.spigot.homes.commands.maincommands.homecommands
import com.masahirosaito.spigot.homes.DelayTeleporter
import com.masahirosaito.spigot.homes.Homes.Companion.homes
import com.masahirosaito.spigot.homes.Permission
import com.masahirosaito.spigot.homes.PlayerDataManager
import com.masahirosaito.spigot.homes.commands.CommandUsage
import com.masahirosaito.spigot.homes.commands.maincommands.MainCommand
import com.masahirosaito.spigot.homes.commands.subcommands.console.ConsoleCommand
import com.masahirosaito.spigot.homes.commands.subcommands.console.helpcommands.ConsoleHelpCommand
import com.masahirosaito.spigot.homes.commands.subcommands.console.listcommands.ConsoleListCommand
import com.masahirosaito.spigot.homes.commands.subcommands.console.reloadcommands.ConsoleReloadCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.PlayerCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.deletecommands.PlayerDeleteCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.helpcommands.PlayerHelpCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.invitecommands.PlayerInviteCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.listcommands.PlayerListCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.privatecommands.PlayerPrivateCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.reloadcommands.PlayerReloadCommand
import com.masahirosaito.spigot.homes.commands.subcommands.player.setcommands.PlayerSetCommand
import com.masahirosaito.spigot.homes.exceptions.DefaultHomePrivateException
import com.masahirosaito.spigot.homes.exceptions.NamedHomePrivateException
import com.masahirosaito.spigot.homes.strings.commands.HomeCommandStrings.DESCRIPTION
import com.masahirosaito.spigot.homes.strings.commands.HomeCommandStrings.USAGE_HOME
import com.masahirosaito.spigot.homes.strings.commands.HomeCommandStrings.USAGE_HOME_NAME
import com.masahirosaito.spigot.homes.strings.commands.HomeCommandStrings.USAGE_HOME_NAME_PLAYER
import com.masahirosaito.spigot.homes.strings.commands.HomeCommandStrings.USAGE_HOME_PLAYER
import org.bukkit.Location
import org.bukkit.OfflinePlayer
import org.bukkit.entity.Player
class HomeCommand : MainCommand, PlayerCommand {
override var payNow: Boolean = false
override val name: String = "home"
override val description: String = DESCRIPTION()
override val permissions: List<String> = listOf(
Permission.home_command
)
override val usage: CommandUsage = CommandUsage(this, listOf(
"/home" to USAGE_HOME(),
"/home <home_name>" to USAGE_HOME_NAME(),
"/home -p <player_name>" to USAGE_HOME_PLAYER(),
"/home <home_name> -p <player_name>" to USAGE_HOME_NAME_PLAYER()
))
override val playerSubCommands: List<PlayerCommand> = listOf(
PlayerSetCommand(),
PlayerDeleteCommand(),
PlayerPrivateCommand(),
PlayerInviteCommand(),
PlayerListCommand(),
PlayerHelpCommand(),
PlayerReloadCommand()
)
override val consoleSubCommands: List<ConsoleCommand> = listOf(
ConsoleHelpCommand(),
ConsoleListCommand(),
ConsoleReloadCommand()
)
override val commands: List<PlayerCommand> = listOf(
HomeNameCommand(this),
HomePlayerCommand(this),
HomeNamePlayerCommand(this)
)
init {
homeCommand = this
}
companion object {
lateinit var homeCommand: HomeCommand
}
override fun fee(): Double = homes.fee.HOME
override fun configs(): List<Boolean> = listOf()
override fun isValidArgs(args: List<String>): Boolean = args.isEmpty()
override fun execute(player: Player, args: List<String>) {
DelayTeleporter.run(player, getTeleportLocation(player), this)
}
fun getTeleportLocation(player: OfflinePlayer, homeName: String? = null): Location {
if (homeName == null) {
return PlayerDataManager.findDefaultHome(player).apply {
if (isPrivate && !isOwner(player)) throw DefaultHomePrivateException(player)
}.location
} else {
return PlayerDataManager.findNamedHome(player, homeName).apply {
if (isPrivate && !isOwner(player)) throw NamedHomePrivateException(player, homeName)
}.location
}
}
}
| apache-2.0 | cb856e67dbcfb9e225d83f93d9985e97 | 46.904255 | 102 | 0.755718 | 4.676012 | false | false | false | false |
allotria/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/settings/MarkdownScriptsTable.kt | 2 | 2606 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.settings
import com.intellij.ui.layout.*
import com.intellij.ui.table.JBTable
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.extensions.MarkdownConfigurableExtension
import org.intellij.plugins.markdown.extensions.MarkdownExtension
import org.intellij.plugins.markdown.extensions.MarkdownExtensionWithExternalFiles
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanelProvider
import java.awt.Component
import javax.swing.JComponent
import javax.swing.table.TableCellRenderer
internal class MarkdownScriptsTable : JBTable() {
init {
setShowGrid(false)
setState(emptyMap(), null)
}
override fun getCellSelectionEnabled(): Boolean = false
override fun prepareRenderer(renderer: TableCellRenderer, row: Int, column: Int): Component {
var prepared = super.prepareRenderer(renderer, row, column)
if (prepared is JComponent) {
val tableModel = model as MarkdownScriptsTableModel
val extension = tableModel.getExtensionAt(row)
if (column == MarkdownScriptsTableModel.NAME_COLUMN_INDEX) {
prepared = panel {
row {
cell {
label(tableModel.getValueAt(row, column) as String)
if (extension is MarkdownExtensionWithExternalFiles && !extension.isAvailable) {
label(MarkdownBundle.message("markdown.settings.download.extension.not.installed.label")).also {
it.enabled(false)
}
}
}
}
}
}
(prepared as JComponent).toolTipText = extension.description
}
return prepared
}
fun getState(): MutableMap<String, Boolean> = (model as MarkdownScriptsTableModel).state
fun setState(state: Map<String, Boolean>, providerInfo: MarkdownHtmlPanelProvider.ProviderInfo?) {
val extensions = MarkdownExtension.all.filterIsInstance<MarkdownConfigurableExtension>()
val mergedState = extensions.map { it.id to false }.toMap().toMutableMap()
for ((key, value) in state) {
if (key in state.keys) {
mergedState[key] = value
}
}
model = MarkdownScriptsTableModel(mergedState, extensions)
setColumnWidth(MarkdownScriptsTableModel.ENABLED_COLUMN_INDEX, 60)
repaint()
}
private fun setColumnWidth(index: Int, width: Int) {
columnModel.getColumn(index)?.let {
it.preferredWidth = width
it.maxWidth = width
}
}
}
| apache-2.0 | 6cfd22d64dd8b08d731278e11813c52d | 36.228571 | 140 | 0.713354 | 4.678636 | false | false | false | false |
leafclick/intellij-community | platform/util/concurrency/com/intellij/util/concurrency/SynchronizedClearableLazy.kt | 1 | 1270 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.concurrency
@Suppress("ClassName")
private object UNINITIALIZED_VALUE
/**
* Kotlin-friendly version of ClearableLazyValue
*/
@Suppress("LocalVariableName")
class SynchronizedClearableLazy<T>(private val initializer: () -> T) : Lazy<T> {
@Volatile
private var _value: Any? = UNINITIALIZED_VALUE
override var value: T
get() {
val _v1 = _value
if (_v1 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST")
return _v1 as T
}
return synchronized(this) {
val _v2 = _value
if (_v2 !== UNINITIALIZED_VALUE) {
@Suppress("UNCHECKED_CAST") (_v2 as T)
}
else {
val typedValue = initializer()
_value = typedValue
typedValue
}
}
}
set(value) {
synchronized(this) {
_value = value
}
}
override fun isInitialized() = _value !== UNINITIALIZED_VALUE
override fun toString() = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
fun drop() {
synchronized(this) {
_value = UNINITIALIZED_VALUE
}
}
} | apache-2.0 | 0982f62a048929d2d0b58cf6cce76805 | 24.42 | 140 | 0.612598 | 4.233333 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/ui/colorpicker/ColorPipetteButton.kt | 1 | 1512 | /*
* 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.intellij.ui.colorpicker
import com.intellij.ui.colorpicker.ColorPickerModel
import java.awt.*
import javax.swing.*
class ColorPipetteButton(private val colorPickerModel: ColorPickerModel, private val pipette: ColorPipette) : JButton() {
init {
isRolloverEnabled = true
icon = pipette.icon
rolloverIcon = pipette.rolloverIcon
pressedIcon = pipette.pressedIcon
addActionListener { pipette.pick(MyCallback(colorPickerModel)) }
}
private inner class MyCallback(val model: ColorPickerModel): ColorPipette.Callback {
private val originalColor = model.color
override fun picked(pickedColor: Color) = model.setColor(pickedColor, this@ColorPipetteButton)
override fun update(updatedColor: Color) = model.setColor(updatedColor, this@ColorPipetteButton)
override fun cancel() = model.setColor(originalColor, this@ColorPipetteButton)
}
}
| apache-2.0 | a6bf11be81583e7777461cefcc6f5024 | 33.363636 | 121 | 0.758598 | 4.32 | false | false | false | false |
JuliusKunze/kotlin-native | shared/src/main/kotlin/org/jetbrains/kotlin/konan/target/KonanProperties.kt | 1 | 3645 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed -> in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.konan.properties
import org.jetbrains.kotlin.konan.file.*
import org.jetbrains.kotlin.konan.target.*
import org.jetbrains.kotlin.konan.util.DependencyProcessor
class KonanProperties(val target: KonanTarget, val properties: Properties, val baseDir: String? = null) {
fun downloadDependencies() {
dependencyProcessor!!.run()
}
fun targetString(key: String): String?
= properties.targetString(key, target)
fun targetList(key: String): List<String>
= properties.targetList(key, target)
fun hostString(key: String): String?
= properties.hostString(key)
fun hostList(key: String): List<String>
= properties.hostList(key)
fun hostTargetString(key: String): String?
= properties.hostTargetString(key, target)
fun hostTargetList(key: String): List<String>
= properties.hostTargetList(key, target)
val llvmHome get() = hostString("llvmHome")
// TODO: Delegate to a map?
val llvmLtoNooptFlags get() = targetList("llvmLtoNooptFlags")
val llvmLtoOptFlags get() = targetList("llvmLtoOptFlags")
val llvmLtoFlags get() = targetList("llvmLtoFlags")
val llvmLtoDynamicFlags get() = targetList("llvmLtoDynamicFlags")
val entrySelector get() = targetList("entrySelector")
val linkerOptimizationFlags get() = targetList("linkerOptimizationFlags")
val linkerKonanFlags get() = targetList("linkerKonanFlags")
val linkerNoDebugFlags get() = targetList("linkerNoDebugFlags")
val linkerDynamicFlags get() = targetList("linkerDynamicFlags")
val llvmDebugOptFlags get() = targetList("llvmDebugOptFlags")
val s2wasmFlags get() = targetList("s2wasmFlags")
val targetSysRoot get() = targetString("targetSysRoot")
val libffiDir get() = targetString("libffiDir")
val gccToolchain get() = targetString("gccToolchain")
val targetArg get() = targetString("quadruple")
// Notice: these ones are host-target.
val targetToolchain get() = hostTargetString("targetToolchain")
val dependencies get() = hostTargetList("dependencies")
private fun absolute(value: String?): String =
dependencyProcessor!!.resolveRelative(value!!).absolutePath
val absoluteTargetSysRoot get() = absolute(targetSysRoot)
val absoluteTargetToolchain get() = absolute(targetToolchain)
val absoluteGccToolchain get() = absolute(gccToolchain)
val absoluteLlvmHome get() = absolute(llvmHome)
val absoluteLibffiDir get() = absolute(libffiDir)
val mingwWithLlvm: String?
get() {
if (target != KonanTarget.MINGW) {
error("Only mingw target can have '.mingwWithLlvm' property")
}
// TODO: make it a property in the konan.properties.
// Use (equal) llvmHome fow now.
return targetString("llvmHome")
}
val osVersionMin: String? get() = targetString("osVersionMin")
private val dependencyProcessor = baseDir?.let { DependencyProcessor(java.io.File(it), this) }
}
| apache-2.0 | 38125de16d41e8a6e201b7bf47c37fc3 | 40.420455 | 105 | 0.706447 | 4.308511 | false | false | false | false |
Pozo/threejs-kotlin | examples/src/main/kotlin/examples/HelloWorldShadowWithPlane.kt | 1 | 3045 | package examples
import three.Shading
import three.ShadowMap
import three.cameras.PerspectiveCamera
import three.geometries.BoxGeometry
import three.geometries.PlaneGeometry
import three.lights.PointLight
import three.materials.phong.MeshPhongMaterial
import three.materials.phong.MeshPhongMaterialParam
import three.objects.Mesh
import three.renderers.webglrenderer.WebGLRenderer
import three.renderers.webglrenderer.WebGLRendererParams
import three.scenes.Scene
import kotlin.browser.document
import kotlin.browser.window
import kotlin.math.PI
class HelloWorldShadowWithPlane {
val renderer: WebGLRenderer
val scene: Scene
val camera: PerspectiveCamera
val cube: Mesh
init {
scene = Scene()
camera = PerspectiveCamera(75, (window.innerWidth / window.innerHeight).toDouble(), 0.1, 1000)
val params = WebGLRendererParams()
params.antialias = true
renderer = WebGLRenderer(params)
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
renderer.shadowMap.type = ShadowMap.PCFSoftShadowMap.value
document.body?.appendChild(renderer.domElement)
val light = createLight()
scene.add(light)
cube = createCube()
scene.add(cube)
val plane = createPlane()
scene.add(plane)
plane.position.y = -2.0
plane.rotation.x = - PI / 2
camera.position.z = 5.0
camera.position.y = 2.0
camera.lookAt(cube.position)
}
private fun createPlane(): Mesh {
val planeGeometry = PlaneGeometry(20, 20, 32, 32)
val param = MeshPhongMaterialParam()
param.color = 0x00dddd
param.specular = 0x009900
param.shininess = 10
param.shading = Shading.FlatShading.value
val planeMaterial = MeshPhongMaterial(param)
val plane = Mesh(planeGeometry, planeMaterial)
plane.receiveShadow = true
return plane
}
private fun createCube(): Mesh {
val geometry = BoxGeometry(1, 1, 1)
val param = createPhongMaterialParam()
val material = MeshPhongMaterial(param)
val mesh = Mesh(geometry, material)
mesh.castShadow = true
return mesh
}
private fun createLight(): PointLight {
val light = PointLight(0xffffff, 1.0, 100)
light.position.set(0f, 8f, 0f)
light.castShadow = true
light.shadow.mapSize.width = 1024f
light.shadow.mapSize.height = 1024f
return light
}
private fun createPhongMaterialParam(): MeshPhongMaterialParam {
val param = MeshPhongMaterialParam()
param.color = 0xdddddd
param.specular = 0x999999
param.shininess = 15
param.shading = Shading.FlatShading.value
return param
}
fun render() {
window.requestAnimationFrame {
cube.rotation.x += 0.01
cube.rotation.y += 0.01
render()
}
renderer.render(scene, camera)
}
}
| mit | a15b179774b044f0f34d49814543f616 | 25.710526 | 102 | 0.660755 | 4.438776 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/arrays/multiDecl/MultiDeclForComponentExtensions.kt | 5 | 345 | class C(val i: Int) {
}
operator fun C.component1() = i + 1
operator fun C.component2() = i + 2
fun doTest(l : Array<C>): String {
var s = ""
for ((a, b) in l) {
s += "$a:$b;"
}
return s
}
fun box(): String {
val l = Array<C>(3, {x -> C(x)})
val s = doTest(l)
return if (s == "1:2;2:3;3:4;") "OK" else "fail: $s"
} | apache-2.0 | 7908e4be1ca10d083e6e098f11d08c57 | 17.210526 | 54 | 0.486957 | 2.412587 | false | true | false | false |
AndroidX/androidx | compose/material/material/src/androidAndroidTest/kotlin/androidx/compose/material/ColorsTest.kt | 3 | 4180 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
class ColorsTest {
@get:Rule
val rule = createComposeRule()
/**
* Test for switching between provided [Colors], ensuring that the existing colors objects
* are preserved. (b/182635582)
*/
@Test
fun switchingBetweenColors() {
val lightColors = lightColors()
val darkColors = darkColors()
val colorState = mutableStateOf(lightColors)
var currentColors: Colors? = null
rule.setContent {
MaterialTheme(colorState.value) {
Button(onReadColors = { currentColors = it })
}
}
rule.runOnIdle {
// Initial colors should never be touched
assertThat(lightColors.contentEquals(lightColors())).isTrue()
assertThat(darkColors.contentEquals(darkColors())).isTrue()
// Current colors should be light
assertThat(currentColors!!.contentEquals(lightColors)).isTrue()
// Change current colors to dark
colorState.value = darkColors
}
rule.runOnIdle {
// Initial colors should never be touched
assertThat(lightColors.contentEquals(lightColors())).isTrue()
assertThat(darkColors.contentEquals(darkColors())).isTrue()
// Current colors should be dark
assertThat(currentColors!!.contentEquals(darkColors)).isTrue()
// Change current colors back to light
colorState.value = lightColors
}
rule.runOnIdle {
// Initial colors should never be touched
assertThat(lightColors.contentEquals(lightColors())).isTrue()
assertThat(darkColors.contentEquals(darkColors())).isTrue()
// Current colors should be light
assertThat(currentColors!!.contentEquals(lightColors)).isTrue()
}
}
@Composable
private fun Button(onReadColors: (Colors) -> Unit) {
val colors = MaterialTheme.colors
onReadColors(colors)
}
}
/**
* [Colors] is @Stable, so by contract it doesn't have equals implemented. And since it creates a
* new Colors object to mutate internally, we can't compare references. Instead we compare the
* properties to make sure that the properties are equal.
*
* @return true if all the properties inside [this] are equal to those in [other], false otherwise.
*/
private fun Colors.contentEquals(other: Colors): Boolean {
if (primary != other.primary) return false
if (primaryVariant != other.primaryVariant) return false
if (secondary != other.secondary) return false
if (secondaryVariant != other.secondaryVariant) return false
if (background != other.background) return false
if (surface != other.surface) return false
if (error != other.error) return false
if (onPrimary != other.onPrimary) return false
if (onSecondary != other.onSecondary) return false
if (onBackground != other.onBackground) return false
if (onSurface != other.onSurface) return false
if (onError != other.onError) return false
if (isLight != other.isLight) return false
return true
} | apache-2.0 | 492927bd9860e7d8abb43cc04b30da59 | 36.666667 | 99 | 0.686603 | 4.871795 | false | true | false | false |
Xenoage/Zong | core/src/com/xenoage/zong/core/header/ColumnHeader.kt | 1 | 12471 | package com.xenoage.zong.core.header
import com.xenoage.utils.annotations.Untested
import com.xenoage.utils.math.Fraction
import com.xenoage.utils.math._0
import com.xenoage.utils.throwEx
import com.xenoage.zong.core.Score
import com.xenoage.zong.core.format.Break
import com.xenoage.zong.core.music.ColumnElement
import com.xenoage.zong.core.music.MeasureSide
import com.xenoage.zong.core.music.barline.Barline
import com.xenoage.zong.core.music.barline.BarlineRepeat.Both
import com.xenoage.zong.core.music.direction.DaCapo
import com.xenoage.zong.core.music.direction.NavigationSign
import com.xenoage.zong.core.music.direction.Tempo
import com.xenoage.zong.core.music.key.Key
import com.xenoage.zong.core.music.time.TimeSignature
import com.xenoage.zong.core.music.util.*
import com.xenoage.zong.core.music.volta.Volta
import com.xenoage.zong.core.position.Beat
import com.xenoage.zong.core.position.MP
import com.xenoage.zong.core.position.MP.Companion.atColumnBeat
import com.xenoage.zong.core.position.MPContainer
import com.xenoage.zong.core.position.MPElement
/**
* A [ColumnHeader] stores information that
* is used for the whole measure column,
* i.e. key signature and time signature.
*
* The start and end barline as well as middle barlines
* are saved here, and a volta if it begins in this
* measure.
*
* There is also a list of tempo directions for this
* measure and layout break information.
*/
class ColumnHeader(
/** Back reference to the parent score. */
val parentScore: Score
) : MPContainer {
/** The time signature at the beginning of this measure */
var time: TimeSignature? = null; private set
/** The barline at the beginning of this measure */
var startBarline: Barline? = null
/** The barline at the end of this measure */
var endBarline: Barline? = null
/** The barlines in the middle of the measure */
var middleBarlines: BeatEList<Barline> = BeatEList()
/** The volta that begins at this measure */
var volta: Volta? = null
/** The key signature changes in this measure */
var keys: BeatEList<Key> = BeatEList()
/** The tempo changes in this measure */
var tempos: BeatEList<Tempo> = BeatEList()
/** The [Break] after this measure, or null. */
var measureBreak: Break? = null
/** The [NavigationSign] at the beginning of this measure, or null */
var navigationTarget: NavigationSign? = null
/** The [NavigationSign] at the end of this measure, or null. */
var navigationOrigin: NavigationSign? = null
/** Back reference: measure index, or -1 if not part of a score. */
val parentMeasureIndex: Int =
parentScore.header.columnHeaders.indexOf(this)
/**
* A sequence of all [ColumnElement]s in this column, which
* are assigned to a beat (middle barlines, keys and tempos).
*/
val columnElementsWithBeats: Sequence<BeatE<out ColumnElement>>
get() = middleBarlines.asSequence() + keys.asSequence() + tempos.asSequence()
/**
* A sequence of all [ColumnElement]s in this column, which
* are not assigned to a beat (time, start and end barline, volta, measure break).
*/
val columnElementsWithoutBeats: Sequence<out ColumnElement>
get() = sequenceOf(time, startBarline, endBarline, volta, measureBreak).filterNotNull()
/**
* Sets the time signature, or null if unset.
* If there is already one, it is replaced and returned (otherwise null).
*/
fun setTime(time: TimeSignature?) =
replace({ this.time = it }, this.time, time)
/**
* Sets the barline at the beginning of this measure, or null if unset.
* If there is already one, it is replaced and returned (otherwise null).
*/
fun setStartBarline(startBarline: Barline?) =
replace({ this.startBarline = it}, this.startBarline, checkStartBarline(startBarline))
/**
* Sets the barline at the end of this measure, or null if unset.
* If there is already one, it is replaced and returned (otherwise null).
*/
fun setEndBarline(endBarline: Barline?) =
replace({ this.endBarline = it}, this.endBarline, checkEndBarline(endBarline))
/**
* Sets a barline in the middle of the measure (or null to remove it).
* If there is already one at the given beat, it is replaced and returned (otherwise null).
*/
fun setMiddleBarline(middleBarline: Barline?, beat: Fraction) =
replace(middleBarlines, beat, middleBarline)
/**
* Sets the volta beginning at this measure, or null if unset.
* If there is already one, it is replaced and returned (otherwise null).
*/
fun setVolta(volta: Volta) =
replace({ this.volta = it }, this.volta, volta)
/**
* Sets a key in this measure (or null to remove it).
* If there is already one at the given beat, it is replaced and returned (otherwise null).
*/
fun setKey(key: Key?, beat: Fraction) =
replace(this.keys, beat, key)
/**
* Sets a tempo in this measure (or null to remove it)
* If there is already one at the given beat, it is replaced and returned (otherwise null).
*/
fun setTempo(tempo: Tempo?, beat: Fraction) =
replace(this.tempos, beat, tempo)
/**
* Sets the [Break] after this measure, or null if there is none.
* If there is already one, it is replaced and returned (otherwise null).
*/
fun setBreak(measureBreak: Break?) =
replace({ this.measureBreak = measureBreak}, this.measureBreak, measureBreak)
/**
* Sets the [NavigationSign] (or null to remove it) at the beginning of a measure
* into which can be jumped, e.g. a jump indicated by "segno" or "coda".
* If there is already one, it is replaced and returned (otherwise null).
* Setting a "capo" is not possible here.
*/
fun setNavigationTarget(sign: NavigationSign?): NavigationSign? {
if (sign is DaCapo)
throw IllegalArgumentException("DaCapo can not be a navigation target")
return replace({ this.navigationTarget = it}, this.navigationTarget, sign)
}
/**
* Sets the [NavigationSign] (or null to remove it) to perform after this measure,
* e.g. a jump indicated by "da capo", "dal segno" or "to coda".
* If there is already one, it is replaced and returned (otherwise null).
*/
fun setNavigationOrigin(sign: NavigationSign?) =
replace({ this.navigationOrigin = it}, this.navigationOrigin, sign)
/**
* Checks the given start barline.
*/
private fun checkStartBarline(startBarline: Barline?): Barline? {
//both side repeat is not allowed
if (startBarline != null && startBarline.repeat === Both)
throw IllegalArgumentException("${Both} is not supported for a start barline.")
return startBarline
}
/**
* Checks the given end barline.
*/
private fun checkEndBarline(endBarline: Barline?): Barline? {
//both side repeat is not allowed
if (endBarline != null && endBarline.repeat === Both)
throw IllegalArgumentException("${Both} is not supported for an end barline.")
return endBarline
}
/**
* Sets the given [ColumnElement] at the given beat.
*
* If there is already another element of this type,
* it is replaced and returned (otherwise null).
*
* @param element the element to set
* @param beat the beat where to add the element. Only needed for
* key, tempo, middle barlines and navigation signs
* @param side Only needed for barlines
*/
@Untested
fun setColumnElement(element: ColumnElement, beat: Fraction? = null,
side: MeasureSide? = null): ColumnElement? {
return when (element) {
is Barline -> {
//left or right barline
if (side == MeasureSide.Left)
setStartBarline(element)
else if (side == MeasureSide.Right)
setEndBarline(element)
else //middle barline
setMiddleBarline(element, checkNotNull(beat))
}
is Break -> setBreak(element)
is Key -> setKey(element, checkNotNull(beat))
is Tempo -> setTempo(element, checkNotNull(beat))
is TimeSignature -> setTime(element)
is Volta -> setVolta(element)
is NavigationSign -> {
//write at beginning of measure (jump target), when beat is 0,
//otherwise write to end of measure (jump origin)
if (checkNotNull(beat).is0)
setNavigationTarget(element)
else
setNavigationOrigin(element)
}
else -> throwEx()
}
}
/**
* Removes the given [ColumnElement].
*/
@Untested
fun removeColumnElement(element: ColumnElement) {
element.parent = null
when (element) {
is Barline -> {
//left or right barline
if (element === startBarline)
startBarline = null
else if (element === endBarline)
endBarline = null
else
middleBarlines.remove(element) //middle barline
}
is Break -> measureBreak = null
is Key -> keys.remove(element)
is Tempo -> tempos.remove(element)
is TimeSignature -> time = null
is Volta -> volta = null
else -> throwEx()
}
}
/**
* Replaces the given [ColumnElement] with the other given one.
*/
@Untested
fun <T : ColumnElement> replaceColumnElement(oldElement: T, newElement: T) {
when (newElement) {
is Barline -> {
//left or right barline
if (oldElement === startBarline)
setStartBarline(newElement)
else if (oldElement === endBarline)
setEndBarline(newElement)
else {
//middle barline
for (middleBarline in middleBarlines) {
if (middleBarline.element === oldElement) {
setMiddleBarline(newElement, middleBarline.beat)
return
}
}
throwEx("Old barline not part of this column")
}
}
is Break -> setBreak(newElement)
is Key -> {
for (key in keys) {
if (key.element === oldElement) {
setKey(newElement, key.beat)
return
}
}
throwEx("Old key not part of this column")
}
is Tempo -> {
for (tempo in tempos) {
if (tempo.element === oldElement) {
setTempo(newElement as Tempo, tempo.beat)
return
}
}
throwEx("Old tempo not part of this column")
}
is TimeSignature -> setTime(newElement)
is Volta -> setVolta(newElement)
else -> throwEx()
}
}
/**
* Gets the [MP] of the given [ColumnElement], or null if it is not part
* of this column or this column is not part of a score.
*/
override fun getChildMP(element: MPElement): MP? {
val score = parentScore
val measureIndex = parentMeasureIndex
if (score === null || measureIndex === null)
return null
//elements at the beginning of the measure
if (time === element || startBarline === element || volta === element)
return atColumnBeat(measureIndex, _0)
//elements at the end of the measure
else if (endBarline === element || measureBreak === element)
return atColumnBeat(measureIndex, score.getMeasureBeats(measureIndex))
//elements in the middle of the measure
else if (element is Barline)
return getMPIn(element, middleBarlines)
else if (element is Key)
return getMPIn(element, keys)
else if (element is Tempo)
return getMPIn(element, tempos)
return null
}
/**
* Gets the [MP] of the given element within the given list of elements,
* or null if the list of elements is null or the element could not be found.
*/
private fun getMPIn(element: MPElement, elements: BeatEList<*>?): MP? =
parentMeasureIndex?.let { measure ->
elements?.find { it.element === element }?.let { atColumnBeat(measure, it.beat) } }
/**
* Gets the [MeasureSide] of the given element in this column. This applies only to
* start and end barlines. For all other elements, null is returned.
*/
fun getSide(element: ColumnElement) = when {
element === startBarline -> MeasureSide.Left
element === endBarline -> MeasureSide.Right
else -> null
}
/**
* Calls the given function to update the given property, and updates the parent
* of the given old and new property value to null and this instance. The old value is returned.
*/
private fun <T : ColumnElement> replace(propertyUpdate: (T?) -> Unit, oldValue: T?, newValue: T?): T? {
propertyUpdate(newValue)
newValue?.parent = this
oldValue?.parent = null
return oldValue
}
/**
* For the given list, find the element at the given beat. If one is found, replace it by the
* the given new value (or removes it if the new value is null) and sets the parent of the old value to null.
* The parent of the new value is set to this instance. The old value is returned.
*/
private fun <T : ColumnElement> replace(list: BeatEList<T>, beat: Beat, newValue: T?): T? {
var oldValue: T? = if (newValue != null) list.set(newValue, beat) else list.remove(beat)
newValue?.parent = this
oldValue?.parent = null
return oldValue
}
} | agpl-3.0 | 93bf74a8366d84c464a71d6ef3008fbd | 32.983651 | 110 | 0.698501 | 3.755194 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/timeline/GHPRTimelineItemComponentFactory.kt | 1 | 13549 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.timeline
import com.intellij.collaboration.async.CompletableFutureUtil.successOnEdt
import com.intellij.collaboration.ui.codereview.timeline.TimelineItemComponentFactory
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ide.plugins.newui.HorizontalLayout
import com.intellij.ide.plugins.newui.VerticalLayout
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.ui.components.ActionLink
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.ui.components.panels.HorizontalBox
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBDimension
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.intellij.lang.annotations.Language
import org.jetbrains.plugins.github.GithubIcons
import org.jetbrains.plugins.github.api.data.GHActor
import org.jetbrains.plugins.github.api.data.GHGitActor
import org.jetbrains.plugins.github.api.data.GHIssueComment
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequest
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestCommitShort
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReview
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewState.*
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineEvent
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.comment.convertToHtml
import org.jetbrains.plugins.github.pullrequest.comment.ui.GHPRReviewThreadComponent
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRCommentsDataProvider
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRDetailsDataProvider
import org.jetbrains.plugins.github.pullrequest.data.provider.GHPRReviewDataProvider
import org.jetbrains.plugins.github.pullrequest.ui.GHEditableHtmlPaneHandle
import org.jetbrains.plugins.github.pullrequest.ui.GHTextActions
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import org.jetbrains.plugins.github.ui.util.HtmlEditorPane
import java.awt.Dimension
import java.util.*
import javax.swing.*
import kotlin.math.ceil
import kotlin.math.floor
class GHPRTimelineItemComponentFactory(private val project: Project,
private val detailsDataProvider: GHPRDetailsDataProvider,
private val commentsDataProvider: GHPRCommentsDataProvider,
private val reviewDataProvider: GHPRReviewDataProvider,
private val avatarIconsProvider: GHAvatarIconsProvider,
private val reviewsThreadsModelsProvider: GHPRReviewsThreadsModelsProvider,
private val reviewDiffComponentFactory: GHPRReviewThreadDiffComponentFactory,
private val eventComponentFactory: GHPRTimelineEventComponentFactory<GHPRTimelineEvent>,
private val selectInToolWindowHelper: GHPRSelectInToolWindowHelper,
private val currentUser: GHUser) : TimelineItemComponentFactory<GHPRTimelineItem> {
override fun createComponent(item: GHPRTimelineItem): Item {
try {
return when (item) {
is GHPullRequestCommitShort -> createComponent(item)
is GHIssueComment -> createComponent(item)
is GHPullRequestReview -> createComponent(item)
is GHPRTimelineEvent -> eventComponentFactory.createComponent(item)
is GHPRTimelineItem.Unknown -> throw IllegalStateException("Unknown item type: " + item.__typename)
else -> error("Undefined item type")
}
}
catch (e: Exception) {
return Item(AllIcons.General.Warning, HtmlEditorPane(GithubBundle.message("cannot.display.item", e.message ?: "")))
}
}
private fun createComponent(commit: GHPullRequestCommitShort): Item {
val gitCommit = commit.commit
val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply {
add(userAvatar(gitCommit.author))
add(HtmlEditorPane(gitCommit.messageHeadlineHTML))
add(ActionLink(gitCommit.abbreviatedOid) {
selectInToolWindowHelper.selectCommit(gitCommit.abbreviatedOid)
})
}
return Item(AllIcons.Vcs.CommitNode, titlePanel)
}
fun createComponent(details: GHPullRequestShort): Item {
val contentPanel: JPanel?
val actionsPanel: JPanel?
if (details is GHPullRequest) {
val textPane = HtmlEditorPane(details.body.convertToHtml(project))
val panelHandle = GHEditableHtmlPaneHandle(project,
textPane,
{ detailsDataProvider.getDescriptionMarkdownBody(EmptyProgressIndicator()) },
{ newText ->
detailsDataProvider.updateDetails(EmptyProgressIndicator(),
description = newText).successOnEdt {
textPane.setBody(it.body)
}
})
contentPanel = panelHandle.panel
actionsPanel = if (details.viewerCanUpdate) NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply {
add(GHTextActions.createEditButton(panelHandle))
}
else null
}
else {
contentPanel = null
actionsPanel = null
}
val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply {
add(actionTitle(details.author, GithubBundle.message("pull.request.timeline.created"), details.createdAt))
if (actionsPanel != null && actionsPanel.componentCount > 0) add(actionsPanel)
}
return Item(userAvatar(details.author), titlePanel, contentPanel)
}
private fun createComponent(comment: GHIssueComment): Item {
val textPane = HtmlEditorPane(comment.body.convertToHtml(project))
val panelHandle = GHEditableHtmlPaneHandle(project,
textPane,
{ commentsDataProvider.getCommentMarkdownBody(EmptyProgressIndicator(), comment.id) },
{ newText ->
commentsDataProvider.updateComment(EmptyProgressIndicator(), comment.id,
newText).successOnEdt { textPane.setBody(it) }
})
val actionsPanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply {
if (comment.viewerCanUpdate) add(GHTextActions.createEditButton(panelHandle))
if (comment.viewerCanDelete) add(GHTextActions.createDeleteButton {
commentsDataProvider.deleteComment(EmptyProgressIndicator(), comment.id)
})
}
val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply {
add(actionTitle(comment.author, GithubBundle.message("pull.request.timeline.commented"), comment.createdAt))
if (actionsPanel.componentCount > 0) add(actionsPanel)
}
return Item(userAvatar(comment.author), titlePanel, panelHandle.panel)
}
private fun createComponent(review: GHPullRequestReview): Item {
val reviewThreadsModel = reviewsThreadsModelsProvider.getReviewThreadsModel(review.id)
val panelHandle: GHEditableHtmlPaneHandle?
if (review.body.isNotEmpty()) {
val editorPane = HtmlEditorPane(review.body)
panelHandle =
GHEditableHtmlPaneHandle(project,
editorPane,
{ reviewDataProvider.getReviewMarkdownBody(EmptyProgressIndicator(), review.id) },
{ newText ->
reviewDataProvider.updateReviewBody(EmptyProgressIndicator(), review.id, newText).successOnEdt {
editorPane.setBody(it)
}
})
}
else {
panelHandle = null
}
val actionsPanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(8))).apply {
if (panelHandle != null && review.viewerCanUpdate) add(GHTextActions.createEditButton(panelHandle))
}
val contentPanel = NonOpaquePanel(VerticalLayout(JBUIScale.scale(12))).apply {
border = JBUI.Borders.emptyTop(4)
if (panelHandle != null) add(panelHandle.panel, VerticalLayout.FILL_HORIZONTAL)
add(GHPRReviewThreadsPanel.create(reviewThreadsModel) {
GHPRReviewThreadComponent.createWithDiff(project, it, reviewDataProvider, selectInToolWindowHelper, reviewDiffComponentFactory,
avatarIconsProvider, currentUser)
}, VerticalLayout.FILL_HORIZONTAL)
}
val actionText = when (review.state) {
APPROVED -> GithubBundle.message("pull.request.timeline.approved.changes")
CHANGES_REQUESTED -> GithubBundle.message("pull.request.timeline.requested.changes")
PENDING -> GithubBundle.message("pull.request.timeline.started.review")
COMMENTED, DISMISSED -> GithubBundle.message("pull.request.timeline.reviewed")
}
val titlePanel = NonOpaquePanel(HorizontalLayout(JBUIScale.scale(12))).apply {
add(actionTitle(avatarIconsProvider, review.author, actionText, review.createdAt))
if (actionsPanel.componentCount > 0) add(actionsPanel)
}
val icon = when (review.state) {
APPROVED -> GithubIcons.ReviewAccepted
CHANGES_REQUESTED -> GithubIcons.ReviewRejected
COMMENTED -> GithubIcons.Review
DISMISSED -> GithubIcons.Review
PENDING -> GithubIcons.Review
}
return Item(icon, titlePanel, contentPanel, NOT_DEFINED_SIZE)
}
private fun userAvatar(user: GHActor?): JLabel {
return userAvatar(avatarIconsProvider, user)
}
private fun userAvatar(user: GHGitActor?): JLabel {
return LinkLabel<Any>("", avatarIconsProvider.getIcon(user?.avatarUrl), LinkListener { _, _ ->
user?.url?.let { BrowserUtil.browse(it) }
})
}
class Item(val marker: JLabel, title: JComponent, content: JComponent? = null, size: Dimension = getDefaultSize()) : JPanel() {
constructor(markerIcon: Icon, title: JComponent, content: JComponent? = null, size: Dimension = getDefaultSize())
: this(createMarkerLabel(markerIcon), title, content, size)
init {
isOpaque = false
layout = MigLayout(LC().gridGap("0", "0")
.insets("0", "0", "0", "0")
.fill()).apply {
columnConstraints = "[]${JBUIScale.scale(8)}[]"
}
add(marker, CC().pushY())
add(title, CC().pushX())
if (content != null) add(content, CC().newline().skip().grow().push().maxWidth(size))
}
companion object {
private fun CC.maxWidth(dimension: Dimension) = if (dimension.width > 0) this.maxWidth("${dimension.width}") else this
private fun createMarkerLabel(markerIcon: Icon) =
JLabel(markerIcon).apply {
val verticalGap = if (markerIcon.iconHeight < 20) (20f - markerIcon.iconHeight) / 2 else 0f
val horizontalGap = if (markerIcon.iconWidth < 20) (20f - markerIcon.iconWidth) / 2 else 0f
border = JBUI.Borders.empty(floor(verticalGap).toInt(), floor(horizontalGap).toInt(),
ceil(verticalGap).toInt(), ceil(horizontalGap).toInt())
}
}
}
companion object {
private val NOT_DEFINED_SIZE = Dimension(-1, -1)
fun getDefaultSize() = Dimension(GHUIUtil.getPRTimelineWidth(), -1)
fun userAvatar(avatarIconsProvider: GHAvatarIconsProvider, user: GHActor?): JLabel {
return LinkLabel<Any>("", avatarIconsProvider.getIcon(user?.avatarUrl), LinkListener { _, _ ->
user?.url?.let { BrowserUtil.browse(it) }
})
}
fun actionTitle(avatarIconsProvider: GHAvatarIconsProvider, actor: GHActor?, @Language("HTML") actionHTML: String, date: Date)
: JComponent {
return HorizontalBox().apply {
add(userAvatar(avatarIconsProvider, actor))
add(Box.createRigidArea(JBDimension(8, 0)))
add(actionTitle(actor, actionHTML, date))
}
}
fun actionTitle(actor: GHActor?, actionHTML: String, date: Date): JComponent {
//language=HTML
val text = """<a href='${actor?.url}'>${actor?.login ?: "unknown"}</a> $actionHTML ${GHUIUtil.formatActionDate(date)}"""
return HtmlEditorPane(text).apply {
foreground = UIUtil.getContextHelpForeground()
}
}
}
} | apache-2.0 | 73ca19ceb9ff3dca4f00878d88f62f16 | 48.452555 | 140 | 0.674441 | 5.237341 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/StepperValueFormView.kt | 1 | 3643 | package com.habitrpg.android.habitica.ui.views.tasks.form
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.EditText
import android.widget.ImageButton
import android.widget.RelativeLayout
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.OnChangeTextWatcher
import com.habitrpg.android.habitica.extensions.asDrawable
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import java.text.DecimalFormat
class StepperValueFormView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
private val editText: EditText by bindView(R.id.edit_text)
private val upButton: ImageButton by bindView(R.id.up_button)
private val downButton: ImageButton by bindView(R.id.down_button)
var onValueChanged: ((Double) -> Unit)? = null
private val decimalFormat = DecimalFormat("0.###")
private var editTextIsFocused = false
var value = 0.0
set(new) {
var newValue = if (new >= minValue) new else minValue
maxValue?.let {
if (newValue > it && it > 0) {
newValue = it
}
}
val oldValue = field
field = newValue
if (oldValue != new) {
valueString = decimalFormat.format(newValue)
}
downButton.isEnabled = field > minValue
maxValue?.let {
if (it == 0.0) return@let
upButton.isEnabled = value < it
}
onValueChanged?.invoke(value)
}
var maxValue: Double? = null
var minValue: Double = 0.0
private var valueString = ""
set(value) {
if (value.isEmpty()) return
field = value
if (editText.text.toString() != field) {
editText.setText(field)
if (editTextIsFocused) {
editText.setSelection(field.length)
}
}
val newValue = field.toDoubleOrNull() ?: 0.0
if (this.value != newValue) {
this.value = newValue
}
}
var iconDrawable: Drawable?
get() {
return editText.compoundDrawables.firstOrNull()
}
set(value) {
editText.setCompoundDrawablesWithIntrinsicBounds(value, null, null, null)
}
init {
inflate(R.layout.form_stepper_value, true)
val attributes = context.theme?.obtainStyledAttributes(
attrs,
R.styleable.StepperValueFormView,
0, 0)
//set value here, so that the setter is called and everything is set up correctly
maxValue = attributes?.getFloat(R.styleable.StepperValueFormView_maxValue, 0f)?.toDouble()
minValue = attributes?.getFloat(R.styleable.StepperValueFormView_minValue, 0f)?.toDouble() ?: 0.0
value = attributes?.getFloat(R.styleable.StepperValueFormView_defaultValue, 10.0f)?.toDouble() ?: 10.0
iconDrawable = attributes?.getDrawable(R.styleable.StepperValueFormView_iconDrawable) ?: HabiticaIconsHelper.imageOfGold().asDrawable(context.resources)
upButton.setOnClickListener {
value += 1
}
downButton.setOnClickListener {
value -= 1
}
editText.addTextChangedListener(OnChangeTextWatcher { s, _, _, _ ->
valueString = s.toString()
})
editText.setOnFocusChangeListener { _, hasFocus -> editTextIsFocused = hasFocus }
}
} | gpl-3.0 | e3bba8dc0d60c7c66e933700544d50c1 | 33.056075 | 160 | 0.653033 | 4.74349 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/common/collectors/CommonConstraintsCollector.kt | 2 | 5929 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.inference.common.collectors
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.nj2k.inference.common.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.asAssignment
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class CommonConstraintsCollector : ConstraintsCollector() {
override fun ConstraintBuilder.collectConstraints(
element: KtElement,
boundTypeCalculator: BoundTypeCalculator,
inferenceContext: InferenceContext,
resolutionFacade: ResolutionFacade
) = with(boundTypeCalculator) {
when {
element is KtBinaryExpressionWithTypeRHS && KtPsiUtil.isUnsafeCast(element) -> {
element.right?.typeElement?.let { inferenceContext.typeElementToTypeVariable[it] }?.also { typeVariable ->
element.left.isSubtypeOf(typeVariable, ConstraintPriority.ASSIGNMENT)
}
}
element is KtBinaryExpression && element.asAssignment() != null -> {
element.right?.isSubtypeOf(element.left ?: return, ConstraintPriority.ASSIGNMENT)
}
element is KtVariableDeclaration -> {
inferenceContext.declarationToTypeVariable[element]?.also { typeVariable ->
element.initializer?.isSubtypeOf(typeVariable, ConstraintPriority.INITIALIZER)
}
}
element is KtParameter -> {
inferenceContext.declarationToTypeVariable[element]?.also { typeVariable ->
element.defaultValue?.isSubtypeOf(
typeVariable,
ConstraintPriority.INITIALIZER
)
}
}
element is KtReturnExpression -> {
val functionTypeVariable = element.getTargetFunction(element.analyze(resolutionFacade))
?.resolveToDescriptorIfAny(resolutionFacade)
?.let { functionDescriptor ->
inferenceContext.declarationDescriptorToTypeVariable[functionDescriptor]
} ?: return
element.returnedExpression?.isSubtypeOf(
functionTypeVariable,
ConstraintPriority.RETURN
)
}
element is KtReturnExpression -> {
val targetTypeVariable =
element.getTargetFunction(element.analyze(resolutionFacade))?.let { function ->
inferenceContext.declarationToTypeVariable[function]
}
if (targetTypeVariable != null) {
element.returnedExpression?.isSubtypeOf(
targetTypeVariable,
ConstraintPriority.RETURN
)
}
}
element is KtLambdaExpression -> {
val targetTypeVariable =
inferenceContext.declarationToTypeVariable[element.functionLiteral] ?: return
element.functionLiteral.bodyExpression?.statements?.lastOrNull()
?.takeIf { it !is KtReturnExpression }
?.also { implicitReturn ->
implicitReturn.isSubtypeOf(
targetTypeVariable,
ConstraintPriority.RETURN
)
}
}
element is KtForExpression -> {
val loopParameterTypeVariable =
element.loopParameter?.typeReference?.typeElement?.let { typeElement ->
inferenceContext.typeElementToTypeVariable[typeElement]
}
if (loopParameterTypeVariable != null) {
val loopRangeBoundType = element.loopRange?.boundType(inferenceContext) ?: return
val boundType =
element.loopRangeElementType(resolutionFacade)
?.boundType(
contextBoundType = loopRangeBoundType,
inferenceContext = inferenceContext
) ?: return
boundType.typeParameters.firstOrNull()?.boundType?.isSubtypeOf(
loopParameterTypeVariable.asBoundType(),
ConstraintPriority.ASSIGNMENT
)
}
}
}
Unit
}
private fun KtForExpression.loopRangeElementType(resolutionFacade: ResolutionFacade): KotlinType? {
val loopRangeType = loopRange?.getType(analyze(resolutionFacade)) ?: return null
return loopRangeType
.constructor
.declarationDescriptor
?.safeAs<ClassDescriptor>()
?.getMemberScope(loopRangeType.arguments)
?.getDescriptorsFiltered(DescriptorKindFilter.FUNCTIONS) {
it.asString() == "iterator"
}?.filterIsInstance<FunctionDescriptor>()
?.firstOrNull { it.valueParameters.isEmpty() }
?.original
?.returnType
}
} | apache-2.0 | 39951000eb6cf58b0d3a89a2a0a4212c | 44.267176 | 158 | 0.602968 | 6.87022 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/OldCrap1.kt | 1 | 24272 | package vgrechka
import alraune.*
import alraune.operations.*
import com.google.api.client.http.FileContent
import com.google.common.hash.Hashing
import vgrechka.BigPile.exitingProcessDespitePossibleJavaFXThread
import java.io.File
import java.io.FileOutputStream
import java.time.LocalDateTime
import kotlin.system.exitProcess
object OldCrap1 {
object CLIPile {
val regexpTag = "@@regexp "
class printAndCheckProcessResult(res: RunProcessResult, expectedLines: List<String>) {
init {
clog(res.stdout)
val stderr = res.stderr
if (stderr.isNotEmpty()) {
clog("---------- STDERR ----------\n")
clog(stderr)
sayError("I didn't expect any stderr from TF")
bitchAboutObscureOutput()
}
if (false) {
clog("Expected output:")
clog(expectedLines.joinToString("\n"))
exitProcess(0)
}
val actualLines = res.stdout.lines().map {it.trim()}.toMutableList()
for ((index, expected) in expectedLines.withIndex()) {
val actual = takeActualLine(actualLines)
if (actual == null) {
sayError("Expecting at least ${index + 1} lines of output from TF")
bitchAboutObscureOutput()
}
val expectedRegex = when {
expected.startsWith(regexpTag) -> Regex(expected.substring(regexpTag.length))
else -> Regex.fromLiteral(expected)
}
if (!actual.matches(expectedRegex)) {
sayError("Shitty TF output at line $index (0-based)")
sayError("Expected: [$expected]")
sayError("Actual: [$actual]")
bitchAboutObscureOutput()
}
}
if (actualLines.isNotEmpty()) {
clog("\n---------- UNEXPECTED EXTRA LINES { ----------")
clog(actualLines.joinToString("\n"))
clog("---------- UNEXPECTED EXTRA LINES } ----------\n")
sayError("Got unexpected extra ${actualLines.size} lines from TF")
bitchAboutObscureOutput()
}
}
fun takeActualLine(actualLines: MutableList<String>): String? {
if (actualLines.isEmpty()) {
return null
} else {
val s = actualLines.first()
actualLines.removeAt(0)
return s
}
}
fun sayError(msg: String) {
clog("[ERROR] $msg")
}
fun bitchAboutObscureOutput(): Nothing =
bitch("TF says to us some obscure bullshit")
}
}
// NOTE: For some reason WSL Bash doesn't want to work from IDEA console, so run this from cmd.exe
object CLI_BackShitUp__CheckShitUploadedToOneDrive {
@JvmStatic
fun main(args: Array<String>) {
val stamp = args[0]
BackShitUpStuff(stamp) {
it.uploadShitToOneDrive {
it.doubleCheck()
}
}
}
}
// Ex: _run vgrechka.CLI_BackShitUp
object CLI_BackShitUp {
@JvmStatic
fun main(args: Array<String>) {
BackShitUpStuff {
Pieces.cleanPrepareArchives(it)
it.uploadShitToDropbox()
it.uploadShitToGoogleDrive()
it.uploadShitToOneDrive()
it.checkInToTFVC()
}
}
}
object CLI_BackShitUp_DontUpload {
@JvmStatic
fun main(args: Array<String>) {
BackShitUpStuff {
Pieces.cleanPrepareArchives(it)
}
}
}
object CLI_BackShitUp_OnlyUploadToOneDriveAndTFVC {
@JvmStatic
fun main(args: Array<String>) {
BackShitUpStuff {
it.uploadShitToOneDrive()
it.checkInToTFVC()
}
}
}
object CLI_BackShitUp_Partial {
@JvmStatic
fun main(args: Array<String>) {
BackShitUpStuff {
it.uploadShitToOneDrive()
it.checkInToTFVC()
}
}
}
private object Pieces {
fun cleanPrepareArchives(it: BackShitUpStuff) {
it.recreateTFVCOutDir()
it.recreateReducedOutDir()
it.copyIDEASettings()
it.dumpPostgres()
it.zipFuckingEverything()
it.zipAPS()
it.zipFuckingPrivateEverything()
it.hashShit()
}
}
private class BackShitUpStuff(stamp: String? = null, block: (BackShitUpStuff) -> Unit) {
init {wtf("Don't run me, I'm fucking obsolete")}
val stamp = stamp ?: LocalDateTime.now().format(TimePile.FMT_YMD)!!
val tfvcOutDirWin = "e:/febig/bak/${this.stamp}"
val tfvcOutDirWSL = win2Wsl(tfvcOutDirWin)
val reducedOutDirWin = "e:/bak/${this.stamp}"
val reducedOutDirWSL = win2Wsl(reducedOutDirWin)
val tmpDirWin = "c:/tmp"
init {
exitingProcessDespitePossibleJavaFXThread {
clog("reducedOutDirWin = $reducedOutDirWSL")
block(this)
clog("\nOK")
}
}
fun runTFAndCheckOutput(cmdPieces: List<String>, expectedLines: List<String>) {
val res = runProcessAndWait(
listOf("cmd", "/c", "tf") + cmdPieces.toTypedArray(),
workingDirectory = File("e:/febig"),
inheritIO = false,
noisy = true)
if (res.exitValue != 0)
bitch("TF said us 'Fuck you', providing code ${res.exitValue}")
CLIPile.printAndCheckProcessResult(res, expectedLines)
}
inner class checkInToTFVC {
private var files = File(tfvcOutDirWin).listFiles()
private var fileNames: List<String>
private var filePaths: List<String>
init {
files.sortWith(Comparator {a, b -> a.name.compareTo(b.name)})
fileNames = files.map {it.name}
filePaths = files.map {
val s = it.path
check(s.matches(Regex("^\\w:.*")))
s[0].toUpperCase() + s.substring(1)
}
runStatus()
runTFAndCheckOutput(cmdPieces = listOf("add") + filePaths, expectedLines = mutableListOf<String>()-{
it += "bak\\$stamp:"
for (name in fileNames)
it += name
it += ""
})
runTFAndCheckOutput(cmdPieces = listOf("checkin") + filePaths, expectedLines = mutableListOf<String>()-{
it += "bak\\$stamp:"
for (name in fileNames)
it += "Checking in add: $name"
it += ""
it += "${CLIPile.regexpTag}Changeset #\\d+ checked in."
it += ""
})
}
private fun runStatus() {
runTFAndCheckOutput(cmdPieces = listOf("status", tfvcOutDirWin + "/*"), expectedLines = run {
val maxFileNameLength = fileNames.maxBy {it.length}!!.length
// val maxFilePathLength = filePaths.maxBy {it.length}!!.length
val width = 79
var fileNameColumnTitle = "File name"
if (maxFileNameLength > fileNameColumnTitle.length) {
fileNameColumnTitle += " ".repeat(maxFileNameLength - fileNameColumnTitle.length)
}
var columnLine = "-".repeat(fileNameColumnTitle.length) + " ------ "
if (columnLine.length <= width)
columnLine += "-".repeat(width - columnLine.length)
else
columnLine += "-"
val expectedLines = mutableListOf(
"",
"-".repeat(width),
"Detected Changes:",
"-".repeat(width),
"$fileNameColumnTitle Change Local path",
columnLine,
"\$/febig/bak/$stamp")
for (index in files.indices) {
expectedLines += (""
+ fileNames[index].padEnd(maxFileNameLength + 1)
+ "add "
+ filePaths[index])
}
expectedLines += listOf(
"",
"0 change(s), ${files.size} detected change(s)",
"")
expectedLines
})
}
}
fun dumpPostgres() {
clog("Dumping fepg")
val dumpFileName = "fepg-$stamp.pg_dump"
val dumpFile = "$reducedOutDirWin/$dumpFileName"
DBPile2.pg_dump(BigPile.saucerfulOfSecrets.fepg.prod, toFile = dumpFile)
bash("cd $reducedOutDirWSL && zip $dumpFileName.zip $dumpFileName")
bash("cp $reducedOutDirWSL/$dumpFileName.zip $tfvcOutDirWSL")
check(File(dumpFile).delete()) {"b41fd906-e8ba-4b1c-babd-b3310d2c465e"}
}
fun hashShit() {
fun jerk(dirWin: String) {
for (localFile in File(dirWin).listFiles()) {
val sha256 = Hashing.sha256().hashBytes(localFile.readBytes()).toString()
File(localFile.path + ".sha256").writeText(sha256)
}
}
jerk(reducedOutDirWin)
jerk(tfvcOutDirWin)
}
fun uploadShitToDropbox() {
val box = Dropbox(BigPile.saucerfulOfSecrets.dropbox.vgrechka)
object : UploadShitSomewhereTemplate() {
override fun getOutputLabel() = "[DROPBOX]"
override fun getAccountName(): String {
return box.account.name.displayName
}
override fun createFolder(remotePath: String) {
box.client.files().createFolder(remotePath)
}
override fun uploadFile(file: File, remoteFilePath: String) {
file.inputStream().use {stm->
box.client.files()
.uploadBuilder(remoteFilePath)
.uploadAndFinish(stm)
}
}
override fun listFolder(removeFolder: String, recursive: Boolean): List<Meta> {
return box.listFolder(removeFolder, recursive).map {
object : Meta() {
override val path get() = it.pathLower
}
}
}
override fun downloadFile(remotePath: String, stm: FileOutputStream) {
box.client.files()
.download(remotePath)
.download(stm)
}
}
}
fun uploadShitToOneDrive(block: ((UploadShitSomewhereTemplate) -> Unit)? = null) {
val drive = OneDrive()
object : UploadShitSomewhereTemplate(block) {
override fun getOutputLabel() = "[ONEDRIVE]"
override fun getAccountName(): String {
return drive.account.displayName
}
override fun createFolder(remotePath: String) {
drive.createFolder(remotePath)
}
override fun uploadFile(file: File, remoteFilePath: String) {
drive.uploadFile(file, remoteFilePath)
}
override fun listFolder(remoteFolder: String, recursive: Boolean): List<Meta> {
imf("0e7e2391-83aa-4d0c-8d05-07262d893305")
}
override fun downloadFile(remotePath: String, stm: FileOutputStream) {
drive.downloadFile(remotePath, stm)
}
}
}
fun uploadShitToGoogleDrive() {
val g = GoogleDrive()
object : UploadShitSomewhereTemplate() {
override fun getOutputLabel() = "[GDRIVE]"
override fun getAccountName(): String {
return g.drive.about().get().setFields("user").execute()
.user.displayName
}
inner class FilePathShit(val parentID: String, val name: String)
override fun createFolder(remotePath: String) {
// GDrive can happily create several files/folders with same name, which is a little bit confusing
if (fileExists(remotePath)) bitch("793558ff-6fc3-46b3-a89a-08a56f30fa00")
val fps = getFilePathShit(remotePath)
val fileMetadata = com.google.api.services.drive.model.File()
fileMetadata.name = fps.name
fileMetadata.parents = listOf(fps.parentID)
fileMetadata.mimeType = "application/vnd.google-apps.folder"
g.drive.files().create(fileMetadata)
.execute()
}
fun fileExists(remotePath: String): Boolean {
check(remotePath.startsWith("/"))
val theRemotePath = remotePath.substring(1)
var parentID = "root"
for (name in theRemotePath.split("/")) {
val q = "name = '$name' and '$parentID' in parents and trashed = false"
val list = g.drive.files().list()
.setQ(q)
.execute()
if (list.files.size == 0)
return false
check(list.files.size == 1)
val f = list.files.first()
parentID = f.id
}
return true
}
fun getFilePathShit(remotePath: String): FilePathShit {
check(remotePath.startsWith("/"))
val theRemotePath = remotePath.substring(1)
val steps = theRemotePath.split("/")
val name = steps.last()
val parentID = getRemoteFileID(steps.dropLast(1))
return FilePathShit(parentID, name)
}
private fun getRemoteFile(pathParts: List<String>): com.google.api.services.drive.model.File {
var parentID = "root"
val parentsSoFar = mutableListOf(parentID)
var file: com.google.api.services.drive.model.File? = null
for (name in pathParts) {
val q = "name = '$name' and '$parentID' in parents and trashed = false"
// clog("q = $q")
val list = g.drive.files().list()
.setQ(q)
.execute()
if (list.files.size == 0)
bitch("File `$name` not found under `${parentsSoFar.joinToString("/")}`")
check(list.files.size == 1)
val f = list.files.first()
file = f
parentID = f.id
parentsSoFar += parentID
}
return file!!
}
private fun getRemoteFileID(pathParts: List<String>): String {
return getRemoteFile(pathParts).id
}
override fun uploadFile(file: File, remoteFilePath: String) {
val fps = getFilePathShit(remoteFilePath)
val fileMetadata = com.google.api.services.drive.model.File()
fileMetadata.name = fps.name
fileMetadata.parents = listOf(fps.parentID)
val fileContent = FileContent(HTTPPile.contentType.octetStream, file)
val insert = g.drive.files().create(fileMetadata, fileContent)
val uploader = insert.mediaHttpUploader
uploader.isDirectUploadEnabled = true
// uploader.setProgressListener(...)
insert.execute()
}
override fun listFolder(remoteFolder: String, recursive: Boolean): List<Meta> {
imf("5f958cdc-5fdc-4767-8f66-a446a4e76b5a")
}
override fun downloadFile(remotePath: String, stm: FileOutputStream) {
check(remotePath.startsWith("/"))
val theRemotePath = remotePath.substring(1)
val id = getRemoteFileID(theRemotePath.split("/"))
val remoteFile = g.drive.files().get(id)
remoteFile.executeMediaAndDownloadTo(stm)
}
}
}
abstract inner class UploadShitSomewhereTemplate(
block: ((UploadShitSomewhereTemplate) -> Unit)? = null
) {
abstract fun getOutputLabel(): String
abstract fun getAccountName(): String
abstract fun createFolder(remotePath: String)
abstract fun uploadFile(file: File, remoteFilePath: String)
abstract fun listFolder(remoteFolder: String, recursive: Boolean): List<Meta>
abstract fun downloadFile(remotePath: String, stm: FileOutputStream)
val bs = ConsoleBullshitter(getOutputLabel())
val targetFolder = "/bak/$stamp"
abstract inner class Meta {
abstract val path: String
}
init {
clog()
bs.say("Account: " + getAccountName())
when (block) {
null -> all()
else -> block(this)
}
}
fun all() {
createFolder()
uploadShit()
doubleCheck()
}
fun listShit() {
bs.say()
bs.section("Listing shit under $targetFolder") {
val metas = listFolder(targetFolder, recursive = true)
for (meta in metas) {
bs.say(meta.path)
}
}
}
fun doubleCheck() {
bs.section("Double-checking shit") {
for (origFile in File(reducedOutDirWin).listFiles()) {
val downloadedFile = File("$tmpDirWin/checking--${origFile.name}")
if (downloadedFile.exists()) {
check(downloadedFile.delete()) {"f683d3b4-d096-40b6-85a6-43395c1181c0"}
}
bs.operation("Downloading ${origFile.name}") {
downloadedFile.outputStream().use {stm ->
downloadFile("$targetFolder/${origFile.name}", stm)
}
}
bs.operation("Comparing with original") {
val downloadedBytes = downloadedFile.readBytes()
val origBytes = origFile.readBytes()
if (downloadedBytes.size != origBytes.size)
bitch("Sizes don't match. Expected ${origBytes.size}, got ${downloadedBytes.size}")
for (i in downloadedBytes.indices)
if (downloadedBytes[i] != origBytes[i])
bitch("Bytes don't batch")
}
}
}
}
fun uploadShit() {
for (localFile in File(reducedOutDirWin).listFiles()) {
bs.operation("Uploading ${localFile.name}") {
uploadFile(localFile, "$targetFolder/${localFile.name}")
}
}
}
fun createFolder() {
bs.operation("Creating folder $targetFolder") {
createFolder(targetFolder)
}
}
}
fun copyIDEASettings() {
val exportedSettings = "/mnt/c/tmp/idea-settings-$stamp.jar"
bash("cp $exportedSettings $reducedOutDirWSL")
bash("cp $exportedSettings $tfvcOutDirWSL")
}
fun zipAPS() {
fun jerk(subName: String, outDirWSL: String, opts: String) {
bash("" + " cd /mnt/e/work/aps"
+ " && zip -r $outDirWSL/aps-$subName-$stamp.zip . $opts")
}
jerk(subName = "full", outDirWSL = tfvcOutDirWSL, opts = "")
jerk(subName = "reduced", outDirWSL = reducedOutDirWSL, opts = ""
+ " -x /.git*"
+ " -x /node_modules/*"
+ " -x /back/.gradle/*"
+ " -x /back/built/*"
+ " -x /back/lib-gradle/*"
+ " -x /back/out/*"
+ " -x /front/out/*"
+ " -x /javaagent/out/*"
+ " -x /kotlin-js-playground/node_modules/*"
+ " -x /kotlin-js-playground/out/*"
+ " -x /kotlin-jvm-playground/out/*"
+ " -x /tools/out/*")
}
fun zipFuckingEverything() {
fun jerk(subName: String, outDirWSL: String, opts: String) {
bash("" + " cd /mnt/e/fegh"
+ " && zip -r $outDirWSL/fe-$subName-$stamp.zip . $opts")
}
jerk(subName = "full", outDirWSL = tfvcOutDirWSL, opts = "")
jerk(subName = "reduced", outDirWSL = reducedOutDirWSL, opts = ""
+ " -x /.git*"
+ " -x /node_modules/*"
+ " -x /composer/vendor/*"
+ " -x /out/*"
+ " -x /lib-gradle/*"
+ " -x /.gradle/*"
+ " -x /phizdets/phizdets-idea/eclipse-lib/*"
+ " -x /okaml/okaml-fucking/1/_build/*"
+ " -x /okaml/okaml-fucking/2/_build/*")
}
fun zipFuckingPrivateEverything() {
fun jerk(subName: String, outDirWSL: String, opts: String) {
bash("" + " cd /mnt/e/fpebb"
+ " && zip -r $outDirWSL/fpe-$subName-$stamp.zip . $opts")
}
jerk(subName = "full", outDirWSL = tfvcOutDirWSL, opts = "")
jerk(subName = "reduced", outDirWSL = reducedOutDirWSL, opts = ""
+ " -x /.git*")
}
private fun recreateDir(pathWin: String) {
bash("rm -rf ${win2Wsl(pathWin)}")
val file = File(pathWin)
if (file.exists())
bitch("Unable to remove directory $pathWin")
bash("mkdir ${win2Wsl(pathWin)}")
if (!file.exists() || !file.isDirectory)
bitch("Unable to create directory $pathWin")
}
fun recreateReducedOutDir() {
recreateDir(reducedOutDirWin)
}
fun recreateTFVCOutDir() {
recreateDir(tfvcOutDirWin)
}
fun bash(cmd: String) {
val res = runProcessAndWait(listOf(
"bash", "-c", cmd
), noisy = true)
if (res.exitValue != 0)
bitch("Bash said us 'Fuck you', providing code ${res.exitValue}")
}
}
}
| apache-2.0 | f13fe470932703fddb58642cafe50dd6 | 36.226994 | 120 | 0.472355 | 5.334505 | false | false | false | false |
ZhangQinglian/dcapp | src/main/kotlin/com/zqlite/android/diycode/device/utils/Route.kt | 1 | 4387 | /*
* Copyright 2017 zhangqinglian
*
* 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.zqlite.android.diycode.device.utils
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.support.v4.app.Fragment
import com.zqlite.android.diycode.device.view.about.AboutActivity
import com.zqlite.android.diycode.device.view.custom.ImageViewerActivity
import com.zqlite.android.diycode.device.view.favorite.FavoriteActivity
import com.zqlite.android.diycode.device.view.follow.FollowAvtivity
import com.zqlite.android.diycode.device.view.login.LoginActivity
import com.zqlite.android.diycode.device.view.topicdetial.TopicDetailActivity
import com.zqlite.android.diycode.device.view.userdetail.UserDetailActivity
/**
* Created by scott on 2017/8/14.
*/
object Route {
val PICK_IMAGE_REQUEST_CODE = 100
fun goUserDetail(activity:Activity,loginName:String){
val intent : Intent = Intent(activity,UserDetailActivity::class.java)
intent.apply {
putExtra(UserDetailActivity.kUserLoiginKey,loginName)
}
activity.startActivity(intent)
}
fun goTopicDetail(activity: Activity,topicId:Int,topicReplyId:Int = -1){
val intent : Intent = Intent(activity, TopicDetailActivity::class.java)
intent.apply {
putExtra("topicId",topicId)
if(topicReplyId != -1){
putExtra("replyId",topicReplyId)
}
}
activity.startActivity(intent)
}
fun goLogin(activity: Activity){
val intent : Intent = Intent(activity,LoginActivity::class.java)
activity.startActivity(intent)
}
fun openBrowser(activity: Activity,urlStr :String){
val intent = Intent(Intent.ACTION_VIEW)
intent.apply {
data = Uri.parse(urlStr)
}
activity.startActivity(intent)
}
fun openImageView(activity: Activity,urlStr: String){
val intent : Intent = Intent(activity,ImageViewerActivity::class.java)
intent.apply {
putExtra("url",urlStr)
}
activity.startActivity(intent)
}
fun pickImage(fragment: Fragment){
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.apply {
type = "image/*"
}
fragment.startActivityForResult(intent, PICK_IMAGE_REQUEST_CODE)
}
fun goFavorite(loginName: String,activity: Activity){
val intent = Intent(activity,FavoriteActivity::class.java)
intent.apply {
putExtra("login",loginName)
putExtra("type",0)
}
activity.startActivity(intent)
}
fun goMyTopic(loginName: String,activity: Activity){
val intent = Intent(activity,FavoriteActivity::class.java)
intent.apply {
putExtra("login",loginName)
putExtra("type",1)
}
activity.startActivity(intent)
}
fun goFollowing(loginName: String,activity: Activity){
val intent = Intent(activity, FollowAvtivity::class.java)
intent.apply {
putExtra("login",loginName)
putExtra("type",0)
}
activity.startActivity(intent)
}
fun goFollowers(loginName: String,activity: Activity){
val intent = Intent(activity, FollowAvtivity::class.java)
intent.apply {
putExtra("login",loginName)
putExtra("type",1)
}
activity.startActivity(intent)
}
fun goAbout(activity: Activity){
val intent = Intent(activity,AboutActivity::class.java)
activity.startActivity(intent)
}
fun goGithub(activity: Activity){
val intent= Intent(Intent.ACTION_VIEW)
intent.apply {
data = Uri.parse("https://github.com/ZhangQinglian")
}
activity.startActivity(intent)
}
} | apache-2.0 | 22165268fe32ffc979d4ab198ca0b9e8 | 31.503704 | 79 | 0.66264 | 4.313668 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/klib/KlibMetadataDecompiler.kt | 3 | 5947 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.klib
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.psi.compiled.ClassFileDecompilers
import org.jetbrains.kotlin.analysis.decompiler.psi.KotlinDecompiledFileViewProvider
import org.jetbrains.kotlin.analysis.decompiler.psi.text.DecompiledText
import org.jetbrains.kotlin.analysis.decompiler.psi.text.buildDecompiledText
import org.jetbrains.kotlin.analysis.decompiler.psi.text.createIncompatibleAbiVersionDecompiledText
import org.jetbrains.kotlin.analysis.decompiler.psi.text.defaultDecompilerRendererOptions
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.metadata.deserialization.NameResolverImpl
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol
import org.jetbrains.kotlin.serialization.deserialization.ClassDeserializer
import org.jetbrains.kotlin.serialization.deserialization.FlexibleTypeDeserializer
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.utils.addIfNotNull
import java.io.IOException
abstract class KlibMetadataDecompiler<out V : BinaryVersion>(
private val fileType: FileType,
private val serializerProtocol: () -> SerializerExtensionProtocol,
private val flexibleTypeDeserializer: FlexibleTypeDeserializer,
private val expectedBinaryVersion: () -> V,
private val invalidBinaryVersion: () -> V,
stubVersion: Int
) : ClassFileDecompilers.Full() {
private val metadataStubBuilder: KlibMetadataStubBuilder =
KlibMetadataStubBuilder(
stubVersion,
fileType,
serializerProtocol,
::readFileSafely
)
private val renderer: DescriptorRenderer by lazy {
DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() }
}
protected abstract fun doReadFile(file: VirtualFile): FileWithMetadata?
override fun accepts(file: VirtualFile) = FileTypeRegistry.getInstance().isFileOfType(file, fileType)
override fun getStubBuilder() = metadataStubBuilder
override fun createFileViewProvider(file: VirtualFile, manager: PsiManager, physical: Boolean) =
KotlinDecompiledFileViewProvider(manager, file, physical) { provider ->
KlibDecompiledFile(
provider,
::buildDecompiledText
)
}
private fun readFileSafely(file: VirtualFile): FileWithMetadata? {
if (!file.isValid) return null
return try {
doReadFile(file)
} catch (e: IOException) {
// This is needed because sometimes we're given VirtualFile instances that point to non-existent .jar entries.
// Such files are valid (isValid() returns true), but an attempt to read their contents results in a FileNotFoundException.
// Note that although calling "refresh()" instead of catching an exception would seem more correct here,
// it's not always allowed and also is likely to degrade performance
null
}
}
private fun buildDecompiledText(virtualFile: VirtualFile): DecompiledText {
assert(FileTypeRegistry.getInstance().isFileOfType(virtualFile, fileType)) { "Unexpected file type ${virtualFile.fileType}" }
return when (val file = readFileSafely(virtualFile)) {
is FileWithMetadata.Incompatible -> createIncompatibleAbiVersionDecompiledText(expectedBinaryVersion(), file.version)
is FileWithMetadata.Compatible -> decompiledText(
file,
serializerProtocol(),
flexibleTypeDeserializer,
renderer
)
null -> createIncompatibleAbiVersionDecompiledText(expectedBinaryVersion(), invalidBinaryVersion())
}
}
}
sealed class FileWithMetadata {
class Incompatible(val version: BinaryVersion) : FileWithMetadata()
open class Compatible(val proto: ProtoBuf.PackageFragment) : FileWithMetadata() {
val nameResolver = NameResolverImpl(proto.strings, proto.qualifiedNames)
val packageFqName = FqName(proto.getExtension(KlibMetadataProtoBuf.fqName))
open val classesToDecompile: List<ProtoBuf.Class> =
proto.class_List.filter { proto ->
val classId = nameResolver.getClassId(proto.fqName)
!classId.isNestedClass && classId !in ClassDeserializer.BLACK_LIST
}
}
}
//todo: this function is extracted for KotlinNativeMetadataStubBuilder, that's the difference from Big Kotlin.
fun decompiledText(
file: FileWithMetadata.Compatible,
serializerProtocol: SerializerExtensionProtocol,
flexibleTypeDeserializer: FlexibleTypeDeserializer,
renderer: DescriptorRenderer
): DecompiledText {
val packageFqName = file.packageFqName
val resolver = KlibMetadataDeserializerForDecompiler(
packageFqName, file.proto, file.nameResolver,
serializerProtocol, flexibleTypeDeserializer
)
val declarations = arrayListOf<DeclarationDescriptor>()
declarations.addAll(resolver.resolveDeclarationsInFacade(packageFqName))
for (classProto in file.classesToDecompile) {
val classId = file.nameResolver.getClassId(classProto.fqName)
declarations.addIfNotNull(resolver.resolveTopLevelClass(classId))
}
return buildDecompiledText(packageFqName, declarations, renderer)
}
| apache-2.0 | e31f850056b089eba7b04719dbeb9571 | 45.460938 | 158 | 0.750799 | 5.526952 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/RenameUselessCallFix.kt | 1 | 2363 | // 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.inspections.collections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class RenameUselessCallFix(private val newName: String, private val invert: Boolean = false) : LocalQuickFix {
override fun getName() = KotlinBundle.message("rename.useless.call.fix.text", newName)
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
(descriptor.psiElement as? KtQualifiedExpression)?.let {
val psiFactory = KtPsiFactory(project)
val selectorCallExpression = it.selectorExpression as? KtCallExpression
val calleeExpression = selectorCallExpression?.calleeExpression ?: return
calleeExpression.replaced(psiFactory.createExpression(newName))
selectorCallExpression.renameGivenReturnLabels(psiFactory, calleeExpression.text, newName)
if (invert) it.invert()
}
}
private fun KtCallExpression.renameGivenReturnLabels(factory: KtPsiFactory, labelName: String, newName: String) {
val lambdaExpression = lambdaArguments.firstOrNull()?.getLambdaExpression() ?: return
val bodyExpression = lambdaExpression.bodyExpression ?: return
bodyExpression.forEachDescendantOfType<KtReturnExpression> {
if (it.getLabelName() != labelName) return@forEachDescendantOfType
it.replaced(
factory.createExpressionByPattern(
"return@$0 $1",
newName,
it.returnedExpression ?: ""
)
)
}
}
private fun KtQualifiedExpression.invert() {
val parent = parent.safeAs<KtPrefixExpression>() ?: return
val baseExpression = parent.baseExpression ?: return
parent.replace(baseExpression)
}
}
| apache-2.0 | be56351e99f5fa47ca51b21c38ea52ab | 44.442308 | 158 | 0.715616 | 5.394977 | false | false | false | false |
androidx/androidx | navigation/navigation-safe-args-generator/src/test/test-data/expected/kotlin_nav_writer_test/MainFragmentDirections.kt | 3 | 832 | package a.b
import android.os.Bundle
import androidx.navigation.ActionOnlyNavDirections
import androidx.navigation.NavDirections
import kotlin.Int
import kotlin.String
public class MainFragmentDirections private constructor() {
private data class Next(
public val main: String,
public val optional: String = "bla",
) : NavDirections {
public override val actionId: Int = R.id.next
public override val arguments: Bundle
get() {
val result = Bundle()
result.putString("main", this.main)
result.putString("optional", this.optional)
return result
}
}
public companion object {
public fun previous(): NavDirections = ActionOnlyNavDirections(R.id.previous)
public fun next(main: String, optional: String = "bla"): NavDirections = Next(main, optional)
}
}
| apache-2.0 | 338d54ec397d4a22d837741310820e9e | 26.733333 | 97 | 0.707933 | 4.473118 | false | false | false | false |
androidx/androidx | health/connect/connect-client/src/main/java/androidx/health/connect/client/records/ExerciseEventRecord.kt | 3 | 4159 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.health.connect.client.records
import androidx.annotation.IntDef
import androidx.annotation.RestrictTo
import androidx.health.connect.client.records.metadata.Metadata
import java.time.Instant
import java.time.ZoneOffset
/**
* Captures pause or rest events within an exercise. Each record contains the start / stop time of
* the event.
*
* For pause events, resume state can be assumed from the end time of the pause or rest event.
*/
public class ExerciseEventRecord(
override val startTime: Instant,
override val startZoneOffset: ZoneOffset?,
override val endTime: Instant,
override val endZoneOffset: ZoneOffset?,
/**
* Type of event. Required field. Allowed values: [EventType].
*
* @see EventType
*/
@property:EventTypes public val eventType: Int,
override val metadata: Metadata = Metadata.EMPTY,
) : IntervalRecord {
init {
require(startTime.isBefore(endTime)) { "startTime must be before endTime." }
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ExerciseEventRecord) return false
if (eventType != other.eventType) return false
if (startTime != other.startTime) return false
if (startZoneOffset != other.startZoneOffset) return false
if (endTime != other.endTime) return false
if (endZoneOffset != other.endZoneOffset) return false
if (metadata != other.metadata) return false
return true
}
override fun hashCode(): Int {
var result = eventType.hashCode()
result = 31 * result + (startZoneOffset?.hashCode() ?: 0)
result = 31 * result + endTime.hashCode()
result = 31 * result + (endZoneOffset?.hashCode() ?: 0)
result = 31 * result + metadata.hashCode()
return result
}
/**
* Types of exercise event. They can be either explicitly requested by a user or auto-detected
* by a tracking app.
*/
internal object EventType {
/**
* Explicit pause during a workout, requested by the user (by clicking a pause button in
* the session UI). Movement happening during pause should not contribute to session
* metrics.
*/
const val PAUSE = "pause"
/**
* Auto-detected periods of rest during a workout. There should be no user movement
* detected during rest and any movement detected should finish rest event.
*/
const val REST = "rest"
}
/**
* Types of exercise event. They can be either explicitly requested by a user or auto-detected
* by a tracking app.
*
* @suppress
*/
@Retention(AnnotationRetention.SOURCE)
@IntDef(
value =
[
EVENT_TYPE_UNKNOWN,
EVENT_TYPE_PAUSE,
EVENT_TYPE_REST,
]
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
annotation class EventTypes
companion object {
const val EVENT_TYPE_UNKNOWN = 0
const val EVENT_TYPE_PAUSE = 1
const val EVENT_TYPE_REST = 2
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val EVENT_TYPE_STRING_TO_INT_MAP: Map<String, Int> =
mapOf(
EventType.PAUSE to EVENT_TYPE_PAUSE,
EventType.REST to EVENT_TYPE_REST,
)
@RestrictTo(RestrictTo.Scope.LIBRARY)
@JvmField
val EVENT_TYPE_INT_TO_STRING_MAP = EVENT_TYPE_STRING_TO_INT_MAP.reverse()
}
}
| apache-2.0 | 4869a6991be5bf2d049e366b4c37deb6 | 32.813008 | 98 | 0.647271 | 4.59558 | false | false | false | false |
androidx/androidx | benchmark/benchmark-macro/src/androidTest/java/androidx/benchmark/macro/perfetto/FrameTimingQueryTest.kt | 3 | 3533 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark.macro.perfetto
import androidx.benchmark.macro.createTempFileFromAsset
import androidx.benchmark.macro.perfetto.FrameTimingQuery.SubMetric.FrameDurationCpuNs
import androidx.benchmark.macro.perfetto.FrameTimingQuery.SubMetric.FrameOverrunNs
import androidx.benchmark.macro.perfetto.FrameTimingQuery.SubMetric.FrameDurationUiNs
import androidx.benchmark.perfetto.PerfettoHelper.Companion.isAbiSupported
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.test.assertEquals
@RunWith(AndroidJUnit4::class)
class FrameTimingQueryTest {
@MediumTest
@Test
fun fixedTrace28() {
assumeTrue(isAbiSupported())
val traceFile = createTempFileFromAsset("api28_scroll", ".perfetto-trace")
val frameSubMetrics = PerfettoTraceProcessor.runServer(traceFile.absolutePath) {
FrameTimingQuery.getFrameSubMetrics(
perfettoTraceProcessor = this,
captureApiLevel = 28,
packageName = "androidx.benchmark.integration.macrobenchmark.target"
)
}
assertEquals(
expected = mapOf(
FrameDurationCpuNs to listOf(9907605L, 6038595L, 4812136L, 3938490L),
FrameDurationUiNs to listOf(3086979L, 2868490L, 2232709L, 1889479L)
),
actual = frameSubMetrics.mapValues {
it.value.subList(0, 4)
}
)
assertEquals(
expected = List(2) { 62 },
actual = frameSubMetrics.map { it.value.size },
message = "Expect same number of frames for each metric"
)
}
@MediumTest
@Test
fun fixedTrace31() {
assumeTrue(isAbiSupported())
val traceFile = createTempFileFromAsset("api31_scroll", ".perfetto-trace")
val frameSubMetrics = PerfettoTraceProcessor.runServer(traceFile.absolutePath) {
FrameTimingQuery.getFrameSubMetrics(
perfettoTraceProcessor = this,
captureApiLevel = 31,
packageName = "androidx.benchmark.integration.macrobenchmark.target"
)
}
assertEquals(
expected = mapOf(
FrameDurationCpuNs to listOf(6881407L, 5648542L, 3830261L, 4343438L),
FrameDurationUiNs to listOf(2965052L, 3246407L, 1562188L, 1945469L),
FrameOverrunNs to listOf(-5207137L, -11699862L, -14025295L, -12300155L)
),
actual = frameSubMetrics.mapValues {
it.value.subList(0, 4)
}
)
assertEquals(
expected = List(3) { 96 },
actual = frameSubMetrics.map { it.value.size },
message = "Expect same number of frames for each metric"
)
}
} | apache-2.0 | 39207bce08fa07adcdb33d7068cc72b9 | 37 | 88 | 0.666572 | 4.546976 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertArrayParameterToVarargIntention.kt | 3 | 2945 | // 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.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.project.builtIns
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
class ConvertArrayParameterToVarargIntention : SelfTargetingIntention<KtParameter>(
KtParameter::class.java, KotlinBundle.lazyMessage("convert.to.vararg.parameter")
) {
override fun isApplicableTo(element: KtParameter, caretOffset: Int): Boolean {
val typeReference = element.getChildOfType<KtTypeReference>() ?: return false
if (element.parent.parent is KtFunctionLiteral) return false
if (element.isVarArg) return false
val type = element.descriptor?.type ?: return false
return when {
KotlinBuiltIns.isPrimitiveArray(type) -> {
setTextGetter(defaultTextGetter)
true
}
KotlinBuiltIns.isArray(type) -> {
val typeArgument = typeReference.typeElement?.typeArgumentsAsTypes?.firstOrNull()
val typeProjection = typeArgument?.parent as? KtTypeProjection
if (typeProjection?.hasModifier(KtTokens.IN_KEYWORD) == false) {
setTextGetter(
if (!typeProjection.hasModifier(KtTokens.OUT_KEYWORD) && !KotlinBuiltIns.isPrimitiveType(
element.builtIns.getArrayElementType(
type
)
)
) {
{ KotlinBundle.message("0.may.break.code", defaultText) }
} else {
defaultTextGetter
}
)
true
} else {
false
}
}
else ->
false
}
}
override fun applyTo(element: KtParameter, editor: Editor?) {
val typeReference = element.getChildOfType<KtTypeReference>() ?: return
val type = element.descriptor?.type ?: return
val newType = KotlinBuiltIns.getPrimitiveArrayElementType(type)?.typeName?.asString()
?: typeReference.typeElement?.typeArgumentsAsTypes?.firstOrNull()?.text
?: return
typeReference.replace(KtPsiFactory(element).createType(newType))
element.addModifier(KtTokens.VARARG_KEYWORD)
}
} | apache-2.0 | 6ec122333fb0ba96535b4db219a9c4fb | 44.323077 | 158 | 0.62309 | 5.674374 | false | false | false | false |
hellenxu/TipsProject | DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/material/OptionsAdapter.kt | 1 | 2080 | package six.ca.droiddailyproject.material
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import six.ca.droiddailyproject.R
/**
* @author hellenxu
* @date 2021-04-27
* Copyright 2021 Six. All rights reserved.
*/
class OptionsAdapter(
private val ctx: Context,
private val data: List<Option> = emptyList()
) : BaseAdapter() {
override fun getCount(): Int {
return data.size
}
override fun getItem(position: Int): Option {
val pos = position.coerceAtLeast(0).coerceAtMost(data.lastIndex)
return data[pos]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view: View
val vh: OptionViewHolder
if (convertView == null) {
vh = OptionViewHolder()
view = LayoutInflater.from(ctx).inflate(R.layout.option_list_item, parent, false)
vh.itemTextView = view.findViewById(R.id.tv_item)
view.tag = vh
} else {
view = convertView
vh = convertView.tag as OptionViewHolder
}
val item = data[position]
vh.itemTextView.setText(item.labelResId)
vh.itemTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(item.iconResId, 0, 0, 0)
return view
}
inner class OptionViewHolder {
lateinit var itemTextView: TextView
}
}
data class Option(
val iconResId: Int,
val labelResId: Int
)
class OptionDiffCallback : DiffUtil.ItemCallback<Option>() {
override fun areItemsTheSame(oldItem: Option, newItem: Option): Boolean {
return oldItem.iconResId == newItem.iconResId && oldItem.labelResId == newItem.labelResId
}
override fun areContentsTheSame(oldItem: Option, newItem: Option): Boolean {
return oldItem == newItem
}
} | apache-2.0 | e9ec78aa905dbda5ea731cca8d8f9bce | 26.025974 | 97 | 0.674519 | 4.511931 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/KotlinGradleModelBuilder.kt | 1 | 12288 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.gradle
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.tooling.BuildController
import org.gradle.tooling.model.Model
import org.gradle.tooling.model.gradle.GradleBuild
import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider
import org.gradle.api.provider.Property
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.tooling.ErrorMessageBuilder
import org.jetbrains.plugins.gradle.tooling.ModelBuilderContext
import org.jetbrains.plugins.gradle.tooling.ModelBuilderService
import java.io.File
import java.io.Serializable
import java.lang.reflect.InvocationTargetException
import java.util.*
interface ArgsInfo : Serializable {
val currentArguments: List<String>
val defaultArguments: List<String>
val dependencyClasspath: List<String>
}
data class ArgsInfoImpl(
override val currentArguments: List<String>,
override val defaultArguments: List<String>,
override val dependencyClasspath: List<String>
) : ArgsInfo {
constructor(argsInfo: ArgsInfo) : this(
ArrayList(argsInfo.currentArguments),
ArrayList(argsInfo.defaultArguments),
ArrayList(argsInfo.dependencyClasspath)
)
}
typealias CompilerArgumentsBySourceSet = Map<String, ArgsInfo>
/**
* Creates deep copy in order to avoid holding links to Proxy objects created by gradle tooling api
*/
fun CompilerArgumentsBySourceSet.deepCopy(): CompilerArgumentsBySourceSet {
val result = HashMap<String, ArgsInfo>()
this.forEach { key, value -> result[key] = ArgsInfoImpl(value) }
return result
}
interface KotlinGradleModel : Serializable {
val hasKotlinPlugin: Boolean
val compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet
val coroutines: String?
val platformPluginId: String?
val implements: List<String>
val kotlinTarget: String?
val kotlinTaskProperties: KotlinTaskPropertiesBySourceSet
val gradleUserHome: String
}
data class KotlinGradleModelImpl(
override val hasKotlinPlugin: Boolean,
override val compilerArgumentsBySourceSet: CompilerArgumentsBySourceSet,
override val coroutines: String?,
override val platformPluginId: String?,
override val implements: List<String>,
override val kotlinTarget: String? = null,
override val kotlinTaskProperties: KotlinTaskPropertiesBySourceSet,
override val gradleUserHome: String
) : KotlinGradleModel
abstract class AbstractKotlinGradleModelBuilder : ModelBuilderService {
companion object {
val kotlinCompileJvmTaskClasses = listOf(
"org.jetbrains.kotlin.gradle.tasks.KotlinCompile_Decorated",
"org.jetbrains.kotlin.gradle.tasks.KotlinCompileWithWorkers_Decorated"
)
val kotlinCompileTaskClasses = kotlinCompileJvmTaskClasses + listOf(
"org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile_Decorated",
"org.jetbrains.kotlin.gradle.tasks.KotlinCompileCommon_Decorated",
"org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompileWithWorkers_Decorated",
"org.jetbrains.kotlin.gradle.tasks.KotlinCompileCommonWithWorkers_Decorated"
)
val platformPluginIds = listOf("kotlin-platform-jvm", "kotlin-platform-js", "kotlin-platform-common")
val pluginToPlatform = linkedMapOf(
"kotlin" to "kotlin-platform-jvm",
"kotlin2js" to "kotlin-platform-js"
)
val kotlinPluginIds = listOf("kotlin", "kotlin2js", "kotlin-android")
val ABSTRACT_KOTLIN_COMPILE_CLASS = "org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile"
val kotlinProjectExtensionClass = "org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension"
val kotlinSourceSetClass = "org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet"
val kotlinPluginWrapper = "org.jetbrains.kotlin.gradle.plugin.KotlinPluginWrapperKt"
private val propertyClassPresent = GradleVersion.current() >= GradleVersion.version("4.3")
fun Task.getSourceSetName(): String = try {
val method = javaClass.methods.firstOrNull { it.name.startsWith("getSourceSetName") && it.parameterTypes.isEmpty() }
val sourceSetName = method?.invoke(this)
when {
sourceSetName is String -> sourceSetName
propertyClassPresent && sourceSetName is Property<*> -> sourceSetName.get() as? String
else -> null
}
} catch (e: InvocationTargetException) {
null // can be thrown if property is not initialized yet
} ?: "main"
}
}
private const val REQUEST_FOR_NON_ANDROID_MODULES_ONLY = "*"
class AndroidAwareGradleModelProvider<TModel>(
private val modelClass: Class<TModel>,
private val androidPluginIsRequestingVariantSpecificModels: Boolean
) : ProjectImportModelProvider {
override fun populateBuildModels(
controller: BuildController,
buildModel: GradleBuild,
consumer: ProjectImportModelProvider.BuildModelConsumer
) = Unit
override fun populateProjectModels(
controller: BuildController,
projectModel: Model,
modelConsumer: ProjectImportModelProvider.ProjectModelConsumer
) {
val model = if (androidPluginIsRequestingVariantSpecificModels) {
controller.findModel(projectModel, modelClass, ModelBuilderService.Parameter::class.java) {
it.value = REQUEST_FOR_NON_ANDROID_MODULES_ONLY
}
} else {
controller.findModel(projectModel, modelClass)
}
if (model != null) {
modelConsumer.consume(model, modelClass)
}
}
class Result(
private val hasProjectAndroidBasePlugin: Boolean,
private val requestedVariantNames: Set<String>?
) {
fun shouldSkipBuildAllCall(): Boolean =
hasProjectAndroidBasePlugin && requestedVariantNames?.singleOrNull() == REQUEST_FOR_NON_ANDROID_MODULES_ONLY
fun shouldSkipSourceSet(sourceSetName: String): Boolean =
requestedVariantNames != null && !requestedVariantNames.contains(sourceSetName.toLowerCase())
}
companion object {
fun parseParameter(project: Project, parameterValue: String?): Result {
return Result(
hasProjectAndroidBasePlugin = project.plugins.findPlugin("com.android.base") != null,
requestedVariantNames = parameterValue?.splitToSequence(',')?.map { it.toLowerCase() }?.toSet()
)
}
}
}
class KotlinGradleModelBuilder : AbstractKotlinGradleModelBuilder(), ModelBuilderService.Ex {
override fun getErrorMessageBuilder(project: Project, e: Exception): ErrorMessageBuilder {
return ErrorMessageBuilder.create(project, e, "Gradle import errors")
.withDescription("Unable to build Kotlin project configuration")
}
override fun canBuild(modelName: String?): Boolean = modelName == KotlinGradleModel::class.java.name
private fun getImplementedProjects(project: Project): List<Project> {
return listOf("expectedBy", "implement")
.flatMap { project.configurations.findByName(it)?.dependencies ?: emptySet<Dependency>() }
.filterIsInstance<ProjectDependency>()
.mapNotNull { it.dependencyProject }
}
// see GradleProjectResolverUtil.getModuleId() in IDEA codebase
private fun Project.pathOrName() = if (path == ":") name else path
@Suppress("UNCHECKED_CAST")
private fun Task.getCompilerArguments(methodName: String): List<String>? {
return try {
javaClass.getDeclaredMethod(methodName).invoke(this) as List<String>
} catch (e: Exception) {
// No argument accessor method is available
null
}
}
private fun Task.getDependencyClasspath(): List<String> {
try {
val abstractKotlinCompileClass = javaClass.classLoader.loadClass(ABSTRACT_KOTLIN_COMPILE_CLASS)
val getCompileClasspath = abstractKotlinCompileClass.getDeclaredMethod("getCompileClasspath").apply { isAccessible = true }
@Suppress("UNCHECKED_CAST")
return (getCompileClasspath.invoke(this) as Collection<File>).map { it.path }
} catch (e: ClassNotFoundException) {
// Leave arguments unchanged
} catch (e: NoSuchMethodException) {
// Leave arguments unchanged
} catch (e: InvocationTargetException) {
// We can safely ignore this exception here as getCompileClasspath() gets called again at a later time
// Leave arguments unchanged
}
return emptyList()
}
private fun getCoroutines(project: Project): String? {
val kotlinExtension = project.extensions.findByName("kotlin") ?: return null
val experimentalExtension = try {
kotlinExtension::class.java.getMethod("getExperimental").invoke(kotlinExtension)
} catch (e: NoSuchMethodException) {
return null
}
return try {
experimentalExtension::class.java.getMethod("getCoroutines").invoke(experimentalExtension)?.toString()
} catch (e: NoSuchMethodException) {
null
}
}
override fun buildAll(modelName: String, project: Project): KotlinGradleModelImpl? {
return buildAll(project, null)
}
override fun buildAll(modelName: String, project: Project, builderContext: ModelBuilderContext): KotlinGradleModelImpl? {
return buildAll(project, builderContext)
}
private fun buildAll(project: Project, builderContext: ModelBuilderContext?): KotlinGradleModelImpl? {
// When running in Android Studio, Android Studio would request specific source sets only to avoid syncing
// currently not active build variants. We convert names to the lower case to avoid ambiguity with build variants
// accidentally named starting with upper case.
val androidVariantRequest = AndroidAwareGradleModelProvider.parseParameter(project, builderContext?.parameter)
if (androidVariantRequest.shouldSkipBuildAllCall()) return null
val kotlinPluginId = kotlinPluginIds.singleOrNull { project.plugins.findPlugin(it) != null }
val platformPluginId = platformPluginIds.singleOrNull { project.plugins.findPlugin(it) != null }
val compilerArgumentsBySourceSet = LinkedHashMap<String, ArgsInfo>()
val extraProperties = HashMap<String, KotlinTaskProperties>()
project.getAllTasks(false)[project]?.forEach { compileTask ->
if (compileTask.javaClass.name !in kotlinCompileTaskClasses) return@forEach
val sourceSetName = compileTask.getSourceSetName()
if (androidVariantRequest.shouldSkipSourceSet(sourceSetName)) return@forEach
val currentArguments = compileTask.getCompilerArguments("getSerializedCompilerArguments")
?: compileTask.getCompilerArguments("getSerializedCompilerArgumentsIgnoreClasspathIssues") ?: emptyList()
val defaultArguments = compileTask.getCompilerArguments("getDefaultSerializedCompilerArguments").orEmpty()
val dependencyClasspath = compileTask.getDependencyClasspath()
compilerArgumentsBySourceSet[sourceSetName] = ArgsInfoImpl(currentArguments, defaultArguments, dependencyClasspath)
extraProperties.acknowledgeTask(compileTask, null)
}
val platform = platformPluginId ?: pluginToPlatform.entries.singleOrNull { project.plugins.findPlugin(it.key) != null }?.value
val implementedProjects = getImplementedProjects(project)
return KotlinGradleModelImpl(
kotlinPluginId != null || platformPluginId != null,
compilerArgumentsBySourceSet,
getCoroutines(project),
platform,
implementedProjects.map { it.pathOrName() },
platform ?: kotlinPluginId,
extraProperties,
project.gradle.gradleUserHomeDir.absolutePath
)
}
}
| apache-2.0 | fde4fcac1b3f59d0fae17cbe9644ae0b | 44.010989 | 158 | 0.710124 | 5.517737 | false | false | false | false |
JetBrains/xodus | query/src/main/kotlin/jetbrains/exodus/query/Utils.kt | 1 | 1665 | /**
* Copyright 2010 - 2022 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.query
import jetbrains.exodus.query.metadata.ModelMetaData
import java.lang.Boolean.parseBoolean
import java.lang.Integer.getInteger
internal object Utils {
@JvmStatic
val unionSubtypes = parseBoolean(System.getProperty("jetbrains.exodus.query.unionSubtypesResults", "true"))
@JvmStatic
val reduceUnionsOfLinksDepth: Int = getInteger("jetbrains.exodus.query.reduceUnionsOfLinksDepth", 4)
@JvmStatic
fun safe_equals(left: Any?, right: Any?) = if (left != null) left == right else right == null
@JvmStatic
fun isTypeOf(type: String?, ofType: String, mmd: ModelMetaData): Boolean {
var t: String = type ?: return false
while (true) {
if (t == ofType) {
return true
}
val emd = mmd.getEntityMetaData(t) ?: break
for (i in emd.interfaceTypes) {
if (i == ofType) {
return true
}
}
t = emd.superType ?: break
}
return false
}
}
| apache-2.0 | 8945602aa6559e0f259c561d8a741baf | 32.3 | 111 | 0.651652 | 4.258312 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/callTranslator/CallInfo.kt | 1 | 8741 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.translate.callTranslator
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.js.backend.ast.JsBlock
import org.jetbrains.kotlin.js.backend.ast.JsConditional
import org.jetbrains.kotlin.js.backend.ast.JsExpression
import org.jetbrains.kotlin.js.backend.ast.JsLiteral
import org.jetbrains.kotlin.js.translate.context.TranslationContext
import org.jetbrains.kotlin.js.translate.reference.CallArgumentTranslator
import org.jetbrains.kotlin.js.translate.reference.ReferenceTranslator
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
import org.jetbrains.kotlin.js.translate.utils.JsDescriptorUtils.getReceiverParameterForReceiver
import org.jetbrains.kotlin.js.translate.utils.TranslationUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.isSafeCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.tasks.ExplicitReceiverKind.*
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
interface CallInfo {
val context: TranslationContext
val resolvedCall: ResolvedCall<out CallableDescriptor>
val dispatchReceiver: JsExpression?
val extensionReceiver: JsExpression?
fun constructSafeCallIfNeeded(result: JsExpression): JsExpression
}
abstract class AbstractCallInfo : CallInfo {
override fun toString(): String {
val location = DiagnosticUtils.atLocation(callableDescriptor)
val name = callableDescriptor.name.asString()
return "callableDescriptor: $name at $location; dispatchReceiver: $dispatchReceiver; extensionReceiver: $extensionReceiver"
}
}
// if value == null, it is get access
class VariableAccessInfo(callInfo: CallInfo, val value: JsExpression? = null) : AbstractCallInfo(), CallInfo by callInfo
class FunctionCallInfo(
callInfo: CallInfo,
val argumentsInfo: CallArgumentTranslator.ArgumentsInfo
) : AbstractCallInfo(), CallInfo by callInfo
/**
* no receivers - extensionOrDispatchReceiver = null, extensionReceiver = null
* this - extensionOrDispatchReceiver = this, extensionReceiver = null
* receiver - extensionOrDispatchReceiver = receiver, extensionReceiver = null
* both - extensionOrDispatchReceiver = this, extensionReceiver = receiver
*/
class ExplicitReceivers(val extensionOrDispatchReceiver: JsExpression?, val extensionReceiver: JsExpression? = null)
fun TranslationContext.getCallInfo(
resolvedCall: ResolvedCall<out CallableDescriptor>,
extensionOrDispatchReceiver: JsExpression?
): CallInfo {
return createCallInfo(resolvedCall, ExplicitReceivers(extensionOrDispatchReceiver))
}
// two receiver need only for FunctionCall in VariableAsFunctionResolvedCall
fun TranslationContext.getCallInfo(
resolvedCall: ResolvedCall<out FunctionDescriptor>,
explicitReceivers: ExplicitReceivers
): FunctionCallInfo {
val argsBlock = JsBlock()
val argumentsInfo = CallArgumentTranslator.translate(resolvedCall, explicitReceivers.extensionOrDispatchReceiver, this, argsBlock)
val explicitReceiversCorrected =
if (!argsBlock.isEmpty && explicitReceivers.extensionOrDispatchReceiver != null) {
val receiverOrThisRef = cacheExpressionIfNeeded(explicitReceivers.extensionOrDispatchReceiver)
var receiverRef = explicitReceivers.extensionReceiver
if (receiverRef != null) {
receiverRef = defineTemporary(explicitReceivers.extensionReceiver!!)
}
ExplicitReceivers(receiverOrThisRef, receiverRef)
}
else {
explicitReceivers
}
this.addStatementsToCurrentBlockFrom(argsBlock)
val callInfo = createCallInfo(resolvedCall, explicitReceiversCorrected)
return FunctionCallInfo(callInfo, argumentsInfo)
}
private fun boxIfNeedeed(v: ReceiverValue?, d: ReceiverParameterDescriptor?, r: JsExpression?): JsExpression? {
if (r != null && v != null && KotlinBuiltIns.isCharOrNullableChar(v.type) &&
(d == null || !KotlinBuiltIns.isCharOrNullableChar(d.type))) {
return JsAstUtils.charToBoxedChar(r)
}
return r
}
private fun TranslationContext.getDispatchReceiver(receiverValue: ReceiverValue): JsExpression {
return getDispatchReceiver(getReceiverParameterForReceiver(receiverValue))
}
private fun TranslationContext.createCallInfo(
resolvedCall: ResolvedCall<out CallableDescriptor>,
explicitReceivers: ExplicitReceivers
): CallInfo {
val receiverKind = resolvedCall.explicitReceiverKind
// I'm not sure if it's a proper code, and why it should work. Just copied similar logic from ExpressionCodegen.generateConstructorCall.
// See box/classes/inner/instantiateInDerived.kt
// TODO: revisit this code later, write more tests (or borrow them from JVM backend)
fun getDispatchReceiver(): JsExpression? {
val receiverValue = resolvedCall.dispatchReceiver ?: return null
return when (receiverKind) {
DISPATCH_RECEIVER, BOTH_RECEIVERS -> explicitReceivers.extensionOrDispatchReceiver
else -> getDispatchReceiver(receiverValue)
}
}
fun getExtensionReceiver(): JsExpression? {
val receiverValue = resolvedCall.extensionReceiver ?: return null
return when (receiverKind) {
EXTENSION_RECEIVER -> explicitReceivers.extensionOrDispatchReceiver
BOTH_RECEIVERS -> explicitReceivers.extensionReceiver
else -> getDispatchReceiver(receiverValue)
}
}
var dispatchReceiver = getDispatchReceiver()
var extensionReceiver = getExtensionReceiver()
var notNullConditional: JsConditional? = null
if (resolvedCall.call.isSafeCall()) {
when (resolvedCall.explicitReceiverKind) {
BOTH_RECEIVERS, EXTENSION_RECEIVER -> {
notNullConditional = TranslationUtils.notNullConditional(extensionReceiver!!, JsLiteral.NULL, this)
extensionReceiver = notNullConditional.thenExpression
}
else -> {
notNullConditional = TranslationUtils.notNullConditional(dispatchReceiver!!, JsLiteral.NULL, this)
dispatchReceiver = notNullConditional.thenExpression
}
}
}
if (dispatchReceiver == null) {
val container = resolvedCall.resultingDescriptor.containingDeclaration
if (DescriptorUtils.isObject(container)) {
dispatchReceiver = ReferenceTranslator.translateAsValueReference(container, this)
}
}
dispatchReceiver = boxIfNeedeed(resolvedCall.dispatchReceiver,
resolvedCall.candidateDescriptor.dispatchReceiverParameter,
dispatchReceiver)
extensionReceiver = boxIfNeedeed(resolvedCall.extensionReceiver,
resolvedCall.candidateDescriptor.extensionReceiverParameter,
extensionReceiver)
return object : AbstractCallInfo(), CallInfo {
override val context: TranslationContext = this@createCallInfo
override val resolvedCall: ResolvedCall<out CallableDescriptor> = resolvedCall
override val dispatchReceiver: JsExpression? = dispatchReceiver
override val extensionReceiver: JsExpression? = extensionReceiver
val notNullConditionalForSafeCall: JsConditional? = notNullConditional
override fun constructSafeCallIfNeeded(result: JsExpression): JsExpression {
if (notNullConditionalForSafeCall == null) {
return result
}
else {
notNullConditionalForSafeCall.thenExpression = result
return notNullConditionalForSafeCall
}
}
}
}
| apache-2.0 | bc74ce12313a21773feb7712e29acbd5 | 43.596939 | 140 | 0.734241 | 5.788742 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/gtdu.kt | 1 | 3381 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.navigation.impl
import com.intellij.codeInsight.navigation.CtrlMouseInfo
import com.intellij.find.actions.PsiTargetVariant
import com.intellij.find.actions.SearchTargetVariant
import com.intellij.find.actions.TargetVariant
import com.intellij.find.usages.impl.symbolSearchTarget
import com.intellij.model.psi.PsiSymbolService
import com.intellij.model.psi.impl.TargetData
import com.intellij.model.psi.impl.declaredReferencedData
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.SmartList
internal fun gotoDeclarationOrUsages(file: PsiFile, offset: Int): GTDUActionData? {
return processInjectionThenHost(file, offset, ::gotoDeclarationOrUsagesInner)
}
/**
* "Go To Declaration Or Usages" action data
*/
internal interface GTDUActionData {
fun ctrlMouseInfo(): CtrlMouseInfo?
fun result(): GTDUActionResult?
}
/**
* "Go To Declaration Or Usages" action result
*/
internal sealed class GTDUActionResult {
/**
* Go To Declaration
*/
class GTD(val navigationActionResult: NavigationActionResult) : GTDUActionResult()
/**
* Show Usages
*/
class SU(val targetVariants: List<TargetVariant>) : GTDUActionResult() {
init {
require(targetVariants.isNotEmpty())
}
}
}
private fun gotoDeclarationOrUsagesInner(file: PsiFile, offset: Int): GTDUActionData? {
return fromDirectNavigation(file, offset)?.toGTDUActionData()
?: fromTargetData(file, offset)
}
private fun fromTargetData(file: PsiFile, offset: Int): GTDUActionData? {
val (declaredData, referencedData) = declaredReferencedData(file, offset) ?: return null
return referencedData?.toGTDActionData(file.project)?.toGTDUActionData() // GTD of referenced symbols
?: (referencedData)?.let { ShowUsagesGTDUActionData(file.project, it) } // SU of referenced symbols if nowhere to navigate
?: declaredData?.let { ShowUsagesGTDUActionData(file.project, it) } // SU of declared symbols
}
internal fun GTDActionData.toGTDUActionData(): GTDUActionData? {
val gtdActionResult = result() ?: return null // nowhere to navigate
return object : GTDUActionData {
override fun ctrlMouseInfo(): CtrlMouseInfo? = [email protected]()
override fun result(): GTDUActionResult = GTDUActionResult.GTD(gtdActionResult)
}
}
private class ShowUsagesGTDUActionData(private val project: Project, private val targetData: TargetData) : GTDUActionData {
override fun ctrlMouseInfo(): CtrlMouseInfo? = targetData.ctrlMouseInfo()
override fun result(): GTDUActionResult? = searchTargetVariants(project, targetData).let { targets ->
if (targets.isEmpty()) {
null
}
else {
GTDUActionResult.SU(targets)
}
}
}
private fun searchTargetVariants(project: Project, data: TargetData): List<TargetVariant> {
return data.targets.mapNotNullTo(SmartList()) { (symbol, _) ->
val psi: PsiElement? = PsiSymbolService.getInstance().extractElementFromSymbol(symbol)
if (psi == null) {
symbolSearchTarget(project, symbol)?.let(::SearchTargetVariant)
}
else {
PsiTargetVariant(psi)
}
}
}
| apache-2.0 | 3c8710db90aa86770b7eb4e6ce853695 | 34.589474 | 158 | 0.748299 | 4.702364 | false | false | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/indexedProperty/IndexedPropertyAnnotationChecker.kt | 12 | 1790 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.transformations.indexedProperty
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.HighlightSeverity
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.annotator.checkers.CustomAnnotationChecker
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration
class IndexedPropertyAnnotationChecker : CustomAnnotationChecker() {
override fun checkApplicability(holder: AnnotationHolder, annotation: GrAnnotation): Boolean {
if (annotation.qualifiedName != indexedPropertyFqn) return false
val modifierList = annotation.owner as? GrModifierList ?: return true
val parent = modifierList.parent as? GrVariableDeclaration ?: return true
val field = parent.variables.singleOrNull() as? GrField ?: return true
if (!field.isProperty) {
holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("indexed.property.is.applicable.to.properties.only")).range(annotation).create()
return true
}
if (field.getIndexedComponentType() == null) {
val message = GroovyBundle.message("inspection.message.property.not.indexable.type.must.be.array.or.list.but.found.0",
field.type.presentableText)
holder.newAnnotation(HighlightSeverity.ERROR, message).create()
}
return true
}
}
| apache-2.0 | ff632cac84057d2b8b86d2e1b3f257b2 | 51.647059 | 153 | 0.779888 | 4.613402 | false | false | false | false |
android/compose-samples | Jetsurvey/app/src/main/java/com/example/compose/jetsurvey/survey/SurveyScreen.kt | 1 | 12012 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.jetsurvey.survey
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.with
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.ProgressIndicatorDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.example.compose.jetsurvey.R
import com.example.compose.jetsurvey.theme.stronglyDeemphasizedAlpha
import com.example.compose.jetsurvey.util.supportWideScreen
private const val CONTENT_ANIMATION_DURATION = 500
@OptIn(ExperimentalAnimationApi::class, ExperimentalMaterial3Api::class)
// AnimatedContent is experimental, Scaffold is experimental in m3
@Composable
fun SurveyQuestionsScreen(
questions: SurveyState.Questions,
shouldAskPermissions: Boolean,
onDoNotAskForPermissions: () -> Unit,
onAction: (Int, SurveyActionType) -> Unit,
onDonePressed: () -> Unit,
onBackPressed: () -> Unit
) {
val questionState = remember(questions.currentQuestionIndex) {
questions.questionsState[questions.currentQuestionIndex]
}
Surface(modifier = Modifier.supportWideScreen()) {
Scaffold(
topBar = {
SurveyTopAppBar(
questionIndex = questionState.questionIndex,
totalQuestionsCount = questionState.totalQuestionsCount,
onBackPressed = onBackPressed
)
},
content = { innerPadding ->
AnimatedContent(
targetState = questionState,
transitionSpec = {
val animationSpec: TweenSpec<IntOffset> = tween(CONTENT_ANIMATION_DURATION)
val direction =
if (targetState.questionIndex > initialState.questionIndex) {
// Going forwards in the survey: Set the initial offset to start
// at the size of the content so it slides in from right to left, and
// slides out from the left of the screen to -fullWidth
AnimatedContentScope.SlideDirection.Left
} else {
// Going back to the previous question in the set, we do the same
// transition as above, but with different offsets - the inverse of
// above, negative fullWidth to enter, and fullWidth to exit.
AnimatedContentScope.SlideDirection.Right
}
slideIntoContainer(
towards = direction,
animationSpec = animationSpec
) with
slideOutOfContainer(
towards = direction,
animationSpec = animationSpec
)
}
) { targetState ->
Question(
question = targetState.question,
answer = targetState.answer,
shouldAskPermissions = shouldAskPermissions,
onAnswer = {
if (it !is Answer.PermissionsDenied) {
targetState.answer = it
}
targetState.enableNext = true
},
onAction = onAction,
onDoNotAskForPermissions = onDoNotAskForPermissions,
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
)
}
},
bottomBar = {
SurveyBottomBar(
questionState = questionState,
onPreviousPressed = { questions.currentQuestionIndex-- },
onNextPressed = { questions.currentQuestionIndex++ },
onDonePressed = onDonePressed
)
}
)
}
}
@OptIn(ExperimentalMaterial3Api::class) // Scaffold is experimental in m3
@Composable
fun SurveyResultScreen(
result: SurveyState.Result,
onDonePressed: () -> Unit
) {
Surface(modifier = Modifier.supportWideScreen()) {
Scaffold(
content = { innerPadding ->
val modifier = Modifier.padding(innerPadding)
SurveyResult(result = result, modifier = modifier)
},
bottomBar = {
OutlinedButton(
onClick = { onDonePressed() },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp, vertical = 24.dp)
) {
Text(text = stringResource(id = R.string.done))
}
}
)
}
}
@Composable
private fun SurveyResult(result: SurveyState.Result, modifier: Modifier = Modifier) {
LazyColumn(modifier = modifier.fillMaxSize()) {
item {
Spacer(modifier = Modifier.height(44.dp))
Text(
text = result.surveyResult.library,
style = MaterialTheme.typography.displaySmall,
modifier = Modifier.padding(horizontal = 20.dp)
)
Text(
text = stringResource(
result.surveyResult.result,
result.surveyResult.library
),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(20.dp)
)
Text(
text = stringResource(result.surveyResult.description),
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(horizontal = 20.dp)
)
}
}
}
@Composable
private fun TopAppBarTitle(
questionIndex: Int,
totalQuestionsCount: Int,
modifier: Modifier = Modifier
) {
Row(modifier = modifier) {
Text(
text = (questionIndex + 1).toString(),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = stronglyDeemphasizedAlpha)
)
Text(
text = stringResource(R.string.question_count, totalQuestionsCount),
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
)
}
}
@Composable
private fun SurveyTopAppBar(
questionIndex: Int,
totalQuestionsCount: Int,
onBackPressed: () -> Unit
) {
Column(modifier = Modifier.fillMaxWidth()) {
Box(modifier = Modifier.fillMaxWidth()) {
TopAppBarTitle(
questionIndex = questionIndex,
totalQuestionsCount = totalQuestionsCount,
modifier = Modifier
.padding(vertical = 20.dp)
.align(Alignment.Center)
)
IconButton(
onClick = onBackPressed,
modifier = Modifier
.padding(horizontal = 20.dp, vertical = 20.dp)
.fillMaxWidth()
) {
Icon(
Icons.Filled.Close,
contentDescription = stringResource(id = R.string.close),
modifier = Modifier.align(Alignment.CenterEnd),
tint = MaterialTheme.colorScheme.onSurface.copy(stronglyDeemphasizedAlpha)
)
}
}
val animatedProgress by animateFloatAsState(
targetValue = (questionIndex + 1) / totalQuestionsCount.toFloat(),
animationSpec = ProgressIndicatorDefaults.ProgressAnimationSpec
)
LinearProgressIndicator(
progress = animatedProgress,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp),
trackColor = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f),
)
}
}
@Composable
private fun SurveyBottomBar(
questionState: QuestionState,
onPreviousPressed: () -> Unit,
onNextPressed: () -> Unit,
onDonePressed: () -> Unit
) {
Surface(
modifier = Modifier.fillMaxWidth(),
shadowElevation = 7.dp,
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp, vertical = 20.dp)
) {
if (questionState.showPrevious) {
OutlinedButton(
modifier = Modifier
.weight(1f)
.height(48.dp),
onClick = onPreviousPressed
) {
Text(text = stringResource(id = R.string.previous))
}
Spacer(modifier = Modifier.width(16.dp))
}
if (questionState.showDone) {
Button(
modifier = Modifier
.weight(1f)
.height(48.dp),
onClick = onDonePressed,
enabled = questionState.enableNext
) {
Text(text = stringResource(id = R.string.done))
}
} else {
Button(
modifier = Modifier
.weight(1f)
.height(48.dp),
onClick = onNextPressed,
enabled = questionState.enableNext
) {
Text(text = stringResource(id = R.string.next))
}
}
}
}
}
| apache-2.0 | 7128ac26f27d00a5ec7f1897359ac39e | 37.5 | 101 | 0.574259 | 5.613084 | false | false | false | false |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/data/PackageSearchProjectService.kt | 1 | 13825 | package com.jetbrains.packagesearch.intellij.plugin.data
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.openapi.application.readAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.intellij.util.concurrency.AppExecutorUtil
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment
import com.jetbrains.packagesearch.intellij.plugin.api.PackageSearchApiClient
import com.jetbrains.packagesearch.intellij.plugin.api.ServerURLs
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider
import com.jetbrains.packagesearch.intellij.plugin.util.BackgroundLoadingBarController
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.batchAtIntervals
import com.jetbrains.packagesearch.intellij.plugin.util.catchAndLog
import com.jetbrains.packagesearch.intellij.plugin.util.coroutineModuleTransformers
import com.jetbrains.packagesearch.intellij.plugin.util.filesChangedEventFlow
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import com.jetbrains.packagesearch.intellij.plugin.util.mapLatestTimedWithLoading
import com.jetbrains.packagesearch.intellij.plugin.util.modifiedBy
import com.jetbrains.packagesearch.intellij.plugin.util.moduleChangesSignalFlow
import com.jetbrains.packagesearch.intellij.plugin.util.moduleTransformers
import com.jetbrains.packagesearch.intellij.plugin.util.nativeModulesChangesFlow
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectCachesService
import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap
import com.jetbrains.packagesearch.intellij.plugin.util.parallelUpdatedKeys
import com.jetbrains.packagesearch.intellij.plugin.util.replayOnSignals
import com.jetbrains.packagesearch.intellij.plugin.util.showBackgroundLoadingBar
import com.jetbrains.packagesearch.intellij.plugin.util.throttle
import com.jetbrains.packagesearch.intellij.plugin.util.timer
import com.jetbrains.packagesearch.intellij.plugin.util.trustedProjectFlow
import com.jetbrains.packagesearch.intellij.plugin.util.whileLoading
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.stateIn
import kotlinx.serialization.json.Json
import kotlin.time.Duration
@Service(Service.Level.PROJECT)
internal class PackageSearchProjectService(private val project: Project) : CoroutineScope by project.lifecycleScope {
private val retryFromErrorChannel = Channel<Unit>()
private val restartChannel = Channel<Unit>()
val dataProvider = ProjectDataProvider(
PackageSearchApiClient(ServerURLs.base),
project.packageSearchProjectCachesService.installedDependencyCache
)
private val projectModulesLoadingFlow = MutableStateFlow(false)
private val knownRepositoriesLoadingFlow = MutableStateFlow(false)
private val moduleModelsLoadingFlow = MutableStateFlow(false)
private val allInstalledKnownRepositoriesLoadingFlow = MutableStateFlow(false)
private val installedPackagesStep1LoadingFlow = MutableStateFlow(false)
private val installedPackagesStep2LoadingFlow = MutableStateFlow(false)
private val installedPackagesDifferenceLoadingFlow = MutableStateFlow(false)
private val packageUpgradesLoadingFlow = MutableStateFlow(false)
private val operationExecutedChannel = Channel<List<ProjectModule>>()
private val json = Json { prettyPrint = true }
private val cacheDirectory = project.packageSearchProjectCachesService.projectCacheDirectory.resolve("installedDependencies")
val isLoadingFlow = combineTransform(
projectModulesLoadingFlow,
knownRepositoriesLoadingFlow,
moduleModelsLoadingFlow,
allInstalledKnownRepositoriesLoadingFlow,
installedPackagesStep1LoadingFlow,
installedPackagesStep2LoadingFlow,
installedPackagesDifferenceLoadingFlow,
packageUpgradesLoadingFlow
) { booleans -> emit(booleans.any { it }) }.stateIn(this, SharingStarted.Eagerly, false)
private val projectModulesSharedFlow = project.trustedProjectFlow.flatMapLatest { isProjectTrusted ->
if (isProjectTrusted) project.nativeModulesChangesFlow else flowOf(emptyList())
}
.replayOnSignals(
retryFromErrorChannel.receiveAsFlow().throttle(Duration.seconds(10), true),
project.moduleChangesSignalFlow,
restartChannel.receiveAsFlow()
)
.mapLatestTimedWithLoading("projectModulesSharedFlow", projectModulesLoadingFlow) { modules ->
val moduleTransformations = project.moduleTransformers.map { transformer ->
async { readAction { runCatching { transformer.transformModules(project, modules) } }.getOrThrow() }
}
val coroutinesModulesTransformations = project.coroutineModuleTransformers
.map { async { it.transformModules(project, modules) } }
.awaitAll()
.flatten()
moduleTransformations.awaitAll().flatten() + coroutinesModulesTransformations
}
.catchAndLog(
context = "${this::class.qualifiedName}#projectModulesSharedFlow",
message = "Error while elaborating latest project modules",
fallbackValue = emptyList(),
retryChannel = retryFromErrorChannel
)
.shareIn(this, SharingStarted.Eagerly)
val projectModulesStateFlow = projectModulesSharedFlow.stateIn(this, SharingStarted.Eagerly, emptyList())
val isAvailable
get() = projectModulesStateFlow.value.isNotEmpty()
private val knownRepositoriesFlow = timer(Duration.hours(1))
.mapLatestTimedWithLoading("knownRepositoriesFlow", knownRepositoriesLoadingFlow) { dataProvider.fetchKnownRepositories() }
.catchAndLog(
context = "${this::class.qualifiedName}#knownRepositoriesFlow",
message = "Error while refreshing known repositories",
fallbackValue = emptyList()
)
.stateIn(this, SharingStarted.Eagerly, emptyList())
private val buildFileChangesFlow = combine(
projectModulesSharedFlow,
project.filesChangedEventFlow.map { it.mapNotNull { it.file } }
) { modules, changedBuildFiles -> modules.filter { it.buildFile in changedBuildFiles } }
.shareIn(this, SharingStarted.Eagerly)
private val projectModulesChangesFlow = merge(
buildFileChangesFlow.filter { it.isNotEmpty() },
operationExecutedChannel.consumeAsFlow()
)
.batchAtIntervals(Duration.seconds(1))
.map { it.flatMap { it }.distinct() }
.catchAndLog(
context = "${this::class.qualifiedName}#projectModulesChangesFlow",
message = "Error while checking Modules changes",
fallbackValue = emptyList()
)
.shareIn(this, SharingStarted.Eagerly)
val moduleModelsStateFlow = projectModulesSharedFlow
.mapLatestTimedWithLoading(
loggingContext = "moduleModelsStateFlow",
loadingFlow = moduleModelsLoadingFlow
) { projectModules ->
projectModules.parallelMap { it to ModuleModel(it) }.toMap()
}
.modifiedBy(projectModulesChangesFlow) { repositories, changedModules ->
repositories.parallelUpdatedKeys(changedModules) { ModuleModel(it) }
}
.map { it.values.toList() }
.catchAndLog(
context = "${this::class.qualifiedName}#moduleModelsStateFlow",
message = "Error while evaluating modules models",
fallbackValue = emptyList(),
retryChannel = retryFromErrorChannel
)
.stateIn(this, SharingStarted.Eagerly, emptyList())
val allInstalledKnownRepositoriesFlow =
combine(moduleModelsStateFlow, knownRepositoriesFlow) { moduleModels, repos -> moduleModels to repos }
.mapLatestTimedWithLoading(
loggingContext = "allInstalledKnownRepositoriesFlow",
loadingFlow = allInstalledKnownRepositoriesLoadingFlow
) { (moduleModels, repos) ->
allKnownRepositoryModels(moduleModels, repos)
}
.catchAndLog(
context = "${this::class.qualifiedName}#allInstalledKnownRepositoriesFlow",
message = "Error while evaluating installed repositories",
fallbackValue = KnownRepositories.All.EMPTY
)
.stateIn(this, SharingStarted.Eagerly, KnownRepositories.All.EMPTY)
private val dependenciesByModuleStateFlow = projectModulesSharedFlow
.mapLatestTimedWithLoading("installedPackagesStep1LoadingFlow", installedPackagesStep1LoadingFlow) {
fetchProjectDependencies(it, cacheDirectory, json)
}
.modifiedBy(projectModulesChangesFlow) { installed, changedModules ->
val (result, time) = installedPackagesDifferenceLoadingFlow.whileLoading {
installed.parallelUpdatedKeys(changedModules) { it.installedDependencies(cacheDirectory, json) }
}
logTrace("installedPackagesStep1LoadingFlow") {
"Took ${time} to elaborate diffs for ${changedModules.size} module" + if (changedModules.size > 1) "s" else ""
}
result
}
.catchAndLog(
context = "${this::class.qualifiedName}#dependenciesByModuleStateFlow",
message = "Error while evaluating installed dependencies",
fallbackValue = emptyMap(),
retryChannel = retryFromErrorChannel
)
.flowOn(AppExecutorUtil.getAppExecutorService().asCoroutineDispatcher())
.shareIn(this, SharingStarted.Eagerly)
val installedPackagesStateFlow = dependenciesByModuleStateFlow
.mapLatestTimedWithLoading("installedPackagesStep2LoadingFlow", installedPackagesStep2LoadingFlow) {
installedPackages(
it,
project,
dataProvider,
TraceInfo(TraceInfo.TraceSource.INIT)
)
}
.catchAndLog(
context = "${this::class.qualifiedName}#installedPackagesStateFlow",
message = "Error while evaluating installed packages",
fallbackValue = emptyList(),
retryChannel = retryFromErrorChannel
)
.flowOn(AppExecutorUtil.getAppExecutorService().asCoroutineDispatcher())
.stateIn(this, SharingStarted.Eagerly, emptyList())
val packageUpgradesStateFlow = installedPackagesStateFlow
.mapLatestTimedWithLoading("packageUpgradesStateFlow", packageUpgradesLoadingFlow) {
coroutineScope {
val stableUpdates = async { computePackageUpgrades(it, true, packageVersionNormalizer) }
val allUpdates = async { computePackageUpgrades(it, false, packageVersionNormalizer) }
PackageUpgradeCandidates(stableUpdates.await(), allUpdates.await())
}
}
.catchAndLog(
context = "${this::class.qualifiedName}#packageUpgradesStateFlow",
message = "Error while evaluating packages upgrade candidates",
fallbackValue = PackageUpgradeCandidates.EMPTY,
retryChannel = retryFromErrorChannel
)
.stateIn(this, SharingStarted.Eagerly, PackageUpgradeCandidates.EMPTY)
init {
// allows rerunning PKGS inspections on already opened files
// when the data is finally available or changes for PackageUpdateInspection
// or when a build file changes
packageUpgradesStateFlow.onEach { DaemonCodeAnalyzer.getInstance(project).restart() }
.launchIn(this)
var controller: BackgroundLoadingBarController? = null
if (PluginEnvironment.isNonModalLoadingEnabled) {
isLoadingFlow.throttle(Duration.seconds(1), true)
.onEach { controller?.clear() }
.filter { it }
.onEach {
controller = showBackgroundLoadingBar(
project,
PackageSearchBundle.message("toolwindow.stripe.Dependencies"),
PackageSearchBundle.message("packagesearch.ui.loading")
)
}.launchIn(this)
}
}
fun notifyOperationExecuted(successes: List<ProjectModule>) {
operationExecutedChannel.trySend(successes)
}
suspend fun restart() {
restartChannel.send(Unit)
}
}
| apache-2.0 | 0f2a836ddfff3b00203f47c92a8a6e90 | 48.375 | 131 | 0.731429 | 5.959052 | false | false | false | false |
mackristof/FollowMe | mobile/src/main/java/org/mackristof/followme/LoginActivity.kt | 1 | 12849 | package org.mackristof.followme
import android.Manifest.permission.READ_CONTACTS
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.annotation.TargetApi
import android.app.LoaderManager.LoaderCallbacks
import android.content.Context
import android.content.CursorLoader
import android.content.Intent
import android.content.Loader
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.provider.ContactsContract
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import android.widget.EditText
import android.widget.TextView
import com.github.kittinunf.fuel.httpGet
import com.github.kittinunf.fuel.httpPost
import kotlinx.android.synthetic.main.activity_login.*
import java.util.*
/**
* A login screen that offers login via email/password.
*/
class LoginActivity : AppCompatActivity(), LoaderCallbacks<Cursor> {
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private var mAuthTask: UserLoginTask? = null
// UI references.
private var mEmailView: AutoCompleteTextView? = null
private var mPasswordView: EditText? = null
private var mProgressView: View? = null
private var mLoginFormView: View? = null
override fun onPause() {
super.onPause()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
LoginActivityInstance = this
setContentView(R.layout.activity_login)
// Set up the login form.
mEmailView = email as AutoCompleteTextView
populateAutoComplete()
mPasswordView = password as EditText
mPasswordView?.setOnEditorActionListener(TextView.OnEditorActionListener { textView, id, keyEvent ->
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin()
return@OnEditorActionListener true
}
false
})
val mEmailSignInButton = email_sign_in_button
mEmailSignInButton.setOnClickListener { attemptLogin() }
mLoginFormView = login_form
mProgressView = login_progress
}
private fun populateAutoComplete() {
if (!mayRequestContacts()) {
return
}
loaderManager.initLoader(0, null, this)
}
private fun mayRequestContacts(): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
return true
}
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
return true
}
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
Snackbar.make(mEmailView as View,
R.string.permission_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok) {
requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS)
}
return false
} else {
requestPermissions(arrayOf(READ_CONTACTS), REQUEST_READ_CONTACTS)
}
return false
}
/**
* Callback received when a permissions request has been completed.
*/
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>,
grantResults: IntArray) {
if (requestCode == REQUEST_READ_CONTACTS) {
if (grantResults.size == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
populateAutoComplete()
}
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private fun attemptLogin() {
if (mAuthTask != null) {
return
}
// Reset errors.
mEmailView?.error = null
mPasswordView?.error = null
// Store values at the time of the login attempt.
val email = mEmailView?.text.toString()
val password = mPasswordView?.text.toString()
var cancel = false
var focusView: View? = null
// Check for a valid password, if the user entered one.
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
mPasswordView?.error = getString(R.string.error_invalid_password)
focusView = mPasswordView
cancel = true
}
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView?.error = getString(R.string.error_field_required)
focusView = mEmailView
cancel = true
} else if (!isEmailValid(email)) {
mEmailView?.error = getString(R.string.error_invalid_email)
focusView = mEmailView
cancel = true
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView?.requestFocus()
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true)
mAuthTask = UserLoginTask(email, password)
mAuthTask?.execute(null)
}
}
private fun isEmailValid(email: String): Boolean {
//TODO: Replace this with your own logic
return email.contains("@")
}
private fun isPasswordValid(password: String): Boolean {
//TODO: Replace this with your own logic
return password.length > 4
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private fun showProgress(show: Boolean) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime)
mLoginFormView?.visibility = if (show) View.GONE else View.VISIBLE
mLoginFormView?.animate()?.setDuration(shortAnimTime.toLong())?.alpha(
(if (show) 0 else 1).toFloat())?.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
mLoginFormView?.visibility = if (show) View.GONE else View.VISIBLE
}
})
mProgressView?.visibility = if (show) View.VISIBLE else View.GONE
mProgressView?.animate()?.setDuration(shortAnimTime.toLong())?.alpha(
(if (show) 1 else 0).toFloat())?.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
mProgressView?.visibility = if (show) View.VISIBLE else View.GONE
}
})
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView?.visibility = if (show) View.VISIBLE else View.GONE
mLoginFormView?.visibility = if (show) View.GONE else View.VISIBLE
}
}
override fun onCreateLoader(i: Int, bundle: Bundle?): Loader<Cursor> {
return CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE + " = ?", arrayOf<String>(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE),
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC")
}
override fun onLoadFinished(cursorLoader: Loader<Cursor>, cursor: Cursor) {
val emails = ArrayList<String>()
cursor.moveToFirst()
while (!cursor.isAfterLast) {
emails.add(cursor.getString(ProfileQuery.ADDRESS))
cursor.moveToNext()
}
addEmailsToAutoComplete(emails)
}
override fun onLoaderReset(cursorLoader: Loader<Cursor>) {
}
private fun addEmailsToAutoComplete(emailAddressCollection: List<String>) {
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
val adapter = ArrayAdapter(this@LoginActivity,
android.R.layout.simple_dropdown_item_1line, emailAddressCollection)
mEmailView?.setAdapter(adapter)
}
private interface ProfileQuery {
companion object {
val PROJECTION = arrayOf(ContactsContract.CommonDataKinds.Email.ADDRESS, ContactsContract.CommonDataKinds.Email.IS_PRIMARY)
val ADDRESS = 0
//val IS_PRIMARY = 1
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
inner class UserLoginTask internal constructor(private val mEmail: String, private val mPassword: String) : AsyncTask<Void, Void, Boolean?>() {
fun createAccount(mEmail: String, mPassword: String): Boolean{
val (request, response, result) = "http://192.168.1.19:8080/auth".httpPost(listOf("login" to mEmail, "password" to mPassword)).response()
when (response.httpStatusCode) {
200 -> return true
else -> {
Log.e(LoginActivity::class.java.simpleName, "error result from account creation request : "+ response.httpStatusCode)
LoginActivity.getInstance().mEmailView?.error = response.httpResponseMessage + " in account creation"
// LoginActivity.getInstance().mEmailView?.requestFocus()
return false
}
}
}
override fun doInBackground(vararg params: Void): Boolean {
// TODO: attempt authentication against a network service.
val (request, response, result) = "http://192.168.1.64:8080/auth".httpGet(listOf("login" to mEmail, "password" to mPassword)).response()
when (response.httpStatusCode){
200 -> return true
401 -> {
LoginActivity.getInstance().mPasswordView?.error = getString(R.string.error_incorrect_password)
// LoginActivity.getInstance().mPasswordView?.requestFocus()
return false
}
404 -> return createAccount(mEmail, mPassword)
else -> {
LoginActivity.getInstance().mEmailView?.error = "impossible to authenticate user : server offline"
//@TODO change this
return true
}
}
}
override fun onPostExecute(success: Boolean?) {
mAuthTask = null
showProgress(false)
if (success!!) {
finish()
val i = Intent(applicationContext as Context, MainActivity::class.java)
startActivity(i)
}
}
override fun onCancelled() {
mAuthTask = null
showProgress(false)
}
}
companion object {
/**
* Id to identity READ_CONTACTS permission request.
*/
private val REQUEST_READ_CONTACTS = 0
/**
* A dummy authentication store containing known user names and passwords.
* TODO: remove after connecting to a real authentication system.
*/
private val DUMMY_CREDENTIALS = arrayOf("[email protected]:hello", "[email protected]:world")
private var LoginActivityInstance: LoginActivity? = null
fun getInstance(): LoginActivity {
if (LoginActivityInstance != null) {
return LoginActivityInstance as LoginActivity
}
else {
throw IllegalStateException(LoginActivity::class.java.simpleName + " instance is null")
}
}
}
}
| apache-2.0 | 6482b38f0a08a9b143f63e84cfb6bac0 | 36.135838 | 149 | 0.621371 | 5.214692 | false | false | false | false |
AlexKrupa/kotlin-koans | src/v_builders/_40_BuildersHowItWorks.kt | 1 | 1978 | package v_builders.builders
import util.questions.Answer
import util.questions.Answer.*
fun todoTask40(): Nothing = TODO(
"""
Task 40.
Look at the questions below and give your answers:
change 'insertAnswerHere()' in task40's map tail your choice (a, b or c).
All the constants are imported via 'util.questions.Answer.*', so they can be accessed by name.
"""
)
fun insertAnswerHere(): Nothing = todoTask40()
fun task40() = linkedMapOf<Int, Answer>(
/*
1. In the Kotlin code
tr {
td {
text("Product")
}
td {
text("Popularity")
}
}
'td' is:
a. special built-in syntactic construct
b. function declaration
c. function invocation
*/
1 to c,
/*
2. In the Kotlin code
tr (color = "yellow") {
td {
text("Product")
}
td {
text("Popularity")
}
}
'color' is:
a. new variable declaration
b. argument name
c. argument value
*/
2 to b,
/*
3. The block
{
text("Product")
}
from the previous question is:
a. block inside built-in syntax construction 'td'
b. function literal (or "lambda")
c. something mysterious
*/
3 to b,
/*
4. For the code
tr (color = "yellow") {
this.td {
text("Product")
}
td {
text("Popularity")
}
}
which of the following is true:
a. this code doesn't compile
b. 'this' refers tail an instance of an outer class
c. 'this' refers tail a receiver parameter TR of the function literal:
tr (color = "yellow") { TR.(): Unit ->
this.td {
text("Product")
}
}
*/
4 to c
)
| mit | 3cdc4c88606ec5a1473dd790a116c3e7 | 21.477273 | 102 | 0.481294 | 4.475113 | false | false | false | false |
glorantq/KalanyosiRamszesz | src/glorantq/ramszesz/commands/ConfigDumpCommand.kt | 1 | 1831 | package glorantq.ramszesz.commands
import glorantq.ramszesz.utils.BotUtils
import glorantq.ramszesz.config.ConfigFile
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent
import sx.blah.discord.util.EmbedBuilder
/**
* Created by glorantq on 2017. 07. 23..
*/
class ConfigDumpCommand : ICommand {
override val commandName: String
get() = "configdump"
override val description: String
get() = "Dumps the config of this guild"
override val undocumented: Boolean
get() = true
override val permission: Permission
get() = Permission.ADMIN
override fun execute(event: MessageReceivedEvent, args: List<String>) {
val config: ConfigFile = BotUtils.getGuildConfig(event)
val embedBuilder: EmbedBuilder = BotUtils.embed("Config dump for ${event.guild.name}", event.author)
embedBuilder.appendField("guildId", config.guildId, true)
embedBuilder.appendField("emojiNameAppend", config.emojiNameAppend.toString(), true)
embedBuilder.appendField("deleteCommands", config.deleteCommands.toString(), true)
embedBuilder.appendField("userRole", if(config.userRole != -1L) {event.guild.getRoleByID(config.userRole).name} else {"Everyone"}, true)
embedBuilder.appendField("adminRole", if(config.adminRole != -1L) {event.guild.getRoleByID(config.adminRole).name} else {"Server Owner"}, true)
embedBuilder.appendField("modLogChannel", if(config.modLogChannel != -1L) {event.guild.getChannelByID(config.modLogChannel).name} else {"None"}, true)
embedBuilder.appendField("logModerations", config.logModerations.toString(), true)
embedBuilder.appendField("statsCalcLimit", config.statsCalcLimit.toString(), true)
BotUtils.sendMessage(embedBuilder.build(), event.channel)
}
} | gpl-3.0 | b1ecca08175129c409bbd709678f148a | 48.513514 | 158 | 0.731294 | 4.349169 | false | true | false | false |
neverwoodsS/StudyWithKotlin | src/excel/Main.kt | 1 | 4262 | package excel
import java.io.FileInputStream
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.Cell
/**
* Created by zhangll on 2017/4/9.
*/
fun main(args: Array<String>) {
val firstData = getFirstData("/Users/zhangll/Desktop/nana/201703收款单上海.xls")
val secondData = getSecondData("/Users/zhangll/Desktop/nana/泵业银行明细表0301-0331.xls")
val result = compare(firstData, secondData, "first")
result.addAll(compare(secondData, firstData, "second"))
result.forEach { println(it) }
}
private fun compare(first: List<Data>, second: List<Data>, tag: String): MutableList<Compare> {
val list = mutableListOf<Compare>()
for (data1 in first) {
var count = 0
for (data2 in second) {
if (data1 == data2) {
count++
}
}
val data = when(count) {
0 -> Compare(data1.date, data1.company, data1.money, "在${tag}中出现独立内容")
in 2 .. Int.MAX_VALUE -> Compare(data1.date, data1.company, data1.money, "内容重复,需手动检查")
else -> null
}
if (data != null && !contain(list, data)) {
list.add(data)
}
}
return list
}
private fun contain(list: MutableList<Compare>, compare: Compare): Boolean {
for (data in list) {
if (data.company == compare.company && data.date == compare.date && data.money == compare.money && data.content == compare.content) {
return true
}
}
return false
}
private fun getFirstData(filePath: String): List<Data> {
val fis = FileInputStream(filePath)
//根据上述创建的输入流 创建工作簿对象
val wb = HSSFWorkbook(fis)
//得到第一页 sheet
//页Sheet是从0开始索引的
val sheet = wb.getSheetAt(0)
fis.close()
return sheet.flatMap { it }
.map { data -> data.row }
.filter { it.getCell(0).stringCellValue != "合计" && it.getCell(6).cellType == Cell.CELL_TYPE_NUMERIC }
.map {
val date = it.getCell(1)
val company = it.getCell(2)
val money = it.getCell(6)
if (date == null || company == null || money == null) {
println("find a null data: ${it.getCell(0)}, $date, $company, $money")
null
} else {
Data(date.stringCellValue.replace("-", ""), company.stringCellValue, money.numericCellValue)
}
}
.filter { it != null }
.map { it as Data }
}
private fun getSecondData(filePath: String): List<Data> {
val fis = FileInputStream(filePath)
//根据上述创建的输入流 创建工作簿对象
val wb = HSSFWorkbook(fis)
//得到第一页 sheet
//页Sheet是从0开始索引的
val sheet = wb.getSheetAt(0)
fis.close()
return sheet.flatMap { it }
.map { data -> data.row }
.filter { it.getCell(0).stringCellValue != "合计"
&& it.lastCellNum >= 2
&& it.getCell(2).cellType == Cell.CELL_TYPE_NUMERIC }
.map {
val date = it.getCell(0)
val company = it.getCell(11)
val money = it.getCell(2)
if (date == null || company == null || money == null) {
println("find a null data: ${it.getCell(0)}, $date, $company, $money")
null
} else {
Data(date.stringCellValue, company.stringCellValue, money.numericCellValue)
}
}
.filter { it != null }
.map { it as Data }
}
open private class Data(open val date: String, open val company: String, open val money: Double) {
override fun toString(): String {
return "Data(date='$date', company='$company', money=$money)"
}
}
private class Compare(override val date: String, override val company: String, override val money: Double, val content: String) : Data(date, company, money) {
override fun toString(): String {
return "Compare(date='$date', company='$company', money=$money, content='$content')"
}
} | mit | a06e1561e2e86c45bf1f055fef9dfdda | 31.34127 | 158 | 0.560628 | 3.789767 | false | false | false | false |
bixlabs/bkotlin | bkotlin/src/main/java/com/bixlabs/bkotlin/utils/BixMediaPicker.kt | 1 | 11402 | package com.bixlabs.bkotlin.utils
import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.app.Fragment
import android.app.FragmentManager
import android.content.ContentValues
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.DocumentsContract
import android.provider.MediaStore
import androidx.core.content.ContextCompat
import com.bixlabs.bkotlin.EMPTY
import java.text.SimpleDateFormat
import java.util.*
class BixMediaPicker {
companion object {
val PICK_FROM_CAMERA = 0
val PICK_FROM_GALLERY = 1
val PICK_FROM_GALLERY_VIDEO = 2
val PICK_FROM_CAMERA_VIDEO = 3
val PICK_SUCCESS = 1
val PICK_FAILED = 0
private val DATE_FORMAT = "yyyyMMdd_HHmmss"
}
private var currentPhotoPath: String? = null
private var currentVideoPath: String? = null
/**
* pick image from Camera
*
* @param[callback] callback, should make class PickMediaCallback : PickMediaCallback
*/
fun pickFromCamera(context: Context, callback: (Int, String) -> Unit) = requestPhotoPick(context, PICK_FROM_CAMERA, callback)
/**
* pick image from Gallery
*
* @param[callback] callback, should make class PickMediaCallback : PickMediaCallback
*/
fun pickPhotoFromGallery(context: Context, callback: (Int, String) -> Unit) = requestPhotoPick(context, PICK_FROM_GALLERY, callback)
/**
* pick image from Video
*
* @param[callback] callback, should make class PickMediaCallback : PickMediaCallback
*/
fun pickVideoFromGallery(context: Context, callback: (Int, String) -> Unit) = requestPhotoPick(context, PICK_FROM_GALLERY_VIDEO, callback)
/**
* pick image from Camera (Video Mode)
*
* @param[callback] callback, should make class PickMediaCallback : PickMediaCallback
*/
fun pickFromVideoCamera(context: Context, callback: (Int, String) -> Unit) = requestPhotoPick(context, PICK_FROM_CAMERA_VIDEO, callback)
/* ********************************************
* Private methods *
******************************************** */
private fun getActivity(context: Context): Activity? {
var c = context
while (c is ContextWrapper) {
if (c is Activity) {
return c
}
c = c.baseContext
}
return null
}
@SuppressLint("ValidFragment")
private fun requestPhotoPick(context: Context, pickType: Int, callback: (Int, String) -> Unit) {
val fm = getActivity(context)?.fragmentManager
val fragment = ResultFragment(fm as FragmentManager, callback)
val fragmentTag = "FRAGMENT_TAG"
fm.beginTransaction().add(fragment, fragmentTag).commitAllowingStateLoss()
fm.executePendingTransactions()
when (pickType) {
PICK_FROM_GALLERY, PICK_FROM_GALLERY_VIDEO -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
fragment.requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), pickType)
return
}
}
PICK_FROM_CAMERA, PICK_FROM_CAMERA_VIDEO -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
(ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
fragment.requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA), pickType)
return
}
}
}
val intent = Intent("", MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
when (pickType) {
PICK_FROM_CAMERA -> {
val captureUri = createImageUri(context)
currentPhotoPath = captureUri.toString()
intent.action = MediaStore.ACTION_IMAGE_CAPTURE
intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri)
}
PICK_FROM_GALLERY -> {
intent.action = Intent.ACTION_PICK
intent.type = "image/*"
}
PICK_FROM_GALLERY_VIDEO -> {
intent.action = Intent.ACTION_PICK
intent.type = "video/*"
}
PICK_FROM_CAMERA_VIDEO -> {
val captureUri = createVideoUri(context)
currentVideoPath = captureUri.toString()
intent.action = MediaStore.ACTION_VIDEO_CAPTURE
intent.putExtra(MediaStore.EXTRA_OUTPUT, captureUri)
}
}
fragment.startActivityForResult(intent, pickType)
}
private fun createImageUri(context: Context): Uri {
val contentResolver = context.contentResolver
val cv = ContentValues()
val timeStamp = SimpleDateFormat(DATE_FORMAT, Locale.getDefault()).format(Date())
cv.put(MediaStore.Images.Media.TITLE, timeStamp)
return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv)
}
private fun createVideoUri(context: Context): Uri {
val contentResolver = context.contentResolver
val cv = ContentValues()
val timeStamp = SimpleDateFormat(DATE_FORMAT, Locale.getDefault()).format(Date())
cv.put(MediaStore.Images.Media.TITLE, timeStamp)
return contentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, cv)
}
@SuppressLint("ValidFragment")
inner class ResultFragment() : Fragment() {
private var fm: FragmentManager? = null
private var callback: ((Int, String) -> Unit)? = null
constructor(fm: FragmentManager, callback: (Int, String) -> Unit) : this() {
this.fm = fm
this.callback = callback
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (verifyPermissions(grantResults)) {
requestPhotoPick(activity, requestCode, callback as ((Int, String) -> Unit))
} else {
callback?.invoke(PICK_FAILED, "")
}
fm?.beginTransaction()?.remove(this)?.commitAllowingStateLoss()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
PICK_FROM_CAMERA ->
if (resultCode == Activity.RESULT_OK) {
currentPhotoPath?.let {
callback?.invoke(PICK_SUCCESS, getRealPath(activity, requestCode, Uri.parse(it)))
}
}
PICK_FROM_GALLERY ->
if (resultCode == Activity.RESULT_OK) {
data?.data?.let {
callback?.invoke(PICK_SUCCESS, getRealPath(activity, requestCode, it))
}
}
PICK_FROM_GALLERY_VIDEO ->
if (resultCode == Activity.RESULT_OK) {
data?.data?.let {
callback?.invoke(PICK_SUCCESS, getRealPath(activity, requestCode, it))
}
}
PICK_FROM_CAMERA_VIDEO ->
if (resultCode == Activity.RESULT_OK) {
var path = data?.data?.let {
getRealPath(activity, requestCode, it)
}
if (path.isNullOrEmpty()) {
path = currentVideoPath as String
}
if (path != null) {
callback?.invoke(PICK_SUCCESS, path)
} else {
callback?.invoke(PICK_SUCCESS, String.EMPTY())
}
}
}
fm?.beginTransaction()?.remove(this)?.commit()
}
}
private fun verifyPermissions(grantResults: IntArray): Boolean =
if (grantResults.isEmpty()) false else grantResults.none { it != PackageManager.PERMISSION_GRANTED }
private fun getRealPath(context: Context, pickType: Int, uri: Uri): String {
var filePath: String? = null
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
filePath = getRealPathPostKitKat(context, pickType, uri)
}
if (filePath != null) {
return filePath
}
val column = arrayOf(MediaStore.MediaColumns.DATA)
val cursor = context.applicationContext.contentResolver.query(uri, column, null, null, null)
if (cursor != null) {
if (cursor.moveToFirst()) {
val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA)
filePath = cursor.getString(columnIndex)
}
cursor.close()
}
return if (filePath == null) uri.path else filePath
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private fun getRealPathPostKitKat(context: Context, pickType: Int, uri: Uri): String? {
var filePath: String? = null
if (DocumentsContract.isDocumentUri(context.applicationContext, uri)) {
val wholeID = DocumentsContract.getDocumentId(uri)
val id = wholeID.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]
val column = arrayOf(MediaStore.Video.Media.DATA)
val sel = MediaStore.Video.Media._ID + "=?"
val cursor: Cursor? = when (pickType) {
PICK_FROM_CAMERA, PICK_FROM_GALLERY -> {
context.applicationContext.contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, arrayOf(id), null)
}
PICK_FROM_CAMERA_VIDEO, PICK_FROM_GALLERY_VIDEO -> {
context.applicationContext.contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
column, sel, arrayOf(id), null)
}
else -> null
}
if (cursor != null) {
val columnIndex = cursor.getColumnIndex(column[0])
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex)
}
cursor.close()
}
}
return filePath
}
} | apache-2.0 | 9d5986b19c1934bb5ee2d5a6cac78e49 | 37.265101 | 181 | 0.585073 | 5.17802 | false | false | false | false |
chiken88/passnotes | app/src/main/kotlin/com/ivanovsky/passnotes/presentation/server_login/ServerLoginViewModel.kt | 1 | 3703 | package com.ivanovsky.passnotes.presentation.server_login
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.terrakok.cicerone.Router
import com.ivanovsky.passnotes.R
import com.ivanovsky.passnotes.data.entity.FSType
import com.ivanovsky.passnotes.data.entity.ServerCredentials
import com.ivanovsky.passnotes.domain.ResourceProvider
import com.ivanovsky.passnotes.domain.interactor.ErrorInteractor
import com.ivanovsky.passnotes.domain.interactor.server_login.ServerLoginInteractor
import com.ivanovsky.passnotes.presentation.Screens.ServerLoginScreen
import com.ivanovsky.passnotes.presentation.core.DefaultScreenStateHandler
import com.ivanovsky.passnotes.presentation.core.ScreenState
import com.ivanovsky.passnotes.presentation.core.event.SingleLiveEvent
import com.ivanovsky.passnotes.util.StringUtils.EMPTY
import kotlinx.coroutines.launch
class ServerLoginViewModel(
private val interactor: ServerLoginInteractor,
private val errorInteractor: ErrorInteractor,
private val resourceProvider: ResourceProvider,
private val router: Router,
private val args: ServerLoginArgs
) : ViewModel() {
val screenStateHandler = DefaultScreenStateHandler()
val screenState = MutableLiveData(ScreenState.data())
val url = MutableLiveData(EMPTY)
val username = MutableLiveData(EMPTY)
val password = MutableLiveData(EMPTY)
val urlError = MutableLiveData<String?>()
val doneButtonVisibility = MutableLiveData(true)
val hideKeyboardEvent = SingleLiveEvent<Unit>()
init {
loadDebugData()
}
fun authenticate() {
val url = url.value ?: return
val username = username.value ?: return
val password = password.value ?: return
if (!isFieldsValid(url)) {
return
}
val credentials = ServerCredentials(url, username, password)
screenState.value = ScreenState.loading()
hideKeyboardEvent.call()
doneButtonVisibility.value = false
viewModelScope.launch {
val authentication = interactor.authenticate(credentials, args.fsAuthority)
if (authentication.isFailed) {
val message = errorInteractor.processAndGetMessage(authentication.error)
screenState.value = ScreenState.dataWithError(message)
doneButtonVisibility.value = true
return@launch
}
val save = interactor.saveCredentials(credentials, args.fsAuthority)
if (save.isFailed) {
val message = errorInteractor.processAndGetMessage(save.error)
screenState.value = ScreenState.dataWithError(message)
doneButtonVisibility.value = true
return@launch
}
val fsAuthority = args.fsAuthority.copy(
credentials = credentials
)
router.sendResult(ServerLoginScreen.RESULT_KEY, fsAuthority)
router.exit()
}
}
fun navigateBack() = router.exit()
private fun isFieldsValid(url: String): Boolean {
urlError.value = if (url.isBlank()) {
resourceProvider.getString(R.string.empty_field)
} else {
null
}
return url.isNotBlank()
}
private fun loadDebugData() {
val credentials = when (args.fsAuthority.type) {
FSType.WEBDAV -> interactor.getDebugWebDavCredentials()
else -> null
}
credentials?.let {
url.value = it.serverUrl
username.value = it.username
password.value = it.password
}
}
} | gpl-2.0 | bda77e48858a6624424e2f8e6eda6158 | 33.616822 | 88 | 0.6862 | 5.100551 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/VirtualStorageLinkInfo.kt | 2 | 1742 | package com.github.kerubistan.kerub.model
import com.github.kerubistan.kerub.model.collection.HostDataCollection
import com.github.kerubistan.kerub.model.collection.VirtualStorageDataCollection
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageAllocation
import com.github.kerubistan.kerub.model.services.HostService
import com.github.kerubistan.kerub.model.services.StorageService
import java.io.Serializable
/**
* Collection of all the technical data needed for a VM disk attachment.
*/
data class VirtualStorageLinkInfo(
val link: VirtualStorageLink,
val device: VirtualStorageDataCollection,
val allocation: VirtualStorageAllocation,
val hostServiceUsed: HostService?,
val storageHost: HostDataCollection
) : Serializable {
init {
check(allocation.hostId == storageHost.stat.id) {
"host id of allocation (${allocation.hostId}) does not match storage host id ${storageHost.stat.id}"
}
check(link.virtualStorageId == device.stat.id) {
"virtual storage id of the link (${link.virtualStorageId}) does not match the device id (${device.stat.id})"
}
if (hostServiceUsed is StorageService) {
check(hostServiceUsed.vstorageId == device.stat.id) {
"virtual storage id (${hostServiceUsed.vstorageId}) of storage service " +
"does not match device id ${device.stat.id}"
}
}
check(allocation.requires().isInstance(
storageHost.stat.capabilities?.index?.storageCapabilitiesById?.get(allocation.capabilityId))) {
"allocation $allocation does not match the type of the referenced allocation (${allocation.capabilityId}) " +
"of host ${storageHost.stat.address}, " +
"registered host storage capabilities are: ${storageHost.stat.capabilities?.storageCapabilities}"
}
}
} | apache-2.0 | 9d25178ee17540080877383e096aa7c4 | 42.575 | 112 | 0.769805 | 4.177458 | false | false | false | false |
spinnaker/kork | kork-sql/src/test/kotlin/com/netflix/spinnaker/kork/sql/health/SqlHealthProviderSpec.kt | 3 | 2997 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.sql.health
import com.netflix.spectator.api.NoopRegistry
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.doThrow
import com.nhaarman.mockito_kotlin.isA
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.reset
import com.nhaarman.mockito_kotlin.whenever
import org.jooq.DSLContext
import org.jooq.DeleteUsingStep
import org.jooq.Table
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.gherkin.Feature
import strikt.api.expectThat
import strikt.assertions.isEqualTo
internal object SqlHealthProviderSpec : Spek({
Feature("healthchecking sql") {
val dslContext = mock<DSLContext>()
val query = mock<DeleteUsingStep<*>>()
Scenario("a healthy current state") {
val subject = SqlHealthProvider(dslContext, NoopRegistry(), readOnly = false, unhealthyThreshold = 1).apply {
_enabled.set(true)
}
afterEachStep { reset(dslContext, query) }
When("successive write failures") {
whenever(dslContext.delete(isA<Table<*>>())) doThrow RuntimeException("oh no")
subject.performCheck()
subject.performCheck()
}
Then("deactivates its enabled flag") {
expectThat(subject.enabled).isEqualTo(false)
}
}
Scenario("a healthy current readOnly state") {
val subject = SqlHealthProvider(dslContext, NoopRegistry(), readOnly = true, unhealthyThreshold = 1).apply {
_enabled.set(true)
}
afterEachStep { reset(dslContext, query) }
When("successive read failures") {
whenever(dslContext.select()) doThrow RuntimeException("oh no")
subject.performCheck()
subject.performCheck()
}
Then("deactivates its enabled flag") {
expectThat(subject.enabled).isEqualTo(false)
}
}
Scenario("an unhealthy sql connection") {
val subject = SqlHealthProvider(dslContext, NoopRegistry(), readOnly = false, healthyThreshold = 1).apply {
_enabled.set(false)
}
afterEachStep { reset(dslContext, query) }
When("successive write failures") {
whenever(dslContext.delete(isA<Table<*>>())) doReturn query
subject.performCheck()
subject.performCheck()
}
Then("deactivates its enabled flag") {
expectThat(subject.enabled).isEqualTo(true)
}
}
}
})
| apache-2.0 | 374bbff5cd2ac9c73560528394955ec2 | 29.896907 | 115 | 0.698699 | 4.44 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/listener/PlayerQuitListener.kt | 1 | 1844 | /*
* Copyright 2019 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.essentials.bukkit.listener
import com.rpkit.essentials.bukkit.RPKEssentialsBukkit
import com.rpkit.essentials.bukkit.logmessage.RPKLogMessageProvider
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerQuitEvent
class PlayerQuitListener(private val plugin: RPKEssentialsBukkit): Listener {
@EventHandler
fun onPlayerQuit(event: PlayerQuitEvent) {
val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val logMessageProvider = plugin.core.serviceManager.getServiceProvider(RPKLogMessageProvider::class)
val quitMessage = event.quitMessage
if (quitMessage != null) {
plugin.server.onlinePlayers
.mapNotNull { player -> minecraftProfileProvider.getMinecraftProfile(player) }
.filter { minecraftProfile -> logMessageProvider.isLogMessagesEnabled(minecraftProfile) }
.forEach { minecraftProfile ->
minecraftProfile.sendMessage(quitMessage)
}
}
event.quitMessage = null
}
} | apache-2.0 | a44579d7deffbb21bb3bde8fc87fc2ad | 39.108696 | 120 | 0.729935 | 5.093923 | false | false | false | false |
duftler/clouddriver | cats/cats-sql/src/main/kotlin/com/netflix/spinnaker/cats/sql/cache/SqlTableMetricsAgent.kt | 1 | 2286 | package com.netflix.spinnaker.cats.sql.cache
import com.netflix.spectator.api.Registry
import com.netflix.spinnaker.cats.agent.RunnableAgent
import com.netflix.spinnaker.clouddriver.sql.SqlAgent
import com.netflix.spinnaker.clouddriver.cache.CustomScheduledAgent
import com.netflix.spinnaker.clouddriver.core.provider.CoreProvider
import org.jooq.DSLContext
import org.jooq.impl.DSL.table
import org.slf4j.LoggerFactory
import java.time.Clock
import java.util.concurrent.TimeUnit
class SqlTableMetricsAgent(
private val jooq: DSLContext,
private val registry: Registry,
private val clock: Clock,
private val namespace: String?
) : RunnableAgent, CustomScheduledAgent, SqlAgent {
companion object {
private val DEFAULT_POLL_INTERVAL_MILLIS = TimeUnit.MINUTES.toMillis(1)
private val DEFAULT_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(2)
private val log = LoggerFactory.getLogger(SqlTableMetricsAgent::class.java)
}
private val countId = registry.createId("cats.sqlCache.tableMetricsAgent.count")
.withTag("namespace", namespace ?: "none")
private val timingId = registry.createId("cats.sqlCache.tableMetricsAgent.timing")
.withTag("namespace", namespace ?: "none")
override fun run() {
val start = clock.millis()
var tableCount = 0
val baseName = if (namespace == null) {
"cats_v${SqlSchemaVersion.current()}_"
} else {
"cats_v${SqlSchemaVersion.current()}_${namespace}_"
}
val rs = jooq.fetch("show tables like '$baseName%'").intoResultSet()
while (rs.next()) {
val tableName = rs.getString(1)
val type = tableName.replace(baseName, "")
val count = jooq.selectCount()
.from(table(tableName))
.fetchOne(0, Int::class.java)
registry.gauge(countId.withTag("type", type)).set(count.toDouble())
tableCount++
}
val runTime = clock.millis() - start
registry.gauge(timingId).set(runTime.toDouble())
log.info("Read counts for $tableCount tables in ${runTime}ms")
}
override fun getAgentType(): String = javaClass.simpleName
override fun getProviderName(): String = CoreProvider.PROVIDER_NAME
override fun getPollIntervalMillis(): Long = DEFAULT_POLL_INTERVAL_MILLIS
override fun getTimeoutMillis(): Long = DEFAULT_TIMEOUT_MILLIS
}
| apache-2.0 | db6047cce016f9dc349a7fe8f0c625da | 33.119403 | 84 | 0.730534 | 4.060391 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/test/kotlin/com/gmail/blueboxware/libgdxplugin/properties/TestReferences.kt | 1 | 6207 | package com.gmail.blueboxware.libgdxplugin.properties
import com.gmail.blueboxware.libgdxplugin.filetypes.properties.GDXPropertyReference
import com.gmail.blueboxware.libgdxplugin.utils.asPlainString
import com.gmail.blueboxware.libgdxplugin.utils.asString
import com.gmail.blueboxware.libgdxplugin.utils.firstParent
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.lang.properties.psi.Property
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.psi.PsiLiteralExpression
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
/*
* Copyright 2017 Blue Box Ware
*
* 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.
*/
class TestReferences : PropertiesCodeInsightFixtureTestCase() {
private val kotlinTests = listOf(
"""
I18NBundle().get("<caret>noTranslation");
""" to true,
"""
I18NBundle().format("<caret>noTranslation", "germanTranslation");
""" to true,
"""
I18NBundle().format("noTranslation", "<caret>noTranslation");
""" to false,
"""
I18NBundle().get("<caret>french.Only");
""" to true,
"""
i18NBundle.get("<caret>noTranslation");
""" to true,
"""
i18NBundle.format("<caret>noTranslation", "germanTranslation");
""" to true,
"""
i18NBundle.format("noTranslation", "<caret>noTranslation");
""" to false,
"""
i18NBundle.get("<caret>french.Only");
""" to true,
"""
i18NBundle2.get("<caret>noTranslation");
""" to false,
"""
i18NBundle2.format("<caret>noTranslation", "germanTranslation");
""" to false,
"""
i18NBundle2.format("noTranslation", "<caret>noTranslation");
""" to false,
"""
i18NBundle2.get("<caret>french.Only");
""" to false
)
private val javaTests = listOf(
"""
new I18NBundle().get("<caret>noTranslation");
""" to true,
"""
new I18NBundle().format("<caret>noTranslation", "germanTranslation");
""" to true,
"""
new I18NBundle().format("noTranslation", "<caret>noTranslation");
""" to false,
"""
new I18NBundle().get("<caret>french.Only");
""" to true,
"""
i18NBundle.get("<caret>noTranslation");
""" to true,
"""
i18NBundle.format("<caret>noTranslation", "germanTranslation");
""" to true,
"""
i18NBundle.format("noTranslation", "<caret>noTranslation");
""" to false,
"""
i18NBundle.get("<caret>french.Only");
""" to true,
"""
i18NBundle2.get("<caret>noTranslation");
""" to false,
"""
i18NBundle2.format("<caret>noTranslation", "germanTranslation");
""" to false,
"""
i18NBundle2.format("noTranslation", "<caret>noTranslation");
""" to false,
"""
i18NBundle2.get("<caret>french.Only");
""" to false
)
fun testKotlinPropertiesReferences() {
addKotlin()
for ((test, shouldBeFound) in kotlinTests) {
val content = """
import com.badlogic.gdx.utils.I18NBundle
import com.gmail.blueboxware.libgdxplugin.annotations.GDXAssets
@GDXAssets(propertiesFiles = ["src/messages.properties"])
val i18NBundle = I18NBundle()
@GDXAssets(propertiesFiles = arrayOf("src/doesnotexist.properties"))
val i18NBundle2 = I18NBundle()
fun f() {
$test
}
"""
doTest(KotlinFileType.INSTANCE, content, shouldBeFound)
}
}
fun testJavaPropertiesReferences() {
for ((test, shouldBeFound) in javaTests) {
val content = """
import com.badlogic.gdx.utils.I18NBundle;
import com.gmail.blueboxware.libgdxplugin.annotations.GDXAssets;
class Test {
@GDXAssets(propertiesFiles = "src/messages.properties")
I18NBundle i18NBundle;
@GDXAssets(propertiesFiles = "src/doesnotexist.properties")
I18NBundle i18NBundle2;
void m() {
$test
}
}
"""
doTest(JavaFileType.INSTANCE, content, shouldBeFound)
}
}
fun doTest(fileType: LanguageFileType, content: String, shouldBeFound: Boolean = true) {
configureByText(fileType, content)
val referencingElement = file.findElementAt(myFixture.caretOffset)?.let { elementAtCaret ->
elementAtCaret.firstParent { it is KtStringTemplateExpression || it is PsiLiteralExpression }
} ?: throw AssertionError("Referencing element not found")
var found = false
referencingElement.references.forEach { reference ->
(reference as? GDXPropertyReference)?.multiResolve(true)?.forEach { resolveResult ->
assertTrue(resolveResult.element is Property)
val text =
when (referencingElement) {
is PsiLiteralExpression -> referencingElement.asString()
is KtStringTemplateExpression -> referencingElement.asPlainString()
else -> throw AssertionError()
}
assertEquals((resolveResult.element as? Property)?.name, text)
found = true
}
}
assertEquals(content, shouldBeFound, found)
}
}
| apache-2.0 | dfd7aba7feef45e5ab0a1206629169dd | 32.918033 | 105 | 0.592557 | 5.017785 | false | true | false | false |
gradle/gradle | subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheState.kt | 2 | 28343 | /*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache
import org.gradle.api.artifacts.component.BuildIdentifier
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.BuildDefinition
import org.gradle.api.internal.FeaturePreviews
import org.gradle.api.internal.GradleInternal
import org.gradle.api.internal.SettingsInternal.BUILD_SRC
import org.gradle.api.internal.project.ProjectState
import org.gradle.api.provider.Provider
import org.gradle.api.services.internal.BuildServiceProvider
import org.gradle.api.services.internal.BuildServiceRegistryInternal
import org.gradle.api.services.internal.RegisteredBuildServiceProvider
import org.gradle.caching.configuration.BuildCache
import org.gradle.caching.configuration.internal.BuildCacheServiceRegistration
import org.gradle.configurationcache.CachedProjectState.Companion.computeCachedState
import org.gradle.configurationcache.CachedProjectState.Companion.configureProjectFromCachedState
import org.gradle.configurationcache.extensions.serviceOf
import org.gradle.configurationcache.extensions.unsafeLazy
import org.gradle.configurationcache.problems.DocumentationSection.NotYetImplementedSourceDependencies
import org.gradle.configurationcache.serialization.DefaultReadContext
import org.gradle.configurationcache.serialization.DefaultWriteContext
import org.gradle.configurationcache.serialization.codecs.Codecs
import org.gradle.configurationcache.serialization.logNotImplemented
import org.gradle.configurationcache.serialization.readCollection
import org.gradle.configurationcache.serialization.readFile
import org.gradle.configurationcache.serialization.readList
import org.gradle.configurationcache.serialization.readNonNull
import org.gradle.configurationcache.serialization.readStrings
import org.gradle.configurationcache.serialization.runReadOperation
import org.gradle.configurationcache.serialization.withDebugFrame
import org.gradle.configurationcache.serialization.withGradleIsolate
import org.gradle.configurationcache.serialization.writeCollection
import org.gradle.configurationcache.serialization.writeFile
import org.gradle.configurationcache.serialization.writeStrings
import org.gradle.configurationcache.services.EnvironmentChangeTracker
import org.gradle.execution.plan.Node
import org.gradle.initialization.BuildIdentifiedProgressDetails
import org.gradle.initialization.BuildStructureOperationProject
import org.gradle.initialization.ProjectsIdentifiedProgressDetails
import org.gradle.initialization.RootBuildCacheControllerSettingsProcessor
import org.gradle.internal.Actions
import org.gradle.internal.build.BuildStateRegistry
import org.gradle.internal.build.CompositeBuildParticipantBuildState
import org.gradle.internal.build.IncludedBuildState
import org.gradle.internal.build.PublicBuildPath
import org.gradle.internal.build.RootBuildState
import org.gradle.internal.build.event.BuildEventListenerRegistryInternal
import org.gradle.internal.buildoption.FeatureFlags
import org.gradle.internal.buildtree.BuildTreeWorkGraph
import org.gradle.internal.composite.IncludedBuildInternal
import org.gradle.internal.enterprise.core.GradleEnterprisePluginAdapter
import org.gradle.internal.enterprise.core.GradleEnterprisePluginManager
import org.gradle.internal.execution.BuildOutputCleanupRegistry
import org.gradle.internal.operations.BuildOperationProgressEventEmitter
import org.gradle.internal.serialize.Decoder
import org.gradle.internal.serialize.Encoder
import org.gradle.plugin.management.internal.PluginRequests
import org.gradle.vcs.internal.VcsMappingsStore
import java.io.File
import java.io.InputStream
import java.io.OutputStream
internal
enum class StateType {
Work, Model, Entry, BuildFingerprint, ProjectFingerprint, IntermediateModels, ProjectMetadata
}
internal
interface ConfigurationCacheStateFile {
val exists: Boolean
fun outputStream(): OutputStream
fun inputStream(): InputStream
fun delete()
// Replace the contents of this state file, by moving the given file to the location of this state file
fun moveFrom(file: File)
fun stateFileForIncludedBuild(build: BuildDefinition): ConfigurationCacheStateFile
}
internal
class ConfigurationCacheState(
private val codecs: Codecs,
private val stateFile: ConfigurationCacheStateFile
) {
/**
* Writes the state for the whole build starting from the given root [build] and returns the set
* of stored included build directories.
*/
suspend fun DefaultWriteContext.writeRootBuildState(build: VintageGradleBuild) =
writeRootBuild(build).also {
writeInt(0x1ecac8e)
}
suspend fun DefaultReadContext.readRootBuildState(graph: BuildTreeWorkGraph, loadAfterStore: Boolean, createBuild: (File?, String) -> ConfigurationCacheBuild): BuildTreeWorkGraph.FinalizedGraph {
val buildState = readRootBuild(createBuild)
require(readInt() == 0x1ecac8e) {
"corrupt state file"
}
if (!loadAfterStore) {
identifyBuild(buildState)
}
return calculateRootTaskGraph(buildState, graph)
}
private
fun identifyBuild(state: CachedBuildState) {
val gradle = state.build.gradle
val emitter = gradle.serviceOf<BuildOperationProgressEventEmitter>()
emitter.emitNowForCurrent(BuildIdentifiedProgressDetails { gradle.identityPath.toString() })
emitter.emitNowForCurrent(object : ProjectsIdentifiedProgressDetails {
override fun getBuildPath() = gradle.identityPath.toString()
override fun getRootProject() = BuildStructureOperationProject.from(gradle)
})
state.children.forEach(::identifyBuild)
}
private
fun calculateRootTaskGraph(state: CachedBuildState, graph: BuildTreeWorkGraph): BuildTreeWorkGraph.FinalizedGraph {
return graph.scheduleWork { builder ->
builder.withWorkGraph(state.build.state) {
it.setScheduledNodes(state.workGraph)
}
for (child in state.children) {
addNodesForChildBuilds(child, builder)
}
}
}
private
fun addNodesForChildBuilds(state: CachedBuildState, builder: BuildTreeWorkGraph.Builder) {
builder.withWorkGraph(state.build.state) {
it.setScheduledNodes(state.workGraph)
}
for (child in state.children) {
addNodesForChildBuilds(child, builder)
}
}
private
suspend fun DefaultWriteContext.writeRootBuild(build: VintageGradleBuild) {
require(build.gradle.owner is RootBuildState)
val gradle = build.gradle
withDebugFrame({ "Gradle" }) {
write(gradle.settings.settingsScript.resource.file)
writeString(gradle.rootProject.name)
writeBuildTreeState(gradle)
}
val buildEventListeners = buildEventListenersOf(gradle)
writeBuildState(
build,
StoredBuildTreeState(
storedBuilds = storedBuilds(),
requiredBuildServicesPerBuild = buildEventListeners
.groupBy { it.buildIdentifier }
)
)
writeRootEventListenerSubscriptions(gradle, buildEventListeners)
}
private
suspend fun DefaultReadContext.readRootBuild(
createBuild: (File?, String) -> ConfigurationCacheBuild
): CachedBuildState {
val settingsFile = read() as File?
val rootProjectName = readString()
val build = createBuild(settingsFile, rootProjectName)
val gradle = build.gradle
readBuildTreeState(gradle)
val rootBuildState = readBuildState(build)
readRootEventListenerSubscriptions(gradle)
return rootBuildState
}
internal
suspend fun DefaultWriteContext.writeBuildState(build: VintageGradleBuild, buildTreeState: StoredBuildTreeState) {
val gradle = build.gradle
withDebugFrame({ "Gradle" }) {
writeGradleState(gradle, buildTreeState)
}
withDebugFrame({ "Work Graph" }) {
val scheduledNodes = build.scheduledWork
val relevantProjects = getRelevantProjectsFor(scheduledNodes, gradle.serviceOf())
writeRelevantProjectRegistrations(relevantProjects)
writeProjectStates(gradle, relevantProjects)
writeRequiredBuildServicesOf(gradle, buildTreeState)
writeWorkGraphOf(gradle, scheduledNodes)
}
withDebugFrame({ "cleanup registrations" }) {
writeBuildOutputCleanupRegistrations(gradle)
}
}
internal
suspend fun DefaultReadContext.readBuildState(build: ConfigurationCacheBuild): CachedBuildState {
val gradle = build.gradle
lateinit var children: List<CachedBuildState>
val readOperation: suspend DefaultReadContext.() -> Unit = {
children = readGradleState(build)
}
runReadOperation(readOperation)
readRelevantProjectRegistrations(build)
build.registerProjects()
initProjectProvider(build::getProject)
readProjectStates(gradle)
readRequiredBuildServicesOf(gradle)
val workGraph = readWorkGraph(gradle)
readBuildOutputCleanupRegistrations(gradle)
return CachedBuildState(build, workGraph, children)
}
data class CachedBuildState(
val build: ConfigurationCacheBuild,
val workGraph: List<Node>,
val children: List<CachedBuildState>
)
private
suspend fun DefaultWriteContext.writeWorkGraphOf(gradle: GradleInternal, scheduledNodes: List<Node>) {
workNodeCodec(gradle).run {
writeWork(scheduledNodes)
}
}
private
suspend fun DefaultReadContext.readWorkGraph(gradle: GradleInternal) =
workNodeCodec(gradle).run {
readWork()
}
private
fun workNodeCodec(gradle: GradleInternal) =
codecs.workNodeCodecFor(gradle)
private
suspend fun DefaultWriteContext.writeRequiredBuildServicesOf(gradle: GradleInternal, buildTreeState: StoredBuildTreeState) {
withGradleIsolate(gradle, userTypesCodec) {
write(buildTreeState.requiredBuildServicesPerBuild[buildIdentifierOf(gradle)])
}
}
private
suspend fun DefaultReadContext.readRequiredBuildServicesOf(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
read()
}
}
private
suspend fun DefaultWriteContext.writeProjectStates(gradle: GradleInternal, relevantProjects: List<ProjectState>) {
withGradleIsolate(gradle, userTypesCodec) {
// Do not serialize trivial states to speed up deserialization.
val nonTrivialProjectStates = relevantProjects.asSequence()
.map { project -> project.mutableModel.computeCachedState() }
.filterNotNull()
.toList()
writeCollection(nonTrivialProjectStates)
}
}
private
suspend fun DefaultReadContext.readProjectStates(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
readCollection {
configureProjectFromCachedState(read() as CachedProjectState)
}
}
}
private
suspend fun DefaultWriteContext.writeBuildTreeState(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
withDebugFrame({ "environment state" }) {
writeCachedEnvironmentState(gradle)
writePreviewFlags(gradle)
}
withDebugFrame({ "gradle enterprise" }) {
writeGradleEnterprisePluginManager(gradle)
}
withDebugFrame({ "build cache" }) {
writeBuildCacheConfiguration(gradle)
}
}
}
private
suspend fun DefaultReadContext.readBuildTreeState(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
readCachedEnvironmentState(gradle)
readPreviewFlags(gradle)
// It is important that the Gradle Enterprise plugin be read before
// build cache configuration, as it may contribute build cache configuration.
readGradleEnterprisePluginManager(gradle)
readBuildCacheConfiguration(gradle)
}
}
private
suspend fun DefaultWriteContext.writeRootEventListenerSubscriptions(gradle: GradleInternal, listeners: List<Provider<*>>) {
withGradleIsolate(gradle, userTypesCodec) {
withDebugFrame({ "listener subscriptions" }) {
writeBuildEventListenerSubscriptions(listeners)
}
}
}
private
suspend fun DefaultReadContext.readRootEventListenerSubscriptions(gradle: GradleInternal) {
withGradleIsolate(gradle, userTypesCodec) {
readBuildEventListenerSubscriptions(gradle)
}
}
private
suspend fun DefaultWriteContext.writeGradleState(gradle: GradleInternal, buildTreeState: StoredBuildTreeState) {
withGradleIsolate(gradle, userTypesCodec) {
// per build
writeStartParameterOf(gradle)
withDebugFrame({ "included builds" }) {
writeChildBuilds(gradle, buildTreeState)
}
}
}
private
suspend fun DefaultReadContext.readGradleState(
build: ConfigurationCacheBuild
): List<CachedBuildState> {
val gradle = build.gradle
withGradleIsolate(gradle, userTypesCodec) {
// per build
readStartParameterOf(gradle)
return readChildBuildsOf(build)
}
}
private
fun DefaultWriteContext.writeStartParameterOf(gradle: GradleInternal) {
val startParameterTaskNames = gradle.startParameter.taskNames
writeStrings(startParameterTaskNames)
}
private
fun DefaultReadContext.readStartParameterOf(gradle: GradleInternal) {
// Restore startParameter.taskNames to enable `gradle.startParameter.setTaskNames(...)` idiom in included build scripts
// See org/gradle/caching/configuration/internal/BuildCacheCompositeConfigurationIntegrationTest.groovy:134
val startParameterTaskNames = readStrings()
gradle.startParameter.setTaskNames(startParameterTaskNames)
}
private
suspend fun DefaultWriteContext.writeChildBuilds(gradle: GradleInternal, buildTreeState: StoredBuildTreeState) {
writeCollection(gradle.includedBuilds()) {
writeIncludedBuildState(it, buildTreeState)
}
if (gradle.serviceOf<VcsMappingsStore>().asResolver().hasRules()) {
logNotImplemented(
feature = "source dependencies",
documentationSection = NotYetImplementedSourceDependencies
)
writeBoolean(true)
} else {
writeBoolean(false)
}
}
private
suspend fun DefaultReadContext.readChildBuildsOf(
parentBuild: ConfigurationCacheBuild
): List<CachedBuildState> {
val includedBuilds = readList {
readIncludedBuildState(parentBuild)
}
if (readBoolean()) {
logNotImplemented(
feature = "source dependencies",
documentationSection = NotYetImplementedSourceDependencies
)
}
parentBuild.gradle.setIncludedBuilds(includedBuilds.map { it.first.model })
return includedBuilds.mapNotNull { it.second }
}
private
suspend fun DefaultWriteContext.writeIncludedBuildState(
reference: IncludedBuildInternal,
buildTreeState: StoredBuildTreeState
) {
when (val target = reference.target) {
is IncludedBuildState -> {
writeBoolean(true)
val includedGradle = target.mutableModel
val buildDefinition = includedGradle.serviceOf<BuildDefinition>()
writeBuildDefinition(buildDefinition)
when {
buildTreeState.storedBuilds.store(buildDefinition) -> {
writeBoolean(true)
target.projects.withMutableStateOfAllProjects {
includedGradle.serviceOf<ConfigurationCacheIO>().writeIncludedBuildStateTo(
stateFileFor(buildDefinition),
buildTreeState
)
}
}
else -> {
writeBoolean(false)
}
}
}
is RootBuildState -> {
writeBoolean(false)
}
else -> {
TODO("Unsupported included build type '${target.javaClass}'")
}
}
}
private
suspend fun DefaultReadContext.readIncludedBuildState(
parentBuild: ConfigurationCacheBuild
): Pair<CompositeBuildParticipantBuildState, CachedBuildState?> =
when {
readBoolean() -> {
val buildDefinition = readIncludedBuildDefinition(parentBuild)
val includedBuild = parentBuild.addIncludedBuild(buildDefinition)
val stored = readBoolean()
val cachedBuildState =
if (stored) {
val confCacheBuild = includedBuild.withState { includedGradle ->
includedGradle.serviceOf<ConfigurationCacheHost>().createBuild(null, includedBuild.name)
}
confCacheBuild.gradle.serviceOf<ConfigurationCacheIO>().readIncludedBuildStateFrom(
stateFileFor(buildDefinition),
confCacheBuild
)
} else null
includedBuild to cachedBuildState
}
else -> {
rootBuildStateOf(parentBuild) to null
}
}
private
fun rootBuildStateOf(parentBuild: ConfigurationCacheBuild): RootBuildState =
parentBuild.gradle.serviceOf<BuildStateRegistry>().rootBuild
private
suspend fun DefaultWriteContext.writeBuildDefinition(buildDefinition: BuildDefinition) {
buildDefinition.run {
writeString(name!!)
writeFile(buildRootDir)
write(fromBuild)
writeBoolean(isPluginBuild)
}
}
private
suspend fun DefaultReadContext.readIncludedBuildDefinition(parentBuild: ConfigurationCacheBuild): BuildDefinition {
val includedBuildName = readString()
val includedBuildRootDir = readFile()
val fromBuild = readNonNull<PublicBuildPath>()
val pluginBuild = readBoolean()
return BuildDefinition.fromStartParameterForBuild(
parentBuild.gradle.startParameter,
includedBuildName,
includedBuildRootDir,
PluginRequests.EMPTY,
Actions.doNothing(),
fromBuild,
pluginBuild
)
}
private
suspend fun DefaultWriteContext.writeBuildCacheConfiguration(gradle: GradleInternal) {
gradle.settings.buildCache.let { buildCache ->
write(buildCache.local)
write(buildCache.remote)
write(buildCache.registrations)
}
}
private
suspend fun DefaultReadContext.readBuildCacheConfiguration(gradle: GradleInternal) {
gradle.settings.buildCache.let { buildCache ->
buildCache.local = readNonNull()
buildCache.remote = read() as BuildCache?
buildCache.registrations = readNonNull<MutableSet<BuildCacheServiceRegistration>>()
}
RootBuildCacheControllerSettingsProcessor.process(gradle)
}
private
suspend fun DefaultWriteContext.writeBuildEventListenerSubscriptions(listeners: List<Provider<*>>) {
writeCollection(listeners) { listener ->
when (listener) {
is RegisteredBuildServiceProvider<*, *> -> {
writeBoolean(true)
write(listener.buildIdentifier)
writeString(listener.name)
}
else -> {
writeBoolean(false)
write(listener)
}
}
}
}
private
suspend fun DefaultReadContext.readBuildEventListenerSubscriptions(gradle: GradleInternal) {
val eventListenerRegistry by unsafeLazy {
gradle.serviceOf<BuildEventListenerRegistryInternal>()
}
val buildStateRegistry by unsafeLazy {
gradle.serviceOf<BuildStateRegistry>()
}
readCollection {
when (readBoolean()) {
true -> {
val buildIdentifier = readNonNull<BuildIdentifier>()
val serviceName = readString()
val provider = buildStateRegistry.buildServiceRegistrationOf(buildIdentifier).getByName(serviceName)
eventListenerRegistry.subscribe(provider.service)
}
else -> {
val provider = readNonNull<Provider<*>>()
eventListenerRegistry.subscribe(provider)
}
}
}
}
private
suspend fun DefaultWriteContext.writeBuildOutputCleanupRegistrations(gradle: GradleInternal) {
val buildOutputCleanupRegistry = gradle.serviceOf<BuildOutputCleanupRegistry>()
withGradleIsolate(gradle, userTypesCodec) {
writeCollection(buildOutputCleanupRegistry.registeredOutputs)
}
}
private
suspend fun DefaultReadContext.readBuildOutputCleanupRegistrations(gradle: GradleInternal) {
val buildOutputCleanupRegistry = gradle.serviceOf<BuildOutputCleanupRegistry>()
withGradleIsolate(gradle, userTypesCodec) {
readCollection {
val files = readNonNull<FileCollection>()
buildOutputCleanupRegistry.registerOutputs(files)
}
}
}
private
suspend fun DefaultWriteContext.writeCachedEnvironmentState(gradle: GradleInternal) {
val environmentChangeTracker = gradle.serviceOf<EnvironmentChangeTracker>()
write(environmentChangeTracker.getCachedState())
}
private
suspend fun DefaultReadContext.readCachedEnvironmentState(gradle: GradleInternal) {
val environmentChangeTracker = gradle.serviceOf<EnvironmentChangeTracker>()
val storedState = read() as EnvironmentChangeTracker.CachedEnvironmentState
environmentChangeTracker.loadFrom(storedState)
}
private
suspend fun DefaultWriteContext.writePreviewFlags(gradle: GradleInternal) {
val featureFlags = gradle.serviceOf<FeatureFlags>()
val enabledFeatures = FeaturePreviews.Feature.values().filter { featureFlags.isEnabledWithApi(it) }
writeCollection(enabledFeatures)
}
private
suspend fun DefaultReadContext.readPreviewFlags(gradle: GradleInternal) {
val featureFlags = gradle.serviceOf<FeatureFlags>()
readCollection {
val enabledFeature = read() as FeaturePreviews.Feature
featureFlags.enable(enabledFeature)
}
}
private
suspend fun DefaultWriteContext.writeGradleEnterprisePluginManager(gradle: GradleInternal) {
val manager = gradle.serviceOf<GradleEnterprisePluginManager>()
val adapter = manager.adapter
val writtenAdapter = adapter?.takeIf {
it.shouldSaveToConfigurationCache()
}
write(writtenAdapter)
}
private
suspend fun DefaultReadContext.readGradleEnterprisePluginManager(gradle: GradleInternal) {
val adapter = read() as GradleEnterprisePluginAdapter?
if (adapter != null) {
val manager = gradle.serviceOf<GradleEnterprisePluginManager>()
if (manager.adapter == null) {
// Don't replace the existing adapter. The adapter will be present if the current Gradle invocation wrote this entry.
adapter.onLoadFromConfigurationCache()
manager.registerAdapter(adapter)
}
}
}
private
fun getRelevantProjectsFor(nodes: List<Node>, relevantProjectsRegistry: RelevantProjectsRegistry): List<ProjectState> {
return fillTheGapsOf(relevantProjectsRegistry.relevantProjects(nodes))
}
private
fun Encoder.writeRelevantProjectRegistrations(relevantProjects: List<ProjectState>) {
writeCollection(relevantProjects) { project ->
writeProjectRegistration(project)
}
}
private
fun Decoder.readRelevantProjectRegistrations(build: ConfigurationCacheBuild) {
readCollection {
readProjectRegistration(build)
}
}
private
fun Encoder.writeProjectRegistration(project: ProjectState) {
val mutableModel = project.mutableModel
writeString(mutableModel.path)
writeFile(mutableModel.projectDir)
writeFile(mutableModel.layout.buildDirectory.apply { finalizeValue() }.get().asFile)
}
private
fun Decoder.readProjectRegistration(build: ConfigurationCacheBuild) {
val projectPath = readString()
val projectDir = readFile()
val buildDir = readFile()
build.createProject(projectPath, projectDir, buildDir)
}
private
fun stateFileFor(buildDefinition: BuildDefinition) =
stateFile.stateFileForIncludedBuild(buildDefinition)
private
val userTypesCodec
get() = codecs.userTypesCodec()
private
fun storedBuilds() = object : StoredBuilds {
val buildRootDirs = hashSetOf<File>()
override fun store(build: BuildDefinition): Boolean =
buildRootDirs.add(build.buildRootDir!!)
}
private
fun buildIdentifierOf(gradle: GradleInternal) =
gradle.owner.buildIdentifier
private
fun buildEventListenersOf(gradle: GradleInternal) =
gradle.serviceOf<BuildEventListenerRegistryInternal>()
.subscriptions
.filterIsInstance<RegisteredBuildServiceProvider<*, *>>()
.filter(::isRelevantBuildEventListener)
private
fun isRelevantBuildEventListener(provider: RegisteredBuildServiceProvider<*, *>) =
provider.buildIdentifier.name != BUILD_SRC
private
fun BuildStateRegistry.buildServiceRegistrationOf(buildId: BuildIdentifier) =
getBuild(buildId).mutableModel.serviceOf<BuildServiceRegistryInternal>().registrations
}
internal
class StoredBuildTreeState(
val storedBuilds: StoredBuilds,
val requiredBuildServicesPerBuild: Map<BuildIdentifier, List<BuildServiceProvider<*, *>>>
)
internal
interface StoredBuilds {
/**
* Returns true if this is the first time the given [build] is seen and its state should be stored to the cache.
* Returns false if the build has already been stored to the cache.
*/
fun store(build: BuildDefinition): Boolean
}
internal
fun fillTheGapsOf(projects: Collection<ProjectState>): List<ProjectState> {
val projectsWithoutGaps = ArrayList<ProjectState>(projects.size)
var index = 0
projects.forEach { project ->
var parent = project.parent
var added = 0
while (parent !== null && parent !in projectsWithoutGaps) {
projectsWithoutGaps.add(index, parent)
added += 1
parent = parent.parent
}
if (project !in projectsWithoutGaps) {
projectsWithoutGaps.add(project)
added += 1
}
index += added
}
return projectsWithoutGaps
}
| apache-2.0 | b7c1e4543fbab086e34fb7078c815e55 | 36.790667 | 199 | 0.684472 | 5.804424 | false | true | false | false |
egorich239/playground | kotlin/tracer.kt | 1 | 3922 | package rt
data class Vec3(val x: Double = 0.0, val y: Double = 0.0, val z: Double = 0.0) {
val norm: Double
get() = MathSqrt(x*x + y*y + z*z)
operator fun div(d: Double) = Vec3(x/d, y/d, z/d)
operator fun unaryMinus() = Vec3(-x, -y, -z)
operator fun plus(o: Vec3) = Vec3(x + o.x, y + o.y, z + o.z)
operator fun minus(o: Vec3) = this + (-o)
fun Normalize() = this / norm
infix fun CrossProduct(o: Vec3) = Vec3(
y * o.z - o.y * z,
z * o.x - o.z * x,
x * o.y - o.x * y)
infix fun DotProduct(o: Vec3) = x*o.x + y*o.y + z*o.z
}
operator fun Double.times(v: Vec3) = Vec3(this*v.x, this*v.y, this*v.z)
data class Ray(val origin: Vec3, val dir: Vec3)
interface Shape {
fun color(p: Vec3): Vec3
fun n(p: Vec3): Vec3
fun RayIntersect(ray: Ray): Double
}
data class Sphere(val center: Vec3, val r: Double, val color: Vec3) : Shape {
override fun color(p: Vec3) = color
override fun n(p: Vec3) = (p - center).Normalize()
override fun RayIntersect(ray: Ray): Double {
val a = center - ray.origin
val p = a DotProduct ray.dir
val d2 = (a DotProduct a) - p*p
val r2 = r*r
if (d2 > r2) return Double.NEGATIVE_INFINITY
val delta = MathSqrt(r2 - d2)
return if (p - delta > 0) p - delta else p + delta
}
}
const val EPS = 1e-6
data class Plane(val center: Vec3, val n: Vec3, val color: Vec3) : Shape {
private val n_ = n.Normalize()
private val x_ = GetP(n_)
private val y_ = n_ CrossProduct x_
override fun color(p: Vec3): Vec3 {
val dir = p - center
val xCoord = (dir DotProduct x_).toLong()
val yCoord = (dir DotProduct y_).toLong()
val xMod = if (xCoord > 0) xCoord % 100 - 50 else 50 + xCoord % 100
val yMod = if (yCoord > 0) yCoord % 100 - 50 else 50 + yCoord % 100
val pr = xMod * yMod
return if (pr < 0) color else 0.5*color
}
override fun n(p: Vec3) = n_
override fun RayIntersect(ray: Ray): Double {
val p1 = ray.dir DotProduct n_
val p2 = (ray.origin - center) DotProduct n_
return (
if (MathAbs(p2) < EPS) 0.0
else if (MathAbs(p1) < EPS) Double.POSITIVE_INFINITY
else -p2/p1)
}
companion object {
private fun GetP(n: Vec3) =
if (MathAbs(n.x) < EPS) Vec3(1.0, 0.0, 0.0)
else if (MathAbs(n.y) < EPS) Vec3(0.0, 1.0, 0.0)
else if (MathAbs(n.z) < EPS) Vec3(0.0, 0.0, 1.0)
else Vec3(-n.y, n.x, 0.0).Normalize()
}
}
const val BACKGROUND_RADIATION = 0.3
fun trace(ray: Ray, scene: List<Shape>, lightSource: Vec3): Vec3 {
var index = 0
var distance = Double.POSITIVE_INFINITY
for (t in 0..scene.size-1) {
val sd = scene[t].RayIntersect(ray)
if (0 <= sd && sd < distance) {
distance = sd
index = t
}
}
if (distance.isInfinite()) return Vec3(0.0, 0.0, 0.0)
val rPoint = ray.origin + distance * (1.0 - EPS) * ray.dir
val lightVec = lightSource - rPoint
val lightDistance = lightVec.norm
val lightDir = lightVec.Normalize()
distance = Double.POSITIVE_INFINITY
for (t in 0..scene.size-1) {
val sd = scene[t].RayIntersect(Ray(rPoint, lightDir))
if (sd >= 0.0 && sd < lightDistance) {
distance = sd
break
}
}
val bgColor = BACKGROUND_RADIATION * scene[index].color(rPoint)
if (!distance.isInfinite()) return bgColor
return bgColor + (1.0 - BACKGROUND_RADIATION) * MathAbs(lightDir DotProduct scene[index].n(rPoint)) * scene[index].color(rPoint)
}
fun render(width: Int, height: Int, cameraDepth : Double, lightSource: Vec3, scene: List<Shape>): Array<Vec3> {
var result = Array<Vec3>(4 * width * height) { Vec3() }
val camera = Vec3(0.0, 0.0, -cameraDepth)
for (x in -width..width-1) {
for (y in -height..height-1) {
val rayDir = (Vec3(x.toDouble(), y.toDouble(), 0.0) - camera).Normalize()
val color = trace(Ray(camera, rayDir), scene, lightSource)
result[(y + height) * 2 * width + (x + width)] = color
}
}
return result
}
| apache-2.0 | 29aa4d1535d5045c442a0323cf228cd8 | 29.169231 | 130 | 0.608363 | 2.835864 | false | false | false | false |
duftler/orca | orca-qos/src/main/kotlin/com/netflix/spinnaker/orca/qos/promotionpolicy/NaivePromotionPolicy.kt | 1 | 1671 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.qos.promotionpolicy
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.qos.PromotionPolicy
import com.netflix.spinnaker.orca.qos.PromotionResult
import org.springframework.stereotype.Component
@Component
class NaivePromotionPolicy(
private val configService: DynamicConfigService
) : PromotionPolicy {
override fun apply(candidates: List<Execution>): PromotionResult {
if (!configService.isEnabled("qos.promotion-policy.naive", true)) {
return PromotionResult(candidates, false, "Naive policy is disabled")
}
val maxPromoteSize = configService.getConfig(Int::class.java, "qos.promotion-policy.naive.size", 1)
val promoteSize = if (maxPromoteSize > candidates.size) candidates.size else maxPromoteSize
return PromotionResult(
candidates = candidates.subList(0, promoteSize),
finalized = false,
reason = "Naive policy promotes $maxPromoteSize execution every cycle"
)
}
}
| apache-2.0 | adcc814c39cb0cd200f457d3e997822e | 37.860465 | 103 | 0.764811 | 4.262755 | false | true | false | false |
AlekseyZhelo/LBM | CLISettings/src/main/kotlin/com/alekseyzhelo/lbm/cli/CLIUtil.kt | 1 | 1060 | package com.alekseyzhelo.lbm.cli
import com.beust.jcommander.JCommander
import com.beust.jcommander.ParameterException
/**
* @author Aleks on 29-05-2016.
*/
fun collectArguments(programName: String, args: Array<String>): CLISettings {
val cli = CLISettings()
val commander = JCommander(cli)
commander.setProgramName(programName)
try {
commander.parse(*args)
} catch (e: ParameterException) {
val builder = StringBuilder()
builder.appendln(e.message)
commander.usage(builder)
print(builder.toString())
System.exit(1)
} finally {
return cli
}
}
fun collectArguments(programName: String, parameters: Array<Any>, args: Array<String>) {
val commander = JCommander(parameters)
commander.setProgramName(programName)
try {
commander.parse(*args)
} catch (e: ParameterException) {
val builder = StringBuilder()
builder.appendln(e.message)
commander.usage(builder)
print(builder.toString())
System.exit(1)
}
}
| apache-2.0 | 0f79af9c7f1e49b99caaa53b160daa18 | 24.853659 | 88 | 0.660377 | 4.124514 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/Editor.kt | 1 | 2343 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor
import javafx.application.Application
import javafx.stage.Stage
import org.lwjgl.glfw.GLFW
import uk.co.nickthecoder.paratask.util.AutoExit
import uk.co.nickthecoder.tickle.Game
import uk.co.nickthecoder.tickle.editor.resources.DesignJsonResources
import uk.co.nickthecoder.tickle.graphics.Window
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.sound.SoundManager
import uk.co.nickthecoder.tickle.util.DelayedErrorHandler
import uk.co.nickthecoder.tickle.util.ErrorHandler
import java.io.File
class Editor : Application() {
lateinit var window: Window
override fun start(primaryStage: Stage) {
AutoExit.disable()
window = Window("Tickle Editor Hidden Window", 100, 100)
// MainWindow will handle any errors later, when it is created.
ErrorHandler.errorHandler = DelayedErrorHandler()
val json = DesignJsonResources(resourceFile!!)
val resources = if (resourceFile == null) Resources() else json.loadResources()
Game(window, resources)
println("Loaded resource, creating main window")
MainWindow(primaryStage, window)
}
override fun stop() {
println("Stopping JavaFX Application, deleting GL context")
window.delete()
SoundManager.cleanUp()
// Terminate GLFW and free the error callback
GLFW.glfwTerminate()
GLFW.glfwSetErrorCallback(null).free()
}
companion object {
var resourceFile: File? = null
fun start(file: File? = null) {
resourceFile = file
Application.launch(Editor::class.java)
}
}
}
| gpl-3.0 | 736a21de200bf2608d1f3fd0acdf9d30 | 31.09589 | 87 | 0.72898 | 4.471374 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/user/UserInfoActivity.kt | 1 | 9264 | package com.fuyoul.sanwenseller.ui.user
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.bean.reshttp.ResLoginInfoBean
import com.fuyoul.sanwenseller.configs.Code
import com.fuyoul.sanwenseller.configs.Data
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.utils.GlideUtils
import com.youquan.selector.Matisse
import kotlinx.android.synthetic.main.userinfolayout.*
import org.litepal.crud.DataSupport
import permissions.dispatcher.RuntimePermissions
import permissions.dispatcher.NeedsPermission
import android.Manifest
import android.annotation.SuppressLint
import android.text.TextUtils
import android.view.View
import com.fuyoul.sanwenseller.bean.others.MultDialogBean
import com.fuyoul.sanwenseller.helper.MsgDialogHelper
import com.fuyoul.sanwenseller.listener.KeyBordChangerListener
import com.fuyoul.sanwenseller.listener.MultDialogListener
import com.fuyoul.sanwenseller.structure.model.EditUserInfoM
import com.fuyoul.sanwenseller.structure.presenter.EditUserInfoP
import com.fuyoul.sanwenseller.structure.view.EditUserInfoV
import com.fuyoul.sanwenseller.utils.NormalFunUtils
import com.fuyoul.sanwenseller.utils.PhotoSelectUtils
import com.fuyoul.sanwenseller.widgets.pickerview.InitCityDataHelper
import permissions.dispatcher.PermissionRequest
import permissions.dispatcher.OnShowRationale
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.OnNeverAskAgain
/**
* @author: chen
* @CreatDate: 2017\10\28 0028
* @Desc:
*/
@RuntimePermissions
class UserInfoActivity : BaseActivity<EditUserInfoM, EditUserInfoV, EditUserInfoP>() {
private var photoUtils: PhotoSelectUtils = PhotoSelectUtils()
private val userInfo = DataSupport.findFirst(ResLoginInfoBean::class.java)
private var headPath: String? = ""
companion object {
fun start(activity: Activity) {
activity.startActivityForResult(Intent(activity, UserInfoActivity::class.java), Code.REQ_USERINFO)
}
}
override fun setLayoutRes(): Int = R.layout.userinfolayout
override fun initData(savedInstanceState: Bundle?) {
headPath = userInfo.avatar
GlideUtils.loadCircleImg(this, headPath, userHeadInfo, false, 0, R.mipmap.ic_my_wdltx, R.mipmap.ic_my_wdltx)
userNickInfo.text = userInfo.nickname
editExp.setText(userInfo.selfExp)
editDes.setText(userInfo.selfInfo)
if (userInfo.gender < 0 || userInfo.gender == Data.MAN) {
userSexInfo_Man.isChecked = true
} else {
userSexInfo_Woman.isChecked = true
}
if (TextUtils.isEmpty(userInfo.provinces) || TextUtils.isEmpty(userInfo.city)) {
userAddressInfo.text = "请选择地址"
} else {
userAddressInfo.text = "${userInfo.provinces}${userInfo.city}"
}
}
override fun setListener() {
registKeyBordListener(userInfoContent, editExp, object : KeyBordChangerListener {
override fun onShow(height: Int, srollHeight: Int) {
if (editExp.isFocused) {
userInfoContent.scrollBy(0, srollHeight + height)
} else if (editDes.isFocused) {
userInfoScroll.scrollBy(0, height)
}
}
override fun onHidden() {
if (editExp.isFocused) {
userInfoContent.scrollTo(0, 0)
} else if (editDes.isFocused) {
userInfoScroll.scrollTo(0, 0)
}
}
})
userAddressInfo.setOnClickListener {
NormalFunUtils.changeKeyBord(this, false, editExp)
NormalFunUtils.changeKeyBord(this, false, editDes)
InitCityDataHelper.getInstance().showAddress(this,
{ options1, options2, options3, v ->
val province = InitCityDataHelper.getInstance().city[options1].name
val city = InitCityDataHelper.getInstance().province[options1][options2]
val address = InitCityDataHelper.getInstance().address[options1][options2][options3]
userAddressInfo.text = "$province$city$address"
userInfo.provinces = province
userInfo.city = city
})
}
userNickInfo.setOnClickListener {
EditUserNickActivity.start(this, userNickInfo.text.toString())
}
if (userInfo.gender < 0) {//性别只能设置一次,如果之前没有设置过默认值为-1
userSexInfo.setOnCheckedChangeListener { radioGroup, i ->
when (i) {
R.id.userSexInfo_Man -> {
userInfo.gender = Data.MAN
userInfo.gender = Data.MAN
}
R.id.userSexInfo_Woman -> {
userInfo.gender = Data.WOMAN
userInfo.gender = Data.WOMAN
}
}
}
}
userHeadInfo.setOnClickListener {
initViewImpl().doSelectPic(this)
}
}
override fun getPresenter(): EditUserInfoP = EditUserInfoP(initViewImpl())
override fun initViewImpl(): EditUserInfoV = object : EditUserInfoV() {
override fun doSelectPic(activity: Activity) {
tackPicWithPermissionCheck(activity)
}
}
override fun initTopBar(): TopBarOption {
val op = TopBarOption()
op.isShowBar = true
op.mainTitle = "个人资料"
op.childTitle = "完成"
op.childTitleColor = R.color.color_3CC5BC
op.childListener = View.OnClickListener {
userInfo.avatar = headPath
userInfo.nickname = userNickInfo.text.toString()
userInfo.selfExp = editExp.text.toString()
userInfo.selfInfo = editDes.text.toString()
getPresenter().upInfo(this, userInfo)
}
return op
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK && Code.REQ_SELECTIMGS == requestCode) {
headPath = Matisse.obtainPathResult(data)[0]
GlideUtils.loadCircleImg(this, headPath, userHeadInfo)
} else if (Code.REQ_CAMERA == requestCode && resultCode == Activity.RESULT_OK) {
headPath = photoUtils.getCapturePath(this)
GlideUtils.loadCircleImg(this, headPath, userHeadInfo)
} else if (Code.REQ_EDITNICK == requestCode && resultCode == Activity.RESULT_OK) {
userInfo.nickname = data!!.getStringExtra("nick")
userNickInfo.text = userInfo.nickname
}
}
@NeedsPermission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun tackPic(activity: Activity) {
val multItem = ArrayList<MultDialogBean>()
val camera = MultDialogBean()
camera.title = "拍照获取"
multItem.add(camera)
val gallary = MultDialogBean()
gallary.title = "相册获取"
multItem.add(gallary)
MsgDialogHelper.showMultItemDialog(activity, multItem, "取消", object : MultDialogListener {
override fun onItemClicked(position: Int) {
when (position) {
0 -> {
photoUtils.doCapture(activity)
}
1 -> {
photoUtils.doSelect(activity, 1, null)
}
}
}
})
}
@SuppressLint("NeedOnRequestPermissionsResult")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
onRequestPermissionsResult(requestCode, grantResults)
}
@OnShowRationale(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun tackPicR(request: PermissionRequest) {
MsgDialogHelper.showNormalDialog(this, false, "温馨提示", "缺少必要权限,是否进行授权?", object : MsgDialogHelper.DialogListener {
override fun onPositive() {
request.proceed()
}
override fun onNagetive() {
request.cancel()
}
})
}
@OnPermissionDenied(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun tackPicD() {
NormalFunUtils.showToast(this, "缺少必要权限,请前往权限管理中心开启对应权限")
}
@OnNeverAskAgain(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
fun tackPicN() {
NormalFunUtils.showToast(this, "缺少必要权限,请前往权限管理中心开启对应权限")
}
} | apache-2.0 | e8a931eb7a35358b21f412604b890677 | 34.410156 | 138 | 0.648941 | 4.708571 | false | false | false | false |
Kotlin/anko | anko/library/generated/sdk15/src/main/java/Properties.kt | 4 | 6124 | @file:JvmName("Sdk15PropertiesKt")
package org.jetbrains.anko
import org.jetbrains.anko.*
import org.jetbrains.anko.internals.AnkoInternals
import kotlin.DeprecationLevel
var android.view.View.backgroundColor: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setBackgroundColor(v)
var android.view.View.backgroundResource: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setBackgroundResource(v)
var android.view.View.minimumHeight: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setMinimumHeight(v)
var android.view.View.minimumWidth: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setMinimumWidth(v)
var android.widget.TextView.textColor: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setTextColor(v)
var android.widget.TextView.highlightColor: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setHighlightColor(v)
var android.widget.TextView.hintTextColor: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setHintTextColor(v)
var android.widget.TextView.linkTextColor: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setLinkTextColor(v)
var android.widget.TextView.minLines: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setMinLines(v)
var android.widget.TextView.maxLines: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setMaxLines(v)
var android.widget.TextView.lines: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setLines(v)
var android.widget.TextView.minEms: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setMinEms(v)
var android.widget.TextView.maxEms: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setMaxEms(v)
var android.widget.TextView.singleLine: Boolean
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setSingleLine(v)
var android.widget.TextView.marqueeRepeatLimit: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setMarqueeRepeatLimit(v)
var android.widget.TextView.cursorVisible: Boolean
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setCursorVisible(v)
var android.widget.ImageView.imageResource: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setImageResource(v)
var android.widget.ImageView.imageURI: android.net.Uri?
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setImageURI(v)
var android.widget.ImageView.imageBitmap: android.graphics.Bitmap?
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setImageBitmap(v)
var android.widget.RelativeLayout.gravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setGravity(v)
var android.widget.RelativeLayout.horizontalGravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setHorizontalGravity(v)
var android.widget.RelativeLayout.verticalGravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setVerticalGravity(v)
var android.widget.LinearLayout.dividerDrawable: android.graphics.drawable.Drawable?
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setDividerDrawable(v)
var android.widget.LinearLayout.gravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setGravity(v)
var android.widget.LinearLayout.horizontalGravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setHorizontalGravity(v)
var android.widget.LinearLayout.verticalGravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setVerticalGravity(v)
var android.widget.Gallery.gravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setGravity(v)
var android.widget.Spinner.gravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setGravity(v)
var android.widget.GridView.gravity: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setGravity(v)
var android.widget.AbsListView.selectorResource: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setSelector(v)
var android.widget.TextView.hintResource: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setHint(v)
var android.widget.TextView.textResource: Int
@Deprecated(AnkoInternals.NO_GETTER, level = DeprecationLevel.ERROR) get() = AnkoInternals.noGetter()
set(v) = setText(v)
| apache-2.0 | 9c72c4b00673af55833735f971687e5f | 44.029412 | 105 | 0.758491 | 3.974043 | false | false | false | false |
hyst329/OpenFool | core/src/ru/hyst329/openfool/Holiday.kt | 1 | 529 | package ru.hyst329.openfool
import java.util.*
import java.util.Calendar.*
enum class Holiday {
OCTOBER_REVOLUTION,
NEW_YEAR
}
fun getCurrentHoliday(date: Calendar = Calendar.getInstance()): Holiday? {
val month = date.get(Calendar.MONTH)
val day = date.get(Calendar.DAY_OF_MONTH)
if (month == NOVEMBER && day in 5..10) {
return Holiday.OCTOBER_REVOLUTION
}
if (month == DECEMBER && day in 24..31 || month == JANUARY && day in 1..9) {
return Holiday.NEW_YEAR
}
return null
} | gpl-3.0 | 22ff4ebcb078b446258894b8c06f1ada | 24.238095 | 80 | 0.648393 | 3.457516 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/administration/RenameChannelCommand.kt | 1 | 3885 | package net.perfectdreams.loritta.morenitta.commands.vanilla.administration
import net.dv8tion.jda.api.Permission
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.commands.arguments
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase
import net.perfectdreams.loritta.morenitta.utils.Constants
class RenameChannelCommand(loritta: LorittaBot) : DiscordAbstractCommandBase(loritta, listOf("renamechannel", "renomearcanal"), net.perfectdreams.loritta.common.commands.CommandCategory.MODERATION) {
companion object {
private const val LOCALE_PREFIX = "commands.command"
}
override fun command() = create {
localizedDescription("$LOCALE_PREFIX.renamechannel.description")
localizedExamples("$LOCALE_PREFIX.renamechannel.examples")
usage {
arguments {
argument(ArgumentType.TEXT) {}
argument(ArgumentType.TEXT) {}
}
}
canUseInPrivateChannel = false
botRequiredPermissions = listOf(Permission.MANAGE_CHANNEL)
userRequiredPermissions = listOf(Permission.MANAGE_CHANNEL)
executesDiscord {
val context = this
if (context.args.isEmpty()) explainAndExit()
val textChannel = context.textChannel(0)
val voiceChannel = context.voiceChannel(0)
if (textChannel == null && voiceChannel == null) {
context.reply(
LorittaReply(
context.locale["$LOCALE_PREFIX.renamechannel.channelNotFound"],
Constants.ERROR
)
)
return@executesDiscord
}
val textChannelManager = textChannel?.manager
val voiceChannelManager = voiceChannel?.manager
val newNameArguments = args.drop(1)
val toRename = newNameArguments.joinToString(" ")
.trim()
.replace("(\\s\\|\\s|\\|)".toRegex(), "│")
.replace("(\\s&\\s|&)".toRegex(), "&")
.replace("[\\s]".toRegex(), "-")
try {
if (textChannel != null && voiceChannel == null) {
textChannelManager?.setName(toRename)?.queue()
context.reply(
LorittaReply(
context.locale["$LOCALE_PREFIX.renamechannel.successfullyRenamed"],
"\uD83C\uDF89"
)
)
} else if (voiceChannel != null && textChannel == null) {
voiceChannelManager?.setName(args.drop(1).joinToString(" ").trim())?.queue()
context.reply(
LorittaReply(
context.locale["$LOCALE_PREFIX.renamechannel.successfullyRenamed"],
"\uD83C\uDF89"
)
)
} else {
context.reply(
LorittaReply(
context.locale["$LOCALE_PREFIX.renamechannel.channelConflict"],
Constants.ERROR
)
)
}
} catch (e: Exception) {
context.reply(
LorittaReply(
locale["commands.command.renamechannel.cantRename"],
Constants.ERROR
)
)
}
}
}
}
| agpl-3.0 | 21e43c1f459ad5d1d7d902f17d0d9f95 | 39.852632 | 199 | 0.520742 | 6.045171 | false | false | false | false |
ericberman/MyFlightbookAndroid | app/src/main/java/com/myflightbook/android/CurrencyWidgetService.kt | 1 | 6506 | /*
MyFlightbook for Android - provides native access to MyFlightbook
pilot's logbook
Copyright (C) 2019-2022 MyFlightbook, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// This code adapted from https://android.googlesource.com/platform/development/+/master/samples/StackWidget/src/com/example/android/stackwidget/StackWidgetService.java
package com.myflightbook.android
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.SpannableString
import android.text.style.StyleSpan
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import android.widget.RemoteViewsService.RemoteViewsFactory
import com.myflightbook.android.webservices.AuthToken
import com.myflightbook.android.webservices.CurrencySvc
import model.CurrencyStatusItem
import model.MFBUtil.deserializeFromString
import model.MFBUtil.serializeToString
class CurrencyWidgetService : RemoteViewsService() {
override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
return CurrencyRemoteViewsFactory(this.applicationContext, intent)
}
}
internal class CurrencyRemoteViewsFactory(private val mContext: Context, intent: Intent?) :
RemoteViewsFactory {
private var mCurrencyItems: List<CurrencyStatusItem> = ArrayList()
override fun onCreate() {
// In onCreate() you setup any connections / cursors to your data source. Heavy lifting,
// for example downloading or creating content etc, should be deferred to onDataSetChanged()
// or getViewAt(). Taking more than 20 seconds in this call will result in an ANR.
val prefs = mContext.getSharedPreferences(prefCurrency, Activity.MODE_PRIVATE)
val szTotals = prefs.getString(prefCurrencyLast, null)
if (szTotals != null) {
val rgcsi = deserializeFromString<Array<CurrencyStatusItem>>(szTotals) ?: arrayOf()
mCurrencyItems = listOf(*rgcsi)
}
}
override fun onDestroy() {
// In onDestroy() you should tear down anything that was setup for your data source,
// eg. cursors, connections, etc.
mCurrencyItems = ArrayList()
}
override fun getCount(): Int {
return mCurrencyItems.size
}
override fun getViewAt(position: Int): RemoteViews {
// position will always range from 0 to getCount() - 1.
// We construct a remote views item based on our widget item xml file, and set the
// text based on the position.
val rv = RemoteViews(mContext.packageName, R.layout.widget_currency_item)
// Next, we set a fill-intent which will be used to fill-in the pending intent template
// which is set on the collection view in StackWidgetProvider.
val extras = Bundle()
val fillInIntent = Intent()
fillInIntent.putExtras(extras)
rv.setOnClickFillInIntent(R.id.layoutWidgetCurrencyItem, fillInIntent)
val csi = mCurrencyItems[position]
rv.setTextColor(R.id.txtCsiDiscrepancy, mContext.getColor(R.color.textColorPrimary))
rv.setTextColor(R.id.txtCsiAttribute, mContext.getColor(R.color.textColorPrimary))
rv.setTextViewText(R.id.txtCsiDiscrepancy, csi.discrepancy)
rv.setTextViewText(R.id.txtCsiAttribute, csi.attribute)
val value = SpannableString(csi.value)
when {
csi.status.compareTo("NotCurrent") == 0 -> {
rv.setTextColor(R.id.txtCsiValue, Color.RED)
value.setSpan(StyleSpan(Typeface.BOLD), 0, csi.value.length, 0)
}
csi.status.compareTo("GettingClose") == 0 -> {
rv.setTextColor(R.id.txtCsiValue, Color.argb(255, 0, 128, 255))
}
csi.status.compareTo("NoDate") == 0 -> {
value.setSpan(StyleSpan(Typeface.BOLD), 0, csi.value.length, 0)
rv.setTextColor(R.id.txtCsiValue, mContext.getColor(R.color.textColorPrimary))
}
else -> rv.setTextColor(R.id.txtCsiValue, mContext.getColor(R.color.currencyGreen))
}
rv.setTextViewText(R.id.txtCsiValue, value)
// Return the remote views object.
return rv
}
override fun getLoadingView(): RemoteViews? {
// You can create a custom loading view (for instance when getViewAt() is slow.) If you
// return null here, you will get the default loading view.
return null
}
override fun getViewTypeCount(): Int {
return 1
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun hasStableIds(): Boolean {
return true
}
override fun onDataSetChanged() {
// This is triggered when you call AppWidgetManager notifyAppWidgetViewDataChanged
// on the collection view corresponding to this factory. You can do heaving lifting in
// here, synchronously. For example, if you need to process an image, fetch something
// from the network, etc., it is ok to do it here, synchronously. The widget will remain
// in its current state while work is being done here, so you don't need to worry about
// locking up the widget.
if (AuthToken.m_szAuthToken == null || AuthToken.m_szAuthToken!!.isEmpty()) return
val cs = CurrencySvc()
val rgcsi = cs.getCurrencyForUser(AuthToken.m_szAuthToken, mContext)
mCurrencyItems = listOf(*rgcsi)
val prefs = mContext.getSharedPreferences(prefCurrency, Activity.MODE_PRIVATE)
val ed = prefs.edit()
ed.putString(prefCurrencyLast, serializeToString(rgcsi))
ed.apply()
}
companion object {
private const val prefCurrency = "prefCurrencyWidget"
private const val prefCurrencyLast = "prefCurrencyWidgetLast"
}
} | gpl-3.0 | 5ff90b0d3ecdeae29df6e3d7471931e7 | 43.265306 | 168 | 0.69874 | 4.755848 | false | false | false | false |
chrsep/Kingfish | app/src/main/java/com/directdev/portal/features/resources/ResourcesPresenter.kt | 1 | 2517 | package com.directdev.portal.features.resources
import com.directdev.portal.interactors.AuthInteractor
import com.directdev.portal.interactors.CourseInteractor
import com.directdev.portal.interactors.ResourceInteractor
import com.directdev.portal.interactors.TermInteractor
import com.directdev.portal.models.ResModel
import com.directdev.portal.utils.generateMessage
import io.reactivex.Single
import java.io.Serializable
import javax.inject.Inject
class ResourcesPresenter @Inject constructor(
private val termInteractor: TermInteractor,
private val courseInteractor: CourseInteractor,
private val resourceInteractor: ResourceInteractor,
private val authInteractor: AuthInteractor,
private val view: ResourcesContract.View
) : ResourcesContract.Presenter, Serializable {
private lateinit var courseNumbers: List<Int>
private var isSyncing = false
private var isStopped = false
override fun sync() {
if (!isSyncing)
authInteractor.execute().flatMap { cookie ->
Single.zip(courseNumbers.map {
resourceInteractor.sync(cookie, courseInteractor.getCourse(it))
}) {
// TODO: This empty funtion is bad, fix it
}
}.doOnSubscribe {
if (!isStopped) view.showLoading()
isSyncing = true
}.doFinally {
if (!isStopped) view.hideLoading()
isSyncing = false
}.subscribe({
view.showSuccess("Resources Successfully updated")
}, {
view.showFailed(it.generateMessage())
})
}
override fun onStart() {
if (isSyncing) view.showLoading()
isStopped = false
}
override fun onStop() {
isStopped = true
}
override fun getResources(classNumber: Int): ResModel? =
resourceInteractor.getResource(classNumber)
override fun getSemesters(): List<Pair<Int, String>> {
val terms = termInteractor.getTerms()
val semesterNames = terms.map {
termInteractor.getSemesterName(it)
}
return terms.zip(semesterNames)
}
override fun updateSelectedSemester(selectedTerm: Int) {
val courses = courseInteractor.getCourses(selectedTerm)
courseNumbers = courses.map { it.third }
view.updateCourses(courses.toList())
}
override fun getCourses(term: String): List<String> = mutableListOf()
} | gpl-3.0 | f76644e5f8ddf03d7bbc0b53af56d6be | 33.972222 | 83 | 0.654748 | 4.974308 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/widgets/BoostWidgetProvider.kt | 1 | 1339 | package com.androidvip.hebf.widgets
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import com.androidvip.hebf.R
class BoostWidgetProvider : AppWidgetProvider() {
override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
if (context == null) return
val remoteViews = RemoteViews(context.packageName, R.layout.widget_boost)
val active = Intent(context, BoostWidgetProvider::class.java)
active.action = ACTION_WIDGET_BOOST
val actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0)
remoteViews.setOnClickPendingIntent(R.id.boost_widget, actionPendingIntent)
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews)
}
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == ACTION_WIDGET_BOOST) {
val fs = Intent(context, WidgetBoost::class.java)
fs.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(fs)
} else {
super.onReceive(context, intent)
}
}
companion object {
var ACTION_WIDGET_BOOST = "boost"
}
}
| apache-2.0 | 61d6b270da67e58abc2a8aeb4e4bcf8a | 32.475 | 106 | 0.713219 | 4.649306 | false | false | false | false |
DataDozer/DataDozer | core/src/main/kotlin/org/datadozer/Validation.kt | 1 | 8121 | package org.datadozer
import org.datadozer.models.KeyValue
import org.datadozer.models.OperationMessage
import org.datadozer.models.OperationStatus
/*
* Licensed to DataDozer under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. DataDozer licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* An exception that is thrown to signify validation errors. This is more
* performant than standard exception as we have overridden the fillInStackTrace.
* In most of the validation exceptions we don't really care about the StackTrace.
*
* NOTE: After carefully considering various options like ResultType and error codes
* for control flow, I feel this is the best and easiest option. I also get the feeling
* that Java is designed to optimize the use of exceptions as I can't find any tryParse
* method in standard library.
*
* Some of the rationale behind this strategy comes from the following articles:
*
* https://shipilev.net/blog/2014/exceptional-performance/
* http://www.drmaciver.com/2009/03/exceptions-for-control-flow-considered-perfectly-acceptable-thanks-very-much/
*
*/
class OperationException(val operationMessage: OperationMessage) : Exception(operationMessage.message) {
@Synchronized
override fun fillInStackTrace(): Throwable {
return this
}
override fun toString(): String {
return operationMessage.toString()
}
override val message: String?
get() = operationMessage.toString()
}
/**
* Add a given key value pair to the operation message
*/
fun OperationMessage.Builder.addKeyValue(key: String, value: Any): OperationMessage.Builder {
this.addDetails(KeyValue.newBuilder().setKey(key).setValue(value.toString()).build())
return this
}
/**
* Sets the operation status to failure
*/
fun OperationMessage.Builder.setFailureStatus(): OperationMessage.Builder {
this.status = OperationStatus.FAILURE
return this
}
/**
* Sets the operation status to success
*/
fun OperationMessage.Builder.setSuccessStatus(): OperationMessage.Builder {
this.status = OperationStatus.SUCCESS
return this
}
/**
* Throws an [OperationException] with the result of calling [lazyMessage] if the [value] is false.
*/
inline fun check(value: Boolean, lazyMessage: () -> OperationMessage) {
if (!value) {
throw OperationException(lazyMessage())
}
}
/**
* Throws an [OperationException] with the result of calling [lazyMessage] if the [value] is null. Otherwise
* returns the not null value.
*/
inline fun <T : Any> checkNotNull(value: T?, lazyMessage: () -> OperationMessage): T {
if (value == null) {
val message = lazyMessage()
throw OperationException(message)
} else {
return value
}
}
/**
* Wrapper around general validation method which returns boolean instead of Exception
*/
fun tryValidate(validation: () -> Unit): Boolean {
return try {
validation()
true
} catch (e: OperationException) {
false
}
}
inline fun <T> tryParse(parser: (String) -> T, value: String, defaultValue: T): Pair<Boolean, T> {
return try {
val v = parser(value)
Pair(true, v)
} catch (e: OperationException) {
Pair(false, defaultValue)
}
}
inline fun <T> tryParseWith(parser: (String) -> T, value: String, defaultValue: T): T {
return try {
parser(value)
} catch (e: OperationException) {
defaultValue
}
}
fun <T : Comparable<T>> greaterThan(fieldName: String, lowerLimit: T, value: T) {
if (value <= lowerLimit) {
throw OperationException(
OperationMessage.newBuilder()
.setMessage("Field '$fieldName' must be greater than '$lowerLimit', but found '$value'.")
.addKeyValue(FIELD_NAME, fieldName)
.addKeyValue(LOWER_LIMIT, lowerLimit)
.addKeyValue(VALUE, value)
.setFailureStatus()
.build())
}
}
fun <T : Comparable<T>> greaterThanEqual(fieldName: String, lowerLimit: T, value: T) {
if (value < lowerLimit) {
throw OperationException(
OperationMessage.newBuilder()
.setMessage(
"Field '$fieldName' must be greater than or equal to '$lowerLimit', but found '$value'")
.addKeyValue(FIELD_NAME, fieldName)
.addKeyValue(LOWER_LIMIT, lowerLimit)
.addKeyValue(VALUE, value)
.setFailureStatus()
.build())
}
}
fun <T : Comparable<T>> lessThan(fieldName: String, upperLimit: T, value: T) {
if (value >= upperLimit) {
throw OperationException(
OperationMessage.newBuilder()
.setMessage("Field '$fieldName' must be less than '$upperLimit', but found '$value'")
.addKeyValue(FIELD_NAME, fieldName)
.addKeyValue(UPPER_LIMIT, upperLimit)
.addKeyValue(VALUE, value)
.setFailureStatus()
.build())
}
}
fun <T : Comparable<T>> lessThanEqual(fieldName: String, upperLimit: T, value: T) {
if (value > upperLimit) {
throw OperationException(
OperationMessage.newBuilder()
.setMessage(
"Field '$fieldName' must be less than or equal to '$upperLimit', but found '$value'")
.addKeyValue(FIELD_NAME, fieldName)
.addKeyValue(UPPER_LIMIT, upperLimit)
.addKeyValue(VALUE, value)
.setFailureStatus()
.build())
}
}
/**
* Checks if the given array has any duplicate values
*/
fun hasDuplicates(groupName: String, fieldName: String, input: Array<String>) {
if (input.count() != input.distinct().count()) {
throw OperationException(
OperationMessage.newBuilder()
.setMessage("A duplicate entry '$fieldName' has been found in the group '$groupName'")
.addKeyValue(FIELD_NAME, fieldName)
.addKeyValue(GROUP_NAME, groupName)
.setFailureStatus()
.build())
}
}
/**
* Checks if the given string is null or empty
*/
fun notBlank(fieldName: String, value: String) {
if (value.isBlank()) {
throw OperationException(OperationMessage.newBuilder()
.setMessage("Field '$fieldName' must not be blank.")
.addKeyValue(FIELD_NAME, fieldName)
.setFailureStatus()
.build())
}
}
private val regex = Regex("^[a-z0-9_]*\$")
/**
* Validates if the fields name satisfies the naming rules
*/
fun isPropertyName(fieldName: String, value: String) {
if (!regex.containsMatchIn(value)) {
throw OperationException(
OperationMessage.newBuilder()
.setMessage(
"Name is invalid for fields '$fieldName'. A property name can only contain 'a-z', '0-9' and '_' characters.")
.addKeyValue(FIELD_NAME, fieldName)
.setFailureStatus()
.build())
}
} | apache-2.0 | 86e62a2f7a7b0a8db668f4f582719787 | 34.622807 | 141 | 0.609531 | 4.833929 | false | false | false | false |
jsargent7089/android | src/main/java/com/nextcloud/client/etm/EtmViewModel.kt | 1 | 5830 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2020 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.etm
import android.accounts.Account
import android.accounts.AccountManager
import android.content.SharedPreferences
import android.content.res.Resources
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.nextcloud.client.etm.pages.EtmAccountsFragment
import com.nextcloud.client.etm.pages.EtmBackgroundJobsFragment
import com.nextcloud.client.etm.pages.EtmMigrations
import com.nextcloud.client.etm.pages.EtmPreferencesFragment
import com.nextcloud.client.jobs.BackgroundJobManager
import com.nextcloud.client.jobs.JobInfo
import com.nextcloud.client.migrations.MigrationInfo
import com.nextcloud.client.migrations.MigrationsDb
import com.nextcloud.client.migrations.MigrationsManager
import com.owncloud.android.R
import com.owncloud.android.lib.common.accounts.AccountUtils
import javax.inject.Inject
@Suppress("LongParameterList") // Dependencies Injection
class EtmViewModel @Inject constructor(
private val defaultPreferences: SharedPreferences,
private val platformAccountManager: AccountManager,
private val resources: Resources,
private val backgroundJobManager: BackgroundJobManager,
private val migrationsManager: MigrationsManager,
private val migrationsDb: MigrationsDb
) : ViewModel() {
companion object {
val ACCOUNT_USER_DATA_KEYS = listOf(
// AccountUtils.Constants.KEY_COOKIES, is disabled
AccountUtils.Constants.KEY_DISPLAY_NAME,
AccountUtils.Constants.KEY_OC_ACCOUNT_VERSION,
AccountUtils.Constants.KEY_OC_BASE_URL,
AccountUtils.Constants.KEY_OC_VERSION,
AccountUtils.Constants.KEY_USER_ID
)
const val PAGE_SETTINGS = 0
const val PAGE_ACCOUNTS = 1
const val PAGE_JOBS = 2
const val PAGE_MIGRATIONS = 3
}
/**
* This data class holds all relevant account information that is
* otherwise kept in separate collections.
*/
data class AccountData(val account: Account, val userData: Map<String, String?>)
val currentPage: LiveData<EtmMenuEntry?> = MutableLiveData()
val pages: List<EtmMenuEntry> = listOf(
EtmMenuEntry(
iconRes = R.drawable.ic_settings,
titleRes = R.string.etm_preferences,
pageClass = EtmPreferencesFragment::class
),
EtmMenuEntry(
iconRes = R.drawable.ic_user,
titleRes = R.string.etm_accounts,
pageClass = EtmAccountsFragment::class
),
EtmMenuEntry(
iconRes = R.drawable.ic_clock,
titleRes = R.string.etm_background_jobs,
pageClass = EtmBackgroundJobsFragment::class
),
EtmMenuEntry(
iconRes = R.drawable.ic_arrow_up,
titleRes = R.string.etm_migrations,
pageClass = EtmMigrations::class
)
)
val preferences: Map<String, String> get() {
return defaultPreferences.all
.map { it.key to "${it.value}" }
.sortedBy { it.first }
.toMap()
}
val accounts: List<AccountData> get() {
val accountType = resources.getString(R.string.account_type)
return platformAccountManager.getAccountsByType(accountType).map { account ->
val userData: Map<String, String?> = ACCOUNT_USER_DATA_KEYS.map { key ->
key to platformAccountManager.getUserData(account, key)
}.toMap()
AccountData(account, userData)
}
}
val backgroundJobs: LiveData<List<JobInfo>> get() {
return backgroundJobManager.jobs
}
val migrationsInfo: List<MigrationInfo> get() {
return migrationsManager.info
}
val migrationsStatus: MigrationsManager.Status get() {
return migrationsManager.status.value ?: MigrationsManager.Status.UNKNOWN
}
val lastMigratedVersion: Int get() {
return migrationsDb.lastMigratedVersion
}
init {
(currentPage as MutableLiveData).apply {
value = null
}
}
fun onPageSelected(index: Int) {
if (index < pages.size) {
currentPage as MutableLiveData
currentPage.value = pages[index]
}
}
fun onBackPressed(): Boolean {
(currentPage as MutableLiveData)
return if (currentPage.value != null) {
currentPage.value = null
true
} else {
false
}
}
fun pruneJobs() {
backgroundJobManager.pruneJobs()
}
fun cancelAllJobs() {
backgroundJobManager.cancelAllJobs()
}
fun startTestJob(periodic: Boolean) {
if (periodic) {
backgroundJobManager.scheduleTestJob()
} else {
backgroundJobManager.startImmediateTestJob()
}
}
fun cancelTestJob() {
backgroundJobManager.cancelTestJob()
}
fun clearMigrations() {
migrationsDb.clearMigrations()
}
}
| gpl-2.0 | dded98aa91da7472d9ae41f02a07b76f | 31.937853 | 85 | 0.674271 | 4.751426 | false | false | false | false |
JackParisi/DroidBox | droidbox/src/main/java/com/github/giacomoparisi/droidbox/recycler/DroidAdapter.kt | 1 | 2222 | package com.github.giacomoparisi.droidbox.recycler
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.github.giacomoparisi.droidbox.architecture.model.DroidViewModel
/**
* Created by Giacomo Parisi on 07/07/2017.
* https://github.com/giacomoParisi
*/
/**
*
* The recyclerView.Adapter that populate the recyclerView with DroidItems
* and bind them with the data.
* The adapter support the following features:
*
* - Android data binding
* - Different DroidItem (with different DroidViewHolder.Factory)
*
* @param itemList The list of DroidItem for populate the recyclerView
* @param layoutInflater The layoutInflater reference for layout inflating
* @param viewModel The viewModel of the view that hold the recyclerView
*/
open class DroidAdapter(
private var itemList: List<DroidItem>,
private val layoutInflater: LayoutInflater,
private val viewModel: DroidViewModel? = null)
: androidx.recyclerview.widget.RecyclerView.Adapter<DroidViewHolder<*>>() {
// Map of the all DroidViewHolder.Factory for the different DroidItems
private var viewHolderMap: MutableMap<Int, DroidViewHolder.Factory<*,*>> = mutableMapOf()
override fun onBindViewHolder(holder: DroidViewHolder<*>, position: Int) {
holder.globalPosition.set(position)
holder.bind(itemList[position])
holder.binding.executePendingBindings()
}
override fun getItemCount(): Int {
return itemList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DroidViewHolder<*> {
val viewHolder = viewHolderMap[viewType]!!.create(layoutInflater, parent)
viewModel.let { viewHolder.viewModel = viewModel}
return viewHolder
}
override fun getItemViewType(position: Int): Int {
val viewHolderlayoutId = itemList[position].getItemViewHolder().layoutId
for ((key, value) in viewHolderMap) {
if (value.layoutId == viewHolderlayoutId) {
return key
}
}
viewHolderMap[viewHolderMap.size + 1] = itemList[position].getItemViewHolder()
return viewHolderMap.size
}
}
| apache-2.0 | 6f69754aefbee66a0a7038f4f390a090 | 33.71875 | 93 | 0.718272 | 5.004505 | false | false | false | false |
avenwu/jk-address-book | android/app/src/main/kotlin/com/jikexueyuan/mobile/address/api/AppService.kt | 1 | 4834 | package com.jikexueyuan.mobile.address.api
import android.os.AsyncTask
import android.support.v4.os.AsyncTaskCompat
import android.text.TextUtils
import com.jikexueyuan.mobile.address.bean.AddressBook
import com.jikexueyuan.mobile.address.bean.User
import com.jikexueyuan.mobile.address.chinese2Pinyin
import com.squareup.okhttp.OkHttpClient
import org.jsoup.Jsoup
import org.jsoup.select.Elements
import retrofit.Retrofit
import java.io.IOException
import java.net.CookieHandler
import java.net.CookieManager
import java.net.CookiePolicy
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Created by aven on 10/22/15.
*/
object AppService {
private val api: API
public val PAGE_COUNT = 20
init {
val cookieManager = CookieManager()
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL)
CookieHandler.setDefault(cookieManager)
val client = OkHttpClient()
client.setConnectTimeout((client.connectTimeout * 2).toLong(), TimeUnit.MILLISECONDS)
client.setReadTimeout((client.readTimeout * 2).toLong(), TimeUnit.MILLISECONDS)
api = Retrofit.Builder().baseUrl("http://work.eoemobile.com")
.addConverterFactory(StringConvertFactory())
.client(client)
.build()
.create(API::class.java)
}
fun getAddressBookByPage(pageIndex: Int, listener: (AddressBook) -> Unit): AsyncTask<*, *, *> {
return AsyncTaskCompat.executeParallel(object : AsyncTask<Int, Void, AddressBook>() {
override fun doInBackground(vararg params: Int?): AddressBook? {
var page = params[0] ?: 0
var result: AddressBook
try {
val call = api.addressBooks(page, PAGE_COUNT)
val response = call.execute()
//User Info
val document = Jsoup.parse(response.body(), "UTF-8")
val userTable = document.select("div table tbody tr")
val userList = ArrayList<User>()
for (index in userTable.indices) {
try {
userList.add(parseUser(userTable, index))
} catch(e: Throwable) {
e.printStackTrace()
}
}
val pages = document.select("p.pagination span.items").first().text()
val totalCount = pages.substring(pages.lastIndexOf("/") + 1, pages.lastIndexOf(")"))
result = AddressBook(userList, Integer.parseInt(totalCount), page)
} catch (e: Throwable) {
e.printStackTrace()
result = AddressBook(null, 0, page)
}
return result
}
private fun parseUser(elements: Elements, index: Int): User {
val td = elements[index].select("td")
val username = td.first().select("a").text()
val email = td[1].select("a").text()
val phone = td[2].text()
val qq = td[3].text()
val wechat = td[4].text()
var pinyin = chinese2Pinyin(username.trim())
return User(username.trim(), email, phone, qq, wechat, pinyin)
}
override fun onPostExecute(addressBook: AddressBook) {
super.onPostExecute(addressBook)
listener(addressBook)
}
}, pageIndex)
}
fun login(name: String, pwd: String, listener: (Boolean) -> Unit): AsyncTask<*, *, *> {
return AsyncTaskCompat.executeParallel(object : AsyncTask<String, Void, Boolean>() {
override fun doInBackground(vararg params: String): Boolean? {
var login: Boolean
try {
//准备登陆数据
var call = api.loginPageHtml()
var response = call.execute()
val document = Jsoup.parse(response.body(), "UTF-8")
val content = document.select("meta[name=csrf-token]").first().attr("content")
// 登陆账号
call = api.login("✓", content, params[0], params[1], "Login »")
response = call.execute()
login = response.code() == 200 && !TextUtils.isEmpty(response.headers().get("Set-Cookie"))
} catch (e: Throwable) {
e.printStackTrace()
login = false
}
return login
}
override fun onPostExecute(aBoolean: Boolean) {
super.onPostExecute(aBoolean)
listener(aBoolean)
}
}, name, pwd)
}
}
| apache-2.0 | 5734c431a98a767bcce789bf1aa6318b | 38.113821 | 110 | 0.550405 | 4.929303 | false | false | false | false |
lanhuaguizha/Christian | app/src/main/java/com/christian/nav/me/MeFragment.kt | 1 | 5071 | package com.christian.nav.me
import android.content.Context
import android.os.Bundle
import android.view.*
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.ViewPager
import com.christian.R
import com.christian.common.CommonApp
import com.christian.nav.NavActivity
import com.christian.nav.NavContract
import com.christian.nav.me.MeChildFragment
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.fragment_home.view.*
import kotlinx.android.synthetic.main.fragment_me.*
import kotlinx.android.synthetic.main.fragment_me.view.*
import kotlinx.android.synthetic.main.fragment_nav_rv.*
import kotlinx.android.synthetic.main.nav_activity.*
open class MeFragment : androidx.fragment.app.Fragment(), NavContract.INavFragment {
lateinit var navChildFragmentPagerAdapter: NavChildFragmentPagerAdapter
override fun onSaveInstanceState(outState: Bundle) {
}
lateinit var navActivity: NavActivity
private lateinit var ctx: Context
lateinit var v: View
var navId = -1
lateinit var gospelId: String
/**
* It is the first place application code can run where the fragment is ready to be used
*/
override fun onAttach(context: Context) {
super.onAttach(context)
navActivity = context as NavActivity
ctx = context
}
private var isInitView = false
private var isVisibled = false
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//包含菜单到所在Activity
// setHasOptionsMenu(true)
v = inflater.inflate(R.layout.fragment_me, container, false)
// isInitView = true
// isCanLoadData()
initView()
return v
}
// override fun setUserVisibleHint(isVisibleToUser: Boolean) {
// super.setUserVisibleHint(isVisibleToUser)
//
// //isVisibleToUser这个boolean值表示:该Fragment的UI 用户是否可见,获取该标志记录下来
// if (isVisibleToUser) {
// isVisibled = true
// isCanLoadData()
// } else {
// isVisibled = false
// }
// }
//
// private fun isCanLoadData() {
// //所以条件是view初始化完成并且对用户可见
// if (isInitView && isVisibled) {
// initView()
//
// //防止重复加载数据
// isInitView = false
// isVisibled = false
// }
// }
override fun initView() {
val tabTitleList: ArrayList<String> = arrayListOf(
CommonApp.context.getString(R.string.tab_gospel),
CommonApp.context.getString(R.string.tab_disciple),
)
initVp(tabTitleList)
}
private lateinit var navFragment: MeChildFragment
private var pageSelectedPosition: Int = -1
private fun initVp(tabTitleList: ArrayList<String>) {
v.vp_me.viewPager = navActivity.vp_nav
navChildFragmentPagerAdapter = NavChildFragmentPagerAdapter(
childFragmentManager, tabTitleList,
)
v.vp_me.adapter = navChildFragmentPagerAdapter
navActivity.tl_me.setupWithViewPager(v.vp_me)//将TabLayout和ViewPager关联起来
v.vp_me.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
pageSelectedPosition = position
navFragment = navChildFragmentPagerAdapter.currentFragment
}
override fun onPageScrollStateChanged(state: Int) {
}
})
}
class NavChildFragmentPagerAdapter(
fm: FragmentManager,
private val tabTitleList: ArrayList<String>,
) : androidx.fragment.app.FragmentStatePagerAdapter(fm) {
lateinit var currentFragment: MeChildFragment
override fun getItem(position: Int): androidx.fragment.app.Fragment {
val navFragment = MeChildFragment()
navFragment.navId = position
return navFragment
}
override fun getCount(): Int {
return tabTitleList.size
}
override fun getPageTitle(position: Int): CharSequence {
return tabTitleList[position]
}
override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) {
currentFragment = `object` as MeChildFragment
super.setPrimaryItem(container, position, `object`)
}
}
fun scrollChildRVToTop() {
if ((navActivity.navFragmentPagerAdapter.currentFragment as MeFragment)::navChildFragmentPagerAdapter.isInitialized) {
(navActivity.navFragmentPagerAdapter.currentFragment as MeFragment).navChildFragmentPagerAdapter.currentFragment.fragment_nav_rv.smoothScrollToPosition(0) // 为了滚到顶
}
}
}
| gpl-3.0 | 1f30ed0677dccb379698fe7303c0604a | 30.660256 | 175 | 0.66147 | 4.776596 | false | false | false | false |
mikegehard/kotlinArchiveChannel | src/main/kotlin/io/github/mikegehard/slack/archive.kt | 1 | 2515 | package io.github.mikegehard.slack
import io.github.mikegehard.slack.timeExtensions.daysAgo
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
fun archiveChannels(host: SlackHost, minimumMembers: Int, archiveMessage: String?) =
getActiveChannels(host)
.filter { it.hasLessThan(minimumMembers) }
.forEach { archive(host, it, archiveMessage) }
fun archiveStaleChannels(host: SlackHost, daysSinceLastMessage: Long, archiveMessage: String?) =
getActiveChannels(host)
.withAdditionalInformation(host)
.filter { it.staleAsOf(daysSinceLastMessage.daysAgo()) }
.forEach { archive(host, it, archiveMessage) }
private fun archive(host: SlackHost, channel: SlackChannel, message: String?) {
message?.let { postChat(host, channel, it) }
archive(host, channel)
}
private fun List<SlackChannel>.withAdditionalInformation(host: SlackHost): List<SlackChannel> =
this.map { getChannelInfo(host, it) }
private fun getChannelInfo(host: SlackHost, channel: SlackChannel): SlackChannel {
val url = host.url {
addQueryParameter("channel", channel.id)
addPathSegment("channels.info")
}
val request = Request.Builder().url(url).build()
return channelFrom(execute(request).body().string())
}
private fun postChat(host: SlackHost, channel: SlackChannel, message: String) {
val url = host.url {
addQueryParameter("channel", channel.id)
addQueryParameter("text", message)
addPathSegment("chat.postMessage")
}
val request = Request.Builder().url(url).build()
// need to log some sort of message if this fails so I can see why??
execute(request)
}
private fun archive(host: SlackHost, channel: SlackChannel) {
val url = host.url {
addQueryParameter("channel", channel.id)
addPathSegment("channels.archive")
}
val request = Request.Builder().url(url).build()
// need to log some sort of message if this fails so I can see why??
execute(request)
}
private fun getActiveChannels(host: SlackHost): List<SlackChannel> {
val url = host.url {
addPathSegment("channels.list")
addQueryParameter("exclude_archived", "1")
}
val request = Request.Builder().url(url).build()
// what happens if this fails??
return channelsFrom(execute(request).body().string())
}
private fun execute(request: Request): Response = OkHttpClient().newCall(request).execute()
| mit | b0b6ab18db69ffdfb5d6ad119f3315d1 | 32.092105 | 96 | 0.687475 | 4.255499 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/uber/UberAuthInterceptor.kt | 1 | 3135 | package com.baulsupp.okurl.services.uber
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.Oauth2AuthInterceptor
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.authenticator.oauth2.Oauth2ServiceDefinition
import com.baulsupp.okurl.authenticator.oauth2.Oauth2Token
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.BaseUrlCompleter
import com.baulsupp.okurl.completion.CompletionVariableCache
import com.baulsupp.okurl.completion.UrlList
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.credentials.NoToken
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.queryMap
import com.baulsupp.okurl.kotlin.requestBuilder
import com.baulsupp.okurl.secrets.Secrets
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Response
class UberAuthInterceptor : Oauth2AuthInterceptor() {
override val serviceDefinition =
Oauth2ServiceDefinition(
"api.uber.com", "Uber API", "uber",
"https://developer.uber.com/docs/riders/references/api",
"https://developer.uber.com/dashboard/"
)
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): Oauth2Token {
val clientId = Secrets.prompt("Uber Client Id", "uber.clientId", "", false)
val clientSecret = Secrets.prompt("Uber Client Secret", "uber.clientSecret", "", true)
return UberAuthFlow.login(client, outputHandler, clientId, clientSecret)
}
override suspend fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
return BaseUrlCompleter(UrlList.fromResource(name())!!, hosts(credentialsStore), completionVariableCache)
}
override suspend fun validate(
client: OkHttpClient,
credentials: Oauth2Token
): ValidatedCredentials {
val map = client.queryMap<Any>(
"https://api.uber.com/v1/me",
TokenValue(credentials)
)
return ValidatedCredentials("${map["first_name"]} ${map["last_name"]}")
}
override fun hosts(credentialsStore: CredentialsStore): Set<String> =
setOf("api.uber.com", "login.uber.com", "sandbox-api.uber.com")
override suspend fun renew(client: OkHttpClient, credentials: Oauth2Token): Oauth2Token? {
val tokenUrl = "https://login.uber.com/oauth/v2/token"
val body = FormBody.Builder().add("client_id", credentials.clientId!!)
.add("client_secret", credentials.clientSecret!!)
.add("refresh_token", credentials.refreshToken!!)
.add("grant_type", "refresh_token")
.build()
val request = requestBuilder(tokenUrl, NoToken).method("POST", body).build()
val responseMap = client.queryMap<Any>(request)
return Oauth2Token(
responseMap["access_token"] as String,
responseMap["refresh_token"] as String, credentials.clientId,
credentials.clientSecret
)
}
}
| apache-2.0 | 8e7c3ade39a361f0528209fb098fafed | 35.453488 | 109 | 0.754067 | 4.360223 | false | false | false | false |
k0shk0sh/FastHub | app/src/main/java/com/fastaccess/ui/modules/main/donation/DonateActivity.kt | 1 | 5564 | package com.fastaccess.ui.modules.main.donation
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.fastaccess.BuildConfig
import com.fastaccess.R
import com.fastaccess.helper.*
import com.fastaccess.provider.fabric.FabricProvider
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.base.mvp.BaseMvp
import com.fastaccess.ui.base.mvp.presenter.BasePresenter
import com.miguelbcr.io.rx_billing_service.RxBillingService
import com.miguelbcr.io.rx_billing_service.RxBillingServiceError
import com.miguelbcr.io.rx_billing_service.RxBillingServiceException
import com.miguelbcr.io.rx_billing_service.entities.ProductType
import com.miguelbcr.io.rx_billing_service.entities.Purchase
import io.reactivex.disposables.Disposable
/**
* Created by Kosh on 10 Jun 2017, 1:04 PM
*/
class DonateActivity : BaseActivity<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() {
private var subscription: Disposable? = null
override fun layout(): Int = 0
override fun isTransparent(): Boolean = true
override fun canBack(): Boolean = false
override fun isSecured(): Boolean = true
override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val bundle: Bundle? = intent?.extras
val productKey = bundle?.getString(BundleConstant.EXTRA)
val price = bundle?.getLong(BundleConstant.EXTRA_FOUR, 0)
val priceText = bundle?.getString(BundleConstant.EXTRA_FIVE)
subscription = RxHelper.getSingle<Purchase>(
RxBillingService.getInstance(this, BuildConfig.DEBUG)
.purchase(ProductType.IN_APP, productKey, "inapp:com.fastaccess.github:$productKey")
)
.subscribe { _: Purchase?, throwable: Throwable? ->
if (throwable == null) {
FabricProvider.logPurchase(productKey, price, priceText)
showMessage(R.string.success, R.string.success_purchase_message)
enableProduct(productKey, applicationContext)
val intent = Intent()
intent.putExtra(BundleConstant.ITEM, productKey)
setResult(Activity.RESULT_OK, intent)
} else {
if (throwable is RxBillingServiceException) {
val code = throwable.code
if (code == RxBillingServiceError.ITEM_ALREADY_OWNED) {
enableProduct(productKey, applicationContext)
val intent = Intent()
intent.putExtra(BundleConstant.ITEM, productKey)
setResult(Activity.RESULT_OK, intent)
} else {
showErrorMessage(throwable.message!!)
Logger.e(code)
setResult(Activity.RESULT_CANCELED)
}
}
throwable.printStackTrace()
}
finish()
}
}
override fun onDestroy() {
subscription?.let { if (!it.isDisposed) it.dispose() }
super.onDestroy()
}
companion object {
fun start(context: Activity, product: String?, price: Long? = 0, priceText: String? = null) {
val intent = Intent(context, DonateActivity::class.java)
intent.putExtras(
Bundler.start()
.put(BundleConstant.EXTRA, product)
.put(BundleConstant.EXTRA_FOUR, price)
.put(BundleConstant.EXTRA_FIVE, priceText)
.end()
)
context.startActivityForResult(intent, BundleConstant.REQUEST_CODE)
}
fun start(context: Fragment, product: String?, price: Long? = 0, priceText: String? = null) {
val intent = Intent(context.context, DonateActivity::class.java)
intent.putExtras(
Bundler.start()
.put(BundleConstant.EXTRA, product)
.put(BundleConstant.EXTRA_FOUR, price)
.put(BundleConstant.EXTRA_FIVE, priceText)
.end()
)
context.startActivityForResult(intent, BundleConstant.REQUEST_CODE)
}
fun enableProduct(productKey: String?, context: Context) {
when (productKey) {
context.getString(R.string.donation_product_3), context.getString(R.string.donation_product_4),
context.getString(R.string.fasthub_all_features_purchase) -> {
PrefGetter.setProItems()
PrefGetter.setEnterpriseItem()
}
context.getString(R.string.donation_product_2), context.getString(R.string.fasthub_pro_purchase) -> PrefGetter.setProItems()
context.getString(R.string.fasthub_enterprise_purchase) -> PrefGetter.setEnterpriseItem()
context.getString(R.string.donation_product_1), context.getString(R.string.amlod_theme_purchase) -> PrefGetter.enableAmlodTheme()
context.getString(R.string.midnight_blue_theme_purchase) -> PrefGetter.enableMidNightBlueTheme()
context.getString(R.string.theme_bluish_purchase) -> PrefGetter.enableBluishTheme()
else -> Logger.e(productKey)
}
}
}
} | gpl-3.0 | 836e63b2fef033f8e406ce0b08acfab0 | 43.52 | 145 | 0.61826 | 4.9812 | false | false | false | false |
ysl3000/PathfindergoalAPI | PathfinderAPI/src/main/java/com/github/ysl3000/bukkit/pathfinding/goals/notworking/PathfinderGoalWalkToSteakAndEat.kt | 1 | 2637 | package com.github.ysl3000.bukkit.pathfinding.goals.notworking
import com.github.ysl3000.bukkit.pathfinding.entity.Insentient
import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderGoal
import org.bukkit.entity.Entity
import org.bukkit.entity.EntityType
import org.bukkit.entity.Item
import org.bukkit.entity.LivingEntity
import java.util.*
/**
* Created by ysl3000 on 09.12.16. todo check if working else update
*/
class PathfinderGoalWalkToSteakAndEat(private val pathfinderGoalEntity: Insentient, private val distance: Double) : PathfinderGoal {
private var target: Entity? = null
private val distanceComperator: DistanceComperator
init {
this.distanceComperator = DistanceComperator()
}
override fun shouldExecute(): Boolean {
return target != null && !target!!.isDead && distanceComperator.getDistance(target!!) > 0
}
/**
* Whether the goal should Terminate
*
* @return true if should terminate
*/
override fun shouldTerminate(): Boolean {
return target == null || target!!.isDead
}
/**
* Runs initially and should be used to setUp goalEnvironment Condition needs to be defined thus
* your code in it isn't called
*/
override fun init() {
val nearestStack = pathfinderGoalEntity.getBukkitEntity()
.getNearbyEntities(distance, distance, distance).stream()
.filter { e -> e.type == EntityType.DROPPED_ITEM }.min(distanceComperator)
nearestStack.ifPresent { entity -> target = entity }
}
/**
* Is called when [.shouldExecute] returns true
*/
override fun execute() {
pathfinderGoalEntity.getNavigation().moveTo(target!!, 2.0)
pathfinderGoalEntity.jump()
}
override fun reset() {
this.pathfinderGoalEntity.getNavigation().clearPathEntity()
if (this.target != null && this.target is Item) {
val buEntity = this.pathfinderGoalEntity.getBukkitEntity()
if (buEntity is LivingEntity) {
buEntity.equipment?.setItemInMainHand((this.target as Item).itemStack)
}
this.target!!.remove()
this.target = null
}
}
private inner class DistanceComperator : Comparator<Entity> {
override fun compare(o1: Entity, o2: Entity): Int {
return java.lang.Double.compare(getDistance(o1), getDistance(o2))
}
fun getDistance(entity: Entity): Double {
return entity.location
.distanceSquared(pathfinderGoalEntity.getBukkitEntity().location)
}
}
} | mit | 84c4ee1cf9d85f6f8f8db35d0d5a4577 | 30.035294 | 132 | 0.660978 | 4.812044 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/telemetry/TelemetrySettingsProvider.kt | 1 | 2719 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@file:Suppress("DEPRECATION")
package org.mozilla.focus.telemetry
import android.content.Context
import mozilla.components.browser.state.search.SearchEngine
import mozilla.components.browser.state.state.selectedOrDefaultSearchEngine
import mozilla.components.support.utils.Browsers
import org.mozilla.focus.R
import org.mozilla.focus.ext.components
import org.mozilla.telemetry.TelemetryHolder
import org.mozilla.telemetry.measurement.SettingsMeasurement
/**
* SharedPreferenceSettingsProvider implementation that additionally injects settings value for
* runtime preferences like "default browser" and "search engine".
*/
internal class TelemetrySettingsProvider(
private val context: Context,
) : SettingsMeasurement.SharedPreferenceSettingsProvider() {
private val prefKeyDefaultBrowser: String
private val prefKeySearchEngine: String
init {
val resources = context.resources
prefKeyDefaultBrowser = resources.getString(R.string.pref_key_default_browser)
prefKeySearchEngine = resources.getString(R.string.pref_key_search_engine)
}
override fun containsKey(key: String): Boolean = when (key) {
// Not actually a setting - but we want to report this like a setting.
prefKeyDefaultBrowser -> true
// We always want to report the current search engine - even if it's not in settings yet.
prefKeySearchEngine -> true
else -> super.containsKey(key)
}
override fun getValue(key: String): Any {
return when (key) {
prefKeyDefaultBrowser -> {
// The default browser is not actually a setting. We determine if we are the
// default and then inject this into telemetry.
val context = TelemetryHolder.get().configuration.context
val browsers = Browsers.all(context)
browsers.isDefaultBrowser.toString()
}
prefKeySearchEngine -> {
// The default search engine is no longer saved using this pref. But we will continue
// to report it here until we switch to our new telemetry system (glean).
val searchEngine = context.components.store.state.search.selectedOrDefaultSearchEngine
if (searchEngine?.type == SearchEngine.Type.CUSTOM) {
"custom"
} else {
searchEngine?.name ?: "<none>"
}
}
else -> super.getValue(key)
}
}
}
| mpl-2.0 | 5842420918d2e94aabdc8abd1881e907 | 40.19697 | 102 | 0.675984 | 4.952641 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/setup/flow/setupsteps/StepCollectCommissionerDeviceInfo.kt | 1 | 1670 | package io.particle.mesh.setup.flow.setupsteps
import io.particle.android.sdk.cloud.ParticleCloud
import io.particle.mesh.R.string
import io.particle.mesh.common.android.livedata.nonNull
import io.particle.mesh.common.android.livedata.runBlockOnUiThreadAndAwaitUpdate
import io.particle.mesh.setup.flow.*
import io.particle.mesh.setup.flow.DialogSpec.ResDialogSpec
import io.particle.mesh.setup.flow.DialogSpec.StringDialogSpec
import io.particle.mesh.setup.flow.context.SetupContexts
class StepCollectCommissionerDeviceInfo(
private val flowUi: FlowUiDelegate,
private val cloud: ParticleCloud
) : MeshSetupStep() {
override suspend fun doRunStep(ctxs: SetupContexts, scopes: Scopes) {
val barcodeLD = ctxs.commissioner.barcode
if (barcodeLD.value != null) {
return
}
val barcodeData = barcodeLD.nonNull(scopes).runBlockOnUiThreadAndAwaitUpdate(scopes) {
flowUi.getCommissionerBarcode()
}
if (barcodeData == ctxs.targetDevice.barcode.value) {
barcodeLD.runBlockOnUiThreadAndAwaitUpdate(scopes) {
ctxs.commissioner.updateBarcode(null, cloud)
}
val error = SameDeviceScannedTwiceException()
flowUi.dialogTool.dialogResultLD
.nonNull(scopes)
.runBlockOnUiThreadAndAwaitUpdate(scopes) {
flowUi.dialogTool.newDialogRequest(
StringDialogSpec(error.userFacingMessage!!)
)
}
throw error
}
if (barcodeData == null) {
throw NoBarcodeScannedException()
}
}
} | apache-2.0 | 31e1c01080b18b0adb23cbbac72bdd76 | 32.42 | 94 | 0.669461 | 4.883041 | false | false | false | false |
DadosAbertosBrasil/android-radar-politico | app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/models/Deputado.kt | 1 | 814 | package br.edu.ifce.engcomp.francis.radarpolitico.models
import java.io.Serializable
data class Deputado(
var idCadastro: String? = "",
var matricula: String? = "",
var idParlamentar: String? = "",
var condicao: String? = "",
var nome: String? = "",
var nomeParlamentar: String? = "",
var urlFoto: String? = "",
var partido: String? = "",
var gabinete: String? = "",
var anexo: String? = "",
var uf: String? = "",
var fone: String? = "",
var email: String? = "",
var numeroLegislatura: Int = 0,
var dataNascimento: String? = "",
var situacaoLegislaturaAtual: String? = "",
var ufRepresentacaoAtual: String? = "",
var nomeProfissao: String? = "",
var ausencia: String? = " ",
var frequencia: Frequencia? = null) : Serializable
| gpl-2.0 | bf86e300b19d1622bbaece495c083f14 | 25.258065 | 56 | 0.603194 | 3.336066 | false | false | false | false |
chenxyu/android-banner | app/src/main/java/com/chenxyu/androidbanner/MainActivity.kt | 1 | 7290 | package com.chenxyu.androidbanner
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.chenxyu.bannerlibrary.BannerView
import com.chenxyu.bannerlibrary.BannerView2
import com.chenxyu.bannerlibrary.indicator.CircleIndicator
import com.chenxyu.bannerlibrary.indicator.ScrollIndicator
import com.chenxyu.bannerlibrary.listener.OnItemClickListener
import com.chenxyu.bannerlibrary.vo.Margins
/**
* @author ChenXingYu
* @version v1.3.0
*/
class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findView()
init()
}
private fun findView() {
}
private fun init() {
// BannerView
val mADBannerView = findViewById<BannerView>(R.id.ad_banner_view)
val mImageUrls = mutableListOf<String?>()
mImageUrls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151718678&di=b0d073ad41f1e125aa7ee4abfcc9e2aa&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1920h1080%2F20180106%2F9692-fyqincu7584307.jpg")
mImageUrls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151462489&di=472f98f77c71a36dc90cde4ced4bb9e9&imgtype=0&src=http%3A%2F%2Fvsd-picture.cdn.bcebos.com%2F4649cd5d6dac13c4ae0901967f988fa691be04a9.jpg")
mImageUrls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151590305&di=09f460cb77e3cee5caae3d638c637abc&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201312%2F27%2F20131227233022_Bd3Ft.jpeg")
mImageUrls.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
val mImageViewAdapter = ImageViewAdapter(this, mImageUrls)
mADBannerView.setLifecycle(this)
.setAdapter(mImageViewAdapter)
.setIndicator(CircleIndicator())
.setAutoPlay(true)
.setDelayMillis(3000L)
.setDuration(500)
.build()
mImageViewAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(view: View?, position: Int) {
Toast.makeText(this@MainActivity, position.toString(),
Toast.LENGTH_SHORT).show()
}
}
val mImageUrls2 = mutableListOf<String?>()
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151718678&di=b0d073ad41f1e125aa7ee4abfcc9e2aa&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1920h1080%2F20180106%2F9692-fyqincu7584307.jpg")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151462489&di=472f98f77c71a36dc90cde4ced4bb9e9&imgtype=0&src=http%3A%2F%2Fvsd-picture.cdn.bcebos.com%2F4649cd5d6dac13c4ae0901967f988fa691be04a9.jpg")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151590305&di=09f460cb77e3cee5caae3d638c637abc&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201312%2F27%2F20131227233022_Bd3Ft.jpeg")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
mImageUrls2.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583151690450&di=c33be331339fbc65459864f802fa1cc7&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn%2Fw1142h639%2F20180203%2F9979-fyrcsrx2995071.png")
// BannerView2
val mADBannerView2 = findViewById<BannerView2>(R.id.ad_banner_view2)
val mImageViewAdapter2 = ImageViewAdapter2(this, mImageUrls2)
mADBannerView2.setLifecycle(this)
.setOrientation(BannerView2.HORIZONTAL)
.setGridLayoutManager(GridLayoutManager(this, 2))
.setAdapter(mImageViewAdapter2, Margins(10, 16, 10, 0))
.setIndicator(ScrollIndicator(false))
.setShowCount(3)
.build()
mImageViewAdapter2.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(view: View?, position: Int) {
Toast.makeText(this@MainActivity, position.toString(),
Toast.LENGTH_SHORT).show()
}
}
// BannerView2
val mNewsBannerView = findViewById<BannerView2>(R.id.news_banner_view)
val mTitles = mutableListOf<String?>()
mTitles.add("世卫组织发言人:新冠疫情尚未到达顶峰")
mTitles.add("莫斯科将实施通行证制度")
mTitles.add("单日新增2972例 意大利累计确诊超16万")
mTitles.add("美或需保持社交隔离措施至2022年")
mTitles.add("新冠肺炎康复者能否抵御二次感染?世卫回应")
val mNewsAdapter = NewsAdapter(mTitles)
mNewsBannerView.setLifecycle(this)
.setOrientation(BannerView2.VERTICAL)
.setAdapter(mNewsAdapter)
.setAutoPlay(true)
.setDelayMillis(3000L)
.setDuration(500)
.build()
mNewsAdapter.onItemClickListener = object : OnItemClickListener {
override fun onItemClick(view: View?, position: Int) {
Toast.makeText(this@MainActivity, position.toString(),
Toast.LENGTH_SHORT).show()
}
}
}
} | mit | 4268b6c4ebcee6cebccfbc425ec03b6a | 65.12037 | 248 | 0.727731 | 3.150927 | false | false | false | false |
google/horologist | media-sample/src/main/java/com/google/android/horologist/mediasample/data/service/complication/MediaStatusComplicationService.kt | 1 | 3640 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.mediasample.data.service.complication
import android.graphics.drawable.Icon
import androidx.media3.common.MediaItem
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.data.SmallImageType
import androidx.wear.watchface.complications.datasource.ComplicationRequest
import coil.ImageLoader
import com.google.android.horologist.media.ui.complication.MediaStatusTemplate
import com.google.android.horologist.media.ui.complication.MediaStatusTemplate.Data
import com.google.android.horologist.media3.navigation.IntentBuilder
import com.google.android.horologist.mediasample.R
import com.google.android.horologist.tiles.complication.ComplicationTemplate
import com.google.android.horologist.tiles.complication.DataComplicationService
import com.google.android.horologist.tiles.images.loadImage
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.withTimeoutOrNull
import javax.inject.Inject
import kotlin.time.Duration.Companion.seconds
/**
* A media complication service that shows the app name and favorites category
* when not playing, but switches to current media when playing.
*/
@AndroidEntryPoint
class MediaStatusComplicationService :
DataComplicationService<Data, ComplicationTemplate<Data>>() {
@Inject
lateinit var intentBuilder: IntentBuilder
@Inject
lateinit var imageLoader: ImageLoader
@Inject
lateinit var dataUpdates: DataUpdates
override val renderer: MediaStatusTemplate = MediaStatusTemplate(this)
override fun previewData(type: ComplicationType): Data = renderer.previewData()
override suspend fun data(request: ComplicationRequest): Data {
val state = dataUpdates.stateFlow.value
return if (state.mediaItem != null) {
whilePlayingData(state.mediaItem)
} else {
notPlayingData()
}
}
private fun notPlayingData() = Data(
text = getString(R.string.favorites),
title = getString(R.string.sample_app_name),
appIconRes = R.drawable.ic_baseline_queue_music_24,
launchIntent = intentBuilder.buildPlayerIntent(),
type = SmallImageType.ICON
)
private suspend fun whilePlayingData(mediaItem: MediaItem): Data {
val bitmap = withTimeoutOrNull(2.seconds) {
imageLoader.loadImage(
context = this@MediaStatusComplicationService,
data = mediaItem.mediaMetadata.artworkUri
) {
size(64)
}
}
val icon = if (bitmap != null) Icon.createWithBitmap(bitmap) else null
val mediaTitle = mediaItem.mediaMetadata.displayTitle.toString()
val mediaArtist = mediaItem.mediaMetadata.artist.toString()
return Data(
text = mediaTitle,
title = mediaArtist,
icon = icon,
type = SmallImageType.PHOTO,
launchIntent = intentBuilder.buildPlayerIntent()
)
}
}
| apache-2.0 | e29d1d4b70445fbb1abad841d690aab0 | 37.315789 | 83 | 0.732692 | 4.715026 | false | false | false | false |
inv3rse/ProxerTv | app/src/main/java/com/inverse/unofficial/proxertv/ui/player/VideoPlayer.kt | 1 | 9250 | package com.inverse.unofficial.proxertv.ui.player
import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Surface
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.google.android.exoplayer2.*
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.source.TrackGroupArray
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.trackselection.TrackSelectionArray
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import timber.log.Timber
/**
* A simple video player based on the [SimpleExoPlayer].
*/
class VideoPlayer(context: Context, savedState: Bundle? = null) : SurfaceHolder.Callback {
private val mPlayer: SimpleExoPlayer
private val mTrackSelector: DefaultTrackSelector
private val mHandler = Handler(Looper.getMainLooper())
private var mProgressRunnable: Runnable? = null
private var mAspectRatio: Float = 0F
// ui, context holding
private var mAspectRatioFrameLayout: AspectRatioFrameLayout? = null
private var mSurface: Surface? = null
// might be context holding, user might have to remove it
private var mStatusListener: StatusListener? = null
var isInitialized: Boolean = false
private set
init {
val bandwidthMeter = DefaultBandwidthMeter()
val videoTrackSelectionFactory = AdaptiveTrackSelection.Factory(bandwidthMeter)
mTrackSelector = DefaultTrackSelector(videoTrackSelectionFactory)
val rendererFactory = DefaultRenderersFactory(context, null)
mPlayer = ExoPlayerFactory.newSimpleInstance(rendererFactory, mTrackSelector)
mPlayer.addListener(ExoPlayerListener())
mPlayer.setVideoListener(VideoEventListener())
if (savedState != null) {
mAspectRatio = savedState.getFloat(KEY_ASPECT_RATIO)
mPlayer.seekTo(savedState.getLong(KEY_PROGRESS))
} else {
mAspectRatio = -1f
}
}
/**
* Initialize the player to play to play a video
* @param videoUri the uri of the video to play
* @param context a context
* @param keepPosition if set to true the player will keep the current position
*/
fun initPlayer(videoUri: Uri, context: Context, keepPosition: Boolean = false) {
if (isInitialized) {
mPlayer.stop()
}
val dataSourceFactory = DefaultDataSourceFactory(context, USER_AGENT)
val extractorsFactory = DefaultExtractorsFactory()
val videoSource = ExtractorMediaSource(videoUri, dataSourceFactory, extractorsFactory, null, null)
mPlayer.prepare(videoSource, !keepPosition, !keepPosition)
isInitialized = true
}
// we assume loading is the same as playing
val isPlaying: Boolean
get() = mPlayer.playWhenReady
/**
* Play once the player is ready
*/
fun play() {
mPlayer.playWhenReady = true
}
/**
* Pause the playback
*/
fun pause() {
mPlayer.playWhenReady = false
}
/**
* Stop the playback. To play again [initPlayer] must be called
*/
fun stop() {
mPlayer.stop()
mPlayer.seekTo(0)
mPlayer.playWhenReady = false
isInitialized = false
}
/**
* Seeks to a position
* @param position the position in milliseconds
*/
fun seekTo(position: Long) {
mPlayer.seekTo(position)
mStatusListener?.progressChanged(position, mPlayer.bufferedPosition)
}
val position: Long
get() = mPlayer.currentPosition
val bufferedPosition: Long
get() = mPlayer.bufferedPosition
val duration: Long
get() = mPlayer.duration
/**
* Destroy the player and free used resources. The player must not be used after calling this method
*/
fun destroy() {
if (isInitialized) {
mPlayer.stop()
}
mStatusListener = null
disconnectFromUi()
stopProgressUpdate()
mPlayer.release()
}
/**
* Connect the player to a surface
* @param frameLayout the layout containing the [SurfaceView] or null
* @param surfaceView the [SurfaceView]
*/
fun connectToUi(frameLayout: AspectRatioFrameLayout?, surfaceView: SurfaceView) {
Timber.d("connect to ui")
mAspectRatioFrameLayout = frameLayout
if (mAspectRatio != -1f) {
frameLayout?.setAspectRatio(mAspectRatio)
}
setVideoRendererDisabled(false)
surfaceView.holder.removeCallback(this)
surfaceView.holder.addCallback(this)
}
/**
* Disconnect the player from its ui components
*/
fun disconnectFromUi() {
Timber.d("disconnect from ui")
setVideoRendererDisabled(true)
mPlayer.clearVideoSurface()
mSurface = null
mAspectRatioFrameLayout = null
}
/**
* Set the [StatusListener]
* @param listener the listener or null
*/
fun setStatusListener(listener: StatusListener?) {
mStatusListener = listener
}
fun saveInstanceState(bundle: Bundle) {
bundle.putLong(KEY_PROGRESS, mPlayer.currentPosition)
bundle.putFloat(KEY_ASPECT_RATIO, mAspectRatio)
}
private fun startProgressUpdate() {
if (mProgressRunnable == null) {
mProgressRunnable = object : Runnable {
override fun run() {
mStatusListener?.progressChanged(mPlayer.currentPosition, mPlayer.bufferedPosition)
mHandler.postDelayed(this, PROGRESS_UPDATE_PERIOD)
}
}
}
mHandler.post(mProgressRunnable)
}
private fun stopProgressUpdate() {
if (mProgressRunnable != null) {
mHandler.removeCallbacks(mProgressRunnable)
mProgressRunnable = null
}
}
override fun surfaceCreated(holder: SurfaceHolder) {
Timber.d("surface created")
mSurface = holder.surface
mPlayer.setVideoSurface(mSurface)
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
Timber.d("surface changed format:$format width:$width height:$height")
// set fixed size to avoid wrong position after picture in picture
holder.setFixedSize(width, height)
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
Timber.d("surface destroyed")
if (mSurface == holder.surface) {
disconnectFromUi()
}
}
/**
* Enable or disable all video renderer
*/
private fun setVideoRendererDisabled(disabled: Boolean) {
(0..(mPlayer.rendererCount - 1))
.filter { mPlayer.getRendererType(it) == C.TRACK_TYPE_VIDEO }
.forEach { mTrackSelector.setRendererDisabled(it, disabled) }
}
interface StatusListener {
fun playStatusChanged(isPlaying: Boolean, playbackState: Int)
fun progressChanged(currentProgress: Long, bufferedProgress: Long)
fun videoDurationChanged(length: Long)
fun onError(error: ExoPlaybackException)
}
private inner class ExoPlayerListener : ExoPlayer.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
if (playWhenReady) {
startProgressUpdate()
} else {
stopProgressUpdate()
}
mStatusListener?.playStatusChanged(playWhenReady, playbackState)
mStatusListener?.videoDurationChanged(mPlayer.duration)
}
override fun onPlaybackParametersChanged(playbackParameters: PlaybackParameters?) {}
override fun onLoadingChanged(isLoading: Boolean) {}
override fun onPositionDiscontinuity() {}
override fun onTimelineChanged(timeline: Timeline?, manifest: Any?) {}
override fun onTracksChanged(trackGroups: TrackGroupArray, trackSelections: TrackSelectionArray) {}
override fun onPlayerError(error: ExoPlaybackException) {
mStatusListener?.onError(error)
}
}
private inner class VideoEventListener : SimpleExoPlayer.VideoListener {
override fun onVideoSizeChanged(width: Int, height: Int, unappliedRotationDegrees: Int, pixelWidthHeightRatio: Float) {
mAspectRatio = if (height == 0) 1F else width * pixelWidthHeightRatio / height
mAspectRatioFrameLayout?.setAspectRatio(mAspectRatio)
}
override fun onRenderedFirstFrame() {
}
}
companion object {
private const val KEY_PROGRESS = "KEY_PROGRESS"
private const val KEY_ASPECT_RATIO = "KEY_ASPECT_RATIO"
private const val USER_AGENT = "ProxerTv"
private const val PROGRESS_UPDATE_PERIOD = 1000L
}
} | mit | 22a2b1f3292a895bafbb47a568e90715 | 31.233449 | 127 | 0.672216 | 5.167598 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/utils/CachedValue.kt | 1 | 569 | package me.mrkirby153.KirBot.utils
import java.lang.ref.WeakReference
class CachedValue<T>(val expiresIn: Long) {
private var value: WeakReference<T>? = null
private var expiresOn: Long = -1
fun set(value: T?) {
if (value == null)
this.value = null
else
this.value = WeakReference(value)
this.expiresOn = System.currentTimeMillis() + this.expiresIn
}
fun get(): T? {
if (this.expiresOn < System.currentTimeMillis()) {
return null
}
return value?.get()
}
} | mit | b7eeab17dab23f15c9e78717107ea9f4 | 21.8 | 68 | 0.588752 | 4.153285 | false | false | false | false |
paronos/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginCheckBoxPreference.kt | 3 | 1774 | package eu.kanade.tachiyomi.widget.preference
import android.content.Context
import android.graphics.Color
import android.support.v7.preference.CheckBoxPreference
import android.support.v7.preference.PreferenceViewHolder
import android.util.AttributeSet
import android.view.View
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.source.online.LoginSource
import eu.kanade.tachiyomi.util.getResourceColor
import eu.kanade.tachiyomi.util.setVectorCompat
import kotlinx.android.synthetic.main.pref_item_source.view.*
class LoginCheckBoxPreference @JvmOverloads constructor(
context: Context,
val source: HttpSource,
attrs: AttributeSet? = null
) : CheckBoxPreference(context, attrs) {
init {
layoutResource = R.layout.pref_item_source
}
private var onLoginClick: () -> Unit = {}
override fun onBindViewHolder(holder: PreferenceViewHolder) {
super.onBindViewHolder(holder)
val loginFrame = holder.itemView.login_frame
if (source is LoginSource) {
val tint = if (source.isLogged())
Color.argb(255, 76, 175, 80)
else
context.getResourceColor(android.R.attr.textColorSecondary)
holder.itemView.login.setVectorCompat(R.drawable.ic_account_circle_black_24dp, tint)
loginFrame.visibility = View.VISIBLE
loginFrame.setOnClickListener {
onLoginClick()
}
} else {
loginFrame.visibility = View.GONE
}
}
fun setOnLoginClickListener(block: () -> Unit) {
onLoginClick = block
}
// Make method public
override public fun notifyChanged() {
super.notifyChanged()
}
} | apache-2.0 | ab4ee15907a5992436af9b3ed5218afa | 30.140351 | 96 | 0.689402 | 4.572165 | false | false | false | false |
kvnxiao/kommandant | kommandant-core/src/main/kotlin/com/github/kvnxiao/kommandant/command/CommandBuilder.kt | 2 | 5608 | /*
* Copyright 2017 Ze Hao Xiao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.kvnxiao.kommandant.command
import java.lang.reflect.InvocationTargetException
/**
* A builder class that helps define a command without needing to specify all the properties for the [ICommand] constructor.
*
* @constructor Constructor which defines the [uniqueName] of the command to build.
* @property[uniqueName] The unique name of the command to build.
*/
open class CommandBuilder<T>(private val uniqueName: String) {
/**
* Constructor which defines the [prefix] and [uniqueName] of the command to build.
*/
constructor(prefix: String, uniqueName: String) : this(uniqueName) {
this.prefix = prefix
}
/**
* The aliases of the command to build, represented as a (nullable) list of strings. If the list is null, the builder
* will default to using the command's [uniqueName] as the command's alias.
*/
private var aliases: Set<String>? = null
/**
* The description of the command to build. Defaults to [CommandDefaults.NO_DESCRIPTION].
*/
private var description: String = CommandDefaults.NO_DESCRIPTION
/**
* The usage of the command to build. Defaults to [CommandDefaults.NO_USAGE].
*/
private var usage: String = CommandDefaults.NO_USAGE
/**
* The prefix of the command to build. Defaults to [CommandDefaults.PREFIX].
*/
private var prefix: String = CommandDefaults.PREFIX
/**
* Whether the command should execute alongside its subcommand or be skipped when subcommands are processed.
* Defaults to [CommandDefaults.EXEC_WITH_SUBCOMMANDS].
*/
private var execWithSubcommands: Boolean = CommandDefaults.EXEC_WITH_SUBCOMMANDS
/**
* Whether the command is disabled. Defaults to [CommandDefaults.IS_DISABLED].
*/
private var isDisabled: Boolean = CommandDefaults.IS_DISABLED
/**
* Sets the prefix of the command to build.
*
* @return The current [CommandBuilder] instance.
*/
fun withPrefix(prefix: String): CommandBuilder<T> {
this.prefix = prefix
return this
}
/**
* Sets the description of the command to build.
*
* @return The current [CommandBuilder] instance.
*/
fun withDescription(description: String): CommandBuilder<T> {
this.description = description
return this
}
/**
* Sets the usage of the command to build.
*
* @return The current [CommandBuilder] instance.
*/
fun withUsage(usage: String): CommandBuilder<T> {
this.usage = usage
return this
}
/**
* Sets whether the command to build should be executed along with its subcommand.
*
* @return The current [CommandBuilder] instance.
*/
fun setExecWithSubcommands(execWithSubcommands: Boolean): CommandBuilder<T> {
this.execWithSubcommands = execWithSubcommands
return this
}
/**
* Sets the aliases of the command to build, taking in a vararg amount of strings.
*
* @return The current [CommandBuilder] instance.
*/
fun withAliases(vararg aliases: String): CommandBuilder<T> {
this.aliases = aliases.toSet()
return this
}
/**
* Sets the aliases of the command to build, taking in a list of strings.
*
* @return The current [CommandBuilder] instance.
*/
fun withAliases(aliases: Set<String>): CommandBuilder<T> {
this.aliases = aliases
return this
}
/**
* Sets whether the command to build is disabled.
*
* @return The current [CommandBuilder] instance.
*/
fun setDisabled(disabled: Boolean): CommandBuilder<T> {
this.isDisabled = disabled
return this
}
/**
* Builds the command with the provided [ICommandExecutable].
*
* @return[ICommand] The built command.
*/
fun build(executor: ICommandExecutable<T>): ICommand<T> {
if (aliases === null) aliases = setOf(uniqueName)
return object : ICommand<T>(prefix, uniqueName, description, usage, execWithSubcommands, isDisabled, aliases!!) {
@Throws(InvocationTargetException::class, IllegalAccessException::class)
override fun execute(context: CommandContext, vararg opt: Any?): T? {
return executor.execute(context, *opt)
}
}
}
companion object {
/**
* Kotlin lambda helper to easily define the [executable][ICommandExecutable] command method. It is recommended
* to not use this in Java as a lambda can be directly used in [build].
*
* @return[ICommandExecutable] The executable method for the command.
*/
@JvmStatic
fun <T> execute(handler: (CommandContext, Array<out Any?>) -> T): ICommandExecutable<T> {
return object : ICommandExecutable<T> {
override fun execute(context: CommandContext, vararg opt: Any?): T = handler(context, opt)
}
}
}
}
| apache-2.0 | 89533ae66d6ad1e6cc82b23e3148ee2a | 32.580838 | 124 | 0.655136 | 4.673333 | false | false | false | false |
EPadronU/balin | src/test/kotlin/com/github/epadronu/balin/core/WithWindowTests.kt | 1 | 6428 | /******************************************************************************
* Copyright 2016 Edinson E. Padrón Urdaneta
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
/* ***************************************************************************/
package com.github.epadronu.balin.core
/* ***************************************************************************/
/* ***************************************************************************/
import com.github.epadronu.balin.extensions.`$`
import org.openqa.selenium.NoSuchWindowException
import org.openqa.selenium.WebDriver
import org.openqa.selenium.htmlunit.HtmlUnitDriver
import org.testng.Assert.assertEquals
import org.testng.Assert.assertThrows
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import com.gargoylesoftware.htmlunit.BrowserVersion.FIREFOX_60 as BROWSER_VERSION
/* ***************************************************************************/
/* ***************************************************************************/
class WithWindowTests {
companion object {
@JvmStatic
val pageWithWindowsUrl = WithWindowTests::class.java
.getResource("/test-pages/page-with-windows.html")
.toString()
}
@DataProvider(name = "JavaScript-incapable WebDriver factory", parallel = true)
fun `Create a JavaScript-incapable WebDriver factory`() = arrayOf(
arrayOf({ HtmlUnitDriver(BROWSER_VERSION) })
)
@Test(description = "Validate context switching to and from a window",
dataProvider = "JavaScript-incapable WebDriver factory")
fun validate_context_switching_to_and_from_a_window(driverFactory: () -> WebDriver) {
Browser.drive(driverFactory) {
// Given I navigate to the page under test, which contains links that open windows
to(pageWithWindowsUrl)
// And I'm in the context of the original window
assertEquals(`$`("h1", 0).text, "Page with links that open windows")
// And I open a new window by clicking on a link
`$`("#ddg-page", 0).click()
// When I change the driver's context to the just opened window
withWindow(windowHandles.toSet().minus(windowHandle).first()) {
// Then I should be able to interact with such window
assertEquals(
`$`(".tag-home__item", 0).text.trim(),
"The search engine that doesn't track you. Learn More.")
}
// And I should return into the context of the original window
assertEquals(`$`("h1", 0).text, "Page with links that open windows")
// And only one window should be opened
assertEquals(windowHandles.size, 1)
}
}
@Test(dataProvider = "JavaScript-incapable WebDriver factory")
fun `Validate automatically context switching to and from the last opened window`(driverFactory: () -> WebDriver) {
Browser.drive(driverFactory) {
// Given I navigate to the page under test, which contains links that open windows
to(pageWithWindowsUrl)
// And I'm in the context of the original window
assertEquals(`$`("h1", 0).text, "Page with links that open windows")
// And I open a new window by clicking on a link
`$`("#ddg-page", 0).click()
// When I change the driver's context to the last opened window
withWindow {
// Then I should be able to interact with such window
assertEquals(
`$`(".tag-home__item", 0).text.trim(),
"The search engine that doesn't track you. Learn More.")
}
// And I should return into the context of the original window
assertEquals(`$`("h1", 0).text, "Page with links that open windows")
// And only two window should be opened
assertEquals(windowHandles.size, 1)
}
}
@Test(dataProvider = "JavaScript-incapable WebDriver factory")
fun `Validate automatically context switching to and from a window when are none opened fails`(driverFactory: () -> WebDriver) {
Browser.drive(driverFactory) {
// Given I navigate to the page under test, which contains links that open windows
to(pageWithWindowsUrl)
// And I'm in the context of the original window
assertEquals(`$`("h1", 0).text, "Page with links that open windows")
// When I try to change the driver's context to another window
// Then an exception should be thrown
assertThrows(NoSuchWindowException::class.java) {
withWindow { }
}
}
}
@Test(dataProvider = "JavaScript-incapable WebDriver factory")
fun `Validate automatically context switching to and from a window when several are opened fails`(driverFactory: () -> WebDriver) {
Browser.drive(driverFactory) {
// Given I navigate to the page under test, which contains links that open windows
to(pageWithWindowsUrl)
// And I'm in the context of the original window
assertEquals(`$`("h1", 0).text, "Page with links that open windows")
// And I open a new window by clicking on a link
`$`("#ddg-page", 0).click()
// And I open another window by clicking on a link
`$`("#ddg-page", 0).click()
// When I try to change the driver's context to another window
// Then an exception should be thrown
assertThrows(NoSuchWindowException::class.java) {
withWindow { }
}
}
}
}
/* ***************************************************************************/
| apache-2.0 | 1f1b96b2579120c943ba963b0878db6b | 43.324138 | 135 | 0.571495 | 5.263718 | false | true | false | false |
Aptoide/aptoide-client-v8 | app/src/main/java/cm/aptoide/pt/wallet/WalletInstallActivity.kt | 1 | 7323 | package cm.aptoide.pt.wallet
import android.graphics.Typeface
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.StyleSpan
import android.view.View
import android.widget.TextView
import cm.aptoide.pt.R
import cm.aptoide.pt.app.DownloadModel
import cm.aptoide.pt.logger.Logger
import cm.aptoide.pt.networking.image.ImageLoader
import cm.aptoide.pt.promotions.WalletApp
import cm.aptoide.pt.utils.GenericDialogs
import cm.aptoide.pt.view.ActivityView
import com.jakewharton.rxbinding.view.RxView
import kotlinx.android.synthetic.main.wallet_install_activity.*
import kotlinx.android.synthetic.main.wallet_install_download_view.*
import rx.Observable
import javax.inject.Inject
class WalletInstallActivity : ActivityView(), WalletInstallView {
@Inject
lateinit var presenter: WalletInstallPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityComponent.inject(this)
setContentView(R.layout.wallet_install_activity)
initStyling()
attachPresenter(presenter)
}
private fun initStyling() {
val walletAppName = getString(R.string.wallet_install_appcoins_wallet)
val message = getString(R.string.wallet_install_request_message_body, walletAppName)
message_textview.text = message
message_textview.setSubstringTypeface(Pair(walletAppName, Typeface.BOLD))
}
override fun showWalletInstallationView(appIcon: String?,
walletApp: WalletApp) {
progress_view.visibility = View.GONE
wallet_install_success_view_group.visibility = View.GONE
close_button.visibility = View.GONE
appIcon?.let {
ImageLoader.with(this).load(appIcon, app_icon_imageview)
}
walletApp.downloadModel?.let { downloadModel ->
Logger.getInstance()
.d("WalletInstallActivity", "download state is " + downloadModel.downloadState)
if (downloadModel.isDownloading) {
setDownloadProgress(downloadModel)
} else {
wallet_install_download_view.visibility = View.GONE
progress_view.visibility = View.GONE
wallet_install_view_group.visibility = View.VISIBLE
}
}
}
private fun setDownloadProgress(downloadModel: DownloadModel) {
wallet_install_download_view.visibility = View.VISIBLE
when (downloadModel.downloadState) {
DownloadModel.DownloadState.ACTIVE,
DownloadModel.DownloadState.PAUSE -> {
wallet_install_view_group.visibility = View.VISIBLE
wallet_download_cancel_button.visibility = View.VISIBLE
wallet_download_progress_bar.isIndeterminate = false
wallet_download_progress_bar.progress = downloadModel
.progress
wallet_download_progress_number.text = downloadModel
.progress.toString() + "%"
wallet_download_progress_number.visibility = View.VISIBLE
}
DownloadModel.DownloadState.INDETERMINATE -> {
wallet_download_progress_bar.isIndeterminate = true
wallet_install_view_group.visibility = View.VISIBLE
wallet_download_cancel_button.visibility = View.VISIBLE
}
DownloadModel.DownloadState.INSTALLING,
DownloadModel.DownloadState.COMPLETE -> {
wallet_download_progress_bar.isIndeterminate = true
wallet_download_progress_number.visibility = View.GONE
wallet_install_view_group.visibility = View.VISIBLE
wallet_download_cancel_button.visibility = View.INVISIBLE
}
DownloadModel.DownloadState.ERROR -> showErrorMessage(
getString(R.string.error_occured))
DownloadModel.DownloadState.NOT_ENOUGH_STORAGE_ERROR -> showErrorMessage(
getString(R.string.out_of_space_dialog_title))
else -> {
throw IllegalArgumentException("Invalid download state" + downloadModel.downloadState)
}
}
}
private fun showErrorMessage(errorMessage: String) {
wallet_download_download_state.text = errorMessage
}
override fun showInstallationSuccessView() {
install_complete_message.visibility = View.INVISIBLE
showSuccessView(getString(R.string.wallet_install_complete_title))
}
override fun showWalletInstalledAlreadyView() {
install_complete_message.text =
getString(R.string.wallet_install_request_already_installed_body)
showSuccessView(getString(R.string.wallet_install_request_already_installed_title))
}
private fun showSuccessView(title: String) {
app_icon_imageview.setImageDrawable(
resources.getDrawable(R.drawable.ic_check_orange_gradient_start))
message_textview.text = title
message_textview.setSubstringTypeface(Pair(title, Typeface.BOLD))
progress_view.visibility = View.GONE
wallet_install_success_view_group.visibility = View.VISIBLE
close_button.visibility = View.VISIBLE
wallet_install_view_group.visibility = View.VISIBLE
wallet_install_download_view.visibility = View.GONE
}
override fun closeButtonClicked(): Observable<Void> {
return RxView.clicks(close_button)
}
override fun dismissDialog() {
finish()
}
override fun showSdkErrorView() {
sdk_error_view_group.visibility = View.VISIBLE
progress_view.visibility = View.GONE
close_button.visibility = View.VISIBLE
wallet_install_success_view_group.visibility = View.GONE
wallet_install_view_group.visibility = View.INVISIBLE
}
override fun showRootInstallWarningPopup(): Observable<Boolean> {
return GenericDialogs.createGenericYesNoCancelMessage(applicationContext, null,
resources.getString(R.string.root_access_dialog),
themeManager.getAttributeForTheme(R.attr.dialogsTheme).resourceId)
.map { response -> response.equals(GenericDialogs.EResponse.YES) }
}
/**
* Sets the specified Typeface Style on the first instance of the specified substring(s)
* @param one or more [Pair] of [String] and [Typeface] style (e.g. BOLD, ITALIC, etc.)
*/
fun TextView.setSubstringTypeface(vararg textsToStyle: Pair<String, Int>) {
val spannableString = SpannableString(this.text)
for (textToStyle in textsToStyle) {
val startIndex = this.text.toString().indexOf(textToStyle.first)
val endIndex = startIndex + textToStyle.first.length
if (startIndex >= 0) {
spannableString.setSpan(
StyleSpan(textToStyle.second),
startIndex,
endIndex,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
}
}
this.setText(spannableString, TextView.BufferType.SPANNABLE)
}
override fun showIndeterminateDownload() {
wallet_install_download_view.visibility = View.VISIBLE
wallet_download_progress_bar.isIndeterminate = true
wallet_install_view_group.visibility = View.VISIBLE
}
override fun cancelDownloadButtonClicked(): Observable<Void> {
return RxView.clicks(wallet_download_cancel_button)
}
override fun showDownloadState(downloadModel: DownloadModel) {
if (downloadModel.isDownloadingOrInstalling) {
wallet_install_download_view.visibility = View.VISIBLE
setDownloadProgress(downloadModel)
} else {
wallet_install_download_view.visibility = View.GONE
progress_view.visibility = View.GONE
wallet_install_view_group.visibility = View.VISIBLE
}
}
} | gpl-3.0 | 07dc1b6a20a6ee900479f7d7a8c08209 | 35.989899 | 94 | 0.730438 | 4.438182 | false | false | false | false |
rock3r/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/UseArrayLiteralsInAnnotationsSpec.kt | 1 | 1013 | package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class UseArrayLiteralsInAnnotationsSpec : Spek({
val subject = UseArrayLiteralsInAnnotations()
describe("suggests replacing arrayOf with [] syntax") {
it("finds an arrayOf usage") {
val findings = subject.compileAndLint("""
annotation class Test(val values: Array<String>)
@Test(arrayOf("value"))
fun test() = Unit
""".trimIndent())
assertThat(findings).hasSize(1)
}
it("expects [] syntax") {
val findings = subject.compileAndLint("""
annotation class Test(val values: Array<String>)
@Test(["value"])
fun test() = Unit
""".trimIndent())
assertThat(findings).isEmpty()
}
}
})
| apache-2.0 | 1c1f74a9f27028284616e3367a93bd94 | 28.794118 | 60 | 0.627838 | 4.800948 | false | true | false | false |
JetBrains/anko | anko/library/static/commons/src/main/java/buildSpanned.kt | 2 | 3033 | /*
* Copyright 2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("unused", "NOTHING_TO_INLINE")
package org.jetbrains.anko
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.style.BackgroundColorSpan
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.StrikethroughSpan
import android.text.style.StyleSpan
import android.text.style.URLSpan
import android.text.style.UnderlineSpan
import android.view.View
inline fun buildSpanned(f: SpannableStringBuilder.() -> Unit): Spanned =
SpannableStringBuilder().apply(f)
inline val SpannableStringBuilder.Bold: StyleSpan
get() = StyleSpan(Typeface.BOLD)
inline val SpannableStringBuilder.Italic: StyleSpan
get() = StyleSpan(Typeface.ITALIC)
inline val SpannableStringBuilder.Underline: UnderlineSpan
get() = UnderlineSpan()
inline val SpannableStringBuilder.Strikethrough: StrikethroughSpan
get() = StrikethroughSpan()
inline fun SpannableStringBuilder.foregroundColor(color: Int): ForegroundColorSpan =
ForegroundColorSpan(color)
inline fun SpannableStringBuilder.backgroundColor(color: Int): BackgroundColorSpan =
BackgroundColorSpan(color)
inline fun SpannableStringBuilder.clickable(crossinline onClick: (View) -> Unit): ClickableSpan {
return object : ClickableSpan() {
override fun onClick(widget: View) {
onClick(widget)
}
}
}
inline fun SpannableStringBuilder.link(url: String): URLSpan {
return URLSpan(url)
}
fun SpannableStringBuilder.append(text: CharSequence, vararg spans: Any) {
val textLength = text.length
append(text)
spans.forEach { span ->
setSpan(span, this.length - textLength, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
}
fun SpannableStringBuilder.append(text: CharSequence, span: Any) {
val textLength = text.length
append(text)
setSpan(span, this.length - textLength, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
inline fun SpannableStringBuilder.append(span: Any, f: SpannableStringBuilder.() -> Unit) = apply {
val start = length
f()
setSpan(span, start, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
inline fun SpannableStringBuilder.appendln(text: CharSequence, vararg spans: Any) {
append(text, *spans)
appendln()
}
inline fun SpannableStringBuilder.appendln(text: CharSequence, span: Any) {
append(text, span)
appendln()
}
| apache-2.0 | 11e9c2aa46c17204be741bb16ddb7423 | 31.612903 | 99 | 0.754039 | 4.453744 | false | false | false | false |
SpryServers/sprycloud-android | src/main/java/com/nextcloud/client/media/PlayerService.kt | 2 | 5325 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.media
import android.accounts.Account
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.media.AudioManager
import android.os.Bundle
import android.os.IBinder
import android.widget.MediaController
import android.widget.Toast
import androidx.core.app.NotificationCompat
import com.owncloud.android.R
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.ui.notifications.NotificationUtils
import com.owncloud.android.utils.ThemeUtils
import dagger.android.AndroidInjection
import java.lang.IllegalArgumentException
import javax.inject.Inject
class PlayerService : Service() {
companion object {
const val EXTRA_ACCOUNT = "ACCOUNT"
const val EXTRA_FILE = "FILE"
const val EXTRA_AUTO_PLAY = "EXTRA_AUTO_PLAY"
const val EXTRA_START_POSITION_MS = "START_POSITION_MS"
const val ACTION_PLAY = "PLAY"
const val ACTION_STOP = "STOP"
const val ACTION_STOP_FILE = "STOP_FILE"
}
class Binder(val service: PlayerService) : android.os.Binder() {
/**
* This property returns current instance of media player interface.
* It is not cached and it is suitable for polling.
*/
val player: MediaController.MediaPlayerControl get() = service.player
}
private val playerListener = object : Player.Listener {
override fun onRunning(file: OCFile) {
startForeground(file)
}
override fun onStart() {
// empty
}
override fun onPause() {
// empty
}
override fun onStop() {
stopForeground(true)
}
override fun onError(error: PlayerError) {
Toast.makeText(this@PlayerService, error.message, Toast.LENGTH_SHORT).show()
}
}
@Inject
protected lateinit var audioManager: AudioManager
private lateinit var player: Player
private lateinit var notificationBuilder: NotificationCompat.Builder
override fun onCreate() {
super.onCreate()
AndroidInjection.inject(this)
player = Player(applicationContext, playerListener, audioManager)
notificationBuilder = NotificationCompat.Builder(this)
notificationBuilder.color = ThemeUtils.primaryColor(this)
val stop = Intent(this, PlayerService::class.java)
stop.action = ACTION_STOP
val pendingStop = PendingIntent.getService(this, 0, stop, 0)
notificationBuilder.addAction(0, "STOP", pendingStop)
}
override fun onBind(intent: Intent?): IBinder? {
return Binder(this)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
when (intent.action) {
ACTION_PLAY -> onActionPlay(intent)
ACTION_STOP -> onActionStop()
ACTION_STOP_FILE -> onActionStopFile(intent.extras)
}
return START_NOT_STICKY
}
private fun onActionPlay(intent: Intent) {
val account: Account = intent.getParcelableExtra(EXTRA_ACCOUNT)
val file: OCFile = intent.getParcelableExtra(EXTRA_FILE)
val startPos = intent.getIntExtra(EXTRA_START_POSITION_MS, 0)
val autoPlay = intent.getBooleanExtra(EXTRA_AUTO_PLAY, true)
val item = PlaylistItem(file = file, startPositionMs = startPos, autoPlay = autoPlay, account = account)
player.play(item)
}
private fun onActionStop() {
player.stop()
}
private fun onActionStopFile(args: Bundle?) {
val file: OCFile = args?.getParcelable(EXTRA_FILE) ?: throw IllegalArgumentException("Missing file argument")
player.stop(file)
}
private fun startForeground(currentFile: OCFile) {
val ticker = String.format(getString(R.string.media_notif_ticker), getString(R.string.app_name))
val content = getString(R.string.media_state_playing, currentFile.getFileName())
notificationBuilder.setSmallIcon(R.drawable.ic_play_arrow)
notificationBuilder.setWhen(System.currentTimeMillis())
notificationBuilder.setOngoing(true)
notificationBuilder.setContentTitle(ticker)
notificationBuilder.setContentText(content)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(NotificationUtils.NOTIFICATION_CHANNEL_MEDIA)
}
startForeground(R.string.media_notif_ticker, notificationBuilder.build())
}
}
| gpl-2.0 | c70a4287da8ded6da9b229d23f7c8aac | 34.97973 | 117 | 0.694272 | 4.658793 | false | false | false | false |
MichaelRocks/Sunny | app/src/main/kotlin/io/michaelrocks/forecast/ui/common/DividerItemDecoration.kt | 1 | 4064 | /*
* Copyright 2016 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.forecast.ui.common
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.RecyclerView
import android.view.View
const val HORIZONTAL = OrientationHelper.HORIZONTAL
const val VERTICAL = OrientationHelper.VERTICAL
fun vertical(divider: Drawable, padding: Int = 0): DividerItemDecoration {
return DividerItemDecoration(divider, padding, padding, VERTICAL)
}
fun vertical(divider: Drawable, paddingStart: Int, paddingEnd: Int): DividerItemDecoration {
return DividerItemDecoration(divider, paddingStart, paddingEnd, VERTICAL)
}
fun horizontal(divider: Drawable, padding: Int = 0): DividerItemDecoration {
return DividerItemDecoration(divider, padding, padding, HORIZONTAL)
}
fun horizontal(divider: Drawable, paddingStart: Int, paddingEnd: Int): DividerItemDecoration {
return DividerItemDecoration(divider, paddingStart, paddingEnd, HORIZONTAL)
}
open class DividerItemDecoration(
private val divider: Drawable,
private val paddingStart: Int,
private val paddingEnd: Int,
private val orientation: Int
) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(rect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildLayoutPosition(view)
val count = state.itemCount
val visible = shouldDisplayDivider(position, count)
if (orientation == HORIZONTAL) {
rect.set(0, 0, 0, if (visible) divider.intrinsicWidth else 0)
} else {
rect.set(0, 0, if (visible) divider.intrinsicHeight else 0, 0)
}
}
override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
if (orientation == VERTICAL) {
onDrawVertical(canvas, parent, state)
} else {
onDrawHorizontal(canvas, parent, state)
}
}
protected open fun onDrawVertical(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val left = parent.paddingLeft + paddingStart
val right = parent.width - parent.paddingRight - paddingEnd
for (i in 0..parent.childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val top = Math.round(child.bottom + params.bottomMargin + child.translationY)
val bottom = top + divider.intrinsicHeight
if (shouldDisplayDivider(parent.getChildLayoutPosition(child), state.itemCount)) {
divider.setBounds(left, top, right, bottom)
divider.draw(canvas)
}
}
}
protected open fun onDrawHorizontal(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
val top = parent.paddingTop + paddingStart
val bottom = parent.height - parent.paddingBottom - paddingEnd
for (i in 0..parent.childCount - 1) {
val child = parent.getChildAt(i)
val params = child.layoutParams as RecyclerView.LayoutParams
val left = Math.round(child.right + params.rightMargin + child.translationX)
val right = left + divider.intrinsicWidth
if (shouldDisplayDivider(parent.getChildLayoutPosition(child), state.itemCount)) {
divider.setBounds(left, top, right, bottom)
divider.draw(canvas)
}
}
}
protected open fun shouldDisplayDivider(position: Int, count: Int): Boolean {
return position != RecyclerView.NO_POSITION && 0 < position && position < count - 1
}
}
| apache-2.0 | 333b42692b68d95f5d3db006ba58b7a7 | 35.612613 | 104 | 0.73376 | 4.495575 | false | false | false | false |
Tomorrowhi/THDemo | THDemo/app/src/main/java/com/tomorrowhi/thdemo/adapter/MainFunctionAdapter.kt | 1 | 1726 | package com.tomorrowhi.thdemo.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.tomorrowhi.thdemo.R
import com.tomorrowhi.thdemo.bean.MainFunctionBean
import com.tomorrowhi.thdemo.interfaces.RecyclerViewClickListener
class MainFunctionAdapter(mCtx: Context) : RecyclerView.Adapter<MainFunctionAdapter.MyViewHolder>() {
private lateinit var functionList: List<MainFunctionBean>
private var context: Context = mCtx
private lateinit var mItemCLickListener: RecyclerViewClickListener
fun setList(functionList: List<MainFunctionBean>) {
this.functionList = functionList
notifyDataSetChanged()
}
fun setItemClickListener(listener: RecyclerViewClickListener) {
this.mItemCLickListener = listener
}
override fun getItemCount(): Int {
return functionList.size
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MyViewHolder {
return MyViewHolder(LayoutInflater.from(context).inflate(R.layout.main_function_item, parent, false))
}
override fun onBindViewHolder(holder: MyViewHolder?, position: Int) {
holder?.functionName?.text = functionList.get(position).name
holder?.functionLl?.setOnClickListener {
mItemCLickListener.itemClick(position)
}
}
class MyViewHolder(item: View) : RecyclerView.ViewHolder(item) {
var functionName: TextView = item.findViewById(R.id.function_name)
var functionLl: LinearLayout = item.findViewById(R.id.function_ll)
}
} | apache-2.0 | 7061591da9fde54992566e1964784120 | 30.981481 | 109 | 0.752607 | 4.639785 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/text/placeholder/Placeholder.kt | 1 | 1000 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.api.text.placeholder
typealias PlaceholderText = org.spongepowered.api.placeholder.PlaceholderComponent
typealias PlaceholderTextBuilder = org.spongepowered.api.placeholder.PlaceholderComponent.Builder
typealias PlaceholderContext = org.spongepowered.api.placeholder.PlaceholderContext
typealias PlaceholderContextBuilder = org.spongepowered.api.placeholder.PlaceholderContext.Builder
typealias PlaceholderParser = org.spongepowered.api.placeholder.PlaceholderParser
typealias PlaceholderParserBuilder = org.spongepowered.api.placeholder.PlaceholderParser.Builder
typealias PlaceholderParsers = org.spongepowered.api.placeholder.PlaceholderParsers
| mit | eafc8540ab76e76547d49b9971ca2875 | 51.631579 | 98 | 0.829 | 4.651163 | false | false | true | false |
cfig/Android_boot_image_editor | bbootimg/src/main/kotlin/avb/desc/UnknownDescriptor.kt | 1 | 3863 | // Copyright 2021 [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.
package avb.desc
import cc.cfig.io.Struct
import cfig.helper.Helper
import org.apache.commons.codec.binary.Hex
import org.slf4j.LoggerFactory
import java.io.ByteArrayInputStream
import java.io.InputStream
class UnknownDescriptor(var data: ByteArray = byteArrayOf()) : Descriptor(0, 0, 0) {
@Throws(IllegalArgumentException::class)
constructor(stream: InputStream, seq: Int = 0) : this() {
this.sequence = seq
val info = Struct(FORMAT).unpack(stream)
this.tag = (info[0] as ULong).toLong()
this.num_bytes_following = (info[1] as ULong).toLong()
log.debug("UnknownDescriptor: tag = $tag, len = ${this.num_bytes_following}")
this.data = ByteArray(this.num_bytes_following.toInt())
if (this.num_bytes_following.toInt() != stream.read(data)) {
throw IllegalArgumentException("descriptor SIZE mismatch")
}
}
override fun encode(): ByteArray {
return Helper.join(Struct(FORMAT).pack(this.tag, this.data.size.toLong()), data)
}
override fun toString(): String {
return "UnknownDescriptor(tag=$tag, SIZE=${data.size}, data=${Hex.encodeHexString(data)}"
}
fun analyze(): Descriptor {
return when (this.tag.toUInt()) {
0U -> {
PropertyDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
1U -> {
HashTreeDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
2U -> {
HashDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
3U -> {
KernelCmdlineDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
4U -> {
ChainPartitionDescriptor(ByteArrayInputStream(this.encode()), this.sequence)
}
else -> {
this
}
}
}
companion object {
private const val SIZE = 16
private const val FORMAT = "!QQ"
private val log = LoggerFactory.getLogger(UnknownDescriptor::class.java)
fun parseDescriptors(stream: InputStream, totalSize: Long): List<Descriptor> {
log.debug("Parse descriptors stream, SIZE = $totalSize")
val ret: MutableList<Descriptor> = mutableListOf()
var currentSize = 0L
var seq = 0
while (true) {
val desc = UnknownDescriptor(stream, ++seq)
currentSize += desc.data.size + SIZE
log.debug("current SIZE = $currentSize")
log.debug(desc.toString())
ret.add(desc.analyze())
if (currentSize == totalSize) {
log.debug("parse descriptor done")
break
} else if (currentSize > totalSize) {
log.error("Read more than expected")
throw IllegalStateException("Read more than expected")
} else {
log.debug(desc.toString())
log.debug("read another descriptor")
}
}
return ret
}
init {
check(SIZE == Struct(FORMAT).calcSize())
}
}
}
| apache-2.0 | ad491bb649b6e74c1f29dcba008d1232 | 36.504854 | 97 | 0.589697 | 4.710976 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/api/pr0gramm/ApiProvider.kt | 1 | 3400 | package com.pr0gramm.app.api.pr0gramm
import com.pr0gramm.app.*
import com.pr0gramm.app.util.catchAll
import com.squareup.moshi.adapter
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okio.BufferedSource
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.create
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.Proxy
class ApiProvider(base: String, client: OkHttpClient,
private val cookieJar: LoginCookieJar) {
private val logger = Logger("ApiProvider")
val api = proxy(restAdapter(base, client))
private fun restAdapter(base: String, client: OkHttpClient): Api {
return Retrofit.Builder()
.baseUrl(base.toHttpUrl())
.addConverterFactory(MoshiConverterFactory.create(MoshiInstance))
.client(client.newBuilder().addInterceptor(ErrorInterceptor()).build())
.validateEagerly(BuildConfig.DEBUG)
.build().create()
}
private fun proxy(backend: Api): Api {
val apiClass = Api::class.java
val proxy = Proxy.newProxyInstance(apiClass.classLoader, arrayOf(apiClass), InvocationHandler(backend))
return proxy as Api
}
private inner class InvocationHandler(private val backend: Api) : java.lang.reflect.InvocationHandler {
private fun doInvoke(method: Method, args: Array<out Any?>?): Any? {
return try {
if (args.isNullOrEmpty()) {
method.invoke(backend)
} else {
method.invoke(backend, *args)
}
} catch (err: InvocationTargetException) {
throw err.cause ?: err
}
}
override fun invoke(proxy: Any, method: Method, args_: Array<Any?>?): Any? {
var args = args_
if (!args.isNullOrEmpty()) {
if (method.parameterTypes[0] == Api.Nonce::class.java) {
args = args.copyOf()
args[0] = cookieJar.requireNonce()
}
}
return doInvoke(method, args)
}
}
private inner class ErrorInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
// if we get a valid "not allowed" error, we'll
if (response.code == 403) {
val body = response.peekBody(1024)
val err = tryDecodeError(body.source())
if (err?.error == "forbidden" && err.msg == "Not logged in") {
logger.warn { "Got 'Not logged in' error, will logout the user now." }
cookieJar.clearLoginCookie()
val key = err.msg.filter { it.isLetter() }
Stats().increment("api.forbidden", "message:$key")
}
}
// everything looks good, just return the response as usual
return response
}
private fun tryDecodeError(source: BufferedSource): Api.Error? {
catchAll {
return MoshiInstance.adapter<Api.Error>().fromJson(source)
}
return null
}
}
}
| mit | 7b7dac1a8785cd11041145818a1ff6b9 | 34.416667 | 111 | 0.592647 | 4.829545 | false | false | false | false |
Finnerale/FileBase | src/main/kotlin/de/leopoldluley/filebase/Extensions.kt | 1 | 2620 | package de.leopoldluley.filebase
import de.leopoldluley.filebase.app.Styles
import javafx.embed.swing.SwingFXUtils
import javafx.event.EventTarget
import javafx.geometry.Insets
import javafx.scene.Node
import javafx.scene.Parent
import javafx.scene.control.MenuItem
import javafx.scene.control.SplitMenuButton
import tornadofx.*
import java.awt.image.BufferedImage
import java.util.*
object Extensions {
fun EventTarget.splitMenuButton(text: String = "", graphic: Node? = null, op: (SplitMenuButton.() -> Unit)? = null): SplitMenuButton {
val button = SplitMenuButton()
button.text = text
if (graphic != null) button.graphic = graphic
return opcr(this, button, op)
}
fun SplitMenuButton.menuitem(text: String = "", op: (MenuItem.() -> Unit)? = null): MenuItem {
val menuitem = MenuItem(text)
op?.invoke(menuitem)
this.items.add(menuitem)
return menuitem
}
fun Properties.booleanOr(key: String) = this.getProperty(key)?.toBoolean()
fun Properties.integer(key: String) = this.getProperty(key)?.toIntOrNull()
fun String.containsOneOf(vararg chars: Char): Boolean {
chars.forEach {
if (contains(it, ignoreCase = true)) {
return true
}
}
return false
}
fun java.awt.Image.toFXImage(): javafx.scene.image.Image {
val bufferedImage: BufferedImage
if (this is BufferedImage) {
bufferedImage = this
} else {
bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB)
val graphics = bufferedImage.createGraphics()
graphics.drawImage(this, 0, 0, null)
graphics.dispose()
}
return SwingFXUtils.toFXImage(bufferedImage, null)
}
fun UIComponent.internalAlert(title: String, content: String, action: () -> Unit): Parent {
return vbox {
padding = Insets(10.0)
spacing = 10.0
label(title) {
addClass(Styles.entryTitle)
}
label(content)
button(messages["close"]) {
action {
action()
}
}
}
}
fun List<Any>.uniqueify(): List<Any> {
val seen = mutableListOf<Any>()
return filter {
if (!seen.contains(it)) {
seen.add(it)
true
} else {
false
}
}
}
} | mit | 27a6014e19ae028847bec4884d503e69 | 29.590361 | 138 | 0.567939 | 4.58042 | false | false | false | false |
sandjelkovic/dispatchd | content-service/src/main/kotlin/com/sandjelkovic/dispatchd/content/service/ContentRefreshService.kt | 1 | 3529 | package com.sandjelkovic.dispatchd.content.service
import arrow.core.Either
import arrow.core.Option
import arrow.core.Try
import arrow.core.toOption
import com.sandjelkovic.dispatchd.content.api.JobReportCreated
import com.sandjelkovic.dispatchd.content.data.entity.Show
import com.sandjelkovic.dispatchd.content.data.entity.UpdateJob
import com.sandjelkovic.dispatchd.content.data.repository.ShowRepository
import com.sandjelkovic.dispatchd.content.data.repository.UpdateJobRepository
import com.sandjelkovic.dispatchd.content.trakt.dto.ShowTrakt
import com.sandjelkovic.dispatchd.content.trakt.dto.ShowUpdateTrakt
import com.sandjelkovic.dispatchd.content.trakt.provider.TraktMediaProvider
import mu.KLogging
import org.springframework.context.ApplicationEventPublisher
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZonedDateTime
/**
* @author sandjelkovic
* @date 10.2.18.
*/
open class ContentRefreshService(
val updateJobRepository: UpdateJobRepository,
val provider: TraktMediaProvider,
val showRepository: ShowRepository,
val importer: ShowImporter,
val eventPublisher: ApplicationEventPublisher
) {
fun updateContentIfStale(): Try<List<Show>> {
return refreshExistingContent()
}
fun updateAllContent(): Long {
TODO("Not yet implemented")
}
companion object : KLogging()
private fun refreshExistingContent(): Try<List<Show>> =
getLastUpdateTime().also { logger.debug("Refreshing content. Last update was: $it") }
.let { fromTime ->
provider.getUpdates(fromTime.toLocalDate())
.map { getIdsForUpdate(it) }
.map { executeContentUpdate(it) }
.map { extractSuccessfulShows(it) }
// // possible optimisation for failure cases -> scan internal db and compare retrieved.updatedAt < internal.lastLocalUpdate
// // in order to only update shows that failed in the past. Since the update time is started from the last successful refresh.
// // independent update of each show in order to continue the refresh evens if some fail.
}
private fun extractSuccessfulShows(it: List<Either<ImportException, Show>>) =
it.filter { it.isRight() }
.map { it as Either.Right }
.map { it.b }
private fun executeContentUpdate(ids: List<String>): List<Either<ImportException, Show>> = ids
.map(importer::refreshImportedShow)
.also { createAndSaveNewJobReport().also { eventPublisher.publishEvent(JobReportCreated(it.copy())) } }
private fun getIdsForUpdate(updates: List<ShowUpdateTrakt>): List<String> = updates
.map(::extractTraktId)
.mapNotNull(Option<String>::orNull)
.filter(::showExists)
private fun showExists(id: String) = showRepository.findByTraktId(id).isPresent
private fun extractTraktId(update: ShowUpdateTrakt): Option<String> = update.toOption()
.flatMap { it.show.toOption() }
.map(ShowTrakt::ids)
.mapNotNull { it["trakt"] }
private fun getLastUpdateTime(): ZonedDateTime =
updateJobRepository.findFirstBySuccessOrderByFinishTimeDesc(true)
.map(UpdateJob::finishTime)
.orElseGet { ZonedDateTime.of(LocalDateTime.MIN, ZoneId.systemDefault()) }
private fun createAndSaveNewJobReport() =
updateJobRepository.save(UpdateJob(finishTime = ZonedDateTime.now(), success = true)).also {
logger.debug("Saved job: $it")
}
}
| apache-2.0 | b4670021fb7c7efe0fd56beb4964dcb7 | 40.517647 | 135 | 0.714367 | 4.541828 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.