repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Mauin/detekt | detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/RunRuleSetWithRuleFiltersSpec.kt | 1 | 2111 | package io.gitlab.arturbosch.detekt.rules
import io.gitlab.arturbosch.detekt.api.RuleSet
import io.gitlab.arturbosch.detekt.rules.empty.EmptyBlocks
import io.gitlab.arturbosch.detekt.rules.empty.EmptyInitBlock
import io.gitlab.arturbosch.detekt.rules.providers.EmptyCodeProvider
import io.gitlab.arturbosch.detekt.rules.style.FileParsingRule
import io.gitlab.arturbosch.detekt.rules.style.WildcardImport
import io.gitlab.arturbosch.detekt.rules.style.optional.OptionalUnit
import io.gitlab.arturbosch.detekt.test.compileForTest
import io.gitlab.arturbosch.detekt.test.loadRuleSet
import org.assertj.core.api.Assertions
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
/**
* @author Artur Bosch
*/
class RunRuleSetWithRuleFiltersSpec : Spek({
val emptyFile = compileForTest(Case.Empty.path())
val defaultFile = compileForTest(Case.Default.path())
describe("RuleSet without MultiRule's") {
val ruleSet = RuleSet("Test", listOf(WildcardImport(), OptionalUnit()))
it("filters WildcardImport, runs OptionalUnit") {
val findings = ruleSet.accept(defaultFile, setOf("WildcardImport"))
Assertions.assertThat(findings).allMatch { it.id != "WildcardImport" }
Assertions.assertThat(findings).anySatisfy { it.id != "OptionalUnit" }
}
}
describe("MultiRule test cases") {
fun ruleSet() = loadRuleSet<EmptyCodeProvider>()
val ruleSetId = EmptyBlocks::class.java.simpleName
it("should filter by RuleSet id") {
assertThat(ruleSet().accept(emptyFile, setOf(ruleSetId))).isEmpty()
}
it("should filter EmptyInitBlock rule") {
val ruleIdToFilter = EmptyInitBlock::class.java.simpleName
assertThat(ruleSet().accept(emptyFile, setOf(ruleIdToFilter))).allMatch { it.id != ruleIdToFilter }
}
}
describe("Mix of MultiRule and normal Rule") {
it("should filter all rules") {
val ruleSet = RuleSet("Test", listOf(FileParsingRule(), OptionalUnit()))
assertThat(ruleSet.accept(emptyFile, setOf("MaxLineLength", "NoTabs", "OptionalUnit"))).isEmpty()
}
}
})
| apache-2.0 | 3b2469082d609a870c42cd1315d45514 | 34.779661 | 102 | 0.770251 | 3.736283 | false | true | false | false |
arturbosch/detekt | detekt-rules-naming/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/MemberNameEqualsClassNameSpec.kt | 1 | 11205 | package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment
import io.gitlab.arturbosch.detekt.test.TestConfig
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
private const val IGNORE_OVERRIDDEN = "ignoreOverridden"
class MemberNameEqualsClassNameSpec : Spek({
setupKotlinEnvironment()
val env: KotlinCoreEnvironment by memoized()
val subject by memoized { MemberNameEqualsClassName(Config.empty) }
describe("MemberNameEqualsClassName rule") {
val noIgnoreOverridden by memoized {
TestConfig(
mapOf(
IGNORE_OVERRIDDEN to "false"
)
)
}
context("some classes with methods which don't have the same name") {
it("does not report a nested function with the same name as the class") {
val code = """
class MethodNameNotEqualsClassName {
fun nestedFunction() {
fun MethodNameNotEqualsClassName() {}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report a function with same name in nested class") {
val code = """
class MethodNameNotEqualsClassName {
class NestedNameEqualsTopClassName {
fun MethodNameNotEqualsClassName() {}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
it("does not report a function with the same name as a companion object") {
val code = """
class StaticMethodNameEqualsObjectName {
companion object A {
fun A() {}
}
}
"""
assertThat(subject.compileAndLintWithContext(env, code)).isEmpty()
}
}
context("some classes with members which have the same name") {
it("reports a method which is named after the class") {
val code = """
class MethodNameEqualsClassName {
fun methodNameEqualsClassName() {}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).hasSize(1)
}
it("reports a method which is named after the object") {
val code = """
object MethodNameEqualsObjectName {
fun MethodNameEqualsObjectName() {}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).hasSize(1)
}
it("reports a property which is named after the class") {
val code = """
class PropertyNameEqualsClassName {
val propertyNameEqualsClassName = 0
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).hasSize(1)
}
it("reports a property which is named after the object") {
val code = """
object PropertyNameEqualsObjectName {
val propertyNameEqualsObjectName = 0
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).hasSize(1)
}
it("reports a companion object function which is named after the class") {
val code = """
class StaticMethodNameEqualsClassName {
companion object {
fun StaticMethodNameEqualsClassName() {}
}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).hasSize(1)
}
it("reports a method which is named after the class even when it's inside another one") {
val code = """
class MethodNameContainer {
class MethodNameEqualsNestedClassName {
fun MethodNameEqualsNestedClassName() {}
}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).hasSize(1)
}
it("doesn't report overridden methods which are named after the class") {
val code = """
class AbstractMethodNameEqualsClassName : BaseClassForMethodNameEqualsClassName() {
override fun AbstractMethodNameEqualsClassName() {}
}
abstract class BaseClassForMethodNameEqualsClassName {
abstract fun AbstractMethodNameEqualsClassName()
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).isEmpty()
}
it("doesn't report an methods which are named after the interface") {
val code = """
interface MethodNameEqualsInterfaceName {
fun MethodNameEqualsInterfaceName() {}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).isEmpty()
}
it("reports overridden methods which are named after the class if they are not ignored") {
val code = """
class AbstractMethodNameEqualsClassName : BaseClassForMethodNameEqualsClassName() {
override fun AbstractMethodNameEqualsClassName() {}
}
abstract class BaseClassForMethodNameEqualsClassName {
abstract fun AbstractMethodNameEqualsClassName()
}
"""
assertThat(MemberNameEqualsClassName(noIgnoreOverridden).compileAndLint(code)).hasSize(1)
}
it("doesn't report overridden properties which are named after the class") {
val code = """
class AbstractMethodNameEqualsClassName : BaseClassForMethodNameEqualsClassName() {
override val AbstractMethodNameEqualsClassName = ""
}
abstract class BaseClassForMethodNameEqualsClassName {
abstract val AbstractMethodNameEqualsClassName: String
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).isEmpty()
}
it("reports overridden properties which are named after the class if they are not ignored") {
val code = """
class AbstractMethodNameEqualsClassName : BaseClassForMethodNameEqualsClassName() {
override val AbstractMethodNameEqualsClassName = ""
}
abstract class BaseClassForMethodNameEqualsClassName {
abstract val AbstractMethodNameEqualsClassName: String
}
"""
assertThat(MemberNameEqualsClassName(noIgnoreOverridden).compileAndLint(code)).hasSize(1)
}
}
context("some companion object functions named after the class (factory functions)") {
it("reports a function which has no return type") {
val code = """
class WrongFactoryClass1 {
companion object {
fun wrongFactoryClass1() {}
}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).hasSize(1)
}
it("reports a function which has the wrong return type") {
val code = """
class WrongFactoryClass2 {
companion object {
fun wrongFactoryClass2(): Int {
return 0
}
}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLint(code)).hasSize(1)
}
it("reports a body-less function which has the wrong return type") {
val code = """
class WrongFactoryClass3 {
companion object {
fun wrongFactoryClass3() = 0
}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLintWithContext(env, code)).hasSize(1)
}
it("doesn't report a factory function") {
val code = """
open class A {
companion object {
fun a(condition: Boolean): A {
return if (condition) B() else C()
}
}
}
class B: A()
class C: A()
"""
assertThat(MemberNameEqualsClassName().compileAndLintWithContext(env, code)).isEmpty()
}
it("doesn't report a generic factory function") {
val code = """
data class GenericClass<T>(val wrapped: T) {
companion object {
fun <T> genericClass(wrapped: T): GenericClass<T> {
return GenericClass(wrapped)
}
fun genericClass(): GenericClass<String> {
return GenericClass("wrapped")
}
}
}
"""
assertThat(MemberNameEqualsClassName().compileAndLintWithContext(env, code)).isEmpty()
}
it("doesn't report a body-less factory function") {
val code = """
open class A {
companion object {
fun a(condition: Boolean) = if (condition) B() else C()
}
}
class B: A()
class C: A()
"""
assertThat(MemberNameEqualsClassName().compileAndLintWithContext(env, code)).isEmpty()
}
}
}
})
| apache-2.0 | 971c29edda351637e0b84e1c62bf620a | 39.894161 | 105 | 0.491388 | 6.673615 | false | false | false | false |
soniccat/android-taskmanager | taskmanager/src/main/java/com/example/alexeyglushkov/taskmanager/rx/SingleTask.kt | 1 | 919 | package com.example.alexeyglushkov.taskmanager.rx
import com.example.alexeyglushkov.taskmanager.task.TaskImpl
import org.junit.Assert
import java.util.concurrent.atomic.AtomicBoolean
import io.reactivex.Single
import io.reactivex.disposables.Disposable
import java.lang.Exception
class SingleTask<T>(private val single: Single<T>) : TaskImpl() {
var disposable: Disposable? = null
override suspend fun startTask() {
val finishedFlag = AtomicBoolean()
disposable = single.subscribe({ t ->
private.taskResult = t
finishedFlag.set(true)
}, { throwable ->
private.taskError = Exception(throwable)
finishedFlag.set(true)
})
Assert.assertTrue("SingleTask: Single must be a sync task", finishedFlag.get())
}
override fun cancelTask(info: Any?) {
super.cancelTask(info)
disposable?.dispose()
}
}
| mit | 76afc3aa1b04dbc27535cc6ac3e1869e | 27.71875 | 87 | 0.678999 | 4.397129 | false | false | false | false |
cout970/Magneticraft | ignore/test/gui/common/blocks/ContainerIcebox.kt | 2 | 1702 | package gui.common.blocks
import com.cout970.magneticraft.misc.network.IBD
import com.cout970.magneticraft.misc.tileentity.getTile
import com.cout970.magneticraft.tileentity.heat.TileIcebox
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraftforge.items.SlotItemHandler
/**
* Created by cout970 on 08/07/2016.
*/
class ContainerIcebox(player: EntityPlayer, world: World, blockPos: BlockPos) : ContainerBase(player, world, blockPos) {
val tile = world.getTile<TileIcebox>(blockPos)
init {
val inv = tile?.inventory
inv?.let { addSlotToContainer(SlotItemHandler(inv, 0, 129, 30)) }
bindPlayerInventory(player.inventory)
}
override fun sendDataToClient(): IBD? {
tile!!
val data = IBD()
data.setFloat(DATA_ID_BURNING_TIME, tile.meltingTime)
data.setFloat(DATA_ID_MAX_BURNING_TIME, tile.maxMeltingTime)
data.setFloat(DATA_ID_MAX_FREEZING_TIME, tile.maxFreezingTime)
data.setFloat(DATA_ID_FREEZING_TIME, tile.freezingTime)
data.setDouble(DATA_ID_MACHINE_HEAT, tile.heat.heat)
data.merge(tile.tank.getData())
return data
}
override fun receiveDataFromServer(ibd: IBD) {
tile!!
ibd.getFloat(DATA_ID_BURNING_TIME, { tile.meltingTime = it })
ibd.getFloat(DATA_ID_MAX_BURNING_TIME, { tile.maxMeltingTime = it })
ibd.getFloat(DATA_ID_FREEZING_TIME, { tile.freezingTime = it })
ibd.getFloat(DATA_ID_MAX_FREEZING_TIME, { tile.maxFreezingTime = it })
ibd.getDouble(DATA_ID_MACHINE_HEAT, { tile.heat.heat = it })
tile.tank.setData(ibd)
}
} | gpl-2.0 | 0e498669a0d5e62c4e994c9e3dd307e1 | 36.021739 | 120 | 0.697415 | 3.494867 | false | false | false | false |
nextcloud/android | app/src/main/java/com/nextcloud/client/database/entity/ExternalLinkEntity.kt | 1 | 1738 | /*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Entity(tableName = ProviderTableMeta.EXTERNAL_LINKS_TABLE_NAME)
data class ExternalLinkEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ProviderTableMeta._ID)
val id: Int?,
@ColumnInfo(name = ProviderTableMeta.EXTERNAL_LINKS_ICON_URL)
val iconUrl: String?,
@ColumnInfo(name = ProviderTableMeta.EXTERNAL_LINKS_LANGUAGE)
val language: String?,
@ColumnInfo(name = ProviderTableMeta.EXTERNAL_LINKS_TYPE)
val type: Int?,
@ColumnInfo(name = ProviderTableMeta.EXTERNAL_LINKS_NAME)
val name: String?,
@ColumnInfo(name = ProviderTableMeta.EXTERNAL_LINKS_URL)
val url: String?,
@ColumnInfo(name = ProviderTableMeta.EXTERNAL_LINKS_REDIRECT)
val redirect: Int?
)
| gpl-2.0 | b4c32ca92d908b69c5c833aee028fe33 | 35.93617 | 80 | 0.749424 | 4.223844 | false | false | false | false |
soywiz/korge | @old/korge-spriter/src/commonMain/kotlin/com/soywiz/korge/ext/spriter/com/brashmonkey/spriter/Calculator.kt | 1 | 6283 | package com.soywiz.korge.ext.spriter.com.brashmonkey.spriter
import com.soywiz.korio.*
import com.soywiz.korma.geom.*
import kotlin.math.*
/**
* A utility class which provides methods to calculate Spriter specific issues,
* like linear interpolation and rotation around a parent object.
* Other interpolation types are coming with the next releases of Spriter.
* @author Trixt0r
*/
object Calculator {
const val PI = kotlin.math.PI.toFloat()
const val NO_SOLUTION = -1f
/**
* Calculates the smallest difference between angle a and b.
* @param a first angle (in degrees)
* *
* @param b second angle (in degrees)
* *
* @return Smallest difference between a and b (between 180� and -180�).
*/
fun angleDifference(a: Float, b: Float): Float {
return ((a - b) % 360 + 540) % 360 - 180
}
/**
* @param x1 x coordinate of first point.
* *
* @param y1 y coordinate of first point.
* *
* @param x2 x coordinate of second point.
* *
* @param y2 y coordinate of second point.
* *
* @return Angle between the two given points.
*/
fun angleBetween(x1: Float, y1: Float, x2: Float, y2: Float): Float {
return Angle.degreesToRadians(atan2((y2 - y1).toDouble(), (x2 - x1).toDouble())).toFloat()
}
/**
* @param x1 x coordinate of first point.
* *
* @param y1 y coordinate of first point.
* *
* @param x2 x coordinate of second point.
* *
* @param y2 y coordinate of second point.
* *
* @return Distance between the two given points.
*/
fun distanceBetween(x1: Float, y1: Float, x2: Float, y2: Float): Float {
val xDiff = x2 - x1
val yDiff = y2 - y1
return sqrt(xDiff * xDiff + yDiff * yDiff)
}
/**
* Solves the equation a*x^3 + b*x^2 + c*x +d = 0.
* @param a
* *
* @param b
* *
* @param c
* *
* @param d
* *
* @return the solution of the cubic function if it belongs [0, 1], [.NO_SOLUTION] otherwise.
*/
fun solveCubic(a: Float, b: Float, c: Float, d: Float): Float {
var b = b
var c = c
var d = d
if (a == 0f) return solveQuadratic(b, c, d)
if (d == 0f) return 0f
b /= a
c /= a
d /= a
val squaredB = squared(b)
var q = (3f * c - squaredB) / 9f
val r = (-27f * d + b * (9f * c - 2f * squaredB)) / 54f
val disc = cubed(q) + squared(r)
val term1 = b / 3f
if (disc > 0) {
val sqrtDisc = sqrt(disc)
var s = r + sqrtDisc
s = if (s < 0) -cubicRoot(-s) else cubicRoot(s)
var t = r - sqrtDisc
t = if (t < 0) -cubicRoot(-t) else cubicRoot(t)
val result = -term1 + s + t
if (result in 0.0..1.0) return result
} else if (disc == 0f) {
val r13 = if (r < 0) -cubicRoot(-r) else cubicRoot(r)
var result = -term1 + 2f * r13
if (result in 0.0..1.0) return result
result = -(r13 + term1)
if (result in 0.0..1.0) return result
} else {
q = -q
var dum1 = q * q * q
dum1 = acos(r / sqrt(dum1))
val r13 = 2f * sqrt(q)
var result = -term1 + r13 * cos(dum1 / 3f)
if (result in 0.0..1.0) return result
result = -term1 + r13 * cos((dum1 + 2f * PI) / 3f)
if (result in 0.0..1.0) return result
result = -term1 + r13 * cos((dum1 + 4f * PI) / 3f)
if (result in 0.0..1.0) return result
}
return NO_SOLUTION
}
/**
* Solves the equation a*x^2 + b*x + c = 0
* @param a
* *
* @param b
* *
* @param c
* *
* @return the solution for the quadratic function if it belongs [0, 1], [.NO_SOLUTION] otherwise.
*/
fun solveQuadratic(a: Float, b: Float, c: Float): Float {
val squaredB = squared(b)
val twoA = 2 * a
val fourAC = 4f * a * c
val sqrt = sqrt(squaredB - fourAC)
var result = (-b + sqrt) / twoA
if (result >= 0 && result <= 1) return result
result = (-b - sqrt) / twoA
if (result >= 0 && result <= 1) return result
return NO_SOLUTION
}
/**
* Returns the square of the given value.
* @param f the value
* *
* @return the square of the value
*/
fun squared(f: Float): Float {
return f * f
}
/**
* Returns the cubed value of the given one.
* @param f the value
* *
* @return the cubed value
*/
fun cubed(f: Float): Float {
return f * f * f
}
/**
* Returns the cubic root of the given value.
* @param f the value
* *
* @return the cubic root
*/
fun cubicRoot(f: Float): Float {
return f.toDouble().pow((1f / 3f).toDouble()).toFloat()
}
/**
* Returns the square root of the given value.
* @param x the value
* *
* @return the square root
*/
fun sqrt(x: Float): Float {
return kotlin.math.sqrt(x.toDouble()).toFloat()
}
/**
* Returns the arc cosine at the given value.
* @param x the value
* *
* @return the arc cosine
*/
fun acos(x: Float): Float {
return kotlin.math.acos(x.toDouble()).toFloat()
}
private val SIN_BITS = 14 // 16KB. Adjust for accuracy.
private val SIN_MASK = (-1 shl SIN_BITS).inv()
private val SIN_COUNT = SIN_MASK + 1
private val radFull = PI * 2
private val degFull = 360f
private val radToIndex = SIN_COUNT / radFull
private val degToIndex = SIN_COUNT / degFull
/** multiply by this to convert from radians to degrees */
val radiansToDegrees = 180f / PI
val radDeg = radiansToDegrees
/** multiply by this to convert from degrees to radians */
val degreesToRadians = PI / 180
val degRad = degreesToRadians
private object Sin {
internal val table = FloatArray(SIN_COUNT).apply {
for (i in 0 until SIN_COUNT)
this[i] = kotlin.math.sin(((i + 0.5f) / SIN_COUNT * radFull).toDouble()).toFloat()
var i = 0
while (i < 360) {
this[(i * degToIndex).toInt() and SIN_MASK] =
kotlin.math.sin((i * degreesToRadians).toDouble()).toFloat()
i += 90
}
}
}
/** Returns the sine in radians from a lookup table. */
fun sin(radians: Float): Float {
return Sin.table[(radians * radToIndex).toInt() and SIN_MASK]
}
/** Returns the cosine in radians from a lookup table. */
fun cos(radians: Float): Float {
return Sin.table[((radians + PI / 2) * radToIndex).toInt() and SIN_MASK]
}
/** Returns the sine in radians from a lookup table. */
fun sinDeg(degrees: Float): Float {
return Sin.table[(degrees * degToIndex).toInt() and SIN_MASK]
}
/** Returns the cosine in radians from a lookup table. */
fun cosDeg(degrees: Float): Float {
return Sin.table[((degrees + 90) * degToIndex).toInt() and SIN_MASK]
}
}
| apache-2.0 | 4fcdb961f60d77aaec4adf7e5a6bedb1 | 24.015936 | 99 | 0.61634 | 2.878955 | false | false | false | false |
soywiz/korge | korge-spine/src/commonMain/kotlin/com/esotericsoftware/spine/Slot.kt | 1 | 5205 | /******************************************************************************
* Spine Runtimes License Agreement
* Last updated January 1, 2020. Replaces all prior versions.
*
* Copyright (c) 2013-2020, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES,
* BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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
* THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.esotericsoftware.spine
import com.soywiz.korim.color.RGBAf
import com.esotericsoftware.spine.Animation.DeformTimeline
import com.esotericsoftware.spine.attachments.Attachment
import com.esotericsoftware.spine.attachments.VertexAttachment
import com.soywiz.kds.*
/** Stores a slot's current pose. Slots organize attachments for [Skeleton.drawOrder] purposes and provide a place to store
* state for an attachment. State cannot be stored in an attachment itself because attachments are stateless and may be shared
* across multiple skeletons. */
class Slot {
/** The slot's setup pose data. */
val data: SlotData
/** The bone this slot belongs to. */
val bone: Bone
/** The color used to tint the slot's attachment. If [.getDarkColor] is set, this is used as the light color for two
* color tinting. */
val color = RGBAf()
/** The dark color used to tint the slot's attachment for two color tinting, or null if two color tinting is not used. The dark
* color's alpha is not used. */
val darkColor: RGBAf?
internal var attachment: Attachment? = null
private var attachmentTime: Float = 0.toFloat()
/** Values to deform the slot's attachment. For an unweighted mesh, the entries are local positions for each vertex. For a
* weighted mesh, the entries are an offset for each vertex which will be added to the mesh's local vertex positions.
*
*
* See [VertexAttachment.computeWorldVertices] and [DeformTimeline]. */
var deform: FloatArrayList = FloatArrayList()
internal var attachmentState: Int = 0
/** The skeleton this slot belongs to. */
val skeleton: Skeleton
get() = bone.skeleton
constructor(data: SlotData, bone: Bone) {
this.data = data
this.bone = bone
darkColor = if (data.darkColor == null) null else RGBAf()
setToSetupPose()
}
/** Copy constructor. */
constructor(slot: Slot, bone: Bone) {
data = slot.data
this.bone = bone
color.setTo(slot.color)
darkColor = if (slot.darkColor == null) null else RGBAf(slot.darkColor)
attachment = slot.attachment
attachmentTime = slot.attachmentTime
this.deform.add(slot.deform)
}
/** The current attachment for the slot, or null if the slot has no attachment. */
fun getAttachment(): Attachment? {
return attachment
}
/** Sets the slot's attachment and, if the attachment changed, resets [.attachmentTime] and clears [.deform].
* @param attachment May be null.
*/
fun setAttachment(attachment: Attachment?) {
if (this.attachment === attachment) return
this.attachment = attachment
attachmentTime = bone.skeleton.time
this.deform!!.clear()
}
/** The time that has elapsed since the last time the attachment was set or cleared. Relies on Skeleton
* [Skeleton.time]. */
fun getAttachmentTime(): Float {
return bone.skeleton.time - attachmentTime
}
fun setAttachmentTime(time: Float) {
attachmentTime = bone.skeleton.time - time
}
/** Sets this slot to the setup pose. */
fun setToSetupPose() {
color.setTo(data.color)
darkColor?.setTo(data.darkColor!!)
if (data.attachmentName == null)
setAttachment(null)
else {
attachment = null
setAttachment(bone.skeleton.getAttachment(data.index, data.attachmentName!!))
}
}
override fun toString(): String {
return data.name
}
}
| apache-2.0 | 96b81187d3a0189cc7c9901b0d669be6 | 39.038462 | 131 | 0.68684 | 4.51431 | false | false | false | false |
Haliucinas/kotlin-koans | src/i_introduction/_7_Nullable_Types/NullableTypes.kt | 1 | 1097 | package i_introduction._7_Nullable_Types
import util.TODO
import util.doc7
fun test() {
val s: String = "this variable cannot store null references"
val q: String? = null
if (q != null) q.length // you have to check to dereference
val i: Int? = q?.length // null
val j: Int = q?.length ?: 0 // 0
}
fun todoTask7(client: Client?, message: String?, mailer: Mailer): Nothing = TODO(
"""
Task 7.
Rewrite JavaCode7.sendMessageToClient in Kotlin, using only one 'if' expression.
Declarations of Client, PersonalInfo and Mailer are given below.
""",
documentation = doc7(),
references = { JavaCode7().sendMessageToClient(client, message, mailer) }
)
fun sendMessageToClient(client: Client?, message: String?, mailer: Mailer) {
if (client?.personalInfo?.email != null && message != null) {
mailer.sendMessage(client?.personalInfo?.email, message)
}
}
class Client (val personalInfo: PersonalInfo?)
class PersonalInfo (val email: String?)
interface Mailer {
fun sendMessage(email: String, message: String)
}
| mit | 5a6914af0abd66ba146f3beff3a67e70 | 29.472222 | 88 | 0.668186 | 3.989091 | false | false | false | false |
icapps/niddler-ui | niddler-ui/src/main/kotlin/com/icapps/niddler/ui/MainClass.kt | 1 | 2623 | package com.icapps.niddler.ui
import com.icapps.niddler.lib.utils.LoggerFactory
import com.icapps.niddler.ui.form.MainThreadDispatcher
import com.icapps.niddler.ui.form.NiddlerWindow
import com.icapps.niddler.ui.form.components.impl.SwingComponentsFactory
import com.icapps.niddler.ui.form.impl.SwingMainThreadDispatcher
import com.icapps.niddler.ui.form.impl.SwingNiddlerUserInterface
import com.icapps.niddler.ui.util.JavaLogFactory
import com.icapps.niddler.ui.util.SwingImageHelper
import com.icapps.niddler.ui.util.iconLoader
import java.awt.BorderLayout
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.util.logging.Level
import java.util.logging.LogRecord
import java.util.logging.Logger
import java.util.logging.SimpleFormatter
import java.util.logging.StreamHandler
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.WindowConstants
/**
* @author Nicola Verbeeck
* @date 10/11/16.
*/
fun main(args: Array<String>) {
initLogging(args)
MainThreadDispatcher.instance = SwingMainThreadDispatcher()
iconLoader = SwingImageHelper()
val factory = SwingComponentsFactory()
val ui = SwingNiddlerUserInterface(factory)
val window = NiddlerWindow(ui, emptyList())
val panel = JPanel(BorderLayout())
panel.add(ui.asComponent, BorderLayout.CENTER)
val frame = JFrame()
frame.add(panel)
frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
frame.pack()
frame.addWindowListener(object : WindowAdapter() {
override fun windowClosing(e: WindowEvent?) {
super.windowClosing(e)
window.onWindowInvisible()
}
override fun windowOpened(e: WindowEvent?) {
super.windowOpened(e)
window.onWindowVisible()
}
})
window.init()
frame.setSize(1300, 600)
frame.isVisible = true
}
private fun initLogging(args: Array<String>) {
if (args.contains("--log")) {
LoggerFactory.instance = JavaLogFactory(args.contains("--verbose"))
System.setProperty("java.util.logging.SimpleFormatter.format",
"%1\$tY-%1\$tm-%1\$td %1\$tH:%1\$tM:%1\$tS.%1\$tL %4$-7s [%3\$s] (%2\$s) %5\$s %6\$s%n")
val consoleHandler = object : StreamHandler(System.out, SimpleFormatter()) {
override fun publish(record: LogRecord?) {
super.publish(record)
flush()
}
}
consoleHandler.level = Level.FINEST
Logger.getLogger("com.icapps").apply {
level = Level.FINEST
addHandler(consoleHandler)
}
}
}
| apache-2.0 | dabe45e44ee11bec86b970d4c36921a2 | 30.22619 | 104 | 0.694243 | 4.010703 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/onthisday/OnThisDayCard.kt | 1 | 1880 | package org.wikipedia.feed.onthisday
import org.wikipedia.R
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.feed.model.CardType
import org.wikipedia.feed.model.WikiSiteCard
import org.wikipedia.feed.view.FeedAdapter
import org.wikipedia.util.DateUtil
import org.wikipedia.util.L10nUtil
import java.util.*
import java.util.concurrent.TimeUnit
class OnThisDayCard(events: List<OnThisDay.Event>, wiki: WikiSite, val age: Int) : WikiSiteCard(wiki) {
private val nextYear: Int
private val date: Calendar = DateUtil.getDefaultDateFor(age)
private val eventShownOnCard: OnThisDay.Event
var callback: FeedAdapter.Callback? = null
init {
var randomIndex = 0
if (events.size > 1) {
randomIndex = Random().nextInt(events.size - 1)
}
eventShownOnCard = events[randomIndex]
nextYear = events.getOrElse(randomIndex + 1) { eventShownOnCard }.year
}
override fun type(): CardType {
return CardType.ON_THIS_DAY
}
override fun title(): String {
return L10nUtil.getStringForArticleLanguage(wikiSite().languageCode, R.string.on_this_day_card_title)
}
override fun subtitle(): String {
return DateUtil.getFeedCardShortDateString(date)
}
override fun dismissHashCode(): Int {
return TimeUnit.MILLISECONDS.toDays(date.time.time).toInt() + wikiSite().hashCode()
}
fun footerActionText(): String {
return L10nUtil.getStringForArticleLanguage(wikiSite().languageCode, R.string.more_events_text)
}
fun text(): CharSequence {
return eventShownOnCard.text
}
fun year(): Int {
return eventShownOnCard.year
}
fun date(): Calendar {
return date
}
fun pages(): List<PageSummary>? {
return eventShownOnCard.pages()
}
}
| apache-2.0 | 87090702cbab597d5d5760b4e0b662d2 | 28.375 | 109 | 0.694681 | 4.168514 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/api/media/Domain.kt | 1 | 5974 | package pl.wendigo.chrome.api.media
/**
* This domain allows detailed inspection of media elements
*
* This API is marked as experimental in protocol definition and can change in the future.
* @link Protocol [Media](https://chromedevtools.github.io/devtools-protocol/tot/Media) domain documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
class MediaDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) :
pl.wendigo.chrome.protocol.Domain("Media", """This domain allows detailed inspection of media elements""", connection) {
/**
* Enables the Media domain
*
* @link Protocol [Media#enable](https://chromedevtools.github.io/devtools-protocol/tot/Media#method-enable) method documentation.
*/
fun enable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Media.enable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Disables the Media domain.
*
* @link Protocol [Media#disable](https://chromedevtools.github.io/devtools-protocol/tot/Media#method-disable) method documentation.
*/
fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Media.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* This can be called multiple times, and can be used to set / override /
remove player properties. A null propValue indicates removal.
*/
fun playerPropertiesChanged(): io.reactivex.rxjava3.core.Flowable<PlayerPropertiesChangedEvent> = connection.events("Media.playerPropertiesChanged", PlayerPropertiesChangedEvent.serializer())
/**
* Send events as a list, allowing them to be batched on the browser for less
congestion. If batched, events must ALWAYS be in chronological order.
*/
fun playerEventsAdded(): io.reactivex.rxjava3.core.Flowable<PlayerEventsAddedEvent> = connection.events("Media.playerEventsAdded", PlayerEventsAddedEvent.serializer())
/**
* Send a list of any messages that need to be delivered.
*/
fun playerMessagesLogged(): io.reactivex.rxjava3.core.Flowable<PlayerMessagesLoggedEvent> = connection.events("Media.playerMessagesLogged", PlayerMessagesLoggedEvent.serializer())
/**
* Send a list of any errors that need to be delivered.
*/
fun playerErrorsRaised(): io.reactivex.rxjava3.core.Flowable<PlayerErrorsRaisedEvent> = connection.events("Media.playerErrorsRaised", PlayerErrorsRaisedEvent.serializer())
/**
* Called whenever a player is created, or when a new agent joins and recieves
a list of active players. If an agent is restored, it will recieve the full
list of player ids and all events again.
*/
fun playersCreated(): io.reactivex.rxjava3.core.Flowable<PlayersCreatedEvent> = connection.events("Media.playersCreated", PlayersCreatedEvent.serializer())
}
/**
* This can be called multiple times, and can be used to set / override /
remove player properties. A null propValue indicates removal.
*
* @link [Media#playerPropertiesChanged](https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerPropertiesChanged) event documentation.
*/
@kotlinx.serialization.Serializable
data class PlayerPropertiesChangedEvent(
/**
*
*/
val playerId: PlayerId,
/**
*
*/
val properties: List<PlayerProperty>
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Media"
override fun eventName() = "playerPropertiesChanged"
}
/**
* Send events as a list, allowing them to be batched on the browser for less
congestion. If batched, events must ALWAYS be in chronological order.
*
* @link [Media#playerEventsAdded](https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerEventsAdded) event documentation.
*/
@kotlinx.serialization.Serializable
data class PlayerEventsAddedEvent(
/**
*
*/
val playerId: PlayerId,
/**
*
*/
val events: List<PlayerEvent>
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Media"
override fun eventName() = "playerEventsAdded"
}
/**
* Send a list of any messages that need to be delivered.
*
* @link [Media#playerMessagesLogged](https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerMessagesLogged) event documentation.
*/
@kotlinx.serialization.Serializable
data class PlayerMessagesLoggedEvent(
/**
*
*/
val playerId: PlayerId,
/**
*
*/
val messages: List<PlayerMessage>
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Media"
override fun eventName() = "playerMessagesLogged"
}
/**
* Send a list of any errors that need to be delivered.
*
* @link [Media#playerErrorsRaised](https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playerErrorsRaised) event documentation.
*/
@kotlinx.serialization.Serializable
data class PlayerErrorsRaisedEvent(
/**
*
*/
val playerId: PlayerId,
/**
*
*/
val errors: List<PlayerError>
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Media"
override fun eventName() = "playerErrorsRaised"
}
/**
* Called whenever a player is created, or when a new agent joins and recieves
a list of active players. If an agent is restored, it will recieve the full
list of player ids and all events again.
*
* @link [Media#playersCreated](https://chromedevtools.github.io/devtools-protocol/tot/Media#event-playersCreated) event documentation.
*/
@kotlinx.serialization.Serializable
data class PlayersCreatedEvent(
/**
*
*/
val players: List<PlayerId>
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Media"
override fun eventName() = "playersCreated"
}
| apache-2.0 | c441c5373735ebd4ca3b75ae65b70b76 | 35.206061 | 226 | 0.718949 | 4.261056 | false | false | false | false |
peterLaurence/TrekAdvisor | app/src/main/java/com/peterlaurence/trekme/core/map/maploader/MapLoader.kt | 1 | 13456 | package com.peterlaurence.trekme.core.map.maploader
import android.util.Log
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.peterlaurence.trekme.core.TrekMeContext
import com.peterlaurence.trekme.core.map.Map
import com.peterlaurence.trekme.core.map.MapArchive
import com.peterlaurence.trekme.core.map.TileStreamProvider
import com.peterlaurence.trekme.core.map.gson.*
import com.peterlaurence.trekme.core.map.mapimporter.MapImporter
import com.peterlaurence.trekme.core.map.maploader.events.MapListUpdateEvent
import com.peterlaurence.trekme.core.map.maploader.tasks.*
import com.peterlaurence.trekme.core.projection.MercatorProjection
import com.peterlaurence.trekme.core.projection.Projection
import com.peterlaurence.trekme.core.projection.UniversalTransverseMercator
import com.peterlaurence.trekme.model.providers.stream.TileStreamProviderDefault
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.io.IOException
import java.io.PrintWriter
import java.util.*
import kotlin.coroutines.resume
/**
* Singleton object that acts as central point for most operations related to the maps.
* It uses the following tasks defined in [com.peterlaurence.trekme.core.map.maploader.tasks]:
*
* * [mapCreationTask] -> create instances of [Map]
* * [MapDeleteTask] -> delete a [Map]
* * [MapMarkerImportTask] -> Import the markers of a [Map]
* * [mapRouteImportTask] -> Import the list of routes for a given [Map]
* * [MapArchiveSearchTask] -> Get the list of [MapArchive]
*
* @author peterLaurence -- converted to Kotlin on 16/02/2019
*/
object MapLoader : MapImporter.MapImportListener {
const val MAP_FILE_NAME = "map.json"
const val MAP_MARKER_FILE_NAME = "markers.json"
const val MAP_ROUTE_FILE_NAME = "routes.json"
const val MAP_LANDMARK_FILE_NAME = "landmarks.json"
/**
* All [Projection]s are registered here.
*/
@JvmStatic
private val PROJECTION_HASH_MAP = object : HashMap<String, Class<out Projection>>() {
init {
put(MercatorProjection.NAME, MercatorProjection::class.java)
put(UniversalTransverseMercator.NAME, UniversalTransverseMercator::class.java)
}
}
private const val TAG = "MapLoader"
private val mGson: Gson
private val mMapList: MutableList<Map> = mutableListOf()
private var mMapMarkerUpdateListener: MapMarkerUpdateListener? = null
/**
* Get a read-only list of [Map]s
*/
val maps: List<Map>
get() = mMapList.toList()
/**
* Create once for all the [Gson] object, that is used to serialize/deserialize json content.
* Register all [Projection] types, depending on their name.
*/
init {
val factory = RuntimeTypeAdapterFactory.of(
Projection::class.java, "projection_name")
for ((key, value) in PROJECTION_HASH_MAP) {
factory.registerSubtype(value, key)
}
mGson = GsonBuilder().serializeNulls().setPrettyPrinting().registerTypeAdapterFactory(factory).create()
}
/**
* Clears the internal list of [Map] : [mMapList].
*/
fun clearMaps() {
mMapList.clear()
}
private fun Map.addIfNew() {
if (this !in mMapList) {
mMapList.add(this)
}
}
/**
* Parses all [Map]s inside the provided list of directories, then updates the internal list of
* [Map] : [mMapList].
* It is intended to be the only public method of updating the [Map] list.
*
* @param dirs The directories in which to search for maps. If not specified, a default value is
* taken.
*/
suspend fun updateMaps(dirs: List<File> = listOf()): List<Map> {
val realDirs = if (dirs.isEmpty()) {
TrekMeContext.mapsDirList
} else {
dirs
} ?: return emptyList()
val maps = findMaps(realDirs)
/* Add the map only if it's indeed a new one */
maps.forEach {
it.addIfNew()
}
notifyMapListUpdateListeners()
return maps
}
/**
* Launches the search in background thread.
*
* @param dirs The directories in which to search for new maps.
*/
private suspend fun findMaps(dirs: List<File>) = withContext(Dispatchers.Default) {
mapCreationTask(mGson, *dirs.toTypedArray())
}
/**
* Launch a [MapMarkerImportTask] which reads the markers.json file.
*/
fun getMarkersForMap(map: Map) {
val mapMarkerImportTask = MapMarkerImportTask(mMapMarkerUpdateListener,
map, mGson)
mapMarkerImportTask.execute()
}
/**
* Launch a task which reads the routes.json file.
* The [mapRouteImportTask] is called off UI thread. Right after, on the calling thread (which
* should be the UI thread), the result (a nullable instance of [RouteGson]) is set on the [Map]
* given as parameter.
*/
suspend fun getRoutesForMap(map: Map) =
withContext(Dispatchers.Default) {
mapRouteImportTask(map, mGson)
}?.let { routeGson ->
map.routeGson = routeGson
}
/**
* Launch a task which reads the landmarks.json file.
* The [mapLandmarkImportTask] is called off UI thread. Right after, on the calling thread (which
* should be the UI thread), the result (a nullable instance of [LandmarkGson]) is set on the [Map]
* given as parameter.
*/
suspend fun getLandmarksForMap(map: Map) =
withContext(Dispatchers.Default) {
mapLandmarkImportTask(map, mGson)
}?.let { landmarkGson ->
map.landmarkGson = landmarkGson
}
/**
* Launch a task which gets the list of [MapArchive].
* It also shows how a java [Thread] can be wrapped inside a coroutine so that it can be used
* by Kotlin code.
*
* TODO: Remove this along with MapArchiveSearchTask class. This logic isn't used anymore.
*/
suspend fun getMapArchiveList(dirs: List<File>): List<MapArchive> = suspendCancellableCoroutine { cont ->
val task = MapArchiveSearchTask(dirs, object : MapArchiveListUpdateListener {
override fun onMapArchiveListUpdate(mapArchiveList: List<MapArchive>) {
cont.resume(mapArchiveList)
}
})
cont.invokeOnCancellation {
task.cancel()
}
task.start()
}
fun setMapMarkerUpdateListener(listener: MapMarkerUpdateListener) {
mMapMarkerUpdateListener = listener
}
fun clearMapMarkerUpdateListener() {
mMapMarkerUpdateListener = null
}
/**
* Add a [Map] to the internal list and generate the json file.
*/
fun addMap(map: Map) {
/* Set TileStreamProvider */
applyTileStreamProviderTo(map)
/* Add the map */
map.addIfNew()
/* Generate the json file */
saveMap(map)
/* Notify for view update */
notifyMapListUpdateListeners()
}
/**
* Add a [Map] to the internal list and generate the json file.
* This is typically called after an import, after a [Map] has been generated from a file
* structure.
*/
override fun onMapImported(map: Map?, status: MapImporter.MapParserStatus) {
if (map == null) return
addMap(map)
}
override fun onMapImportError(e: MapImporter.MapParseException?) {
Log.e(TAG, "Error while parsing a map")
if (e != null) {
Log.e(TAG, e.message, e)
}
}
/**
* Get a [Map] from its id.
*
* @return the [Map] or `null` if the given id is unknown.
*/
fun getMap(mapId: Int): Map? {
return mMapList.firstOrNull { it.id == mapId }
}
/**
* Save the content of a [Map], so the changes persist upon application restart. <br></br>
* Here, it writes to the corresponding json file.
*
*
* Then, call all registered [MapListUpdateListener].
*
* @param map The [Map] to save.
*/
fun saveMap(map: Map) {
val jsonString = mGson.toJson(map.mapGson)
val configFile = map.configFile
writeToFile(jsonString, configFile) {
Log.e(TAG, "Error while saving the map")
}
notifyMapListUpdateListeners()
}
/**
* Save the [MarkerGson] of a [Map], so the changes persist upon application restart.
* Here, it writes to the corresponding json file.
*
* @param map The [Map] to save.
*/
fun saveMarkers(map: Map) {
val jsonString = mGson.toJson(map.markerGson)
val markerFile = File(map.directory, MapLoader.MAP_MARKER_FILE_NAME)
writeToFile(jsonString, markerFile) {
Log.e(TAG, "Error while saving the markers")
}
}
/**
* Save the [LandmarkGson] of a [Map], so the changes persist upon application restart.
* @param map the [Map] to save.
*/
fun saveLandmarks(map: Map) {
val jsonString = mGson.toJson(map.landmarkGson)
val landmarkFile = File(map.directory, MapLoader.MAP_LANDMARK_FILE_NAME)
writeToFile(jsonString, landmarkFile) {
Log.e(TAG, "Error while saving the landmarks")
}
}
/**
* Save the [RouteGson] of a [Map], so the changes persist upon application restart.
* Here, it writes to the corresponding json file.
*
* @param map The [Map] to save.
*/
fun saveRoutes(map: Map) {
val jsonString = mGson.toJson(map.routeGson)
val routeFile = File(map.directory, MapLoader.MAP_ROUTE_FILE_NAME)
writeToFile(jsonString, routeFile) {
Log.e(TAG, "Error while saving the routes")
}
}
/**
* Delete a [Map]. Recursively deletes its directory.
*
* @param map The [Map] to delete.
*/
fun deleteMap(map: Map, listener: MapDeletedListener?) {
val mapDirectory = map.directory
mMapList.remove(map)
/* Notify for view update */
notifyMapListUpdateListeners()
/* Delete the map directory in a separate thread */
val mapDeleteTask = MapDeleteTask(mapDirectory)
mapDeleteTask.execute()
listener?.onMapDeleted()
}
/**
* Delete a [MarkerGson.Marker] from a [Map].
*/
fun deleteMarker(map: Map, marker: MarkerGson.Marker) {
val markerList = map.markers
markerList?.remove(marker)
saveMarkers(map)
}
/**
* Delete a [Landmark] from a [Map].
*/
fun deleteLandmark(map: Map, landmark: Landmark) {
map.landmarkGson.landmarks.remove(landmark)
saveLandmarks(map)
}
/**
* Mutate the [Projection] of a given [Map].
*
* @return true on success, false if something went wrong.
*/
fun mutateMapProjection(map: Map, projectionName: String): Boolean {
val projectionType = PROJECTION_HASH_MAP[projectionName]
try {
val projection = projectionType!!.newInstance()
map.projection = projection
} catch (e: InstantiationException) {
// wrong projection name
return false
} catch (e: IllegalAccessException) {
return false
}
return true
}
private fun notifyMapListUpdateListeners() {
EventBus.getDefault().post(MapListUpdateEvent(maps.isNotEmpty()))
}
enum class CALIBRATION_METHOD {
SIMPLE_2_POINTS,
CALIBRATION_3_POINTS,
CALIBRATION_4_POINTS,
UNKNOWN;
companion object {
fun fromCalibrationName(name: String?): CALIBRATION_METHOD {
if (name != null) {
for (method in CALIBRATION_METHOD.values()) {
if (name.equals(method.toString(), ignoreCase = true)) {
return method
}
}
}
return UNKNOWN
}
}
}
interface MapListUpdateListener {
fun onMapListUpdate(mapsFound: Boolean)
}
/**
* When a map's markers are retrieved from their json content, this listener is called.
*/
interface MapMarkerUpdateListener {
fun onMapMarkerUpdate()
}
interface MapArchiveListUpdateListener {
fun onMapArchiveListUpdate(mapArchiveList: List<MapArchive>)
}
interface MapDeletedListener {
fun onMapDeleted()
}
/**
* Assign a [TileStreamProvider] to a [Map], if the origin of the [Map] is known.
*/
fun applyTileStreamProviderTo(map: Map) {
when (map.origin) {
Map.MapOrigin.VIPS, Map.MapOrigin.IGN_LICENSED -> map.tileStreamProvider = TileStreamProviderDefault(map.directory, map.imageExtension)
Map.MapOrigin.UNDEFINED -> {
Log.e(TAG, "Unknown map origin ${map.origin}")
}
}
}
/**
* Utility method to write a [String] into a [File].
*/
private fun writeToFile(st: String, out: File, errCb: () -> Unit) {
try {
PrintWriter(out).use {
it.print(st)
}
} catch (e: IOException) {
errCb()
Log.e(TAG, e.message, e)
}
}
}
| gpl-3.0 | 6fe538c925c048806689e556d101a223 | 30.661176 | 147 | 0.622325 | 4.266328 | false | false | false | false |
AndroidX/androidx | glance/glance/src/test/kotlin/androidx/glance/CombinedGlanceModifierTest.kt | 3 | 2323 | /*
* 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.glance
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class CombinedGlanceModifierTest {
@Test
fun foldIn() {
assertThat(
testModifier.foldIn(listOf<Int>()) { lst, m ->
if (m is Element) lst + m.value else lst
}
).isEqualTo(listOf(1, 2, 3))
}
@Test
fun foldOut() {
assertThat(
testModifier.foldOut(listOf<Int>()) { m, lst ->
if (m is Element) lst + m.value else lst
}
).isEqualTo(listOf(3, 2, 1))
}
@Test
fun any() {
assertThat(testModifier.any { it == Element(1) }).isTrue()
assertThat(testModifier.any { it == Element(2) }).isTrue()
assertThat(testModifier.any { it == Element(3) }).isTrue()
assertThat(testModifier.any { it == Element(5) }).isFalse()
}
@Test
fun all() {
assertThat(testModifier.all { it is Element && it.value < 10 }).isTrue()
assertThat(testModifier.all { it is Element && it.value > 2 }).isFalse()
}
@Test
fun equals() {
assertThat(testModifier).isEqualTo(GlanceModifier.element(1).element(2).element(3))
assertThat(testModifier).isNotEqualTo(GlanceModifier.element(1).element(2).element(4))
assertThat(testModifier).isNotEqualTo(GlanceModifier.element(1).element(2))
assertThat(testModifier).isNotEqualTo(GlanceModifier)
}
private companion object {
val testModifier = GlanceModifier.element(1).element(2).element(3)
}
}
private data class Element(val value: Int) : GlanceModifier.Element
private fun GlanceModifier.element(value: Int) =
this.then(Element(value)) | apache-2.0 | 268e3f8a3cdb02cbb57722d7739ee92d | 32.2 | 94 | 0.650452 | 4.075439 | false | true | false | false |
androidx/androidx | glance/glance/src/androidMain/kotlin/androidx/glance/template/GalleryTemplateData.kt | 3 | 2227 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.template
/**
* The semantic data required to build Gallery Template layouts
*
* @param header The header of the template.
* @param mainTextBlock The head block for title, body, and other texts of the main gallery object.
* @param mainImageBlock The head block for an image of the main gallery object.
* @param mainActionBlock The head block for a list of action buttons for the main gallery object.
* @param galleryImageBlock The gallery block for a list of gallery images.
*/
class GalleryTemplateData(
val header: HeaderBlock? = null,
val mainTextBlock: TextBlock,
val mainImageBlock: ImageBlock,
val mainActionBlock: ActionBlock? = null,
val galleryImageBlock: ImageBlock,
) {
override fun hashCode(): Int {
var result = mainTextBlock.hashCode()
result = 31 * result + (header?.hashCode() ?: 0)
result = 31 * result + mainImageBlock.hashCode()
result = 31 * result + (mainActionBlock?.hashCode() ?: 0)
result = 31 * result + galleryImageBlock.hashCode()
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as GalleryTemplateData
if (header != other.header) return false
if (mainTextBlock != other.mainTextBlock) return false
if (mainImageBlock != other.mainImageBlock) return false
if (mainActionBlock != other.mainActionBlock) return false
if (galleryImageBlock != other.galleryImageBlock) return false
return true
}
}
| apache-2.0 | f4700e037ffb6b9b55b0b32c797b48d5 | 37.396552 | 99 | 0.701392 | 4.383858 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/psi/elements/ElmNullaryConstructorArgumentPattern.kt | 1 | 1683 | package org.elm.lang.core.psi.elements
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import org.elm.lang.core.psi.ElmPsiElementImpl
import org.elm.lang.core.psi.ElmUnionPatternChildTag
import org.elm.lang.core.resolve.ElmReferenceElement
import org.elm.lang.core.resolve.reference.ElmReference
import org.elm.lang.core.resolve.reference.ModuleNameQualifierReference
import org.elm.lang.core.resolve.reference.QualifiedConstructorReference
import org.elm.lang.core.resolve.reference.SimpleUnionConstructorReference
/**
* A pattern that matches a zero-parameter variant constructor when used as the argument to another
* variant constructor in a pattern.
*
* e.g. `Nothing` in `Just Nothing` when used as a function parameter or case pattern.
*/
class ElmNullaryConstructorArgumentPattern(node: ASTNode) : ElmPsiElementImpl(node), ElmReferenceElement, ElmUnionPatternChildTag {
/** The variant constructor */
val upperCaseQID: ElmUpperCaseQID
get() = findNotNullChildByClass(ElmUpperCaseQID::class.java)
override val referenceNameElement: PsiElement
get() = upperCaseQID.upperCaseIdentifierList.last()
override val referenceName: String
get() = referenceNameElement.text
override fun getReference(): ElmReference =
references.first()
override fun getReferences(): Array<ElmReference> =
if (upperCaseQID.isQualified)
arrayOf(QualifiedConstructorReference(this, upperCaseQID),
ModuleNameQualifierReference(this, upperCaseQID, upperCaseQID.qualifierPrefix))
else
arrayOf(SimpleUnionConstructorReference(this))
}
| mit | e440fad6278a99d89da86f15b9163b2a | 39.071429 | 131 | 0.759952 | 4.675 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/chat/prv/conference/info/ConferenceInfoActivity.kt | 1 | 1259 | package me.proxer.app.chat.prv.conference.info
import android.app.Activity
import android.os.Bundle
import androidx.fragment.app.commitNow
import me.proxer.app.R
import me.proxer.app.base.DrawerActivity
import me.proxer.app.chat.prv.LocalConference
import me.proxer.app.util.extension.getSafeParcelableExtra
import me.proxer.app.util.extension.startActivity
/**
* @author Ruben Gees
*/
class ConferenceInfoActivity : DrawerActivity() {
companion object {
private const val CONFERENCE_EXTRA = "conference"
fun navigateTo(context: Activity, conference: LocalConference) {
context.startActivity<ConferenceInfoActivity>(CONFERENCE_EXTRA to conference)
}
}
val conference: LocalConference
get() = intent.getSafeParcelableExtra(CONFERENCE_EXTRA)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar()
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, ConferenceInfoFragment.newInstance())
}
}
}
private fun setupToolbar() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = conference.topic
}
}
| gpl-3.0 | a44ca1ad6a636a8a5f9cac09e55cbd66 | 27.613636 | 89 | 0.708499 | 4.787072 | false | false | false | false |
adgvcxz/Diycode | app/src/main/java/com/adgvcxz/diycode/ui/main/home/HomeFragment.kt | 1 | 1975 | package com.adgvcxz.diycode.ui.main.home
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import com.adgvcxz.bindTo
import com.adgvcxz.diycode.R
import com.adgvcxz.diycode.databinding.FragmentHomeBinding
import com.adgvcxz.diycode.ui.base.BaseFragmentNew
import com.adgvcxz.diycode.ui.base.NewsFragment
import com.adgvcxz.diycode.ui.base.SitesFragment
import com.adgvcxz.diycode.ui.main.home.HomeFragmentViewModel.Model
import com.adgvcxz.diycode.ui.main.home.topic.TopicFragment
import com.adgvcxz.diycode.util.extensions.stringArr
import com.jakewharton.rxbinding2.support.v7.widget.navigationClicks
/**
* zhaowei
* Created by zhaowei on 2017/2/16.
*/
class HomeFragment : BaseFragmentNew<FragmentHomeBinding, HomeFragmentViewModel, Model>() {
override val layoutId: Int = R.layout.fragment_home
val fragments: Array<Fragment> = arrayOf(TopicFragment(), NewsFragment(), SitesFragment())
override fun inject() {
fragmentComponent.inject(this)
}
override fun initBinding() {
binding.viewPager.offscreenPageLimit = Math.ceil(fragments.size.toDouble() / 2).toInt()
binding.viewPager.adapter = HomeAdapter(childFragmentManager, fragments, R.array.home_tab_titles.stringArr)
binding.tabLayout.setupWithViewPager(binding.viewPager)
binding.toolbar.navigationClicks()
.map { HomeFragmentViewModel.Action.toolbarNavigationDidClicked }
.bindTo(this.viewModel.action)
}
inner class HomeAdapter(fm: FragmentManager,
private val fragments: Array<Fragment>,
private val titles: Array<String>): FragmentPagerAdapter(fm) {
override fun getCount(): Int = fragments.size
override fun getItem(position: Int): Fragment = fragments[position]
override fun getPageTitle(position: Int): CharSequence = titles[position]
}
}
| apache-2.0 | 2211cb4997423e49b29828f136596f8c | 36.980769 | 115 | 0.74481 | 4.359823 | false | false | false | false |
wax911/AniTrendApp | app/src/main/java/com/mxt/anitrend/view/activity/base/LoggingActivity.kt | 1 | 5666 | package com.mxt.anitrend.view.activity.base
import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.os.Environment
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.widget.AppCompatTextView
import androidx.appcompat.widget.Toolbar
import butterknife.BindView
import butterknife.ButterKnife
import butterknife.Unbinder
import com.mxt.anitrend.BuildConfig
import com.mxt.anitrend.R
import com.mxt.anitrend.base.custom.activity.ActivityBase
import com.mxt.anitrend.base.custom.view.text.SingleLineTextView
import com.mxt.anitrend.presenter.base.BasePresenter
import com.mxt.anitrend.util.KeyUtil
import com.mxt.anitrend.util.NotifyUtil
import com.nguyenhoanglam.progresslayout.ProgressLayout
import kotlinx.coroutines.*
import java.io.File
import java.io.FileWriter
import java.io.InputStreamReader
class LoggingActivity : ActivityBase<Void, BasePresenter>(), CoroutineScope by MainScope() {
@BindView(R.id.toolbar)
lateinit var toolbar: Toolbar
@BindView(R.id.report_display)
lateinit var reportLogTextView: AppCompatTextView
@BindView(R.id.application_version)
lateinit var applicationVersionTextView: SingleLineTextView
@BindView(R.id.stateLayout)
lateinit var progressLayout: ProgressLayout
private var binder: Unbinder? = null
private val log = StringBuilder()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_logging)
binder = ButterKnife.bind(this)
setSupportActionBar(toolbar)
}
override fun onPostCreate(savedInstanceState: Bundle?) {
super.onPostCreate(savedInstanceState)
applicationVersionTextView.text = getString(
R.string.text_about_appication_version,
BuildConfig.VERSION_NAME
)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.logging_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_save_log -> {
if (!progressLayout.isLoading) {
progressLayout.showLoading()
if (requestPermissionIfMissing(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
async (Dispatchers.IO) {
val root = File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS
),
"AniTrend Logcat.txt"
)
FileWriter(root).use {
it.write(log.toString())
}
withContext(Dispatchers.Main) {
progressLayout.showContent()
NotifyUtil.makeText(applicationContext, R.string.bug_report_saved, Toast.LENGTH_SHORT).show()
}
}.invokeOnCompletion {
it?.printStackTrace()
}
}
} else {
NotifyUtil.createAlerter(this,
R.string.title_activity_logging,
R.string.busy_please_wait,
R.drawable.ic_bug_report_grey_600_24dp,
R.color.colorStateBlue,
KeyUtil.DURATION_SHORT
)
}
}
R.id.action_share_log -> {
val intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, log.toString())
type = "text/plain"
}
startActivity(intent)
}
}
return super.onOptionsItemSelected(item)
}
/**
* Dispatch onResume() to fragments. Note that for better inter-operation
* with older versions of the platform, at the point of this call the
* fragments attached to the activity are *not* resumed. This means
* that in some cases the previous state may still be saved, not allowing
* fragment transactions that modify the state. To correctly interact
* with fragments in their proper state, you should instead override
* [.onResumeFragments].
*/
override fun onResume() {
super.onResume()
onActivityReady()
}
override fun onActivityReady() {
progressLayout.showLoading()
makeRequest()
}
override fun updateUI() {
progressLayout.showContent()
}
private fun printLog(logHistory: String) {
updateUI()
reportLogTextView.text = logHistory
}
override fun makeRequest() {
async (Dispatchers.IO) {
val process = Runtime.getRuntime().exec("logcat -d -v threadtime com.mxt.anitrend:*")
InputStreamReader(process.inputStream).use { inputStream ->
log.append(inputStream.readText())
.append("\n")
}
val logHistory = log.toString()
withContext(Dispatchers.Main) {
printLog(logHistory)
}
}.invokeOnCompletion {
it?.printStackTrace()
}
}
override fun onDestroy() {
super.onDestroy()
binder?.unbind()
cancel()
}
}
| lgpl-3.0 | 3f045a812c2697426a617d24552dc172 | 34.192547 | 125 | 0.58754 | 5.246296 | false | false | false | false |
felipebz/sonar-plsql | zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/ToCharInOrderByCheck.kt | 1 | 2491 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plugins.plsqlopen.api.DmlGrammar
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.annotations.*
import org.sonar.plugins.plsqlopen.api.matchers.MethodMatcher
import org.sonar.plugins.plsqlopen.api.symbols.PlSqlType
@Rule(priority = Priority.MAJOR, tags = [Tags.BUG])
@ConstantRemediation("5min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class ToCharInOrderByCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(DmlGrammar.ORDER_BY_ITEM)
}
override fun visitNode(node: AstNode) {
val expression = node.firstChild
if (toChar.matches(expression)) {
addIssue(node, getLocalizedMessage())
}
if (expression.type === PlSqlGrammar.LITERAL && semantic(expression).plSqlType === PlSqlType.NUMERIC) {
val index = Integer.parseInt(expression.tokenOriginalValue)
val selectExpression = node.getFirstAncestor(DmlGrammar.SELECT_EXPRESSION)
val queryBlock = selectExpression.getFirstChild(DmlGrammar.QUERY_BLOCK)
val columns = queryBlock.getChildren(DmlGrammar.SELECT_COLUMN)
if (columns.size >= index) {
val selectColumn = columns[index - 1].firstChild
if (toChar.matches(selectColumn)) {
addIssue(node, getLocalizedMessage())
}
}
}
}
companion object {
private val toChar = MethodMatcher.create().name("to_char").withNoParameterConstraint()
}
}
| lgpl-3.0 | b3e72186cc76277d2fafd6487a4b9f62 | 36.179104 | 111 | 0.703332 | 4.40885 | false | false | false | false |
Thuva4/Algorithms_Example | Greatest Common Divisor/Kotlin/EuclideanGCD.kt | 1 | 900 | /**
* Calculates the greatest common divisor of two natural numbers.
*
* @author Sarah Khan
*/
/**
* Calculates the greatest common divisor of two natural numbers using the Euclidean algorithm.
*
* @param num1 natural number
* @param num2 natural number
* @return the largest natural number that divides a and b without leaving a remainder
*/
fun gcd(num1: Int, num2: Int): Int {
var a = num1
var b = num2
while (b != 0) {
val temp = b
b = a % b
a = temp
}
return a
}
fun main(args: Array<String>) {
println(gcd(10, 5)) // gcd is 5
println(gcd(5, 10)) // gcd is 5
println(gcd(10, 8)) // gcd is 2
println(gcd(8, 2)) // gcd is 2
println(gcd(7000, 2000)) // gcd is 1000
println(gcd(2000, 7000)) // gcd is 1000
println(gcd(10, 11)) // gcd is 1
println(gcd(11, 7)) // gcd is 1
println(gcd(239, 293)) // gcd is 1
} | apache-2.0 | 1cef3e8efba697099df4b06fbfdd3560 | 24.742857 | 95 | 0.601111 | 3.135889 | false | true | false | false |
da1z/intellij-community | platform/platform-impl/src/com/intellij/reporting/Reporter.kt | 4 | 3292 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.reporting
import com.google.common.net.HttpHeaders
import com.google.gson.Gson
import com.intellij.openapi.application.PermanentInstallationID
import com.intellij.openapi.diagnostic.Logger
import org.apache.commons.codec.binary.Base64OutputStream
import org.apache.http.client.fluent.Request
import org.apache.http.entity.ContentType
import org.apache.http.message.BasicHeader
import java.io.ByteArrayOutputStream
import java.util.zip.GZIPOutputStream
private class StatsServerInfo(@JvmField var status: String,
@JvmField var url: String,
@JvmField var urlForZipBase64Content: String) {
fun isServiceAlive() = "ok" == status
}
private object Utils {
val gson = Gson()
}
object StatsSender {
private val infoUrl = "https://www.jetbrains.com/config/features-service-status.json"
private val LOG = Logger.getInstance(StatsSender::class.java)
private fun requestServerUrl(): StatsServerInfo? {
try {
val response = Request.Get(infoUrl).execute().returnContent().asString()
val info = Utils.gson.fromJson(response, StatsServerInfo::class.java)
if (info.isServiceAlive()) return info
}
catch (e: Exception) {
LOG.debug(e)
}
return null
}
fun send(text: String, compress: Boolean = true): Boolean {
val info = requestServerUrl() ?: return false
try {
val response = createRequest(info, text, compress).execute()
val code = response.handleResponse { it.statusLine.statusCode }
if (code in 200..299) {
return true
}
}
catch (e: Exception) {
LOG.debug(e)
}
return false
}
private fun createRequest(info: StatsServerInfo, text: String, compress: Boolean): Request {
if (compress) {
val data = Base64GzipCompressor.compress(text)
val request = Request.Post(info.urlForZipBase64Content).bodyByteArray(data)
request.addHeader(BasicHeader(HttpHeaders.CONTENT_ENCODING, "gzip"))
return request
}
return Request.Post(info.url).bodyString(text, ContentType.TEXT_HTML)
}
}
private object Base64GzipCompressor {
fun compress(text: String): ByteArray {
val outputStream = ByteArrayOutputStream()
val base64Stream = GZIPOutputStream(Base64OutputStream(outputStream))
base64Stream.write(text.toByteArray())
base64Stream.close()
return outputStream.toByteArray()
}
}
fun <T> createReportLine(recorderId: String, sessionId: String, data: T): String {
val json = Utils.gson.toJson(data)
val userUid = PermanentInstallationID.get()
val stamp = System.currentTimeMillis()
return "$stamp\t$recorderId\t$userUid\t$sessionId\t$json"
} | apache-2.0 | 7eba1eecfc76d90acdfafbb58e195414 | 31.93 | 94 | 0.717801 | 4.099626 | false | false | false | false |
GabrielCastro/open_otp | app/src/test/kotlin/ca/gabrielcastro/openotp/testutils/FakeDatabase.kt | 1 | 1400 | package ca.gabrielcastro.openotp.testutils
import ca.gabrielcastro.openotp.db.Database
import ca.gabrielcastro.openotp.model.Totp
import ca.gabrielcastro.openotp.rx.ioAndMain
import rx.Observable
import java.util.*
import javax.inject.Inject
class FakeDatabase @Inject constructor() : Database {
val items: MutableList<Totp> = arrayListOf(
Totp(issuer = "Google Inc.", accountName = "[email protected]", secret = "ABC".toByteArray()),
Totp(issuer = "iCloud", accountName = "[email protected]", secret = "DEF".toByteArray()),
Totp(issuer = "Steam", accountName = "gaben", secret = "GHI".toByteArray())
)
override fun list(): Observable<List<Totp>> {
return Observable.just(Collections.unmodifiableList(items))
.ioAndMain()
}
override fun findById(id: String): Observable<Totp?> {
return Observable.fromCallable {
val filtered = items.filter { it.uuid == id }
return@fromCallable filtered[0]
}
}
override fun add(totp: Totp): Observable<Unit> {
items.add(totp)
return Observable.just(Unit)
}
override fun update(id: String, newUserAccountName: String, newUserIssuer: String): Observable<Boolean> {
return Observable.just(false)
}
override fun delete(id: String): Observable<Boolean> {
return Observable.just(false)
}
}
| mit | a52327d0b02420cc2b99b258798a170b | 32.333333 | 109 | 0.66 | 4.191617 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_SUSPEND_V2.kt | 1 | 2039 | package info.nightscout.androidaps.diaconn.pumplog
import java.nio.ByteBuffer
import java.nio.ByteOrder
/*
* 일시정지 시작 (기저정지)
*/
class LOG_SUSPEND_V2 private constructor(
val data: String,
val dttm: String,
typeAndKind: Byte,
val batteryRemain: Byte, // 1=기본, 2=생활1, 3=생활2, 4=생활3, 5=닥터1, 6=닥터2
val patternType: Byte
) {
val type: Byte = PumplogUtil.getType(typeAndKind)
val kind: Byte = PumplogUtil.getKind(typeAndKind)
override fun toString(): String {
val sb = StringBuilder("LOG_SUSPEND_V2{")
sb.append("LOG_KIND=").append(LOG_KIND.toInt())
sb.append(", data='").append(data).append('\'')
sb.append(", dttm='").append(dttm).append('\'')
sb.append(", type=").append(type.toInt())
sb.append(", kind=").append(kind.toInt())
sb.append(", batteryRemain=").append(batteryRemain.toInt())
sb.append(", patternType=").append(patternType.toInt())
sb.append('}')
return sb.toString()
}
fun getBasalPattern(): String {
//1=Injection blockage, 2=Battery shortage, 3=Drug shortage, 4=User shutdown, 5=System reset, 6=Other, 7=Emergency shutdown
return when(patternType) {
1.toByte() -> "Base"
2.toByte() -> "Life1"
3.toByte() -> "Life2"
4.toByte() -> "Life3"
5.toByte() -> "Dr1"
6.toByte() -> "Dr2"
else -> "No Pattern"
}
}
companion object {
const val LOG_KIND: Byte = 0x03
fun parse(data: String): LOG_SUSPEND_V2 {
val bytes = PumplogUtil.hexStringToByteArray(data)
val buffer = ByteBuffer.wrap(bytes)
buffer.order(ByteOrder.LITTLE_ENDIAN)
return LOG_SUSPEND_V2(
data,
PumplogUtil.getDttm(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getByte(buffer)
)
}
}
} | agpl-3.0 | 6b17e7c85927e78f5ddd2d8ce205a150 | 30.68254 | 131 | 0.568922 | 3.701299 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt | 1 | 19257 | package info.nightscout.androidaps.plugins.general.maintenance
import android.Manifest
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.provider.Settings
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.work.*
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.DaggerAppCompatActivityWithResult
import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.UserEntry
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.diaconn.events.EventDiaconnG8PumpLogReset
import info.nightscout.androidaps.events.EventAppExit
import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.ImportExportPrefs
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.maintenance.formats.*
import info.nightscout.androidaps.utils.AndroidPermission
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.MidnightTime
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.alertDialogs.PrefImportSummaryDialog
import info.nightscout.androidaps.utils.alertDialogs.TwoMessagesAlertDialog
import info.nightscout.androidaps.utils.alertDialogs.WarningDialog
import info.nightscout.androidaps.interfaces.BuildHelper
import info.nightscout.androidaps.utils.protection.PasswordCheck
import info.nightscout.androidaps.utils.storage.Storage
import info.nightscout.androidaps.utils.userEntry.UserEntryPresentationHelper
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.system.exitProcess
/**
* Created by mike on 03.07.2016.
*/
@Singleton
class ImportExportPrefsImpl @Inject constructor(
private var log: AAPSLogger,
private val rh: ResourceHelper,
private val sp: SP,
private val buildHelper: BuildHelper,
private val rxBus: RxBus,
private val passwordCheck: PasswordCheck,
private val config: Config,
private val androidPermission: AndroidPermission,
private val encryptedPrefsFormat: EncryptedPrefsFormat,
private val prefFileList: PrefFileListProvider,
private val uel: UserEntryLogger,
private val dateUtil: DateUtil
) : ImportExportPrefs {
override fun prefsFileExists(): Boolean {
return prefFileList.listPreferenceFiles().size > 0
}
override fun exportSharedPreferences(f: Fragment) {
f.activity?.let { exportSharedPreferences(it) }
}
override fun verifyStoragePermissions(fragment: Fragment, onGranted: Runnable) {
fragment.context?.let { ctx ->
val permission = ContextCompat.checkSelfPermission(ctx, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
fragment.activity?.let {
androidPermission.askForPermission(it, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE))
}
} else onGranted.run()
}
}
private fun prepareMetadata(context: Context): Map<PrefsMetadataKey, PrefMetadata> {
val metadata: MutableMap<PrefsMetadataKey, PrefMetadata> = mutableMapOf()
metadata[PrefsMetadataKey.DEVICE_NAME] = PrefMetadata(detectUserName(context), PrefsStatus.OK)
metadata[PrefsMetadataKey.CREATED_AT] = PrefMetadata(dateUtil.toISOString(dateUtil.now()), PrefsStatus.OK)
metadata[PrefsMetadataKey.AAPS_VERSION] = PrefMetadata(BuildConfig.VERSION_NAME, PrefsStatus.OK)
metadata[PrefsMetadataKey.AAPS_FLAVOUR] = PrefMetadata(BuildConfig.FLAVOR, PrefsStatus.OK)
metadata[PrefsMetadataKey.DEVICE_MODEL] = PrefMetadata(config.currentDeviceModelString, PrefsStatus.OK)
metadata[PrefsMetadataKey.ENCRYPTION] = PrefMetadata("Enabled", PrefsStatus.OK)
return metadata
}
@Suppress("SpellCheckingInspection")
private fun detectUserName(context: Context): String {
// based on https://medium.com/@pribble88/how-to-get-an-android-device-nickname-4b4700b3068c
val n1 = Settings.System.getString(context.contentResolver, "bluetooth_name")
val n2 = Settings.Secure.getString(context.contentResolver, "bluetooth_name")
val n3 = try {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S || ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
(context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter?.name
} else null
} catch (e: Exception){
null
}
val n4 = Settings.System.getString(context.contentResolver, "device_name")
val n5 = Settings.Secure.getString(context.contentResolver, "lock_screen_owner_info")
val n6 = Settings.Global.getString(context.contentResolver, "device_name")
// name provided (hopefully) by user
val patientName = sp.getString(R.string.key_patient_name, "")
val defaultPatientName = rh.gs(R.string.patient_name_default)
// name we detect from OS
val systemName = n1 ?: n2 ?: n3 ?: n4 ?: n5 ?: n6 ?: defaultPatientName
return if (patientName.isNotEmpty() && patientName != defaultPatientName) patientName else systemName
}
private fun askForMasterPass(activity: FragmentActivity, @StringRes canceledMsg: Int, then: ((password: String) -> Unit)) {
passwordCheck.queryPassword(activity, R.string.master_password, R.string.key_master_password, { password ->
then(password)
}, {
ToastUtils.warnToast(activity, rh.gs(canceledMsg))
})
}
@Suppress("SameParameterValue")
private fun askForEncryptionPass(
activity: FragmentActivity, @StringRes canceledMsg: Int, @StringRes passwordName: Int, @StringRes passwordExplanation: Int?,
@StringRes passwordWarning: Int?, then: ((password: String) -> Unit)
) {
passwordCheck.queryAnyPassword(activity, passwordName, R.string.key_master_password, passwordExplanation, passwordWarning, { password ->
then(password)
}, {
ToastUtils.warnToast(activity, rh.gs(canceledMsg))
})
}
@Suppress("SameParameterValue")
private fun askForMasterPassIfNeeded(activity: FragmentActivity, @StringRes canceledMsg: Int, then: ((password: String) -> Unit)) {
askForMasterPass(activity, canceledMsg, then)
}
private fun assureMasterPasswordSet(activity: FragmentActivity, @StringRes wrongPwdTitle: Int): Boolean {
if (!sp.contains(R.string.key_master_password) || (sp.getString(R.string.key_master_password, "") == "")) {
WarningDialog.showWarning(activity,
rh.gs(wrongPwdTitle),
rh.gs(R.string.master_password_missing, rh.gs(R.string.configbuilder_general), rh.gs(R.string.protection)),
R.string.nav_preferences, {
val intent = Intent(activity, PreferencesActivity::class.java).apply {
putExtra("id", R.xml.pref_general)
}
activity.startActivity(intent)
})
return false
}
return true
}
private fun askToConfirmExport(activity: FragmentActivity, fileToExport: File, then: ((password: String) -> Unit)) {
if (!assureMasterPasswordSet(activity, R.string.nav_export)) return
TwoMessagesAlertDialog.showAlert(
activity, rh.gs(R.string.nav_export),
rh.gs(R.string.export_to) + " " + fileToExport.name + " ?",
rh.gs(R.string.password_preferences_encrypt_prompt), {
askForMasterPassIfNeeded(activity, R.string.preferences_export_canceled, then)
}, null, R.drawable.ic_header_export
)
}
private fun askToConfirmImport(activity: FragmentActivity, fileToImport: PrefsFile, then: ((password: String) -> Unit)) {
if (!assureMasterPasswordSet(activity, R.string.nav_import)) return
TwoMessagesAlertDialog.showAlert(
activity, rh.gs(R.string.nav_import),
rh.gs(R.string.import_from) + " " + fileToImport.name + " ?",
rh.gs(R.string.password_preferences_decrypt_prompt), {
askForMasterPass(activity, R.string.preferences_import_canceled, then)
}, null, R.drawable.ic_header_import
)
}
private fun promptForDecryptionPasswordIfNeeded(
activity: FragmentActivity, prefs: Prefs, importOk: Boolean,
format: PrefsFormat, importFile: PrefsFile, then: ((prefs: Prefs, importOk: Boolean) -> Unit)
) {
// current master password was not the one used for decryption, so we prompt for old password...
if (!importOk && (prefs.metadata[PrefsMetadataKey.ENCRYPTION]?.status == PrefsStatus.ERROR)) {
askForEncryptionPass(
activity, R.string.preferences_import_canceled, R.string.old_master_password,
R.string.different_password_used, R.string.master_password_will_be_replaced
) { password ->
// ...and use it to load & decrypt file again
val prefsReloaded = format.loadPreferences(importFile.file, password)
prefsReloaded.metadata = prefFileList.checkMetadata(prefsReloaded.metadata)
// import is OK when we do not have errors (warnings are allowed)
val importOkCheckedAgain = checkIfImportIsOk(prefsReloaded)
then(prefsReloaded, importOkCheckedAgain)
}
} else {
then(prefs, importOk)
}
}
private fun exportSharedPreferences(activity: FragmentActivity) {
prefFileList.ensureExportDirExists()
val newFile = prefFileList.newExportFile()
askToConfirmExport(activity, newFile) { password ->
try {
val entries: MutableMap<String, String> = mutableMapOf()
for ((key, value) in sp.getAll()) {
entries[key] = value.toString()
}
val prefs = Prefs(entries, prepareMetadata(activity))
encryptedPrefsFormat.savePreferences(newFile, prefs, password)
ToastUtils.okToast(activity, rh.gs(R.string.exported))
} catch (e: FileNotFoundException) {
ToastUtils.errorToast(activity, rh.gs(R.string.filenotfound) + " " + newFile)
log.error(LTag.CORE, "Unhandled exception", e)
} catch (e: IOException) {
ToastUtils.errorToast(activity, e.message)
log.error(LTag.CORE, "Unhandled exception", e)
} catch (e: PrefFileNotFoundError) {
ToastUtils.Long.errorToast(
activity, rh.gs(R.string.preferences_export_canceled)
+ "\n\n" + rh.gs(R.string.filenotfound)
+ ": " + e.message
+ "\n\n" + rh.gs(R.string.needstoragepermission)
)
log.error(LTag.CORE, "File system exception", e)
} catch (e: PrefIOError) {
ToastUtils.Long.errorToast(
activity, rh.gs(R.string.preferences_export_canceled)
+ "\n\n" + rh.gs(R.string.needstoragepermission)
+ ": " + e.message
)
log.error(LTag.CORE, "File system exception", e)
}
}
}
override fun importSharedPreferences(fragment: Fragment) {
fragment.activity?.let { fragmentAct ->
importSharedPreferences(fragmentAct)
}
}
override fun importSharedPreferences(activity: FragmentActivity) {
try {
if (activity is DaggerAppCompatActivityWithResult)
activity.callForPrefFile.launch(null)
} catch (e: IllegalArgumentException) {
// this exception happens on some early implementations of ActivityResult contracts
// when registered and called for the second time
ToastUtils.errorToast(activity, rh.gs(R.string.goto_main_try_again))
log.error(LTag.CORE, "Internal android framework exception", e)
}
}
override fun importSharedPreferences(activity: FragmentActivity, importFile: PrefsFile) {
askToConfirmImport(activity, importFile) { password ->
val format: PrefsFormat = encryptedPrefsFormat
try {
val prefsAttempted = format.loadPreferences(importFile.file, password)
prefsAttempted.metadata = prefFileList.checkMetadata(prefsAttempted.metadata)
// import is OK when we do not have errors (warnings are allowed)
val importOkAttempted = checkIfImportIsOk(prefsAttempted)
promptForDecryptionPasswordIfNeeded(activity, prefsAttempted, importOkAttempted, format, importFile) { prefs, importOk ->
// if at end we allow to import preferences
val importPossible = (importOk || buildHelper.isEngineeringMode()) && (prefs.values.isNotEmpty())
PrefImportSummaryDialog.showSummary(activity, importOk, importPossible, prefs, {
if (importPossible) {
sp.clear()
for ((key, value) in prefs.values) {
if (value == "true" || value == "false") {
sp.putBoolean(key, value.toBoolean())
} else {
sp.putString(key, value)
}
}
restartAppAfterImport(activity)
} else {
// for impossible imports it should not be called
ToastUtils.errorToast(activity, rh.gs(R.string.preferences_import_impossible))
}
})
}
} catch (e: PrefFileNotFoundError) {
ToastUtils.errorToast(activity, rh.gs(R.string.filenotfound) + " " + importFile)
log.error(LTag.CORE, "Unhandled exception", e)
} catch (e: PrefIOError) {
log.error(LTag.CORE, "Unhandled exception", e)
ToastUtils.errorToast(activity, e.message)
}
}
}
private fun checkIfImportIsOk(prefs: Prefs): Boolean {
var importOk = true
for ((_, value) in prefs.metadata) {
if (value.status == PrefsStatus.ERROR)
importOk = false
}
return importOk
}
private fun restartAppAfterImport(context: Context) {
rxBus.send(EventDiaconnG8PumpLogReset())
sp.putBoolean(R.string.key_setupwizard_processed, true)
OKDialog.show(context, rh.gs(R.string.setting_imported), rh.gs(R.string.restartingapp)) {
uel.log(Action.IMPORT_SETTINGS, Sources.Maintenance)
log.debug(LTag.CORE, "Exiting")
rxBus.send(EventAppExit())
if (context is AppCompatActivity) {
context.finish()
}
System.runFinalization()
exitProcess(0)
}
}
override fun exportUserEntriesCsv(activity: FragmentActivity) {
WorkManager.getInstance(activity).enqueueUniqueWork(
"export",
ExistingWorkPolicy.APPEND_OR_REPLACE,
OneTimeWorkRequest.Builder(CsvExportWorker::class.java).build()
)
}
class CsvExportWorker(
context: Context,
params: WorkerParameters
) : Worker(context, params) {
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var repository: AppRepository
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var prefFileList: PrefFileListProvider
@Inject lateinit var context: Context
@Inject lateinit var userEntryPresentationHelper: UserEntryPresentationHelper
@Inject lateinit var storage: Storage
init {
(context.applicationContext as HasAndroidInjector).androidInjector().inject(this)
}
override fun doWork(): Result {
val entries = repository.getUserEntryFilteredDataFromTime(MidnightTime.calc() - T.days(90).msecs()).blockingGet()
prefFileList.ensureExportDirExists()
val newFile = prefFileList.newExportCsvFile()
var ret = Result.success()
try {
saveCsv(newFile, entries)
ToastUtils.okToast(context, rh.gs(R.string.ue_exported))
} catch (e: FileNotFoundException) {
ToastUtils.errorToast(context, rh.gs(R.string.filenotfound) + " " + newFile)
aapsLogger.error(LTag.CORE, "Unhandled exception", e)
ret = Result.failure(workDataOf("Error" to "Error FileNotFoundException"))
} catch (e: IOException) {
ToastUtils.errorToast(context, e.message)
aapsLogger.error(LTag.CORE, "Unhandled exception", e)
ret = Result.failure(workDataOf("Error" to "Error IOException"))
}
return ret
}
private fun saveCsv(file: File, userEntries: List<UserEntry>) {
try {
val contents = userEntryPresentationHelper.userEntriesToCsv(userEntries)
storage.putFileContents(file, contents)
} catch (e: FileNotFoundException) {
throw PrefFileNotFoundError(file.absolutePath)
} catch (e: IOException) {
throw PrefIOError(file.absolutePath)
}
}
}
} | agpl-3.0 | 4fc453d7dfacde0d25c59787e4219ec8 | 44.961814 | 187 | 0.644908 | 4.831159 | false | false | false | false |
faruktoptas/news-mvp | app/src/main/java/me/toptas/rssreader/features/main/MainActivity.kt | 1 | 2037 | package me.toptas.rssreader.features.main
import android.os.Bundle
import android.support.design.widget.TabLayout
import kotlinx.android.synthetic.main.activity_main.*
import me.toptas.rssconverter.RssItem
import me.toptas.rssreader.R
import me.toptas.rssreader.base.BaseActivity
import me.toptas.rssreader.di.ActivityComponent
import me.toptas.rssreader.features.chrome.ChromeTabsWrapper
import me.toptas.rssreader.features.rss.RssFragment
import me.toptas.rssreader.features.rss.RssFragmentAdapter
import me.toptas.rssreader.model.Feed
import javax.inject.Inject
class MainActivity : BaseActivity(), MainContract.View, RssFragment.OnItemSelectListener {
@Inject
lateinit var presenter: MainContract.Presenter
private lateinit var wrapper: ChromeTabsWrapper
override val layoutResource = R.layout.activity_main
override fun inject(component: ActivityComponent) {
component.inject(this)
}
override fun init(state: Bundle?) {
setSupportActionBar(toolbar)
tablayout.setupWithViewPager(viewPager)
tablayout.tabMode = TabLayout.MODE_SCROLLABLE
presenter.attach(this)
presenter.loadRssFragments()
wrapper = ChromeTabsWrapper(this)
}
override fun onLoadRssFragments(feeds: List<Feed>) {
val fragmentList = ArrayList<RssFragment>()
val titles = ArrayList<String>()
for (feed in feeds) {
fragmentList.add(RssFragment.newInstance(feed))
titles.add(feed.title)
}
val adapter = RssFragmentAdapter(supportFragmentManager, fragmentList, titles)
viewPager.adapter = adapter
}
override fun onItemSelected(rssItem: RssItem) {
wrapper.openCustomtab(rssItem.link)
}
override fun onStart() {
super.onStart()
wrapper.bindCustomTabsService()
}
override fun onStop() {
super.onStop()
wrapper.unbindCustomTabsService()
}
override fun onDestroy() {
super.onDestroy()
presenter.detach()
}
}
| apache-2.0 | 86ba94f75243b9671aac0417ee69be03 | 28.1 | 90 | 0.715268 | 4.587838 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/lessons-data/src/main/java/app/ss/lessons/data/repository/media/VideoDataSource.kt | 1 | 4361 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package app.ss.lessons.data.repository.media
import app.ss.lessons.data.api.SSMediaApi
import app.ss.lessons.data.model.api.VideosInfoModel
import app.ss.lessons.data.repository.DataSource
import app.ss.lessons.data.repository.DataSourceMediator
import app.ss.lessons.data.repository.LocalDataSource
import app.ss.models.media.SSVideosInfo
import app.ss.storage.db.dao.VideoInfoDao
import app.ss.storage.db.entity.VideoInfoEntity
import com.cryart.sabbathschool.core.extensions.connectivity.ConnectivityHelper
import com.cryart.sabbathschool.core.extensions.coroutines.DispatcherProvider
import com.cryart.sabbathschool.core.response.Resource
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
internal class VideoDataSource @Inject constructor(
private val mediaApi: SSMediaApi,
private val videoInfoDao: VideoInfoDao,
dispatcherProvider: DispatcherProvider,
connectivityHelper: ConnectivityHelper
) : DataSourceMediator<SSVideosInfo, VideoDataSource.Request>(
dispatcherProvider = dispatcherProvider,
connectivityHelper = connectivityHelper
) {
data class Request(val lessonIndex: String)
override val cache: LocalDataSource<SSVideosInfo, Request> = object : LocalDataSource<SSVideosInfo, Request> {
override suspend fun get(request: Request): Resource<List<SSVideosInfo>> {
val data = request.lessonIndex.toMediaRequest()?.let { ssMediaRequest ->
videoInfoDao.get("${ssMediaRequest.language}-${ssMediaRequest.quarterlyId}")
} ?: emptyList()
return if (data.isNotEmpty()) Resource.success(data.map { it.toModel() }) else Resource.loading()
}
override suspend fun update(request: Request, data: List<SSVideosInfo>) {
request.lessonIndex.toMediaRequest()?.let { ssMediaRequest ->
videoInfoDao.delete("${ssMediaRequest.language}-${ssMediaRequest.quarterlyId}")
}
videoInfoDao.insertAll(data.map { it.toEntity() })
}
}
override val network: DataSource<SSVideosInfo, Request> = object : DataSource<SSVideosInfo, Request> {
override suspend fun get(request: Request): Resource<List<SSVideosInfo>> {
val data = request.lessonIndex.toMediaRequest()?.let { ssMediaRequest ->
val lessonIndex = "${ssMediaRequest.language}-${ssMediaRequest.quarterlyId}"
val videos = mediaApi.getVideo(ssMediaRequest.language, ssMediaRequest.quarterlyId).body()
videos?.mapIndexed { index, model ->
model.toModel("$lessonIndex-$index", lessonIndex)
}
} ?: emptyList()
return Resource.success(data)
}
}
}
private fun VideoInfoEntity.toModel(): SSVideosInfo = SSVideosInfo(
id = id,
artist = artist,
clips = clips,
lessonIndex = lessonIndex
)
private fun VideosInfoModel.toModel(
id: String,
lessonIndex: String
): SSVideosInfo = SSVideosInfo(
id = id,
artist = artist,
clips = clips,
lessonIndex = lessonIndex
)
private fun SSVideosInfo.toEntity(): VideoInfoEntity = VideoInfoEntity(
id = id,
artist = artist,
clips = clips,
lessonIndex = lessonIndex
)
| mit | b12317ddc82feb8bb67d733272420942 | 40.533333 | 114 | 0.722311 | 4.482014 | false | false | false | false |
bluelinelabs/Conductor | demo/src/main/java/com/bluelinelabs/conductor/demo/controllers/ViewPagerController.kt | 1 | 1859 | package com.bluelinelabs.conductor.demo.controllers
import android.view.View
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Router
import com.bluelinelabs.conductor.RouterTransaction.Companion.with
import com.bluelinelabs.conductor.demo.R
import com.bluelinelabs.conductor.demo.controllers.base.BaseController
import com.bluelinelabs.conductor.demo.databinding.ControllerViewPagerBinding
import com.bluelinelabs.conductor.demo.util.viewBinding
import com.bluelinelabs.conductor.viewpager.RouterPagerAdapter
import java.util.*
class ViewPagerController : BaseController(R.layout.controller_view_pager) {
private val binding: ControllerViewPagerBinding by viewBinding(ControllerViewPagerBinding::bind)
override val title = "ViewPager Demo"
private val pageColors = intArrayOf(R.color.green_300, R.color.cyan_300, R.color.deep_purple_300, R.color.lime_300, R.color.red_300)
private val pagerAdapter = object : RouterPagerAdapter(this) {
override fun configureRouter(router: Router, position: Int) {
if (!router.hasRootController()) {
val page: Controller = ChildController(
title = String.format(Locale.getDefault(), "Child #%d (Swipe to see more)", position),
backgroundColor = pageColors[position],
colorIsResId = true
)
router.setRoot(with(page))
}
}
override fun getCount() = pageColors.size
override fun getPageTitle(position: Int) = "Page $position"
}
override fun onViewCreated(view: View) {
binding.viewPager.adapter = pagerAdapter
binding.tabLayout.setupWithViewPager(binding.viewPager)
}
override fun onDestroyView(view: View) {
if (!activity!!.isChangingConfigurations) {
binding.viewPager.adapter = null
}
binding.tabLayout.setupWithViewPager(null)
super.onDestroyView(view)
}
}
| apache-2.0 | b6245719896d05c3db0a13bf25d22128 | 36.18 | 134 | 0.757396 | 4.415677 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/base/fir/analysis-api-providers/test/org/jetbrains/kotlin/idea/fir/analysis/providers/trackers/KotlinModuleOutOfBlockTrackerTest.kt | 3 | 7983 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.fir.analysis.providers.trackers
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.testFramework.PsiTestUtil
import junit.framework.Assert
import org.jetbrains.kotlin.analysis.providers.createModuleWithoutDependenciesOutOfBlockModificationTracker
import org.jetbrains.kotlin.analysis.providers.createProjectWideOutOfBlockModificationTracker
import org.jetbrains.kotlin.idea.base.projectStructure.getMainKtSourceModule
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.util.sourceRoots
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtPsiFactory
import java.io.File
import java.nio.file.Files
import kotlin.io.path.writeText
class KotlinModuleOutOfBlockTrackerTest : AbstractMultiModuleTest() {
override fun getTestDataDirectory(): File = error("Should not be called")
fun testThatModuleOutOfBlockChangeInfluenceOnlySingleModule() {
val moduleA = createModuleWithModificationTracker("a") {
listOf(
FileWithText("main.kt", "fun main() = 10")
)
}
val moduleB = createModuleWithModificationTracker("b")
val moduleC = createModuleWithModificationTracker("c")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val moduleCWithTracker = ModuleWithModificationTracker(moduleC)
moduleA.typeInFunctionBody("main.kt", textAfterTyping = "fun main() = hello10")
Assert.assertTrue(
"Out of block modification count for module A with out of block should change after typing, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module B without out of block should not change after typing, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module C without out of block should not change after typing, modification count is ${moduleCWithTracker.modificationCount}",
moduleCWithTracker.changed()
)
}
fun testThatInEveryModuleOutOfBlockWillHappenAfterContentRootChange() {
val moduleA = createModuleWithModificationTracker("a")
val moduleB = createModuleWithModificationTracker("b")
val moduleC = createModuleWithModificationTracker("c")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val moduleCWithTracker = ModuleWithModificationTracker(moduleC)
runWriteAction {
moduleA.sourceRoots.first().createChildData(/* requestor = */ null, "file.kt")
}
Assert.assertTrue(
"Out of block modification count for module A should change after content root change, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertTrue(
"Out of block modification count for module B should change after content root change, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertTrue(
"Out of block modification count for module C should change after content root change modification count is ${moduleCWithTracker.modificationCount}",
moduleCWithTracker.changed()
)
}
fun testThatNonPhysicalFileChangeNotCausingBOOM() {
val moduleA = createModuleWithModificationTracker("a") {
listOf(
FileWithText("main.kt", "fun main() {}")
)
}
val moduleB = createModuleWithModificationTracker("b")
val moduleAWithTracker = ModuleWithModificationTracker(moduleA)
val moduleBWithTracker = ModuleWithModificationTracker(moduleB)
val projectWithModificationTracker = ProjectWithModificationTracker(project)
runWriteAction {
val nonPhysicalPsi = KtPsiFactory(moduleA.project).createFile("nonPhysical", "val a = c")
nonPhysicalPsi.add(KtPsiFactory(moduleA.project).createFunction("fun x(){}"))
}
Assert.assertFalse(
"Out of block modification count for module A should not change after non physical file change, modification count is ${moduleAWithTracker.modificationCount}",
moduleAWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for module B should not change after non physical file change, modification count is ${moduleBWithTracker.modificationCount}",
moduleBWithTracker.changed()
)
Assert.assertFalse(
"Out of block modification count for project should not change after non physical file change, modification count is ${projectWithModificationTracker.modificationCount}",
projectWithModificationTracker.changed()
)
}
private fun Module.typeInFunctionBody(fileName: String, textAfterTyping: String) {
val file = "${sourceRoots.first().url}/$fileName"
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(file)!!
val ktFile = PsiManager.getInstance(project).findFile(virtualFile) as KtFile
configureByExistingFile(virtualFile)
val singleFunction = ktFile.declarations.single() as KtNamedFunction
editor.caretModel.moveToOffset(singleFunction.bodyExpression!!.textOffset)
type("hello")
PsiDocumentManager.getInstance(project).commitAllDocuments()
Assert.assertEquals(textAfterTyping, ktFile.text)
}
private fun createModuleWithModificationTracker(
name: String,
createFiles: () -> List<FileWithText> = { emptyList() },
): Module {
val tmpDir = createTempDirectory().toPath()
createFiles().forEach { file ->
Files.createFile(tmpDir.resolve(file.name)).writeText(file.text)
}
val module: Module = createModule("$tmpDir/$name", moduleType)
val root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tmpDir.toFile())!!
WriteCommandAction.writeCommandAction(module.project).run<RuntimeException> {
root.refresh(false, true)
}
PsiTestUtil.addSourceContentToRoots(module, root)
return module
}
private data class FileWithText(val name: String, val text: String)
abstract class WithModificationTracker(protected val modificationTracker: ModificationTracker) {
private val initialModificationCount = modificationTracker.modificationCount
val modificationCount: Long get() = modificationTracker.modificationCount
fun changed(): Boolean =
modificationTracker.modificationCount != initialModificationCount
}
private class ModuleWithModificationTracker(module: Module) : WithModificationTracker(
module.getMainKtSourceModule()!!.createModuleWithoutDependenciesOutOfBlockModificationTracker(module.project)
)
private class ProjectWithModificationTracker(project: Project) : WithModificationTracker(
project.createProjectWideOutOfBlockModificationTracker()
)
} | apache-2.0 | 6163247c514c22f08db4231e9fbcd33a | 45.690058 | 182 | 0.730177 | 5.887168 | false | true | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/module/api/ModuleNetWebApiContext.kt | 1 | 1439 | package com.bajdcc.LALR1.interpret.module.api
import com.bajdcc.LALR1.grammar.runtime.RuntimeObject
import com.bajdcc.LALR1.grammar.runtime.data.RuntimeMap
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
/**
* 【模块】API请求上下文
*
* @author bajdcc
*/
class ModuleNetWebApiContext() {
private var sem: Semaphore? = null // 多线程同步只能用信号量
var req = RuntimeMap()
var resp = RuntimeObject(null)
init {
req.put("__ctx__", RuntimeObject(this))
req.put("resp", RuntimeObject(null))
}
constructor(route: String) : this() {
req.put("route", RuntimeObject(route))
}
constructor(route: String, params: Map<String, String>?) : this(route) {
params?.forEach { key, value -> req.put(key, RuntimeObject(value)) }
}
fun block(): Boolean {
sem = Semaphore(0)
try {
if (!sem!!.tryAcquire(3, TimeUnit.SECONDS)) {
throw TimeoutException("Timed out.")
}
return true
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
fun unblock() {
try {
while (sem == null) {
Thread.sleep(100)
}
} catch (e: InterruptedException) {
e.printStackTrace()
}
sem!!.release()
}
}
| mit | 5a241519e27d509c94515089b47c04a1 | 22.711864 | 76 | 0.5797 | 4.114706 | false | false | false | false |
mutcianm/android-dsl | src/ru/ifmo/rain/adsl/ClassTree.kt | 2 | 3963 | package ru.ifmo.rain.adsl
import java.util.ArrayList
import org.objectweb.asm.tree.ClassNode
import java.util.Queue
import java.util.ArrayDeque
class NoSuchClassException : Exception()
class ClassTreeNode(parent: ClassTreeNode?, data: ClassNode) {
var parent = parent
var children: MutableList<ClassTreeNode> = ArrayList()
var data = data
}
class ClassTree : Iterable<ClassNode>{
private val root = ClassTreeNode(null, ClassNode())
override fun iterator(): ClassTreeIterator {
return ClassTreeIterator(root)
}
public fun add(_class: ClassNode) {
val parent = findNode(root, _class.superName)
val newNode: ClassTreeNode
val orphans = getOrphansOf(_class.name!!)
if (parent != null) {
newNode = ClassTreeNode(parent, _class)
parent.children.add(newNode)
} else {
newNode = ClassTreeNode(root, _class)
root.children.add(newNode)
}
newNode.children.addAll(orphans)
orphans.forEach { it.parent = newNode }
}
public fun isChildOf(_class: ClassNode, ancestorName: String): Boolean {
val treeNode = findNode(root, _class)
if (treeNode == null)
throw NoSuchClassException()
return treeNode.parent?.data?.name == ancestorName
}
public fun isSuccessorOf(_class: ClassNode, ancestorName: String): Boolean {
val parent = findNode(ancestorName)
if (parent == null)
throw NoSuchClassException()
val child = findNode(parent, _class.name!!)
if ((child == null) || (child == parent))
return false
else
return true
}
private fun findParentIf(node: ClassTreeNode, f: (ClassTreeNode) -> Boolean ): ClassTreeNode? {
var n = node
while (n != root) {
if (f(n)) return n
n = n.parent!!
}
return null
}
private fun anyParentIf(node: ClassTreeNode, f: (ClassTreeNode) -> Boolean ): Boolean {
return findParentIf(node, f) != null
}
public fun findParentWithProperty(_class: ClassNode, property: String): ClassNode? {
val node = findNode(root, _class)
if (node == null)
throw NoSuchClassException()
return findParentIf(node, { it.data.methods!!.any { it.isProperty(property) } })?.data
}
private fun getOrphansOf(parentClassName: String): List<ClassTreeNode> {
val res = root.children.partition { it.data.superName == parentClassName }
root.children = res.second as MutableList<ClassTreeNode>
return res.first
}
private fun findChildByName(parent: ClassTreeNode, childName: String): Boolean {
return parent.children.any { it.data.name == childName }
}
private fun findNode(node: ClassTreeNode, name: String?): ClassTreeNode? {
if (name == null) return null
for (child in node.children) {
if (child.data.name == name) {
return child
} else {
val ret = findNode(child, name)
if (ret != null)
return ret
}
}
return null
}
public fun findNode(name: String?): ClassTreeNode? {
return findNode(root, name)
}
public fun findNode(_class: ClassNode): ClassTreeNode? {
return findNode(root, _class.name)
}
private fun findNode(node: ClassTreeNode, _class: ClassNode): ClassTreeNode? {
return findNode(node, _class.name)
}
}
class ClassTreeIterator(var next: ClassTreeNode) : Iterator<ClassNode> {
var nodeQueue: Queue<ClassTreeNode> = ArrayDeque(next.children)
override fun next(): ClassNode {
val node: ClassTreeNode = nodeQueue.element()
nodeQueue.remove()
nodeQueue.addAll(node.children);
return node.data
}
override fun hasNext(): Boolean {
return !nodeQueue.isEmpty()
}
} | apache-2.0 | c0b9e136b92628639611192c273b0f58 | 29.96875 | 99 | 0.615948 | 4.513667 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/FinalFieldsEntityImpl.kt | 1 | 7873 | // 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.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.deft.api.annotations.Default
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class FinalFieldsEntityImpl : FinalFieldsEntity, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
@JvmField
var _descriptor: AnotherDataClass? = null
override val descriptor: AnotherDataClass
get() = _descriptor!!
override var description: String = super<FinalFieldsEntity>.description
override var anotherVersion: Int = super<FinalFieldsEntity>.anotherVersion
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: FinalFieldsEntityData?) : ModifiableWorkspaceEntityBase<FinalFieldsEntity>(), FinalFieldsEntity.Builder {
constructor() : this(FinalFieldsEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity FinalFieldsEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field WorkspaceEntity#entitySource should be initialized")
}
if (!getEntityData().isDescriptorInitialized()) {
error("Field FinalFieldsEntity#descriptor should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
// Relabeling code, move information from dataSource to this builder
override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) {
dataSource as FinalFieldsEntity
this.entitySource = dataSource.entitySource
this.descriptor = dataSource.descriptor
this.description = dataSource.description
this.anotherVersion = dataSource.anotherVersion
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var descriptor: AnotherDataClass
get() = getEntityData().descriptor
set(value) {
checkModificationAllowed()
getEntityData().descriptor = value
changedProperty.add("descriptor")
}
override var description: String
get() = getEntityData().description
set(value) {
checkModificationAllowed()
getEntityData().description = value
changedProperty.add("description")
}
override var anotherVersion: Int
get() = getEntityData().anotherVersion
set(value) {
checkModificationAllowed()
getEntityData().anotherVersion = value
changedProperty.add("anotherVersion")
}
override fun getEntityData(): FinalFieldsEntityData = result ?: super.getEntityData() as FinalFieldsEntityData
override fun getEntityClass(): Class<FinalFieldsEntity> = FinalFieldsEntity::class.java
}
}
class FinalFieldsEntityData : WorkspaceEntityData<FinalFieldsEntity>() {
lateinit var descriptor: AnotherDataClass
var description: String = "Default description"
var anotherVersion: Int = 0
fun isDescriptorInitialized(): Boolean = ::descriptor.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FinalFieldsEntity> {
val modifiable = FinalFieldsEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): FinalFieldsEntity {
val entity = FinalFieldsEntityImpl()
entity._descriptor = descriptor
entity.description = description
entity.anotherVersion = anotherVersion
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return FinalFieldsEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return FinalFieldsEntity(descriptor, entitySource) {
this.description = [email protected]
this.anotherVersion = [email protected]
}
}
override fun getRequiredParents(): List<Class<out WorkspaceEntity>> {
val res = mutableListOf<Class<out WorkspaceEntity>>()
return res
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FinalFieldsEntityData
if (this.entitySource != other.entitySource) return false
if (this.descriptor != other.descriptor) return false
if (this.description != other.description) return false
if (this.anotherVersion != other.anotherVersion) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FinalFieldsEntityData
if (this.descriptor != other.descriptor) return false
if (this.description != other.description) return false
if (this.anotherVersion != other.anotherVersion) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + descriptor.hashCode()
result = 31 * result + description.hashCode()
result = 31 * result + anotherVersion.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + descriptor.hashCode()
result = 31 * result + description.hashCode()
result = 31 * result + anotherVersion.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.add(AnotherDataClass::class.java)
collector.sameForAllEntities = true
}
}
| apache-2.0 | 2f75ebb7fab2e6b18835c90b7b2f66de | 32.7897 | 133 | 0.734028 | 5.513305 | false | false | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/workspaceModel/ContentRootCollector.kt | 1 | 6365 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.idea.maven.importing.workspaceModel
import com.intellij.openapi.util.Comparing
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.jps.model.java.JavaResourceRootType
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
object ContentRootCollector {
fun collect(folders: List<ImportedFolder>): Collection<ContentRootResult> {
class ContentRootWithFolders(val path: String, val folders: MutableList<ImportedFolder> = mutableListOf())
val result = mutableListOf<ContentRootWithFolders>()
folders.sorted().forEach { curr ->
// 1. ADD CONTENT ROOT, IF NEEDED:
var nearestRoot = result.lastOrNull()
if (nearestRoot != null && FileUtil.isAncestor(nearestRoot.path, curr.path, false)) {
if (curr is ProjectRootFolder) {
// don't add nested content roots
return@forEach
}
if (curr is ExcludedFolder && FileUtil.pathsEqual(nearestRoot.path, curr.path)) {
// don't add exclude that points at the root
return@forEach
}
}
else {
if (curr is ExcludedFolder) {
// don't add root when there is only an exclude folder under it
return@forEach
}
nearestRoot = ContentRootWithFolders(curr.path)
result.add(nearestRoot)
}
// 2. MERGE DUPLICATE PATHS
val prev = nearestRoot.folders.lastOrNull()
if (prev != null && FileUtil.pathsEqual(prev.path, curr.path)) {
if (prev.rank <= curr.rank) {
return@forEach
}
}
// 3. MERGE SUBFOLDERS:
if (prev != null && FileUtil.isAncestor(prev.path, curr.path, true)) {
if (prev is SourceFolder && curr is UserOrGeneratedSourceFolder) {
// don't add sub source folders
return@forEach
}
else if (prev is GeneratedSourceFolder && curr is UserOrGeneratedSourceFolder) {
// don't add generated folder when there are sub source folder
nearestRoot.folders.removeLast()
}
else if (prev is ExcludedFolderAndPreventSubfolders && curr is UserOrGeneratedSourceFolder) {
// don't add source folders under corresponding exclude folders
return@forEach
}
else if (prev.rank == curr.rank) {
// merge other subfolders of the same type
return@forEach
}
}
// 4. REGISTER FOLDER UNDER THE ROOT
nearestRoot.folders.add(curr)
}
// Now, we need a second pass over the merged folders, to remove nested exclude folders.
// Couldn't do it during the first pass, since exclude folders have different properties (preventing subfolders),
// which need to be taken into account during the first pass.
val rootIterator = result.iterator()
while (rootIterator.hasNext()) {
val root = rootIterator.next()
val folderIterator = root.folders.iterator()
var prev: ImportedFolder? = null
while (folderIterator.hasNext()) {
val curr = folderIterator.next()
if (prev is BaseExcludedFolder && curr is BaseExcludedFolder
&& FileUtil.isAncestor(prev.path, curr.path, false)) {
folderIterator.remove()
}
else {
prev = curr
}
}
}
return result.map { root ->
val sourceFolders = root.folders.asSequence().filterIsInstance<UserOrGeneratedSourceFolder>().map { folder ->
SourceFolderResult(folder.path, folder.type, folder is GeneratedSourceFolder)
}
val excludeFolders = root.folders.asSequence().filterIsInstance<BaseExcludedFolder>().map { folder ->
ExcludedFolderResult(folder.path)
}
ContentRootResult(root.path, sourceFolders.toList(), excludeFolders.toList())
}
}
sealed class ImportedFolder(path: String, internal val rank: Int) : Comparable<ImportedFolder> {
val path: String = FileUtil.toCanonicalPath(path)
override fun compareTo(other: ImportedFolder): Int {
val result = FileUtil.comparePaths(path, other.path)
if (result != 0) return result
return Comparing.compare(rank, other.rank)
}
override fun toString(): String {
return path
}
}
abstract class UserOrGeneratedSourceFolder(path: String, val type: JpsModuleSourceRootType<*>, rank: Int) : ImportedFolder(path, rank) {
override fun compareTo(other: ImportedFolder): Int {
val result = super.compareTo(other)
if (result != 0 || other !is UserOrGeneratedSourceFolder) return result
return Comparing.compare(rootTypeRank, other.rootTypeRank)
}
val rootTypeRank
get() = when (type) {
JavaSourceRootType.SOURCE -> 0
JavaSourceRootType.TEST_SOURCE -> 1
JavaResourceRootType.RESOURCE -> 2
JavaResourceRootType.TEST_RESOURCE -> 3
else -> error("$type not match to maven root item")
}
override fun toString(): String {
return "$path rootType='${if (type.isForTests) "test" else "main"} ${type.javaClass.simpleName}'"
}
}
abstract class BaseExcludedFolder(path: String, rank: Int) : ImportedFolder(path, rank)
class ProjectRootFolder(path: String) : ImportedFolder(path, 0)
class SourceFolder(path: String, type: JpsModuleSourceRootType<*>) : UserOrGeneratedSourceFolder(path, type, 1)
class ExcludedFolderAndPreventSubfolders(path: String) : BaseExcludedFolder(path, 2)
class GeneratedSourceFolder(path: String, type: JpsModuleSourceRootType<*>) : UserOrGeneratedSourceFolder(path, type, 3)
class ExcludedFolder(path: String) : BaseExcludedFolder(path, 4)
class ContentRootResult(val path: String,
val sourceFolders: List<SourceFolderResult>,
val excludeFolders: List<ExcludedFolderResult>) {
override fun toString() = path
}
class SourceFolderResult(val path: String, val type: JpsModuleSourceRootType<*>, val isGenerated: Boolean) {
override fun toString() = "$path ${if (isGenerated) "generated" else ""} rootType='${if (type.isForTests) "test" else "main"} ${type.javaClass.simpleName}'"
}
class ExcludedFolderResult(val path: String) {
override fun toString() = path
}
}
| apache-2.0 | ffc3c877349e8a1b3c61d59dae1636a0 | 39.28481 | 161 | 0.672899 | 4.753547 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/base/fe10/highlighting/src/org/jetbrains/kotlin/idea/highlighter/KotlinSuppressableWarningProblemGroup.kt | 4 | 7724 | // 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.highlighter
import com.intellij.codeInspection.SuppressIntentionAction
import com.intellij.codeInspection.SuppressableProblemGroup
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
import org.jetbrains.kotlin.diagnostics.Severity
import org.jetbrains.kotlin.idea.base.fe10.highlighting.KotlinBaseFe10HighlightingBundle
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class KotlinSuppressableWarningProblemGroup(private val diagnosticFactory: DiagnosticFactory<*>) : SuppressableProblemGroup {
init {
assert(diagnosticFactory.severity == Severity.WARNING)
}
override fun getProblemName() = diagnosticFactory.name
override fun getSuppressActions(element: PsiElement?): Array<SuppressIntentionAction> {
return if (element != null) {
createSuppressWarningActions(element, diagnosticFactory).toTypedArray()
} else {
SuppressIntentionAction.EMPTY_ARRAY
}
}
}
fun createSuppressWarningActions(element: PsiElement, diagnosticFactory: DiagnosticFactory<*>): List<SuppressIntentionAction> =
createSuppressWarningActions(element, diagnosticFactory.severity, diagnosticFactory.name)
fun createSuppressWarningActions(element: PsiElement, severity: Severity, suppressionKey: String): List<SuppressIntentionAction> {
if (severity != Severity.WARNING) {
return emptyList()
}
val actions = arrayListOf<SuppressIntentionAction>()
var current: PsiElement? = element
var suppressAtStatementAllowed = true
while (current != null) {
when {
current is KtDeclaration && current !is KtDestructuringDeclaration -> {
val declaration = current
val kind = DeclarationKindDetector.detect(declaration)
if (kind != null) {
actions.add(Fe10QuickFixProvider.getInstance(declaration.project).createSuppressFix(declaration, suppressionKey, kind))
}
suppressAtStatementAllowed = false
}
current is KtExpression && suppressAtStatementAllowed -> {
// Add suppress action at first statement
if (current.parent is KtBlockExpression || current.parent is KtDestructuringDeclaration) {
val kind = if (current.parent is KtBlockExpression)
KotlinBaseFe10HighlightingBundle.message("declaration.kind.statement")
else
KotlinBaseFe10HighlightingBundle.message("declaration.kind.initializer")
val hostKind = AnnotationHostKind(kind, null, true)
actions.add(Fe10QuickFixProvider.getInstance(current.project).createSuppressFix(current, suppressionKey, hostKind))
suppressAtStatementAllowed = false
}
}
current is KtFile -> {
val hostKind = AnnotationHostKind(KotlinBaseFe10HighlightingBundle.message("declaration.kind.file"), current.name, true)
actions.add(Fe10QuickFixProvider.getInstance(current.project).createSuppressFix(current, suppressionKey, hostKind))
suppressAtStatementAllowed = false
}
}
current = current.parent
}
return actions
}
private object DeclarationKindDetector : KtVisitor<AnnotationHostKind?, Unit?>() {
fun detect(declaration: KtDeclaration) = declaration.accept(this, null)
override fun visitDeclaration(declaration: KtDeclaration, data: Unit?) = null
private fun getDeclarationName(declaration: KtDeclaration): @NlsSafe String {
return declaration.name ?: KotlinBaseFe10HighlightingBundle.message("declaration.name.anonymous")
}
override fun visitClass(declaration: KtClass, data: Unit?): AnnotationHostKind {
val kind = when {
declaration.isInterface() -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.interface")
else -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.class")
}
return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true)
}
override fun visitNamedFunction(declaration: KtNamedFunction, data: Unit?): AnnotationHostKind {
val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.fun")
return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true)
}
override fun visitProperty(declaration: KtProperty, data: Unit?): AnnotationHostKind {
val kind = when {
declaration.isVar -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.var")
else -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.val")
}
return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true)
}
override fun visitDestructuringDeclaration(declaration: KtDestructuringDeclaration, data: Unit?): AnnotationHostKind {
val kind = when {
declaration.isVar -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.var")
else -> KotlinBaseFe10HighlightingBundle.message("declaration.kind.val")
}
val name = declaration.entries.joinToString(", ", "(", ")") { it.name!! }
return AnnotationHostKind(kind, name, newLineNeeded = true)
}
override fun visitTypeParameter(declaration: KtTypeParameter, data: Unit?): AnnotationHostKind {
val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.type.parameter")
return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = false)
}
override fun visitEnumEntry(declaration: KtEnumEntry, data: Unit?): AnnotationHostKind {
val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.enum.entry")
return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true)
}
override fun visitParameter(declaration: KtParameter, data: Unit?): AnnotationHostKind {
val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.parameter")
return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = false)
}
override fun visitSecondaryConstructor(declaration: KtSecondaryConstructor, data: Unit?): AnnotationHostKind {
val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.secondary.constructor.of")
return AnnotationHostKind(kind, getDeclarationName(declaration), newLineNeeded = true)
}
override fun visitObjectDeclaration(d: KtObjectDeclaration, data: Unit?): AnnotationHostKind? {
return when {
d.isCompanion() -> {
val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.companion.object")
val name = KotlinBaseFe10HighlightingBundle.message(
"declaration.name.0.of.1",
d.name.toString(),
d.getStrictParentOfType<KtClass>()?.name.toString()
)
AnnotationHostKind(kind, name, newLineNeeded = true)
}
d.parent is KtObjectLiteralExpression -> null
else -> {
val kind = KotlinBaseFe10HighlightingBundle.message("declaration.kind.object")
AnnotationHostKind(kind, getDeclarationName(d), newLineNeeded = true)
}
}
}
} | apache-2.0 | 7bff8999bb6c403d8f3191341808b8a6 | 47.892405 | 158 | 0.701709 | 5.474132 | false | false | false | false |
ktorio/ktor | ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/NettyApplicationCallHandler.kt | 1 | 3772 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.netty
import io.ktor.http.*
import io.ktor.http.HttpHeaders
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.http1.*
import io.ktor.util.pipeline.*
import io.ktor.utils.io.*
import io.netty.channel.*
import io.netty.handler.codec.http.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
private const val CHUNKED_VALUE = "chunked"
internal class NettyApplicationCallHandler(
userCoroutineContext: CoroutineContext,
private val enginePipeline: EnginePipeline
) : ChannelInboundHandlerAdapter(), CoroutineScope {
override val coroutineContext: CoroutineContext = userCoroutineContext
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
when (msg) {
is ApplicationCall -> handleRequest(ctx, msg)
else -> ctx.fireChannelRead(msg)
}
}
private fun handleRequest(context: ChannelHandlerContext, call: ApplicationCall) {
val callContext = CallHandlerCoroutineName + NettyDispatcher.CurrentContext(context)
launch(callContext, start = CoroutineStart.UNDISPATCHED) {
when {
call is NettyHttp1ApplicationCall && !call.request.isValid() -> {
respondError400BadRequest(call)
}
else ->
try {
enginePipeline.execute(call)
} catch (error: Exception) {
handleFailure(call, error)
}
}
}
}
private suspend fun respondError400BadRequest(call: NettyHttp1ApplicationCall) {
logCause(call)
call.response.status(HttpStatusCode.BadRequest)
call.response.headers.append(HttpHeaders.ContentLength, "0", safeOnly = false)
call.response.headers.append(HttpHeaders.Connection, "close", safeOnly = false)
call.response.sendResponse(chunked = false, ByteReadChannel.Empty)
call.finish()
}
private fun logCause(call: NettyHttp1ApplicationCall) {
if (call.application.log.isTraceEnabled) {
val cause = call.request.httpRequest.decoderResult()?.cause() ?: return
call.application.log.trace("Failed to decode request", cause)
}
}
companion object {
internal val CallHandlerCoroutineName = CoroutineName("call-handler")
}
}
internal fun NettyHttp1ApplicationRequest.isValid(): Boolean {
if (httpRequest.decoderResult().isFailure) {
return false
}
if (!headers.contains(HttpHeaders.TransferEncoding)) return true
val encodings = headers.getAll(HttpHeaders.TransferEncoding) ?: return true
if (!encodings.hasValidTransferEncoding()) {
return false
}
return true
}
internal fun List<String>.hasValidTransferEncoding(): Boolean {
forEachIndexed { headerIndex, header ->
val chunkedStart = header.indexOf(CHUNKED_VALUE)
if (chunkedStart == -1) return@forEachIndexed
if (chunkedStart > 0 && !header[chunkedStart - 1].isSeparator()) {
return@forEachIndexed
}
val afterChunked: Int = chunkedStart + CHUNKED_VALUE.length
if (afterChunked < header.length && !header[afterChunked].isSeparator()) {
return@forEachIndexed
}
if (headerIndex != lastIndex) {
return false
}
val chunkedIsNotLast = chunkedStart + CHUNKED_VALUE.length < header.length
if (chunkedIsNotLast) {
return false
}
}
return true
}
private fun Char.isSeparator(): Boolean =
(this == ' ' || this == ',')
| apache-2.0 | db100cc2a1d2d1e26325dbea219ae674 | 31.239316 | 118 | 0.653234 | 4.720901 | false | false | false | false |
marcbaldwin/RxAdapter | rxadapter/src/main/kotlin/xyz/marcb/rxadapter/internal/CompositeAdapterPartSnapshot.kt | 1 | 1356 | package xyz.marcb.rxadapter.internal
import androidx.recyclerview.widget.RecyclerView
import xyz.marcb.rxadapter.AdapterPartSnapshot
internal class CompositeAdapterPartSnapshot(val parts: List<AdapterPartSnapshot>) : AdapterPartSnapshot {
override val itemIds: List<Long> = parts.flatMap { it.itemIds }
override fun viewHolderClass(index: Int): Class<out RecyclerView.ViewHolder> {
val (adapter, adjustedIndex) = adapterWithAdjustedIndex(index)
return adapter.viewHolderClass(index = adjustedIndex)
}
override fun bind(viewHolder: RecyclerView.ViewHolder, index: Int) {
val (adapter, adjustedIndex) = adapterWithAdjustedIndex(index)
adapter.bind(viewHolder, index = adjustedIndex)
}
override fun underlyingObject(index: Int): Any? {
val (adapter, adjustedIndex) = adapterWithAdjustedIndex(index)
return adapter.underlyingObject(index = adjustedIndex)
}
private fun adapterWithAdjustedIndex(index: Int): Pair<AdapterPartSnapshot, Int> {
var currentIndex = 0
for (part in parts) {
currentIndex += part.itemCount
if (currentIndex > index) {
return Pair(part, index - (currentIndex - part.itemCount))
}
}
throw IllegalArgumentException("Internal error: Index exceeded item count")
}
}
| mit | bc8489fd50ab3696b749b3cc5702e6af | 37.742857 | 105 | 0.701327 | 4.59661 | false | false | false | false |
Emberwalker/Laundarray | src/main/kotlin/io/drakon/laundarray/algo/IslandGenerator.kt | 1 | 5840 | package io.drakon.laundarray.algo
import io.drakon.laundarray.util.FutureHelper
import org.apache.logging.log4j.LogManager
import java.util.HashSet
import java.util.Random
import java.util.concurrent.Future
/**
* Floating island algorithm imported from Aide.
*
* @author Arkan <[email protected]>
*/
public class IslandGenerator private (var initSeed:Any? = null) {
companion object {
private val logger = LogManager.getLogger()
/**
* Generates a plain island grid. No dirt etc.
*/
public fun dumbGenerateIsland(maxHeight:Int, maxTopRadius:Int, seed:Any? = null): Future<Array<Array<Array<Boolean>>>> {
return FutureHelper.getFuture({
val gen = IslandGenerator(seed)
gen.generate(maxHeight, maxTopRadius)
}, startNow = true)
}
/**
* Generates a Pair<stone,dirt>, where stone and dirt are Sets of BlockCoords.
*/
public fun generateIslandData(maxHeight:Int, maxTopRadius:Int, seed:Any? = null): Future<Pair<Set<BlockCoord>, Set<BlockCoord>>> {
return FutureHelper.getFuture({
val gen = IslandGenerator(seed)
val grid = gen.generate(maxHeight, maxTopRadius)
convertGridToPairs(grid)
}, startNow = true)
}
[deprecated("Just don't use it okay.")]
public fun getRawGenerator(seed:Any? = null): IslandGenerator {
logger.warn("Someone is getting a raw generator instance. This isn't recommended!")
return IslandGenerator(seed)
}
private fun convertGridToPairs(grid:Array<Array<Array<Boolean>>>): Pair<Set<BlockCoord>, Set<BlockCoord>> {
val stone = HashSet<BlockCoord>()
val dirt = HashSet<BlockCoord>()
for (n in 0..grid.lastIndex) {
for (p in 0..grid[n].lastIndex) {
val col = grid[n][p]
for (x in 0..col.lastIndex-2) if (col[x]) stone.add(BlockCoord(n,p,x))
for (x in col.lastIndex-2..col.lastIndex) if (col[x]) dirt.add(BlockCoord(n,p,x))
}
}
return Pair(stone, dirt)
}
public data class BlockCoord(val x:Int, val y:Int, val z:Int)
}
init {
setSeed(initSeed)
}
private var seed = initSeed
private var rand:Random = Random() // Overriden anyway during init
private var grid:Array<Array<Array<Boolean>>> = Array(0, {Array(0, {Array(0, {false})})}) // Goddamn null checks
/**
* Generate one island.
*
* @note Verify that radius >= height, or poor results may be produced.
*
* @param maxHeight The islands max height.
* @param maxTopRadius The islands max radius (but the final radius is usually slightly smaller)
* @return The 3D grid in form x/y/z, using mathematical axes (x/y is the horizontal plane, z is height) NOT Minecraft axes.
*/
public fun generate(maxHeight:Int, maxTopRadius:Int): Array<Array<Array<Boolean>>> {
restartRandom()
grid = Array(maxTopRadius, {
Array(maxTopRadius, {
Array(maxHeight, {false})
})
})
// Find and spawn centre seed block
val centre:Int = Math.round(maxTopRadius.toDouble()/2).toInt()
grid[centre][centre][0] = true
// Calculate max splat size
val maxSplat:Int = Math.round(maxTopRadius/(maxHeight*2.0)).toInt()
// Main loop
for ( z in 1..maxHeight - 1 ) {
for ( y in 0..maxTopRadius - 1 ) {
for ( x in 0..maxTopRadius - 1 ) {
generateSplat(x, y, z, maxSplat)
}
}
}
return grid
}
/**
* Sets the generators seed.
*
* @note This will RESET the current Random instance.
* @note Use a String, Number or no parameter. Using another type will be treated the same as null - A new randomised seed based on systime.
* @param newSeed The new seed to use.
*/
public fun setSeed(newSeed:Any? = null) {
seed = newSeed
if (seed is String) rand = Random((seed as String).toLong()) // Smart Cast bug :#
else if (seed is Number) rand = Random((seed as Number).toLong())
else rand = Random()
}
private fun restartRandom() {
setSeed(seed)
}
private fun generateSplat(x:Int, y:Int, z:Int, maxSize:Int) {
// Check if block underneath
if (!grid[x][y][z-1]) return
// Splat core
grid[x][y][z] = true
var delta_x_pos = 0
var delta_x_neg = 0
var delta_y_pos = 0
var delta_y_neg = 0
for (_ in 0..maxSize*2) {
val r = rand.nextInt(4)
when (r) {
0 -> {
// +x
delta_x_pos += 1
if (x+delta_x_pos <= grid.lastIndex)
grid[x+delta_x_pos][y][z] = true}
1 -> {
// +y
delta_y_pos += 1
if (y+delta_y_pos <= grid[x].lastIndex)
grid[x][y+delta_y_pos][z] = true}
2 -> {
// -x
delta_x_neg += 1
if (x-delta_x_neg >= 0)
grid[x-delta_x_neg][y][z] = true}
3 -> {
// -y
delta_y_neg += 1
if (y-delta_y_neg >= 0)
grid[x][y-delta_y_neg][z] = true}
else -> {
// Whut
val e = IllegalStateException("Impossible value of r: " + r)
logger.warn(e.getMessage() + " at: \n" + e.getStackTrace())}
}
}
}
} | mit | 6ced85311154fac33861cbfb9ab3bbff | 33.157895 | 144 | 0.528082 | 3.95664 | false | false | false | false |
iSoron/uhabits | uhabits-android/src/main/java/org/isoron/platform/gui/AndroidDataView.kt | 1 | 4427 | /*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.platform.gui
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.widget.Scroller
import kotlin.math.abs
import kotlin.math.max
/**
* An AndroidView that implements scrolling.
*/
class AndroidDataView(
context: Context,
attrs: AttributeSet? = null,
) : AndroidView<DataView>(context, attrs),
GestureDetector.OnGestureListener,
ValueAnimator.AnimatorUpdateListener {
private val detector = GestureDetector(context, this)
private val scroller = Scroller(context, null, true)
private val scrollAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
addUpdateListener(this@AndroidDataView)
}
override fun onTouchEvent(event: MotionEvent?) = detector.onTouchEvent(event)
override fun onDown(e: MotionEvent?) = true
override fun onShowPress(e: MotionEvent?) = Unit
override fun onSingleTapUp(e: MotionEvent?): Boolean {
return handleClick(e, true)
}
override fun onLongPress(e: MotionEvent?) {
handleClick(e)
}
override fun onScroll(
e1: MotionEvent?,
e2: MotionEvent?,
dx: Float,
dy: Float,
): Boolean {
if (abs(dx) > abs(dy)) {
val parent = parent
parent?.requestDisallowInterceptTouchEvent(true)
}
scroller.startScroll(
scroller.currX,
scroller.currY,
-dx.toInt(),
dy.toInt(),
0
)
scroller.computeScrollOffset()
updateDataOffset()
return true
}
override fun onFling(
e1: MotionEvent?,
e2: MotionEvent?,
velocityX: Float,
velocityY: Float,
): Boolean {
scroller.fling(
scroller.currX,
scroller.currY,
velocityX.toInt() / 2,
0,
0,
Integer.MAX_VALUE,
0,
0
)
invalidate()
scrollAnimator.duration = scroller.duration.toLong()
scrollAnimator.start()
return false
}
override fun onAnimationUpdate(animation: ValueAnimator?) {
if (!scroller.isFinished) {
scroller.computeScrollOffset()
updateDataOffset()
} else {
scrollAnimator.cancel()
}
}
fun resetDataOffset() {
scroller.finalX = 0
scroller.computeScrollOffset()
updateDataOffset()
}
private fun updateDataOffset() {
view?.let { v ->
var newDataOffset: Int =
scroller.currX / (v.dataColumnWidth * canvas.innerDensity).toInt()
newDataOffset = max(0, newDataOffset)
if (newDataOffset != v.dataOffset) {
v.dataOffset = newDataOffset
postInvalidate()
}
}
}
private fun handleClick(e: MotionEvent?, isSingleTap: Boolean = false): Boolean {
val x: Float
val y: Float
try {
val pointerId = e!!.getPointerId(0)
x = e.getX(pointerId)
y = e.getY(pointerId)
} catch (ex: RuntimeException) {
// Android often throws IllegalArgumentException here. Apparently,
// the pointer id may become invalid shortly after calling
// e.getPointerId.
return false
}
if (isSingleTap) view?.onClick(x / canvas.innerDensity, y / canvas.innerDensity)
else view?.onLongClick(x / canvas.innerDensity, y / canvas.innerDensity)
return true
}
}
| gpl-3.0 | 729af657ca4e583177757dafeec67691 | 29.108844 | 88 | 0.620651 | 4.693531 | false | false | false | false |
spotify/heroic | heroic-component/src/main/java/com/spotify/heroic/suggest/TagSuggest.kt | 1 | 3471 | /*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"): you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.suggest
import com.spotify.heroic.cluster.ClusterShard
import com.spotify.heroic.common.DateRange
import com.spotify.heroic.common.OptionalLimit
import com.spotify.heroic.filter.Filter
import com.spotify.heroic.metric.RequestError
import com.spotify.heroic.metric.ShardError
import eu.toolchain.async.Collector
import eu.toolchain.async.Transform
import java.util.*
data class TagSuggest(
val errors: List<RequestError> = emptyList(),
val suggestions: List<Suggestion> = emptyList()
) {
constructor(suggestions: List<Suggestion>): this(emptyList(), suggestions)
companion object {
@JvmStatic fun reduce(limit: OptionalLimit): Collector<TagSuggest, TagSuggest> {
return Collector { groups: Collection<TagSuggest> ->
val errors1: MutableList<RequestError> = mutableListOf()
val suggestions1: MutableMap<Pair<String, String>, Float> = hashMapOf()
groups.forEach { group ->
errors1.addAll(group.errors)
group.suggestions.forEach { suggestion ->
val key = suggestion.key to suggestion.value
val old = suggestions1.put(key, suggestion.score)
// prefer higher score if available
if (old != null && suggestion.score < old) {
suggestions1[key] = old
}
}
}
val values = suggestions1
.map { Suggestion(it.value, it.key.first, it.key.second) }
.sorted()
TagSuggest(errors1, limit.limitList(values))
}
}
@JvmStatic fun shardError(shard: ClusterShard): Transform<Throwable, TagSuggest> {
return Transform { e: Throwable ->
TagSuggest(errors = listOf(ShardError.fromThrowable(shard, e)))
}
}
}
data class Suggestion(
val score: Float,
val key: String,
val value: String
): Comparable<Suggestion> {
override fun compareTo(other: Suggestion): Int {
val s = other.score.compareTo(score)
if (s != 0) return s
val k = key.compareTo(other.key)
if (k != 0) return k
return value.compareTo(other.value)
}
}
data class Request(
val filter: Filter,
val range: DateRange,
val limit: OptionalLimit,
val options: MatchOptions,
val key: Optional<String>,
val value: Optional<String>
)
}
| apache-2.0 | 7dd0fdb9169e0334ab845e3c6e11859e | 34.418367 | 90 | 0.623163 | 4.634179 | false | false | false | false |
gmariotti/kotlin-koans | lesson4/task4/src/tests.kt | 2 | 430 | import org.junit.Assert
import org.junit.Test
class TestDelegatesHowItWorks {
@Test fun testDate() {
val d = D()
d.date = MyDate(2014, 1, 13)
val message = "The methods 'getValue' and 'setValue' are implemented incorrectly"
Assert.assertTrue(message, 2014 == d.date.year)
Assert.assertTrue(message, 1 == d.date.month)
Assert.assertTrue(message, 13 == d.date.dayOfMonth)
}
} | mit | 4134ac495e25e492ed6bb993100f739f | 32.153846 | 89 | 0.646512 | 3.73913 | false | true | false | false |
paplorinc/intellij-community | plugins/git4idea/src/git4idea/remote/GitConfigureRemotesDialog.kt | 7 | 11207 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.remote
import com.intellij.dvcs.DvcsUtil
import com.intellij.dvcs.DvcsUtil.sortRepositories
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.DialogWrapper.IdeModalityType.IDE
import com.intellij.openapi.ui.DialogWrapper.IdeModalityType.PROJECT
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.Messages.*
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.ColoredTableCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.table.JBTable
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil.DEFAULT_HGAP
import git4idea.commands.Git
import git4idea.commands.GitCommandResult
import git4idea.repo.GitRemote
import git4idea.repo.GitRemote.ORIGIN
import git4idea.repo.GitRepository
import java.awt.Dimension
import java.awt.Font
import java.util.*
import javax.swing.*
import javax.swing.table.AbstractTableModel
class GitConfigureRemotesDialog(val project: Project, val repositories: Collection<GitRepository>) :
DialogWrapper(project, true, getModalityType()) {
private val git = service<Git>()
private val LOG = logger<GitConfigureRemotesDialog>()
private val NAME_COLUMN = 0
private val URL_COLUMN = 1
private val REMOTE_PADDING = 30
private val table = JBTable(RemotesTableModel())
private var nodes = buildNodes(repositories)
init {
init()
title = "Git Remotes"
updateTableWidth()
}
override fun createActions(): Array<Action> = arrayOf(okAction)
override fun getPreferredFocusedComponent(): JBTable = table
override fun createCenterPanel(): JComponent? {
table.selectionModel = DefaultListSelectionModel()
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
table.intercellSpacing = JBUI.emptySize()
table.setDefaultRenderer(Any::class.java, MyCellRenderer())
return ToolbarDecorator.createDecorator(table).
setAddAction { addRemote() }.
setRemoveAction { removeRemote() }.
setEditAction { editRemote() }.
setEditActionUpdater { isRemoteSelected() }.
setRemoveActionUpdater { isRemoteSelected() }.
disableUpDownActions().createPanel()
}
private fun addRemote() {
val repository = getSelectedRepo()
val proposedName = if (repository.remotes.any { it.name == ORIGIN }) "" else ORIGIN
val dialog = GitDefineRemoteDialog(repository, git, proposedName, "")
if (dialog.showAndGet()) {
runInModalTask("Adding Remote...", repository,
"Add Remote", "Couldn't add remote ${dialog.remoteName} '${dialog.remoteUrl}'") {
git.addRemote(repository, dialog.remoteName, dialog.remoteUrl)
}
}
}
private fun removeRemote() {
val remoteNode = getSelectedRemote()!!
val remote = remoteNode.remote
if (YES == showYesNoDialog(rootPane, "Remove remote ${remote.name} '${getUrl(remote)}'?", "Remove Remote", getQuestionIcon())) {
runInModalTask("Removing Remote...", remoteNode.repository, "Remove Remote", "Couldn't remove remote $remote") {
git.removeRemote(remoteNode.repository, remote)
}
}
}
private fun editRemote() {
val remoteNode = getSelectedRemote()!!
val remote = remoteNode.remote
val repository = remoteNode.repository
val oldName = remote.name
val oldUrl = getUrl(remote)
val dialog = GitDefineRemoteDialog(repository, git, oldName, oldUrl)
if (dialog.showAndGet()) {
val newRemoteName = dialog.remoteName
val newRemoteUrl = dialog.remoteUrl
if (newRemoteName == oldName && newRemoteUrl == oldUrl) return
runInModalTask("Changing Remote...", repository,
"Change Remote", "Couldn't change remote $oldName to $newRemoteName '$newRemoteUrl'") {
changeRemote(repository, oldName, oldUrl, newRemoteName, newRemoteUrl)
}
}
}
private fun changeRemote(repo: GitRepository, oldName: String, oldUrl: String, newName: String, newUrl: String): GitCommandResult {
var result : GitCommandResult? = null
if (newName != oldName) {
result = git.renameRemote(repo, oldName, newName)
if (!result.success()) return result
}
if (newUrl != oldUrl) {
result = git.setRemoteUrl(repo, newName, newUrl) // NB: remote name has just been changed
}
return result!! // at least one of two has changed
}
private fun updateTableWidth() {
var maxNameWidth = 30
var maxUrlWidth = 250
for (node in nodes) {
val fontMetrics = table.getFontMetrics(UIManager.getFont("Table.font").deriveFont(Font.BOLD))
val nameWidth = fontMetrics.stringWidth(node.getPresentableString())
val remote = (node as? RemoteNode)?.remote
val urlWidth = if (remote == null) 0 else fontMetrics.stringWidth(getUrl(remote))
if (maxNameWidth < nameWidth) maxNameWidth = nameWidth
if (maxUrlWidth < urlWidth) maxUrlWidth = urlWidth
}
maxNameWidth += REMOTE_PADDING + DEFAULT_HGAP
table.columnModel.getColumn(NAME_COLUMN).preferredWidth = maxNameWidth
table.columnModel.getColumn(URL_COLUMN).preferredWidth = maxUrlWidth
val defaultPreferredHeight = table.rowHeight*(table.rowCount+3)
table.preferredScrollableViewportSize = Dimension(maxNameWidth + maxUrlWidth + DEFAULT_HGAP, defaultPreferredHeight)
}
private fun buildNodes(repositories: Collection<GitRepository>): List<Node> {
val nodes = mutableListOf<Node>()
for (repository in sortRepositories(repositories)) {
if (repositories.size > 1) nodes.add(RepoNode(repository))
for (remote in sortedRemotes(repository)) {
nodes.add(RemoteNode(remote, repository))
}
}
return nodes
}
private fun sortedRemotes(repository: GitRepository): List<GitRemote> {
return repository.remotes.sortedWith(Comparator<GitRemote> { r1, r2 ->
if (r1.name == ORIGIN) {
if (r2.name == ORIGIN) 0 else -1
}
else if (r2.name == ORIGIN) 1 else r1.name.compareTo(r2.name)
})
}
private fun rebuildTable() {
nodes = buildNodes(repositories)
(table.model as RemotesTableModel).fireTableDataChanged()
}
private fun runInModalTask(title: String,
repository: GitRepository,
errorTitle: String,
errorMessage: String,
operation: () -> GitCommandResult) {
ProgressManager.getInstance().run(object : Task.Modal(project, title, true) {
private var result: GitCommandResult? = null
override fun run(indicator: ProgressIndicator) {
result = operation()
repository.update()
}
override fun onSuccess() {
rebuildTable()
if (result == null || !result!!.success()) {
val errorDetails = if (result == null) "operation was not executed" else result!!.errorOutputAsJoinedString
val message = "$errorMessage in $repository:\n$errorDetails"
LOG.warn(message)
Messages.showErrorDialog(myProject, message, errorTitle)
}
}
})
}
private fun getSelectedRepo(): GitRepository {
val selectedRow = table.selectedRow
if (selectedRow < 0) return sortRepositories(repositories).first()
val value = nodes[selectedRow]
if (value is RepoNode) return value.repository
if (value is RemoteNode) return value.repository
throw IllegalStateException("Unexpected selected value: $value")
}
private fun getSelectedRemote() : RemoteNode? {
val selectedRow = table.selectedRow
if (selectedRow < 0) return null
return nodes[selectedRow] as? RemoteNode
}
private fun isRemoteSelected() = getSelectedRemote() != null
private fun getUrl(remote: GitRemote) = remote.urls.firstOrNull() ?: ""
private abstract class Node {
abstract fun getPresentableString() : String
}
private class RepoNode(val repository: GitRepository) : Node() {
override fun toString() = repository.presentableUrl
override fun getPresentableString() = DvcsUtil.getShortRepositoryName(repository)
}
private class RemoteNode(val remote: GitRemote, val repository: GitRepository) : Node() {
override fun toString() = remote.name
override fun getPresentableString() = remote.name
}
private inner class RemotesTableModel() : AbstractTableModel() {
override fun getRowCount() = nodes.size
override fun getColumnCount() = 2
override fun getColumnName(column: Int): String {
if (column == NAME_COLUMN) return "Name"
else return "URL"
}
override fun getValueAt(rowIndex: Int, columnIndex: Int): Any {
val node = nodes[rowIndex]
when {
columnIndex == NAME_COLUMN -> return node
node is RepoNode -> return ""
node is RemoteNode -> return getUrl(node.remote)
else -> {
LOG.error("Unexpected position at row $rowIndex and column $columnIndex")
return ""
}
}
}
}
private inner class MyCellRenderer : ColoredTableCellRenderer() {
override fun customizeCellRenderer(table: JTable?, value: Any?, selected: Boolean, hasFocus: Boolean, row: Int, column: Int) {
if (value is RepoNode) {
append(value.getPresentableString(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES)
}
else if (value is RemoteNode) {
if (repositories.size > 1) append("", SimpleTextAttributes.REGULAR_ATTRIBUTES, REMOTE_PADDING, SwingConstants.LEFT)
append(value.getPresentableString())
}
else if (value is String) {
append(value)
}
border = null
}
}
}
private fun getModalityType() = if (Registry.`is`("ide.perProjectModality")) PROJECT else IDE
| apache-2.0 | 108523d4c67fc3cf0c01607f371c2262 | 36.861486 | 133 | 0.704827 | 4.484594 | false | false | false | false |
marcplouhinec/trust-service-reputation | src/main/kotlin/fr/marcsworld/model/entity/AgencyName.kt | 1 | 696 | package fr.marcsworld.model.entity
import javax.persistence.*
/**
* Represents the name of an agency translated into a language.
*
* @author Marc Plouhinec
*/
@Entity
@Table(name = "AGENCY_NAME")
class AgencyName (
@Id @GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AGENCY_NAME_ID", nullable = false)
var id: Long? = null,
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "AGENCY_ID", nullable = false)
var agency: Agency,
@Column(name = "NAME", nullable = false, length = 500)
var name: String,
@Column(name = "LANGUAGE_CODE", nullable = false, length = 20)
var languageCode: String
) | mit | 2fcd595e3e949f5e4c606c0941c82786 | 25.807692 | 70 | 0.633621 | 3.741935 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/hints/AbstractKotlinLambdasHintsProviderTest.kt | 5 | 1937 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight.hints
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.utils.inlays.InlayHintsProviderTestCase
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import java.io.File
abstract class AbstractKotlinLambdasHintsProvider :
InlayHintsProviderTestCase() { // Abstract- prefix is just a convention for GenerateTests
override fun getProjectDescriptor(): LightProjectDescriptor {
return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
fun doTest(testPath: String) { // named according to the convention imposed by GenerateTests
assertThatActualHintsMatch(testPath)
}
private fun assertThatActualHintsMatch(fileName: String) {
with(KotlinLambdasHintsProvider()) {
val fileContents = FileUtil.loadFile(File(fileName), true)
val settings = createSettings()
with(settings) {
when (InTextDirectivesUtils.findStringWithPrefixes(fileContents, "// MODE: ")) {
"return" -> set(returns = true)
"receivers_params" -> set(receiversAndParams = true)
"return-&-receivers_params" -> set(returns = true, receiversAndParams = true)
else -> set()
}
}
doTestProvider("KotlinLambdasHintsProvider.kt", fileContents, this, settings, true)
}
}
private fun KotlinLambdasHintsProvider.Settings.set(returns: Boolean = false, receiversAndParams: Boolean = false) {
this.returnExpressions = returns
this.implicitReceiversAndParams = receiversAndParams
}
} | apache-2.0 | f13f053186964856f6d3b6715705eb9d | 43.045455 | 120 | 0.709344 | 5.395543 | false | true | false | false |
vhromada/Catalog | core/src/main/kotlin/com/github/vhromada/catalog/service/impl/EpisodeServiceImpl.kt | 1 | 2093 | package com.github.vhromada.catalog.service.impl
import com.github.vhromada.catalog.common.exception.InputException
import com.github.vhromada.catalog.common.provider.UuidProvider
import com.github.vhromada.catalog.domain.Episode
import com.github.vhromada.catalog.repository.EpisodeRepository
import com.github.vhromada.catalog.repository.SeasonRepository
import com.github.vhromada.catalog.service.EpisodeService
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
/**
* A class represents implementation of service for episodes.
*
* @author Vladimir Hromada
*/
@Service("episodeService")
class EpisodeServiceImpl(
/**
* Repository for episodes
*/
private val episodeRepository: EpisodeRepository,
/**
* Repository for seasons
*/
private val seasonRepository: SeasonRepository,
/**
* Provider for UUID
*/
private val uuidProvider: UuidProvider
) : EpisodeService {
override fun search(season: Int, pageable: Pageable): Page<Episode> {
return episodeRepository.findAllBySeasonId(id = season, pageable = pageable)
}
override fun get(uuid: String): Episode {
return episodeRepository.findByUuid(uuid = uuid)
.orElseThrow { InputException(key = "EPISODE_NOT_EXIST", message = "Episode doesn't exist.", httpStatus = HttpStatus.NOT_FOUND) }
}
@Transactional
override fun store(episode: Episode): Episode {
return episodeRepository.save(episode)
}
@Transactional
override fun remove(episode: Episode) {
val season = episode.season!!
season.episodes.remove(episode)
seasonRepository.save(season)
}
@Transactional
override fun duplicate(episode: Episode): Episode {
val copy = episode.copy(id = null, uuid = uuidProvider.getUuid())
copy.season!!.episodes.add(copy)
return episodeRepository.save(copy)
}
}
| mit | 98a058345edd6cca2fb01eebe264a0cd | 31.703125 | 141 | 0.731486 | 4.501075 | false | false | false | false |
ncipollo/android-viper | sample/src/main/kotlin/viper/sample/ui/presenters/GitPresenter.kt | 1 | 1336 | package viper.sample.ui.presenters
import rx.Observable
import viper.presenters.CollectionPresenter
import viper.sample.model.interactors.SampleInteractors
import viper.sample.ui.fragments.GitCollectionView
import viper.view.fragments.CollectionView
/**
* Base class for presenters which utilize a Git API.
* Created by Nick Cipollo on 1/10/17.
*/
abstract class GitPresenter<ListItem, Interactors : Any>
: CollectionPresenter<GitCollectionView,ListItem,Interactors>() {
val FINISH_REFRESHING_ID = 1
val SHOW_ERROR = 2
protected val itemList = mutableListOf<ListItem>()
override val count: Int
get() = itemList.size
override fun getListItem(index: Int): ListItem = itemList[index]
override fun onTakeInteractors(interactors: Interactors) {
if (itemList.isEmpty()) {
refresh()
}
}
fun finishRefresh() {
stop(FINISH_REFRESHING_ID)
restartableFirst(FINISH_REFRESHING_ID,
{ Observable.just(true) },
{ view, noOp -> view?.finishRefresh() })
start(FINISH_REFRESHING_ID)
}
fun showError(error:Throwable) {
stop(SHOW_ERROR)
restartableFirst(SHOW_ERROR,
{ Observable.just(error) },
{ view, err -> view?.onError(err) })
start(SHOW_ERROR)
}
} | mit | 369ccf4c1113f3ae9730aed9fd26a16d | 29.386364 | 69 | 0.66018 | 4.214511 | false | false | false | false |
Kiskae/DiscordKt | api/src/main/kotlin/net/serverpeon/discord/model/Channel.kt | 1 | 10529 | package net.serverpeon.discord.model
import net.serverpeon.discord.interaction.Deletable
import net.serverpeon.discord.interaction.Editable
import net.serverpeon.discord.interaction.PermissionException
import net.serverpeon.discord.message.Message
import rx.Completable
import rx.Observable
import java.time.Duration
import java.util.concurrent.CompletableFuture
/**
* A channel is a line of communication in Discord.
* Channels can either exist within a guild ([Public]) or happen between two people ([Private]).
*/
interface Channel : DiscordId.Identifiable<Channel>, Deletable {
/**
* Indicates whether this is a private or a public (guild) channel.
*
* If `true` then this can be cast to [Channel.Private], otherwise [Channel.Public]
*/
val isPrivate: Boolean
/**
* Indicates the communication type of this channel.
*
* [Type.TEXT] -> Channel is [Public] and [Text]
* [Type.VOICE] -> Channel is [Public] and [Voice]
* [Type.PRIVATE] -> Channel is [Private] and [Text]
*/
val type: Type
/**
* A channel that belongs to a [Guild], members can join according to the permissions defined by the guild
* and the permission overrides for the individual channel.
*
* At any time an arbitrary number of people can receive the messages sent to this channel.
*/
interface Public : Channel, Text, Voice, Editable<Public, Public.Edit> {
/**
* The guild that this channel belongs to.
*/
val guild: Guild
/**
* The topic set for this channel.
*
* **Note:** [Type.VOICE] channels do not have a topic and will always return `""`
*/
val topic: String
/**
* The name of this channel, this shows up in channel list on the official discord interface.
*/
val name: String
/**
* A list of members that have customized permissions in this channel.
*
* @see [setOverride]
*/
val memberOverrides: Observable<ResolvedPermission<Guild.Member>>
/**
* A list of roles that have customized permissions in this channel.
*
* @see [setOverride]
*/
val roleOverrides: Observable<ResolvedPermission<Role>>
/**
* Queries the final permissions for the given role after applying channel-specific overrides.
*
* Accessing permissions through this method instead of [roleOverrides] is more efficient for
* single role queries.
*
* @param role Role to query for permissions with overrides
*/
fun permissionsFor(role: Role): PermissionSet
/**
* Queries the final permissions for the given member after applying channel-specific overrides for both the
* roles that this member has and member-specific ones.
*
* Accessing permissions through this method instead of [memberOverrides] is more efficient for
* single member queries.
*
* @param member Member to query for permissions with overrides
*/
fun permissionsFor(member: Guild.Member): PermissionSet
/**
* Create a new invite which another use can use to join this channel/server.
*
* @param expiredAfter Sets the invite to expire after this amount of time has passed. Set to [Duration.ZERO]
* to make the invite never expire.
* @param maxUses Limit the number of times the invite can be used. Set to 0 for unlimited.
* @param temporaryMembership Whether this invite grants temporary membership, which means the user will be
* kicked from the server when they go offline.
* @param humanReadableId Whether to generate a human-readable invite using the method described in
* http://xkcd.com/936/ instead of a random alphanumeric code.
* @throws PermissionException if the client does now have [PermissionSet.Permission.CREATE_INSTANT_INVITE]
*/
@Throws(PermissionException::class)
fun createInvite(expiredAfter: Duration = Duration.ZERO,
maxUses: Int = 0,
temporaryMembership: Boolean = false,
humanReadableId: Boolean = false): CompletableFuture<Invite.Details>
/**
* Retrieves all active invites previously created for this channel.
*
* @throws PermissionException If the client does not have [PermissionSet.Permission.MANAGE_CHANNEL] for this
* channel.
*/
@Throws(PermissionException::class)
fun getActiveInvites(): Observable<Invite.Details>
/**
* Customizes the permissions for the given member.
* Any permissions that are in neither [allow] nor [deny] will use the state given by the member's roles.
*
* Setting both [allow] and [deny] to [PermissionSet.ZERO] will clear a previously established override.
*
* @param allow Permissions to explicitly allow.
* @param deny Permissions to explicitly deny.
* @param member Target to customize the permissions for.
* @return Future that will complete when the change has been applied, will return the permissions effective
* after applying the change.
* @throws PermissionException if the permission [PermissionSet.Permission.MANAGE_PERMISSIONS] is missing.
*/
@Throws(PermissionException::class)
fun setOverride(allow: PermissionSet, deny: PermissionSet, member: Guild.Member): CompletableFuture<PermissionSet>
/**
* Customizes the permissions for the given role.
* Any permissions that are in neither [allow] nor [deny] will use the state assigned to the base role.
*
* Setting both [allow] and [deny] to [PermissionSet.ZERO] will clear a previously established override.
*
* @param allow Permissions to explicitly allow.
* @param deny Permissions to explicitly deny.
* @param role Target to customize the permissions for.
* @return Future that will complete when the change has been applied, will return the permissions effective
* after applying the change.
* @throws PermissionException if the permission [PermissionSet.Permission.MANAGE_PERMISSIONS] is missing.
*/
@Throws(PermissionException::class)
fun setOverride(allow: PermissionSet, deny: PermissionSet, role: Role): CompletableFuture<PermissionSet>
interface Edit : Editable.Transaction<Edit, Public> {
/**
* Attempt to change the topic of the channel. This will only have an effect if the channel is a [Text]
* channel.
*/
var topic: String
/**
* Change the public name of the channel.
* It must be between 2-100 characters long and can only contain alphanumeric characters and dashes.
*/
var name: String
}
}
/**
* Represents the final permissions given to the [holder] after applying all role permissions and relevant overrides.
*
* @property holder Whoever holds these permissions.
* @property perms The permissions at the time that the source method was called.
*/
data class ResolvedPermission<G : DiscordId.Identifiable<*>>(val holder: G, val perms: PermissionSet)
/**
* A direct messaging channel to [recipient], messages can be read by you and them.
*/
interface Private : Channel, Text {
/**
* The recipient on the other end of this channel.
*/
val recipient: User
}
interface Text : Channel {
/**
* Overload for [sendMessage] with textToSpeech set to null.
*/
@Throws(PermissionException::class)
fun sendMessage(message: Message) = sendMessage(message, null)
/**
* Sends the given message to the channel
*
* @param message The message to send
* @param textToSpeech Whether to mark the message for text-to-speech.
* @return A future that returns the message with additional information about the post.
* @throws PermissionException if the permission [PermissionSet.Permission.SEND_MESSAGES] is missing.
*/
@Throws(PermissionException::class)
fun sendMessage(message: Message, textToSpeech: Boolean?): CompletableFuture<PostedMessage>
/**
* Retrieves the last [limit] messages sent to this channel.
*
* @param limit The number of messages to retrieve.
* @param before Start the message history at this message.
* @return A lazy observable that retrieves the messages from the backend, if only a subset of the
* returned value is used then it will attempt to limit additional requests.
* @throws PermissionException if the permission [PermissionSet.Permission.READ_MESSAGE_HISTORY] is missing.
*/
@Throws(PermissionException::class)
fun messageHistory(limit: Int, before: DiscordId<PostedMessage>? = null): Observable<PostedMessage>
/**
* Subscribing to the returned completable will send a 'typing' state to discord.
*
* It will maintain this state for **5** seconds so it will need to be resubscribed to repeatedly in order to
* maintain typing state for longer periods.
*/
fun indicateTyping(): Completable
}
interface Voice : Channel {
/**
* Retrieves the current voice states for all people in this voice channel.
*
* Calling this on a non-voice channel will result in an empty observable.
*/
val voiceStates: Observable<VoiceState>
//TODO: potentially allow the opening of a voice channel....
}
enum class Type {
/**
* Standard text chat, receives [PostedMessage] as units of communication.
*/
TEXT,
/**
* A voice channel, communication happens outside of the monitoring capabilities of this client.
*/
VOICE,
/**
* Direct message chat, for sending [PostedMessage] back and forth with a single person.
*/
PRIVATE
}
} | mit | 9f1dc386a726fc38d2831b825f4ade3b | 42.155738 | 122 | 0.634628 | 5.1765 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/feature/CertificateFeature.kt | 1 | 8177 | package no.skatteetaten.aurora.boober.feature
import com.fkorotkov.kubernetes.metadata
import com.fkorotkov.kubernetes.newSecret
import com.fkorotkov.kubernetes.newVolume
import com.fkorotkov.kubernetes.newVolumeMount
import com.fkorotkov.kubernetes.secret
import io.fabric8.kubernetes.api.model.OwnerReference
import io.fabric8.kubernetes.api.model.Secret
import mu.KotlinLogging
import no.skatteetaten.aurora.boober.model.AuroraConfigFieldHandler
import no.skatteetaten.aurora.boober.model.AuroraContextCommand
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
import no.skatteetaten.aurora.boober.model.AuroraResource
import no.skatteetaten.aurora.boober.model.Paths.secretsPath
import no.skatteetaten.aurora.boober.model.addVolumesAndMounts
import no.skatteetaten.aurora.boober.service.resourceprovisioning.StsProvisioner
import no.skatteetaten.aurora.boober.service.resourceprovisioning.StsProvisioningResult
import no.skatteetaten.aurora.boober.utils.ConditionalOnPropertyMissingOrEmpty
import no.skatteetaten.aurora.boober.utils.addIfNotNull
import no.skatteetaten.aurora.boober.utils.boolean
import no.skatteetaten.aurora.boober.utils.normalizeLabels
import org.apache.commons.codec.binary.Base64
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Service
import java.io.ByteArrayOutputStream
import java.util.Properties
val AuroraDeploymentSpec.certificateCommonName: String?
get() {
val simplified = this.isSimplifiedConfig("certificate")
if (!simplified) {
return this.getOrNull("certificate/commonName")
}
val value: Boolean = this["certificate"]
if (!value) {
return null
}
val groupId: String = this.getOrNull<String>("groupId") ?: ""
return "$groupId.${this.name}"
}
private val logger = KotlinLogging.logger { }
@ConditionalOnPropertyMissingOrEmpty("integrations.skap.url")
@Service
class CertificateDisabledFeature : Feature {
override fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> {
return setOf(
AuroraConfigFieldHandler(
"certificate",
defaultValue = false,
validator = { it.boolean() },
canBeSimplifiedConfig = true
),
AuroraConfigFieldHandler("certificate/commonName"),
header.groupIdHandler
)
}
override fun validate(
adc: AuroraDeploymentSpec,
fullValidation: Boolean,
context: FeatureContext
): List<Exception> {
adc.certificateCommonName?.let {
if (it.isNotEmpty()) {
return listOf(IllegalArgumentException("STS is not supported."))
}
}
return emptyList()
}
}
@Service
@ConditionalOnProperty("integrations.skap.url")
class CertificateFeature(val sts: StsProvisioner) : Feature {
private val suffix = "cert"
override fun handlers(header: AuroraDeploymentSpec, cmd: AuroraContextCommand): Set<AuroraConfigFieldHandler> {
return setOf(
AuroraConfigFieldHandler(
"certificate",
defaultValue = false,
validator = { it.boolean() },
canBeSimplifiedConfig = true
),
AuroraConfigFieldHandler("certificate/commonName"),
header.groupIdHandler
)
}
override fun generate(adc: AuroraDeploymentSpec, context: FeatureContext): Set<AuroraResource> {
return adc.certificateCommonName?.let {
val result = sts.generateCertificate(it, adc.name, adc.envName)
val secret = StsSecretGenerator.create(adc.name, result, adc.namespace)
setOf(generateResource(secret))
} ?: emptySet()
}
override fun modify(
adc: AuroraDeploymentSpec,
resources: Set<AuroraResource>,
context: FeatureContext
) {
adc.certificateCommonName?.let {
StsSecretGenerator.attachSecret(
appName = adc.name,
certSuffix = suffix,
resources = resources,
source = this::class.java
)
}
}
fun willCreateResource(spec: AuroraDeploymentSpec) = spec.certificateCommonName != null
}
object StsSecretGenerator {
const val RENEW_AFTER_LABEL = "stsRenewAfter"
const val APP_ANNOTATION = "gillis.skatteetaten.no/app"
const val COMMON_NAME_ANNOTATION = "gillis.skatteetaten.no/commonName"
private fun createBasePath(sName: String) = "$secretsPath/$sName"
private fun createSecretName(appName: String, certSuffix: String) = "$appName-$certSuffix"
fun attachSecret(
appName: String,
certSuffix: String,
resources: Set<AuroraResource>,
source: Class<out Feature>,
additionalEnv: Map<String, String> = emptyMap()
) {
val sName = createSecretName(appName, certSuffix)
val baseUrl = createBasePath(sName)
val stsVars = mapOf(
"STS_CERTIFICATE_URL" to "$baseUrl/certificate.crt",
"STS_PRIVATE_KEY_URL" to "$baseUrl/privatekey.key",
"STS_KEYSTORE_DESCRIPTOR" to "$baseUrl/descriptor.properties",
"VOLUME_$sName".uppercase() to baseUrl
).addIfNotNull(additionalEnv)
.toEnvVars()
val mount = newVolumeMount {
name = sName
mountPath = baseUrl
}
val volume = newVolume {
name = sName
secret {
secretName = sName
}
}
resources.addVolumesAndMounts(stsVars, listOf(volume), listOf(mount), source)
}
fun create(
appName: String,
stsProvisionResults: StsProvisioningResult,
secretNamespace: String,
certSuffix: String = "cert"
): Secret {
val secretName = createSecretName(appName, certSuffix)
val baseUrl = "${createBasePath(secretName)}/keystore.jks"
val cert = stsProvisionResults.cert
return newSecret {
metadata {
labels =
mapOf(RENEW_AFTER_LABEL to stsProvisionResults.renewAt.epochSecond.toString()).normalizeLabels()
name = secretName
namespace = secretNamespace
annotations = mapOf(
APP_ANNOTATION to appName,
COMMON_NAME_ANNOTATION to stsProvisionResults.cn
)
}
data = mapOf(
"privatekey.key" to cert.key,
"keystore.jks" to cert.keystore,
"certificate.crt" to cert.crt,
"descriptor.properties" to createDescriptorFile(
jksPath = baseUrl,
alias = "ca",
storePassword = cert.storePassword,
keyPassword = cert.keyPassword
)
).mapValues { Base64.encodeBase64String(it.value) }
}
}
fun create(
appName: String,
stsProvisionResults: StsProvisioningResult,
labels: Map<String, String>,
ownerReference: OwnerReference,
namespace: String,
suffix: String
): Secret {
val secret = create(
appName = appName,
stsProvisionResults = stsProvisionResults,
secretNamespace = namespace,
certSuffix = suffix
)
secret.metadata.labels = labels.addIfNotNull(secret.metadata?.labels).normalizeLabels()
secret.metadata.ownerReferences = listOf(ownerReference)
return secret
}
fun createDescriptorFile(
jksPath: String,
alias: String,
storePassword: String,
keyPassword: String
): ByteArray {
return Properties().run {
put("keystore-file", jksPath)
put("alias", alias)
put("store-password", storePassword)
put("key-password", keyPassword)
val bos = ByteArrayOutputStream()
store(bos, "")
bos.toByteArray()
}
}
}
| apache-2.0 | 91fd9cf37f171018d1144c8af218f283 | 33.795745 | 116 | 0.637887 | 4.893477 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/text/StringTest/replaceDelimited.kt | 2 | 1232 | import kotlin.test.*
fun box() {
val s = "/user/folder/file.extension"
// chars
assertEquals("/user/folder/file.doc", s.replaceAfter('.', "doc"))
assertEquals("/user/folder/another.doc", s.replaceAfterLast('/', "another.doc"))
assertEquals("new name.extension", s.replaceBefore('.', "new name"))
assertEquals("/new/path/file.extension", s.replaceBeforeLast('/', "/new/path"))
// strings
assertEquals("/user/folder/file.doc", s.replaceAfter(".", "doc"))
assertEquals("/user/folder/another.doc", s.replaceAfterLast("/", "another.doc"))
assertEquals("new name.extension", s.replaceBefore(".", "new name"))
assertEquals("/new/path/file.extension", s.replaceBeforeLast("/", "/new/path"))
// non-existing delimiter
assertEquals("/user/folder/file.extension", s.replaceAfter("=", "doc"))
assertEquals("/user/folder/file.extension", s.replaceAfterLast("=", "another.doc"))
assertEquals("/user/folder/file.extension", s.replaceBefore("=", "new name"))
assertEquals("/user/folder/file.extension", s.replaceBeforeLast("=", "/new/path"))
assertEquals("xxx", s.replaceBefore("=", "new name", "xxx"))
assertEquals("xxx", s.replaceBeforeLast("=", "/new/path", "xxx"))
}
| apache-2.0 | 190ebfb7f169bd4372210de3b3172542 | 46.384615 | 87 | 0.659091 | 3.911111 | false | false | false | false |
blokadaorg/blokada | android5/app/src/main/java/ui/stats/RetentionFragment.kt | 1 | 1563 | /*
* This file is part of Blokada.
*
* 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 https://mozilla.org/MPL/2.0/.
*
* Copyright © 2021 Blocka AB. All rights reserved.
*
* @author Karol Gusak ([email protected])
*/
package ui.stats
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import org.blokada.R
import repository.Repos
import utils.Links
class RetentionFragment : Fragment() {
private val cloudRepo by lazy { Repos.cloud }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_retention, container, false)
// TODO: same code in StatsFragment
val retention: StatsRetentionView = root.findViewById(R.id.activity_retention)
retention.lifecycleScope = lifecycleScope
retention.openPolicy = {
val nav = findNavController()
nav.navigate(
RetentionFragmentDirections.actionRetentionFragmentToWebFragment(
Links.privacy, getString(R.string.payment_action_terms_and_privacy)
)
)
}
retention.setup()
return root
}
}
| mpl-2.0 | f372a80c321d7e92dd3cc84fb0c64bf6 | 28.471698 | 87 | 0.681818 | 4.475645 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/increment/prefixIncrementOnSmartCast.kt | 3 | 193 | public fun box() : String {
var i : Int?
i = 10
// Prefix increment on a smart cast should work
val j = ++i
return if (j == 11 && 11 == i) "OK" else "fail j = $j i = $i"
}
| apache-2.0 | 8ea5b2da1dfb43f4765803725e81eeae | 23.125 | 65 | 0.507772 | 3.063492 | false | false | false | false |
smmribeiro/intellij-community | plugins/ide-features-trainer/src/training/statistic/StatisticBase.kt | 1 | 17102 | // 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 training.statistic
import com.intellij.ide.TipsOfTheDayUsagesCollector.TipInfoValidationRule
import com.intellij.ide.plugins.PluginManager
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.events.*
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.keymap.Keymap
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.impl.DefaultKeymapImpl
import com.intellij.openapi.util.BuildNumber
import com.intellij.util.TimeoutUtil
import training.lang.LangManager
import training.learn.CourseManager
import training.learn.course.IftModule
import training.learn.course.Lesson
import training.learn.lesson.LessonManager
import training.statistic.FeatureUsageStatisticConsts.ACTION_ID
import training.statistic.FeatureUsageStatisticConsts.COMPLETED_COUNT
import training.statistic.FeatureUsageStatisticConsts.COURSE_SIZE
import training.statistic.FeatureUsageStatisticConsts.DURATION
import training.statistic.FeatureUsageStatisticConsts.EXPAND_WELCOME_PANEL
import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_ENTRY_PLACE
import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_EXPERIENCED_USER
import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_HAS_BEEN_SENT
import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_LIKENESS_ANSWER
import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_OPENED_VIA_NOTIFICATION
import training.statistic.FeatureUsageStatisticConsts.HELP_LINK_CLICKED
import training.statistic.FeatureUsageStatisticConsts.KEYMAP_SCHEME
import training.statistic.FeatureUsageStatisticConsts.LANGUAGE
import training.statistic.FeatureUsageStatisticConsts.LAST_BUILD_LEARNING_OPENED
import training.statistic.FeatureUsageStatisticConsts.LEARN_PROJECT_OPENED_FIRST_TIME
import training.statistic.FeatureUsageStatisticConsts.LEARN_PROJECT_OPENING_WAY
import training.statistic.FeatureUsageStatisticConsts.LESSON_ID
import training.statistic.FeatureUsageStatisticConsts.LESSON_LINK_CLICKED_FROM_TIP
import training.statistic.FeatureUsageStatisticConsts.LESSON_STARTING_WAY
import training.statistic.FeatureUsageStatisticConsts.MODULE_NAME
import training.statistic.FeatureUsageStatisticConsts.NEED_SHOW_NEW_LESSONS_NOTIFICATIONS
import training.statistic.FeatureUsageStatisticConsts.NEW_LESSONS_COUNT
import training.statistic.FeatureUsageStatisticConsts.NEW_LESSONS_NOTIFICATION_SHOWN
import training.statistic.FeatureUsageStatisticConsts.NON_LEARNING_PROJECT_OPENED
import training.statistic.FeatureUsageStatisticConsts.ONBOARDING_FEEDBACK_DIALOG_RESULT
import training.statistic.FeatureUsageStatisticConsts.ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN
import training.statistic.FeatureUsageStatisticConsts.PASSED
import training.statistic.FeatureUsageStatisticConsts.PROGRESS
import training.statistic.FeatureUsageStatisticConsts.REASON
import training.statistic.FeatureUsageStatisticConsts.RESTORE
import training.statistic.FeatureUsageStatisticConsts.SHORTCUT_CLICKED
import training.statistic.FeatureUsageStatisticConsts.SHOULD_SHOW_NEW_LESSONS
import training.statistic.FeatureUsageStatisticConsts.SHOW_NEW_LESSONS
import training.statistic.FeatureUsageStatisticConsts.START
import training.statistic.FeatureUsageStatisticConsts.START_MODULE_ACTION
import training.statistic.FeatureUsageStatisticConsts.STOPPED
import training.statistic.FeatureUsageStatisticConsts.TASK_ID
import training.statistic.FeatureUsageStatisticConsts.TIP_FILENAME
import training.util.KeymapUtil
import java.awt.event.KeyEvent
import java.util.concurrent.ConcurrentHashMap
import javax.swing.JOptionPane
enum class LessonStartingWay {
NEXT_BUTTON, PREV_BUTTON, RESTART_BUTTON, RESTORE_LINK, ONBOARDING_PROMOTER, LEARN_TAB, TIP_AND_TRICK_PROMOTER
}
internal enum class FeedbackEntryPlace {
WELCOME_SCREEN, LEARNING_PROJECT, ANOTHER_PROJECT
}
internal enum class FeedbackLikenessAnswer {
NO_ANSWER, LIKE, DISLIKE
}
internal class StatisticBase : CounterUsagesCollector() {
override fun getGroup() = GROUP
private data class LessonProgress(val lessonId: String, val taskId: Int)
enum class LearnProjectOpeningWay {
LEARN_IDE, ONBOARDING_PROMOTER
}
enum class LessonStopReason {
CLOSE_PROJECT, RESTART, CLOSE_FILE, OPEN_MODULES, OPEN_NEXT_OR_PREV_LESSON, EXIT_LINK
}
companion object {
private val LOG = logger<StatisticBase>()
private val sessionLessonTimestamp: ConcurrentHashMap<String, Long> = ConcurrentHashMap()
private var prevRestoreLessonProgress: LessonProgress = LessonProgress("", 0)
private val GROUP: EventLogGroup = EventLogGroup("ideFeaturesTrainer", 16)
var isLearnProjectCloseLogged = false
// FIELDS
private val lessonIdField = EventFields.StringValidatedByCustomRule(LESSON_ID, LESSON_ID)
private val languageField = EventFields.StringValidatedByCustomRule(LANGUAGE, LANGUAGE)
private val completedCountField = EventFields.Int(COMPLETED_COUNT)
private val courseSizeField = EventFields.Int(COURSE_SIZE)
private val moduleNameField = EventFields.StringValidatedByCustomRule(MODULE_NAME, MODULE_NAME)
private val taskIdField = EventFields.StringValidatedByCustomRule(TASK_ID, TASK_ID)
private val actionIdField = EventFields.StringValidatedByCustomRule(ACTION_ID, ACTION_ID)
private val keymapSchemeField = EventFields.StringValidatedByCustomRule(KEYMAP_SCHEME, KEYMAP_SCHEME)
private val versionField = EventFields.Version
private val inputEventField = EventFields.InputEvent
private val learnProjectOpeningWayField = EventFields.Enum<LearnProjectOpeningWay>(LEARN_PROJECT_OPENING_WAY)
private val reasonField = EventFields.Enum<LessonStopReason>(REASON)
private val newLessonsCount = EventFields.Int(NEW_LESSONS_COUNT)
private val showNewLessonsState = EventFields.Boolean(SHOULD_SHOW_NEW_LESSONS)
private val tipFilenameField = EventFields.StringValidatedByCustomRule(TIP_FILENAME, TipInfoValidationRule.RULE_ID)
private val lessonStartingWayField = EventFields.Enum<LessonStartingWay>(LESSON_STARTING_WAY)
private val feedbackEntryPlace = EventFields.Enum<FeedbackEntryPlace>(FEEDBACK_ENTRY_PLACE)
private val feedbackHasBeenSent = EventFields.Boolean(FEEDBACK_HAS_BEEN_SENT)
private val feedbackOpenedViaNotification = EventFields.Boolean(FEEDBACK_OPENED_VIA_NOTIFICATION)
private val feedbackLikenessAnswer = EventFields.Enum<FeedbackLikenessAnswer>(FEEDBACK_LIKENESS_ANSWER)
private val feedbackExperiencedUser = EventFields.Boolean(FEEDBACK_EXPERIENCED_USER)
private val lastBuildLearningOpened = object : PrimitiveEventField<String?>() {
override val name: String = LAST_BUILD_LEARNING_OPENED
override val validationRule: List<String>
get() = listOf("{regexp#version}")
override fun addData(fuData: FeatureUsageData, value: String?) {
if (value != null) {
fuData.addData(name, value)
}
}
}
// EVENTS
private val lessonStartedEvent: EventId3<String?, String?, LessonStartingWay> = GROUP.registerEvent(START, lessonIdField, languageField,
lessonStartingWayField)
private val lessonPassedEvent: EventId3<String?, String?, Long> = GROUP.registerEvent(PASSED, lessonIdField, languageField,
EventFields.Long(DURATION))
private val lessonStoppedEvent = GROUP.registerVarargEvent(STOPPED, lessonIdField, taskIdField, languageField, reasonField)
private val progressUpdatedEvent = GROUP.registerVarargEvent(PROGRESS, lessonIdField, completedCountField, courseSizeField,
languageField)
private val moduleStartedEvent: EventId2<String?, String?> = GROUP.registerEvent(START_MODULE_ACTION, moduleNameField, languageField)
private val welcomeScreenPanelExpandedEvent: EventId1<String?> = GROUP.registerEvent(EXPAND_WELCOME_PANEL, languageField)
private val shortcutClickedEvent = GROUP.registerVarargEvent(SHORTCUT_CLICKED, inputEventField, keymapSchemeField,
lessonIdField, taskIdField, actionIdField, versionField)
private val restorePerformedEvent = GROUP.registerVarargEvent(RESTORE, lessonIdField, taskIdField, versionField)
private val learnProjectOpenedFirstTimeEvent: EventId2<LearnProjectOpeningWay, String?> =
GROUP.registerEvent(LEARN_PROJECT_OPENED_FIRST_TIME, learnProjectOpeningWayField, languageField)
private val nonLearningProjectOpened: EventId1<LearnProjectOpeningWay> =
GROUP.registerEvent(NON_LEARNING_PROJECT_OPENED, learnProjectOpeningWayField)
private val newLessonsNotificationShown =
GROUP.registerEvent(NEW_LESSONS_NOTIFICATION_SHOWN, newLessonsCount, lastBuildLearningOpened)
private val showNewLessonsEvent =
GROUP.registerEvent(SHOW_NEW_LESSONS, newLessonsCount, lastBuildLearningOpened)
private val needShowNewLessonsNotifications =
GROUP.registerEvent(NEED_SHOW_NEW_LESSONS_NOTIFICATIONS, newLessonsCount, lastBuildLearningOpened, showNewLessonsState)
private val lessonLinkClickedFromTip = GROUP.registerEvent(LESSON_LINK_CLICKED_FROM_TIP, lessonIdField, languageField, tipFilenameField)
private val helpLinkClicked = GROUP.registerEvent(HELP_LINK_CLICKED, lessonIdField, languageField)
private val onboardingFeedbackNotificationShown = GROUP.registerEvent(ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN,
feedbackEntryPlace)
private val onboardingFeedbackDialogResult = GROUP.registerVarargEvent(ONBOARDING_FEEDBACK_DIALOG_RESULT,
feedbackEntryPlace,
feedbackHasBeenSent,
feedbackOpenedViaNotification,
feedbackLikenessAnswer,
feedbackExperiencedUser,
)
// LOGGING
fun logLessonStarted(lesson: Lesson, startingWay: LessonStartingWay) {
sessionLessonTimestamp[lesson.id] = System.nanoTime()
lessonStartedEvent.log(lesson.id, courseLanguage(), startingWay)
}
fun logLessonPassed(lesson: Lesson) {
val timestamp = sessionLessonTimestamp[lesson.id]
if (timestamp == null) {
LOG.warn("Unable to find timestamp for a lesson: ${lesson.name}")
return
}
val delta = TimeoutUtil.getDurationMillis(timestamp)
lessonPassedEvent.log(lesson.id, courseLanguage(), delta)
progressUpdatedEvent.log(lessonIdField with lesson.id,
completedCountField with completedCount(),
courseSizeField with CourseManager.instance.lessonsForModules.size,
languageField with courseLanguage())
}
fun logLessonStopped(reason: LessonStopReason) {
val lessonManager = LessonManager.instance
if (lessonManager.lessonIsRunning()) {
val lessonId = lessonManager.currentLesson!!.id
val taskId = lessonManager.currentLessonExecutor!!.currentTaskIndex
lessonStoppedEvent.log(lessonIdField with lessonId,
taskIdField with taskId.toString(),
languageField with courseLanguage(),
reasonField with reason
)
if (reason == LessonStopReason.CLOSE_PROJECT || reason == LessonStopReason.EXIT_LINK) {
isLearnProjectCloseLogged = true
}
}
}
fun logModuleStarted(module: IftModule) {
moduleStartedEvent.log(module.id, courseLanguage())
}
fun logWelcomeScreenPanelExpanded() {
welcomeScreenPanelExpandedEvent.log(courseLanguage())
}
fun logShortcutClicked(actionId: String) {
val lessonManager = LessonManager.instance
if (lessonManager.lessonIsRunning()) {
val lesson = lessonManager.currentLesson!!
val keymap = getDefaultKeymap() ?: return
shortcutClickedEvent.log(inputEventField with createInputEvent(actionId),
keymapSchemeField with keymap.name,
lessonIdField with lesson.id,
taskIdField with lessonManager.currentLessonExecutor?.currentTaskIndex.toString(),
actionIdField with actionId,
versionField with getPluginVersion(lesson))
}
}
fun logRestorePerformed(lesson: Lesson, taskId: Int) {
val curLessonProgress = LessonProgress(lesson.id, taskId)
if (curLessonProgress != prevRestoreLessonProgress) {
prevRestoreLessonProgress = curLessonProgress
restorePerformedEvent.log(lessonIdField with lesson.id,
taskIdField with taskId.toString(),
versionField with getPluginVersion(lesson))
}
}
fun logLearnProjectOpenedForTheFirstTime(way: LearnProjectOpeningWay) {
val langManager = LangManager.getInstance()
val langSupport = langManager.getLangSupport() ?: return
if (langManager.getLearningProjectPath(langSupport) == null) {
LearnProjectState.instance.firstTimeOpenedWay = way
learnProjectOpenedFirstTimeEvent.log(way, courseLanguage())
}
}
fun logNonLearningProjectOpened(way: LearnProjectOpeningWay) {
nonLearningProjectOpened.log(way)
}
fun logNewLessonsNotification(newLessonsCount: Int, previousOpenedVersion: BuildNumber?) {
newLessonsNotificationShown.log(newLessonsCount, previousOpenedVersion?.asString())
}
fun logShowNewLessonsEvent(newLessonsCount: Int, previousOpenedVersion: BuildNumber?) {
showNewLessonsEvent.log(newLessonsCount, previousOpenedVersion?.asString())
}
fun logShowNewLessonsNotificationState(newLessonsCount: Int, previousOpenedVersion: BuildNumber?, showNewLessons: Boolean) {
needShowNewLessonsNotifications.log(newLessonsCount, previousOpenedVersion?.asString(), showNewLessons)
}
fun logLessonLinkClickedFromTip(lessonId: String, tipFilename: String) {
lessonLinkClickedFromTip.log(lessonId, courseLanguage(), tipFilename)
}
fun logHelpLinkClicked(lessonId: String) {
helpLinkClicked.log(lessonId, courseLanguage())
}
fun logOnboardingFeedbackNotification(place: FeedbackEntryPlace) {
onboardingFeedbackNotificationShown.log(place)
}
fun logOnboardingFeedbackDialogResult(place: FeedbackEntryPlace,
hasBeenSent: Boolean,
openedViaNotification: Boolean,
likenessAnswer: FeedbackLikenessAnswer,
experiencedUser: Boolean) {
onboardingFeedbackDialogResult.log(
feedbackEntryPlace with place,
feedbackHasBeenSent with hasBeenSent,
feedbackOpenedViaNotification with openedViaNotification,
feedbackLikenessAnswer with likenessAnswer,
feedbackExperiencedUser with experiencedUser
)
}
private fun courseLanguage() = LangManager.getInstance().getLangSupport()?.primaryLanguage?.toLowerCase() ?: ""
private fun completedCount(): Int = CourseManager.instance.lessonsForModules.count { it.passed }
private fun createInputEvent(actionId: String): FusInputEvent? {
val keyStroke = KeymapUtil.getShortcutByActionId(actionId) ?: return null
val inputEvent = KeyEvent(JOptionPane.getRootFrame(),
KeyEvent.KEY_PRESSED,
System.currentTimeMillis(),
keyStroke.modifiers,
keyStroke.keyCode,
keyStroke.keyChar,
KeyEvent.KEY_LOCATION_STANDARD)
return FusInputEvent(inputEvent, "")
}
private fun getPluginVersion(lesson: Lesson): String? {
return PluginManager.getPluginByClass(lesson::class.java)?.version
}
private fun getDefaultKeymap(): Keymap? {
val keymap = KeymapManager.getInstance().activeKeymap
if (keymap is DefaultKeymapImpl) {
return keymap
}
return keymap.parent as? DefaultKeymapImpl
}
}
} | apache-2.0 | a2ff6020540fab9d7630c639bcb4f5a7 | 52.783019 | 158 | 0.726816 | 5.212435 | false | false | false | false |
kickstarter/android-oss | app/src/test/java/com/kickstarter/models/ProjectNotificationBodyTest.kt | 1 | 1932 | package com.kickstarter.models
import com.kickstarter.KSRobolectricTestCase
import com.kickstarter.services.apirequests.ProjectNotificationBody
import org.junit.Test
class ProjectNotificationBodyTest : KSRobolectricTestCase() {
@Test
fun testDefaultInit() {
val projectNotificationBody = ProjectNotificationBody.builder()
.email(true)
.mobile(true)
.build()
assertTrue(projectNotificationBody.email())
assertTrue(projectNotificationBody.mobile())
}
@Test
fun testDefaultToBuilder() {
val projectNotificationBody = ProjectNotificationBody.builder().build().toBuilder().email(true).build()
assertTrue(projectNotificationBody.email())
}
@Test
fun testProjectNotificationBody_equalFalse() {
val projectNotificationBody = ProjectNotificationBody.builder().build()
val projectNotificationBody2 = ProjectNotificationBody.builder()
.email(true).build()
val projectNotificationBody3 = ProjectNotificationBody.builder()
.mobile(true)
.build()
val projectNotificationBody4 = ProjectNotificationBody.builder()
.email(true)
.mobile(true)
.build()
assertFalse(projectNotificationBody == projectNotificationBody2)
assertFalse(projectNotificationBody == projectNotificationBody3)
assertFalse(projectNotificationBody == projectNotificationBody4)
assertFalse(projectNotificationBody3 == projectNotificationBody2)
assertFalse(projectNotificationBody3 == projectNotificationBody4)
}
@Test
fun testProjectNotificationBody_equalTrue() {
val projectNotificationBody1 = ProjectNotificationBody.builder().build()
val projectNotificationBody2 = ProjectNotificationBody.builder().build()
assertEquals(projectNotificationBody1, projectNotificationBody2)
}
}
| apache-2.0 | 37d04186bf041045172851387ed121f7 | 34.777778 | 111 | 0.712733 | 5.567723 | false | true | false | false |
ingokegel/intellij-community | tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/runner/TestWatcherActions.kt | 1 | 1843 | package com.intellij.ide.starter.runner
import com.intellij.ide.starter.ide.IDETestContext
import com.intellij.ide.starter.utils.catchAll
import com.intellij.ide.starter.utils.logOutput
import com.intellij.util.io.exists
import java.util.*
class TestWatcherActions {
private val _onFailureActions: MutableList<(IDETestContext) -> Unit> = Collections.synchronizedList(mutableListOf())
val onFailureActions: List<(IDETestContext) -> Unit>
get() = synchronized(_onFailureActions) { _onFailureActions.toList() }
private val _onFinishedActions: MutableList<(IDETestContext) -> Unit> = Collections.synchronizedList(mutableListOf())
val onFinishedActions: List<(IDETestContext) -> Unit>
get() = synchronized(_onFinishedActions) { _onFinishedActions.toList() }
companion object {
/** Archive and add to test artifact entire ide's `system` dir */
fun getSystemDirAsArtifactAction(): (IDETestContext) -> Unit = { testContext ->
catchAll {
logOutput("Archive with system directory created and will be published to artifacts")
testContext.publishArtifact(source = testContext.paths.systemDir, artifactName = "testSystemDirSnapshot.zip")
val ideaDirPath = testContext.resolvedProjectHome.resolve(".idea")
if (ideaDirPath.exists()) {
logOutput("Archive with .idea dir created and will be published to artifacts")
testContext.publishArtifact(source = ideaDirPath, artifactName = ".idea.zip")
}
}
}
}
fun addOnFailureAction(action: (IDETestContext) -> Unit): TestWatcherActions {
synchronized(_onFailureActions) { _onFailureActions.add(action) }
return this
}
fun addOnFinishedAction(action: (IDETestContext) -> Unit): TestWatcherActions {
synchronized(_onFinishedActions) { _onFinishedActions.add(action) }
return this
}
} | apache-2.0 | c9b6f2802a11cb8231d7f5d04f8d81de | 40.909091 | 119 | 0.734672 | 4.528256 | false | true | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/utils/StringParser.kt | 1 | 1205 | package slatekit.common.utils
class StringParser(private val content: String) {
private val extracts = mutableMapOf<String, String>()
private var pos = 0
private var lastMatch = false
fun extracts(): MutableMap<String, String> = extracts
fun saveUntil(token: String, name: String, ensure: Boolean = true): StringParser {
val start = pos
moveInternal(token, ensure)
if (lastMatch) {
val end = pos - token.length
val content = extract(start, end)
extracts.put(name, content)
}
return this
}
fun moveTo(token: String, ensure: Boolean = true): StringParser {
moveInternal(token, ensure)
return this
}
fun moveInternal(token: String, ensure: Boolean = true): StringParser {
val ndxMatch = content.indexOf(token, pos)
if (ensure && ndxMatch < 0) {
} else {
lastMatch = ndxMatch >= 0
if (ndxMatch >= 0) {
// Update pos to next position
pos = ndxMatch + token.length
}
}
return this
}
fun extract(start: Int, end: Int): String = content.substring(start, end)
}
| apache-2.0 | 4e5a7a1176bd0fc6bc7d7fe933ad1660 | 27.690476 | 86 | 0.580913 | 4.303571 | false | false | false | false |
siosio/intellij-community | plugins/ide-features-trainer/src/training/dsl/TaskContext.kt | 1 | 10283 | // 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 training.dsl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.ui.tree.TreeVisitor
import com.intellij.util.ui.tree.TreeUtil
import org.intellij.lang.annotations.Language
import org.jetbrains.annotations.Nls
import training.learn.LearnBundle
import training.ui.LearningUiHighlightingManager
import java.awt.Component
import java.awt.Rectangle
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Future
import javax.swing.JList
import javax.swing.JTree
import javax.swing.tree.TreePath
@LearningDsl
abstract class TaskContext : LearningDslBase {
abstract val project: Project
open val taskId: TaskId = TaskId(0)
/**
* This property can be set to the true if you want that the next task restore will jump over the current task.
* Default `null` value is reserved for the future automatic transparent restore calculation.
*/
open var transparentRestore: Boolean? = null
/**
* Can be set to true iff you need to rehighlight the triggered element from the previous task when it will be shown again.
* Note: that the rehighlighted element can be different from `previous?.ui` (it can become `null` or `!isValid` or `!isShowing`)
* */
open var rehighlightPreviousUi: Boolean? = null
/** Put here some initialization for the task */
open fun before(preparation: TaskRuntimeContext.() -> Unit) = Unit
/**
* @param [restoreId] where to restore, `null` means the previous task
* @param [delayMillis] the delay before restore actions can be applied.
* Delay may be needed to give pass condition take place.
* It is a hack solution because of possible race conditions.
* @param [restoreRequired] returns true iff restore is needed
*/
open fun restoreState(restoreId: TaskId? = null, delayMillis: Int = 0, restoreRequired: TaskRuntimeContext.() -> Boolean) = Unit
/** Shortcut */
fun restoreByUi(restoreId: TaskId? = null, delayMillis: Int = 0) {
restoreState(restoreId, delayMillis) {
previous.ui?.isShowing?.not() ?: true
}
}
/** Restore when timer is out. Is needed for chained tasks. */
open fun restoreByTimer(delayMillis: Int = 2000, restoreId: TaskId? = null) = Unit
data class RestoreNotification(@Nls val message: String,
@Nls val restoreLinkText: String = LearnBundle.message("learn.restore.default.link.text"),
val callback: () -> Unit)
open fun proposeRestore(restoreCheck: TaskRuntimeContext.() -> RestoreNotification?) = Unit
open fun showWarning(@Language("HTML") @Nls text: String,
restoreTaskWhenResolved: Boolean = false,
warningRequired: TaskRuntimeContext.() -> Boolean) = Unit
/**
* Write a text to the learn panel (panel with a learning tasks).
*/
open fun text(@Language("HTML") @Nls text: String, useBalloon: LearningBalloonConfig? = null) = Unit
/** Insert text in the current position */
open fun type(text: String) = Unit
/** Write a text to the learn panel (panel with a learning tasks). */
open fun runtimeText(@Nls callback: RuntimeTextContext.() -> String?) = Unit
/** Simply wait until an user perform particular action */
open fun trigger(actionId: String) = Unit
/** Simply wait until an user perform actions */
open fun trigger(checkId: (String) -> Boolean) = Unit
/** Trigger on actions start. Needs if you want to split long actions into several tasks. */
open fun triggerStart(actionId: String, checkState: TaskRuntimeContext.() -> Boolean = { true }) = Unit
/** [actionIds] these actions required for the current task */
open fun triggers(vararg actionIds: String) = Unit
/** An user need to rice an action which leads to necessary state change */
open fun <T : Any?> trigger(actionId: String,
calculateState: TaskRuntimeContext.() -> T,
checkState: TaskRuntimeContext.(T, T) -> Boolean) = Unit
/** An user need to rice an action which leads to appropriate end state */
fun trigger(actionId: String, checkState: TaskRuntimeContext.() -> Boolean) {
trigger(actionId, { }, { _, _ -> checkState() })
}
/**
* Check that IDE state is as expected
* In some rare cases DSL could wish to complete a future by itself
*/
open fun stateCheck(checkState: TaskRuntimeContext.() -> Boolean): CompletableFuture<Boolean> = CompletableFuture()
/**
* Check that IDE state is fit
* @return A feature with value associated with fit state
*/
open fun <T : Any> stateRequired(requiredState: TaskRuntimeContext.() -> T?): Future<T> = CompletableFuture()
open fun addFutureStep(p: DoneStepContext.() -> Unit) = Unit
open fun addStep(step: CompletableFuture<Boolean>) = Unit
/** [action] What should be done to pass the current task */
open fun test(waitEditorToBeReady: Boolean = true, action: TaskTestContext.() -> Unit) = Unit
fun triggerByFoundPathAndHighlight(highlightBorder: Boolean = true, highlightInside: Boolean = false, usePulsation: Boolean = false,
checkPath: TaskRuntimeContext.(tree: JTree, path: TreePath) -> Boolean) {
val options = LearningUiHighlightingManager.HighlightingOptions(highlightBorder, highlightInside, usePulsation)
triggerByFoundPathAndHighlight(options) { tree ->
TreeUtil.visitVisibleRows(tree, TreeVisitor { path ->
if (checkPath(tree, path)) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE
})
}
}
// This method later can be converted to the public (But I'm not sure it will be ever needed in a such form)
protected open fun triggerByFoundPathAndHighlight(options: LearningUiHighlightingManager.HighlightingOptions,
checkTree: TaskRuntimeContext.(tree: JTree) -> TreePath?) = Unit
inline fun <reified T : Component> triggerByPartOfComponent(highlightBorder: Boolean = true, highlightInside: Boolean = false,
usePulsation: Boolean = false,
noinline selector: ((candidates: Collection<T>) -> T?)? = null,
crossinline rectangle: TaskRuntimeContext.(T) -> Rectangle?) {
val componentClass = T::class.java
@Suppress("DEPRECATION")
triggerByFoundPathAndHighlightImpl(componentClass, highlightBorder, highlightInside, usePulsation, selector) { rectangle(it) }
}
@Deprecated("Use inline version")
open fun <T : Component> triggerByFoundPathAndHighlightImpl(componentClass: Class<T>,
highlightBorder: Boolean,
highlightInside: Boolean,
usePulsation: Boolean,
selector: ((candidates: Collection<T>) -> T?)?,
rectangle: TaskRuntimeContext.(T) -> Rectangle?) = Unit
fun triggerByListItemAndHighlight(highlightBorder: Boolean = true, highlightInside: Boolean = false, usePulsation: Boolean = false,
checkList: TaskRuntimeContext.(item: Any) -> Boolean) {
val options = LearningUiHighlightingManager.HighlightingOptions(highlightBorder, highlightInside, usePulsation)
triggerByFoundListItemAndHighlight(options) { ui: JList<*> ->
LessonUtil.findItem(ui) { checkList(it) }
}
}
// This method later can be converted to the public (But I'm not sure it will be ever needed in a such form
protected open fun triggerByFoundListItemAndHighlight(options: LearningUiHighlightingManager.HighlightingOptions,
checkList: TaskRuntimeContext.(list: JList<*>) -> Int?) = Unit
inline fun <reified ComponentType : Component> triggerByUiComponentAndHighlight(
highlightBorder: Boolean = true, highlightInside: Boolean = true, usePulsation: Boolean = false,
noinline selector: ((candidates: Collection<ComponentType>) -> ComponentType?)? = null,
crossinline finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean
) {
val componentClass = ComponentType::class.java
@Suppress("DEPRECATION")
triggerByUiComponentAndHighlightImpl(componentClass, highlightBorder, highlightInside, usePulsation, selector) { finderFunction(it) }
}
@Deprecated("Use inline version")
open fun <ComponentType : Component>
triggerByUiComponentAndHighlightImpl(componentClass: Class<ComponentType>,
highlightBorder: Boolean,
highlightInside: Boolean,
usePulsation: Boolean,
selector: ((candidates: Collection<ComponentType>) -> ComponentType?)?,
finderFunction: TaskRuntimeContext.(ComponentType) -> Boolean) = Unit
open fun caret(position: LessonSamplePosition) = before {
caret(position)
}
/** NOTE: [line] and [column] starts from 1 not from zero. So these parameters should be same as in editors. */
open fun caret(line: Int, column: Int) = before {
caret(line, column)
}
class DoneStepContext(private val future: CompletableFuture<Boolean>, rt: TaskRuntimeContext) : TaskRuntimeContext(rt) {
fun completeStep() {
ApplicationManager.getApplication().assertIsDispatchThread()
if (!future.isDone && !future.isCancelled) {
future.complete(true)
}
}
}
data class TaskId(val idx: Int)
companion object {
val CaretRestoreProposal: String
get() = LearnBundle.message("learn.restore.notification.caret.message")
val ModificationRestoreProposal: String
get() = LearnBundle.message("learn.restore.notification.modification.message")
}
}
| apache-2.0 | 562fa4d510c3c4810508fd51142a9a88 | 47.966667 | 140 | 0.661675 | 5.182964 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/utils.kt | 1 | 973 | // 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
fun Class<*>.getMethodOrNull(name: String, vararg parameterTypes: Class<*>) =
try {
getMethod(name, *parameterTypes)
} catch (e: Exception) {
null
}
fun Class<*>.getDeclaredMethodOrNull(name: String, vararg parameterTypes: Class<*>) =
try {
getDeclaredMethod(name, *parameterTypes)?.also { it.isAccessible = true }
} catch (e: Exception) {
null
}
fun ClassLoader.loadClassOrNull(name: String): Class<*>? {
return try {
loadClass(name)
} catch (e: LinkageError) {
return null
} catch (e: ClassNotFoundException) {
return null
}
}
fun compilationFullName(simpleName: String, classifier: String?) =
if (classifier != null) classifier + simpleName.capitalize() else simpleName
| apache-2.0 | 6d28a64a1df3bc9b5f6cd68558a1a434 | 31.433333 | 158 | 0.670092 | 4.363229 | false | false | false | false |
actions-on-google/app-actions-dynamic-shortcuts | app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailViewModel.kt | 1 | 4128 | /*
* Copyright (C) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.taskdetail
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.example.android.architecture.blueprints.todoapp.Event
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.data.Result
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import kotlinx.coroutines.launch
/**
* ViewModel for the Details screen.
*/
class TaskDetailViewModel(
private val tasksRepository: TasksRepository
) : ViewModel() {
private val _taskId = MutableLiveData<String>()
private val _task = _taskId.switchMap { taskId ->
tasksRepository.observeTask(taskId).map { computeResult(it) }
}
val task: LiveData<Task?> = _task
val isDataAvailable: LiveData<Boolean> = _task.map { it != null }
private val _dataLoading = MutableLiveData<Boolean>()
val dataLoading: LiveData<Boolean> = _dataLoading
private val _editTaskEvent = MutableLiveData<Event<Unit>>()
val editTaskEvent: LiveData<Event<Unit>> = _editTaskEvent
private val _deleteTaskEvent = MutableLiveData<Event<Unit>>()
val deleteTaskEvent: LiveData<Event<Unit>> = _deleteTaskEvent
private val _snackbarText = MutableLiveData<Event<Int>>()
val snackbarText: LiveData<Event<Int>> = _snackbarText
// This LiveData depends on another so we can use a transformation.
val completed: LiveData<Boolean> = _task.map { input: Task? ->
input?.isCompleted ?: false
}
fun deleteTask() = viewModelScope.launch {
_taskId.value?.let {
tasksRepository.deleteTask(it)
_deleteTaskEvent.value = Event(Unit)
}
}
fun editTask() {
_editTaskEvent.value = Event(Unit)
}
fun setCompleted(completed: Boolean) = viewModelScope.launch {
val task = _task.value ?: return@launch
if (completed) {
tasksRepository.completeTask(task)
showSnackbarMessage(R.string.task_marked_complete)
} else {
tasksRepository.activateTask(task)
showSnackbarMessage(R.string.task_marked_active)
}
}
fun start(taskId: String?) {
// If we're already loading or already loaded, return (might be a config change)
if (_dataLoading.value == true || taskId == _taskId.value) {
return
}
// Trigger the load
_taskId.value = taskId
}
private fun computeResult(taskResult: Result<Task>): Task? {
return if (taskResult is Success) {
taskResult.data
} else {
showSnackbarMessage(R.string.loading_tasks_error)
null
}
}
fun refresh() {
// Refresh the repository and the task will be updated automatically.
_task.value?.let {
_dataLoading.value = true
viewModelScope.launch {
tasksRepository.refreshTask(it.id)
_dataLoading.value = false
}
}
}
private fun showSnackbarMessage(@StringRes message: Int) {
_snackbarText.value = Event(message)
}
}
| apache-2.0 | 4031c8e42912dc575452f2a97baa623e | 33.4 | 88 | 0.686773 | 4.496732 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/codeInsight/ReferenceVariantsHelper.kt | 4 | 23685 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeInsight
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.incremental.KotlinLookupLocation
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi
import org.jetbrains.kotlin.load.kotlin.toSourceElement
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.calls.smartcasts.SmartCastManager
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.receivers.ClassQualifier
import org.jetbrains.kotlin.resolve.scopes.utils.collectAllFromMeAndParent
import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.synthetic.JavaSyntheticScopes
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.util.suppressedByNotPropertyList
import java.util.*
@OptIn(FrontendInternals::class)
class ReferenceVariantsHelper(
private val bindingContext: BindingContext,
private val resolutionFacade: ResolutionFacade,
private val moduleDescriptor: ModuleDescriptor,
private val visibilityFilter: (DeclarationDescriptor) -> Boolean,
private val notProperties: Set<FqNameUnsafe> = setOf()
) {
fun getReferenceVariants(
expression: KtSimpleNameExpression,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
filterOutJavaGettersAndSetters: Boolean = true,
filterOutShadowed: Boolean = true,
excludeNonInitializedVariable: Boolean = true,
useReceiverType: KotlinType? = null
): Collection<DeclarationDescriptor> = getReferenceVariants(
expression, CallTypeAndReceiver.detect(expression),
kindFilter, nameFilter, filterOutJavaGettersAndSetters, filterOutShadowed, excludeNonInitializedVariable, useReceiverType
)
fun getReferenceVariants(
contextElement: PsiElement,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
filterOutJavaGettersAndSetters: Boolean = true,
filterOutShadowed: Boolean = true,
excludeNonInitializedVariable: Boolean = true,
useReceiverType: KotlinType? = null
): Collection<DeclarationDescriptor> {
var variants: Collection<DeclarationDescriptor> =
getReferenceVariantsNoVisibilityFilter(contextElement, kindFilter, nameFilter, callTypeAndReceiver, useReceiverType)
.filter { !resolutionFacade.frontendService<DeprecationResolver>().isHiddenInResolution(it) && visibilityFilter(it) }
if (filterOutShadowed) {
ShadowedDeclarationsFilter.create(bindingContext, resolutionFacade, contextElement, callTypeAndReceiver)?.let {
variants = it.filter(variants)
}
}
if (filterOutJavaGettersAndSetters && kindFilter.kindMask.and(DescriptorKindFilter.FUNCTIONS_MASK) != 0) {
variants = filterOutJavaGettersAndSetters(variants)
}
if (excludeNonInitializedVariable && kindFilter.kindMask.and(DescriptorKindFilter.VARIABLES_MASK) != 0) {
variants = excludeNonInitializedVariable(variants, contextElement)
}
return variants
}
fun <TDescriptor : DeclarationDescriptor> filterOutJavaGettersAndSetters(variants: Collection<TDescriptor>): Collection<TDescriptor> {
val accessorMethodsToRemove = HashSet<FunctionDescriptor>()
val filteredVariants = variants.filter { it !is SyntheticJavaPropertyDescriptor || !it.suppressedByNotPropertyList(notProperties) }
for (variant in filteredVariants) {
if (variant is SyntheticJavaPropertyDescriptor) {
accessorMethodsToRemove.add(variant.getMethod.original)
val setter = variant.setMethod
if (setter != null && setter.returnType?.isUnit() == true) { // we do not filter out non-Unit setters
accessorMethodsToRemove.add(setter.original)
}
}
}
return filteredVariants.filter { it !is FunctionDescriptor || it.original !in accessorMethodsToRemove }
}
// filters out variable inside its initializer
fun excludeNonInitializedVariable(
variants: Collection<DeclarationDescriptor>,
contextElement: PsiElement
): Collection<DeclarationDescriptor> {
for (element in contextElement.parentsWithSelf) {
val parent = element.parent
if (parent is KtVariableDeclaration && element == parent.initializer) {
return variants.filter { it.findPsi() != parent }
} else if (element is KtParameter) {
// Filter out parameters initialized after the current parameter. For example
// ```
// fun test(a: Int = <caret>, b: Int) {}
// ```
// `b` should not show up in completion.
return variants.filter {
val candidatePsi = it.findPsi()
if (candidatePsi is KtParameter && candidatePsi.parent == parent) {
return@filter candidatePsi.startOffset < element.startOffset
}
true
}
}
if (element is KtDeclaration) break // we can use variable inside lambda or anonymous object located in its initializer
}
return variants
}
private fun getReferenceVariantsNoVisibilityFilter(
contextElement: PsiElement,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
useReceiverType: KotlinType?
): Collection<DeclarationDescriptor> {
val callType = callTypeAndReceiver.callType
@Suppress("NAME_SHADOWING")
val kindFilter = kindFilter.intersect(callType.descriptorKindFilter)
val receiverExpression: KtExpression?
when (callTypeAndReceiver) {
is CallTypeAndReceiver.IMPORT_DIRECTIVE -> {
return getVariantsForImportOrPackageDirective(callTypeAndReceiver.receiver, kindFilter, nameFilter)
}
is CallTypeAndReceiver.PACKAGE_DIRECTIVE -> {
return getVariantsForImportOrPackageDirective(callTypeAndReceiver.receiver, kindFilter, nameFilter)
}
is CallTypeAndReceiver.TYPE -> {
return getVariantsForUserType(callTypeAndReceiver.receiver, contextElement, kindFilter, nameFilter)
}
is CallTypeAndReceiver.ANNOTATION -> {
return getVariantsForUserType(callTypeAndReceiver.receiver, contextElement, kindFilter, nameFilter)
}
is CallTypeAndReceiver.CALLABLE_REFERENCE -> {
return getVariantsForCallableReference(callTypeAndReceiver, contextElement, useReceiverType, kindFilter, nameFilter)
}
is CallTypeAndReceiver.DEFAULT -> receiverExpression = null
is CallTypeAndReceiver.DOT -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.SUPER_MEMBERS -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.SAFE -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.INFIX -> receiverExpression = callTypeAndReceiver.receiver
is CallTypeAndReceiver.OPERATOR -> return emptyList()
is CallTypeAndReceiver.UNKNOWN -> return emptyList()
else -> throw RuntimeException() //TODO: see KT-9394
}
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
val dataFlowInfo = bindingContext.getDataFlowInfoBefore(contextElement)
val containingDeclaration = resolutionScope.ownerDescriptor
val smartCastManager = resolutionFacade.frontendService<SmartCastManager>()
val languageVersionSettings = resolutionFacade.frontendService<LanguageVersionSettings>()
val implicitReceiverTypes = resolutionScope.getImplicitReceiversWithInstance(
languageVersionSettings.supportsFeature(LanguageFeature.DslMarkersSupport)
).flatMap {
smartCastManager.getSmartCastVariantsWithLessSpecificExcluded(
it.value,
bindingContext,
containingDeclaration,
dataFlowInfo,
languageVersionSettings,
resolutionFacade.frontendService()
)
}.toSet()
val descriptors = LinkedHashSet<DeclarationDescriptor>()
val filterWithoutExtensions = kindFilter exclude DescriptorKindExclude.Extensions
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression]
if (qualifier != null) {
descriptors.addAll(qualifier.staticScope.collectStaticMembers(resolutionFacade, filterWithoutExtensions, nameFilter))
}
val explicitReceiverTypes = if (useReceiverType != null) {
listOf(useReceiverType)
} else {
callTypeAndReceiver.receiverTypes(
bindingContext,
contextElement,
moduleDescriptor,
resolutionFacade,
stableSmartCastsOnly = false
)!!
}
descriptors.processAll(implicitReceiverTypes, explicitReceiverTypes, resolutionScope, callType, kindFilter, nameFilter)
} else {
assert(useReceiverType == null) { "'useReceiverType' parameter is not supported for implicit receiver" }
descriptors.processAll(implicitReceiverTypes, implicitReceiverTypes, resolutionScope, callType, kindFilter, nameFilter)
// add non-instance members
descriptors.addAll(
resolutionScope.collectDescriptorsFiltered(
filterWithoutExtensions,
nameFilter,
changeNamesForAliased = true
)
)
descriptors.addAll(resolutionScope.collectAllFromMeAndParent { scope ->
scope.collectSyntheticStaticMembersAndConstructors(resolutionFacade, kindFilter, nameFilter)
})
}
if (callType == CallType.SUPER_MEMBERS) { // we need to unwrap fake overrides in case of "super." because ShadowedDeclarationsFilter does not work correctly
return descriptors.flatMapTo(LinkedHashSet<DeclarationDescriptor>()) {
if (it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE)
it.overriddenDescriptors
else
listOf(it)
}
}
return descriptors
}
private fun getVariantsForUserType(
receiverExpression: KtExpression?,
contextElement: PsiElement,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression] ?: return emptyList()
return qualifier.staticScope.collectStaticMembers(resolutionFacade, kindFilter, nameFilter)
} else {
val scope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
return scope.collectDescriptorsFiltered(kindFilter, nameFilter, changeNamesForAliased = true)
}
}
private fun getVariantsForCallableReference(
callTypeAndReceiver: CallTypeAndReceiver.CALLABLE_REFERENCE,
contextElement: PsiElement,
useReceiverType: KotlinType?,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
val descriptors = LinkedHashSet<DeclarationDescriptor>()
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
val receiver = callTypeAndReceiver.receiver
if (receiver != null) {
val isStatic = bindingContext[BindingContext.DOUBLE_COLON_LHS, receiver] is DoubleColonLHS.Type
val explicitReceiverTypes = if (useReceiverType != null) {
listOf(useReceiverType)
} else {
callTypeAndReceiver.receiverTypes(
bindingContext,
contextElement,
moduleDescriptor,
resolutionFacade,
stableSmartCastsOnly = false
)!!
}
val constructorFilter = { descriptor: ClassDescriptor -> if (isStatic) true else descriptor.isInner }
descriptors.addNonExtensionMembers(explicitReceiverTypes, kindFilter, nameFilter, constructorFilter)
descriptors.addScopeAndSyntheticExtensions(
resolutionScope,
explicitReceiverTypes,
CallType.CALLABLE_REFERENCE,
kindFilter,
nameFilter
)
if (isStatic) {
explicitReceiverTypes
.mapNotNull { (it.constructor.declarationDescriptor as? ClassDescriptor)?.staticScope }
.flatMapTo(descriptors) { it.collectStaticMembers(resolutionFacade, kindFilter, nameFilter) }
}
} else {
// process non-instance members and class constructors
descriptors.addNonExtensionCallablesAndConstructors(
resolutionScope,
kindFilter, nameFilter, constructorFilter = { !it.isInner },
classesOnly = false
)
}
return descriptors
}
private fun getVariantsForImportOrPackageDirective(
receiverExpression: KtExpression?,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
if (receiverExpression != null) {
val qualifier = bindingContext[BindingContext.QUALIFIER, receiverExpression] ?: return emptyList()
val staticDescriptors = qualifier.staticScope.collectStaticMembers(resolutionFacade, kindFilter, nameFilter)
val objectDescriptor =
(qualifier as? ClassQualifier)?.descriptor?.takeIf { it.kind == ClassKind.OBJECT } ?: return staticDescriptors
return staticDescriptors + objectDescriptor.defaultType.memberScope.getDescriptorsFiltered(kindFilter, nameFilter)
} else {
val rootPackage = resolutionFacade.moduleDescriptor.getPackage(FqName.ROOT)
return rootPackage.memberScope.getDescriptorsFiltered(kindFilter, nameFilter)
}
}
private fun MutableSet<DeclarationDescriptor>.processAll(
implicitReceiverTypes: Collection<KotlinType>,
receiverTypes: Collection<KotlinType>,
resolutionScope: LexicalScope,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
addNonExtensionMembers(receiverTypes, kindFilter, nameFilter, constructorFilter = { it.isInner })
addMemberExtensions(implicitReceiverTypes, receiverTypes, callType, kindFilter, nameFilter)
addScopeAndSyntheticExtensions(resolutionScope, receiverTypes, callType, kindFilter, nameFilter)
}
private fun MutableSet<DeclarationDescriptor>.addMemberExtensions(
dispatchReceiverTypes: Collection<KotlinType>,
extensionReceiverTypes: Collection<KotlinType>,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
val memberFilter = kindFilter exclude DescriptorKindExclude.NonExtensions
for (dispatchReceiverType in dispatchReceiverTypes) {
for (member in dispatchReceiverType.memberScope.getDescriptorsFiltered(memberFilter, nameFilter)) {
addAll((member as CallableDescriptor).substituteExtensionIfCallable(extensionReceiverTypes, callType))
}
}
}
private fun MutableSet<DeclarationDescriptor>.addNonExtensionMembers(
receiverTypes: Collection<KotlinType>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
constructorFilter: (ClassDescriptor) -> Boolean
) {
for (receiverType in receiverTypes) {
addNonExtensionCallablesAndConstructors(
receiverType.memberScope.memberScopeAsImportingScope(),
kindFilter, nameFilter, constructorFilter,
false
)
receiverType.constructor.supertypes.forEach {
addNonExtensionCallablesAndConstructors(
it.memberScope.memberScopeAsImportingScope(),
kindFilter, nameFilter, constructorFilter,
true
)
}
}
}
private fun MutableSet<DeclarationDescriptor>.addNonExtensionCallablesAndConstructors(
scope: HierarchicalScope,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean,
constructorFilter: (ClassDescriptor) -> Boolean,
classesOnly: Boolean
) {
var filterToUse =
DescriptorKindFilter(kindFilter.kindMask and DescriptorKindFilter.CALLABLES.kindMask).exclude(DescriptorKindExclude.Extensions)
// should process classes if we need constructors
if (filterToUse.acceptsKinds(DescriptorKindFilter.FUNCTIONS_MASK)) {
filterToUse = filterToUse.withKinds(DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS_MASK)
}
for (descriptor in scope.collectDescriptorsFiltered(filterToUse, nameFilter, changeNamesForAliased = true)) {
if (descriptor is ClassDescriptor) {
if (descriptor.modality == Modality.ABSTRACT || descriptor.modality == Modality.SEALED) continue
if (!constructorFilter(descriptor)) continue
descriptor.constructors.filterTo(this) { kindFilter.accepts(it) }
} else if (!classesOnly && kindFilter.accepts(descriptor)) {
this.add(descriptor)
}
}
}
private fun MutableSet<DeclarationDescriptor>.addScopeAndSyntheticExtensions(
scope: LexicalScope,
receiverTypes: Collection<KotlinType>,
callType: CallType<*>,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
) {
if (kindFilter.excludes.contains(DescriptorKindExclude.Extensions)) return
if (receiverTypes.isEmpty()) return
fun process(extensionOrSyntheticMember: CallableDescriptor) {
if (kindFilter.accepts(extensionOrSyntheticMember) && nameFilter(extensionOrSyntheticMember.name)) {
if (extensionOrSyntheticMember.isExtension) {
addAll(extensionOrSyntheticMember.substituteExtensionIfCallable(receiverTypes, callType))
} else {
add(extensionOrSyntheticMember)
}
}
}
for (descriptor in scope.collectDescriptorsFiltered(
kindFilter exclude DescriptorKindExclude.NonExtensions,
nameFilter,
changeNamesForAliased = true
)) {
// todo: sometimes resolution scope here is LazyJavaClassMemberScope. see ea.jetbrains.com/browser/ea_problems/72572
process(descriptor as CallableDescriptor)
}
val syntheticScopes = resolutionFacade.getFrontendService(SyntheticScopes::class.java).forceEnableSamAdapters()
if (kindFilter.acceptsKinds(DescriptorKindFilter.VARIABLES_MASK)) {
val lookupLocation = (scope.ownerDescriptor.toSourceElement.getPsi() as? KtElement)?.let { KotlinLookupLocation(it) }
?: NoLookupLocation.FROM_IDE
for (extension in syntheticScopes.collectSyntheticExtensionProperties(receiverTypes, lookupLocation)) {
process(extension)
}
}
if (kindFilter.acceptsKinds(DescriptorKindFilter.FUNCTIONS_MASK)) {
for (syntheticMember in syntheticScopes.collectSyntheticMemberFunctions(receiverTypes)) {
process(syntheticMember)
}
}
}
}
private fun MemberScope.collectStaticMembers(
resolutionFacade: ResolutionFacade,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): Collection<DeclarationDescriptor> {
return getDescriptorsFiltered(kindFilter, nameFilter) + collectSyntheticStaticMembersAndConstructors(
resolutionFacade,
kindFilter,
nameFilter
)
}
@OptIn(FrontendInternals::class)
fun ResolutionScope.collectSyntheticStaticMembersAndConstructors(
resolutionFacade: ResolutionFacade,
kindFilter: DescriptorKindFilter,
nameFilter: (Name) -> Boolean
): List<FunctionDescriptor> {
val syntheticScopes = resolutionFacade.getFrontendService(SyntheticScopes::class.java)
val functionDescriptors = getContributedDescriptors(DescriptorKindFilter.FUNCTIONS)
val classifierDescriptors = getContributedDescriptors(DescriptorKindFilter.CLASSIFIERS)
return (syntheticScopes.forceEnableSamAdapters().collectSyntheticStaticFunctions(functionDescriptors) +
syntheticScopes.collectSyntheticConstructors(classifierDescriptors))
.filter { kindFilter.accepts(it) && nameFilter(it.name) }
}
// New Inference disables scope with synthetic SAM-adapters because it uses conversions for resolution
// However, sometimes we need to pretend that we have those synthetic members, for example:
// - to show both option (with SAM-conversion signature, and without) in completion
// - for various intentions and checks (see RedundantSamConstructorInspection, ConflictingExtensionPropertyIntention and other)
// TODO(dsavvinov): review clients, rewrite them to not rely on synthetic adapetrs
fun SyntheticScopes.forceEnableSamAdapters(): SyntheticScopes {
return if (this !is JavaSyntheticScopes)
this
else
object : SyntheticScopes {
override val scopes: Collection<SyntheticScope> = [email protected]
}
}
| apache-2.0 | 04bbe01b2ce626db9ac4bce45d013316 | 45.8083 | 164 | 0.690099 | 6.290837 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/ComposeInputFieldMinMaxLines.kt | 3 | 5382 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.demos.text
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.OffsetMapping
import androidx.compose.ui.text.input.TransformedText
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
@Preview
@Composable
fun BasicTextFieldMinMaxDemo() {
LazyColumn {
item {
TagLine("empty text, no maxLines")
TextFieldWithMinMaxLines("", maxLines = Int.MAX_VALUE)
}
item {
TagLine("maxLines == line count")
TextFieldWithMinMaxLines("abc", maxLines = 1)
}
item {
TagLine("empty text, maxLines > line count")
TextFieldWithMinMaxLines("", maxLines = 2)
}
item {
TagLine("maxLines > line count")
TextFieldWithMinMaxLines("abc", maxLines = 3)
}
item {
TagLine("maxLines < line count")
TextFieldWithMinMaxLines("abc".repeat(20), maxLines = 1)
}
item {
TagLine("empty text, no minLines")
TextFieldWithMinMaxLines("", minLines = 1)
}
item {
TagLine("minLines == line count")
TextFieldWithMinMaxLines(createMultilineText(2), minLines = 2)
}
item {
TagLine("empty text, minLines > line count")
TextFieldWithMinMaxLines("", minLines = 2)
}
item {
TagLine("minLines > line count")
TextFieldWithMinMaxLines(
createMultilineText(4),
minLines = 5
)
}
item {
TagLine("minLines < line count")
TextFieldWithMinMaxLines(createMultilineText(3), minLines = 2)
}
item {
TagLine("minLines < maxLines")
TextFieldWithMinMaxLines(
createMultilineText(4),
minLines = 2,
maxLines = 3
)
}
item {
TagLine("minLines == maxLines")
TextFieldWithMinMaxLines(
createMultilineText(2),
minLines = 3,
maxLines = 3
)
}
item {
TagLine("maxLines=4 with different line heights")
TextFieldWithMinMaxLines(
createMultilineText(5),
maxLines = 4,
spanStyles = listOf(
AnnotatedString.Range(SpanStyle(fontSize = 40.sp), 14, 21)
)
)
}
item {
TagLine("minLines=5 with different line heights")
TextFieldWithMinMaxLines(
createMultilineText(4),
minLines = 5,
spanStyles = listOf(
AnnotatedString.Range(SpanStyle(fontSize = 40.sp), 14, 21)
)
)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TextFieldWithMinMaxLines(
str: String? = null,
minLines: Int = 1,
maxLines: Int = Int.MAX_VALUE,
spanStyles: List<AnnotatedString.Range<SpanStyle>>? = null
) {
val state = rememberSaveable { mutableStateOf(str ?: "abc ".repeat(20)) }
val visualTransformation: VisualTransformation =
if (spanStyles == null) {
VisualTransformation.None
} else {
VisualTransformation { annotatedString ->
TransformedText(
AnnotatedString(
annotatedString.text,
spanStyles = spanStyles
),
OffsetMapping.Identity
)
}
}
BasicTextField(
modifier = demoTextFieldModifiers.clipToBounds(),
value = state.value,
onValueChange = { state.value = it },
textStyle = TextStyle(fontSize = fontSize8),
cursorBrush = SolidColor(Color.Red),
minLines = minLines,
maxLines = maxLines,
visualTransformation = visualTransformation
)
}
private fun createMultilineText(lineCount: Int) =
(1..lineCount).joinToString("\n") { "Line $it" } | apache-2.0 | cf03d5dd9ea1481ab6b8b7175c82bf8d | 32.434783 | 78 | 0.60052 | 5.001859 | false | false | false | false |
androidx/androidx | navigation/navigation-common/src/main/java/androidx/navigation/NavArgsLazy.kt | 3 | 2186 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.collection.ArrayMap
import java.lang.reflect.Method
import kotlin.reflect.KClass
internal val methodSignature = arrayOf(Bundle::class.java)
internal val methodMap = ArrayMap<KClass<out NavArgs>, Method>()
/**
* An implementation of [Lazy] used by [android.app.Activity.navArgs] and
* [androidx.fragment.app.Fragment.navArgs].
*
* [argumentProducer] is a lambda that will be called during initialization to provide
* arguments to construct an [Args] instance via reflection.
*/
public class NavArgsLazy<Args : NavArgs>(
private val navArgsClass: KClass<Args>,
private val argumentProducer: () -> Bundle
) : Lazy<Args> {
private var cached: Args? = null
override val value: Args
get() {
var args = cached
if (args == null) {
val arguments = argumentProducer()
val method: Method = methodMap[navArgsClass]
?: navArgsClass.java.getMethod("fromBundle", *methodSignature).also { method ->
// Save a reference to the method
methodMap[navArgsClass] = method
}
@SuppressLint("BanUncheckedReflection") // needed for method.invoke
@Suppress("UNCHECKED_CAST")
args = method.invoke(null, arguments) as Args
cached = args
}
return args
}
override fun isInitialized(): Boolean = cached != null
}
| apache-2.0 | b3d2753051e7319b5432a9e9f293a050 | 34.836066 | 99 | 0.662855 | 4.641189 | false | false | false | false |
androidx/androidx | navigation/navigation-dynamic-features-runtime/src/main/java/androidx/navigation/dynamicfeatures/NavController.kt | 3 | 1684 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.dynamicfeatures
import androidx.annotation.IdRes
import androidx.navigation.NavController
import androidx.navigation.NavGraph
/**
* Construct a new [androidx.navigation.NavGraph] that supports dynamic navigation destinations
*/
@Suppress("Deprecation")
@Deprecated(
"Use routes to create your dynamic NavGraph instead",
ReplaceWith(
"createGraph(startDestination = startDestination.toString(), route = id.toString()) " +
"{ builder.invoke() }"
)
)
public inline fun NavController.createGraph(
@IdRes id: Int = 0,
@IdRes startDestination: Int,
builder: DynamicNavGraphBuilder.() -> Unit
): NavGraph = navigatorProvider.navigation(id, startDestination, builder)
/**
* Construct a new [androidx.navigation.NavGraph] that supports dynamic navigation destinations
*/
public inline fun NavController.createGraph(
startDestination: String,
route: String? = null,
builder: DynamicNavGraphBuilder.() -> Unit
): NavGraph = navigatorProvider.navigation(startDestination, route, builder)
| apache-2.0 | f6838163c35b634a56f6ac31ce01de3f | 34.829787 | 95 | 0.745249 | 4.677778 | false | false | false | false |
androidx/androidx | text/text/src/main/java/androidx/compose/ui/text/android/TextAndroidCanvas.kt | 3 | 20220 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.android
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BlendMode
import android.graphics.Canvas
import android.graphics.DrawFilter
import android.graphics.Matrix
import android.graphics.NinePatch
import android.graphics.Paint
import android.graphics.Path
import android.graphics.Picture
import android.graphics.PorterDuff
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Region
import android.graphics.RenderNode
import android.graphics.fonts.Font
import android.graphics.text.MeasuredText
import android.os.Build
import androidx.annotation.RequiresApi
/**
* This is a wrapper around Android Canvas that we get from
* androidx.compose.ui.graphics.Canvas#nativeCanvas. This implementation delegates all methods to
* the original nativeCanvas apart from `getClipBounds(Rect)`
*/
@SuppressLint("ClassVerificationFailure")
@Suppress("DEPRECATION")
internal class TextAndroidCanvas : Canvas() {
/**
* Original canvas object to which this class delegates its method calls
*/
private lateinit var nativeCanvas: Canvas
fun setCanvas(canvas: Canvas) {
nativeCanvas = canvas
}
/**
* By overriding this methods we allow android.text.Layout to draw all lines that would
* otherwise be cut due to Layout's internal drawing logic.
*/
override fun getClipBounds(bounds: Rect): Boolean {
val result = nativeCanvas.getClipBounds(bounds)
if (result) {
val currentWidth = bounds.width()
bounds.set(0, 0, currentWidth, Int.MAX_VALUE)
}
return result
}
override fun setBitmap(bitmap: Bitmap?) {
nativeCanvas.setBitmap(bitmap)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun enableZ() {
nativeCanvas.enableZ()
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun disableZ() {
nativeCanvas.disableZ()
}
override fun isOpaque(): Boolean {
return nativeCanvas.isOpaque
}
override fun getWidth(): Int {
return nativeCanvas.width
}
override fun getHeight(): Int {
return nativeCanvas.getHeight()
}
override fun getDensity(): Int {
return nativeCanvas.density
}
override fun setDensity(density: Int) {
nativeCanvas.density = density
}
override fun getMaximumBitmapWidth(): Int {
return nativeCanvas.maximumBitmapWidth
}
override fun getMaximumBitmapHeight(): Int {
return nativeCanvas.maximumBitmapHeight
}
override fun save(): Int {
return nativeCanvas.save()
}
@Deprecated("Deprecated in Java")
override fun saveLayer(bounds: RectF?, paint: Paint?, saveFlags: Int): Int {
return nativeCanvas.saveLayer(bounds, paint, saveFlags)
}
override fun saveLayer(bounds: RectF?, paint: Paint?): Int {
return nativeCanvas.saveLayer(bounds, paint)
}
@Deprecated("Deprecated in Java")
override fun saveLayer(
left: Float,
top: Float,
right: Float,
bottom: Float,
paint: Paint?,
saveFlags: Int
): Int {
return nativeCanvas.saveLayer(left, top, right, bottom, paint, saveFlags)
}
override fun saveLayer(
left: Float,
top: Float,
right: Float,
bottom: Float,
paint: Paint?
): Int {
return nativeCanvas.saveLayer(left, top, right, bottom, paint)
}
@Deprecated("Deprecated in Java")
override fun saveLayerAlpha(bounds: RectF?, alpha: Int, saveFlags: Int): Int {
return nativeCanvas.saveLayerAlpha(bounds, alpha, saveFlags)
}
override fun saveLayerAlpha(bounds: RectF?, alpha: Int): Int {
return nativeCanvas.saveLayerAlpha(bounds, alpha)
}
@Deprecated("Deprecated in Java")
override fun saveLayerAlpha(
left: Float,
top: Float,
right: Float,
bottom: Float,
alpha: Int,
saveFlags: Int
): Int {
return nativeCanvas.saveLayerAlpha(left, top, right, bottom, alpha, saveFlags)
}
override fun saveLayerAlpha(
left: Float,
top: Float,
right: Float,
bottom: Float,
alpha: Int
): Int {
return nativeCanvas.saveLayerAlpha(left, top, right, bottom, alpha)
}
override fun restore() {
nativeCanvas.restore()
}
override fun getSaveCount(): Int {
return nativeCanvas.saveCount
}
override fun restoreToCount(saveCount: Int) {
nativeCanvas.restoreToCount(saveCount)
}
override fun translate(dx: Float, dy: Float) {
nativeCanvas.translate(dx, dy)
}
override fun scale(sx: Float, sy: Float) {
nativeCanvas.scale(sx, sy)
}
override fun rotate(degrees: Float) {
nativeCanvas.rotate(degrees)
}
override fun skew(sx: Float, sy: Float) {
nativeCanvas.skew(sx, sy)
}
override fun concat(matrix: Matrix?) {
nativeCanvas.concat(matrix)
}
override fun setMatrix(matrix: Matrix?) {
nativeCanvas.setMatrix(matrix)
}
@Deprecated("Deprecated in Java")
override fun getMatrix(ctm: Matrix) {
nativeCanvas.getMatrix(ctm)
}
@Deprecated("Deprecated in Java")
override fun clipRect(rect: RectF, op: Region.Op): Boolean {
return nativeCanvas.clipRect(rect, op)
}
@Deprecated("Deprecated in Java")
override fun clipRect(rect: Rect, op: Region.Op): Boolean {
return nativeCanvas.clipRect(rect, op)
}
override fun clipRect(rect: RectF): Boolean {
return nativeCanvas.clipRect(rect)
}
override fun clipRect(rect: Rect): Boolean {
return nativeCanvas.clipRect(rect)
}
@Deprecated("Deprecated in Java")
override fun clipRect(
left: Float,
top: Float,
right: Float,
bottom: Float,
op: Region.Op
): Boolean {
return nativeCanvas.clipRect(left, top, right, bottom, op)
}
override fun clipRect(left: Float, top: Float, right: Float, bottom: Float): Boolean {
return nativeCanvas.clipRect(left, top, right, bottom)
}
override fun clipRect(left: Int, top: Int, right: Int, bottom: Int): Boolean {
return nativeCanvas.clipRect(left, top, right, bottom)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun clipOutRect(rect: RectF): Boolean {
return nativeCanvas.clipOutRect(rect)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun clipOutRect(rect: Rect): Boolean {
return nativeCanvas.clipOutRect(rect)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun clipOutRect(left: Float, top: Float, right: Float, bottom: Float): Boolean {
return nativeCanvas.clipOutRect(left, top, right, bottom)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun clipOutRect(left: Int, top: Int, right: Int, bottom: Int): Boolean {
return nativeCanvas.clipOutRect(left, top, right, bottom)
}
@Deprecated("Deprecated in Java")
override fun clipPath(path: Path, op: Region.Op): Boolean {
return nativeCanvas.clipPath(path, op)
}
override fun clipPath(path: Path): Boolean {
return nativeCanvas.clipPath(path)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun clipOutPath(path: Path): Boolean {
return nativeCanvas.clipOutPath(path)
}
override fun getDrawFilter() = nativeCanvas.drawFilter
override fun setDrawFilter(filter: DrawFilter?) {
nativeCanvas.drawFilter = filter
}
@Deprecated("Deprecated in Java")
override fun quickReject(rect: RectF, type: EdgeType): Boolean {
return nativeCanvas.quickReject(rect, type)
}
@RequiresApi(Build.VERSION_CODES.R)
override fun quickReject(rect: RectF): Boolean {
return nativeCanvas.quickReject(rect)
}
@Deprecated("Deprecated in Java")
override fun quickReject(path: Path, type: EdgeType): Boolean {
return nativeCanvas.quickReject(path, type)
}
@RequiresApi(Build.VERSION_CODES.R)
override fun quickReject(path: Path): Boolean {
return nativeCanvas.quickReject(path)
}
@Deprecated("Deprecated in Java")
override fun quickReject(
left: Float,
top: Float,
right: Float,
bottom: Float,
type: EdgeType
): Boolean {
return nativeCanvas.quickReject(left, top, right, bottom, type)
}
@RequiresApi(Build.VERSION_CODES.R)
override fun quickReject(left: Float, top: Float, right: Float, bottom: Float): Boolean {
return nativeCanvas.quickReject(left, top, right, bottom)
}
override fun drawPicture(picture: Picture) {
nativeCanvas.drawPicture(picture)
}
override fun drawPicture(picture: Picture, dst: RectF) {
nativeCanvas.drawPicture(picture, dst)
}
override fun drawPicture(picture: Picture, dst: Rect) {
nativeCanvas.drawPicture(picture, dst)
}
override fun drawArc(
oval: RectF,
startAngle: Float,
sweepAngle: Float,
useCenter: Boolean,
paint: Paint
) {
nativeCanvas.drawArc(oval, startAngle, sweepAngle, useCenter, paint)
}
override fun drawArc(
left: Float,
top: Float,
right: Float,
bottom: Float,
startAngle: Float,
sweepAngle: Float,
useCenter: Boolean,
paint: Paint
) {
nativeCanvas.drawArc(left, top, right, bottom, startAngle, sweepAngle, useCenter, paint)
}
override fun drawARGB(a: Int, r: Int, g: Int, b: Int) {
nativeCanvas.drawARGB(a, r, g, b)
}
override fun drawBitmap(bitmap: Bitmap, left: Float, top: Float, paint: Paint?) {
nativeCanvas.drawBitmap(bitmap, left, top, paint)
}
override fun drawBitmap(bitmap: Bitmap, src: Rect?, dst: RectF, paint: Paint?) {
nativeCanvas.drawBitmap(bitmap, src, dst, paint)
}
override fun drawBitmap(bitmap: Bitmap, src: Rect?, dst: Rect, paint: Paint?) {
nativeCanvas.drawBitmap(bitmap, src, dst, paint)
}
@Deprecated("Deprecated in Java")
override fun drawBitmap(
colors: IntArray,
offset: Int,
stride: Int,
x: Float,
y: Float,
width: Int,
height: Int,
hasAlpha: Boolean,
paint: Paint?
) {
nativeCanvas.drawBitmap(colors, offset, stride, x, y, width, height, hasAlpha, paint)
}
@Deprecated("Deprecated in Java")
override fun drawBitmap(
colors: IntArray,
offset: Int,
stride: Int,
x: Int,
y: Int,
width: Int,
height: Int,
hasAlpha: Boolean,
paint: Paint?
) {
nativeCanvas.drawBitmap(colors, offset, stride, x, y, width, height, hasAlpha, paint)
}
override fun drawBitmap(bitmap: Bitmap, matrix: Matrix, paint: Paint?) {
nativeCanvas.drawBitmap(bitmap, matrix, paint)
}
override fun drawBitmapMesh(
bitmap: Bitmap,
meshWidth: Int,
meshHeight: Int,
verts: FloatArray,
vertOffset: Int,
colors: IntArray?,
colorOffset: Int,
paint: Paint?
) {
nativeCanvas.drawBitmapMesh(
bitmap,
meshWidth,
meshHeight,
verts,
vertOffset,
colors,
colorOffset,
paint
)
}
override fun drawCircle(cx: Float, cy: Float, radius: Float, paint: Paint) {
nativeCanvas.drawCircle(cx, cy, radius, paint)
}
override fun drawColor(color: Int) {
nativeCanvas.drawColor(color)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun drawColor(color: Long) {
nativeCanvas.drawColor(color)
}
override fun drawColor(color: Int, mode: PorterDuff.Mode) {
nativeCanvas.drawColor(color, mode)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun drawColor(color: Int, mode: BlendMode) {
nativeCanvas.drawColor(color, mode)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun drawColor(color: Long, mode: BlendMode) {
nativeCanvas.drawColor(color, mode)
}
override fun drawLine(startX: Float, startY: Float, stopX: Float, stopY: Float, paint: Paint) {
nativeCanvas.drawLine(startX, startY, stopX, stopY, paint)
}
override fun drawLines(pts: FloatArray, offset: Int, count: Int, paint: Paint) {
nativeCanvas.drawLines(pts, offset, count, paint)
}
override fun drawLines(pts: FloatArray, paint: Paint) {
nativeCanvas.drawLines(pts, paint)
}
override fun drawOval(oval: RectF, paint: Paint) {
nativeCanvas.drawOval(oval, paint)
}
override fun drawOval(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) {
nativeCanvas.drawOval(left, top, right, bottom, paint)
}
override fun drawPaint(paint: Paint) {
nativeCanvas.drawPaint(paint)
}
@RequiresApi(Build.VERSION_CODES.S)
override fun drawPatch(patch: NinePatch, dst: Rect, paint: Paint?) {
nativeCanvas.drawPatch(patch, dst, paint)
}
@RequiresApi(Build.VERSION_CODES.S)
override fun drawPatch(patch: NinePatch, dst: RectF, paint: Paint?) {
nativeCanvas.drawPatch(patch, dst, paint)
}
override fun drawPath(path: Path, paint: Paint) {
nativeCanvas.drawPath(path, paint)
}
override fun drawPoint(x: Float, y: Float, paint: Paint) {
nativeCanvas.drawPoint(x, y, paint)
}
override fun drawPoints(pts: FloatArray?, offset: Int, count: Int, paint: Paint) {
nativeCanvas.drawPoints(pts, offset, count, paint)
}
override fun drawPoints(pts: FloatArray, paint: Paint) {
nativeCanvas.drawPoints(pts, paint)
}
@Deprecated("Deprecated in Java")
override fun drawPosText(
text: CharArray,
index: Int,
count: Int,
pos: FloatArray,
paint: Paint
) {
nativeCanvas.drawPosText(text, index, count, pos, paint)
}
@Deprecated("Deprecated in Java")
override fun drawPosText(text: String, pos: FloatArray, paint: Paint) {
nativeCanvas.drawPosText(text, pos, paint)
}
override fun drawRect(rect: RectF, paint: Paint) {
nativeCanvas.drawRect(rect, paint)
}
override fun drawRect(r: Rect, paint: Paint) {
nativeCanvas.drawRect(r, paint)
}
override fun drawRect(left: Float, top: Float, right: Float, bottom: Float, paint: Paint) {
nativeCanvas.drawRect(left, top, right, bottom, paint)
}
override fun drawRGB(r: Int, g: Int, b: Int) {
nativeCanvas.drawRGB(r, g, b)
}
override fun drawRoundRect(rect: RectF, rx: Float, ry: Float, paint: Paint) {
nativeCanvas.drawRoundRect(rect, rx, ry, paint)
}
override fun drawRoundRect(
left: Float,
top: Float,
right: Float,
bottom: Float,
rx: Float,
ry: Float,
paint: Paint
) {
nativeCanvas.drawRoundRect(left, top, right, bottom, rx, ry, paint)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun drawDoubleRoundRect(
outer: RectF,
outerRx: Float,
outerRy: Float,
inner: RectF,
innerRx: Float,
innerRy: Float,
paint: Paint
) {
nativeCanvas.drawDoubleRoundRect(outer, outerRx, outerRy, inner, innerRx, innerRy, paint)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun drawDoubleRoundRect(
outer: RectF,
outerRadii: FloatArray,
inner: RectF,
innerRadii: FloatArray,
paint: Paint
) {
nativeCanvas.drawDoubleRoundRect(outer, outerRadii, inner, innerRadii, paint)
}
@RequiresApi(Build.VERSION_CODES.S)
override fun drawGlyphs(
glyphIds: IntArray,
glyphIdOffset: Int,
positions: FloatArray,
positionOffset: Int,
glyphCount: Int,
font: Font,
paint: Paint
) {
nativeCanvas.drawGlyphs(
glyphIds,
glyphIdOffset,
positions,
positionOffset,
glyphCount,
font,
paint
)
}
override fun drawText(
text: CharArray,
index: Int,
count: Int,
x: Float,
y: Float,
paint: Paint
) {
nativeCanvas.drawText(text, index, count, x, y, paint)
}
override fun drawText(text: String, x: Float, y: Float, paint: Paint) {
nativeCanvas.drawText(text, x, y, paint)
}
override fun drawText(text: String, start: Int, end: Int, x: Float, y: Float, paint: Paint) {
nativeCanvas.drawText(text, start, end, x, y, paint)
}
override fun drawText(
text: CharSequence,
start: Int,
end: Int,
x: Float,
y: Float,
paint: Paint
) {
nativeCanvas.drawText(text, start, end, x, y, paint)
}
override fun drawTextOnPath(
text: CharArray,
index: Int,
count: Int,
path: Path,
hOffset: Float,
vOffset: Float,
paint: Paint
) {
nativeCanvas.drawTextOnPath(text, index, count, path, hOffset, vOffset, paint)
}
override fun drawTextOnPath(
text: String,
path: Path,
hOffset: Float,
vOffset: Float,
paint: Paint
) {
nativeCanvas.drawTextOnPath(text, path, hOffset, vOffset, paint)
}
@RequiresApi(Build.VERSION_CODES.M)
override fun drawTextRun(
text: CharArray,
index: Int,
count: Int,
contextIndex: Int,
contextCount: Int,
x: Float,
y: Float,
isRtl: Boolean,
paint: Paint
) {
nativeCanvas.drawTextRun(text, index, count, contextIndex, contextCount, x, y, isRtl, paint)
}
@RequiresApi(Build.VERSION_CODES.M)
override fun drawTextRun(
text: CharSequence,
start: Int,
end: Int,
contextStart: Int,
contextEnd: Int,
x: Float,
y: Float,
isRtl: Boolean,
paint: Paint
) {
nativeCanvas.drawTextRun(text, start, end, contextStart, contextEnd, x, y, isRtl, paint)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun drawTextRun(
text: MeasuredText,
start: Int,
end: Int,
contextStart: Int,
contextEnd: Int,
x: Float,
y: Float,
isRtl: Boolean,
paint: Paint
) {
nativeCanvas.drawTextRun(text, start, end, contextStart, contextEnd, x, y, isRtl, paint)
}
override fun drawVertices(
mode: VertexMode,
vertexCount: Int,
verts: FloatArray,
vertOffset: Int,
texs: FloatArray?,
texOffset: Int,
colors: IntArray?,
colorOffset: Int,
indices: ShortArray?,
indexOffset: Int,
indexCount: Int,
paint: Paint
) {
nativeCanvas.drawVertices(
mode,
vertexCount,
verts,
vertOffset,
texs,
texOffset,
colors,
colorOffset,
indices,
indexOffset,
indexCount,
paint
)
}
@RequiresApi(Build.VERSION_CODES.Q)
override fun drawRenderNode(renderNode: RenderNode) {
nativeCanvas.drawRenderNode(renderNode)
}
} | apache-2.0 | 44384c621b4706f8b48039a3e4018a78 | 26.399729 | 100 | 0.621167 | 4.148543 | false | false | false | false |
lnr0626/cfn-templates | plugin/src/main/kotlin/com/lloydramey/cfn/gradle/tasks/CfnTemplateToJson.kt | 1 | 2500 | /*
* Copyright 2017 Lloyd Ramey <[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 com.lloydramey.cfn.gradle.tasks
import com.lloydramey.cfn.gradle.internal.OpenForGradle
import com.lloydramey.cfn.gradle.internal.convertToJson
import com.lloydramey.cfn.scripting.CfnTemplateScript
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.compile.AbstractCompile
import java.io.File
import java.net.URI
import java.net.URLClassLoader
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.concurrent.thread
import kotlin.streams.toList
@OpenForGradle
class CfnTemplateToJson : AbstractCompile() {
private fun list(path: Path) =
Files.list(path).map { it.toAbsolutePath() }.toList()
@TaskAction
override fun compile() {
val files = (classpath.files)
.map(File::toURI)
.map(URI::toURL)
val templateClassNames = files
.map { Paths.get(it.toURI()).toAbsolutePath() }
.filter { Files.isDirectory(it) }
.flatMap { classpathFolder ->
list(classpathFolder)
.map { it.toString() }
.filter { it.endsWith("_template.class") }
.map { it.removePrefix("$classpathFolder/").removeSuffix(".class") }
}
val classloader = URLClassLoader(files.toTypedArray(), CfnTemplateToJson::class.java.classLoader)
@Suppress("UNCHECKED_CAST")
val t = thread(start = true, isDaemon = false, name = "Cloudify Template to JSON", contextClassLoader = classloader) {
val templates = templateClassNames
.map { Class.forName(it, true, classloader) }
.filter { CfnTemplateScript::class.java.isAssignableFrom(it) }
.map { it as Class<CfnTemplateScript> }
templates
.forEach { convertToJson(it, destinationDir) }
}
t.join()
}
}
| apache-2.0 | 0efc67a601204f4e4e2658f226958f67 | 34.714286 | 126 | 0.6668 | 4.295533 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/sdk/PyTargetsIntrospectionFacade.kt | 2 | 3730 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.execution.ExecutionException
import com.intellij.execution.processTools.getResultStdoutStr
import com.intellij.execution.processTools.mapFlat
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.TargetProgressIndicatorAdapter
import com.intellij.execution.target.TargetedCommandLineBuilder
import com.intellij.execution.target.createProcessWithResult
import com.intellij.execution.target.local.LocalTargetEnvironmentRequest
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.Disposer
import com.jetbrains.python.PythonHelper
import com.jetbrains.python.run.*
import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.future.await
import kotlinx.coroutines.withContext
import javax.swing.SwingUtilities
class PyTargetsIntrospectionFacade(val sdk: Sdk, val project: Project) {
private val pyRequest: HelpersAwareTargetEnvironmentRequest =
checkNotNull(PythonInterpreterTargetEnvironmentFactory.findPythonTargetInterpreter(sdk, project))
private val targetEnvRequest: TargetEnvironmentRequest
get() = pyRequest.targetEnvironmentRequest
init {
check(sdk !is Disposable || !Disposer.isDisposed(sdk))
}
fun isLocalTarget(): Boolean = targetEnvRequest is LocalTargetEnvironmentRequest
/**
* Runs python [command] and returns stdout or error
*/
suspend fun getCommandOutput(indicator: ProgressIndicator, command: String): Result<String> {
assert(!SwingUtilities.isEventDispatchThread()) { "Can't run on EDT" }
val cmdBuilder = TargetedCommandLineBuilder(targetEnvRequest)
sdk.configureBuilderToRunPythonOnTarget(cmdBuilder)
cmdBuilder.addParameter("-c")
cmdBuilder.addParameter(command)
val cmd = cmdBuilder.build()
val environment = targetEnvRequest.prepareEnvironment(TargetProgressIndicatorAdapter(indicator))
return withContext(Dispatchers.IO) {
environment.createProcessWithResult(cmd).mapFlat { it.getResultStdoutStr() }
}
}
@Throws(ExecutionException::class)
fun getInterpreterVersion(indicator: ProgressIndicator): String? {
// PythonExecution doesn't support launching a bare interpreter without a script or module
val cmdBuilder = TargetedCommandLineBuilder(targetEnvRequest)
sdk.configureBuilderToRunPythonOnTarget(cmdBuilder)
val sdkFlavor = sdk.sdkFlavor
cmdBuilder.addParameter(sdkFlavor.versionOption)
val cmd = cmdBuilder.build()
val environment = targetEnvRequest.prepareEnvironment(TargetProgressIndicatorAdapter(indicator))
return sdkFlavor.getVersionStringFromOutput(cmd.execute(environment, indicator))
}
@Throws(ExecutionException::class)
fun getInterpreterPaths(indicator: ProgressIndicator): List<String> {
val execution = prepareHelperScriptExecution(helperPackage = PythonHelper.SYSPATH, helpersAwareTargetRequest = pyRequest)
val environment = targetEnvRequest.prepareEnvironment(TargetProgressIndicatorAdapter(indicator))
val cmd = execution.buildTargetedCommandLine(environment, sdk, emptyList())
return cmd.execute(environment, indicator).stdoutLines
}
@Throws(ExecutionException::class)
fun synchronizeRemoteSourcesAndSetupMappings(indicator: ProgressIndicator) {
if (isLocalTarget()) return
PyTargetsRemoteSourcesRefresher(sdk, project).run(indicator)
}
} | apache-2.0 | f134896da7cbd66995ac8e5e0d51eed9 | 43.416667 | 140 | 0.815282 | 4.920844 | false | false | false | false |
GunoH/intellij-community | java/java-impl/src/com/intellij/psi/impl/JavaPlatformModuleSystem.kt | 2 | 13798 | // 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.psi.impl
import com.intellij.codeInsight.JavaModuleSystemEx
import com.intellij.codeInsight.JavaModuleSystemEx.ErrorWithFixes
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.codeInsight.daemon.JavaErrorBundle
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.daemon.impl.quickfix.AddExportsDirectiveFix
import com.intellij.codeInsight.daemon.impl.quickfix.AddRequiresDirectiveFix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.java.JavaBundle
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.JdkOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.psi.*
import com.intellij.psi.impl.light.LightJavaModule
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiUtil
import com.intellij.util.indexing.DumbModeAccessType
import org.jetbrains.annotations.NonNls
import java.util.regex.Pattern
/**
* Checks package accessibility according to JLS 7 "Packages and Modules".
*
* @see <a href="https://docs.oracle.com/javase/specs/jls/se9/html/jls-7.html">JLS 7 "Packages and Modules"</a>
* @see <a href="http://openjdk.org/jeps/261">JEP 261: Module System</a>
*/
class JavaPlatformModuleSystem : JavaModuleSystemEx {
override fun getName(): String = JavaBundle.message("java.platform.module.system.name")
override fun isAccessible(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): Boolean =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = true) == null
override fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement): ErrorWithFixes? =
checkAccess(targetPackageName, targetFile?.originalFile, place, quick = false)
private fun checkAccess(targetPackageName: String, targetFile: PsiFile?, place: PsiElement, quick: Boolean): ErrorWithFixes? {
val useFile = place.containingFile?.originalFile
if (useFile != null && PsiUtil.isLanguageLevel9OrHigher(useFile)) {
val useVFile = useFile.virtualFile
val index = ProjectFileIndex.getInstance(useFile.project)
if (useVFile == null || !index.isInLibrarySource(useVFile)) {
if (targetFile != null && targetFile.isPhysical) {
return checkAccess(targetFile, useFile, targetPackageName, quick)
}
else if (useVFile != null) {
val target = JavaPsiFacade.getInstance(useFile.project).findPackage(targetPackageName)
if (target != null) {
val module = index.getModuleForFile(useVFile)
if (module != null) {
val test = index.isInTestSourceContent(useVFile)
val moduleScope = module.getModuleWithDependenciesAndLibrariesScope(test)
val dirs = target.getDirectories(moduleScope)
if (dirs.isEmpty()) {
if (target.getFiles(moduleScope).isEmpty()) {
return if (quick) ERR else ErrorWithFixes(JavaErrorBundle.message("package.not.found", target.qualifiedName))
}
else {
return null
}
}
val error = checkAccess(dirs[0], useFile, target.qualifiedName, quick)
return when {
error == null -> null
dirs.size == 1 -> error
dirs.asSequence().drop(1).any { checkAccess(it, useFile, target.qualifiedName, true) == null } -> null
else -> error
}
}
}
}
}
}
return null
}
private val ERR = ErrorWithFixes("-")
private fun checkAccess(target: PsiFileSystemItem, place: PsiFileSystemItem, packageName: String, quick: Boolean): ErrorWithFixes? {
val targetModule = JavaModuleGraphUtil.findDescriptorByElement(target)
val useModule = JavaModuleGraphUtil.findDescriptorByElement(place).let { if (it is LightJavaModule) null else it }
if (targetModule != null) {
if (targetModule == useModule) {
return null
}
val targetName = targetModule.name
val useName = useModule?.name ?: "ALL-UNNAMED"
val module = place.virtualFile?.let { ProjectFileIndex.getInstance(place.project).getModuleForFile(it) }
if (useModule == null) {
val origin = targetModule.containingFile?.virtualFile
if (origin == null || module == null || ModuleRootManager.getInstance(module).fileIndex.getOrderEntryForFile(origin) !is JdkOrderEntry) {
return null // a target is not on the mandatory module path
}
if (targetName.startsWith("java.") &&
targetName != PsiJavaModule.JAVA_BASE &&
!inAddedModules(module, targetName) &&
!hasUpgrade(module, targetName, packageName, place)) {
val root = DumbModeAccessType.RELIABLE_DATA_ONLY.ignoreDumbMode<PsiJavaModule, Throwable> {
JavaPsiFacade.getInstance(place.project).findModule("java.se", module.moduleWithLibrariesScope)
}
if (root != null && !JavaModuleGraphUtil.reads(root, targetModule)) {
return if (quick) ERR
else ErrorWithFixes(
JavaErrorBundle.message("module.access.not.in.graph", packageName, targetName),
listOf(AddModulesOptionFix(module, targetName)))
}
}
}
if (!(targetModule is LightJavaModule ||
JavaModuleGraphUtil.exports(targetModule, packageName, useModule) ||
module != null && inAddedExports(module, targetName, packageName, useName) ||
module != null && isPatchedModule(targetName, module, place))) {
if (quick) return ERR
val fixes = when {
packageName.isEmpty() -> emptyList()
targetModule is PsiCompiledElement && module != null -> listOf(AddExportsOptionFix(module, targetName, packageName, useName))
targetModule !is PsiCompiledElement && useModule != null -> listOf(AddExportsDirectiveFix(targetModule, packageName, useName))
else -> emptyList()
}
return when (useModule) {
null -> ErrorWithFixes(JavaErrorBundle.message("module.access.from.unnamed", packageName, targetName), fixes)
else -> ErrorWithFixes(JavaErrorBundle.message("module.access.from.named", packageName, targetName, useName), fixes)
}
}
if (useModule != null && !(targetName == PsiJavaModule.JAVA_BASE || JavaModuleGraphUtil.reads(useModule, targetModule))) {
return when {
quick -> ERR
PsiNameHelper.isValidModuleName(targetName, useModule) -> ErrorWithFixes(
JavaErrorBundle.message("module.access.does.not.read", packageName, targetName, useName),
listOf(AddRequiresDirectiveFix(useModule, targetName)))
else -> ErrorWithFixes(JavaErrorBundle.message("module.access.bad.name", packageName, targetName))
}
}
}
else if (useModule != null) {
val autoModule = detectAutomaticModule(target)
if (autoModule == null || !JavaModuleGraphUtil.reads(useModule, autoModule) && !inSameMultiReleaseModule(place, target)) {
return if (quick) ERR else ErrorWithFixes(JavaErrorBundle.message("module.access.to.unnamed", packageName, useModule.name))
}
}
return null
}
private fun inSameMultiReleaseModule(place: PsiElement, target: PsiElement): Boolean {
val placeModule = ModuleUtilCore.findModuleForPsiElement(place) ?: return false
val targetModule = ModuleUtilCore.findModuleForPsiElement(target) ?: return false
if (targetModule.name.endsWith(".$MAIN")) {
val baseModuleName = targetModule.name.substringBeforeLast(MAIN)
return javaVersionPattern.matcher(placeModule.name.substringAfter(baseModuleName)).matches()
}
return false
}
private fun detectAutomaticModule(target: PsiFileSystemItem): PsiJavaModule? {
val project = target.project
val m = ProjectFileIndex.getInstance(project).getModuleForFile(target.virtualFile) ?: return null
return JavaPsiFacade.getInstance(project).findModule(LightJavaModule.moduleName(m.name), GlobalSearchScope.moduleScope(m))
}
private fun hasUpgrade(module: Module, targetName: String, packageName: String, place: PsiFileSystemItem): Boolean {
if (PsiJavaModule.UPGRADEABLE.contains(targetName)) {
val target = JavaPsiFacade.getInstance(module.project).findPackage(packageName)
if (target != null) {
val useVFile = place.virtualFile
if (useVFile != null) {
val index = ModuleRootManager.getInstance(module).fileIndex
val test = index.isInTestSourceContent(useVFile)
val dirs = target.getDirectories(module.getModuleWithDependenciesAndLibrariesScope(test))
return dirs.any { index.getOrderEntryForFile(it.virtualFile) !is JdkOrderEntry }
}
}
}
return false
}
private fun isPatchedModule(targetModuleName: String, module: Module, place: PsiFileSystemItem): Boolean {
val rootForFile = ProjectRootManager.getInstance(place.project).fileIndex.getSourceRootForFile(place.virtualFile)
return rootForFile != null && JavaCompilerConfigurationProxy.isPatchedModuleRoot(targetModuleName, module, rootForFile)
}
private fun inAddedExports(module: Module, targetName: String, packageName: String, useName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
if (options.isEmpty()) return false
val prefix = "${targetName}/${packageName}="
return JavaCompilerConfigurationProxy.optionValues(options, "--add-exports")
.filter { it.startsWith(prefix) }
.map { it.substring(prefix.length) }
.flatMap { it.splitToSequence(",") }
.any { it == useName }
}
private fun inAddedModules(module: Module, moduleName: String): Boolean {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module)
return JavaCompilerConfigurationProxy.optionValues(options, "--add-modules")
.flatMap { it.splitToSequence(",") }
.any { it == moduleName || it == "ALL-SYSTEM" || it == "ALL-MODULE-PATH" }
}
private abstract class CompilerOptionFix(private val module: Module) : IntentionAction {
@NonNls override fun getFamilyName() = "Fix compiler option" // not visible
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = !module.isDisposed
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (isAvailable(project, editor, file)) {
val options = JavaCompilerConfigurationProxy.getAdditionalOptions(module.project, module).toMutableList()
update(options)
JavaCompilerConfigurationProxy.setAdditionalOptions(module.project, module, options)
PsiManager.getInstance(project).dropPsiCaches()
DaemonCodeAnalyzer.getInstance(project).restart()
}
}
protected abstract fun update(options: MutableList<String>)
override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement? = null
override fun startInWriteAction() = true
}
private class AddExportsOptionFix(module: Module, targetName: String, packageName: String, private val useName: String) : CompilerOptionFix(module) {
private val qualifier = "${targetName}/${packageName}"
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-exports ${qualifier}=${useName}")
override fun update(options: MutableList<String>) {
var idx = -1; var candidate = -1; var offset = 0
val prefix = "--add-exports"
for ((i, option) in options.withIndex()) {
if (option.startsWith(prefix)) {
if (option.length == prefix.length) { candidate = i + 1 ; offset = 0 }
else if (option[prefix.length] == '=') { candidate = i; offset = prefix.length + 1 }
}
if (i == candidate && option.startsWith(qualifier, offset)) {
val qualifierEnd = qualifier.length + offset
if (option.length == qualifierEnd || option[qualifierEnd] == '=') {
idx = i
}
}
}
when (idx) {
-1 -> options += listOf(prefix, "${qualifier}=${useName}")
else -> options[idx] = "${options[idx].trimEnd(',')},${useName}"
}
}
}
private class AddModulesOptionFix(module: Module, private val moduleName: String) : CompilerOptionFix(module) {
override fun getText() = QuickFixBundle.message("add.compiler.option.fix.name", "--add-modules ${moduleName}")
override fun update(options: MutableList<String>) {
var idx = -1
val prefix = "--add-modules"
for ((i, option) in options.withIndex()) {
if (option.startsWith(prefix)) {
if (option.length == prefix.length) idx = i + 1
else if (option[prefix.length] == '=') idx = i
}
}
when (idx) {
-1 -> options += listOf(prefix, moduleName)
options.size -> options += moduleName
else -> {
val value = options[idx]
options[idx] = if (value.endsWith('=') || value.endsWith(',')) value + moduleName else "${value},${moduleName}"
}
}
}
}
private companion object {
const val MAIN = "main"
val javaVersionPattern: Pattern by lazy { Pattern.compile("java\\d+") }
}
}
| apache-2.0 | ce32f36f00e1840891b6e6017af21a54 | 46.253425 | 151 | 0.687563 | 4.785987 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/expressions.kt | 1 | 15564 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k.tree
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiExpression
import com.intellij.psi.PsiSwitchExpression
import org.jetbrains.kotlin.nj2k.symbols.*
import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitor
import org.jetbrains.kotlin.nj2k.types.JKContextType
import org.jetbrains.kotlin.nj2k.types.JKNoType
import org.jetbrains.kotlin.nj2k.types.JKType
import org.jetbrains.kotlin.nj2k.types.JKTypeFactory
abstract class JKExpression : JKAnnotationMemberValue(), PsiOwner by PsiOwnerImpl() {
protected abstract val expressionType: JKType?
open fun calculateType(typeFactory: JKTypeFactory): JKType? {
val psiType = (psi as? PsiExpression)?.type ?: return null
return typeFactory.fromPsiType(psiType)
}
}
abstract class JKOperatorExpression : JKExpression() {
abstract var operator: JKOperator
override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: operator.returnType
}
class JKBinaryExpression(
left: JKExpression,
right: JKExpression,
override var operator: JKOperator,
override val expressionType: JKType? = null,
) : JKOperatorExpression() {
var left by child(left)
var right by child(right)
override fun accept(visitor: JKVisitor) = visitor.visitBinaryExpression(this)
}
abstract class JKUnaryExpression : JKOperatorExpression() {
abstract var expression: JKExpression
}
class JKPrefixExpression(
expression: JKExpression,
override var operator: JKOperator,
override val expressionType: JKType? = null,
) : JKUnaryExpression() {
override var expression by child(expression)
override fun accept(visitor: JKVisitor) = visitor.visitPrefixExpression(this)
}
class JKPostfixExpression(
expression: JKExpression,
override var operator: JKOperator,
override val expressionType: JKType? = null
) : JKUnaryExpression() {
override var expression by child(expression)
override fun accept(visitor: JKVisitor) = visitor.visitPostfixExpression(this)
}
class JKQualifiedExpression(
receiver: JKExpression,
selector: JKExpression,
override val expressionType: JKType? = null,
) : JKExpression() {
var receiver: JKExpression by child(receiver)
var selector: JKExpression by child(selector)
override fun accept(visitor: JKVisitor) = visitor.visitQualifiedExpression(this)
}
class JKParenthesizedExpression(
expression: JKExpression,
override val expressionType: JKType? = null
) : JKExpression() {
var expression: JKExpression by child(expression)
override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: expression.calculateType(typeFactory)
override fun accept(visitor: JKVisitor) = visitor.visitParenthesizedExpression(this)
}
class JKTypeCastExpression(
expression: JKExpression,
type: JKTypeElement,
override val expressionType: JKType? = null,
) : JKExpression() {
var expression by child(expression)
var type by child(type)
override fun calculateType(typeFactory: JKTypeFactory) = expressionType ?: type.type
override fun accept(visitor: JKVisitor) = visitor.visitTypeCastExpression(this)
}
class JKLiteralExpression(
var literal: String,
val type: LiteralType,
override val expressionType: JKType? = null,
) : JKExpression() {
override fun accept(visitor: JKVisitor) = visitor.visitLiteralExpression(this)
override fun calculateType(typeFactory: JKTypeFactory): JKType {
expressionType?.let { return it }
return when (type) {
LiteralType.CHAR -> typeFactory.types.char
LiteralType.BOOLEAN -> typeFactory.types.boolean
LiteralType.INT -> typeFactory.types.int
LiteralType.LONG -> typeFactory.types.long
LiteralType.FLOAT -> typeFactory.types.float
LiteralType.DOUBLE -> typeFactory.types.double
LiteralType.NULL -> typeFactory.types.nullableAny
LiteralType.STRING, LiteralType.TEXT_BLOCK -> typeFactory.types.string
}
}
enum class LiteralType {
STRING, TEXT_BLOCK, CHAR, BOOLEAN, NULL, INT, LONG, FLOAT, DOUBLE
}
}
class JKStubExpression(override val expressionType: JKType? = null) : JKExpression() {
override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType
override fun accept(visitor: JKVisitor) = visitor.visitStubExpression(this)
}
class JKThisExpression(
qualifierLabel: JKLabel,
override val expressionType: JKType? = null,
) : JKExpression() {
var qualifierLabel: JKLabel by child(qualifierLabel)
override fun accept(visitor: JKVisitor) = visitor.visitThisExpression(this)
}
class JKSuperExpression(
override val expressionType: JKType = JKNoType,
val superTypeQualifier: JKClassSymbol? = null,
outerTypeQualifier: JKLabel = JKLabelEmpty(),
) : JKExpression() {
var outerTypeQualifier: JKLabel by child(outerTypeQualifier)
override fun accept(visitor: JKVisitor) = visitor.visitSuperExpression(this)
}
class JKIfElseExpression(
condition: JKExpression,
thenBranch: JKExpression,
elseBranch: JKExpression,
override val expressionType: JKType? = null,
) : JKExpression() {
var condition by child(condition)
var thenBranch by child(thenBranch)
var elseBranch by child(elseBranch)
override fun accept(visitor: JKVisitor) = visitor.visitIfElseExpression(this)
}
class JKLambdaExpression(
statement: JKStatement,
parameters: List<JKParameter>,
functionalType: JKTypeElement = JKTypeElement(JKNoType),
returnType: JKTypeElement = JKTypeElement(JKContextType),
override val expressionType: JKType? = null,
) : JKExpression() {
var statement by child(statement)
var parameters by children(parameters)
var functionalType by child(functionalType)
val returnType by child(returnType)
override fun accept(visitor: JKVisitor) = visitor.visitLambdaExpression(this)
}
abstract class JKCallExpression : JKExpression(), JKTypeArgumentListOwner {
abstract val identifier: JKMethodSymbol
abstract var arguments: JKArgumentList
}
class JKDelegationConstructorCall(
override val identifier: JKMethodSymbol,
expression: JKExpression,
arguments: JKArgumentList,
override val expressionType: JKType? = null,
) : JKCallExpression() {
override var typeArgumentList: JKTypeArgumentList by child(JKTypeArgumentList())
val expression: JKExpression by child(expression)
override var arguments: JKArgumentList by child(arguments)
override fun accept(visitor: JKVisitor) = visitor.visitDelegationConstructorCall(this)
}
class JKCallExpressionImpl(
override val identifier: JKMethodSymbol,
arguments: JKArgumentList = JKArgumentList(),
typeArgumentList: JKTypeArgumentList = JKTypeArgumentList(),
override val expressionType: JKType? = null,
) : JKCallExpression() {
override var typeArgumentList by child(typeArgumentList)
override var arguments by child(arguments)
override fun accept(visitor: JKVisitor) = visitor.visitCallExpressionImpl(this)
}
class JKNewExpression(
val classSymbol: JKClassSymbol,
arguments: JKArgumentList,
typeArgumentList: JKTypeArgumentList = JKTypeArgumentList(),
classBody: JKClassBody = JKClassBody(),
val isAnonymousClass: Boolean = false,
override val expressionType: JKType? = null,
) : JKExpression() {
var typeArgumentList by child(typeArgumentList)
var arguments by child(arguments)
var classBody by child(classBody)
override fun accept(visitor: JKVisitor) = visitor.visitNewExpression(this)
}
class JKFieldAccessExpression(
var identifier: JKFieldSymbol,
override val expressionType: JKType? = null,
) : JKExpression() {
override fun accept(visitor: JKVisitor) = visitor.visitFieldAccessExpression(this)
}
class JKPackageAccessExpression(var identifier: JKPackageSymbol) : JKExpression() {
override val expressionType: JKType? get() = null
override fun calculateType(typeFactory: JKTypeFactory): JKType? = null
override fun accept(visitor: JKVisitor) = visitor.visitPackageAccessExpression(this)
}
class JKClassAccessExpression(
var identifier: JKClassSymbol, override val expressionType: JKType? = null,
) : JKExpression() {
override fun accept(visitor: JKVisitor) = visitor.visitClassAccessExpression(this)
}
class JKMethodAccessExpression(val identifier: JKMethodSymbol, override val expressionType: JKType? = null) : JKExpression() {
override fun accept(visitor: JKVisitor) = visitor.visitMethodAccessExpression(this)
}
class JKTypeQualifierExpression(val type: JKType, override val expressionType: JKType? = null) : JKExpression() {
override fun accept(visitor: JKVisitor) = visitor.visitTypeQualifierExpression(this)
}
class JKMethodReferenceExpression(
qualifier: JKExpression,
val identifier: JKSymbol,
functionalType: JKTypeElement,
val isConstructorCall: Boolean,
override val expressionType: JKType? = null,
) : JKExpression() {
val qualifier by child(qualifier)
val functionalType by child(functionalType)
override fun accept(visitor: JKVisitor) = visitor.visitMethodReferenceExpression(this)
}
class JKLabeledExpression(
statement: JKStatement,
labels: List<JKNameIdentifier>,
override val expressionType: JKType? = null,
) : JKExpression() {
var statement: JKStatement by child(statement)
val labels: List<JKNameIdentifier> by children(labels)
override fun accept(visitor: JKVisitor) = visitor.visitLabeledExpression(this)
}
class JKClassLiteralExpression(
classType: JKTypeElement,
var literalType: ClassLiteralType,
override val expressionType: JKType? = null,
) : JKExpression() {
val classType: JKTypeElement by child(classType)
override fun accept(visitor: JKVisitor) = visitor.visitClassLiteralExpression(this)
enum class ClassLiteralType {
KOTLIN_CLASS,
JAVA_CLASS,
JAVA_PRIMITIVE_CLASS,
JAVA_VOID_TYPE
}
}
abstract class JKKtAssignmentChainLink : JKExpression() {
abstract val receiver: JKExpression
abstract val assignmentStatement: JKKtAssignmentStatement
abstract val field: JKExpression
override val expressionType: JKType? get() = null
override fun calculateType(typeFactory: JKTypeFactory) = field.calculateType(typeFactory)
}
class JKAssignmentChainAlsoLink(
receiver: JKExpression,
assignmentStatement: JKKtAssignmentStatement,
field: JKExpression
) : JKKtAssignmentChainLink() {
override val receiver by child(receiver)
override val assignmentStatement by child(assignmentStatement)
override val field by child(field)
override fun accept(visitor: JKVisitor) = visitor.visitAssignmentChainAlsoLink(this)
}
class JKAssignmentChainLetLink(
receiver: JKExpression,
assignmentStatement: JKKtAssignmentStatement,
field: JKExpression
) : JKKtAssignmentChainLink() {
override val receiver by child(receiver)
override val assignmentStatement by child(assignmentStatement)
override val field by child(field)
override fun accept(visitor: JKVisitor) = visitor.visitAssignmentChainLetLink(this)
}
class JKIsExpression(expression: JKExpression, type: JKTypeElement) : JKExpression() {
var type by child(type)
var expression by child(expression)
override val expressionType: JKType? get() = null
override fun calculateType(typeFactory: JKTypeFactory) = typeFactory.types.boolean
override fun accept(visitor: JKVisitor) = visitor.visitIsExpression(this)
}
class JKKtItExpression(override val expressionType: JKType) : JKExpression() {
override fun accept(visitor: JKVisitor) = visitor.visitKtItExpression(this)
}
class JKKtAnnotationArrayInitializerExpression(
initializers: List<JKAnnotationMemberValue>,
override val expressionType: JKType? = null
) : JKExpression() {
constructor(vararg initializers: JKAnnotationMemberValue) : this(initializers.toList())
val initializers: List<JKAnnotationMemberValue> by children(initializers)
override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType
override fun accept(visitor: JKVisitor) = visitor.visitKtAnnotationArrayInitializerExpression(this)
}
class JKKtTryExpression(
tryBlock: JKBlock,
finallyBlock: JKBlock,
catchSections: List<JKKtTryCatchSection>,
override val expressionType: JKType? = null,
) : JKExpression() {
var tryBlock: JKBlock by child(tryBlock)
var finallyBlock: JKBlock by child(finallyBlock)
var catchSections: List<JKKtTryCatchSection> by children(catchSections)
override fun accept(visitor: JKVisitor) = visitor.visitKtTryExpression(this)
}
class JKThrowExpression(exception: JKExpression) : JKExpression() {
var exception: JKExpression by child(exception)
override val expressionType: JKType? get() = null
override fun calculateType(typeFactory: JKTypeFactory) = typeFactory.types.nothing
override fun accept(visitor: JKVisitor) = visitor.visitKtThrowExpression(this)
}
class JKJavaNewEmptyArray(
initializer: List<JKExpression>,
type: JKTypeElement,
override val expressionType: JKType? = null
) : JKExpression() {
val type by child(type)
var initializer by children(initializer)
override fun accept(visitor: JKVisitor) = visitor.visitJavaNewEmptyArray(this)
}
class JKJavaNewArray(
initializer: List<JKExpression>,
type: JKTypeElement,
override val expressionType: JKType? = null
) : JKExpression() {
val type by child(type)
var initializer by children(initializer)
override fun accept(visitor: JKVisitor) = visitor.visitJavaNewArray(this)
}
class JKJavaAssignmentExpression(
field: JKExpression,
expression: JKExpression,
var operator: JKOperator,
override val expressionType: JKType? = null
) : JKExpression() {
var field by child(field)
var expression by child(expression)
override fun accept(visitor: JKVisitor) = visitor.visitJavaAssignmentExpression(this)
}
class JKJavaSwitchExpression(
expression: JKExpression,
cases: List<JKJavaSwitchCase>,
override val expressionType: JKType? = null,
) : JKExpression(), JKJavaSwitchBlock {
override var expression: JKExpression by child(expression)
override var cases: List<JKJavaSwitchCase> by children(cases)
override fun accept(visitor: JKVisitor) = visitor.visitJavaSwitchExpression(this)
override fun calculateType(typeFactory: JKTypeFactory): JKType? {
val psiType = (psi as? PsiSwitchExpression)?.type ?: return null
return typeFactory.fromPsiType(psiType)
}
}
class JKKtWhenExpression(
expression: JKExpression,
cases: List<JKKtWhenCase>,
override val expressionType: JKType?,
) : JKExpression(), JKKtWhenBlock {
override var expression: JKExpression by child(expression)
override var cases: List<JKKtWhenCase> by children(cases)
override fun accept(visitor: JKVisitor) = visitor.visitKtWhenExpression(this)
override fun calculateType(typeFactory: JKTypeFactory): JKType? = expressionType
}
class JKErrorExpression(
override var psi: PsiElement?,
override val reason: String?,
override val expressionType: JKType? = null
) : JKExpression(), JKErrorElement {
override fun calculateType(typeFactory: JKTypeFactory): JKType = expressionType ?: typeFactory.types.nothing
override fun accept(visitor: JKVisitor) = visitor.visitExpression(this)
} | apache-2.0 | e6c91666f2b639081e7f42ba7eda0304 | 36.147971 | 126 | 0.756939 | 4.990061 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/ir/buildsystem/gradle/GradleIR.kt | 6 | 4881 | // 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.tools.projectWizard.ir.buildsystem.gradle
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.FreeIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.RepositoryIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.render
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.BuildFilePrinter
import org.jetbrains.kotlin.tools.projectWizard.plugins.printer.GradlePrinter
interface GradleIR : BuildSystemIR {
fun GradlePrinter.renderGradle()
override fun BuildFilePrinter.render() {
if (this is GradlePrinter) renderGradle()
}
}
data class RawGradleIR(
val renderer: GradlePrinter.() -> Unit
) : GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() = renderer()
}
class CreateGradleValueIR(@NonNls val name: String, val body: BuildSystemIR) : GradleIR {
override fun GradlePrinter.renderGradle() {
when (dsl) {
GradlePrinter.GradleDsl.KOTLIN -> {
+"val "
+name
+" = "
body.render(this)
}
GradlePrinter.GradleDsl.GROOVY -> {
+"def "
+name
+" = "
body.render(this)
}
}
}
}
data class GradleCallIr(
@NonNls val name: String,
val parameters: List<BuildSystemIR> = emptyList(),
val isConstructorCall: Boolean = false,
) : GradleIR {
constructor(
name: String,
vararg parameters: BuildSystemIR,
isConstructorCall: Boolean = false
) : this(name, parameters.toList(), isConstructorCall)
override fun GradlePrinter.renderGradle() {
if (isConstructorCall && dsl == GradlePrinter.GradleDsl.GROOVY) +"new "
call(name, forceBrackets = true) {
parameters.list { it.render(this) }
}
}
}
data class GradleNewInstanceCall(
@NonNls val name: String,
val parameters: List<BuildSystemIR> = emptyList()
) : GradleIR {
override fun GradlePrinter.renderGradle() {
if (dsl == GradlePrinter.GradleDsl.GROOVY) {
+"new "
}
call(name, forceBrackets = true) {
parameters.list { it.render(this) }
}
}
}
data class GradleSectionIR(
@NonNls val name: String,
val irs: List<BuildSystemIR>
) : GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() {
sectionCall(name) {
if (irs.isNotEmpty()) {
irs.listNl()
}
}
}
}
data class GradleAssignmentIR(
@NonNls val target: String,
val assignee: BuildSystemIR
) : GradleIR, FreeIR {
override fun GradlePrinter.renderGradle() {
+"$target = "
assignee.render(this)
}
}
data class GradleStringConstIR(
@NonNls val text: String
) : GradleIR {
override fun GradlePrinter.renderGradle() {
+text.quotified
}
}
data class CompilationAccessIr(
@NonNls val targetName: String,
@NonNls val compilationName: String,
@NonNls val property: String?
) : GradleIR {
override fun GradlePrinter.renderGradle() {
when (dsl) {
GradlePrinter.GradleDsl.KOTLIN -> +"kotlin.$targetName().compilations[\"$compilationName\"]"
GradlePrinter.GradleDsl.GROOVY -> +"kotlin.$targetName().compilations.$compilationName"
}
property?.let { +".$it" }
}
}
data class GradleDynamicPropertyAccessIR(val qualifier: BuildSystemIR, @NonNls val propertyName: String) : GradleIR {
override fun GradlePrinter.renderGradle() {
qualifier.render(this)
when (dsl) {
GradlePrinter.GradleDsl.KOTLIN -> +"[${propertyName.quotified}]"
GradlePrinter.GradleDsl.GROOVY -> +".$propertyName"
}
}
}
data class GradlePropertyAccessIR(val propertyName: String) : GradleIR {
override fun GradlePrinter.renderGradle() {
+propertyName
}
}
data class GradleImportIR(val import: String) : GradleIR {
override fun GradlePrinter.renderGradle() {
+"import "
+import
}
}
data class GradleBinaryExpressionIR(val left: BuildSystemIR, val op: String, val right: BuildSystemIR) : GradleIR {
override fun GradlePrinter.renderGradle() {
left.render(this)
+" $op "
right.render(this)
}
}
interface BuildScriptIR : BuildSystemIR
data class BuildScriptDependencyIR(val dependencyIR: BuildSystemIR) : BuildScriptIR, BuildSystemIR by dependencyIR
data class BuildScriptRepositoryIR(val repositoryIR: RepositoryIR) : BuildScriptIR, BuildSystemIR by repositoryIR | apache-2.0 | 72704248f21042a34a2088cacb177e43 | 29.5125 | 158 | 0.659701 | 4.417195 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/di/FragmentScoped.kt | 1 | 1122 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.di
import javax.inject.Scope
/**
* ================================================
* <p>
* Created by NIRVANA on 2017/01/27
* Contact with <[email protected]>
* ================================================
*/
@Scope
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
annotation class FragmentScoped
| apache-2.0 | 36363bc5a5b17a6dd8291f7bae8e4403 | 35.193548 | 149 | 0.670232 | 4.365759 | false | false | false | false |
excref/kotblog | blog/service/impl/src/main/kotlin/com/excref/kotblog/blog/service/category/impl/CategoryServiceImpl.kt | 1 | 3395 | package com.excref.kotblog.blog.service.category.impl
import com.excref.kotblog.blog.persistence.category.CategoryRepository
import com.excref.kotblog.blog.service.category.CategoryService
import com.excref.kotblog.blog.service.category.domain.Category
import com.excref.kotblog.blog.service.category.exception.CategoriesNotExistsForUuidsException
import com.excref.kotblog.blog.service.category.exception.CategoryAlreadyExistsForNameException
import com.excref.kotblog.blog.service.category.exception.CategoryNotExistsForUuidException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
/**
* @author Ruben Vardanyan
* @since 06/07/2017 12:31
*/
@Service
class CategoryServiceImpl : CategoryService {
//region Dependencies
@Autowired
private lateinit var categoryRepository: CategoryRepository
//endregion
//region Public methods
@Transactional
override fun create(name: String): Category {
assertCategoryNotExistForName(name)
logger.debug("Creating category with name - $name")
return categoryRepository.save(Category(name))
}
@Transactional(readOnly = true)
override fun getByUuid(uuid: String): Category {
logger.debug("Getting category with uuid - $uuid")
val category = categoryRepository.findByUuid(uuid)
assertCategoryNotNullForUuid(category, uuid)
logger.debug("Successfully got category - $category")
return category as Category
}
@Transactional(readOnly = true)
override fun getByUuids(uuids: List<String>): List<Category> {
logger.debug("Getting categories with uuids - $uuids")
val categories = categoryRepository.findByUuidIn(uuids)
assertCategoriesNotNullForUuids(categories, uuids)
logger.debug("Successfully got categories - $categories")
return categories as List<Category>
}
@Transactional(readOnly = true)
override fun existsForName(name: String): Boolean {
logger.debug("Getting category with name - $name")
return categoryRepository.findByName(name) != null
}
//endregion
//region Utility methods
fun assertCategoryNotExistForName(name: String) {
if (existsForName(name)) {
logger.error("The category with name $name already exists")
throw CategoryAlreadyExistsForNameException(name, "The category with name $name already exists")
}
}
fun assertCategoryNotNullForUuid(category: Category?, uuid: String) {
if (category == null) {
logger.error("Can not find category for uuid $uuid")
throw CategoryNotExistsForUuidException(uuid, "Can not find category for uuid $uuid")
}
}
fun assertCategoriesNotNullForUuids(categories: List<Category>?, uuids: List<String>) {
if (categories == null || categories.isEmpty()) {
logger.error("Can not find categories for uuids $uuids")
throw CategoriesNotExistsForUuidsException(uuids, "Can not find categories for uuids $uuids")
}
}
//endregion
//region Companion
companion object {
private val logger: Logger = LoggerFactory.getLogger(CategoryServiceImpl::class.java)
}
//endregion
} | apache-2.0 | b86e6d07bb28ac1529d2645b183b5735 | 37.590909 | 108 | 0.724006 | 4.637978 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/query/SortOrder.kt | 1 | 817 | package com.orgzly.android.query
sealed class SortOrder {
abstract val desc: Boolean
data class Book(override val desc: Boolean = false) : SortOrder()
data class Title(override val desc: Boolean = false) : SortOrder()
data class Scheduled(override val desc: Boolean = false) : SortOrder()
data class Deadline(override val desc: Boolean = false) : SortOrder()
data class Event(override val desc: Boolean = false) : SortOrder()
data class Closed(override val desc: Boolean = false) : SortOrder()
data class Created(override val desc: Boolean = false) : SortOrder()
data class Priority(override val desc: Boolean = false) : SortOrder()
data class State(override val desc: Boolean = false) : SortOrder()
data class Position(override val desc: Boolean = false) : SortOrder()
} | gpl-3.0 | c59b28fde7b42f0387da237042cb2172 | 50.125 | 74 | 0.716034 | 4.464481 | false | false | false | false |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/tab/TabListLayout.kt | 1 | 10688 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.tab
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.widget.LinearLayout
import androidx.recyclerview.widget.ItemTouchHelper
import com.google.android.material.snackbar.BaseTransientBottomBar
import com.google.android.material.snackbar.Snackbar
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.action.item.TabListSingleAction
import jp.hazuki.yuzubrowser.legacy.tab.adapter.TabListRecyclerAdapterFactory
import jp.hazuki.yuzubrowser.legacy.tab.adapter.TabListRecyclerBaseAdapter
import jp.hazuki.yuzubrowser.legacy.tab.manager.MainTabData
import jp.hazuki.yuzubrowser.legacy.tab.manager.TabManager
import jp.hazuki.yuzubrowser.legacy.utils.view.templatepreserving.TemplatePreservingSnackBar
import jp.hazuki.yuzubrowser.ui.widget.recycler.DividerItemDecoration
class TabListLayout @SuppressLint("RtlHardcoded")
constructor(context: Context, attrs: AttributeSet?, mode: Int, left: Boolean, val lastTabMode: Int) : LinearLayout(context, attrs) {
private lateinit var adapter: TabListRecyclerBaseAdapter
private lateinit var tabManager: TabManager
private lateinit var callback: Callback
private var snackbar: TemplatePreservingSnackBar? = null
private val bottomBar: LinearLayout
private val reverse = mode == TabListSingleAction.MODE_REVERSE
private val horizontal = mode == TabListSingleAction.MODE_HORIZONTAL
private var removedTab: RemovedTab? = null
constructor(context: Context, mode: Int, left: Boolean, lastTabMode: Int) : this(context, null, mode, left, lastTabMode)
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, mode: Int = TabListSingleAction.MODE_NORMAL, lastTabMode: Int = TabListSingleAction.LAST_TAB_MODE_NONE) : this(context, attrs, mode, false, lastTabMode)
init {
val mLayoutInflater = LayoutInflater.from(context)
when {
horizontal -> {
mLayoutInflater.inflate(R.layout.tab_list_horizontal, this)
setOnClickListener { close() }
}
reverse -> mLayoutInflater.inflate(R.layout.tab_list_reverse, this)
else -> mLayoutInflater.inflate(R.layout.tab_list, this)
}
bottomBar = findViewById(R.id.bottomBar)
if (left) {
bottomBar.gravity = Gravity.LEFT
}
}
fun setTabManager(manager: TabManager) {
tabManager = manager
val recyclerView = findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.recyclerView)
val layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context)
if (horizontal) {
layoutManager.orientation = androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL
} else if (reverse) {
layoutManager.stackFromEnd = true
}
recyclerView.layoutManager = layoutManager
val helper = ItemTouchHelper(ListTouch())
helper.attachToRecyclerView(recyclerView)
recyclerView.addItemDecoration(helper)
if (!horizontal) {
recyclerView.addItemDecoration(DividerItemDecoration(context.applicationContext))
}
adapter = TabListRecyclerAdapterFactory.create(context, tabManager, horizontal, object : TabListRecyclerBaseAdapter.OnRecyclerListener {
override fun onRecyclerItemClicked(v: View, position: Int) {
snackbar?.dismiss()
callback.requestSelectTab(position)
close()
}
override fun onCloseButtonClicked(v: View, position: Int) {
snackbar?.dismiss()
val size = tabManager.size()
if (size == 1) {
closeLastTab()
} else {
val current = position == tabManager.currentTabNo
callback.requestRemoveTab(position, true)
if (size != tabManager.size()) {
adapter.notifyItemRemoved(position)
if (current) {
adapter.notifyItemChanged(tabManager.currentTabNo)
}
}
}
}
override fun onHistoryButtonClicked(v: View, position: Int) {
snackbar?.dismiss()
callback.requestShowTabHistory(position)
}
})
recyclerView.adapter = adapter
layoutManager.scrollToPosition(tabManager.currentTabNo)
setOnClickListener { close() }
findViewById<View>(R.id.newTabButton).setOnClickListener {
callback.requestAddTab()
close()
}
}
fun close() {
snackbar?.dismiss()
callback.requestTabListClose()
}
fun closeSnackBar() {
snackbar?.run {
if (isShown) dismiss()
}
}
private fun closeLastTab() {
when (lastTabMode) {
TabListSingleAction.LAST_TAB_MODE_NEW_TAB -> {
callback.requestCloseAllTab()
postDelayed({ adapter.notifyDataSetChanged() }, 100)
}
TabListSingleAction.LAST_TAB_MODE_FINISH -> callback.requestFinish(false)
TabListSingleAction.LAST_TAB_MODE_FINISH_WITH_ALERT -> callback.requestFinish(true)
}
}
private inner class ListTouch : ItemTouchHelper.Callback() {
override fun getMovementFlags(recyclerView: androidx.recyclerview.widget.RecyclerView, viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder): Int {
return if ((viewHolder as TabListRecyclerBaseAdapter.ViewHolder).indexData.isPinning) {
if (horizontal) {
ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT)
} else {
ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.DOWN or ItemTouchHelper.UP)
}
} else {
if (horizontal) {
ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.DOWN or ItemTouchHelper.UP) or ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT)
} else {
ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) or ItemTouchHelper.Callback.makeFlag(ItemTouchHelper.ACTION_STATE_DRAG, ItemTouchHelper.DOWN or ItemTouchHelper.UP)
}
}
}
override fun onMove(recyclerView: androidx.recyclerview.widget.RecyclerView, viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, target: androidx.recyclerview.widget.RecyclerView.ViewHolder): Boolean {
snackbar?.run {
if (isShown) dismiss()
}
callback.requestMoveTab(viewHolder.adapterPosition, target.adapterPosition)
adapter.notifyItemMoved(viewHolder.adapterPosition, target.adapterPosition)
return true
}
override fun onSwiped(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, direction: Int) {
if (adapter.itemCount > 1) {
snackbar?.run {
if (isShown) dismiss()
}
val position = viewHolder.adapterPosition
val current = position == tabManager.currentTabNo
removedTab = RemovedTab(position, tabManager.get(position))
callback.requestRemoveTab(position, false)
adapter.notifyItemRemoved(position)
if (current) {
adapter.notifyItemChanged(tabManager.currentTabNo)
}
snackbar = TemplatePreservingSnackBar.make(bottomBar, context.getString(R.string.closed_tab),
(viewHolder as TabListRecyclerBaseAdapter.ViewHolder).title, Snackbar.LENGTH_SHORT)
.setAction(R.string.undo, OnClickListener {
removedTab?.run {
callback.requestAddTab(index, data)
adapter.notifyItemInserted(index)
removedTab = null
}
})
.addCallback(object : BaseTransientBottomBar.BaseCallback<TemplatePreservingSnackBar>() {
override fun onDismissed(transientBottomBar: TemplatePreservingSnackBar?, event: Int) {
removedTab?.run {
destroy()
removedTab = null
}
snackbar = null
}
}).apply { show() }
} else {
adapter.notifyDataSetChanged()
closeLastTab()
}
}
override fun isItemViewSwipeEnabled(): Boolean {
return adapter.itemCount > 1 || lastTabMode != 0
}
}
interface Callback {
fun requestTabListClose()
fun requestMoveTab(positionFrom: Int, positionTo: Int)
fun requestRemoveTab(no: Int, destroy: Boolean)
fun requestAddTab()
fun requestSelectTab(no: Int)
fun requestShowTabHistory(no: Int)
fun requestAddTab(index: Int, data: MainTabData)
fun requestCloseAllTab()
fun requestFinish(alert: Boolean)
}
fun setCallback(l: Callback) {
callback = l
}
private class RemovedTab internal constructor(internal val index: Int, internal val data: MainTabData) {
internal fun destroy() {
data.mWebView.destroy()
}
}
}
| apache-2.0 | f3cd1aa2d9056172ec6e58484211ee60 | 39.180451 | 252 | 0.634824 | 5.285856 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/chatroom/ui/ChatRoomFragment.kt | 2 | 49394 | package chat.rocket.android.chatroom.ui
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.MediaStore
import android.text.SpannableStringBuilder
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.appcompat.app.AlertDialog
import androidx.core.content.FileProvider
import androidx.core.text.bold
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chat.rocket.android.R
import chat.rocket.android.analytics.AnalyticsManager
import chat.rocket.android.analytics.event.ScreenViewEvent
import chat.rocket.android.chatroom.adapter.AttachmentViewHolder
import chat.rocket.android.chatroom.adapter.ChatRoomAdapter
import chat.rocket.android.chatroom.adapter.CommandSuggestionsAdapter
import chat.rocket.android.chatroom.adapter.EmojiSuggestionsAdapter
import chat.rocket.android.chatroom.adapter.MessageViewHolder
import chat.rocket.android.chatroom.adapter.PEOPLE
import chat.rocket.android.chatroom.adapter.PeopleSuggestionsAdapter
import chat.rocket.android.chatroom.adapter.RoomSuggestionsAdapter
import chat.rocket.android.chatroom.presentation.ChatRoomNavigator
import chat.rocket.android.chatroom.presentation.ChatRoomPresenter
import chat.rocket.android.chatroom.presentation.ChatRoomView
import chat.rocket.android.chatroom.ui.bottomsheet.MessageActionsBottomSheet
import chat.rocket.android.chatroom.uimodel.BaseUiModel
import chat.rocket.android.chatroom.uimodel.MessageUiModel
import chat.rocket.android.chatroom.uimodel.suggestion.ChatRoomSuggestionUiModel
import chat.rocket.android.chatroom.uimodel.suggestion.CommandSuggestionUiModel
import chat.rocket.android.chatroom.uimodel.suggestion.EmojiSuggestionUiModel
import chat.rocket.android.chatroom.uimodel.suggestion.PeopleSuggestionUiModel
import chat.rocket.android.chatrooms.adapter.model.RoomUiModel
import chat.rocket.android.draw.main.ui.DRAWING_BYTE_ARRAY_EXTRA_DATA
import chat.rocket.android.draw.main.ui.DrawingActivity
import chat.rocket.android.emoji.ComposerEditText
import chat.rocket.android.emoji.Emoji
import chat.rocket.android.emoji.EmojiKeyboardListener
import chat.rocket.android.emoji.EmojiKeyboardPopup
import chat.rocket.android.emoji.EmojiParser
import chat.rocket.android.emoji.EmojiPickerPopup
import chat.rocket.android.emoji.EmojiReactionListener
import chat.rocket.android.emoji.internal.isCustom
import chat.rocket.android.helper.EndlessRecyclerViewScrollListener
import chat.rocket.android.helper.KeyboardHelper
import chat.rocket.android.helper.MessageParser
import chat.rocket.android.helper.AndroidPermissionsHelper
import chat.rocket.android.helper.AndroidPermissionsHelper.getCameraPermission
import chat.rocket.android.helper.AndroidPermissionsHelper.getWriteExternalStoragePermission
import chat.rocket.android.helper.AndroidPermissionsHelper.hasCameraPermission
import chat.rocket.android.helper.AndroidPermissionsHelper.hasWriteExternalStoragePermission
import chat.rocket.android.util.extension.asObservable
import chat.rocket.android.util.extension.createImageFile
import chat.rocket.android.util.extension.orFalse
import chat.rocket.android.util.extensions.circularRevealOrUnreveal
import chat.rocket.android.util.extensions.clearLightStatusBar
import chat.rocket.android.util.extensions.fadeIn
import chat.rocket.android.util.extensions.fadeOut
import chat.rocket.android.util.extensions.hideKeyboard
import chat.rocket.android.util.extensions.inflate
import chat.rocket.android.util.extensions.isNotNullNorEmpty
import chat.rocket.android.util.extensions.rotateBy
import chat.rocket.android.util.extensions.showToast
import chat.rocket.android.util.extensions.textContent
import chat.rocket.android.util.extensions.ui
import chat.rocket.common.model.RoomType
import chat.rocket.common.model.roomTypeOf
import chat.rocket.core.internal.realtime.socket.model.State
import com.bumptech.glide.Glide
import com.google.android.material.snackbar.Snackbar
import dagger.android.support.AndroidSupportInjection
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.app_bar_chat_room.*
import kotlinx.android.synthetic.main.emoji_image_row_item.view.*
import kotlinx.android.synthetic.main.emoji_row_item.view.*
import kotlinx.android.synthetic.main.fragment_chat_room.*
import kotlinx.android.synthetic.main.message_attachment_options.*
import kotlinx.android.synthetic.main.message_composer.*
import kotlinx.android.synthetic.main.message_list.*
import kotlinx.android.synthetic.main.reaction_praises_list_item.view.*
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
fun newInstance(
chatRoomId: String,
chatRoomName: String,
chatRoomType: String,
isReadOnly: Boolean,
chatRoomLastSeen: Long,
isSubscribed: Boolean = true,
isCreator: Boolean = false,
isFavorite: Boolean = false,
chatRoomMessage: String? = null
): Fragment = ChatRoomFragment().apply {
arguments = Bundle(1).apply {
putString(BUNDLE_CHAT_ROOM_ID, chatRoomId)
putString(BUNDLE_CHAT_ROOM_NAME, chatRoomName)
putString(BUNDLE_CHAT_ROOM_TYPE, chatRoomType)
putBoolean(BUNDLE_IS_CHAT_ROOM_READ_ONLY, isReadOnly)
putLong(BUNDLE_CHAT_ROOM_LAST_SEEN, chatRoomLastSeen)
putBoolean(BUNDLE_CHAT_ROOM_IS_SUBSCRIBED, isSubscribed)
putBoolean(BUNDLE_CHAT_ROOM_IS_CREATOR, isCreator)
putBoolean(BUNDLE_CHAT_ROOM_IS_FAVORITE, isFavorite)
putString(BUNDLE_CHAT_ROOM_MESSAGE, chatRoomMessage)
}
}
internal const val TAG_CHAT_ROOM_FRAGMENT = "ChatRoomFragment"
private const val BUNDLE_CHAT_ROOM_ID = "chat_room_id"
private const val BUNDLE_CHAT_ROOM_NAME = "chat_room_name"
private const val BUNDLE_CHAT_ROOM_TYPE = "chat_room_type"
private const val BUNDLE_IS_CHAT_ROOM_READ_ONLY = "is_chat_room_read_only"
private const val REQUEST_CODE_FOR_PERFORM_SAF = 42
private const val REQUEST_CODE_FOR_DRAW = 101
private const val REQUEST_CODE_FOR_PERFORM_CAMERA = 102
private const val BUNDLE_CHAT_ROOM_LAST_SEEN = "chat_room_last_seen"
private const val BUNDLE_CHAT_ROOM_IS_SUBSCRIBED = "chat_room_is_subscribed"
private const val BUNDLE_CHAT_ROOM_IS_CREATOR = "chat_room_is_creator"
private const val BUNDLE_CHAT_ROOM_IS_FAVORITE = "chat_room_is_favorite"
private const val BUNDLE_CHAT_ROOM_MESSAGE = "chat_room_message"
class ChatRoomFragment : Fragment(), ChatRoomView, EmojiKeyboardListener, EmojiReactionListener,
ChatRoomAdapter.OnActionSelected, Drawable.Callback {
@Inject
lateinit var presenter: ChatRoomPresenter
@Inject
lateinit var parser: MessageParser
@Inject
lateinit var analyticsManager: AnalyticsManager
@Inject
lateinit var navigator: ChatRoomNavigator
private lateinit var chatRoomAdapter: ChatRoomAdapter
internal lateinit var chatRoomId: String
private lateinit var chatRoomName: String
internal lateinit var chatRoomType: String
private var newMessageCount: Int = 0
private var chatRoomMessage: String? = null
private var isSubscribed: Boolean = true
private var isReadOnly: Boolean = false
private var isCreator: Boolean = false
internal var isFavorite: Boolean = false
private var isBroadcastChannel: Boolean = false
private lateinit var emojiKeyboardPopup: EmojiKeyboardPopup
private var chatRoomLastSeen: Long = -1
private lateinit var actionSnackbar: ActionSnackbar
internal var citation: String? = null
private var editingMessageId: String? = null
private var disableMenu: Boolean = false
private val compositeDisposable = CompositeDisposable()
private var playComposeMessageButtonsAnimation = true
internal var isSearchTermQueried = false
private val dismissConnectionState by lazy { text_connection_status.fadeOut() }
// For reveal and unreveal anim.
private val hypotenuse by lazy {
Math.hypot(
root_layout.width.toDouble(),
root_layout.height.toDouble()
).toFloat()
}
private val max by lazy {
Math.max(
layout_message_attachment_options.width.toDouble(),
layout_message_attachment_options.height.toDouble()
).toFloat()
}
private val centerX by lazy { recycler_view.right }
private val centerY by lazy { recycler_view.bottom }
private val handler = Handler()
private var verticalScrollOffset = AtomicInteger(0)
private val dialogView by lazy { View.inflate(context, R.layout.file_attachments_dialog, null) }
internal val alertDialog by lazy {
activity?.let {
AlertDialog.Builder(it).setView(dialogView).create()
}
}
internal val imagePreview by lazy { dialogView.findViewById<ImageView>(R.id.image_preview) }
internal val sendButton by lazy { dialogView.findViewById<android.widget.Button>(R.id.button_send) }
internal val cancelButton by lazy { dialogView.findViewById<android.widget.Button>(R.id.button_cancel) }
internal val description by lazy { dialogView.findViewById<EditText>(R.id.text_file_description) }
internal val audioVideoAttachment by lazy { dialogView.findViewById<FrameLayout>(R.id.audio_video_attachment) }
internal val textFile by lazy { dialogView.findViewById<TextView>(R.id.text_file_name) }
private var takenPhotoUri: Uri? = null
private val layoutChangeListener =
View.OnLayoutChangeListener { _, _, _, _, bottom, _, _, _, oldBottom ->
val y = oldBottom - bottom
if (Math.abs(y) > 0 && isAdded) {
// if y is positive the keyboard is up else it's down
recycler_view.post {
if (y > 0 || Math.abs(verticalScrollOffset.get()) >= Math.abs(y)) {
ui { recycler_view.scrollBy(0, y) }
} else {
ui { recycler_view.scrollBy(0, verticalScrollOffset.get()) }
}
}
}
}
private lateinit var endlessRecyclerViewScrollListener: EndlessRecyclerViewScrollListener
private val onScrollListener = object : RecyclerView.OnScrollListener() {
var state = AtomicInteger(RecyclerView.SCROLL_STATE_IDLE)
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
state.compareAndSet(RecyclerView.SCROLL_STATE_IDLE, newState)
when (newState) {
RecyclerView.SCROLL_STATE_IDLE -> {
if (!state.compareAndSet(RecyclerView.SCROLL_STATE_SETTLING, newState)) {
state.compareAndSet(RecyclerView.SCROLL_STATE_DRAGGING, newState)
}
}
RecyclerView.SCROLL_STATE_DRAGGING -> {
state.compareAndSet(RecyclerView.SCROLL_STATE_IDLE, newState)
}
RecyclerView.SCROLL_STATE_SETTLING -> {
state.compareAndSet(RecyclerView.SCROLL_STATE_DRAGGING, newState)
}
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (state.get() != RecyclerView.SCROLL_STATE_IDLE) {
verticalScrollOffset.getAndAdd(dy)
}
}
}
private val fabScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (!recyclerView.canScrollVertically(1)) {
text_count.isVisible = false
button_fab.hide()
newMessageCount = 0
} else {
if (dy < 0 && isAdded && !button_fab.isVisible) {
button_fab.show()
if (newMessageCount != 0) text_count.isVisible = true
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this)
arguments?.run {
chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "")
chatRoomName = getString(BUNDLE_CHAT_ROOM_NAME, "")
chatRoomType = getString(BUNDLE_CHAT_ROOM_TYPE, "")
isReadOnly = getBoolean(BUNDLE_IS_CHAT_ROOM_READ_ONLY)
isSubscribed = getBoolean(BUNDLE_CHAT_ROOM_IS_SUBSCRIBED)
chatRoomLastSeen = getLong(BUNDLE_CHAT_ROOM_LAST_SEEN)
isCreator = getBoolean(BUNDLE_CHAT_ROOM_IS_CREATOR)
isFavorite = getBoolean(BUNDLE_CHAT_ROOM_IS_FAVORITE)
chatRoomMessage = getString(BUNDLE_CHAT_ROOM_MESSAGE)
}
?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" }
chatRoomAdapter = ChatRoomAdapter(
roomId = chatRoomId,
roomType = chatRoomType,
roomName = chatRoomName,
actionSelectListener = this,
reactionListener = this,
navigator = navigator,
analyticsManager = analyticsManager
)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = container?.inflate(R.layout.fragment_chat_room)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupToolbar(chatRoomName)
presenter.setupChatRoom(chatRoomId, chatRoomName, chatRoomType, chatRoomMessage)
presenter.loadChatRoomsSuggestions()
setupRecyclerView()
setupFab()
setupSuggestionsView()
setupActionSnackbar()
with(activity as ChatRoomActivity) {
setupToolbarTitle(chatRoomName)
setupExpandMoreForToolbar {
presenter.toChatDetails(
chatRoomId,
chatRoomType,
isSubscribed,
isFavorite,
disableMenu
)
}
}
getDraftMessage()
subscribeComposeTextMessage()
analyticsManager.logScreenView(ScreenViewEvent.ChatRoom)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
text_message.addTextChangedListener(EmojiKeyboardPopup.EmojiTextWatcher(text_message))
}
override fun onDestroyView() {
recycler_view.removeOnScrollListener(endlessRecyclerViewScrollListener)
recycler_view.removeOnScrollListener(onScrollListener)
recycler_view.removeOnLayoutChangeListener(layoutChangeListener)
presenter.saveDraftMessage(text_message.text.toString())
handler.removeCallbacksAndMessages(null)
unsubscribeComposeTextMessage()
presenter.disconnect()
// Hides the keyboard (if it's opened) before going to any view.
activity?.apply { hideKeyboard() }
super.onDestroyView()
}
override fun onPause() {
super.onPause()
dismissEmojiKeyboard()
activity?.invalidateOptionsMenu()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) {
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_CODE_FOR_PERFORM_CAMERA -> takenPhotoUri?.let {
showFileAttachmentDialog(it)
}
REQUEST_CODE_FOR_PERFORM_SAF -> resultData?.data?.let {
showFileAttachmentDialog(it)
}
REQUEST_CODE_FOR_DRAW -> resultData?.getByteArrayExtra(DRAWING_BYTE_ARRAY_EXTRA_DATA)?.let {
showDrawAttachmentDialog(it)
}
}
}
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.clear()
setupMenu(menu)
super.onPrepareOptionsMenu(menu)
}
override fun openFullWebPage(roomId: String, url: String) {
presenter.openFullWebPage(roomId, url)
}
override fun openConfigurableWebPage(roomId: String, url: String, heightRatio: String) {
presenter.openConfigurableWebPage(roomId, url, heightRatio)
}
override fun showMessages(dataSet: List<BaseUiModel<*>>, clearDataSet: Boolean) {
ui {
if (clearDataSet) {
chatRoomAdapter.clearData()
}
if (dataSet.isNotEmpty()) {
var prevMsgModel = dataSet[0]
// track the message sent immediately after the current message
var prevMessageUiModel: MessageUiModel? = null
// Checking for all messages to assign true to the required showDayMaker
// Loop over received messages to determine first unread
var firstUnread = false
for (i in dataSet.indices) {
val msgModel = dataSet[i]
if (i > 0) {
prevMsgModel = dataSet[i - 1]
}
val currentDayMarkerText = msgModel.currentDayMarkerText
val previousDayMarkerText = prevMsgModel.currentDayMarkerText
if (previousDayMarkerText != currentDayMarkerText) {
prevMsgModel.showDayMarker = true
}
if (!firstUnread && msgModel is MessageUiModel) {
val msg = msgModel.rawData
if (msg.timestamp < chatRoomLastSeen) {
// This message was sent before the last seen of the room. Hence, it was seen.
// if there is a message after (below) this, mark it firstUnread.
if (prevMessageUiModel != null) {
prevMessageUiModel.isFirstUnread = true
}
// Found first unread message.
firstUnread = true
}
prevMessageUiModel = msgModel
}
}
}
val oldMessagesCount = chatRoomAdapter.itemCount
chatRoomAdapter.appendData(dataSet)
if (oldMessagesCount == 0 && dataSet.isNotEmpty()) {
recycler_view.scrollToPosition(0)
verticalScrollOffset.set(0)
}
empty_chat_view.isVisible = chatRoomAdapter.itemCount == 0
dismissEmojiKeyboard()
}
}
override fun showSearchedMessages(dataSet: List<BaseUiModel<*>>) {
recycler_view.removeOnScrollListener(endlessRecyclerViewScrollListener)
chatRoomAdapter.clearData()
chatRoomAdapter.prependData(dataSet)
empty_chat_view.isVisible = chatRoomAdapter.itemCount == 0
dismissEmojiKeyboard()
}
override fun onRoomUpdated(roomUiModel: RoomUiModel) {
// TODO: We should rely solely on the user being able to post, but we cannot guarantee
// that the "(channels|groups).getPermissionRoles" endpoint is supported by the server in use.
ui {
setupToolbar(roomUiModel.name.toString())
setupMessageComposer(roomUiModel)
isBroadcastChannel = roomUiModel.broadcast
isFavorite = roomUiModel.favorite.orFalse()
disableMenu = (roomUiModel.broadcast && !roomUiModel.canModerate)
activity?.invalidateOptionsMenu()
}
}
override fun sendMessage(text: String) {
ui {
if (!text.isBlank()) {
when {
text.startsWith("/") -> presenter.runCommand(text, chatRoomId)
text.startsWith("+") -> presenter.reactToLastMessage(text, chatRoomId)
else -> presenter.sendMessage(chatRoomId, text, editingMessageId)
}
}
}
}
override fun showTypingStatus(usernameList: List<String>) {
ui {
when (usernameList.size) {
1 -> text_typing_status.text =
SpannableStringBuilder()
.bold { append(usernameList[0]) }
.append(getString(R.string.msg_is_typing))
2 -> text_typing_status.text =
SpannableStringBuilder()
.bold { append(usernameList[0]) }
.append(getString(R.string.msg_and))
.bold { append(usernameList[1]) }
.append(getString(R.string.msg_are_typing))
else -> text_typing_status.text = getString(R.string.msg_several_users_are_typing)
}
text_typing_status.isVisible = true
}
}
override fun hideTypingStatusView() {
ui { text_typing_status.isVisible = false }
}
override fun showInvalidFileMessage() {
showMessage(getString(R.string.msg_invalid_file))
}
override fun disableSendMessageButton() {
ui { button_send.isEnabled = false }
}
override fun enableSendMessageButton() {
ui {
button_send.isEnabled = true
text_message.isEnabled = true
}
}
override fun clearMessageComposition(deleteMessage: Boolean) {
ui {
citation = null
editingMessageId = null
if (deleteMessage) {
text_message.textContent = ""
}
actionSnackbar.dismiss()
}
}
override fun showNewMessage(message: List<BaseUiModel<*>>, isMessageReceived: Boolean) {
ui {
chatRoomAdapter.prependData(message)
if (isMessageReceived && button_fab.isVisible) {
newMessageCount++
if (newMessageCount <= 99) {
text_count.text = newMessageCount.toString()
} else {
text_count.text = getString(R.string.msg_more_than_ninety_nine_unread_messages)
}
text_count.isVisible = true
} else if (!button_fab.isVisible) {
recycler_view.scrollToPosition(0)
}
verticalScrollOffset.set(0)
empty_chat_view.isVisible = chatRoomAdapter.itemCount == 0
dismissEmojiKeyboard()
}
}
override fun dispatchUpdateMessage(index: Int, message: List<BaseUiModel<*>>) {
ui {
// TODO - investigate WHY we get a empty list here
if (message.isEmpty()) return@ui
when (chatRoomAdapter.updateItem(message.last())) {
// FIXME: What's 0,1 and 2 means for here?
0 -> {
if (message.size > 1) {
chatRoomAdapter.prependData(listOf(message.first()))
}
}
1 -> showNewMessage(message, true)
2 -> {
// Position of new sent message is wrong because of device local time is behind server time
with(chatRoomAdapter) {
removeItem(message.last().messageId)
prependData(listOf(message.last()))
notifyDataSetChanged()
}
}
}
dismissEmojiKeyboard()
}
}
override fun dispatchDeleteMessage(msgId: String) {
ui {
chatRoomAdapter.removeItem(msgId)
}
}
override fun showReplyingAction(
username: String,
replyMarkdown: String,
quotedMessage: String
) {
ui {
citation = replyMarkdown
actionSnackbar.title = username
actionSnackbar.text = quotedMessage
actionSnackbar.show()
KeyboardHelper.showSoftKeyboard(text_message)
}
}
override fun showLoading() {
ui { view_loading.isVisible = true }
}
override fun hideLoading() {
ui { view_loading.isVisible = false }
}
override fun showMessage(message: String) {
ui { showToast(message) }
}
override fun showMessage(resId: Int) {
ui { showToast(resId) }
}
override fun showGenericErrorMessage() {
ui { showMessage(getString(R.string.msg_generic_error)) }
}
override fun populatePeopleSuggestions(members: List<PeopleSuggestionUiModel>) {
ui { suggestions_view.addItems("@", members) }
}
override fun populateRoomSuggestions(chatRooms: List<ChatRoomSuggestionUiModel>) {
ui { suggestions_view.addItems("#", chatRooms) }
}
override fun populateCommandSuggestions(commands: List<CommandSuggestionUiModel>) {
ui { suggestions_view.addItems("/", commands) }
}
override fun populateEmojiSuggestions(emojis: List<EmojiSuggestionUiModel>) {
ui { suggestions_view.addItems(":", emojis) }
}
override fun copyToClipboard(message: String) {
ui {
(it.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).apply {
setPrimaryClip(ClipData.newPlainText("", message))
}
}
}
override fun showEditingAction(roomId: String, messageId: String, text: String) {
ui {
actionSnackbar.title = getString(R.string.action_title_editing)
actionSnackbar.text = text
actionSnackbar.show()
text_message.textContent = text
editingMessageId = messageId
KeyboardHelper.showSoftKeyboard(text_message)
}
}
override fun onEmojiAdded(emoji: Emoji) {
val cursorPosition = text_message.selectionStart
if (cursorPosition > -1) {
context?.let {
val offset = if (!emoji.isCustom()) emoji.unicode.length else emoji.shortname.length
val parsed = if (emoji.isCustom()) emoji.shortname else EmojiParser.parse(
it,
emoji.shortname
)
text_message.text?.insert(cursorPosition, parsed)
text_message.setSelection(cursorPosition + offset)
}
}
}
override fun onNonEmojiKeyPressed(keyCode: Int) {
when (keyCode) {
KeyEvent.KEYCODE_BACK -> with(text_message) {
if (selectionStart > 0) text?.delete(selectionStart - 1, selectionStart)
}
else -> throw IllegalArgumentException("pressed key not expected")
}
}
override fun onReactionTouched(messageId: String, emojiShortname: String) {
presenter.react(messageId, emojiShortname)
}
override fun onReactionAdded(messageId: String, emoji: Emoji) {
presenter.react(messageId, emoji.shortname)
}
override fun onReactionLongClicked(
shortname: String,
isCustom: Boolean,
url: String?,
usernames: List<String>
) {
val layout =
LayoutInflater.from(requireContext()).inflate(R.layout.reaction_praises_list_item, null)
val dialog = AlertDialog.Builder(requireContext())
.setView(layout)
.setCancelable(true)
with(layout) {
view_flipper.displayedChild = if (isCustom) 1 else 0
if (isCustom && url != null) {
val glideRequest = if (url.endsWith("gif", true)) {
Glide.with(requireContext()).asGif()
} else {
Glide.with(requireContext()).asBitmap()
}
glideRequest.load(url).into(view_flipper.emoji_image_view)
} else {
view_flipper.emoji_view.text = EmojiParser.parse(requireContext(), shortname)
}
var listing = ""
if (usernames.size == 1) {
listing = usernames.first()
} else {
usernames.forEachIndexed { index, username ->
listing += if (index == usernames.size - 1) "|$username" else "$username, "
}
listing =
listing.replace(", |", " ${requireContext().getString(R.string.msg_and)} ")
}
text_view_usernames.text = requireContext().resources.getQuantityString(
R.plurals.msg_reacted_with_, usernames.size, listing, shortname
)
dialog.show()
}
}
override fun showReactionsPopup(messageId: String) {
ui {
val emojiPickerPopup = EmojiPickerPopup(it)
emojiPickerPopup.listener = object : EmojiKeyboardListener {
override fun onEmojiAdded(emoji: Emoji) {
onReactionAdded(messageId, emoji)
}
}
emojiPickerPopup.show()
}
}
private fun setReactionButtonIcon(@DrawableRes drawableId: Int) {
button_add_reaction_or_show_keyboard?.setImageResource(drawableId)
button_add_reaction_or_show_keyboard?.tag = drawableId
}
override fun showFileSelection(filter: Array<String>?) {
ui {
val intent = Intent(Intent.ACTION_GET_CONTENT)
// Must set a type otherwise the intent won't resolve
intent.type = "*/*"
intent.addCategory(Intent.CATEGORY_OPENABLE)
// Filter selectable files to those that match the whitelist for this particular server
if (filter != null) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, filter)
}
startActivityForResult(intent, REQUEST_CODE_FOR_PERFORM_SAF)
}
}
override fun showInvalidFileSize(fileSize: Int, maxFileSize: Int) {
showMessage(getString(R.string.max_file_size_exceeded, fileSize, maxFileSize))
}
override fun showConnectionState(state: State) {
ui {
text_connection_status.fadeIn()
handler.removeCallbacks { dismissConnectionState }
text_connection_status.text = when (state) {
is State.Connected -> {
handler.postDelayed({ dismissConnectionState }, 2000)
getString(R.string.status_connected)
}
is State.Disconnected -> getString(R.string.status_disconnected)
is State.Connecting -> getString(R.string.status_connecting)
is State.Authenticating -> getString(R.string.status_authenticating)
is State.Disconnecting -> getString(R.string.status_disconnecting)
is State.Waiting -> getString(R.string.status_waiting, state.seconds)
else -> "" // Show nothing
}
}
}
override fun onJoined(roomUiModel: RoomUiModel) {
ui {
input_container.isVisible = true
button_join_chat.isVisible = false
isSubscribed = true
}
}
private fun setupRecyclerView() {
// Initialize the endlessRecyclerViewScrollListener so we don't NPE at onDestroyView
val linearLayoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, true)
linearLayoutManager.stackFromEnd = true
recycler_view.layoutManager = linearLayoutManager
recycler_view.itemAnimator = DefaultItemAnimator()
endlessRecyclerViewScrollListener = object :
EndlessRecyclerViewScrollListener(recycler_view.layoutManager as LinearLayoutManager) {
override fun onLoadMore(page: Int, totalItemsCount: Int, recyclerView: RecyclerView) {
presenter.loadMessages(chatRoomId, chatRoomType, page * 30L)
}
}
with (recycler_view) {
adapter = chatRoomAdapter
addOnScrollListener(endlessRecyclerViewScrollListener)
addOnLayoutChangeListener(layoutChangeListener)
addOnScrollListener(onScrollListener)
addOnScrollListener(fabScrollListener)
}
if (!isReadOnly) {
val touchCallback: ItemTouchHelper.SimpleCallback =
object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
var replyId: String? = null
when (viewHolder) {
is MessageViewHolder -> replyId = viewHolder.data?.messageId
is AttachmentViewHolder -> replyId = viewHolder.data?.messageId
}
replyId?.let {
citeMessage(chatRoomName, chatRoomType, it, true)
}
chatRoomAdapter.notifyItemChanged(viewHolder.adapterPosition)
}
override fun getSwipeDirs(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder
): Int {
// Currently enable swipes for text and attachment messages only
if (viewHolder is MessageViewHolder || viewHolder is AttachmentViewHolder) {
return super.getSwipeDirs(recyclerView, viewHolder)
}
return 0
}
}
ItemTouchHelper(touchCallback).attachToRecyclerView(recycler_view)
}
}
private fun setupFab() {
button_fab.setOnClickListener {
recycler_view.scrollToPosition(0)
verticalScrollOffset.set(0)
text_count.isVisible = false
button_fab.hide()
newMessageCount = 0
}
}
private fun setupMessageComposer(roomUiModel: RoomUiModel) {
if (isReadOnly || !roomUiModel.writable) {
text_room_is_read_only.isVisible = true
input_container.isVisible = false
text_room_is_read_only.setText(
if (isReadOnly) {
R.string.msg_this_room_is_read_only
} else {
// Not a read-only channel but user has been muted.
R.string.msg_muted_on_this_channel
}
)
} else if (!isSubscribed && roomTypeOf(chatRoomType) !is RoomType.DirectMessage) {
input_container.isVisible = false
button_join_chat.isVisible = true
button_join_chat.setOnClickListener { presenter.joinChat(chatRoomId) }
} else {
input_container.isVisible = true
text_room_is_read_only.isVisible = false
button_show_attachment_options.alpha = 1f
activity?.supportFragmentManager?.registerFragmentLifecycleCallbacks(
object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentAttached(
fm: FragmentManager,
f: Fragment,
context: Context
) {
if (f is MessageActionsBottomSheet) {
dismissEmojiKeyboard()
}
}
},
true
)
emojiKeyboardPopup =
EmojiKeyboardPopup(activity!!, activity!!.findViewById(R.id.fragment_container))
emojiKeyboardPopup.listener = this
text_message.listener = object : ComposerEditText.ComposerEditTextListener {
override fun onKeyboardOpened() {
KeyboardHelper.showSoftKeyboard(text_message)
}
override fun onKeyboardClosed() {
activity?.let {
if (!emojiKeyboardPopup.isKeyboardOpen) {
it.onBackPressed()
}
KeyboardHelper.hideSoftKeyboard(it)
dismissEmojiKeyboard()
}
}
}
button_send.setOnClickListener {
text_message.textContent.run {
if(this.isNotBlank()) {
sendMessage((citation ?: "") + this)
}
}
}
button_show_attachment_options.setOnClickListener {
if (layout_message_attachment_options.isShown) {
hideAttachmentOptions()
} else {
showAttachmentOptions()
}
}
view_dim.setOnClickListener {
hideAttachmentOptions()
}
button_add_reaction_or_show_keyboard.setOnClickListener { toggleKeyboard() }
button_take_a_photo.setOnClickListener {
// Check for camera permission
context?.let {
if (hasCameraPermission(it)) {
dispatchTakePictureIntent()
} else {
getCameraPermission(this)
}
}
handler.postDelayed({
hideAttachmentOptions()
}, 400)
}
button_attach_a_file.setOnClickListener {
handler.postDelayed({
presenter.selectFile()
}, 200)
handler.postDelayed({
hideAttachmentOptions()
}, 400)
}
button_drawing.setOnClickListener {
activity?.let { fragmentActivity ->
if (!hasWriteExternalStoragePermission(fragmentActivity)) {
getWriteExternalStoragePermission(this)
} else {
dispatchDrawingIntent()
}
}
handler.postDelayed({
hideAttachmentOptions()
}, 400)
}
}
}
private fun dispatchDrawingIntent() {
val intent = Intent(activity, DrawingActivity::class.java)
startActivityForResult(intent, REQUEST_CODE_FOR_DRAW)
}
private fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Create the File where the photo should go
val photoFile: File? = try {
activity?.createImageFile()
} catch (ex: IOException) {
Timber.e(ex)
null
}
// Continue only if the File was successfully created
photoFile?.also {
takenPhotoUri = FileProvider.getUriForFile(
requireContext(), "chat.rocket.android.fileprovider", it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, takenPhotoUri)
startActivityForResult(takePictureIntent, REQUEST_CODE_FOR_PERFORM_CAMERA)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
AndroidPermissionsHelper.CAMERA_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
dispatchTakePictureIntent()
} else {
// permission denied
Snackbar.make(
root_layout,
R.string.msg_camera_permission_denied,
Snackbar.LENGTH_SHORT
).show()
}
return
}
AndroidPermissionsHelper.WRITE_EXTERNAL_STORAGE_CODE -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
dispatchDrawingIntent()
} else {
// permission denied
Snackbar.make(
root_layout,
R.string.msg_storage_permission_denied,
Snackbar.LENGTH_SHORT
).show()
}
return
}
}
}
private fun getDraftMessage() {
val unfinishedMessage = presenter.getDraftUnfinishedMessage()
if (unfinishedMessage.isNotNullNorEmpty()) {
text_message.setText(unfinishedMessage)
}
}
private fun setupSuggestionsView() {
suggestions_view.anchorTo(text_message)
.setMaximumHeight(resources.getDimensionPixelSize(R.dimen.suggestions_box_max_height))
.addTokenAdapter(PeopleSuggestionsAdapter(context!!))
.addTokenAdapter(CommandSuggestionsAdapter())
.addTokenAdapter(RoomSuggestionsAdapter())
.addTokenAdapter(EmojiSuggestionsAdapter())
.addSuggestionProviderAction("@") { query ->
if (query.isNotEmpty()) {
presenter.spotlight(query, PEOPLE, true)
}
}
.addSuggestionProviderAction("#") { query ->
if (query.isNotEmpty()) {
presenter.loadChatRoomsSuggestions()
}
}
.addSuggestionProviderAction("/") {
presenter.loadCommands()
}
.addSuggestionProviderAction(":") {
presenter.loadEmojis()
}
presenter.loadEmojis()
presenter.loadCommands()
}
// Shows the emoji or the system keyboard.
private fun toggleKeyboard() {
if (!emojiKeyboardPopup.isShowing) {
openEmojiKeyboard()
} else {
// If popup is showing, simply dismiss it to show the underlying text keyboard
dismissEmojiKeyboard()
}
}
private fun setupActionSnackbar() {
actionSnackbar = ActionSnackbar.make(message_list_container, parser = parser)
actionSnackbar.cancelView.setOnClickListener {
clearMessageComposition(false)
if (text_message.textContent.isEmpty()) {
KeyboardHelper.showSoftKeyboard(text_message)
}
}
}
private fun subscribeComposeTextMessage() {
text_message.asObservable().let {
compositeDisposable.addAll(
subscribeComposeButtons(it),
subscribeComposeTypingStatus(it)
)
}
}
private fun unsubscribeComposeTextMessage() {
compositeDisposable.clear()
}
private fun subscribeComposeButtons(observable: Observable<CharSequence>): Disposable {
return observable.subscribe { t -> setupComposeButtons(t) }
}
private fun subscribeComposeTypingStatus(observable: Observable<CharSequence>): Disposable {
return observable.debounce(300, TimeUnit.MILLISECONDS)
.skip(1)
.subscribe { t -> sendTypingStatus(t) }
}
private fun setupComposeButtons(charSequence: CharSequence) {
if (charSequence.isNotEmpty() && playComposeMessageButtonsAnimation) {
button_show_attachment_options.isVisible = false
button_send.isVisible = true
playComposeMessageButtonsAnimation = false
}
if (charSequence.isEmpty()) {
button_send.isVisible = false
button_show_attachment_options.isVisible = true
playComposeMessageButtonsAnimation = true
}
}
private fun sendTypingStatus(charSequence: CharSequence) {
if (charSequence.isNotBlank()) {
presenter.sendTyping()
} else {
presenter.sendNotTyping()
}
}
private fun showAttachmentOptions() {
view_dim.isVisible = true
// Play anim.
button_show_attachment_options.rotateBy(45F)
layout_message_attachment_options.circularRevealOrUnreveal(centerX, centerY, 0F, hypotenuse)
}
private fun hideAttachmentOptions() {
// Play anim.
button_show_attachment_options.rotateBy(-45F)
layout_message_attachment_options.circularRevealOrUnreveal(centerX, centerY, max, 0F)
view_dim.isVisible = false
}
private fun setupToolbar(toolbarTitle: String) {
with(activity as ChatRoomActivity) {
this.clearLightStatusBar()
this.setupToolbarTitle(toolbarTitle)
toolbar.isVisible = true
}
}
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
text_message?.removeCallbacks(what)
}
override fun invalidateDrawable(who: Drawable) {
text_message?.invalidate()
}
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
text_message?.postDelayed(what, `when`)
}
override fun showMessageInfo(id: String) {
presenter.messageInfo(id)
}
override fun citeMessage(
roomName: String,
roomType: String,
messageId: String,
mentionAuthor: Boolean
) {
presenter.citeMessage(roomName, roomType, messageId, mentionAuthor)
}
override fun copyMessage(id: String) {
presenter.copyMessage(id)
}
override fun editMessage(roomId: String, messageId: String, text: String) {
presenter.editMessage(roomId, messageId, text)
}
override fun toggleStar(id: String, star: Boolean) {
if (star) {
presenter.starMessage(id)
} else {
presenter.unstarMessage(id)
}
}
override fun togglePin(id: String, pin: Boolean) {
if (pin) {
presenter.pinMessage(id)
} else {
presenter.unpinMessage(id)
}
}
override fun deleteMessage(roomId: String, id: String) {
ui {
val builder = AlertDialog.Builder(it)
builder.setTitle(it.getString(R.string.msg_delete_message))
.setMessage(it.getString(R.string.msg_delete_description))
.setPositiveButton(it.getString(android.R.string.ok)) { _, _ ->
presenter.deleteMessage(
roomId,
id
)
}
.setNegativeButton(it.getString(android.R.string.cancel)) { _, _ -> }
.show()
}
}
override fun copyPermalink(id: String) {
presenter.copyPermalink(id)
}
override fun showReactions(id: String) {
presenter.showReactions(id)
}
override fun openDirectMessage(roomName: String, message: String) {
presenter.openDirectMessage(roomName, message)
}
override fun sendMessage(chatRoomId: String, text: String) {
presenter.sendMessage(chatRoomId, text, null)
}
override fun reportMessage(id: String) {
presenter.reportMessage(
messageId = id,
description = "This message was reported by a user from the Android app"
)
}
fun openEmojiKeyboard() {
// If keyboard is visible, simply show the popup
if (emojiKeyboardPopup.isKeyboardOpen) {
emojiKeyboardPopup.showAtBottom()
} else {
// Open the text keyboard first and immediately after that show the emoji popup
text_message.isFocusableInTouchMode = true
text_message.requestFocus()
emojiKeyboardPopup.showAtBottomPending()
KeyboardHelper.showSoftKeyboard(text_message)
}
setReactionButtonIcon(R.drawable.ic_keyboard_black_24dp)
}
fun dismissEmojiKeyboard() {
// Check if the keyboard was ever initialized.
// It may be the case when you are looking a not joined room
if (::emojiKeyboardPopup.isInitialized) {
emojiKeyboardPopup.dismiss()
setReactionButtonIcon(R.drawable.ic_reaction_24dp)
}
}
}
| mit | 24fc2a5d2db61514b885abe059b4a25d | 37.319628 | 115 | 0.612787 | 5.162416 | false | false | false | false |
UnderMybrella/Visi | src/main/kotlin/org/abimon/visi/collections/VCollections.kt | 1 | 5974 | package org.abimon.visi.collections
import java.util.*
fun <T, U, V> Map<Pair<T, U>, V>.containsFirstPair(t: T): Boolean = keys.any { pair -> pair.first == t }
fun <T, U, V> Map<Pair<T, U>, V>.getFirstOfPair(t: T): V? {
return get(keys.firstOrNull { pair -> pair.first == t } ?: return null)
}
fun <T, U, V> Map<Pair<T, U>, V>.getSecondPair(t: T): U? {
return (keys.firstOrNull { pair -> pair.first == t } ?: return null).second
}
fun <T, U, V> Map<Pair<T, U>, V>.containsSecondPair(u: U): Boolean = keys.any { pair -> pair.second == u }
fun <T, U, V> Map<Pair<T, U>, V>.getSecondOfPair(u: U): V? {
return get(keys.firstOrNull { pair -> pair.second == u } ?: return null)
}
fun <T, U, V> Map<Pair<T, U>, V>.getFirstPair(u: U): T? {
return (keys.firstOrNull { pair -> pair.second == u } ?: return null).first
}
fun <T, V> Map<Pair<T, T>, V>.contains(t: T): Boolean = keys.any { pair -> pair.first == t || pair.second == t}
fun <T, V> Map<Pair<T, T>, V>.getFirst(t: T): V? {
return get(keys.firstOrNull { pair -> pair.first == t || pair.second == t } ?: return null)
}
fun <T, V> Map<Pair<T, T>, V>.getPair(t: T): Pair<T, T>? {
return (keys.firstOrNull { pair -> pair.first == t || pair.second == t } ?: return null)
}
fun <T, V> Map<Pair<T, T>, V>.getOther(t: T): T? {
return (keys.firstOrNull { pair -> pair.first == t } ?: return (keys.firstOrNull { pair -> pair.second == t } ?: return null).first).second
}
fun <T, V> Map<T, V>.getForValue(v: V): T? = keys.filter { key -> get(key) == v }.firstOrNull()
fun <T> List<T>.shuffle(): List<T> {
val list = ArrayList<T>()
val copyList = ArrayList<T>(this)
val rng = Random()
while(copyList.size > 0)
list.add(copyList.removeAt(rng.nextInt(copyList.size)))
return list
}
fun <T> List<T>.random(rng: Random = Random()): T = get(rng.nextInt(size))
fun <T> Array<T>.random(rng: Random = Random()): T = get(rng.nextInt(size))
fun <T> MutableList<T>.remove(predicate: (T) -> Boolean): T? {
val index = indexOfFirst(predicate)
if(index == -1)
return null
return removeAt(index)
}
fun <T> MutableList<T>.tryRemove(predicate: (T) -> Boolean): Optional<T> = Optional.ofNullable(remove(predicate))
fun <T, E: MutableCollection<T>> E.addAllReturning(collection: Collection<T>): E {
addAll(collection)
return this
}
fun <T, E: MutableCollection<T>> E.addAll(num: Int, adding: (Int) -> T): Boolean {
var added = false
for(i in 0 until num)
added = add(adding(i))
return added
}
fun <K, V> HashMap<K, V>.flush(): HashMap<K, V> {
val copy = HashMap(this)
this.clear()
return copy
}
fun <T> List<T>.random(): T = this[Random().nextInt(size)]
fun <T> Iterable<T>.coerceAtMost(size: Int): List<T> {
val list = ArrayList<T>()
for(element in this) {
list.add(element)
if(list.size >= size)
break
}
return list
}
fun <T> List<T>.equalsBy(equalCheck: (Int, T) -> Boolean): Boolean {
return indices.all { equalCheck(it, get(it)) }
}
inline fun <reified T> Iterable<T>.segment(sizes: Int): List<Array<T>> {
val list = ArrayList<Array<T>>()
val segment = ArrayList<T>()
for(element in this) {
segment.add(element)
if(segment.size >= sizes) {
list.add(segment.toTypedArray())
segment.clear()
}
}
return list
}
fun <T> Iterable<T>.pass(passing: (T, T) -> T): T {
val list = this.toList()
var t: T = list.first()
for(i in (1 until list.size))
t = passing(t, list[i])
return t
}
fun <T> Collection<T>.joinToPrefixedString(separator: String, elementPrefix: String = "", elementSuffix: String = "", transform: T.() -> String = { this.toString() }) = joinToString(separator) { element -> "$elementPrefix${element.transform()}$elementSuffix"}
fun ByteArray.toArrayString(): String = Arrays.toString(this)
fun BooleanArray.toArrayString(): String = Arrays.toString(this)
fun Array<*>.toArrayString(): String = Arrays.toString(this)
fun IntArray.copyFrom(index: Int): IntArray = copyOfRange(index, size)
fun <T> Array<T>.copyFrom(index: Int): Array<T> = copyOfRange(index, size)
fun <T> List<T>.toSequentialString(separator: String = ", ", finalSeparator: String = ", and ", transform: T.() -> String = { this.toString() }): String {
if(size == 0)
return ""
else if(size == 1)
return this[0].transform()
else if(size == 2)
return this[0].transform() + finalSeparator + this[1].transform()
var str = ""
for(i in 0 until size - 2)
str += this[i].transform() + separator
str += this[size - 2].transform() + finalSeparator
str += this[size - 1].transform()
return str
}
fun <T> Array<T>.toSequentialString(separator: String = ", ", finalSeparator: String = ", and ", transform: T.() -> String = { this.toString() }): String {
if(size == 0)
return ""
else if(size == 1)
return this[0].transform()
else if(size == 2)
return this[0].transform() + finalSeparator + this[1].transform()
var str = ""
for(i in 0 until size - 2)
str += this[i].transform() + separator
str += this[size - 2].transform() + finalSeparator
str += this[size - 1].transform()
return str
}
infix fun ByteArray.asBase(base: Int): String = this.joinToString(" ") { byte ->
when(base) {
2 -> "0b${byte.toString(2)}"
16 -> "0x${byte.toString(16)}"
else -> byte.toString(base)
}
}
infix fun IntArray.asBase(base: Int): String = this.joinToString(" ") { byte ->
when(base) {
2 -> "0b${byte.toString(2)}"
16 -> "0x${byte.toString(16)}"
else -> byte.toString(base)
}
}
operator fun <K, V> Map<K, V>.get(v: V): K? = getByValue(v)
fun <K, V> Map<K, V>.getByValue(v: V): K? = entries.firstOrNull { (_, value) -> value == v }?.key
operator fun <T> List<T>.get(index: Int, default: T): T = if(index < size) this[index] else default | mit | a2272c5fdc43476abbb557d2aac63075 | 33.142857 | 259 | 0.60077 | 3.139254 | false | false | false | false |
BenoitDuffez/AndroidCupsPrint | app/src/main/java/org/cups4j/operations/ipp/IppHoldJobOperation.kt | 1 | 2745 | package org.cups4j.operations.ipp
/**
* Copyright (C) 2011 Harald Weyhing
*
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*
* See the GNU Lesser General Public License for more details. You should have received a copy of
* the GNU Lesser General Public License along with this program; if not, see
* <http:></http:>//www.gnu.org/licenses/>.
*/
/*Notice
* This file has been modified. It is not the original.
* Jon Freeman - 2013
*/
import android.content.Context
import ch.ethz.vppserver.ippclient.IppTag
import org.cups4j.CupsClient
import org.cups4j.PrintRequestResult
import org.cups4j.operations.IppOperation
import java.io.UnsupportedEncodingException
import java.net.URL
import java.nio.ByteBuffer
import java.util.HashMap
class IppHoldJobOperation(context: Context) : IppOperation(context) {
init {
operationID = 0x000C
bufferSize = 8192
}
@Throws(UnsupportedEncodingException::class)
override fun getIppHeader(url: URL, map: Map<String, String>?): ByteBuffer {
var ippBuf = ByteBuffer.allocateDirect(bufferSize.toInt())
ippBuf = IppTag.getOperation(ippBuf, operationID)
// ippBuf = IppTag.getUri(ippBuf, "job-uri", stripPortNumber(url));
if (map == null) {
ippBuf = IppTag.getEnd(ippBuf)
ippBuf.flip()
return ippBuf
}
map["job-id"]?.let {
ippBuf = IppTag.getUri(ippBuf, "printer-uri", stripPortNumber(url))
ippBuf = IppTag.getInteger(ippBuf, "job-id", it.toInt())
} ?: run {
ippBuf = IppTag.getUri(ippBuf, "job-uri", stripPortNumber(url))
}
ippBuf = IppTag.getNameWithoutLanguage(ippBuf, "requesting-user-name", map["requesting-user-name"])
ippBuf = IppTag.getEnd(ippBuf)
ippBuf.flip()
return ippBuf
}
@Throws(Exception::class)
fun holdJob(url: URL, userName: String?, jobID: Int): Boolean {
val requestUrl = URL(url.toString() + "/jobs/" + Integer.toString(jobID))
val map = HashMap<String, String>()
map["requesting-user-name"] = userName?:CupsClient.DEFAULT_USER
map["job-uri"] = requestUrl.toString()
val result = request(requestUrl, map)
// IppResultPrinter.print(result);
return PrintRequestResult(result).isSuccessfulResult
}
}
| lgpl-3.0 | b105db202178b5fddbe7107db632e614 | 34.649351 | 107 | 0.679053 | 3.833799 | false | false | false | false |
AndroidX/constraintlayout | projects/ComposeConstraintLayout/dsl-verification/src/androidTest/java/com/example/dsl_verification/VerificationUtils.kt | 2 | 2849 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dsl_verification
import junit.framework.TestCase
import org.junit.Assert.assertEquals
internal fun parseBaselineResults(rawString: String): MutableMap<String, String> {
return rawString.split(";").mapNotNull {
val nameValue = it.takeIf { it.isNotBlank() }?.trimIndent()?.split("=")
if (nameValue?.size == 2) {
Pair(nameValue[0], nameValue[1])
} else {
null
}
}.toMap(mutableMapOf())
}
internal fun checkTest(
baselineRaw: String,
results: Map<String, String>
) {
var failed = false
var failedCount = 0
val baselineResults = parseBaselineResults(baselineRaw)
for (result in results) {
if (baselineResults.contains(result.key)) {
if (baselineResults[result.key] != result.value) {
println("----------")
println("Error in Composable: ${result.key}")
println("Expected: ${baselineResults[result.key]}")
println("Was: ${result.value}")
println("----------")
failed = true
failedCount++
}
baselineResults.remove(result.key)
} else {
println("----------")
println("New Composable Result: ${result.key}")
println("----------")
failed = true
failedCount++
}
}
for (baseline in baselineResults) {
println("----------")
println("Missing result for: ${baseline.key}")
println("----------")
failed = true
failedCount++
}
if (failed) {
println("----------")
println("$failedCount Composables failed")
println("New Baseline:")
val newResults = results.map { "${it.key}=${it.value}" }.joinToString(";\n")
// TODO: Find a better way to output the result, so that it's easy to update the
// baseline (results.txt), alternatively, reduce the amount of text in the file
// You can update results.txt by placing a breakpoint here in debugging mode and copying
// the contents of 'base' into the file.
assertEquals(baselineRaw, newResults)
println("----------")
}
} | apache-2.0 | 4fc743bba7863484d71d92e519a6384e | 34.625 | 96 | 0.59284 | 4.565705 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/bean/Mv.kt | 1 | 1747 | package tech.summerly.quiet.bean
import android.os.Parcel
import android.os.Parcelable
import tech.summerly.quiet.extensions.CacheHelper
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/9/8
* desc :
*/
data class Mv(
val id: Long,
val urlList: ArrayList<Pair<String, String>>, //Url匹配规则 Pair<清晰度,播放地址>
val duration: Long,
val title: String
) : Parcelable, CacheHelper.CacheAble {
var currentPlayIndex = 0
set(value) {
if (value < 0 || value >= urlList.size) {
throw ArrayIndexOutOfBoundsException("Array playIndex out of range: $value , must in 0..${urlList.size}")
}
field = value
}
suspend fun url(bitrate: Int): String {
return urlList[currentPlayIndex].second
}
override fun cachedName(): String {
return "${id}_${urlList[currentPlayIndex].first}.mp4"
}
constructor(source: Parcel) : this(
source.readLong(),
ArrayList<Pair<String, String>>().apply { source.readList(this, Pair::class.java.classLoader) },
source.readLong(),
source.readString()
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeLong(id)
writeList(urlList)
writeLong(duration)
writeString(title)
}
companion object {
@Suppress("unused")
@JvmField
val CREATOR: Parcelable.Creator<Mv> = object : Parcelable.Creator<Mv> {
override fun createFromParcel(source: Parcel): Mv = Mv(source)
override fun newArray(size: Int): Array<Mv?> = arrayOfNulls(size)
}
}
}
| gpl-2.0 | 69d9658fda3e924c4af1624bafc6cf34 | 27.75 | 121 | 0.606377 | 4.146635 | false | false | false | false |
FWDekker/intellij-randomness | src/test/kotlin/com/fwdekker/randomness/Dummies.kt | 1 | 4403 | package com.fwdekker.randomness
import com.fwdekker.randomness.array.ArrayDecorator
import com.fwdekker.randomness.array.ArrayDecoratorEditor
import com.fwdekker.randomness.ui.addChangeListenerTo
import java.awt.BorderLayout
import java.awt.Color
import javax.swing.JPanel
import javax.swing.JTextField
import kotlin.random.Random
/**
* Dummy implementation of [Scheme].
*
* @property literals The outputs to cyclically produce.
* @property decorators Settings that determine whether the output should be decorated.
*/
data class DummyScheme(
var literals: List<String> = listOf(DEFAULT_OUTPUT),
override var decorators: List<SchemeDecorator> = listOf(ArrayDecorator())
) : Scheme() {
override var typeIcon: TypeIcon? = TypeIcon(RandomnessIcons.SCHEME, "dum", listOf(Color.GRAY))
override val name: String
get() = literals.joinToString()
/**
* Returns the single [ArrayDecorator] in [decorators].
*
* Use this field only if the test assumes that this scheme has a single decorator the entire time.
*/
var arrayDecorator: ArrayDecorator
get() = decorators.single() as ArrayDecorator
set(value) {
decorators = listOf(value)
}
override fun generateUndecoratedStrings(count: Int) = List(count) { literals[it % literals.size] }
override fun doValidate() =
if (literals[0] == INVALID_OUTPUT) "Invalid input!"
else decorators.firstNotNullOfOrNull { it.doValidate() }
override fun deepCopy(retainUuid: Boolean) =
copy(decorators = decorators.map { it.deepCopy(retainUuid) })
.also { if (retainUuid) it.uuid = this.uuid }
/**
* Holds constants.
*/
companion object {
/**
* The default singular value contained in [literals].
*/
const val DEFAULT_OUTPUT = "literal"
/**
* The magic string contained in [literals] to make the scheme invalid according to [doValidate].
*/
const val INVALID_OUTPUT = "invalid"
/**
* Convenience method for creating a [DummyScheme] using vararg notation.
*
* @param literals the literals for the dummy scheme
* @return a [DummyScheme] with [literals]
*/
fun from(vararg literals: String) = DummyScheme(literals = literals.toList())
}
}
/**
* Dummy implementation of [StateEditor] for a [DummyScheme].
*
* Dummy schemes have a producer, but this editor only supports returning a producer of a single string.
*
* @param scheme the scheme to edit in the component
*/
class DummySchemeEditor(scheme: DummyScheme = DummyScheme()) : StateEditor<DummyScheme>(scheme) {
override val rootComponent = JPanel(BorderLayout())
private val literalsInput = JTextField()
.also { it.name = "literals" }
.also { rootComponent.add(it, BorderLayout.NORTH) }
private val arrayDecoratorEditor = ArrayDecoratorEditor(originalState.arrayDecorator)
.also { rootComponent.add(it.rootComponent, BorderLayout.SOUTH) }
init {
loadState()
}
override fun loadState(state: DummyScheme) {
super.loadState(state)
literalsInput.text = state.literals.joinToString(separator = ",")
arrayDecoratorEditor.loadState(state.arrayDecorator)
}
override fun readState() =
DummyScheme(
literals = literalsInput.text.split(','),
decorators = listOf(arrayDecoratorEditor.readState())
)
override fun addChangeListener(listener: () -> Unit) {
addChangeListenerTo(literalsInput, listener = listener)
arrayDecoratorEditor.addChangeListener(listener)
}
}
/**
* Dummy implementation of [SettingsConfigurable].
*/
class DummySettingsConfigurable : SettingsConfigurable() {
override fun getDisplayName() = "Dummy"
override fun createEditor() = DummySchemeEditor()
}
/**
* Inserts a dummy value.
*
* Mostly for testing and demonstration purposes.
*
* @param repeat `true` if and only if the same value should be inserted at each caret
* @property dummySupplier Generates dummy values to insert.
*/
class DummyInsertAction(repeat: Boolean = false, private val dummySupplier: (Random) -> String) :
InsertAction(repeat, "Random Dummy", null, null) {
override fun generateStrings(count: Int) = List(count) { dummySupplier(Random.Default) }
}
| mit | 2a2d67a5db3c9b4c3eab614b2b51a119 | 30.676259 | 105 | 0.682716 | 4.539175 | false | false | false | false |
ethauvin/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/ParallelLogger.kt | 2 | 4356 | package com.beust.kobalt.internal
import com.beust.kobalt.Args
import com.beust.kobalt.KobaltException
import com.beust.kobalt.misc.*
import com.google.inject.Inject
import com.google.inject.Singleton
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedQueue
interface ILogger {
fun log(tag: CharSequence, level: Int, message: CharSequence, newLine: Boolean = true)
}
/**
* This class manages logs for parallel builds. These logs come from multiple projects interwoven as
* they are being scheduled on different threads. This class maintains a "current" project which has
* its logs always displayed instantaneously while logs from other projects are being stored for later display.
* Once the current project is done, this class will catch up all the finished project logs and then
* pick the next current project to be displayed live.
*
* Yes, this code was pretty painful to write and I'm pretty sure it can be made less ugly.
*/
@Singleton
class ParallelLogger @Inject constructor(val args: Args) : ILogger {
enum class Type { LOG, WARN, ERROR }
class LogLine(val name: CharSequence? = null, val level: Int, val message: CharSequence, val type: Type,
val newLine: Boolean)
private val logLines = ConcurrentHashMap<CharSequence, ArrayList<LogLine>>()
private val runningProjects = ConcurrentLinkedQueue<String>()
var startTime: Long? = null
fun onProjectStarted(name: String) {
if (startTime == null) {
startTime = System.currentTimeMillis()
}
runningProjects.add(name)
logLines[name] = arrayListOf()
if (currentName == null) {
currentName = name
}
}
val stoppedProjects = ConcurrentHashMap<String, String>()
fun onProjectStopped(name: String) {
debug("onProjectStopped($name)")
stoppedProjects[name] = name
if (name == currentName && runningProjects.any()) {
emptyProjectLog(name)
var nextProject = runningProjects.peek()
while (nextProject != null && stoppedProjects.containsKey(nextProject)) {
val sp = runningProjects.remove()
emptyProjectLog(sp)
nextProject = runningProjects.peek()
}
currentName = nextProject
} else {
debug("Non current project $name stopping, not doing anything")
}
}
private fun debug(s: CharSequence) {
if (args.log >= 3) {
val time = System.currentTimeMillis() - startTime!!
kobaltLog(1, " ### [$time] $s")
}
}
val LOCK = Any()
var currentName: String? = null
set(newName) {
field = newName
}
private fun displayLine(ll: LogLine) {
val time = System.currentTimeMillis() - startTime!!
val m = (if (args.dev) "### [$time] " else "") + ll.message
when(ll.type) {
Type.LOG -> kobaltLog(ll.level, m, ll.newLine)
Type.WARN -> kobaltWarn(m)
Type.ERROR -> kobaltError(m)
}
}
private fun emptyProjectLog(name: CharSequence?) {
val lines = logLines[name]
if (lines != null && lines.any()) {
debug("emptyProjectLog($name)")
lines.forEach {
displayLine(it)
}
lines.clear()
debug("Done emptyProjectLog($name)")
// logLines.remove(name)
} else if (lines == null) {
throw KobaltException("Didn't call onStartProject() for $name")
}
}
private fun addLogLine(name: CharSequence, ll: LogLine) {
if (name != currentName) {
val list = logLines[name] ?: arrayListOf()
logLines[name] = list
list.add(ll)
} else {
emptyProjectLog(name)
displayLine(ll)
}
}
override fun log(tag: CharSequence, level: Int, message: CharSequence, newLine: Boolean) {
if (args.sequential) {
kobaltLog(level, message, newLine)
} else {
addLogLine(tag, LogLine(tag, level, message, Type.LOG, newLine))
}
}
fun shutdown() {
runningProjects.forEach {
emptyProjectLog(it)
}
kobaltLog(1, "")
}
}
| apache-2.0 | 722457e8a6bd38998b907d703cb9a0f0 | 32.507692 | 111 | 0.606749 | 4.5 | false | false | false | false |
uber/AutoDispose | static-analysis/autodispose-lint/src/main/kotlin/autodispose2/lint/AutoDisposeDetector.kt | 1 | 19417 | /*
* Copyright (C) 2019. Uber Technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package autodispose2.lint
import com.android.tools.lint.client.api.JavaEvaluator
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Context
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.UImplicitCallExpression
import com.android.tools.lint.detector.api.isJava
import com.android.tools.lint.detector.api.isKotlin
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiSynchronizedStatement
import com.intellij.psi.PsiType
import com.intellij.psi.util.PsiUtil
import org.jetbrains.uast.UAnnotationMethod
import org.jetbrains.uast.UBlockExpression
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UCallableReferenceExpression
import org.jetbrains.uast.UClassInitializer
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.UIfExpression
import org.jetbrains.uast.ULambdaExpression
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UParenthesizedExpression
import org.jetbrains.uast.UQualifiedReferenceExpression
import org.jetbrains.uast.USwitchClauseExpressionWithBody
import org.jetbrains.uast.USwitchExpression
import org.jetbrains.uast.UYieldExpression
import org.jetbrains.uast.getContainingUClass
import org.jetbrains.uast.getParentOfType
import org.jetbrains.uast.skipParenthesizedExprUp
import org.jetbrains.uast.visitor.AbstractUastVisitor
import java.io.StringReader
import java.util.EnumSet
import java.util.Properties
internal const val CUSTOM_SCOPE_KEY = "autodispose.typesWithScope"
internal const val LENIENT = "autodispose.lenient"
internal const val OVERRIDE_SCOPES = "autodispose.overrideScopes"
internal const val KOTLIN_EXTENSION_FUNCTIONS = "autodispose.kotlinExtensionFunctions"
/**
* Detector which checks if your stream subscriptions are handled by AutoDispose.
*/
public class AutoDisposeDetector : Detector(), SourceCodeScanner {
internal companion object {
internal const val LINT_DESCRIPTION = "Missing Disposable handling: Apply AutoDispose or cache " +
"the Disposable instance manually and enable lenient mode."
internal val ISSUE: Issue = Issue.create(
"AutoDispose",
LINT_DESCRIPTION,
"You're subscribing to an observable but not handling its subscription. This " +
"can result in memory leaks. You can avoid memory leaks by appending " +
"`.as(autoDisposable(this))` before you subscribe or cache the Disposable instance" +
" manually and enable lenient mode. More: https://github.com/uber/AutoDispose/wiki/Lint-Check",
Category.CORRECTNESS,
10,
Severity.ERROR,
// We use the overloaded constructor that takes a varargs of `Scope` as the last param.
// This is to enable on-the-fly IDE checks. We are telling lint to run on both
// JAVA and TEST_SOURCES in the `scope` parameter but by providing the `analysisScopes`
// params, we're indicating that this check can run on either JAVA or TEST_SOURCES and
// doesn't require both of them together.
// From discussion on lint-dev https://groups.google.com/d/msg/lint-dev/ULQMzW1ZlP0/1dG4Vj3-AQAJ
// TODO: This was supposed to be fixed in AS 3.4 but still required as recently as 3.6-alpha10.
Implementation(
AutoDisposeDetector::class.java,
EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES),
EnumSet.of(Scope.JAVA_FILE),
EnumSet.of(Scope.TEST_SOURCES)
)
)
private const val OBSERVABLE = "io.reactivex.rxjava3.core.Observable"
private const val FLOWABLE = "io.reactivex.rxjava3.core.Flowable"
private const val PARALLEL_FLOWABLE = "io.reactivex.rxjava3.core.parallel.ParallelFlowable"
private const val SINGLE = "io.reactivex.rxjava3.core.Single"
private const val MAYBE = "io.reactivex.rxjava3.core.Maybe"
private const val COMPLETABLE = "io.reactivex.rxjava3.core.Completable"
private const val KOTLIN_EXTENSIONS = "autodispose2.KotlinExtensions"
// The default scopes for Android.
private val DEFAULT_SCOPES = setOf(
"androidx.lifecycle.LifecycleOwner",
"autodispose2.ScopeProvider",
"android.app.Activity",
"android.app.Fragment"
)
private val REACTIVE_TYPES = setOf(
OBSERVABLE, FLOWABLE, PARALLEL_FLOWABLE, SINGLE, MAYBE,
COMPLETABLE
)
private val REACTIVE_SUBSCRIBE_METHOD_NAMES = setOf("subscribe", "subscribeWith")
internal const val PROPERTY_FILE = "gradle.properties"
}
// The scopes that are applicable for the lint check.
// This includes the DEFAULT_SCOPES as well as any custom scopes
// defined by the consumer.
private var appliedScopes: Set<String> = DEFAULT_SCOPES
private var ktExtensionMethodToPackageMap: Map<String, Set<String>> = emptyMap()
private var appliedMethodNames: List<String> = REACTIVE_SUBSCRIBE_METHOD_NAMES.toList()
private var lenient: Boolean = false
override fun beforeCheckRootProject(context: Context) {
var overrideScopes = false
val scopes = mutableSetOf<String>()
val ktExtensionMethodToPackageMap = mutableMapOf<String, MutableSet<String>>()
// Add the custom scopes defined in configuration.
val props = Properties()
context.project.propertyFiles.find { it.name == PROPERTY_FILE }?.apply {
val content = StringReader(context.client.readFile(this).toString())
props.load(content)
props.getProperty(CUSTOM_SCOPE_KEY)?.let { scopeProperty ->
val customScopes = scopeProperty.split(",")
.asSequence()
.map(String::trim)
.filter(String::isNotBlank)
.toList()
scopes.addAll(customScopes)
}
props.getProperty(KOTLIN_EXTENSION_FUNCTIONS)?.let { ktExtensionProperty ->
ktExtensionProperty.split(",")
.forEach {
val arr = it.split("#", limit = 2)
if (arr.size >= 2) {
val (packageName, methodName) = arr
ktExtensionMethodToPackageMap.getOrPut(methodName, ::mutableSetOf).add(packageName)
}
}
}
props.getProperty(LENIENT)?.toBoolean()?.let {
lenient = it
}
props.getProperty(OVERRIDE_SCOPES)?.toBoolean()?.let {
overrideScopes = it
}
}
// If scopes are not overridden, add the default ones.
if (!overrideScopes) {
scopes.addAll(DEFAULT_SCOPES)
}
this.appliedScopes = scopes
this.ktExtensionMethodToPackageMap = ktExtensionMethodToPackageMap
this.appliedMethodNames = (REACTIVE_SUBSCRIBE_METHOD_NAMES + ktExtensionMethodToPackageMap.keys).toList()
}
override fun getApplicableMethodNames(): List<String> = appliedMethodNames
override fun createUastHandler(context: JavaContext): UElementHandler {
return object : UElementHandler() {
override fun visitCallableReferenceExpression(node: UCallableReferenceExpression) {
node.resolve()?.let { method ->
if (method is PsiMethod) {
callableReferenceChecker(context, node, method, ::containingClassScopeChecker)
}
}
}
override fun visitCallExpression(node: UCallExpression) {
node.resolve()?.let { method ->
// Check if it's one of our withScope() higher order functions. If so, we handle that
// separately and visit the passed in lambda body and run the subscribe method call checks
// inside it with the "isInScope" check just hardcoded to true.
if (method.name == "withScope" &&
method.containingClass?.qualifiedName == KOTLIN_EXTENSIONS
) {
val args = node.valueArguments
if (args.size == 2) {
val last = args[1]
// Check the lambda type too because it's a cheaper instance check
if (last is ULambdaExpression) {
// This is the AutoDisposeContext.() call
// TODO we can't determine this exactly with lint as far as I can tell
val body = last.body
val visitor = SubscribeCallVisitor(
context,
callExpressionChecker = { context, node, calledMethod ->
callExpressionChecker(context, node, calledMethod) { _, _ -> true }
},
callableReferenceChecker = { context, node, calledMethod ->
callableReferenceChecker(context, node, calledMethod) { _, _ -> true }
}
)
body.accept(visitor)
return@let
}
}
}
callExpressionChecker(context, node, method, ::containingClassScopeChecker)
}
}
}
}
private fun callExpressionChecker(
context: JavaContext,
node: UCallExpression,
method: PsiMethod,
isInScope: (JavaEvaluator, UCallExpression) -> Boolean
) {
evaluateMethodCall(node, method, context, isInScope)
}
private fun callableReferenceChecker(
context: JavaContext,
node: UCallableReferenceExpression,
method: PsiMethod,
isInScope: (JavaEvaluator, UCallExpression) -> Boolean
) {
// Check if the resolved call reference is method and check that it's invocation is a
// call expression so that we can get it's return type etc.
if (node.uastParent != null && node.uastParent is UCallExpression) {
evaluateMethodCall(node.uastParent as UCallExpression, method, context, isInScope)
}
}
private class SubscribeCallVisitor(
private val context: JavaContext,
private val callExpressionChecker: (JavaContext, UCallExpression, PsiMethod) -> Unit,
private val callableReferenceChecker: (JavaContext, UCallableReferenceExpression, PsiMethod) -> Unit
) : AbstractUastVisitor() {
override fun visitCallExpression(node: UCallExpression): Boolean {
node.resolve()?.let { callExpressionChecker(context, node, it) }
return super.visitCallExpression(node)
}
override fun afterVisitCallableReferenceExpression(node: UCallableReferenceExpression) {
node.resolve()?.let {
if (it is PsiMethod) {
callableReferenceChecker(context, node, it)
}
}
super.afterVisitCallableReferenceExpression(node)
}
}
override fun getApplicableUastTypes(): List<Class<out UElement>> =
listOf(UCallExpression::class.java, UCallableReferenceExpression::class.java)
/**
* Checks if the calling method is in "scope" that can be handled by AutoDispose.
*
* If your `subscribe`/`subscribeWith` method is called in a scope
* that is recognized by AutoDispose, this returns true. This indicates that
* you're subscribing in a scope and therefore, you must handle the subscription.
* Default scopes include Android activities, fragments and custom classes that
* implement ScopeProvider.
*
* @param evaluator the java evaluator.
* @param node the call expression.
* @return whether the `subscribe` method is called "in-scope".
* @see appliedScopes
*/
private fun containingClassScopeChecker(evaluator: JavaEvaluator, node: UCallExpression): Boolean {
node.getContainingUClass()?.let { callingClass ->
return appliedScopes.any {
evaluator.inheritsFrom(callingClass, it, false)
}
}
return false
}
private fun isReactiveType(evaluator: JavaEvaluator, method: PsiMethod): Boolean {
return REACTIVE_SUBSCRIBE_METHOD_NAMES.contains(method.name) && REACTIVE_TYPES.any {
evaluator.isMemberInClass(method, it)
}
}
private fun isKotlinExtension(evaluator: JavaEvaluator, method: PsiMethod): Boolean {
return ktExtensionMethodToPackageMap[method.name]?.any {
evaluator.isMemberInClass(method, it)
} ?: false
}
/**
* Returns whether the given [returnType] is allowed to bypass the lint check.
*
* If a `subscribe`/`subscribeWith` method return type is captured by the consumer
* AND the return type implements Disposable, we let it bypass the lint check.
* For example, subscribing with a plain Observer instead of a DiposableObserver will
* not bypass the lint check since Observer doesn't extend Disposable.
*
* @param returnType the return type of the `subscribe`/`subscribeWith` call.
* @param evaluator the evaluator.
* @return whether the return type is allowed to bypass the lint check.
*/
private fun isCapturedTypeAllowed(returnType: PsiType?, evaluator: JavaEvaluator): Boolean {
PsiUtil.resolveClassInType(returnType)?.let {
return evaluator.inheritsFrom(it, "io.reactivex.rxjava3.disposables.Disposable", false)
}
return false
}
/**
* Evaluates the given [method] and it's expression.
*
* @param node the node which calls the method.
* @param method the method representation.
* @param context project context.
*/
private fun evaluateMethodCall(
node: UCallExpression,
method: PsiMethod,
context: JavaContext,
isInScope: (JavaEvaluator, UCallExpression) -> Boolean
) {
if (!getApplicableMethodNames().contains(method.name)) return
val evaluator = context.evaluator
val shouldReport = (isReactiveType(evaluator, method) || isKotlinExtension(evaluator, method)) &&
isInScope(evaluator, node)
if (shouldReport) {
if (!lenient) {
context.report(ISSUE, node, context.getLocation(node), LINT_DESCRIPTION)
} else {
val isUnusedReturnValue = isExpressionValueUnused(node)
if (isUnusedReturnValue || !isCapturedTypeAllowed(node.returnType, evaluator)) {
// The subscribe return type isn't handled by consumer or the returned type
// doesn't implement Disposable.
context.report(ISSUE, node, context.getLocation(node), LINT_DESCRIPTION)
}
}
}
}
/**
* Checks whether the given expression's return value is unused.
*
* Borrowed from https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/CheckResultDetector.kt;l=289;drc=c5fd7e6e7dd92bf3c57c6fe7a3a3a3ab61f4aec6
*
* @param element the element to be analyzed.
* @return whether the expression is unused.
*/
private fun isExpressionValueUnused(element: UElement): Boolean {
if (element is UParenthesizedExpression) {
return isExpressionValueUnused(element.expression)
}
var prev: UElement = element.getParentOfType(UExpression::class.java, false) ?: return true
if (prev is UImplicitCallExpression) {
// Wrapped overloaded operator call: we need to point to the original element
// such that the identity check below (for example in the UIfExpression handling)
// recognizes it.
prev = prev.expression
}
var curr: UElement = prev.uastParent ?: return true
while (curr is UQualifiedReferenceExpression && curr.selector === prev || curr is UParenthesizedExpression) {
prev = curr
curr = curr.uastParent ?: return true
}
@Suppress("RedundantIf")
if (curr is UBlockExpression) {
if (curr.sourcePsi is PsiSynchronizedStatement) {
return false
}
// In Java, it's apparent when an expression is unused:
// the parent is a block expression. However, in Kotlin it's
// much trickier: values can flow through blocks and up through
// if statements, try statements.
//
// In Kotlin, we consider an expression unused if its parent
// is not a block, OR, the expression is not the last statement
// in the block, OR, recursively the parent expression is not
// used (e.g. you're in an if, but that if statement is itself
// not doing anything with the value.)
val block = curr
val expression = prev
val index = block.expressions.indexOf(expression)
if (index == -1) {
return true
}
if (index < block.expressions.size - 1) {
// Not last child
return true
}
// It's the last child: see if the parent is unused
val parent = skipParenthesizedExprUp(curr.uastParent)
if (parent is ULambdaExpression && isKotlin(curr.sourcePsi)) {
val expressionType = parent.getExpressionType()?.canonicalText
if (expressionType != null &&
expressionType.startsWith("kotlin.jvm.functions.Function") &&
expressionType.endsWith("kotlin.Unit>")
) {
// We know that this lambda does not return anything so the value is unused
return true
}
// Lambda block: for now assume used (e.g. parameter
// in call. Later consider recursing here to
// detect if the lambda itself is unused.
return false
}
if (isJava(curr.sourcePsi)) {
// In Java there's no implicit passing to the parent
return true
}
// It's the last child: see if the parent is unused
parent ?: return true
if (parent is UMethod || parent is UClassInitializer) {
return true
}
return isExpressionValueUnused(parent)
} else if (curr is UMethod && curr.isConstructor) {
return true
} else if (curr is UIfExpression) {
if (curr.condition === prev) {
return false
} else if (curr.isTernary) {
// Ternary expressions can only be used as expressions, not statements,
// so we know that the value is used
return false
}
val parent = skipParenthesizedExprUp(curr.uastParent) ?: return true
if (parent is UMethod || parent is UClassInitializer) {
return true
}
return isExpressionValueUnused(curr)
} else if (curr is UMethod || curr is UClassInitializer) {
if (curr is UAnnotationMethod) {
return false
}
return true
} else {
@Suppress("UnstableApiUsage")
if (curr is UYieldExpression) {
val p2 = skipParenthesizedExprUp((skipParenthesizedExprUp(curr.uastParent))?.uastParent)
val body = p2 as? USwitchClauseExpressionWithBody ?: return false
val switch = body.getParentOfType(USwitchExpression::class.java) ?: return true
return isExpressionValueUnused(switch)
}
// Some other non block node type, such as assignment,
// method declaration etc: not unused
// TODO: Make sure that a void/unit method inline declaration
// works correctly
return false
}
}
}
| apache-2.0 | 819b6d01b409e6ad81347b712c23d7e6 | 39.792017 | 242 | 0.694804 | 4.604458 | false | false | false | false |
gdgplzen/gugorg-android | app/src/main/java/cz/jacktech/gugorganizer/storage/Settings.kt | 1 | 850 | package cz.jacktech.gugorganizer.storage
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import cz.jacktech.gugorganizer.core.App
import cz.jacktech.gugorganizer.data.User
/**
* Created by toor on 12.8.15.
*/
public object Settings {
private val CONF_USER = "user"
private var sPrefs: SharedPreferences? = null
public fun getUser(): User? {
val json = prefs().getString(CONF_USER, null)
return if (json == null) null else User.fromJson(json)
}
public fun setUser(user: User?) {
prefs().edit().putString(CONF_USER, user?.toJson()).apply()
}
private fun prefs(): SharedPreferences {
if (sPrefs == null)
sPrefs = PreferenceManager.getDefaultSharedPreferences(App.get())
return sPrefs!!
}
}
| gpl-2.0 | cb27848996352c3d6021f4e0da5d47b7 | 24 | 77 | 0.682353 | 4.009434 | false | false | false | false |
etesync/android | app/src/main/java/com/etesync/syncadapter/AccountSettings.kt | 1 | 9736 | /*
* Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter
import android.accounts.Account
import android.accounts.AccountManager
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.BroadcastReceiver
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import at.bitfire.vcard4android.ContactsStorageException
import at.bitfire.vcard4android.GroupMethod
import com.etesync.journalmanager.Crypto
import com.etesync.syncadapter.log.Logger
import com.etesync.syncadapter.utils.Base64
import java.net.URI
import java.net.URISyntaxException
import java.util.logging.Level
class AccountSettings @TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Throws(InvalidAccountException::class)
constructor(internal val context: Context, internal val account: Account) {
internal val accountManager: AccountManager
// authentication settings
var uri: URI?
get() {
val uri = accountManager.getUserData(account, KEY_URI)
if (uri == null) {
return null
}
try {
return URI(uri)
} catch (e: URISyntaxException) {
return null
}
}
set(uri) = accountManager.setUserData(account, KEY_URI, uri.toString())
var authToken: String
get() = accountManager.getUserData(account, KEY_TOKEN)
set(token) = accountManager.setUserData(account, KEY_TOKEN, token)
var keyPair: Crypto.AsymmetricKeyPair?
get() {
if (accountManager.getUserData(account, KEY_ASYMMETRIC_PUBLIC_KEY) != null) {
val pubkey = Base64.decode(accountManager.getUserData(account, KEY_ASYMMETRIC_PUBLIC_KEY), Base64.NO_WRAP)
val privkey = Base64.decode(accountManager.getUserData(account, KEY_ASYMMETRIC_PRIVATE_KEY), Base64.NO_WRAP)
return Crypto.AsymmetricKeyPair(privkey, pubkey)
}
return null
}
set(keyPair) {
accountManager.setUserData(account, KEY_ASYMMETRIC_PUBLIC_KEY, Base64.encodeToString(keyPair?.publicKey, Base64.NO_WRAP))
accountManager.setUserData(account, KEY_ASYMMETRIC_PRIVATE_KEY, Base64.encodeToString(keyPair?.privateKey, Base64.NO_WRAP))
}
val syncWifiOnly: Boolean
get() = accountManager.getUserData(account, KEY_WIFI_ONLY) != null
var syncWifiOnlySSID: String?
get() = accountManager.getUserData(account, KEY_WIFI_ONLY_SSID)
set(ssid) = accountManager.setUserData(account, KEY_WIFI_ONLY_SSID, ssid)
var etebaseSession: String?
get() = accountManager.getUserData(account, KEY_ETEBASE_SESSION)
set(value) = accountManager.setUserData(account, KEY_ETEBASE_SESSION, value)
val isLegacy: Boolean
get() = authToken != null
// CalDAV settings
var manageCalendarColors: Boolean
get() = accountManager.getUserData(account, KEY_MANAGE_CALENDAR_COLORS) == null
set(manage) = accountManager.setUserData(account, KEY_MANAGE_CALENDAR_COLORS, if (manage) null else "0")
// CardDAV settings
var groupMethod: GroupMethod
get() {
val name = accountManager.getUserData(account, KEY_CONTACT_GROUP_METHOD)
return if (name != null)
GroupMethod.valueOf(name)
else
GroupMethod.GROUP_VCARDS
}
set(method) {
val name = if (method == GroupMethod.GROUP_VCARDS) null else method.name
accountManager.setUserData(account, KEY_CONTACT_GROUP_METHOD, name)
}
init {
accountManager = AccountManager.get(context)
synchronized(AccountSettings::class.java) {
val versionStr = accountManager.getUserData(account, KEY_SETTINGS_VERSION)
?: throw InvalidAccountException(account)
var version = 0
try {
version = Integer.parseInt(versionStr)
} catch (ignored: NumberFormatException) {
}
Logger.log.fine("Account " + account.name + " has version " + version + ", current version: " + CURRENT_VERSION)
if (version < CURRENT_VERSION)
update(version)
}
}
fun username(): String {
return accountManager.getUserData(account, KEY_USERNAME)
}
fun username(userName: String) {
accountManager.setUserData(account, KEY_USERNAME, userName)
}
fun password(): String {
return accountManager.getPassword(account)
}
fun password(password: String) {
accountManager.setPassword(account, password)
}
// sync. settings
fun getSyncInterval(authority: String): Long? {
if (ContentResolver.getIsSyncable(account, authority) <= 0)
return null
if (ContentResolver.getSyncAutomatically(account, authority)) {
val syncs = ContentResolver.getPeriodicSyncs(account, authority)
return if (syncs.isEmpty())
SYNC_INTERVAL_MANUALLY
else
syncs[0].period
} else
return SYNC_INTERVAL_MANUALLY
}
fun setSyncInterval(authority: String, seconds: Long) {
if (seconds == SYNC_INTERVAL_MANUALLY) {
ContentResolver.setSyncAutomatically(account, authority, false)
} else {
ContentResolver.setSyncAutomatically(account, authority, true)
ContentResolver.addPeriodicSync(account, authority, Bundle(), seconds)
}
}
fun setSyncWiFiOnly(wiFiOnly: Boolean) {
accountManager.setUserData(account, KEY_WIFI_ONLY, if (wiFiOnly) "1" else null)
}
// update from previous account settings
private fun update(fromVersion: Int) {
val toVersion = CURRENT_VERSION
Logger.log.info("Updating account " + account.name + " from version " + fromVersion + " to " + toVersion)
try {
updateInner(fromVersion)
accountManager.setUserData(account, KEY_SETTINGS_VERSION, toVersion.toString())
} catch (e: Exception) {
Logger.log.log(Level.SEVERE, "Couldn't update account settings", e)
}
}
@Throws(ContactsStorageException::class)
private fun updateInner(fromVersion: Int) {
if (fromVersion < 2) {
}
}
class AppUpdatedReceiver : BroadcastReceiver() {
@SuppressLint("UnsafeProtectedBroadcastReceiver,MissingPermission")
override fun onReceive(context: Context, intent: Intent) {
Logger.log.info("EteSync was updated, checking for AccountSettings version")
// peek into AccountSettings to initiate a possible migration
val accountManager = AccountManager.get(context)
for (account in accountManager.getAccountsByType(App.accountType))
try {
Logger.log.info("Checking account " + account.name)
AccountSettings(context, account)
} catch (e: InvalidAccountException) {
Logger.log.log(Level.SEVERE, "Couldn't check for updated account settings", e)
}
}
}
class AccountMigrationException(msg: String) : Exception(msg)
companion object {
private val CURRENT_VERSION = 2
private val KEY_SETTINGS_VERSION = "version"
private val KEY_URI = "uri"
private val KEY_USERNAME = "user_name"
private val KEY_TOKEN = "auth_token"
private val KEY_ASYMMETRIC_PRIVATE_KEY = "asymmetric_private_key"
private val KEY_ASYMMETRIC_PUBLIC_KEY = "asymmetric_public_key"
private val KEY_WIFI_ONLY = "wifi_only"
private val KEY_ETEBASE_SESSION = "etebase_session"
// sync on WiFi only (default: false)
private val KEY_WIFI_ONLY_SSID = "wifi_only_ssid" // restrict sync to specific WiFi SSID
/**
* Time range limitation to the past [in days]
* value = null default value (DEFAULT_TIME_RANGE_PAST_DAYS)
* < 0 (-1) no limit
* >= 0 entries more than n days in the past won't be synchronized
*/
private val KEY_TIME_RANGE_PAST_DAYS = "time_range_past_days"
private val DEFAULT_TIME_RANGE_PAST_DAYS = 90
/* Whether DAVdroid sets the local calendar color to the value from service DB at every sync
value = null (not existing) true (default)
"0" false */
private val KEY_MANAGE_CALENDAR_COLORS = "manage_calendar_colors"
/**
* Contact group method:
* value = null (not existing) groups as separate VCards (default)
* "CATEGORIES" groups are per-contact CATEGORIES
*/
private val KEY_CONTACT_GROUP_METHOD = "contact_group_method"
val SYNC_INTERVAL_MANUALLY: Long = -1
// XXX: Workaround a bug in Android where passing a bundle to addAccountExplicitly doesn't work.
fun setUserData(accountManager: AccountManager, account: Account, uri: URI?, userName: String) {
accountManager.setUserData(account, KEY_SETTINGS_VERSION, CURRENT_VERSION.toString())
accountManager.setUserData(account, KEY_USERNAME, userName)
accountManager.setUserData(account, KEY_URI, uri?.toString())
}
}
}
| gpl-3.0 | c166871c127d5a6328666352b5c5e1f6 | 36.007605 | 135 | 0.645125 | 4.595373 | false | false | false | false |
signed/intellij-community | plugins/stats-collector/src/com/intellij/plugin/Startup.kt | 1 | 1279 | package com.intellij.plugin
import com.intellij.ide.util.PropertiesComponent
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
class NotificationManager : StartupActivity {
companion object {
private val PLUGIN_NAME = "Completion Stats Collector"
private val MESSAGE_TEXT =
"Data about your code completion usage will be anonymously reported. " +
"No personal data or code will be sent."
private val MESSAGE_SHOWN_KEY = "completion.stats.allow.message.shown"
}
private fun isMessageShown() = PropertiesComponent.getInstance().getBoolean(MESSAGE_SHOWN_KEY, false)
private fun setMessageShown(value: Boolean) = PropertiesComponent.getInstance().setValue(MESSAGE_SHOWN_KEY, value)
override fun runActivity(project: Project) {
if (!isMessageShown()) {
notify(project)
setMessageShown(true)
}
}
private fun notify(project: Project) {
val notification = Notification(PLUGIN_NAME, PLUGIN_NAME, MESSAGE_TEXT, NotificationType.INFORMATION)
notification.notify(project)
}
} | apache-2.0 | a7f9d07876e9716bdf0af359ee922e8e | 34.555556 | 118 | 0.70602 | 4.919231 | false | false | false | false |
cketti/okhttp | okhttp/src/main/kotlin/okhttp3/internal/platform/android/AndroidLog.kt | 1 | 3787 | /*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.platform.android
import android.util.Log
import java.util.concurrent.CopyOnWriteArraySet
import java.util.logging.Handler
import java.util.logging.Level
import java.util.logging.LogRecord
import java.util.logging.Logger
import okhttp3.OkHttpClient
import okhttp3.internal.SuppressSignatureCheck
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.http2.Http2
import okhttp3.internal.platform.android.AndroidLog.androidLog
private val LogRecord.androidLevel: Int
get() = when {
level.intValue() > Level.INFO.intValue() -> Log.WARN
level.intValue() == Level.INFO.intValue() -> Log.INFO
else -> Log.DEBUG
}
object AndroidLogHandler : Handler() {
override fun publish(record: LogRecord) {
androidLog(record.loggerName, record.androidLevel, record.message, record.thrown)
}
override fun flush() {
}
override fun close() {
}
}
@SuppressSignatureCheck
object AndroidLog {
private const val MAX_LOG_LENGTH = 4000
// Keep references to loggers to prevent their configuration from being GC'd.
private val configuredLoggers = CopyOnWriteArraySet<Logger>()
private val knownLoggers = LinkedHashMap<String, String>().apply {
val packageName = OkHttpClient::class.java.`package`?.name
if (packageName != null) {
this[packageName] = "OkHttp"
}
this[OkHttpClient::class.java.name] = "okhttp.OkHttpClient"
this[Http2::class.java.name] = "okhttp.Http2"
this[TaskRunner::class.java.name] = "okhttp.TaskRunner"
}.toMap()
internal fun androidLog(loggerName: String, logLevel: Int, message: String, t: Throwable?) {
val tag = loggerTag(loggerName)
if (Log.isLoggable(tag, logLevel)) {
var logMessage = message
if (t != null) logMessage = logMessage + '\n'.toString() + Log.getStackTraceString(t)
// Split by line, then ensure each line can fit into Log's maximum length.
var i = 0
val length = logMessage.length
while (i < length) {
var newline = logMessage.indexOf('\n', i)
newline = if (newline != -1) newline else length
do {
val end = minOf(newline, i + MAX_LOG_LENGTH)
Log.println(logLevel, tag, logMessage.substring(i, end))
i = end
} while (i < newline)
i++
}
}
}
private fun loggerTag(loggerName: String): String {
// We need to handle long logger names before they hit Log.
// java.lang.IllegalArgumentException: Log tag "okhttp3.mockwebserver.MockWebServer" exceeds limit of 23 characters
return knownLoggers[loggerName] ?: loggerName.take(23)
}
fun enable() {
for ((logger, tag) in knownLoggers) {
enableLogging(logger, tag)
}
}
private fun enableLogging(logger: String, tag: String) {
val logger = Logger.getLogger(logger)
if (configuredLoggers.add(logger)) {
logger.useParentHandlers = false
// log based on levels at startup to avoid logging each frame
logger.level = when {
Log.isLoggable(tag, Log.DEBUG) -> Level.FINE
Log.isLoggable(tag, Log.INFO) -> Level.INFO
else -> Level.WARNING
}
logger.addHandler(AndroidLogHandler)
}
}
}
| apache-2.0 | fc5e856b90f73f5a6fdb081d505d83c5 | 31.646552 | 119 | 0.695009 | 4.024442 | false | false | false | false |
angcyo/RLibrary | uiview/src/main/java/com/angcyo/uiview/widget/group/GuideFrameLayout.kt | 1 | 9849 | package com.angcyo.uiview.widget.group
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.FrameLayout
import com.angcyo.uiview.R
import com.angcyo.uiview.kotlin.exactlyMeasure
import com.angcyo.uiview.kotlin.getDrawable
import com.angcyo.uiview.utils.UI
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:
* 创建人员:Robi
* 创建时间:2017/12/26 17:26
* 修改人员:Robi
* 修改时间:2017/12/26 17:26
* 修改备注:
* Version: 1.0.0
*/
class GuideFrameLayout(context: Context, attributeSet: AttributeSet? = null) : FrameLayout(context, attributeSet) {
companion object {
val LEFT = 1
val TOP = 2
val RIGHT = 3
val BOTTOM = 4
val CENTER = 5
val LEFT_CENTER = 6
val TOP_CENTER = 7
val RIGHT_CENTER = 8
val BOTTOM_CENTER = 9
}
/*锚点坐标列表*/
private var anchorList = mutableListOf<Rect>()
init {
val array = context.obtainStyledAttributes(attributeSet, R.styleable.GuideFrameLayout)
if (isInEditMode) {
val anchors = array.getString(R.styleable.GuideFrameLayout_r_guide_anchors)
anchors?.let {
val splits = it.split(":")
if (splits.isNotEmpty()) {
anchorList.clear()
for (i in 0 until splits.size) {
val ss = splits[i].split(",")
anchorList.add(Rect(ss[0].toInt(), ss[1].toInt(),
ss[0].toInt() + ss[2].toInt(), ss[1].toInt() + ss[3].toInt()))
}
}
}
}
array.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
//修正大小
for (i in 0 until childCount) {
val childAt = getChildAt(i)
val layoutParams = childAt.layoutParams
if (layoutParams is LayoutParams) {
if (layoutParams.anchorIndex >= 0 && layoutParams.anchorIndex < anchorList.size) {
//需要对齐锚点
val anchorRect = anchorList[layoutParams.anchorIndex]
val offsetWidth = layoutParams.offsetWidth
val offsetHeight = layoutParams.offsetHeight
if (layoutParams.isAnchor) {
val w = anchorRect.width() + offsetWidth
val h = anchorRect.height() + offsetHeight
childAt.measure(exactlyMeasure(w), exactlyMeasure(h))
}
}
}
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
super.onLayout(changed, left, top, right, bottom)
//修正坐标
for (i in 0 until childCount) {
val childAt = getChildAt(i)
val layoutParams = childAt.layoutParams
if (layoutParams is LayoutParams) {
if (layoutParams.anchorIndex >= 0 && layoutParams.anchorIndex < anchorList.size) {
//需要对齐锚点
val anchorRect = anchorList[layoutParams.anchorIndex]
val offsetX = layoutParams.offsetX
val offsetY = layoutParams.offsetY
if (layoutParams.isAnchor) {
//自动设置锚点View的背景为 蚂蚁线
if (childAt.background == null) {
UI.setBackgroundDrawable(childAt, getDrawable(R.drawable.base_guide_shape_line_dash))
}
val l = anchorRect.centerX() - childAt.measuredWidth / 2
val t = anchorRect.centerY() - childAt.measuredHeight / 2
childAt.layout(l + offsetX, t + offsetY, l + childAt.measuredWidth + offsetX, t + childAt.measuredHeight + offsetY)
} else {
when (layoutParams.guideGravity) {
LEFT -> {
val l = anchorRect.left - offsetX - childAt.measuredWidth
val t = anchorRect.top + offsetY
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
TOP -> {
val t = anchorRect.top - offsetY - childAt.measuredHeight
val l = anchorRect.left + offsetX
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
RIGHT -> {
val l = anchorRect.right + offsetX
val t = anchorRect.top + offsetY
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
BOTTOM -> {
val l = anchorRect.left + offsetX
val t = anchorRect.bottom + offsetY
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
CENTER -> {
val l = anchorRect.centerX() - childAt.measuredWidth / 2 + offsetX
val t = anchorRect.centerY() - childAt.measuredHeight / 2 + offsetY
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
LEFT_CENTER -> {
val l = anchorRect.left - offsetX - childAt.measuredWidth
val t = anchorRect.centerY() - childAt.measuredHeight / 2 + offsetY
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
TOP_CENTER -> {
val t = anchorRect.top - offsetY - childAt.measuredHeight
val l = anchorRect.centerX() - childAt.measuredWidth / 2 + offsetX
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
RIGHT_CENTER -> {
val l = anchorRect.right + offsetX
val t = anchorRect.centerY() - childAt.measuredHeight / 2 + offsetY
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
BOTTOM_CENTER -> {
val t = anchorRect.bottom + offsetY
val l = anchorRect.centerX() - childAt.measuredWidth / 2 + offsetX
childAt.layout(l, t, l + childAt.measuredWidth, t + childAt.measuredHeight)
}
else -> {
}
}
}
}
}
}
}
fun addAnchorList(anchors: List<Rect>) {
anchorList.clear()
anchorList.addAll(anchors)
}
fun addAnchor(anchor: Rect) {
anchorList.add(anchor)
}
override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
return LayoutParams(context, attrs)
}
override fun generateLayoutParams(lp: ViewGroup.LayoutParams?): ViewGroup.LayoutParams {
return LayoutParams(lp)
}
override fun generateDefaultLayoutParams(): LayoutParams {
return LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
class LayoutParams : FrameLayout.LayoutParams {
var anchorIndex = -1
var guideGravity = 0
var offsetX = 0
var offsetY = 0
/*只当 isAnchor=true 时有效*/
var offsetWidth = 0
var offsetHeight = 0
var isAnchor = false
constructor(c: Context, attrs: AttributeSet?) : super(c, attrs) {
val a = c.obtainStyledAttributes(attrs, R.styleable.GuideFrameLayout)
anchorIndex = a.getInt(R.styleable.GuideFrameLayout_r_guide_show_in_anchor, anchorIndex)
guideGravity = a.getInt(R.styleable.GuideFrameLayout_r_guide_gravity, guideGravity)
offsetX = a.getDimensionPixelOffset(R.styleable.GuideFrameLayout_r_guide_offset_x, offsetX)
offsetY = a.getDimensionPixelOffset(R.styleable.GuideFrameLayout_r_guide_offset_y, offsetY)
offsetWidth = a.getDimensionPixelOffset(R.styleable.GuideFrameLayout_r_guide_offset_width, offsetWidth)
offsetHeight = a.getDimensionPixelOffset(R.styleable.GuideFrameLayout_r_guide_offset_height, offsetHeight)
isAnchor = a.getBoolean(R.styleable.GuideFrameLayout_r_guide_is_anchor, isAnchor)
a.recycle()
}
constructor(width: Int, height: Int) : super(width, height)
constructor(width: Int, height: Int, gravity: Int) : super(width, height, gravity)
constructor(source: ViewGroup.LayoutParams?) : super(source)
constructor(source: MarginLayoutParams?) : super(source)
}
} | apache-2.0 | bdb1cb3fc44ddc09f55b09c1984acf8a | 43.580189 | 139 | 0.514232 | 5.050183 | false | false | false | false |
jean79/yested_fw | src/jsMain/kotlin/net/yested/ext/pickadate/dateinput.kt | 1 | 2064 | package net.yested.ext.pickadate
import globals.jQuery
import net.yested.core.html.bind
import net.yested.core.properties.Property
import net.yested.core.utils.whenAddedToDom
import net.yested.ext.moment.FormatString
import net.yested.ext.moment.FormatStringBuilder
import net.yested.ext.moment.Moment
import net.yested.ext.moment.asText
import org.w3c.dom.HTMLElement
import org.w3c.dom.HTMLInputElement
import kotlin.browser.document
/**
* uses library: http://amsul.ca/pickadate.js/
* @author Eric Pabst ([email protected])
* Date: 1/21/17
* Time: 6:44 AM
*/
/**
* A dateInput.
* @param clearLabel the label to put on the "Clear" button on the pick-a-date dialog.
* @param containerSelector any valid CSS selector for the container to place the picker's root element.
*/
fun HTMLElement.dateInput(data: Property<Moment?>,
placeholder: String? = null,
clearLabel: String = "Clear",
containerSelector: String? = null,
formatter: FormatStringBuilder.()-> FormatString,
init: (HTMLInputElement.() -> Unit)? = null) {
val formatString = FormatStringBuilder().formatter().toString()
val text = data.asText(formatString)
val element = document.createElement("input") as HTMLInputElement
element.className = "date"
element.size = formatString.length
element.type = "text"
if (placeholder != null) { element.placeholder = placeholder }
element.bind(text)
if (init != null) element.init()
this.appendChild(element)
val options = PickADateOptions(
format= formatString.toLowerCase(),
selectMonths = true,
selectYears = true,
clear = clearLabel,
container = containerSelector,
onSet = { context -> data.set(context.select?.let { Moment.fromMillisecondsSinceUnixEpoch(it) }) }
)
whenAddedToDom {
text.onNext { setAttribute("data-value", it) }
jQuery(element).pickadate(options)
}
}
| mit | ff0efc35bb62773f1151d2d1e2584773 | 32.290323 | 110 | 0.661822 | 4.195122 | false | false | false | false |
filipebezerra/VerseOfTheDay | app/src/main/java/com/github/filipebezerra/bible/verseoftheday/ui/home/HomeFragment.kt | 1 | 1815 | package com.github.filipebezerra.bible.verseoftheday.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.github.filipebezerra.bible.verseoftheday.databinding.HomeFragmentBinding
import com.github.filipebezerra.bible.verseoftheday.extension.repeatOnLifecycleStarted
import com.github.filipebezerra.bible.verseoftheday.presentation.home.HomeViewModel
class HomeFragment : Fragment() {
private var _binding: HomeFragmentBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
private val homeViewModel by lazy { ViewModelProvider(this)[HomeViewModel::class.java] }
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = HomeFragmentBinding.inflate(inflater, container, false)
.also { _binding = it }
.root
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
repeatOnLifecycleStarted {
homeViewModel.title.collect { title -> binding.titleText.text = title }
}
repeatOnLifecycleStarted {
homeViewModel.verseOfTheDay.collect { verse ->
with(binding) {
with(verse) {
verseText.text = content
referenceText.text = reference
bibleVersionText.text = version
}
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| apache-2.0 | f70d77c92bdecbfcca1b1ada892a709e | 32 | 92 | 0.667769 | 4.986264 | false | false | false | false |
world-federation-of-advertisers/common-jvm | src/main/kotlin/org/wfanet/measurement/gcloud/spanner/testing/SpannerEmulatorDatabaseRule.kt | 1 | 3171 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.gcloud.spanner.testing
import com.google.cloud.spanner.DatabaseId
import com.google.cloud.spanner.Spanner
import com.google.cloud.spanner.connection.SpannerPool
import java.nio.file.Path
import java.sql.DriverManager
import java.util.logging.Level
import kotlinx.coroutines.runBlocking
import liquibase.Contexts
import liquibase.Scope
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import org.wfanet.measurement.common.db.liquibase.Liquibase
import org.wfanet.measurement.common.db.liquibase.setLogLevel
import org.wfanet.measurement.gcloud.spanner.AsyncDatabaseClient
import org.wfanet.measurement.gcloud.spanner.buildSpanner
import org.wfanet.measurement.gcloud.spanner.getAsyncDatabaseClient
/**
* JUnit rule exposing a temporary Google Cloud Spanner database via Spanner Emulator.
*
* @param changelogPath [Path] to a Liquibase changelog.
*/
class SpannerEmulatorDatabaseRule(
private val changelogPath: Path,
private val databaseName: String = "test-db"
) : TestRule {
lateinit var databaseClient: AsyncDatabaseClient
private set
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
check(!::databaseClient.isInitialized)
SpannerEmulator().use { emulator ->
val emulatorHost = runBlocking { emulator.start() }
try {
createDatabase(emulatorHost).use { spanner ->
databaseClient =
spanner.getAsyncDatabaseClient(DatabaseId.of(PROJECT, INSTANCE, databaseName))
base.evaluate()
}
} finally {
// Make sure these Spanner instances from JDBC are closed before the emulator is shut
// down, otherwise it will block JVM shutdown.
SpannerPool.closeSpannerPool()
}
}
}
}
}
private fun createDatabase(emulatorHost: String): Spanner {
val connectionString =
SpannerEmulator.buildJdbcConnectionString(emulatorHost, PROJECT, INSTANCE, databaseName)
DriverManager.getConnection(connectionString).use { connection ->
Liquibase.fromPath(connection, changelogPath).use { liquibase ->
Scope.getCurrentScope().setLogLevel(Level.FINE)
liquibase.update(Contexts())
}
}
return buildSpanner(PROJECT, emulatorHost)
}
companion object {
private const val PROJECT = "test-project"
private const val INSTANCE = "test-instance"
}
}
| apache-2.0 | 56045a13270a1527b3118ea16b162d39 | 35.448276 | 97 | 0.731315 | 4.602322 | false | true | false | false |
robinverduijn/gradle | subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/provider/KotlinScriptClassPathProvider.kt | 1 | 8297 | /*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.provider
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.SelfResolvingDependency
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.ClassPathRegistry
import org.gradle.api.internal.artifacts.dsl.dependencies.DependencyFactory
import org.gradle.api.internal.classpath.ModuleRegistry
import org.gradle.api.internal.file.FileCollectionFactory
import org.gradle.api.internal.initialization.ClassLoaderScope
import org.gradle.internal.classloader.ClassLoaderVisitor
import org.gradle.internal.classpath.ClassPath
import org.gradle.internal.classpath.DefaultClassPath
import org.gradle.kotlin.dsl.codegen.generateApiExtensionsJar
import org.gradle.kotlin.dsl.support.gradleApiMetadataModuleName
import org.gradle.kotlin.dsl.support.isGradleKotlinDslJar
import org.gradle.kotlin.dsl.support.isGradleKotlinDslJarName
import org.gradle.kotlin.dsl.support.ProgressMonitor
import org.gradle.kotlin.dsl.support.serviceOf
import org.gradle.util.GFileUtils.moveFile
import com.google.common.annotations.VisibleForTesting
import java.io.File
import java.net.URI
import java.net.URISyntaxException
import java.net.URL
import java.util.concurrent.ConcurrentHashMap
fun gradleKotlinDslOf(project: Project): List<File> =
kotlinScriptClassPathProviderOf(project).run {
gradleKotlinDsl.asFiles
}
fun gradleKotlinDslJarsOf(project: Project): FileCollection =
project.fileCollectionOf(
kotlinScriptClassPathProviderOf(project).gradleKotlinDslJars.asFiles.filter(::isGradleKotlinDslJar),
"gradleKotlinDsl"
)
internal
fun Project.fileCollectionOf(files: Collection<File>, name: String): FileCollection =
serviceOf<FileCollectionFactory>().fixed(name, files)
internal
fun kotlinScriptClassPathProviderOf(project: Project) =
project.serviceOf<KotlinScriptClassPathProvider>()
internal
typealias JarCache = (String, JarGenerator) -> File
internal
typealias JarGenerator = (File) -> Unit
private
typealias JarGeneratorWithProgress = (File, () -> Unit) -> Unit
internal
typealias JarsProvider = () -> Collection<File>
class KotlinScriptClassPathProvider(
val moduleRegistry: ModuleRegistry,
val classPathRegistry: ClassPathRegistry,
val coreAndPluginsScope: ClassLoaderScope,
val gradleApiJarsProvider: JarsProvider,
val jarCache: JarCache,
val progressMonitorProvider: JarGenerationProgressMonitorProvider
) {
/**
* Generated Gradle API jar plus supporting libraries such as groovy-all.jar and generated API extensions.
*/
@VisibleForTesting
val gradleKotlinDsl: ClassPath by lazy {
gradleApi + gradleApiExtensions + gradleKotlinDslJars
}
private
val gradleApi: ClassPath by lazy {
DefaultClassPath.of(gradleApiJarsProvider())
}
/**
* Generated extensions to the Gradle API.
*/
private
val gradleApiExtensions: ClassPath by lazy {
DefaultClassPath.of(gradleKotlinDslExtensions())
}
/**
* gradle-kotlin-dsl.jar plus kotlin libraries.
*/
internal
val gradleKotlinDslJars: ClassPath by lazy {
DefaultClassPath.of(gradleKotlinDslJars())
}
/**
* The Gradle implementation classpath which should **NOT** be visible
* in the compilation classpath of any script.
*/
private
val gradleImplementationClassPath: Set<File> by lazy {
cachedClassLoaderClassPath.of(coreAndPluginsScope.exportClassLoader)
}
fun compilationClassPathOf(scope: ClassLoaderScope): ClassPath =
cachedScopeCompilationClassPath.computeIfAbsent(scope, ::computeCompilationClassPath)
private
fun computeCompilationClassPath(scope: ClassLoaderScope): ClassPath {
return gradleKotlinDsl + exportClassPathFromHierarchyOf(scope)
}
fun exportClassPathFromHierarchyOf(scope: ClassLoaderScope): ClassPath {
require(scope.isLocked) {
"$scope must be locked before it can be used to compute a classpath!"
}
val exportedClassPath = cachedClassLoaderClassPath.of(scope.exportClassLoader)
return DefaultClassPath.of(exportedClassPath - gradleImplementationClassPath)
}
private
fun gradleKotlinDslExtensions(): File =
produceFrom("kotlin-dsl-extensions") { outputFile, onProgress ->
generateApiExtensionsJar(outputFile, gradleJars, gradleApiMetadataJar, onProgress)
}
private
fun produceFrom(id: String, generate: JarGeneratorWithProgress): File =
jarCache(id) { outputFile ->
progressMonitorFor(outputFile, 3).use { progressMonitor ->
generateAtomically(outputFile) { generate(it, progressMonitor::onProgress) }
}
}
private
fun generateAtomically(outputFile: File, generate: JarGenerator) {
val tempFile = tempFileFor(outputFile)
generate(tempFile)
moveFile(tempFile, outputFile)
}
private
fun progressMonitorFor(outputFile: File, totalWork: Int): ProgressMonitor =
progressMonitorProvider.progressMonitorFor(outputFile, totalWork)
private
fun tempFileFor(outputFile: File): File =
createTempFile(outputFile.nameWithoutExtension, outputFile.extension).apply {
deleteOnExit()
}
private
fun gradleKotlinDslJars(): List<File> =
gradleJars.filter { file ->
file.name.let { isKotlinJar(it) || isGradleKotlinDslJarName(it) }
}
private
val gradleJars by lazy {
classPathRegistry.getClassPath(gradleApiNotation.name).asFiles
}
private
val gradleApiMetadataJar by lazy {
moduleRegistry.getExternalModule(gradleApiMetadataModuleName).classpath.asFiles.single()
}
private
val cachedScopeCompilationClassPath = ConcurrentHashMap<ClassLoaderScope, ClassPath>()
private
val cachedClassLoaderClassPath = ClassLoaderClassPathCache()
}
internal
fun gradleApiJarsProviderFor(dependencyFactory: DependencyFactory): JarsProvider =
{ (dependencyFactory.gradleApi() as SelfResolvingDependency).resolve() }
private
fun DependencyFactory.gradleApi(): Dependency =
createDependency(gradleApiNotation)
private
val gradleApiNotation = DependencyFactory.ClassPathNotation.GRADLE_API
private
fun isKotlinJar(name: String): Boolean =
name.startsWith("kotlin-stdlib-")
|| name.startsWith("kotlin-reflect-")
private
class ClassLoaderClassPathCache {
private
val cachedClassPaths = hashMapOf<ClassLoader, Set<File>>()
fun of(classLoader: ClassLoader): Set<File> =
cachedClassPaths.getOrPut(classLoader) {
classPathOf(classLoader)
}
private
fun classPathOf(classLoader: ClassLoader): Set<File> {
val classPathFiles = mutableSetOf<File>()
object : ClassLoaderVisitor() {
override fun visitClassPath(classPath: Array<URL>) {
classPath.forEach { url ->
if (url.protocol == "file") {
classPathFiles.add(fileFrom(url))
}
}
}
override fun visitParent(classLoader: ClassLoader) {
classPathFiles.addAll(of(classLoader))
}
}.visit(classLoader)
return classPathFiles
}
private
fun fileFrom(url: URL) = File(toURI(url))
}
private
fun toURI(url: URL): URI =
try {
url.toURI()
} catch (e: URISyntaxException) {
URL(
url.protocol,
url.host,
url.port,
url.file.replace(" ", "%20")).toURI()
}
| apache-2.0 | a2a61574a332ac5c64d1558de00192e5 | 28.738351 | 110 | 0.717609 | 4.743854 | false | false | false | false |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/assets/AssetsV1Entity.kt | 1 | 417 | package com.waz.zclient.storage.db.assets
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "Assets")
data class AssetsV1Entity(
@PrimaryKey
@ColumnInfo(name = "_id")
val id: String,
@ColumnInfo(name = "asset_type", defaultValue = "")
val assetType: String,
@ColumnInfo(name = "data", defaultValue = "")
val data: String
)
| gpl-3.0 | 03b05e966c041f6b2887ebf8d54f0703 | 22.166667 | 55 | 0.70024 | 3.756757 | false | false | false | false |
fabmax/calculator | app/src/main/kotlin/de/fabmax/calc/MainActivity.kt | 1 | 9302 | package de.fabmax.calc
import android.os.Bundle
import de.fabmax.calc.layout.phoneLayout
import de.fabmax.calc.ui.Button
import de.fabmax.calc.ui.Layout
import de.fabmax.calc.ui.Orientation
import de.fabmax.lightgl.*
import de.fabmax.lightgl.scene.Node
import de.fabmax.lightgl.scene.TransformGroup
import de.fabmax.lightgl.util.GlMath
import de.fabmax.lightgl.util.Painter
/**
* The one and only Activity in this project. Extends LightGlActivity which does most of the
* OpenGL related heavy lifting. The only content is a GLSurfaceView.
*/
class MainActivity : LightGlActivity() {
private val mRotationSens = RotationSensor()
private var mParallax: ParallaxHelper? = null
private var mContentGrp = TransformGroup()
private var mContent: Content? = null
private var mScreenWidth = 0
private var mScreenHeight = 0
private val mScreenBounds = BoundingBox(0f, 0f, 0f)
private val mCamPos = Vec3fAnimation()
private val mCamLookAt = Vec3fAnimation()
private val mCamTmp = FloatArray(3)
private var mPerspectiveMode = false
private val mTouch = object {
var posX = -1f
var posY = -1f
var action = -1
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ParallaxHelper makes the camera wobble a bit when in perspective mode
mParallax = ParallaxHelper(this)
mParallax?.setIntensity(0.5f, 1f)
mParallax?.invertAxis(true, false)
// Create the engine
setNumSamples(4)
createEngine(false)
//setLogFramesPerSecond(true)
// Create a perspective camera with 40° field of view
val cam = PerspectiveCamera()
cam.fovy = 40.0f
mEngine.camera = cam
// Install a OnTouchListener which saves the touch events for later evaluation from
// within the render loop
mGlView.setOnTouchListener({ view, event ->
// store touch event in order to process it within the OpenGL thread
mTouch.posX = event.x
mTouch.posY = event.y
mTouch.action = event.actionMasked
true
})
}
override fun onResume() {
super.onResume()
mParallax?.onResume()
mRotationSens.onResume(this)
}
override fun onPause() {
super.onPause()
mParallax?.onPause()
mRotationSens.onPause(this)
}
/**
* Called when the OpenGL viewport size has changed.
*/
override fun onViewportChange(width: Int, height: Int) {
super.onViewportChange(width, height);
// Adjust camera position so that at z = 0 one pixel corresponds to exactly one unit in
// GL coordinates
val cam = mEngine.camera as PerspectiveCamera
val fovy = cam.fovy
val d = ((height * 0.5) / Math.tan(Math.toRadians(fovy / 2.0))).toFloat();
cam.setPosition(0.0f, 0.0f, -d)
cam.setClipRange(100.0f, d * 2.0f - 200.0f)
cam.setUpDirection(0.0f, -1.0f, 0.0f)
// setup camera animation for toggling between standard mode and perspective mode
// animations are not started yet
mCamPos.set(0.0f, 0.0f, -d, d*0.45f, -d*0.6f, -d*0.75f)
mCamPos.whenDone = { -> mCamPos.reverse(); mPerspectiveMode = !mPerspectiveMode }
mCamLookAt.set(0f, 0f, 0f, width/20f, -height/20f, 0f)
mCamLookAt.whenDone = { -> mCamLookAt.reverse() }
// do layout computations for new viewport size
setContentSize(width, height)
}
/**
* Called when the OpenGL context is created, does the initial scene setup.
*/
override fun onLoadScene(glContext: LightGlContext) {
// basic engine setup
glContext.state.setBackgroundColor(1.0f, 1.0f, 1.0f)
glContext.state.setDepthTesting(false)
glContext.engine.scene = mContentGrp
// create a directional light, actual direction is set in onRenderFrame()
// light color is currently ignored
val light = Light.createDirectionalLight(1f, 1f, 1f, 1f, 1f, 1f)
glContext.engine.addLight(light)
// enable dynamic shadow rendering
val sceneBounds = BoundingBox(-1000f, 1000f, -1000f, 1000f, -1000f, 1000f)
val shadow = ShadowRenderPass()
shadow.setSceneBounds(sceneBounds)
shadow.shadowMapSize = 2048
glContext.engine.preRenderPass = shadow
// Load the layout and set it as content
mContent = Content(glContext, phoneLayout(this));
mContentGrp.addChild(mContent)
mContentGrp.resetTransform()
// invert axis to get intuitive coordinates
mContentGrp.scale(-1f, -1f, -1f)
// do layout computations for current viewport size
setContentSize(mScreenWidth, mScreenHeight)
}
/**
* Called before every rendered frame.
*/
override fun onRenderFrame(glContext: LightGlContext?) {
super.onRenderFrame(glContext)
// interpolate layout between portrait and landscape for current orientation
mContent?.layout?.mixConfigs(mRotationSens.normalizedHV)
// ParallaxHelper needs to know the orientation as well...
mParallax?.rotation = mRotationSens.rotation
// animate camera between normal mode and perspective mode
// position remains static as long as the animation is not started
val pos = mCamPos.animate()
val lookAt = mCamLookAt.animate()
mCamTmp[0] = pos.x
mCamTmp[1] = pos.y
mCamTmp[2] = pos.z
// reset light direction
val light = mEngine.lights[0]
light.position[0] = -.4f;
light.position[1] = .5f;
light.position[2] = -1f
if (mPerspectiveMode) {
// if perspective mode is active, camera position and light direction are modified
// based on the device gyroscope
mParallax?.transformCameraVector(mCamTmp)
mParallax?.transformLightVector(light.position)
}
// update camera position and up direction for this frame
val upDir = mRotationSens.upDirection
mEngine.camera.setUpDirection(upDir.x, upDir.y, upDir.z)
mEngine.camera.setPosition(mCamTmp[0], mCamTmp[1], mCamTmp[2])
mEngine.camera.setLookAt(lookAt.x, lookAt.y, lookAt.z)
}
/**
* Toggles the camera mode between standard and perspective mode. The animations are
* automatically setup for the reverse direction when finished
*/
fun toggleCamera() {
mCamPos.start(0.25f, true)
mCamLookAt.start(0.25f, true)
}
/**
* Called when the user hits the 'inv' button. Flips the 'sin', 'cos' and 'tan' function
* buttons to show their inverse functions and vice versa.
*/
fun flipFunctions() {
val layout = mContent?.layout
if (layout != null) {
val sin = layout.findById("sin") as Button
val cos = layout.findById("cos") as Button
val tan = layout.findById("tan") as Button
if (sin.text == "sin") {
sin.flipText("asin")
cos.flipText("acos")
tan.flipText("atan")
} else {
sin.flipText("sin")
cos.flipText("cos")
tan.flipText("tan")
}
}
}
/**
* Updates screen bounds and layout configurations for the given viewport size.
*/
private fun setContentSize(width: Int, height: Int) {
mScreenWidth = width
mScreenHeight = height
mScreenBounds.reset(0f, 0f, 0f)
mScreenBounds.maxX = width.toFloat()
mScreenBounds.maxY = height.toFloat()
mContent?.layout?.doLayout(Orientation.PORTRAIT, mScreenBounds, this)
mScreenBounds.reset(0f, 0f, 0f)
mScreenBounds.maxX = height.toFloat()
mScreenBounds.maxY = width.toFloat()
mContent?.layout?.doLayout(Orientation.LANDSCAPE, mScreenBounds, this)
mContent?.layout?.mixConfigs(1f)
}
/**
* Content is the root node for all OpenGL UI elements.
*/
private inner class Content(glContext: LightGlContext, layout: Layout) : Node() {
val painter = Painter(glContext)
val pickRay = Ray()
var layout: Layout = layout
/**
* Renders the layout.
*/
override fun render(context: LightGlContext) {
if (mTouch.action != -1) {
// compute a pick ray for the current touch input and process touch action
context.engine.camera
.getPickRay(context.state.viewport, mTouch.posX, mTouch.posY, pickRay)
GlMath.multiplyMV(mContentGrp.inverseTransformation, 0, pickRay.origin, 0);
GlMath.multiplyMV(mContentGrp.inverseTransformation, 0, pickRay.direction, 0);
layout.processTouch(pickRay, mTouch.action)
mTouch.action = -1
}
// do the drawing!
painter.pushTransform()
painter.translate(layout.x, layout.y, layout.z)
layout.paint(painter)
painter.popTransform()
}
override fun delete(context: LightGlContext?) {
// Content is never deleted
}
}
}
| apache-2.0 | 1a2624b2759e3b693b73854e337079f8 | 34.365019 | 95 | 0.627889 | 4.099163 | false | false | false | false |
danybony/word-clock | AndroidThings/things/src/main/java/net/bonysoft/wordclock/MatrixSerialiser.kt | 1 | 1060 | package net.bonysoft.wordclock
import net.bonysoft.wordclock.common.Configuration
const val LED_SEPARATOR = ','
const val START = "/"
const val RED = "r"
const val GREEN = "g"
const val BLUE = "b"
const val BRIGHTNESS = "a"
const val END = '!'
class MatrixSerialiser {
fun serialise(matrix: BooleanArray, configuration: Configuration): String {
val r = configuration.color shr 16 and 0xFF
val g = configuration.color shr 8 and 0xFF
val b = configuration.color shr 0 and 0xFF
val brightness = (configuration.brightness * 255f / 100f).toInt()
val stringBuilder = StringBuilder(START)
.append(r).append(RED)
.append(g).append(GREEN)
.append(b).append(BLUE)
.append(brightness).append(BRIGHTNESS)
matrix.forEachIndexed { index, isOn ->
if (isOn) {
stringBuilder.append(index.toString()).append(LED_SEPARATOR)
}
}
stringBuilder.append(END)
return stringBuilder.toString()
}
}
| apache-2.0 | d8a2eb1874631dfb00206b47361b50e2 | 30.176471 | 79 | 0.619811 | 4.291498 | false | true | false | false |
yshrsmz/monotweety | app/src/main/java/net/yslibrary/monotweety/license/LicenseController.kt | 1 | 3045 | package net.yslibrary.monotweety.license
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.ControllerChangeType
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.rxkotlin.subscribeBy
import net.yslibrary.licenseadapter.Library
import net.yslibrary.licenseadapter.LicenseAdapter
import net.yslibrary.monotweety.App
import net.yslibrary.monotweety.R
import net.yslibrary.monotweety.analytics.Analytics
import net.yslibrary.monotweety.base.ActionBarController
import net.yslibrary.monotweety.base.ObjectWatcherDelegate
import net.yslibrary.monotweety.base.findById
import javax.inject.Inject
import kotlin.properties.Delegates
class LicenseController : ActionBarController() {
override val hasBackButton: Boolean = true
lateinit var bindings: Bindings
@set:[Inject]
var viewModel by Delegates.notNull<LicenseViewModel>()
@set:[Inject]
var objectWatcherDelegate by Delegates.notNull<ObjectWatcherDelegate>()
override val title: String?
get() = getString(R.string.title_license)
val component: LicenseComponent by lazy {
val activityBus =
getComponentProvider<LicenseViewModule.DependencyProvider>(activity!!).activityBus()
DaggerLicenseComponent.builder()
.userComponent(App.userComponent(applicationContext!!))
.licenseViewModule(LicenseViewModule(activityBus))
.build()
}
override fun onContextAvailable(context: Context) {
super.onContextAvailable(context)
component.inject(this)
analytics.viewEvent(Analytics.VIEW_LICENSE)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
val view = inflater.inflate(R.layout.controller_license, container, false)
bindings = Bindings(view)
setEvents()
return view
}
override fun onChangeEnded(
changeHandler: ControllerChangeHandler,
changeType: ControllerChangeType
) {
super.onChangeEnded(changeHandler, changeType)
objectWatcherDelegate.handleOnChangeEnded(isDestroyed, changeType)
}
override fun onDestroy() {
super.onDestroy()
objectWatcherDelegate.handleOnDestroy()
}
fun setEvents() {
viewModel.licenses
.bindToLifecycle()
.observeOn(AndroidSchedulers.mainThread())
.subscribeBy { initAdapter(it) }
}
fun initAdapter(dataSet: List<Library>) {
bindings.list.layoutManager = LinearLayoutManager(activity)
bindings.list.adapter = LicenseAdapter(dataSet)
}
class Bindings(view: View) {
val list = view.findById<RecyclerView>(R.id.list)
}
}
| apache-2.0 | c9138617f071b279e75207348e5c2308 | 30.071429 | 96 | 0.733005 | 4.991803 | false | false | false | false |
andreab91/BirthdayGreetingsKotlin | src/test/kotlin/EmployeeTest.kt | 1 | 803 | package test
import main.Employee
import main.XDate
import org.junit.Test
import org.junit.Assert.*
class EmployeeTest {
@Test
@Throws(Exception::class)
fun testBirthday() {
val employee = Employee("foo", "bar", "1990/01/31", "[email protected]")
assertFalse(employee.isBirthday(XDate("2008/01/30")))
assertTrue(employee.isBirthday(XDate("2008/01/31")))
}
@Test
@Throws(Exception::class)
fun equality() {
val base = Employee("First", "Last", "1999/09/01", "[email protected]")
val same = Employee("First", "Last", "1999/09/01", "[email protected]")
val different = Employee("First", "Last", "1999/09/01", "[email protected]")
assertFalse(base.equals(""))
assertTrue(base == same)
assertFalse(base == different)
}
}
| apache-2.0 | 22844d1d68a1cfd124e26b6d3a509f98 | 25.766667 | 80 | 0.611457 | 3.461207 | false | true | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/musicbrainz/artist/get/ArtistGet.kt | 1 | 2596 | package uk.co.ourfriendirony.medianotifier.clients.musicbrainz.artist.get
import com.fasterxml.jackson.annotation.*
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder(
"disambiguation",
"id",
"area",
"gender",
"begin-area",
"sort-name",
"gender-id",
"name",
"type",
"release-groups",
"end-area",
"ipis",
"type-id",
"life-span",
"isnis",
"country"
)
class ArtistGet {
@get:JsonProperty("disambiguation")
@set:JsonProperty("disambiguation")
@JsonProperty("disambiguation")
var disambiguation: String? = null
@get:JsonProperty("id")
@set:JsonProperty("id")
@JsonProperty("id")
var id: String? = null
@get:JsonProperty("area")
@set:JsonProperty("area")
@JsonProperty("area")
var area: ArtistGetArea? = null
@get:JsonProperty("gender")
@set:JsonProperty("gender")
@JsonProperty("gender")
var gender: Any? = null
@get:JsonProperty("begin-area")
@set:JsonProperty("begin-area")
@JsonProperty("begin-area")
var beginArea: ArtistGetBeginArea? = null
@get:JsonProperty("sort-name")
@set:JsonProperty("sort-name")
@JsonProperty("sort-name")
var sortName: String? = null
@get:JsonProperty("gender-id")
@set:JsonProperty("gender-id")
@JsonProperty("gender-id")
var genderId: Any? = null
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
@get:JsonProperty("type")
@set:JsonProperty("type")
@JsonProperty("type")
var type: String? = null
@get:JsonProperty("release-groups")
@set:JsonProperty("release-groups")
@JsonProperty("release-groups")
var releaseGroups: List<ArtistGetReleaseGroup>? = null
@get:JsonProperty("end-area")
@set:JsonProperty("end-area")
@JsonProperty("end-area")
var endArea: Any? = null
@get:JsonProperty("ipis")
@set:JsonProperty("ipis")
@JsonProperty("ipis")
var ipis: List<Any>? = null
@get:JsonProperty("type-id")
@set:JsonProperty("type-id")
@JsonProperty("type-id")
var typeId: String? = null
@get:JsonProperty("life-span")
@set:JsonProperty("life-span")
@JsonProperty("life-span")
var lifeSpan: ArtistGetLifeSpan? = null
@get:JsonProperty("isnis")
@set:JsonProperty("isnis")
@JsonProperty("isnis")
var isnis: List<String>? = null
@get:JsonProperty("country")
@set:JsonProperty("country")
@JsonProperty("country")
var country: String? = null
} | apache-2.0 | dfbaaa09eb50d35b78bacfeeafa2fb65 | 23.733333 | 73 | 0.644838 | 3.713877 | false | false | false | false |
SoulBeaver/kindinium | src/main/kotlin/com/sbg/vindinium/kindinium/VindiniumClient.kt | 1 | 4203 | /*
Copyright 2014 Christian Broomfield
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.sbg.vindinium.kindinium
import java.net.URL
import javax.ws.rs.client.ClientBuilder
import javax.ws.rs.core.MediaType
import com.google.gson.Gson
import com.sbg.vindinium.kindinium.model.Response
import javax.ws.rs.BadRequestException
import javax.ws.rs.client.WebTarget
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import javax.ws.rs.NotFoundException
import com.sbg.vindinium.kindinium.bot.Bot
import com.sbg.vindinium.kindinium.model.board.MetaBoard
import org.slf4j.LoggerFactory
/**
* Controller class that starts, runs, and terminates a session with the Vindinium server. Accepts
* and forwards the bot's decisions to the server.
*
* The VindiniumClient supports training and arena modes, and can optionally specify the maximum number of turns
* and the map on which to spar.
*/
class VindiniumClient(val bot: Bot) {
private val log = LoggerFactory.getLogger(javaClass<VindiniumClient>())!!
private val serverUrl = "http://vindinium.org/api"
private val client = ClientBuilder.newClient()!!
/**
* Play an official arena match.
*/
fun playInArenaMode() {
val url = "${serverUrl}/arena?key=${API_KEY}"
play(url)
}
/**
* Play a training game.
* @param turnsToPlay the maximum number of turns a game should last
* @param map the predefined map on which to play, or null for a random map
*/
fun playInTrainingMode(turnsToPlay: Int, map: String?) {
val url =
if (map != null)
"${serverUrl}/training?key=${API_KEY}&turns=${turnsToPlay}&map=${map}"
else
"${serverUrl}/training?key=${API_KEY}&turns=${turnsToPlay}"
play(url)
}
private fun play(startingUrl: String) {
var response = sendRequest(startingUrl)
bot.initialize(response, MetaBoard(response.game.board))
log.info("The game has started, you can view it here: ${response.viewUrl}")
log.info("Please don't exit the program until it has notified you of game completion")
while (!response.game.finished) {
log.info("Turn ${response.game.turn} of ${response.game.maxTurns}")
val metaBoard = MetaBoard(response.game.board)
val nextAction = bot.chooseAction(response, metaBoard)
response = sendRequest("${response.playUrl}?key=${API_KEY}&dir=${nextAction.name}")
}
log.info("The game has finished.")
}
private fun sendRequest(url: String): Response {
val serverTarget = client.target(url)!!
val jsonResponse = post(serverTarget)
return Gson().fromJson(jsonResponse, javaClass<Response>())!!
}
private fun post(serverTarget: WebTarget): String {
try {
return serverTarget.request(MediaType.APPLICATION_JSON)!!
.post(null, javaClass<String>())!!
} catch (e: BadRequestException) {
formatAndDisplayError(e.getResponse()!!)
throw e
} catch (e: NotFoundException) {
formatAndDisplayError(e.getResponse()!!)
throw e
}
}
private fun formatAndDisplayError(response: javax.ws.rs.core.Response) {
val entity = response.getEntity() as ByteArrayInputStream
InputStreamReader(entity).use {
log.error("There was an error with the request and the server replied: ${it.readText()}")
}
}
class object {
/*
* TODO: You must specify your own API key in order to play the game.
*/
val API_KEY = "u3d1qxgf"
}
} | apache-2.0 | f3e3bbccd1a3fa2d2721914f28a2fd9e | 32.102362 | 112 | 0.665239 | 4.297546 | false | false | false | false |
orbit/orbit | src/orbit-client/src/main/kotlin/orbit/client/net/LocalNode.kt | 1 | 1030 | /*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.client.net
import orbit.client.OrbitClientConfig
import orbit.shared.mesh.NodeCapabilities
import orbit.shared.mesh.NodeInfo
import orbit.util.concurrent.atomicSet
import java.util.concurrent.atomic.AtomicReference
internal class LocalNode(private val config: OrbitClientConfig) {
private val default = NodeData(config.grpcEndpoint, config.namespace)
private val ref = AtomicReference(
default.copy()
)
val status get() = ref.get()!!
fun manipulate(body: (NodeData) -> NodeData) = ref.atomicSet(body)!!
fun reset() {
manipulate {
default.copy()
}
}
}
internal data class NodeData(
val grpcEndpoint: String,
val namespace: String,
val nodeInfo: NodeInfo? = null,
val capabilities: NodeCapabilities? = null,
val clientState: ClientState = ClientState.IDLE
) | bsd-3-clause | 5353c23f22bce33321e113938fb0edad | 25.435897 | 73 | 0.708738 | 4.071146 | false | true | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/pools/Pools.kt | 1 | 8007 | package com.binarymonks.jj.core.pools
import com.badlogic.gdx.math.Matrix3
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.math.Vector3
import com.badlogic.gdx.utils.Array
import com.badlogic.gdx.utils.ObjectMap
import com.badlogic.gdx.utils.ObjectSet
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.api.PoolsAPI
import com.binarymonks.jj.core.pools.managers.Matrix3PoolManager
import com.binarymonks.jj.core.pools.managers.Vector2PoolManager
import com.binarymonks.jj.core.pools.managers.Vector3PoolManager
import com.binarymonks.jj.core.specs.InstanceParams
import com.binarymonks.jj.core.specs.ParamsPoolManager
import kotlin.reflect.KClass
/**
* Get a new instance of a pooled class
*
* @param pooledClass the class of the object that is pooled
* *
* @return an instance of the pooled class
**/
fun <T> new(clazz: Class<T>): T {
return JJ.B.pools.nuw(clazz)
}
/**
* Get a new instance of a pooled class
*
* @param pooledClass the class of the object that is pooled
* *
* @return an instance of the pooled class
**/
fun <T : Any> new(pooledClass: KClass<T>): T {
return new(pooledClass.java)
}
/**
* Get a new instance of an ObjectMap from a pool
*/
fun <K, V> newObjectMap(): ObjectMap<K, V> {
return JJ.B.pools.nuwObjectMap()
}
/**
* Get a new instance of an ObjectSet from a pool
*/
fun <T> newObjectSet(): ObjectSet<T> {
return JJ.B.pools.nuwObjectSet()
}
/**
*
*/
fun <T> newArray(): Array<T> {
return JJ.B.pools.nuwArray()
}
/**
* Recycle a pooled object
*/
fun recycle(vararg objects: Any) {
for (o in objects) {
JJ.B.pools.recycle(o)
}
}
/**
* Recycle a collection of pooled objects
*/
fun recycleItems(collectionOfObjects: Iterable<*>) {
for (o in collectionOfObjects) {
if (o != null) recycle(o)
}
}
@Suppress("UNCHECKED_CAST")
/**
* A place to manage your pools and pooled objects.
*
* If your scene is [Poolable] then you can just get new ones and recycle old ones here.
* If not - A [PoolManager] must be registered.
*
* Once you have that you can use [new], [recycle] and [recycleItems] to deal with your pooled objects
*/
class Pools : PoolsAPI {
internal var pools = ObjectMap<Class<*>, Pool<*>>()
internal var poolablePools = ObjectMap<Class<*>, Array<Poolable>>()
internal var objectMapPool = Array<ObjectMap<*, *>>()
internal var objectSetPool = Array<ObjectSet<*>>()
internal var arrayPool = Array<Array<*>>()
init {
registerManager(Vector2PoolManager(), Vector2::class.java)
registerManager(Vector3PoolManager(), Vector3::class.java)
registerManager(Matrix3PoolManager(), Matrix3::class.java)
registerManager(ParamsPoolManager(), InstanceParams::class.java)
}
/**
* Get something from the pool or make a new one.
*
*
* If your scene is [Poolable] then all is done for you.
* If not - A [PoolManager] must be registered.
*
*
* There is a nice little convenience function with much less to type [new]
* Be sure to [recycle] it when you are done.
* @param pooledClass the class of the object that is pooled
* *
* @return an instance of the pooled class
**/
fun <T> nuw(pooledClass: Class<T>): T {
if (Poolable::class.java.isAssignableFrom(pooledClass)) {
return nuwPoolable(pooledClass)
}
if (!pools.containsKey(pooledClass)) {
throw NoPoolManagerException(pooledClass)
} else {
return pools.get(pooledClass).getPooled() as T
}
}
/**
* Get something from the pool or make a new one.
*
*
* If your scene is [Poolable] then all is done for you.
* If not - A [PoolManager] must be registered.
*
*
* There is a nice little convenience function with much less to type [new]
* Be sure to [recycle] it when you are done.
* @param pooledClass the class of the object that is pooled
* *
* @return an instance of the pooled class
**/
fun <T : Any> nuw(pooledClass: KClass<T>): T {
return nuw(pooledClass.java)
}
private fun <T> nuwPoolable(pooledClass: Class<T>): T {
if (poolablePools.containsKey(pooledClass) && poolablePools.get(pooledClass).size > 0) {
return poolablePools.get(pooledClass).pop() as T
} else {
try {
return pooledClass.newInstance()
} catch (e: InstantiationException) {
throw CouldNotCreateOneException(pooledClass)
} catch (e: IllegalAccessException) {
throw CouldNotCreateOneException(pooledClass)
}
}
}
/**
* Recycle the used pooled object. A [PoolManager] must be registered.
* There is a nice little convenience function with much less to type [recycle]
* @param pooled
*/
fun recycle(pooled: Any) {
if (pooled is ObjectMap<*, *>) {
pooled.clear()
objectMapPool.add(pooled)
return
}
if (pooled is Array<*>) {
pooled.clear()
arrayPool.add(pooled)
return
}
if (pooled is ObjectSet<*>) {
pooled.clear()
objectSetPool.add(pooled)
return
}
if (pooled is Poolable) {
recyclePoolable(pooled)
return
}
if (!pools.containsKey(pooled.javaClass)) {
throw NoPoolManagerException(pooled.javaClass)
} else {
pools.get(pooled.javaClass).add(pooled)
}
}
private fun recyclePoolable(pooled: Poolable) {
if (!poolablePools.containsKey(pooled.javaClass)) {
poolablePools.put(pooled.javaClass, Array<Poolable>())
}
poolablePools.get(pooled.javaClass).add(pooled)
pooled.reset()
}
/**
* Use this if you want to dump the pooled objects.
* They will be disposed by the PoolManager before being removed from the pool.
* @param clazzToClear
*/
override fun clearPool(clazzToClear: Class<*>) {
pools.get(clazzToClear).clear()
}
/**
* Use this if you want to dump the pooled objects.
* They will be disposed by the PoolManager before being removed from the pool.
* @param clazzToClear
*/
override fun clearPool(clazzToClear: KClass<*>) {
pools.get(clazzToClear.java).clear()
}
override fun <P, T : PoolManager<P>> registerManager(poolManager: T, sceneToPoolClass: Class<P>) {
if (!pools.containsKey(sceneToPoolClass)) {
pools.put(sceneToPoolClass, Pool(poolManager))
}
}
fun <K, V> nuwObjectMap(): ObjectMap<K, V> {
if (objectMapPool.size > 0) {
val map = objectMapPool.pop()
map.clear()
return map as ObjectMap<K, V>
}
return ObjectMap()
}
fun <T> nuwArray(): Array<T> {
if (arrayPool.size > 0) {
val array = arrayPool.pop()
array.clear()
return array as Array<T>
}
return Array()
}
fun <T> nuwObjectSet(): ObjectSet<T> {
if (objectSetPool.size > 0) {
val set = objectSetPool.pop()
set.clear()
return set as ObjectSet<T>
}
return ObjectSet()
}
class NoPoolManagerException(classWithMissingPool: Class<*>) : RuntimeException(String.format("No PoolManager for %s. Register a pool manager.", classWithMissingPool.canonicalName))
class CouldNotCreateOneException(noDefault: Class<*>) : RuntimeException(String.format("Could not access a default constructor for %s", noDefault.canonicalName))
}
| apache-2.0 | 6c61e7685bf66f8e8c8e3bcab071f038 | 28.215094 | 185 | 0.604721 | 4.070666 | false | false | false | false |
JanYoStudio/WhatAnime | app/src/main/java/pw/janyo/whatanime/config/Configure.kt | 1 | 1547 | package pw.janyo.whatanime.config
import android.content.Context
import com.tencent.mmkv.MMKV
import pw.janyo.whatanime.BuildConfig
import pw.janyo.whatanime.model.entity.NightMode
object Configure {
private val kv = MMKV.mmkvWithID("configure", Context.MODE_PRIVATE)!!
var lastVersion: Int
set(value) {
kv.encode("config_last_version", value)
}
get() = kv.decodeInt("config_last_version", 0)
var hideSex: Boolean
set(value) {
kv.encode("config_hide_sex", value)
}
get() = kv.decodeBool("config_hide_sex", true)
var apiKey: String
set(value) {
kv.encode("config_api_key", value)
}
get() = kv.decodeString("config_api_key", "")!!
var allowSendCrashReport: Boolean
set(value) {
kv.encode("allowSendCrashReport", value)
}
get() = kv.decodeBool("allowSendCrashReport", !BuildConfig.DEBUG)
var nightMode: NightMode
set(value) {
kv.encode("nightMode", value.value)
}
get() {
val value = kv.decodeInt("nightMode", NightMode.AUTO.value)
return NightMode.values().first { it.value == value }
}
var showChineseTitle: Boolean
set(value) {
kv.encode("showChineseTitle", value)
}
get() = kv.decodeBool("showChineseTitle", true)
var cutBorders: Boolean
set(value) {
kv.encode("cutBorders", value)
}
get() = kv.decodeBool("cutBorders", true)
} | apache-2.0 | acd7b50c492a6be2c4b5cda9f571eedb | 30.591837 | 73 | 0.590175 | 3.987113 | false | true | false | false |
jjoller/foxinabox | src/jjoller/foxinabox/Odds.kt | 1 | 1229 | package jjoller.foxinabox
import java.util.*
/**
* Created by jost on 2/20/16.
*/
public class Odds() {
public fun pWin(holeCards: EnumSet<Card>, tableCards: EnumSet<Card>, numOpponents: Int): Double {
return 0.0;
}
private fun encode(holeCards: EnumSet<Card>, tableCards: EnumSet<Card>, numOpponents: Long): Long {
var suitMap: MutableMap<Card.CardSuit, Card.CardSuit> = HashMap()
val holeCardIterator = holeCards.iterator()
val cards = ArrayList<Card>();
cards.add(map(holeCardIterator.next(), suitMap))
cards.add(map(holeCardIterator.next(), suitMap))
val tableCardIterator = tableCards.iterator()
while (tableCardIterator.hasNext())
cards.add(map(tableCardIterator.next(), suitMap))
var code: Long = numOpponents - 1
for (i in cards.indices) {
val card = cards[i];
}
return code
}
private fun map(card: Card, map: MutableMap<Card.CardSuit, Card.CardSuit>): Card {
if (!map.containsKey(card.suit))
map.put(card.suit, Card.CardSuit.values()[map.size])
val suit: Card.CardSuit = map[card.suit]!!
return Card.get(card.value, suit);
}
} | mit | 630d3282ff21936990f2581be2eabb84 | 27.604651 | 103 | 0.624898 | 3.735562 | false | false | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/background/CopyToClipboardReceiver.kt | 1 | 1391 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.background
import android.content.BroadcastReceiver
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.util.Log
import org.openhab.habdroid.R
import org.openhab.habdroid.util.showToast
class CopyToClipboardReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val toCopy = intent.getStringExtra(EXTRA_TO_COPY) ?: return
Log.d(TAG, "Copy to clipboard: $toCopy")
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(context.getString(R.string.app_name), toCopy)
clipboard.setPrimaryClip(clip)
context.showToast(context.getString(R.string.copied_item_name, toCopy))
}
companion object {
private val TAG = CopyToClipboardReceiver::class.java.simpleName
const val EXTRA_TO_COPY = "extra_to_copy"
}
}
| epl-1.0 | 6f65c91783a66f0c31e51a215ce94134 | 34.666667 | 95 | 0.746945 | 4.103245 | false | false | false | false |
SzymonGrochowiak/Android-Kotlin-Starter-Pack | app/src/main/java/com/szymongrochowiak/androidkotlinstarterpack/data/network/NetworkTransformers.kt | 1 | 1482 | package com.szymongrochowiak.androidkotlinstarterpack.data.network
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import java.io.IOException
/**
* @author Szymon Grochowiak
*/
fun <T> applyTransformations(vararg transformers: ObservableTransformer<T, T>): ObservableTransformer<T, T> {
return ObservableTransformer { observable ->
var resultObservable = observable
for (transformer in transformers) {
resultObservable = resultObservable.compose(transformer)
}
resultObservable
}
}
fun <T> applySchedulers() = ObservableTransformer<T, T> {
it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
}
fun <T> applyOnErrorResumeNext() = ObservableTransformer<T, T> {
it.onErrorResumeNext(Function { throwable ->
if (throwable is IOException) Observable.empty<T>() else Observable.error<T>(throwable)
})
}
/*
fun <T> applySaveLocally(repositoryWriter: RepositoryWriter): ObservableTransformer<T, T> {
return { observable ->
observable.map({ `object` ->
val savedObject = repositoryWriter.saveToRepository(`object`)
savedObject ?: `object`
})
}
}
*/
fun <T> applyConnectionRetires(connectionRetries: Int) = ObservableTransformer<T, T> {
it.retry(connectionRetries.toLong())
} | apache-2.0 | d6f0069cdd15048ce64b94e4f69eed1c | 31.23913 | 109 | 0.726046 | 4.371681 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.