repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/social/GenderCommand.kt
|
1
|
2926
|
package net.perfectdreams.loritta.morenitta.commands.vanilla.social
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.extensions.isEmote
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.morenitta.utils.locale.Gender
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.utils.onReactionAddByAuthor
import net.dv8tion.jda.api.EmbedBuilder
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.extensions.addReaction
class GenderCommand(loritta: LorittaBot) : AbstractCommand(loritta, "gender", listOf("gênero", "genero"), net.perfectdreams.loritta.common.commands.CommandCategory.SOCIAL) {
override fun getDescriptionKey() = LocaleKeyData("commands.command.gender.description")
override suspend fun run(context: CommandContext, locale: BaseLocale) {
OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "gender")
val embed = EmbedBuilder()
.setTitle(locale["commands.command.gender.whatAreYou"])
.setDescription(locale["commands.command.gender.whyShouldYouSelect"])
.build()
val message = context.sendMessageEmbeds(embed)
message.addReaction("male:384048518853296128").queue()
message.addReaction("female:384048518337265665").queue()
message.addReaction("❓").queue()
message.onReactionAddByAuthor(context) {
message.delete().queue()
if (it.emoji.asCustom().id == "384048518853296128") {
loritta.newSuspendedTransaction {
context.lorittaUser.profile.settings.gender = Gender.MALE
}
context.reply(
LorittaReply(
locale["commands.command.gender.successfullyChanged"],
"\uD83C\uDF89"
)
)
}
if (it.emoji.asCustom().id == "384048518337265665") {
loritta.newSuspendedTransaction {
context.lorittaUser.profile.settings.gender = Gender.FEMALE
}
context.reply(
LorittaReply(
locale["commands.command.gender.successfullyChanged"],
"\uD83C\uDF89"
)
)
}
if (it.emoji.isEmote("❓")) {
loritta.newSuspendedTransaction {
context.lorittaUser.profile.settings.gender = Gender.UNKNOWN
}
context.reply(
LorittaReply(
locale["commands.command.gender.successfullyChanged"],
"\uD83C\uDF89"
)
)
}
}
}
}
|
agpl-3.0
|
96fb1aed1de1b0fc36b94860ace7cdef
| 36.461538 | 173 | 0.676138 | 4.68109 | false | false | false | false |
LorittaBot/Loritta
|
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/Backgrounds.kt
|
1
|
978
|
package net.perfectdreams.loritta.cinnamon.pudding.tables
import net.perfectdreams.loritta.common.utils.Rarity
import net.perfectdreams.loritta.cinnamon.pudding.utils.exposed.array
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IdTable
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.TextColumnType
object Backgrounds : IdTable<String>() {
val internalName = text("internal_name")
override val id: Column<EntityID<String>> = internalName.entityId()
val enabled = bool("enabled").index()
val rarity = enumeration("rarity", Rarity::class).index()
val createdBy = array<String>("created_by", TextColumnType())
val availableToBuyViaDreams = bool("available_to_buy_via_dreams").index()
val availableToBuyViaMoney = bool("available_to_buy_via_money").index()
val set = optReference("set", Sets)
val addedAt = long("added_at").default(-1L)
override val primaryKey = PrimaryKey(id)
}
|
agpl-3.0
|
5f8a9df18a1e31a67075a5de49ce4612
| 41.565217 | 77 | 0.755624 | 3.943548 | false | false | false | false |
angcyo/RLibrary
|
uiview/src/main/java/com/angcyo/uiview/game/GameRenderView.kt
|
1
|
11299
|
package com.angcyo.uiview.game
import android.animation.Animator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import android.util.AttributeSet
import android.util.SparseArray
import android.view.MotionEvent
import android.view.View
import android.view.animation.LinearInterpolator
import com.angcyo.library.utils.L
import com.angcyo.uiview.R
import com.angcyo.uiview.game.layer.BaseLayer
import com.angcyo.uiview.kotlin.density
import com.angcyo.uiview.resources.RAnimListener
import com.angcyo.uiview.skin.SkinHelper
import com.angcyo.uiview.utils.RUtils
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicBoolean
/**
* Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved.
* 项目名称:
* 类的描述:按照60帧的速度一直绘制的游戏渲染View
* 创建人员:Robi
* 创建时间:2017/12/15 10:41
* 修改人员:Robi
* 修改时间:2017/12/15 10:41
* 修改备注:
* Version: 1.0.0
*/
class GameRenderView(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet) {
val layerList = CopyOnWriteArrayList<BaseLayer>()
/**允许的触击点个数, -1不限制*/
var maxTouchPoint = -1
/**onDetachedFromWindow*/
var isGameViewDetached = true
/**是否在渲染中*/
@Volatile
var isGameRenderStart = false
/**暂停游戏渲染, 数据更新线程还在进行*/
var pauseGameRender: AtomicBoolean = AtomicBoolean(false)
/**暂停游戏数据更新线程*/
var pauseGameRenderThread: AtomicBoolean = AtomicBoolean(false)
/**界面显示时, 是否开始渲染*/
var autoStartRender = true
companion object {
var SHOW_DEBUG = L.LOG_DEBUG
}
init {
val array = context.obtainStyledAttributes(attributeSet, R.styleable.GameRenderView)
maxTouchPoint = array.getInt(R.styleable.GameRenderView_r_max_touch_point, maxTouchPoint)
autoStartRender = array.getBoolean(R.styleable.GameRenderView_r_auto_start_render, autoStartRender)
array.recycle()
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
isGameViewDetached = false
startRenderInner()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
isGameViewDetached = true
endRender()
}
override fun onVisibilityChanged(changedView: View?, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (visibility == View.VISIBLE) {
startRenderInner()
} else {
endRender()
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
for (i in 0 until layerList.size) {
layerList[i].onSizeChanged(w, h, oldw, oldh)
}
startRenderInner()
}
/**暂停渲染, 暂停数据线程*/
fun pauseGame() {
pauseGameRender.set(true)
pauseGameRenderThread.set(true)
}
/*多点控制*/
private val pointList = SparseArray<PointF>()
private val pointColorList = SparseArray<Int>()
/*触摸点偏差多少距离算点击事件*/
private val deviation = 10 * density
// override fun dispatchTouchEvent(event: MotionEvent): Boolean {
// val actionIndex = event.actionIndex
// val id = event.getPointerId(actionIndex)
//
// if (event.actionMasked == MotionEvent.ACTION_DOWN ||
// event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) {
// L.e("call: dispatchTouchEvent -> $id $event")
// }
//
// return super.dispatchTouchEvent(event)
// }
override fun onTouchEvent(event: MotionEvent): Boolean {
val actionIndex = event.actionIndex
val id = event.getPointerId(actionIndex)
val eventX = event.getX(actionIndex)
val eventY = event.getY(actionIndex)
when (event.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
//L.e("call: dispatchTouchEvent -> _$id $event")
if (maxTouchPoint > 0) {
if (pointList.size() < maxTouchPoint) {
pointList.put(id, PointF(eventX, eventY))
pointColorList.put(id, RUtils.randomColor(random, 0, 255))
}
} else {
pointList.put(id, PointF(eventX, eventY))
pointColorList.put(id, RUtils.randomColor(random, 0, 255))
}
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
val p = pointList.get(id)
p?.let {
if (Math.abs(it.x - eventX) < deviation &&
Math.abs(it.y - eventY) < deviation) {
for (i in layerList.size - 1 downTo 0) {
val touchEvent = layerList[i].onTouchEvent(event, it)
if (touchEvent) {
break
}
}
}
pointList.remove(id)
pointColorList.remove(id)
}
}
}
return true /*super.onTouchEvent(event)*/
}
private var showFps = L.LOG_DEBUG
private val fpsPaint: Paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = 14 * density
color = SkinHelper.getSkin().themeSubColor
strokeWidth = 1 * density
style = Paint.Style.FILL_AND_STROKE
}
}
private fun time(): Long = System.currentTimeMillis()
private var lastRenderTime = 0L
private var lastRenderTimeThread = 0L
protected val random: Random by lazy {
Random(System.nanoTime())
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (!pauseGameRender.get()) {
val nowTime = time()
for (i in 0 until layerList.size) {
val layer = layerList[i]
if (layer.isRenderStart) {
layer.draw(canvas, gameRenderStartTime, lastRenderTime, nowTime)
}
}
lastRenderTime = nowTime
}
if (SHOW_DEBUG) {
canvas.save()
for (i in 0 until pointList.size()) {
val pointF = pointList.get(pointList.keyAt(i))
fpsPaint.color = pointColorList.get(pointList.keyAt(i))
canvas.drawLine(0f, pointF.y, measuredWidth.toFloat(), pointF.y, fpsPaint)
canvas.drawLine(pointF.x, 0f, pointF.x, measuredHeight.toFloat(), fpsPaint)
}
canvas.restore()
}
if (showFps && !isInEditMode) {
val text = fpsText
fpsPaint.color = SkinHelper.getSkin().themeSubColor
canvas.drawText(text, 10 * density, measuredHeight - 10 * density, fpsPaint)
}
}
private var fps = 0
private var fpsText = ""
private val renderAnim: ValueAnimator by lazy {
ValueAnimator.ofInt(0, 60).apply {
interpolator = LinearInterpolator()
repeatMode = ValueAnimator.RESTART
repeatCount = ValueAnimator.INFINITE
duration = 1000
addListener(object : RAnimListener() {
override fun onAnimationRepeat(animation: Animator?) {
super.onAnimationRepeat(animation)
fpsText = "$fps"
//L.e("call: onAnimationRepeat -> fps:$fpsText")
fps = 0
}
})
addUpdateListener {
fps++
postInvalidateOnAnimation()
}
}
}
/*开始渲染的时间*/
private var gameRenderStartTime = 0L
private fun startRenderInner() {
if (autoStartRender) {
startRender()
}
}
/*开始渲染界面*/
fun startRender() {
L.e("startRender -> w:$measuredWidth h:$measuredHeight detach:$isGameViewDetached v:$visibility isRenderStart:$isGameRenderStart isAnimStart:${renderAnim.isStarted}")
if (measuredWidth == 0 || measuredHeight == 0) {
isGameRenderStart = false
return
}
if (isGameViewDetached) {
isGameRenderStart = false
return
}
if (visibility != View.VISIBLE) {
isGameRenderStart = false
return
}
if (isGameRenderStart) {
return
}
isGameRenderStart = true
fps = 0
if (renderAnim.isStarted) {
} else {
gameRenderStartTime = time()
renderAnim.start()
}
for (i in 0 until layerList.size) {
try {
layerList[i].onRenderStart(this)
} catch (e: Exception) {
e.printStackTrace()
}
}
//开始渲染子线程
RenderThread().apply {
start()
}
}
/**结束渲染*/
fun endRender() {
if (isGameRenderStart) {
isGameRenderStart = false
gameRenderStartTime = 0L
renderAnim.cancel()
for (i in 0 until layerList.size) {
try {
layerList[i].onRenderEnd(this)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
fun addLayer(layer: BaseLayer) {
layerList.add(layer)
}
fun clearLayer() {
layerList.clear()
}
/**子线程用来计算游戏数据*/
inner class RenderThread : Thread() {
init {
name = "GameRenderThread"
priority = NORM_PRIORITY
}
override fun run() {
super.run()
while (isGameRenderStart) {
try {
if (!pauseGameRenderThread.get()) {
val nowTime = time()
for (i in 0 until layerList.size) {
val layer = layerList[i]
if (layer.isRenderStart) {
layer.drawThread(gameRenderStartTime, lastRenderTimeThread, nowTime)
}
}
lastRenderTimeThread = nowTime
}
Thread.sleep(16) //60帧速率 回调
//L.e("call: renderThread -> $id $name")
} catch (e: Exception) {
e.printStackTrace()
}
}
interrupt()
yield()
}
}
}
|
apache-2.0
|
6daa17890b5a3926e64608d1dd98dfbd
| 29.309456 | 174 | 0.533089 | 4.834071 | false | false | false | false |
gotev/recycler-adapter
|
recycleradapter-extensions/src/main/java/net/gotev/recycleradapter/ext/NestedRecyclerAdapterItem.kt
|
1
|
1495
|
package net.gotev.recycleradapter.ext
import android.content.Context
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.HORIZONTAL
import net.gotev.recycleradapter.AdapterItem
import net.gotev.recycleradapter.RecyclerAdapter
import net.gotev.recycleradapter.RecyclerAdapterViewHolder
/**
* @author Aleksandar Gotev
*/
abstract class NestedRecyclerAdapterItem<T : NestedRecyclerAdapterItem.Holder>(
val recyclerAdapter: RecyclerAdapter,
val recycledViewsPool: RecyclerView.RecycledViewPool?,
model: Any
) : AdapterItem<T>(model) {
override fun getView(parent: ViewGroup) = parent.inflating(R.layout.item_nested)
open fun getLayoutManager(context: Context): RecyclerView.LayoutManager =
LinearLayoutManager(context, HORIZONTAL, false)
override fun bind(firstTime: Boolean, holder: T) {
with(holder.recyclerView) {
// reset layout manager and adapter
layoutManager = null
adapter = null
layoutManager = getLayoutManager(context)
adapter = recyclerAdapter
recycledViewsPool?.let {
setRecycledViewPool(it)
}
}
}
open class Holder(itemView: View) : RecyclerAdapterViewHolder(itemView) {
val recyclerView: RecyclerView = itemView.findViewById(R.id.recycler_view)
}
}
|
apache-2.0
|
448c3367b12be7253f0de908b34e9f54
| 32.977273 | 84 | 0.73311 | 5.016779 | false | false | false | false |
nebula-plugins/java-source-refactor
|
rewrite-java/src/test/kotlin/org/openrewrite/java/refactor/RenameVariableTest.kt
|
1
|
2093
|
/*
* Copyright 2020 the original 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.openrewrite.java.refactor
import org.junit.jupiter.api.Test
import org.openrewrite.java.JavaParser
import org.openrewrite.java.assertRefactored
import org.openrewrite.java.tree.J
open class RenameVariableTest : JavaParser() {
@Test
fun renameVariable() {
val a = parse("""
public class B {
int n;
{
int n;
n = 1;
n /= 2;
if(n + 1 == 2) {}
n++;
}
public int foo(int n) {
return n + this.n;
}
}
""".trimIndent())
val blockN = (a.classes[0].body.statements[1] as J.Block<*>).statements[0] as J.VariableDecls
val paramN = (a.classes[0].methods[0]).params.params[0] as J.VariableDecls
val fixed = a.refactor()
.visit(RenameVariable(blockN.vars[0], "n1"))
.visit(RenameVariable(paramN.vars[0], "n2"))
.fix().fixed
assertRefactored(fixed, """
public class B {
int n;
{
int n1;
n1 = 1;
n1 /= 2;
if(n1 + 1 == 2) {}
n1++;
}
public int foo(int n2) {
return n2 + this.n;
}
}
""")
}
}
|
apache-2.0
|
a4ad70532f18d5fdfcd1e5b8f45ed2a0
| 28.914286 | 101 | 0.498806 | 4.397059 | false | false | false | false |
DevCharly/kotlin-ant-dsl
|
converter/src/main/kotlin/com/devcharly/kotlin/ant/converter/Main.kt
|
1
|
3666
|
/*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant.converter
import java.io.FileReader
import java.io.FileWriter
const val NAME = "[\\w-_.]+"
const val STRING = "\"[^\"]*?\""
const val WHITESPACES_OPT = "(?:\\s*)"
const val ATTRIBUTE = "(${NAME})${WHITESPACES_OPT}=${WHITESPACES_OPT}(${STRING})"
const val ATTRIBUTES = "(${ATTRIBUTE}${WHITESPACES_OPT})*"
const val TAG = "<(${NAME})${WHITESPACES_OPT}(${ATTRIBUTES})/>"
const val TAG_OPEN = "<(${NAME})${WHITESPACES_OPT}(${ATTRIBUTES})>"
const val TAG_CLOSE = "</(${NAME})>"
const val PARENTHESIS_SPACE = ""
/**
* Converts Ant XML files to Kotlin Ant DSL.
*
* The primary goal is support migration of Ant builds to Kotlin based build systems (e.g. Kobalt)
*
* Note that Kotlin Ant DSL does not support some Ant tags (e.g. <project> and <target>).
* So you can not compile/run the output, but you can copy the parts that you need.
*
* Uses simple regex string manipulation to preserve formatting.
*/
fun main(args: Array<String>) {
args.forEach { convertAntXml2Kotlin(it) }
}
fun convertAntXml2Kotlin(fileName: String) {
println("Convert $fileName")
// read Ant XML file
var s = FileReader(fileName).readText()
// determine used line separator
val lineSeparator = if (s.contains("\r\n")) "\r\n" else "\n"
// <?xml version="1.0"?>
s = s.replace(Regex("^\\s*<\\?xml.*\\?>\\s*"), "")
// comments
s = s.replace(Regex("<!--(.+?)-->", RegexOption.DOT_MATCHES_ALL), "/*$1*/")
// top-level elements must be assigned to a val in Kotlin
s = s.replace("<project", "val p = <project")
// tag
s = s.replace(Regex(TAG), { match ->
val name = match.groupValues[1].toLowerCase()
val params = attrs2params(match.groupValues[2])
"$name($PARENTHESIS_SPACE$params$PARENTHESIS_SPACE)"
})
// open tag
s = s.replace(Regex(TAG_OPEN), { match ->
val name = match.groupValues[1]
val params = attrs2params(match.groupValues[2])
if (params.isEmpty())
"$name {"
else
"$name($PARENTHESIS_SPACE$params$PARENTHESIS_SPACE) {"
})
// close tag
s = s.replace(Regex(TAG_CLOSE), "}")
// insert imports
s = "import com.devcharly.kotlin.ant.*$lineSeparator$lineSeparator$s"
// write Kotlin file
val kotlinFileName = fileName.removeSuffix(".xml") + ".kt"
println(" to $kotlinFileName")
FileWriter(kotlinFileName).apply {
write(s)
flush()
}
}
private fun attrs2params(attrs: String): String {
var s = attrs.replace(Regex("(?:${ATTRIBUTE})(${WHITESPACES_OPT})"), { match ->
"${match.groupValues[1].toLowerCase()} = ${attr2paramValue(match.groupValues[2])},${match.groupValues[3]}"
})
// remove trailing ',', but keep whitespace (in case it contains line separator
s = s.replace(Regex(",(\\s*)$"), "$1")
// remove trailing spaces
s = s.trimEnd(' ')
return s
}
private fun attr2paramValue(attrValue: String): String {
return when(attrValue) {
"\"true\"" -> "true"
"\"false\"" -> "false"
"\"yes\"" -> "true"
"\"no\"" -> "false"
// replace "${ant.property}" with "${p("ant.property")}"
else -> attrValue.replace(Regex("\\$\\{([^}]*)\\}"), "\\\${p(\"$1\")}")
}
}
|
apache-2.0
|
c8e166a801c24864933e1fc76069fd42
| 28.804878 | 108 | 0.654937 | 3.363303 | false | false | false | false |
danrien/projectBlue
|
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/fakes/ResolvablePlaybackHandler.kt
|
2
|
1055
|
package com.lasthopesoftware.bluewater.client.playback.file.fakes
import com.lasthopesoftware.bluewater.client.playback.file.PlayedFile
import com.lasthopesoftware.bluewater.shared.promises.extensions.ProgressedPromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.Messenger
import com.namehillsoftware.handoff.promises.MessengerOperator
import com.namehillsoftware.handoff.promises.Promise
import org.joda.time.Duration
class ResolvablePlaybackHandler : FakeBufferingPlaybackHandler() {
private val promise: ProgressedPromise<Duration, PlayedFile> = object : ProgressedPromise<Duration, PlayedFile>(MessengerOperator { messenger -> resolve = messenger }) {
override val progress: Promise<Duration>
get() = Duration.millis(backingCurrentPosition.toLong()).toPromise()
}
private var resolve: Messenger<PlayedFile>? = null
override fun promisePlayedFile(): ProgressedPromise<Duration, PlayedFile> = promise
fun resolve() {
resolve?.sendResolution(this)
resolve = null
}
}
|
lgpl-3.0
|
73548d281f39138884ee7de10cfecbe3
| 41.2 | 170 | 0.823697 | 4.414226 | false | false | false | false |
TouK/bubble
|
bubble/src/main/java/pl/touk/android/bubble/Bubble.kt
|
1
|
4577
|
/*
* Copyright 2015 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 pl.touk.android.bubble
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import pl.touk.android.bubble.coordinates.Coordinates
import pl.touk.android.bubble.coordinates.CoordinatesCalculator
import pl.touk.android.bubble.listener.BubbleListener
import pl.touk.android.bubble.orientation.Orientation
import pl.touk.android.bubble.state.BubbleStateMachine
import rx.Observable
import rx.subjects.PublishSubject
public class Bubble: SensorEventListener {
companion object {
private val SAMPLE_SIZE = 20
}
enum class Registration { UNREGISTERED, LISTENER, OBSERVER }
var orientationPublisher: PublishSubject<BubbleEvent>? = null
var bubbleListener: BubbleListener? = null
lateinit private var accelerometerSensor: Sensor
lateinit private var magneticSensor: Sensor
lateinit private var sensorManager: SensorManager
lateinit private var coordinatesPublisher: PublishSubject<Coordinates>
private val orientationStateMachine = BubbleStateMachine()
private val coordinatesCalculator = CoordinatesCalculator()
var registration = Registration.UNREGISTERED
public fun register(context: Context): Observable<BubbleEvent> {
orientationPublisher = PublishSubject.create()
registration = Registration.OBSERVER
setupAndRegisterSensorsListeners(context)
return orientationPublisher!!
}
public fun register(bubbleListener: BubbleListener, context: Context) {
this.bubbleListener = bubbleListener
registration = Registration.LISTENER
setupAndRegisterSensorsListeners(context)
}
private fun setupAndRegisterSensorsListeners(context: Context) {
coordinatesPublisher = PublishSubject.create()
coordinatesPublisher
.buffer(SAMPLE_SIZE)
.map { coordinates: List<Coordinates> -> coordinatesCalculator.calculateAverage(coordinates) }
.subscribe { coordinates: Coordinates ->
if (orientationStateMachine.update(coordinates)) {
informClient(orientationStateMachine.orientation)
}
}
loadSensors(context)
sensorManager.registerListener(this, accelerometerSensor, SensorManager.SENSOR_DELAY_UI)
sensorManager.registerListener(this, magneticSensor, SensorManager.SENSOR_DELAY_UI)
}
private fun informClient(orientation: Orientation) {
if (registration == Registration.OBSERVER) {
orientationPublisher!!.onNext(BubbleEvent(orientation))
} else {
bubbleListener!!.onOrientationChanged(BubbleEvent(orientation))
}
}
override fun onSensorChanged(sensorEvent: SensorEvent) {
coordinatesPublisher.onNext(coordinatesCalculator.calculate(sensorEvent))
}
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
private fun loadSensors(context: Context) {
sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
magneticSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)
}
public fun unregister() {
sensorManager.unregisterListener(this)
ifRegistered() {
coordinatesPublisher.onCompleted()
if (registration == Registration.OBSERVER) {
orientationPublisher!!.onCompleted()
} else {
bubbleListener = null
}
}
}
inline fun ifRegistered(action: () -> Unit) {
if (registration != Registration.UNREGISTERED) {
action.invoke()
} else {
throw IllegalStateException("Detector must be registered before use.")
}
}
}
|
apache-2.0
|
7e93ea5c18f217ff7ea94a6baeaa9af4
| 35.624 | 110 | 0.70898 | 5.346963 | false | false | false | false |
wireapp/wire-android
|
app/src/main/kotlin/com/waz/zclient/core/network/api/token/TokenService.kt
|
1
|
974
|
package com.waz.zclient.core.network.api.token
import com.waz.zclient.core.exception.Failure
import com.waz.zclient.core.functional.Either
import com.waz.zclient.core.network.ApiService
import com.waz.zclient.core.network.NetworkHandler
class TokenService(
override val networkHandler: NetworkHandler,
private val tokenApi: TokenApi
) : ApiService() {
suspend fun renewAccessToken(refreshToken: String): Either<Failure, AccessTokenResponse> =
request(AccessTokenResponse.EMPTY) {
tokenApi.access(generateCookieHeader(refreshToken))
}
suspend fun logout(refreshToken: String, accessToken: String): Either<Failure, Unit> =
request { tokenApi.logout(generateCookieHeader(refreshToken), generateTokenQuery(accessToken)) }
private fun generateTokenQuery(accessToken: String) = mapOf("access_token" to accessToken)
private fun generateCookieHeader(refreshToken: String) = mapOf("Cookie" to "zuid=$refreshToken")
}
|
gpl-3.0
|
a9e9c728094274d96c2d328bba4850a0
| 39.583333 | 104 | 0.76694 | 4.40724 | false | false | false | false |
facebook/litho
|
litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/ExperimentalTransparencyEnabledCardClip.kt
|
1
|
5180
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.litho.kotlin.widget
import android.content.Context
import android.graphics.Color
import androidx.annotation.ColorInt
import com.facebook.litho.DynamicValue
import com.facebook.litho.MeasureScope
import com.facebook.litho.MountableComponent
import com.facebook.litho.MountableComponentScope
import com.facebook.litho.MountableRenderResult
import com.facebook.litho.SimpleMountable
import com.facebook.litho.Style
import com.facebook.litho.widget.CardClipDrawable.BOTTOM_LEFT
import com.facebook.litho.widget.CardClipDrawable.BOTTOM_RIGHT
import com.facebook.litho.widget.CardClipDrawable.NONE
import com.facebook.litho.widget.CardClipDrawable.TOP_LEFT
import com.facebook.litho.widget.CardClipDrawable.TOP_RIGHT
import com.facebook.litho.widget.TransparencyEnabledCardClipDrawable
import com.facebook.rendercore.MeasureResult
private const val DEFAULT_BACKGROUND_COLOR = Color.WHITE
private const val DEFAULT_CLIPPING_COLOR = Color.TRANSPARENT
/**
* A component that paints a card with rounded edges to perform a clipping operation on the
* component being rendered below it. Used in [CardSpec] when transparencyEnabled(true).
*
* @param cardBackgroundColor Background color for the drawable.
* @param clippingColor Color for corner clipping.
* @param cornerRadius Radius for corner clipping.
* @param disableClipTopLeft If set, opt out of clipping the top-left corner.
* @param disableClipTopRight If set, opt out of clipping the top-right corner.
* @param disableClipBottomLeft If set, opt out of clipping the bottom-left corner.
* @param disableClipBottomRight If set, opt out of clipping the bottom-right corner.
*/
class ExperimentalTransparencyEnabledCardClip(
private val cardBackgroundColor: Int = DEFAULT_BACKGROUND_COLOR,
private val clippingColor: Int = DEFAULT_CLIPPING_COLOR,
private val cornerRadius: Float? = null,
private val disableClipTopLeft: Boolean = false,
private val disableClipTopRight: Boolean = false,
private val disableClipBottomLeft: Boolean = false,
private val disableClipBottomRight: Boolean = false,
@ColorInt private val dynamicCardBackgroundColor: DynamicValue<Int>? = null,
private val style: Style? = null
) : MountableComponent() {
override fun MountableComponentScope.render(): MountableRenderResult {
dynamicCardBackgroundColor?.bindTo(
DEFAULT_BACKGROUND_COLOR, TransparencyEnabledCardClipDrawable::setBackgroundColor)
return MountableRenderResult(
mountable =
TransparencyEnabledCardClipMountable(
cardBackgroundColor = cardBackgroundColor,
clippingColor = clippingColor,
cornerRadius = cornerRadius,
disableClipTopLeft = disableClipTopLeft,
disableClipTopRight = disableClipTopRight,
disableClipBottomLeft = disableClipBottomLeft,
disableClipBottomRight = disableClipBottomRight),
style = style)
}
}
internal class TransparencyEnabledCardClipMountable(
private val cardBackgroundColor: Int,
private val clippingColor: Int,
private val cornerRadius: Float? = null,
private val disableClipTopLeft: Boolean,
private val disableClipTopRight: Boolean,
private val disableClipBottomLeft: Boolean,
private val disableClipBottomRight: Boolean
) : SimpleMountable<TransparencyEnabledCardClipDrawable>(RenderType.DRAWABLE) {
override fun createContent(context: Context): TransparencyEnabledCardClipDrawable =
TransparencyEnabledCardClipDrawable()
override fun MeasureScope.measure(widthSpec: Int, heightSpec: Int): MeasureResult =
fromSpecs(widthSpec, heightSpec)
override fun mount(c: Context, content: TransparencyEnabledCardClipDrawable, layoutData: Any?) {
content.setBackgroundColor(cardBackgroundColor)
content.setClippingColor(clippingColor)
cornerRadius?.let { content.setCornerRadius(cornerRadius) }
val clipEdge =
((if (disableClipTopLeft) TOP_LEFT else NONE) or
(if (disableClipTopRight) TOP_RIGHT else NONE) or
(if (disableClipBottomLeft) BOTTOM_LEFT else NONE) or
if (disableClipBottomRight) BOTTOM_RIGHT else NONE)
content.setDisableClip(clipEdge)
}
override fun unmount(c: Context, content: TransparencyEnabledCardClipDrawable, layoutData: Any?) {
content.setBackgroundColor(DEFAULT_BACKGROUND_COLOR)
content.setClippingColor(DEFAULT_CLIPPING_COLOR)
content.setCornerRadius(0f)
content.resetCornerPaint()
content.setDisableClip(NONE)
}
}
|
apache-2.0
|
d00dedb93d59710ad42beb51072e53b9
| 43.273504 | 100 | 0.769305 | 4.966443 | false | false | false | false |
consp1racy/android-commons
|
commons/src/main/java/net/xpece/android/graphics/drawable/LazyDrawable.kt
|
1
|
4340
|
package net.xpece.android.graphics.drawable
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.PorterDuff
import android.graphics.Rect
import android.graphics.Region
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.support.v4.graphics.drawable.DrawableCompat
import net.xpece.android.content.getDrawableCompat
/**
* Drawable which loads lazily.
*/
open class LazyDrawable(context: Context, @DrawableRes resId: Int) : Drawable(), Drawable.Callback {
val wrappedDrawable: Drawable by lazy(LazyThreadSafetyMode.NONE) {
context.getDrawableCompat(resId)
}
override fun draw(canvas: Canvas) {
wrappedDrawable.draw(canvas)
}
override fun onBoundsChange(bounds: Rect) {
wrappedDrawable.bounds = bounds
}
override fun setChangingConfigurations(configs: Int) {
wrappedDrawable.changingConfigurations = configs
}
override fun getChangingConfigurations(): Int {
return wrappedDrawable.changingConfigurations
}
@Suppress("OverridingDeprecatedMember", "DEPRECATION")
override fun setDither(dither: Boolean) {
wrappedDrawable.setDither(dither)
}
override fun setFilterBitmap(filter: Boolean) {
wrappedDrawable.isFilterBitmap = filter
}
override fun setAlpha(alpha: Int) {
wrappedDrawable.alpha = alpha
}
override fun setColorFilter(cf: ColorFilter?) {
wrappedDrawable.colorFilter = cf
}
override fun isStateful(): Boolean {
return wrappedDrawable.isStateful
}
override fun setState(stateSet: IntArray): Boolean {
return wrappedDrawable.setState(stateSet)
}
override fun getState(): IntArray {
return wrappedDrawable.state
}
override fun jumpToCurrentState() {
wrappedDrawable.jumpToCurrentState()
}
override fun getCurrent(): Drawable {
return wrappedDrawable.current
}
override fun setVisible(visible: Boolean, restart: Boolean): Boolean {
return super.setVisible(visible, restart) || wrappedDrawable.setVisible(visible, restart)
}
override fun getOpacity(): Int {
return wrappedDrawable.opacity
}
override fun getTransparentRegion(): Region? {
return wrappedDrawable.transparentRegion
}
override fun getIntrinsicWidth(): Int {
return wrappedDrawable.intrinsicWidth
}
override fun getIntrinsicHeight(): Int {
return wrappedDrawable.intrinsicHeight
}
override fun getMinimumWidth(): Int {
return wrappedDrawable.minimumWidth
}
override fun getMinimumHeight(): Int {
return wrappedDrawable.minimumHeight
}
override fun getPadding(padding: Rect): Boolean {
return wrappedDrawable.getPadding(padding)
}
/**
* {@inheritDoc}
*/
override fun invalidateDrawable(who: Drawable) {
invalidateSelf()
}
/**
* {@inheritDoc}
*/
override fun scheduleDrawable(who: Drawable, what: Runnable, `when`: Long) {
scheduleSelf(what, `when`)
}
/**
* {@inheritDoc}
*/
override fun unscheduleDrawable(who: Drawable, what: Runnable) {
unscheduleSelf(what)
}
override fun onLevelChange(level: Int): Boolean {
return wrappedDrawable.setLevel(level)
}
override fun setAutoMirrored(mirrored: Boolean) {
DrawableCompat.setAutoMirrored(wrappedDrawable, mirrored)
}
override fun isAutoMirrored(): Boolean {
return DrawableCompat.isAutoMirrored(wrappedDrawable)
}
override fun setTint(tint: Int) {
DrawableCompat.setTint(wrappedDrawable, tint)
}
override fun setTintList(tint: ColorStateList?) {
DrawableCompat.setTintList(wrappedDrawable, tint)
}
override fun setTintMode(tintMode: PorterDuff.Mode) {
DrawableCompat.setTintMode(wrappedDrawable, tintMode)
}
override fun setHotspot(x: Float, y: Float) {
DrawableCompat.setHotspot(wrappedDrawable, x, y)
}
override fun setHotspotBounds(left: Int, top: Int, right: Int, bottom: Int) {
DrawableCompat.setHotspotBounds(wrappedDrawable, left, top, right, bottom)
}
}
|
apache-2.0
|
438e18ef2e088e5161725d419c95fcab
| 25.956522 | 100 | 0.693548 | 5.046512 | false | false | false | false |
Arello-Mobile/Moxy
|
sample-kotlin/src/main/kotlin/com/arellomobile/mvp/sample/kotlin/MainActivity.kt
|
1
|
1565
|
package com.arellomobile.mvp.sample.kotlin
import android.os.Bundle
import android.support.v7.app.AlertDialog
import com.arellomobile.mvp.MvpAppCompatActivity
import com.arellomobile.mvp.presenter.InjectPresenter
import com.arellomobile.mvp.presenter.PresenterType
import com.arellomobile.mvp.presenter.ProvidePresenter
import com.arellomobile.mvp.presenter.ProvidePresenterTag
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : MvpAppCompatActivity(), DialogView {
@InjectPresenter(type = PresenterType.GLOBAL)
lateinit var dialogPresenter: DialogPresenter
var alertDialog: AlertDialog? = null
@ProvidePresenterTag(presenterClass = DialogPresenter::class, type = PresenterType.GLOBAL)
fun provideDialogPresenterTag(): String = "Hello"
@ProvidePresenter(type = PresenterType.GLOBAL)
fun provideDialogPresenter() = DialogPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rootView.setOnClickListener { dialogPresenter.onShowDialogClick() }
}
override fun showDialog() {
alertDialog = AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Message")
.setOnDismissListener { dialogPresenter.onHideDialog() }
.show()
}
override fun hideDialog() {
alertDialog?.setOnDismissListener { }
alertDialog?.cancel()
}
override fun onDestroy() {
super.onDestroy()
hideDialog()
}
}
|
mit
|
40079be15d25728434079769043e4c64
| 30.32 | 94 | 0.728435 | 4.952532 | false | false | false | false |
SUPERCILEX/Robot-Scouter
|
library/core/src/main/java/com/supercilex/robotscouter/core/Async.kt
|
1
|
1852
|
package com.supercilex.robotscouter.core
import android.app.Activity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.google.android.gms.tasks.Task
import kotlinx.coroutines.CancellationException
import java.lang.ref.WeakReference
import kotlin.coroutines.intrinsics.intercepted
import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn
fun <T> Task<T>.fastAddOnSuccessListener(
activity: Activity? = null,
listener: (T) -> Unit
): Task<T> {
if (isSuccessful) { // Fast path
@Suppress("UNCHECKED_CAST") // Let the caller decide nullability
listener(result as T)
return this
}
return if (activity == null) {
addOnSuccessListener(listener)
} else {
addOnSuccessListener(activity, listener)
}
}
fun <T : Any> T.asReference() = Ref(this)
fun <T : LifecycleOwner> T.asLifecycleReference(
minState: Lifecycle.State = Lifecycle.State.STARTED
) = asLifecycleReference(this, minState)
fun <T : Any> T.asLifecycleReference(
owner: LifecycleOwner,
minState: Lifecycle.State = Lifecycle.State.STARTED
) = LifecycleOwnerRef(asReference(), owner.asReference(), minState)
class LifecycleOwnerRef<out T : Any>(
private val obj: Ref<T>,
private val owner: Ref<LifecycleOwner>,
private val minState: Lifecycle.State
) {
suspend operator fun invoke(): T {
if (!owner().lifecycle.currentState.isAtLeast(minState)) throw CancellationException()
return obj()
}
}
class Ref<out T : Any> internal constructor(obj: T) {
private val weakRef = WeakReference(obj)
suspend operator fun invoke(): T {
return suspendCoroutineUninterceptedOrReturn {
it.intercepted()
weakRef.get() ?: throw CancellationException()
}
}
}
|
gpl-3.0
|
e1b6ba3e3d875c7f45ef7d2900709d44
| 29.866667 | 94 | 0.697624 | 4.462651 | false | false | false | false |
mbarta/scr-redesign
|
app/src/main/java/me/barta/stayintouch/ui/views/ToolbarBackgroundView.kt
|
1
|
3598
|
package me.barta.stayintouch.ui.views
import android.content.Context
import android.graphics.*
import android.media.ThumbnailUtils
import android.util.AttributeSet
import android.view.View
import me.barta.stayintouch.R
import me.barta.stayintouch.common.utils.blur
class ToolbarBackgroundView : View {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
resolveAttributes(attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
resolveAttributes(attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
resolveAttributes(attrs)
}
var scale: Float = 1.0f
set(value) {
field = value
invalidate()
}
var bitmap: Bitmap? = null
set(value) {
field = value
processBitmapBackground()
}
private var topMargin: Int = 0
private val paint = Paint()
private var upperLeft = PointF()
private var upperRight = PointF()
private var bottomRight = PointF()
private var bottomLeft = PointF()
private val path = Path()
private var gradientColourTop = Color.TRANSPARENT
private var gradientColourBottom = Color.TRANSPARENT
private var gradient = LinearGradient(0f, 0f, 0f, 0f, gradientColourTop, gradientColourBottom, Shader.TileMode.MIRROR)
private var loadedBitmap: Bitmap? = null
private var bitmapShader: BitmapShader? = null
init {
paint.apply {
isAntiAlias = true
shader = gradient
style = Paint.Style.FILL
}
}
private fun resolveAttributes(attrs: AttributeSet?) {
val a = context.theme.obtainStyledAttributes(attrs, R.styleable.ToolbarBackgroundView, 0, 0)
try {
topMargin = a.getDimensionPixelSize(R.styleable.ToolbarBackgroundView_topMargin, 0)
gradientColourTop = a.getColor(R.styleable.ToolbarBackgroundView_gradientColorStart, Color.TRANSPARENT)
gradientColourBottom = a.getColor(R.styleable.ToolbarBackgroundView_gradientColorEnd, Color.TRANSPARENT)
} finally {
a.recycle()
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
gradient = LinearGradient(0f, 0f, width.toFloat(), height * 2f, gradientColourTop, gradientColourBottom, Shader.TileMode.MIRROR)
paint.shader = gradient
if (bitmap != null) {
processBitmapBackground()
}
}
private fun processBitmapBackground() {
loadedBitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height).blur(context)
bitmapShader = BitmapShader(loadedBitmap!!, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
paint.shader = bitmapShader
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
upperLeft.set(0f, 0f)
upperRight.set(width.toFloat(), 0f)
bottomRight.set(width.toFloat(), height.toFloat() - topMargin.toFloat() + ((1 - scale) * topMargin.toFloat()))
bottomLeft.set(0f, height.toFloat())
path.reset()
path.moveTo(0f, 0f)
path.lineTo(upperRight.x, upperRight.y)
path.lineTo(bottomRight.x, bottomRight.y)
path.lineTo(bottomLeft.x, bottomLeft.y)
path.close()
canvas.drawPath(path, paint)
}
}
|
mit
|
f4392da6cdbafc603a73773b5525e725
| 31.414414 | 145 | 0.662312 | 4.431034 | false | false | false | false |
AerisG222/maw_photos_android
|
MaWPhotos/src/main/java/us/mikeandwan/photos/ui/BindingAdapters.kt
|
1
|
5321
|
package us.mikeandwan.photos.ui
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import androidx.fragment.app.FragmentContainerView
import androidx.recyclerview.widget.RecyclerView
import io.noties.markwon.Markwon
import us.mikeandwan.photos.R
import us.mikeandwan.photos.domain.models.*
import us.mikeandwan.photos.ui.controls.categorychooser.CategoryChooserFragment
import us.mikeandwan.photos.ui.controls.categorylist.CategoryListRecyclerAdapter
import us.mikeandwan.photos.ui.controls.categorylist.CategoryWithYearVisibility
import us.mikeandwan.photos.ui.controls.imagegrid.ImageGridFragment
import us.mikeandwan.photos.ui.controls.imagegrid.ImageGridItem
import us.mikeandwan.photos.ui.controls.imagegrid.ImageGridItemWithSize
import us.mikeandwan.photos.ui.controls.imagegrid.ImageGridRecyclerAdapter
import us.mikeandwan.photos.ui.controls.searchnavmenu.SearchTermListRecyclerAdapter
import us.mikeandwan.photos.ui.controls.yearnavmenu.YearListRecyclerAdapter
import us.mikeandwan.photos.utils.GlideApp
import java.io.File
@BindingAdapter("yearListData")
fun bindYearRecyclerView(recyclerView: RecyclerView, data: List<Int>?) {
val adapter = recyclerView.adapter as YearListRecyclerAdapter
adapter.submitList(data)
}
@BindingAdapter("categoryList")
fun bindCategoryListRecyclerView(recyclerView: RecyclerView, data: List<CategoryWithYearVisibility>?) {
when(val adapter = recyclerView.adapter) {
is CategoryListRecyclerAdapter -> adapter.submitList(data)
}
}
@BindingAdapter("searchTerms")
fun bindSearchTermRecyclerView(recyclerView: RecyclerView, data: List<SearchHistory>?) {
val adapter = recyclerView.adapter as SearchTermListRecyclerAdapter
adapter.submitList(data?.map{ it.term })
}
@BindingAdapter("imageGridItemList")
fun bindImageGridRecyclerView(recyclerView: RecyclerView, gridItems: List<ImageGridItemWithSize>?) {
when(val adapter = recyclerView.adapter) {
is ImageGridRecyclerAdapter -> adapter.submitList(gridItems)
}
}
@BindingAdapter("imageUrl")
fun bindImage(imgView: ImageView, imgUrl: String?) {
imgUrl?.let {
GlideApp.with(imgView.context)
.load(imgUrl)
.centerCrop()
.placeholder(R.drawable.ic_placeholder)
.error(R.drawable.ic_broken_image)
.into(imgView)
}
}
@BindingAdapter("tint")
fun bindTint(imgView: ImageView, color: Int?) {
color?.let {
imgView.setColorFilter(color)
}
}
@BindingAdapter("imageGridThumbnailSize")
fun bindImageGridThumbnailSize(container: FragmentContainerView, thumbnailSize: GridThumbnailSize) {
val imageGridFragment = container.getFragment<ImageGridFragment>()
imageGridFragment.setThumbnailSize(thumbnailSize)
}
@BindingAdapter("imageGridPhotoList")
fun bindImageGridPhotoList(container: FragmentContainerView, photoList: List<Photo>) {
val imageGridFragment = container.getFragment<ImageGridFragment>()
imageGridFragment.setGridItems(photoList.map { it.toImageGridItem() })
}
@BindingAdapter("imageGridFileList")
fun bindImageGridFileList(container: FragmentContainerView, fileList: List<File>) {
val imageGridFragment = container.getFragment<ImageGridFragment>()
imageGridFragment.setGridItems(fileList.mapIndexed { id, file -> ImageGridItem(id, file.path, file) })
}
@BindingAdapter("imageGridClickHandler")
fun bindImageGridClickHandler(container: FragmentContainerView, handler: ImageGridRecyclerAdapter.ClickListener) {
val imageGridFragment = container.getFragment<ImageGridFragment>()
imageGridFragment.setClickHandler(handler)
}
@BindingAdapter("markdownText")
fun bindMarkdownText(textView: TextView, markdown: String) {
val markwon = Markwon.create(textView.context)
markwon.setMarkdown(textView, markdown)
}
@BindingAdapter("categoryChooserDisplayType")
fun bindCategoryChooserDisplayType(container: FragmentContainerView, displayType: CategoryDisplayType) {
val categoryChooserFragment = container.getFragment<CategoryChooserFragment>()
categoryChooserFragment.setDisplayType(displayType)
}
@BindingAdapter("categoryChooserCategories")
fun bindCategoryChooserCategories(container: FragmentContainerView, categories: List<PhotoCategory>) {
val categoryChooserFragment = container.getFragment<CategoryChooserFragment>()
categoryChooserFragment.setCategories(categories)
}
@BindingAdapter("categoryChooserCategorySelectedHandler")
fun bindCategoryChooserClickHandler(container: FragmentContainerView, handler: CategoryChooserFragment.CategorySelectedListener) {
val categoryChooserFragment = container.getFragment<CategoryChooserFragment>()
categoryChooserFragment.setClickHandler(handler)
}
@BindingAdapter("categoryChooserGridThumbnailSize")
fun bindCategoryChooserGridThumbnailSize(container: FragmentContainerView, size: GridThumbnailSize) {
val categoryChooserFragment = container.getFragment<CategoryChooserFragment>()
categoryChooserFragment.setGridThumbnailSize(size)
}
@BindingAdapter("categoryChooserShowYearInList")
fun bindCategoryChooserShowYearInList(container: FragmentContainerView, show: Boolean) {
val categoryChooserFragment = container.getFragment<CategoryChooserFragment>()
categoryChooserFragment.setShowYearsInList(show)
}
|
mit
|
20e2981c68ef49c81e828aeeb17d3f3a
| 37.846715 | 130 | 0.810562 | 5.067619 | false | false | false | false |
siosio/upsource-kotlin-api
|
src/test/java/com/github/siosio/upsource/integration/IntegrationTest.kt
|
1
|
3000
|
package com.github.siosio.upsource.integration
import com.github.siosio.upsource.*
import com.github.siosio.upsource.bean.*
import com.github.siosio.upsource.exception.*
import org.hamcrest.CoreMatchers.*
import org.junit.*
import org.junit.Assert.*
import java.util.concurrent.*
class IntegrationTest {
val sut = UpsourceClient("http://localhost:8080/", "siosio", "siosio")
@Test
fun getAllProject() {
sut.project {
allProjects {
println("it = ${it}")
}
}
sut.project {
val project = get("domasupport")
println("project = ${project}")
}
}
@Test
fun createProject() {
sut.project {
+project(
projectId = "kotlin-sql",
projectName = "kotlinのSQL",
projectType = ProjectType.Gradle,
pathToModel = "src",
codeReviewIdPattern = "kot-{}",
vcs = {
+repository(id = "kotlin-sql", vcs = Vcs.git, url = "https://github.com/siosio/kotlin-sql")
},
checkIntervalSeconds = 600,
runInspections = false,
links = {
+link("https://github.com/siosio/kotlin-sql/issues/{}", "#{}")
},
createUserGroups = true,
defaultEncoding = "utf-8",
defaultBranch = "master"
)
for (i in (1..5)) {
try {
val project = this["kotlin-sql"]
assertThat(project.projectId, `is`("kotlin-sql"))
break
} catch (e: ProjectNotFoundException) {
println("e.message = ${e.message}")
TimeUnit.SECONDS.sleep(5)
}
}
-"kotlin-sql"
}
}
@Test
fun createReview() {
sut.project("demo") {
-review("DM-CR-37")
val reviewId = (+review(
title = "Hello Kotlinをば",
branch = "feature/2"
) {
assertThat(branch, `is`("feature/2"))
+reviewer("81db1f0d-bcb2-4ae4-9174-08fff2fc7a4f")
+reviewer("8a4f008c-ef07-4d2a-91d1-58324e71b107")
+watcher("0aa10d06-13f1-4f96-bfb4-789bb2041571")
}).reviewId
UpsourceClient("http://localhost:8080/", "reviewer1", "reviewer1").project("demo") {
review(reviewId) {
title("Hello Kotlin( ・ิω・ิ)")
state(ParticipantStateEnum.Accepted)
}
}
review(reviewId) {
assertThat(this.participants?.find { it.userId == "81db1f0d-bcb2-4ae4-9174-08fff2fc7a4f" }?.state, `is`(ParticipantStateEnum.Accepted))
-reviewer("8a4f008c-ef07-4d2a-91d1-58324e71b107")
-watcher("0aa10d06-13f1-4f96-bfb4-789bb2041571")
}
val review = review(reviewId)
println("----------------------------------------------------------------------------------------------------")
println(review)
println("----------------------------------------------------------------------------------------------------")
println("******************** delete review: ${review.reviewId}")
-review(reviewId)
}
}
}
|
mit
|
15ff5bb0a83c6944e4d30987ab291785
| 26.385321 | 143 | 0.528643 | 3.817136 | false | false | false | false |
helixs/WingsToolsX
|
app/src/main/java/com/helixs/ui/sensor/SensorListActivity.kt
|
1
|
2164
|
package com.helixs.ui.sensor
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.helixs.adapter.BaseRecycleAdapter
import com.helixs.base.BaseActivity
import com.helixs.tools.R
import com.helixs.ui.func.FucResUtilRes
import com.helixs.ui.func.binding.ItemFuncBinding
import java.util.ArrayList
class SensorListActivity : BaseActivity() {
private lateinit var sensorListCtrl: SensorCtrl
private lateinit var recycleView : RecyclerView
private val funcContents = arrayOf("指南针")
private val funcIcons = intArrayOf(R.mipmap.ic_launcher)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sensor_list)
val fucList = ArrayList<FucResUtilRes>()
for (i in funcContents.indices) {
val fucRes = FucResUtilRes()
fucRes.content = funcContents[i]
fucRes.image = funcIcons[i]
fucList.add(fucRes)
}
sensorListCtrl = SensorCtrl(this)
recycleView = findViewById(R.id.ry_sensor) as RecyclerView
recycleView.layoutManager = LinearLayoutManager(this)
val itemFuncAdapter = SensorListActivity.ItemSensorAdapter(this, R.layout.item_func)
recycleView.adapter=itemFuncAdapter
itemFuncAdapter.setList(fucList)
itemFuncAdapter.notifyDataSetChanged()
}
class ItemSensorAdapter(context: Context?, layout: Int) : BaseRecycleAdapter<FucResUtilRes, ItemFuncBinding>(context, layout) {
override fun bindViewHolder(b: ItemFuncBinding, position: Int, t1: FucResUtilRes) {
b.info= FucResUtilRes.FuncItemModel()
b.info.content.set(t1.content)
b.info.resourcesImage.set(t1.image)
b.root.setOnClickListener { view: View -> when (t1.content){
"指南针" -> {
view.context.startActivity(Intent(view.context,CompassActivity::class.java))
}
} }
}
}
}
|
apache-2.0
|
7e0bfc2c2d0db8274b35f6a9b23fd71b
| 38.851852 | 131 | 0.700743 | 4.227898 | false | false | false | false |
herbeth1u/VNDB-Android
|
app/src/main/java/com/booboot/vndbandroid/model/vndb/Label.kt
|
1
|
3715
|
package com.booboot.vndbandroid.model.vndb
import android.content.Context
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.booboot.vndbandroid.App
import com.booboot.vndbandroid.R
import com.booboot.vndbandroid.extensions.adjustAlpha
import com.booboot.vndbandroid.extensions.darken
import com.booboot.vndbandroid.extensions.dayNightTheme
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Label(
var id: Long = 0,
var label: String = ""
) : Comparable<Label> {
companion object {
/* VNDB official labels */
val UNKNOWN = Label(0L, "Unknown")
val PLAYING = Label(1L, "Playing")
val FINISHED = Label(2L, "Finished")
val STALLED = Label(3L, "Stalled")
val DROPPED = Label(4L, "Dropped")
val WISHLIST = Label(5L, "Wishlist")
val BLACKLIST = Label(6L, "Blacklist")
val VOTED = Label(7L, "Voted")
/* Custom labels */
private const val VOTE_ID = -20100L
val NO_VOTE = Label(-30100L, "No vote")
const val NO_LABELS = -30101L
const val CLEAR_FILTERS = -30102L
const val CUSTOM_VOTE = -30103L
const val NOTES_ITEM = -30104L
val VOTES = mutableListOf<Label>().apply { for (i in 1..10) add(Label(VOTE_ID + i, "$i")) }
/* Notable collections of label ids */
val STATUSES = linkedSetOf(PLAYING.id, FINISHED.id, STALLED.id, DROPPED.id, UNKNOWN.id)
val WISHLISTS = linkedSetOf(WISHLIST.id, BLACKLIST.id)
val VOTELISTS = VOTES.map { it.id }
val VOTE_CONTROLS = linkedSetOf(VOTED.id, NO_VOTE.id)
val ALL_VOTES = VOTELISTS + VOTE_CONTROLS
val ALL = STATUSES.plus(WISHLISTS)
fun toShortString(status: Long?): String = when (status) {
UNKNOWN.id -> "?"
PLAYING.id -> "P"
FINISHED.id -> "F"
STALLED.id -> "S"
DROPPED.id -> "D"
WISHLIST.id -> "W"
BLACKLIST.id -> "B"
else -> App.context.getString(R.string.dash)
}
fun voteIdToVote(voteId: Long) = voteId - VOTE_ID
fun voteIdToVoteOutOf100(voteId: Long) = voteIdToVote(voteId).toInt() * 10
@ColorInt
fun textColor(context: Context, @ColorRes colorRes: Int): Int {
val color = ContextCompat.getColor(context, colorRes)
return if (context.dayNightTheme() == "light") color.darken() else color
}
@ColorInt
fun backgroundColor(context: Context, @ColorRes colorRes: Int): Int {
val color = ContextCompat.getColor(context, colorRes)
return color.adjustAlpha(0.157f)
}
}
@ColorRes
fun buttonColor() = when (id) {
PLAYING.id -> R.color.playing
FINISHED.id -> R.color.finished
STALLED.id -> R.color.stalled
DROPPED.id -> R.color.dropped
UNKNOWN.id -> R.color.unknown
WISHLIST.id -> R.color.playing
BLACKLIST.id -> R.color.unknown
else -> R.color.textColorPrimary
}
@ColorInt
fun textColor(context: Context) = textColor(context, buttonColor())
@ColorInt
fun backgroundColor(context: Context) = backgroundColor(context, buttonColor())
fun getGroup() = when (id) {
in STATUSES -> STATUSES
in WISHLISTS -> WISHLISTS
else -> linkedSetOf()
}
override fun compareTo(other: Label): Int {
var index = ALL.indexOf(id).toLong()
if (index < 0) index = id
var otherIndex = ALL.indexOf(other.id).toLong()
if (otherIndex < 0) otherIndex = other.id
return index.compareTo(otherIndex)
}
}
|
gpl-3.0
|
5ee52c24c0b9753d885d0da54b173a52
| 34.056604 | 99 | 0.619919 | 3.960554 | false | false | false | false |
alygin/intellij-rust
|
src/test/kotlin/org/rust/ide/inspections/RsVariableMutableInspectionTest.kt
|
2
|
3734
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
class RsVariableMutableInspectionTest : RsInspectionsTestBase(RsVariableMutableInspection()) {
fun `test should annotate unused variable`() = checkByText("""
fn main() {
let <warning>mut f</warning> = 10;
}
""")
fun `test should not annotate if there is not mut`() = checkByText("""
fn main() {
let f = 10;
}
""")
fun `test should not annotate self methods`() = checkByText("""
struct Foo { foo: bool }
impl Foo {
fn push(&mut self, test: i32) {
}
}
fn foo() {
let <warning>mut t</warning> = 10;
let mut f = Foo { foo: true };
f.push(t);
}
""")
fun `test should not annotate mutated fields`() = checkByText("""
struct Foo { foo: bool }
fn foo(b: &mut bool) {}
fn bar() {
let mut f = Foo { foo: true };
foo(&mut f.foo);
}
""")
fun `test should annotate mutated parameter`() = checkByText("""
fn foo(i: i32) {
println!("{:?}", i);
}
fn main() {
let <warning descr="Variable `f` does not need to be mutable">mut f</warning> = 10;
foo(f);
}
""")
fun `test should not annotate mutated parameter`() = checkByText("""
fn foo(&mut i: i32) {
i = 20;
}
fn main() {
let mut f = 10;
foo(&mut f);
}
""")
fun `test first mut and second not mut`() = checkByText("""
fn main() {
let <warning>mut f</warning> = 10;
let mut f = 10;
f = 20;
}
""")
fun `test tuple`() = checkByText("""
fn bar(s: &mut (u8, u8)) {}
fn main() {
let mut a = 1u8;
let mut b = 2u8;
bar(&mut (a, b));
}
""")
fun `test match arms`() = checkByText("""
fn main() {
let mut a = Some(20);
if let Some(ref mut b) = a { *b = 10; }
match a {
Some(ref mut b) => *b = 10,
None => {},
}
}
""")
fun `test should not annotate if macro after expr`() = checkByText("""
fn foo(a: &mut u32) { }
macro_rules! call_foo { () => { w = 20; } }
fn main() {
let mut w = 10;
call_foo!();
}
""")
fun `test should annotate if macro before expr`() = checkByText("""
fn foo(a: &mut u32) { }
macro_rules! call_foo { () => { let mut w = 20; w = 20; } }
fn main() {
call_foo!();
let <warning>mut<caret> f</warning> = 10;
}
""")
fun `test should annotate function parameter`() = checkFixByText("Remove mutable", """
fn foo(mut test: i32) {
test = 10;
}
fn foo2(<warning>mut<caret> test</warning>: i32) {
}
""", """
fn foo(mut test: i32) {
test = 10;
}
fn foo2(test: i32) {
}
""")
fun `test first not mut and second mut`() = checkFixByText("Remove mutable", """
fn main() {
let mut f = 10;
f = 20;
let <warning>mut<caret> f</warning> = 10;
}
""", """
fn main() {
let mut f = 10;
f = 20;
let f = 10;
}
""")
fun `test function`() = checkByText("""
fn main() {
let mut a = 10;
let mut foo = || a = 20;
foo();
}
""")
}
|
mit
|
0c47201880461fbc89bff96a754406fc
| 23.405229 | 95 | 0.431173 | 4.032397 | false | true | false | false |
tipsy/javalin
|
javalin/src/test/java/io/javalin/TestWebSocket.kt
|
1
|
25172
|
/*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin
import io.javalin.apibuilder.ApiBuilder.ws
import io.javalin.core.util.Header
import io.javalin.http.UnauthorizedResponse
import io.javalin.testing.SerializableObject
import io.javalin.testing.TestUtil
import io.javalin.testing.TypedException
import io.javalin.testing.fasterJacksonMapper
import io.javalin.websocket.WsContext
import kong.unirest.Unirest
import org.assertj.core.api.Assertions.assertThat
import org.eclipse.jetty.websocket.api.CloseStatus
import org.eclipse.jetty.websocket.api.MessageTooLargeException
import org.eclipse.jetty.websocket.api.StatusCode
import org.eclipse.jetty.websocket.api.WebSocketConstants
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft_6455
import org.java_websocket.handshake.ServerHandshake
import org.junit.jupiter.api.Test
import java.net.URI
import java.time.Duration
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicInteger
/**
* This test could be better
*/
class TestWebSocket {
data class TestLogger(val log: ConcurrentLinkedQueue<String> = ConcurrentLinkedQueue<String>())
private fun Javalin.logger(): TestLogger {
if (this.attribute<TestLogger>(TestLogger::class.java.name) == null) {
this.attribute(TestLogger::class.java.name, TestLogger())
}
return this.attribute(TestLogger::class.java.name)
}
fun contextPathJavalin() = Javalin.create { it.contextPath = "/websocket" }
fun accessManagedJavalin() = Javalin.create().apply {
this._conf.accessManager { handler, ctx, roles ->
this.logger().log.add("handling upgrade request ...")
when {
ctx.queryParam("allowed") == "true" -> {
this.logger().log.add("upgrade request valid!")
handler.handle(ctx)
}
ctx.queryParam("exception") == "true" -> throw UnauthorizedResponse()
else -> this.logger().log.add("upgrade request invalid!")
}
}
this.ws("/*") { ws ->
ws.onConnect { this.logger().log.add("connected with upgrade request") }
}
}
@Test
fun `each connection receives a unique id`() = TestUtil.test(contextPathJavalin()) { app, _ ->
app.ws("/test-websocket-1") { ws ->
ws.onConnect { ctx -> app.logger().log.add(ctx.sessionId) }
ws.onClose { ctx -> app.logger().log.add(ctx.sessionId) }
}
app.routes {
ws("/test-websocket-2") { ws ->
ws.onConnect { ctx -> app.logger().log.add(ctx.sessionId) }
ws.onClose { ctx -> app.logger().log.add(ctx.sessionId) }
}
}
TestClient(app, "/websocket/test-websocket-1").connectAndDisconnect()
TestClient(app, "/websocket/test-websocket-1").connectAndDisconnect()
TestClient(app, "/websocket/test-websocket-2").connectAndDisconnect()
// 3 clients and 6 operations should yield 3 unique identifiers total
val uniqueLog = HashSet(app.logger().log)
assertThat(uniqueLog).hasSize(3)
uniqueLog.forEach { id -> assertThat(uniqueLog.count { it == id }).isEqualTo(1) }
}
@Test
fun `general integration test`() = TestUtil.test(contextPathJavalin()) { app, _ ->
val idMap = ConcurrentHashMap<WsContext, Int>()
val atomicInteger = AtomicInteger()
app.ws("/test-websocket-1") { ws ->
ws.onConnect { ctx ->
idMap[ctx] = atomicInteger.getAndIncrement()
app.logger().log.add("${idMap[ctx]} connected")
}
ws.onMessage { ctx ->
app.logger().log.add("${idMap[ctx]} sent '${ctx.message()}' to server")
idMap.forEach { (client, _) -> client.send("Server sent '${ctx.message()}' to ${idMap[client]}") }
}
ws.onClose { ctx -> app.logger().log.add("${idMap[ctx]} disconnected") }
}
app.routes { // use .routes to test apibuilder
ws("/test-websocket-2") { ws ->
ws.onConnect { app.logger().log.add("Connected to other endpoint") }
ws.onClose { app.logger().log.add("Disconnected from other endpoint") }
}
}
val testClient0 = TestClient(app, "/websocket/test-websocket-1").also { it.connectBlocking() } // logsize = 1
val testClient1 = TestClient(app, "/websocket/test-websocket-1").also { it.connectBlocking() } // logsize = 2
doBlocking({
testClient0.send("A") // logsize = 3 (this will add +2 to logsize when clients register echo)
testClient1.send("B") // logsize = 4 (this will add +2 to logsize when clients register echo)
}, { app.logger().log.size != 8 }) // // logsize = 8 (block until all echos registered)
testClient0.closeBlocking()
testClient1.closeBlocking()
TestClient(app, "/websocket/test-websocket-2").also { it.connectAndDisconnect() }
assertThat(app.logger().log).containsExactlyInAnyOrder(
"0 connected",
"1 connected",
"0 sent 'A' to server",
"1 sent 'B' to server",
"Server sent 'A' to 0",
"Server sent 'A' to 1",
"Server sent 'B' to 0",
"Server sent 'B' to 1",
"0 disconnected",
"1 disconnected",
"Connected to other endpoint",
"Disconnected from other endpoint"
)
}
@Test
fun `receive and send json messages`() = TestUtil.test(Javalin.create {
it.jsonMapper(fasterJacksonMapper)
}) { app, _ ->
app.ws("/message") { ws ->
ws.onMessage { ctx ->
val receivedMessage = ctx.messageAsClass<SerializableObject>()
receivedMessage.value1 = "updated"
ctx.send(receivedMessage)
}
}
val clientJsonString = fasterJacksonMapper.toJsonString(SerializableObject().apply { value1 = "test1"; value2 = "test2" })
var response: String? = null
val testClient = TestClient(app, "/message").also {
it.onMessage = { msg -> response = msg }
it.connectBlocking()
}
doBlocking({ testClient.send(clientJsonString) }, { response == null }) // have to wait for client to recive response
assertThat(response).contains(""""value1":"updated"""")
assertThat(response).contains(""""value2":"test2"""")
}
@Test
fun `binary messages`() = TestUtil.test(contextPathJavalin()) { app, _ ->
val byteDataToSend1 = (0 until 4096).shuffled().map { it.toByte() }.toByteArray()
val byteDataToSend2 = (0 until 4096).shuffled().map { it.toByte() }.toByteArray()
val receivedBinaryData = mutableListOf<ByteArray>()
app.ws("/binary") { ws ->
ws.onBinaryMessage { ctx ->
receivedBinaryData.add(ctx.data())
}
}
TestClient(app, "/websocket/binary").also {
it.connectBlocking()
it.send(byteDataToSend1)
it.send(byteDataToSend2)
it.closeBlocking()
}
assertThat(receivedBinaryData).containsExactlyInAnyOrder(byteDataToSend1, byteDataToSend2)
}
@Test
fun `routing and pathParams work`() = TestUtil.test(contextPathJavalin()) { app, _ ->
app.ws("/params/{1}") { ws -> ws.onConnect { ctx -> app.logger().log.add(ctx.pathParam("1")) } }
app.ws("/params/{1}/test/{2}/{3}") { ws -> ws.onConnect { ctx -> app.logger().log.add(ctx.pathParam("1") + " " + ctx.pathParam("2") + " " + ctx.pathParam("3")) } }
app.ws("/*") { ws -> ws.onConnect { _ -> app.logger().log.add("catchall") } } // this should not be triggered since all calls match more specific handlers
TestClient(app, "/websocket/params/one").connectAndDisconnect()
TestClient(app, "/websocket/params/%E2%99%94").connectAndDisconnect()
TestClient(app, "/websocket/params/another/test/long/path").connectAndDisconnect()
assertThat(app.logger().log).containsExactlyInAnyOrder("one", "♔", "another long path")
assertThat(app.logger().log).doesNotContain("catchall")
}
@Test
fun `websocket 404 works`() = TestUtil.test { app, _ ->
val response = Unirest.get("http://localhost:" + app.port() + "/invalid-path")
.header("Connection", "Upgrade")
.header("Upgrade", "websocket")
.header("Host", "localhost:" + app.port())
.header("Sec-WebSocket-Key", "SGVsbG8sIHdvcmxkIQ==")
.header("Sec-WebSocket-Version", "13")
.asString()
assertThat(response.body).containsSequence("WebSocket handler not found")
}
@Test
fun `headers and host are available in session`() = TestUtil.test { app, _ ->
app.ws("/websocket") { ws ->
ws.onConnect { ctx -> app.logger().log.add("Header: " + ctx.header("Test")!!) }
ws.onClose { ctx -> app.logger().log.add("Closed connection from: " + ctx.host()!!) }
}
TestClient(app, "/websocket", mapOf("Test" to "HeaderParameter")).connectAndDisconnect()
assertThat(app.logger().log).containsExactlyInAnyOrder("Header: HeaderParameter", "Closed connection from: localhost")
}
@Test
fun `extracting path information works`() = TestUtil.test { app, _ ->
var matchedPath = ""
var pathParam = ""
var queryParam = ""
var queryParams = listOf<String>()
app.ws("/websocket/{channel}") { ws ->
ws.onConnect { ctx ->
matchedPath = ctx.matchedPath()
pathParam = ctx.pathParam("channel")
queryParam = ctx.queryParam("qp")!!
queryParams = ctx.queryParams("qps")
}
}
TestClient(app, "/websocket/channel-one?qp=just-a-qp&qps=1&qps=2").connectAndDisconnect()
assertThat(matchedPath).isEqualTo("/websocket/{channel}")
assertThat(pathParam).isEqualTo("channel-one")
assertThat(queryParam).isEqualTo("just-a-qp")
assertThat(queryParams).contains("1", "2")
}
@Test
fun `extracting path information works in all handlers`() = TestUtil.test { app, _ ->
app.ws("/context-life") { ws ->
ws.onConnect { app.logger().log.add(it.queryParam("qp")!! + 1) }
ws.onMessage { app.logger().log.add(it.queryParam("qp")!! + 2) }
ws.onClose { app.logger().log.add(it.queryParam("qp")!! + 3) }
}
TestClient(app, "/context-life?qp=great").connectSendAndDisconnect("not-important")
assertThat(app.logger().log).containsExactly("great1", "great2", "great3")
}
@Test
fun `set attributes works`() = TestUtil.test { app, _ ->
app.ws("/attributes") { ws ->
ws.onConnect { it.attribute("test", "Success") }
ws.onClose { app.logger().log.add(it.attribute("test") ?: "Fail") }
}
TestClient(app, "/attributes").connectAndDisconnect()
assertThat(app.logger().log).containsExactly("Success")
}
@Test
fun `getting session attributes works`() = TestUtil.test { app, http ->
app.get("/") { it.sessionAttribute("session-key", "session-value") }
app.ws("/") { ws ->
ws.onConnect {
app.logger().log.add(it.sessionAttribute("session-key")!!)
app.logger().log.add("sessionAttributeMapSize:${it.sessionAttributeMap().size}")
}
}
val sessionCookie = http.get("/").headers["Set-Cookie"]!!.first().removePrefix("JSESSIONID=")
TestClient(app, "/", mapOf("Cookie" to "JSESSIONID=${sessionCookie}")).connectAndDisconnect()
assertThat(app.logger().log).containsExactly("session-value", "sessionAttributeMapSize:1")
}
@Test
fun `routing and path-params case sensitive works`() = TestUtil.test { app, _ ->
app.ws("/pAtH/{param}") { ws -> ws.onConnect { ctx -> app.logger().log.add(ctx.pathParam("param")) } }
app.ws("/other-path/{param}") { ws -> ws.onConnect { ctx -> app.logger().log.add(ctx.pathParam("param")) } }
TestClient(app, "/PaTh/my-param").connectAndDisconnect()
assertThat(app.logger().log).doesNotContain("my-param")
TestClient(app, "/other-path/My-PaRaM").connectAndDisconnect()
assertThat(app.logger().log).contains("My-PaRaM")
}
@Test
fun `web socket logging works`() = TestUtil.test(Javalin.create().apply {
this._conf.wsLogger { ws ->
ws.onConnect { ctx -> this.logger().log.add(ctx.pathParam("param") + " connected") }
ws.onClose { ctx -> this.logger().log.add(ctx.pathParam("param") + " disconnected") }
}
}) { app, _ ->
app.ws("/path/{param}") {}
TestClient(app, "/path/0").connectAndDisconnect()
TestClient(app, "/path/1").connectAndDisconnect()
assertThat(app.logger().log).containsExactlyInAnyOrder(
"0 connected",
"1 connected",
"0 disconnected",
"1 disconnected"
)
}
@Test
fun `dev logging works for web sockets`() = TestUtil.test(Javalin.create { it.enableDevLogging() }) { app, _ ->
app.ws("/path/{param}") {}
TestClient(app, "/path/0").connectAndDisconnect()
TestClient(app, "/path/1?test=banana&hi=1&hi=2").connectAndDisconnect()
assertThat(app.logger().log.size).isEqualTo(0)
}
@Test
fun `queryParamMap does not throw`() = TestUtil.test { app, _ ->
app.ws("/*") { ws ->
ws.onConnect { ctx ->
ctx.queryParamMap()
app.logger().log.add("call succeeded")
}
}
TestClient(app, "/path/0").connectAndDisconnect()
assertThat(app.logger().log).contains("call succeeded")
}
@Test
fun `custom WebSocketServletFactory works`() {
var err: Throwable? = Exception("Bang")
val maxTextSize = 1
val app = Javalin.create {
it.wsFactoryConfig { wsFactory ->
wsFactory.policy.maxTextMessageSize = maxTextSize
}
}.ws("/ws") { ws ->
ws.onError { ctx -> err = ctx.error() }
}
TestUtil.test(app) { _, _ ->
TestClient(app, "/ws").connectSendAndDisconnect("This text is far too long.")
assertThat(err!!.message).isEqualTo("Text message size [26] exceeds maximum size [$maxTextSize]")
assertThat(err).isExactlyInstanceOf(MessageTooLargeException::class.java)
}
}
@Test
fun `AccessManager rejects invalid request`() = TestUtil.test(accessManagedJavalin()) { app, _ ->
TestClient(app, "/").connectAndDisconnect()
assertThat(app.logger().log.size).isEqualTo(2)
assertThat(app.logger().log).containsExactlyInAnyOrder("handling upgrade request ...", "upgrade request invalid!")
}
@Test
fun `AccessManager accepts valid request`() = TestUtil.test(accessManagedJavalin()) { app, _ ->
TestClient(app, "/?allowed=true").connectAndDisconnect()
assertThat(app.logger().log.size).isEqualTo(3)
assertThat(app.logger().log).containsExactlyInAnyOrder("handling upgrade request ...", "upgrade request valid!", "connected with upgrade request")
}
@Test
fun `AccessManager doesn't crash on exception`() = TestUtil.test(accessManagedJavalin()) { app, _ ->
TestClient(app, "/?exception=true").connectAndDisconnect()
assertThat(app.logger().log.size).isEqualTo(1)
}
@Test
fun `cookies work`() = TestUtil.test { app, _ ->
app.ws("/cookies") { ws ->
ws.onConnect { ctx ->
app.logger().log.add(ctx.cookie("name")!!)
app.logger().log.add("cookieMapSize:${ctx.cookieMap().size}")
}
}
TestClient(app, "/cookies", mapOf("Cookie" to "name=value; name2=value2; name3=value3")).connectAndDisconnect()
assertThat(app.logger().log).containsExactly("value", "cookieMapSize:3")
}
@Test
fun `before handlers work`() = TestUtil.test { app, _ ->
app.wsBefore { ws ->
ws.onConnect { app.logger().log.add("before handler: onConnect") }
ws.onMessage { app.logger().log.add("before handler: onMessage") }
ws.onClose { app.logger().log.add("before handler: onClose") }
}
app.ws("/ws") { ws ->
ws.onConnect { app.logger().log.add("endpoint handler: onConnect") }
ws.onMessage { app.logger().log.add("endpoint handler: onMessage") }
ws.onClose { app.logger().log.add("endpoint handler: onClose") }
}
TestClient(app, "/ws").connectSendAndDisconnect("test")
assertThat(app.logger().log).containsExactly(
"before handler: onConnect", "endpoint handler: onConnect",
"before handler: onMessage", "endpoint handler: onMessage",
"before handler: onClose", "endpoint handler: onClose"
)
}
@Test
fun `throw in wsBefore short circuits endpoint handler`() = TestUtil.test { app, _ ->
app.wsBefore { it.onConnect { throw UnauthorizedResponse() } }
app.ws("/ws") { it.onConnect { app.logger().log.add("This should not be added") } }
app.wsException(Exception::class.java) { e, _ -> app.logger().log.add(e.message!!) }
TestClient(app, "/ws").connectAndDisconnect()
assertThat(app.logger().log).contains("Unauthorized")
assertThat(app.logger().log).doesNotContain("This should not be added")
}
@Test
fun `wsBefore with path works`() = TestUtil.test { app, _ ->
app.wsBefore("/ws/*") { it.onConnect { app.logger().log.add("Before!") } }
app.ws("/ws/test") { it.onConnect { app.logger().log.add("Endpoint!") } }
TestClient(app, "/ws/test").connectAndDisconnect()
assertThat(app.logger().log).containsExactly("Before!", "Endpoint!")
}
@Test
fun `multiple before and after handlers can be called`() = TestUtil.test { app, _ ->
app.wsBefore { it.onConnect { app.logger().log.add("Before 1") } }
app.wsBefore("/ws/*") { it.onConnect { app.logger().log.add("Before 2") } }
app.wsAfter { it.onConnect { app.logger().log.add("After 1") } }
app.wsAfter("/ws/*") { it.onConnect { app.logger().log.add("After 2") } }
app.ws("/ws/test") { it.onConnect { app.logger().log.add("Endpoint") } }
TestClient(app, "/ws/test").connectAndDisconnect()
assertThat(app.logger().log).containsExactly("Before 1", "Before 2", "Endpoint", "After 1", "After 2")
}
@Test
fun `after handlers work`() = TestUtil.test { app, _ ->
app.ws("/ws") { ws ->
ws.onConnect { app.logger().log.add("endpoint handler: onConnect") }
ws.onMessage { app.logger().log.add("endpoint handler: onMessage") }
ws.onClose { app.logger().log.add("endpoint handler: onClose") }
}
app.wsAfter { ws ->
ws.onConnect { app.logger().log.add("after handler: onConnect") }
ws.onMessage { app.logger().log.add("after handler: onMessage") }
ws.onClose { app.logger().log.add("after handler: onClose") }
}
TestClient(app, "/ws").connectSendAndDisconnect("test")
assertThat(app.logger().log).containsExactly(
"endpoint handler: onConnect", "after handler: onConnect",
"endpoint handler: onMessage", "after handler: onMessage",
"endpoint handler: onClose", "after handler: onClose"
)
}
@Test
fun `unmapped exceptions are caught by default handler`() = TestUtil.test { app, _ ->
val exception = Exception("Error message")
app.ws("/ws") { it.onConnect { throw exception } }
val client = object : TestClient(app, "/ws") {
override fun onClose(status: Int, message: String, byRemote: Boolean) {
this.app.logger().log.add("Status code: $status")
this.app.logger().log.add("Reason: $message")
}
}
doBlocking({ client.connect() }, { !client.isClosed }) // hmmm
assertThat(client.app.logger().log).containsExactly(
"Status code: ${StatusCode.SERVER_ERROR}",
"Reason: ${exception.message}"
)
}
@Test
fun `mapped exceptions are handled`() = TestUtil.test { app, _ ->
app.ws("/ws") { it.onConnect { throw Exception() } }
app.wsException(Exception::class.java) { _, _ -> app.logger().log.add("Exception handler called") }
TestClient(app, "/ws").connectAndDisconnect()
assertThat(app.logger().log).containsExactly("Exception handler called")
}
@Test
fun `most specific exception handler handles exception`() = TestUtil.test { app, _ ->
app.ws("/ws") { it.onConnect { throw TypedException() } }
app.wsException(Exception::class.java) { _, _ -> app.logger().log.add("Exception handler called") }
app.wsException(TypedException::class.java) { _, _ -> app.logger().log.add("TypedException handler called") }
TestClient(app, "/ws").connectAndDisconnect()
assertThat(app.logger().log).containsExactly("TypedException handler called")
}
@Test
fun `websocket subprotocol is set if included`() = TestUtil.test { app, http ->
app.ws("/ws") {}
val response = Unirest.get("http://localhost:${app.port()}/ws")
.header(Header.SEC_WEBSOCKET_KEY, "not-null")
.header(WebSocketConstants.SEC_WEBSOCKET_PROTOCOL, "mqtt")
.asString()
assertThat(response.headers.getFirst(WebSocketConstants.SEC_WEBSOCKET_PROTOCOL)).isEqualTo("mqtt")
}
@Test
fun `websocket closeSession() methods`() {
val scenarios = mapOf(
{ client: TestClient -> client.send("NO_ARGS") } to CloseStatus(1000, "null"),
{ client: TestClient -> client.send("STATUS_OBJECT") } to CloseStatus(1001, "STATUS_OBJECT"),
{ client: TestClient -> client.send("CODE_AND_REASON") } to CloseStatus(1002, "CODE_AND_REASON"),
{ client: TestClient -> client.send("UNEXPECTED") } to CloseStatus(1003, "UNEXPECTED")
)
scenarios.forEach { (sendAction, closeStatus) ->
TestUtil.test { app, _ ->
app.ws("/websocket") { ws ->
ws.onMessage { ctx ->
when (ctx.message()) {
"NO_ARGS" -> ctx.closeSession()
"STATUS_OBJECT" -> ctx.closeSession(CloseStatus(1001, "STATUS_OBJECT"))
"CODE_AND_REASON" -> ctx.closeSession(1002, "CODE_AND_REASON")
else -> ctx.closeSession(1003, "UNEXPECTED")
}
}
ws.onClose {
assertThat(it.reason() ?: "null").isEqualTo(closeStatus.phrase)
assertThat(it.status()).isEqualTo(closeStatus.code)
}
}
TestClient(app, "/websocket", onOpen = { sendAction(it) }).connectBlocking()
}
}
}
// ********************************************************************************************
// Helpers
// ********************************************************************************************
internal open inner class TestClient(
var app: Javalin,
path: String,
headers: Map<String, String> = emptyMap(),
val onOpen: (TestClient) -> Unit = {},
var onMessage: ((String) -> Unit)? = null
) : WebSocketClient(URI.create("ws://localhost:" + app.port() + path), Draft_6455(), headers, 0), AutoCloseable {
override fun onOpen(serverHandshake: ServerHandshake) = onOpen(this)
override fun onClose(status: Int, message: String, byRemote: Boolean) {}
override fun onError(exception: Exception) {}
override fun onMessage(message: String) {
onMessage?.invoke(message)
app.logger().log.add(message)
}
fun connectAndDisconnect() = connectBlocking().also { closeBlocking() }
fun connectSendAndDisconnect(message: String) {
connectBlocking()
send(message)
closeBlocking()
}
}
private fun doBlocking(slowFunction: () -> Unit, conditionFunction: () -> Boolean, timeout: Duration = Duration.ofSeconds(1)) {
val startTime = System.currentTimeMillis()
val limitTime = startTime + timeout.toMillis()
slowFunction.invoke()
while (conditionFunction.invoke()) {
if (System.currentTimeMillis() > limitTime) {
throw TimeoutException("Wait for condition has timed out")
}
Thread.sleep(2)
}
}
}
|
apache-2.0
|
c31c4b035b79557422b7bbe3939f25cc
| 44.513562 | 171 | 0.588065 | 4.3216 | false | true | false | false |
Aunmag/a-zombie-shooter-game
|
src/main/java/aunmag/shooter/items/ItemWeapon.kt
|
1
|
3799
|
package aunmag.shooter.items
import aunmag.nightingale.Application
import aunmag.nightingale.font.FontStyleDefault
import aunmag.nightingale.font.Text
import aunmag.nightingale.input.Input
import aunmag.nightingale.math.CollisionCC
import aunmag.nightingale.math.BodyCircle
import aunmag.nightingale.utilities.*
import aunmag.shooter.client.App
import aunmag.shooter.environment.actor.Actor
import aunmag.shooter.data.player
import aunmag.shooter.environment.weapon.Weapon
import org.joml.Vector4f
import org.lwjgl.glfw.GLFW
class ItemWeapon private constructor(
x: Float,
y: Float,
val weapon: Weapon,
private var giver: Actor? = null
) : Operative() {
constructor(x: Float, y: Float, weapon: Weapon) : this(x, y, weapon, null)
constructor(giver: Actor, weapon: Weapon) : this(
giver.body.position.x,
giver.body.position.y,
weapon,
giver
)
val body = BodyCircle(x, y, 0f, 0f)
private val timer = Timer(weapon.world.time, 15.0)
private val pulse = FluidValue(weapon.world.time, 0.4)
private val pulseMin = 0.12f
private val pulseMax = 0.18f
private val rotationVelocity = Math.PI.toFloat()
private val text = Text(x, y, weapon.type.name, FontStyleDefault.simple)
init {
text.setOnWorldRendering(true)
timer.next()
}
private fun drop() {
giver?.let {
body.position.x = it.body.position.x
body.position.y = it.body.position.y
text.position.x = it.body.position.x
text.position.y = it.body.position.y
}
timer.next()
giver = null
}
override fun update() {
val owner = this.giver
if (owner == null) {
if (timer.isDone) {
remove()
} else {
updateColor()
updateRadius()
updateWeapon()
updatePickup()
}
} else if (!owner.isAlive || owner.isRemoved) {
drop()
}
}
private fun updateColor() {
val alpha = UtilsMath.limitNumber(
4.0f * (1.0 - timer.calculateIsDoneRatio()).toFloat(),
0.0f,
0.8f
)
body.color.set(0.9f, 0.9f, 0.9f, alpha / 2f)
text.setColour(Vector4f(1f, 1f, 1f, alpha))
}
private fun updateRadius() {
pulse.update()
if (pulse.isTargetReached) {
pulse.target = if (pulse.target == pulseMin) {
pulseMax
} else {
pulseMin
}
}
body.radius = pulse.current
}
private fun updateWeapon() {
weapon.body.positionTail.set(body.position)
weapon.body.radians -= rotationVelocity * weapon.world.time.delta.toFloat()
weapon.update()
}
private fun updatePickup() {
val player: Actor = player ?: return
val collision = CollisionCC(body, player.hands.coverage)
if (Input.keyboard.isKeyPressed(GLFW.GLFW_KEY_E) && collision.isTrue) {
player.weapon?.let {
val replacement = ItemWeapon(body.position.x, body.position.y, it)
player.world.itemsWeapon.all.add(replacement)
}
player.weapon = weapon
remove()
}
}
override fun render() {
if (giver == null) {
UtilsGraphics.drawPrepare()
body.render()
text.orderRendering()
if (!App.main.isDebug) {
Application.getShader().bind()
weapon.render()
}
}
}
override fun remove() {
if (isRemoved) {
return
}
text.remove()
super.remove()
}
}
|
apache-2.0
|
276d01a6954d2595b867ea52f8725977
| 25.943262 | 83 | 0.564622 | 4.102592 | false | false | false | false |
LanternPowered/LanternServer
|
src/main/kotlin/org/lanternpowered/server/scheduler/LanternScheduler.kt
|
1
|
4666
|
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.scheduler
import org.lanternpowered.api.cause.CauseStack
import org.lanternpowered.api.cause.withFrame
import org.lanternpowered.api.plugin.PluginContainer
import org.lanternpowered.api.util.collections.toImmutableSet
import org.lanternpowered.api.util.optional.asOptional
import org.spongepowered.api.scheduler.ScheduledTask
import org.spongepowered.api.scheduler.Scheduler
import org.spongepowered.api.scheduler.Task
import org.spongepowered.api.scheduler.TaskExecutorService
import java.util.Optional
import java.util.UUID
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Future
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import java.util.function.Supplier
import java.util.regex.Pattern
class LanternScheduler(val service: ScheduledExecutorService) : Scheduler {
private val tasksByUniqueId: MutableMap<UUID, LanternScheduledTask> = ConcurrentHashMap()
fun shutdown(timeout: Long, unit: TimeUnit) {
for (task in this.tasksByUniqueId.values)
task.cancel()
try {
this.service.shutdown()
if (!this.service.awaitTermination(timeout, unit))
this.service.shutdownNow()
} catch (ignored: InterruptedException) {
}
}
override fun getTaskById(id: UUID): Optional<ScheduledTask> = this.tasksByUniqueId[id].asOptional()
override fun getTasksByName(pattern: String): Set<ScheduledTask> {
val searchPattern = Pattern.compile(pattern)
return this.tasksByUniqueId.values.stream()
.filter { task -> searchPattern.matcher(task.name).matches() }
.toImmutableSet()
}
override fun getTasks(): Set<ScheduledTask> = this.tasksByUniqueId.values.toImmutableSet()
override fun getTasksByPlugin(plugin: PluginContainer): Set<ScheduledTask> = this.tasksByUniqueId.values.stream()
.filter { task: LanternScheduledTask -> task.owner == plugin }
.toImmutableSet()
override fun createExecutor(plugin: PluginContainer): TaskExecutorService =
LanternTaskExecutorService({ LanternTaskBuilder().plugin(plugin) }, this)
/**
* Removes the stored [LanternScheduledTask].
*
* @param task The scheduled task
*/
fun remove(task: LanternScheduledTask) {
this.tasksByUniqueId.remove(task.uniqueId)
}
override fun submit(task: Task): LanternScheduledTask {
return submit(task) { executor, scheduledTask, runnable ->
val delay = scheduledTask.task.delayNanos
val interval = scheduledTask.task.intervalNanos
when {
interval != 0L -> executor.scheduleAtFixedRate(runnable, delay, interval, TimeUnit.NANOSECONDS)
delay != 0L -> executor.schedule(runnable, delay, TimeUnit.NANOSECONDS)
else -> executor.submit(runnable)
}
}
}
fun submit(task: Task, submitFunction: (ScheduledExecutorService, LanternScheduledTask, Runnable) -> Future<*>): LanternScheduledTask {
val scheduledTask = LanternScheduledTask(task as LanternTask, this)
val runnable = Runnable {
val causeStack = CauseStack.currentOrEmpty()
causeStack.pushCause(task.owner)
causeStack.pushCause(task)
try {
causeStack.withFrame { task.consumer.accept(scheduledTask) }
} catch (throwable: Throwable) {
task.owner.logger.error("Error while handling task: {}", task.name, throwable)
}
causeStack.popCauses(2)
// Remove the scheduled task once it's done,
// only do this if it's not a repeated task
if (scheduledTask.task.intervalNanos == 0L || scheduledTask.scheduledRemoval)
remove(scheduledTask)
}
scheduledTask.future = submitFunction(this.service, scheduledTask, runnable)
this.tasksByUniqueId[scheduledTask.uniqueId] = scheduledTask
return scheduledTask
}
fun <R> submit(callable: () -> R): CompletableFuture<R> = CompletableFuture.supplyAsync(Supplier(callable), this.service)
fun submit(runnable: Runnable): CompletableFuture<Unit> = submit { runnable.run() }
}
|
mit
|
046c30ab83523d3e2e599297bd976876
| 41.418182 | 139 | 0.695242 | 4.875653 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement
|
src/main/kotlin/org/wfanet/measurement/duchy/service/system/v1alpha/AdvanceComputationRequestHeaders.kt
|
1
|
3023
|
// 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.duchy.service.system.v1alpha
import org.wfanet.measurement.common.grpc.failGrpc
import org.wfanet.measurement.duchy.toProtocolStage
import org.wfanet.measurement.internal.duchy.ComputationStage
import org.wfanet.measurement.internal.duchy.protocol.LiquidLegionsSketchAggregationV2
import org.wfanet.measurement.system.v1alpha.AdvanceComputationRequest
import org.wfanet.measurement.system.v1alpha.AdvanceComputationRequest.Header.ProtocolCase
import org.wfanet.measurement.system.v1alpha.ComputationKey
import org.wfanet.measurement.system.v1alpha.LiquidLegionsV2
/** True if the protocol specified in the header is asynchronous. */
fun AdvanceComputationRequest.Header.isForAsyncComputation(): Boolean =
when (protocolCase) {
ProtocolCase.LIQUID_LEGIONS_V2 -> true
else -> failGrpc { "Unknown protocol $protocolCase" }
}
/** Returns the [ComputationStage] which expects the input described in the header. */
fun AdvanceComputationRequest.Header.stageExpectingInput(): ComputationStage =
when (protocolCase) {
ProtocolCase.LIQUID_LEGIONS_V2 -> liquidLegionsV2.stageExpectingInput()
else -> failGrpc { "Unknown protocol $protocolCase" }
}
private fun LiquidLegionsV2.stageExpectingInput(): ComputationStage =
when (description) {
LiquidLegionsV2.Description.SETUP_PHASE_INPUT ->
LiquidLegionsSketchAggregationV2.Stage.WAIT_SETUP_PHASE_INPUTS
LiquidLegionsV2.Description.EXECUTION_PHASE_ONE_INPUT ->
LiquidLegionsSketchAggregationV2.Stage.WAIT_EXECUTION_PHASE_ONE_INPUTS
LiquidLegionsV2.Description.EXECUTION_PHASE_TWO_INPUT ->
LiquidLegionsSketchAggregationV2.Stage.WAIT_EXECUTION_PHASE_TWO_INPUTS
LiquidLegionsV2.Description.EXECUTION_PHASE_THREE_INPUT ->
LiquidLegionsSketchAggregationV2.Stage.WAIT_EXECUTION_PHASE_THREE_INPUTS
else -> failGrpc { "Unknown LiquidLegionsV2 payload description '$description'." }
}.toProtocolStage()
/** Creates an [AdvanceComputationRequest.Header] for a liquid legions v2 computation. */
fun advanceComputationHeader(
liquidLegionsV2ContentDescription: LiquidLegionsV2.Description,
globalComputationId: String
): AdvanceComputationRequest.Header =
AdvanceComputationRequest.Header.newBuilder()
.apply {
name = ComputationKey(globalComputationId).toName()
liquidLegionsV2Builder.description = liquidLegionsV2ContentDescription
}
.build()
|
apache-2.0
|
5f2e6acc744e89ada58dbc52f9334f0a
| 46.984127 | 90 | 0.794575 | 4.498512 | false | false | false | false |
Mauin/detekt
|
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/ForbiddenClassName.kt
|
1
|
1566
|
package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.api.SplitPattern
import org.jetbrains.kotlin.psi.KtClassOrObject
/**
* Reports class names which are forbidden per configuration.
* By default this rule does not report any classes.
* Examples for forbidden names might be too generic class names like `...Manager`.
*
* @configuration forbiddenName - forbidden class names (default: '')
* @author Marvin Ramin
*/
class ForbiddenClassName(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(javaClass.simpleName, Severity.Style,
"Forbidden class name as per configuration detected.",
Debt.FIVE_MINS)
private val forbiddenNames = SplitPattern(valueOrDefault(FORBIDDEN_NAME, ""))
override fun visitClassOrObject(classOrObject: KtClassOrObject) {
val name = classOrObject.name ?: ""
val forbiddenEntries = forbiddenNames.matches(name)
if (forbiddenEntries.isNotEmpty()) {
var message = "Class name $name is forbidden as it contains:"
forbiddenEntries.forEach { message += " $it," }
message.trimEnd { it == ',' }
report(CodeSmell(issue, Entity.from(classOrObject), message))
}
}
companion object {
const val FORBIDDEN_NAME = "forbiddenName"
}
}
|
apache-2.0
|
629a984af380c5309d4734e822358c7e
| 34.590909 | 83 | 0.765006 | 3.944584 | false | true | false | false |
Dimigo-AppClass-Mission/SaveTheEarth
|
app/src/main/kotlin/me/hyemdooly/sangs/dimigo/app/project/database/Achieve.kt
|
1
|
519
|
package me.hyemdooly.sangs.dimigo.app.project.database
import io.realm.RealmObject
/**
* Created by songhyemin on 2017. 8. 24..
*/
public open class Achieve : RealmObject() {
public open var sequence: Int? = null // 순서
public open var categoryId: Int? = null // 시간 : 1, 레벨 : 2, 앱 사용 제약조건 : 3
public open var title : String? = null // 업적 이름
public open var purpose: Int? = null // 목표
public open var state: Boolean? = null // 상태, 했는지 안했는지
}
|
gpl-3.0
|
ebeeb0f32e2eadd7d8e112fe4ca14097
| 32.142857 | 76 | 0.658747 | 3.14966 | false | false | false | false |
TeamAmaze/AmazeFileManager
|
app/src/main/java/com/amaze/filemanager/ui/fragments/CompressedExplorerFragment.kt
|
1
|
29748
|
/*
* Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.ui.fragments
import android.content.ComponentName
import android.content.ContentResolver
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.KITKAT
import android.os.Build.VERSION_CODES.LOLLIPOP
import android.os.Bundle
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import android.view.ActionMode
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import androidx.core.view.children
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.MaterialDialog.SingleButtonCallback
import com.amaze.filemanager.R
import com.amaze.filemanager.adapters.CompressedExplorerAdapter
import com.amaze.filemanager.adapters.data.CompressedObjectParcelable
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.asynchronous.asynctasks.DeleteTask
import com.amaze.filemanager.asynchronous.services.ExtractService
import com.amaze.filemanager.databinding.ActionmodeBinding
import com.amaze.filemanager.databinding.MainFragBinding
import com.amaze.filemanager.fileoperations.filesystem.OpenMode
import com.amaze.filemanager.fileoperations.filesystem.compressed.ArchivePasswordCache
import com.amaze.filemanager.filesystem.HybridFileParcelable
import com.amaze.filemanager.filesystem.compressed.CompressedHelper
import com.amaze.filemanager.filesystem.compressed.showcontents.Decompressor
import com.amaze.filemanager.filesystem.files.FileUtils
import com.amaze.filemanager.ui.activities.MainActivity
import com.amaze.filemanager.ui.colors.ColorPreferenceHelper
import com.amaze.filemanager.ui.dialogs.GeneralDialogCreation
import com.amaze.filemanager.ui.fragments.data.CompressedExplorerFragmentViewModel
import com.amaze.filemanager.ui.fragments.preferencefragments.PreferencesConstants
import com.amaze.filemanager.ui.theme.AppTheme
import com.amaze.filemanager.ui.views.DividerItemDecoration
import com.amaze.filemanager.ui.views.FastScroller
import com.amaze.filemanager.utils.BottomBarButtonPath
import com.amaze.filemanager.utils.Utils
import com.github.junrar.exception.UnsupportedRarV5Exception
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.apache.commons.compress.PasswordRequiredException
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
@Suppress("TooManyFunctions")
class CompressedExplorerFragment : Fragment(), BottomBarButtonPath {
lateinit var compressedFile: File
private val viewModel: CompressedExplorerFragmentViewModel by viewModels()
/**
* files to be deleted from cache with a Map maintaining key - the root of directory created (for
* deletion purposes after we exit out of here and value - the path of file to open
*/
@JvmField
var files: ArrayList<HybridFileParcelable>? = null
@JvmField
var selection = false
/** Normally this would be "/" but for pathing issues it isn't */
var relativeDirectory = ""
@JvmField
@ColorInt
var accentColor = 0
@JvmField
@ColorInt
var iconskin = 0
var compressedExplorerAdapter: CompressedExplorerAdapter? = null
@JvmField
var mActionMode: ActionMode? = null
@JvmField
var coloriseIcons = false
@JvmField
var showSize = false
@JvmField
var showLastModified = false
var gobackitem = false
var listView: RecyclerView? = null
lateinit var swipeRefreshLayout: SwipeRefreshLayout
/** flag states whether to open file after service extracts it */
@JvmField
var isOpen = false
private lateinit var fastScroller: FastScroller
private lateinit var decompressor: Decompressor
private var addheader = true
private var dividerItemDecoration: DividerItemDecoration? = null
private var showDividers = false
private var mToolbarContainer: View? = null
private var stopAnims = true
private var file = 0
private var folder = 0
private var isCachedCompressedFile = false
private val offsetListenerForToolbar =
OnOffsetChangedListener { appBarLayout: AppBarLayout?, verticalOffset: Int ->
fastScroller.updateHandlePosition(verticalOffset, 112)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val rootView: View = MainFragBinding.inflate(inflater).root
listView = rootView.findViewById<RecyclerView>(R.id.listView).also {
it.setOnTouchListener { _: View?, _: MotionEvent? ->
compressedExplorerAdapter?.apply {
if (stopAnims && !this.stoppedAnimation) {
stopAnim()
}
this.stoppedAnimation = true
stopAnims = false
}
false
}
}
swipeRefreshLayout = rootView
.findViewById<SwipeRefreshLayout>(R.id.activity_main_swipe_refresh_layout).also {
it.setOnRefreshListener { refresh() }
it.isRefreshing = true
}
viewModel.elements.observe(
viewLifecycleOwner,
{ elements ->
viewModel.folder?.run {
createViews(elements, this)
swipeRefreshLayout.isRefreshing = false
updateBottomBar()
}
}
)
return rootView
}
/**
* Stop animation at archive file list view.
*/
fun stopAnim() {
listView?.children?.forEach { v ->
v.clearAnimation()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val sp = PreferenceManager.getDefaultSharedPreferences(requireActivity())
val fileName = prepareCompressedFile(requireArguments().getString(KEY_PATH, "/"))
mToolbarContainer = requireMainActivity().appbar.appbarLayout.also {
it.setOnTouchListener { _: View?, _: MotionEvent? ->
if (stopAnims) {
if (false == compressedExplorerAdapter?.stoppedAnimation) {
stopAnim()
}
compressedExplorerAdapter?.stoppedAnimation = true
}
stopAnims = false
false
}
}
listView?.visibility = View.VISIBLE
listView?.layoutManager = LinearLayoutManager(activity)
val utilsProvider = AppConfig.getInstance().utilsProvider
when (utilsProvider.appTheme) {
AppTheme.DARK ->
requireView()
.setBackgroundColor(Utils.getColor(context, R.color.holo_dark_background))
AppTheme.BLACK ->
listView?.setBackgroundColor(Utils.getColor(context, android.R.color.black))
else ->
listView?.setBackgroundColor(
Utils.getColor(
context,
android.R.color.background_light
)
)
}
gobackitem = sp.getBoolean(PreferencesConstants.PREFERENCE_SHOW_GOBACK_BUTTON, false)
coloriseIcons = sp.getBoolean(PreferencesConstants.PREFERENCE_COLORIZE_ICONS, true)
showSize = sp.getBoolean(PreferencesConstants.PREFERENCE_SHOW_FILE_SIZE, false)
showLastModified = sp.getBoolean(PreferencesConstants.PREFERENCE_SHOW_LAST_MODIFIED, true)
showDividers = sp.getBoolean(PreferencesConstants.PREFERENCE_SHOW_DIVIDERS, true)
accentColor = requireMainActivity().accent
iconskin = requireMainActivity().currentColorPreference.iconSkin
// mainActivity.findViewById(R.id.buttonbarframe).setBackgroundColor(Color.parseColor(skin));
if (savedInstanceState == null) {
compressedFile.run {
files = ArrayList()
// adding a cache file to delete where any user interaction elements will be cached
val path =
if (isCachedCompressedFile) {
this.absolutePath
} else {
requireActivity().externalCacheDir!!
.path + CompressedHelper.SEPARATOR + fileName
}
files?.add(HybridFileParcelable(path))
val decompressor = CompressedHelper.getCompressorInstance(requireContext(), this)
if (decompressor == null) {
Toast.makeText(
requireContext(),
R.string.error_cant_decompress_that_file,
Toast.LENGTH_LONG
).show()
parentFragmentManager.beginTransaction()
.remove(this@CompressedExplorerFragment).commit()
return
}
[email protected] = decompressor
changePath("")
}
} else {
onRestoreInstanceState(savedInstanceState)
}
requireMainActivity().supportInvalidateOptionsMenu()
}
private fun prepareCompressedFile(pathArg: String): String {
val pathUri = Uri.parse(pathArg)
var fileName: String = pathUri.path ?: "filename"
if (ContentResolver.SCHEME_CONTENT == pathUri.scheme) {
requireContext()
.contentResolver
.query(
pathUri,
arrayOf(MediaStore.MediaColumns.DISPLAY_NAME),
null,
null,
null
)?.run {
try {
if (moveToFirst()) {
fileName = getString(0)
compressedFile = File(requireContext().cacheDir, fileName)
} else {
// At this point, we know nothing the file the URI represents, we are doing everything
// wild guess.
compressedFile =
File.createTempFile(
"compressed",
null,
requireContext().cacheDir
)
.also {
fileName = it.name
}
}
compressedFile.deleteOnExit()
FileOutputStream(compressedFile).use { outputStream ->
requireContext().contentResolver.openInputStream(pathUri)
?.use { it.copyTo(outputStream, DEFAULT_BUFFER_SIZE) }
}
isCachedCompressedFile = true
} catch (e: IOException) {
Log.e(TAG, "Error opening URI $pathUri for reading", e)
AppConfig.toast(
requireContext(),
requireContext()
.getString(
R.string.compressed_explorer_fragment_error_open_uri,
pathUri.toString()
)
)
requireActivity().onBackPressed()
} finally {
close()
}
}
} else {
pathUri.path?.let { path ->
compressedFile = File(path).also {
fileName = it.name.substring(0, it.name.lastIndexOf("."))
}
}
}
return fileName
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putParcelableArrayList(KEY_ELEMENTS, viewModel.elements.value)
outState.putString(KEY_PATH, relativeDirectory)
outState.putString(KEY_URI, compressedFile.path)
outState.putParcelableArrayList(KEY_CACHE_FILES, files)
outState.putBoolean(KEY_OPEN, isOpen)
}
private fun onRestoreInstanceState(savedInstanceState: Bundle?) {
savedInstanceState?.let { bundle ->
prepareCompressedFile(bundle.getString(KEY_URI)!!)
files = bundle.getParcelableArrayList(KEY_CACHE_FILES)
isOpen = bundle.getBoolean(KEY_OPEN)
relativeDirectory = bundle.getString(KEY_PATH, "")
compressedFile.let {
val decompressor = CompressedHelper.getCompressorInstance(requireContext(), it)
if (decompressor == null) {
parentFragmentManager.beginTransaction()
.remove(this@CompressedExplorerFragment).commit()
Toast.makeText(
requireContext(),
R.string.error_cant_decompress_that_file,
Toast.LENGTH_LONG
).show()
return
}
[email protected] = decompressor
}
viewModel.elements.value = bundle.getParcelableArrayList(KEY_ELEMENTS)
}
}
@JvmField
var mActionModeCallback: ActionMode.Callback = object : ActionMode.Callback {
private fun hideOption(id: Int, menu: Menu) {
val item = menu.findItem(id)
item.isVisible = false
}
private fun showOption(id: Int, menu: Menu) {
val item = menu.findItem(id)
item.isVisible = true
}
// called when the action mode is created; startActionMode() was called
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
// Inflate a menu resource providing context menu items
val v = ActionmodeBinding.inflate(LayoutInflater.from(requireContext())).root
mode.customView = v
// assumes that you have "contexual.xml" menu resources
mode.menuInflater.inflate(R.menu.contextual, menu)
hideOption(R.id.cpy, menu)
hideOption(R.id.cut, menu)
hideOption(R.id.delete, menu)
hideOption(R.id.addshortcut, menu)
hideOption(R.id.share, menu)
hideOption(R.id.openwith, menu)
showOption(R.id.all, menu)
hideOption(R.id.compress, menu)
hideOption(R.id.hide, menu)
showOption(R.id.ex, menu)
mode.title = getString(R.string.select)
requireMainActivity().updateViews(
ColorDrawable(
Utils.getColor(
context,
R.color.holo_dark_action_mode
)
)
)
if (SDK_INT >= LOLLIPOP) {
val window = requireActivity().window
if (requireMainActivity()
.getBoolean(PreferencesConstants.PREFERENCE_COLORED_NAVIGATION)
) {
window.navigationBarColor =
Utils.getColor(context, android.R.color.black)
}
}
if (SDK_INT < KITKAT) {
requireMainActivity().appbar.toolbar.visibility = View.GONE
}
return true
}
// the following method is called each time
// the action mode is shown. Always called after
// onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
compressedExplorerAdapter?.checkedItemPositions?.let { positions ->
(mode.customView.findViewById<View>(R.id.item_count) as TextView).text =
positions.size.toString()
menu.findItem(R.id.all)
.setTitle(
if (positions.size == folder + file) {
R.string.deselect_all
} else {
R.string.select_all
}
)
}
return false // Return false if nothing is done
}
// called when the user selects a contextual menu item
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return compressedExplorerAdapter?.let {
when (item.itemId) {
R.id.all -> {
val positions = it.checkedItemPositions
val shouldDeselectAll = positions.size != folder + file
it.toggleChecked(shouldDeselectAll)
mode.invalidate()
item.setTitle(
if (shouldDeselectAll) {
R.string.deselect_all
} else {
R.string.select_all
}
)
if (!shouldDeselectAll) {
selection = false
mActionMode?.finish()
mActionMode = null
}
return true
}
R.id.ex -> {
Toast.makeText(activity, getString(R.string.extracting), Toast.LENGTH_SHORT)
.show()
val dirs = arrayOfNulls<String>(
it.checkedItemPositions.size
)
var i = 0
while (i < dirs.size) {
dirs[i] =
viewModel
.elements
.value!![it.checkedItemPositions[i]].path
i++
}
decompressor.decompress(compressedFile.path, dirs)
mode.finish()
return true
}
else -> false
}
} ?: false
}
override fun onDestroyActionMode(actionMode: ActionMode) {
compressedExplorerAdapter?.toggleChecked(false)
@ColorInt val primaryColor = ColorPreferenceHelper.getPrimary(
requireMainActivity().currentColorPreference,
MainActivity.currentTab
)
selection = false
requireMainActivity().updateViews(ColorDrawable(primaryColor))
if (SDK_INT >= LOLLIPOP) {
val window = requireActivity().window
if (requireMainActivity()
.getBoolean(PreferencesConstants.PREFERENCE_COLORED_NAVIGATION)
) {
window.navigationBarColor =
requireMainActivity().skinStatusBar
}
}
mActionMode = null
}
}
override fun onDestroyView() {
super.onDestroyView()
// Clearing the touch listeners allows the fragment to
// be cleaned after it is destroyed, preventing leaks
mToolbarContainer?.setOnTouchListener(null)
(mToolbarContainer as AppBarLayout?)?.removeOnOffsetChangedListener(
offsetListenerForToolbar
)
requireMainActivity().supportInvalidateOptionsMenu()
// needed to remove any extracted file from cache, when onResume was not called
// in case of opening any unknown file inside the zip
if (true == files?.isNotEmpty() && true == files?.get(0)?.exists()) {
DeleteTask(requireActivity(), this).execute(files)
}
if (isCachedCompressedFile) {
compressedFile.delete()
}
}
override fun onResume() {
super.onResume()
requireMainActivity().hideFab()
val intent = Intent(activity, ExtractService::class.java)
requireActivity().bindService(intent, mServiceConnection, 0)
}
override fun onPause() {
super.onPause()
requireActivity().unbindService(mServiceConnection)
}
private val mServiceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) = Unit
override fun onServiceDisconnected(name: ComponentName) {
// open file if pending
if (isOpen) {
files?.let { cachedFiles ->
// open most recent entry added to files to be deleted from cache
val cacheFile = File(cachedFiles[cachedFiles.size - 1].path)
if (cacheFile.exists()) {
FileUtils.openFile(
cacheFile,
requireMainActivity(),
requireMainActivity().prefs
)
}
// reset the flag and cache file, as it's root is already in the list for deletion
isOpen = false
cachedFiles.removeAt(cachedFiles.size - 1)
}
}
}
}
override fun changePath(path: String) {
var folder = path
if (folder.startsWith("/")) folder = folder.substring(1)
val addGoBackItem = gobackitem && !isRoot(folder)
decompressor.let {
Flowable.fromCallable(it.changePath(folder, addGoBackItem))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ result ->
viewModel.elements.postValue(result)
viewModel.folder = folder
},
{ error ->
if (error is PasswordRequiredException) {
dialogGetPasswordFromUser(folder)
} else {
archiveCorruptOrUnsupportedToast(error)
}
}
)
swipeRefreshLayout.isRefreshing = true
updateBottomBar()
}
}
private fun dialogGetPasswordFromUser(filePath: String) {
val positiveCallback =
SingleButtonCallback { dialog: MaterialDialog, action: DialogAction? ->
val editText = dialog.view.findViewById<EditText>(R.id.singleedittext_input)
val password: String = editText.getText().toString()
ArchivePasswordCache.getInstance()[filePath] = password
dialog.dismiss()
changePath(filePath)
}
ArchivePasswordCache.getInstance().remove(filePath)
GeneralDialogCreation.showPasswordDialog(
requireContext(),
(requireActivity() as MainActivity),
AppConfig.getInstance().utilsProvider.appTheme,
R.string.archive_password_prompt,
R.string.authenticate_password,
positiveCallback,
null
)
}
private fun archiveCorruptOrUnsupportedToast(e: Throwable?) {
@StringRes val msg: Int =
if (e?.cause?.javaClass is UnsupportedRarV5Exception) {
R.string.error_unsupported_v5_rar
} else {
R.string.archive_unsupported_or_corrupt
}
Toast.makeText(
activity,
requireContext().getString(msg, compressedFile.absolutePath),
Toast.LENGTH_LONG
).show()
requireActivity().supportFragmentManager.beginTransaction().remove(this).commit()
}
override val path: String
get() = if (!isRootRelativePath) {
CompressedHelper.SEPARATOR + relativeDirectory
} else {
""
}
override val rootDrawable: Int
get() = R.drawable.ic_compressed_white_24dp
private fun refresh() {
changePath(relativeDirectory)
}
private fun updateBottomBar() {
compressedFile.let {
val path =
if (!isRootRelativePath) {
it.name + CompressedHelper.SEPARATOR + relativeDirectory
} else {
it.name
}
requireMainActivity()
.getAppbar()
.bottomBar
.updatePath(path, false, null, OpenMode.FILE, folder, file, this)
}
}
private fun createViews(items: List<CompressedObjectParcelable>?, dir: String) {
if (compressedExplorerAdapter == null) {
compressedExplorerAdapter = CompressedExplorerAdapter(
activity,
AppConfig.getInstance().utilsProvider,
items,
this,
decompressor,
PreferenceManager.getDefaultSharedPreferences(requireMainActivity())
)
listView?.adapter = compressedExplorerAdapter
} else {
compressedExplorerAdapter?.generateZip(items)
}
folder = 0
file = 0
items?.forEach { item ->
if (item.type == CompressedObjectParcelable.TYPE_GOBACK) Unit // do nothing
if (item.directory) folder++ else file++
}
stopAnims = true
if (!addheader) {
dividerItemDecoration?.run {
listView?.removeItemDecoration(this)
}
// listView.removeItemDecoration(headersDecor);
addheader = true
} else {
dividerItemDecoration = DividerItemDecoration(
activity,
true,
showDividers
).also {
listView?.addItemDecoration(it)
}
// headersDecor = new StickyRecyclerHeadersDecoration(compressedExplorerAdapter);
// listView.addItemDecoration(headersDecor);
addheader = false
}
fastScroller = requireView().findViewById<FastScroller>(R.id.fastscroll).also {
it.setRecyclerView(listView!!, 1)
it.setPressedHandleColor(requireMainActivity().accent)
}
(mToolbarContainer as AppBarLayout?)?.addOnOffsetChangedListener(offsetListenerForToolbar)
listView?.stopScroll()
relativeDirectory = dir
updateBottomBar()
swipeRefreshLayout.isRefreshing = false
}
/**
* Indicator whether navigation through back button is possible.
*/
fun canGoBack(): Boolean {
return !isRootRelativePath
}
/**
* Go one level up in the archive hierarchy.
*/
fun goBack() {
val parent: String = File(relativeDirectory).parent ?: ""
changePath(parent)
}
private val isRootRelativePath: Boolean
get() = isRoot(relativeDirectory)
private fun isRoot(folder: String?): Boolean {
return folder == null || folder.isEmpty()
}
/**
* Wrapper of requireActivity() to return [MainActivity].
*
* @return [MainActivity]
*/
fun requireMainActivity(): MainActivity = requireActivity() as MainActivity
companion object {
const val KEY_PATH = "path"
private const val KEY_CACHE_FILES = "cache_files"
private const val KEY_URI = "uri"
private const val KEY_ELEMENTS = "elements"
private const val KEY_OPEN = "is_open"
private val TAG = CompressedExplorerFragment::class.java.simpleName
}
}
|
gpl-3.0
|
37e9eb34cd5f8c74edc9d4eb2e07fc32
| 38.983871 | 114 | 0.579535 | 5.776311 | false | false | false | false |
GeoffreyMetais/vlc-android
|
application/vlc-android/src/org/videolan/vlc/gui/AudioPlayerContainerActivity.kt
|
1
|
17220
|
/*
* *************************************************************************
* AudioPlayerContainerActivity.kt
* **************************************************************************
* Copyright © 2019 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui
import android.annotation.SuppressLint
import android.media.AudioManager
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.appcompat.widget.ViewStubCompat
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.bottomsheet.BottomSheetBehavior.*
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.tabs.TabLayout
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.ObsoleteCoroutinesApi
import kotlinx.coroutines.delay
import org.videolan.libvlc.util.AndroidUtil
import org.videolan.medialibrary.interfaces.Medialibrary
import org.videolan.resources.util.getFromMl
import org.videolan.resources.util.startMedialibrary
import org.videolan.tools.*
import org.videolan.vlc.*
import org.videolan.vlc.gui.audio.AudioPlayer
import org.videolan.vlc.gui.browser.StorageBrowserFragment
import org.videolan.vlc.gui.helpers.BottomNavigationBehavior
import org.videolan.vlc.gui.helpers.PlayerBehavior
import org.videolan.vlc.gui.helpers.UiTools
import org.videolan.vlc.gui.helpers.getHeightWhenReady
import org.videolan.vlc.interfaces.IRefreshable
import org.videolan.vlc.media.PlaylistManager
private const val TAG = "VLC/APCActivity"
private const val ACTION_DISPLAY_PROGRESSBAR = 1339
private const val ACTION_SHOW_PLAYER = 1340
private const val ACTION_HIDE_PLAYER = 1341
private const val BOTTOM_IS_HIDDEN = "bottom_is_hidden"
@SuppressLint("Registered")
@ExperimentalCoroutinesApi
@ObsoleteCoroutinesApi
open class AudioPlayerContainerActivity : BaseActivity() {
private var bottomBar: BottomNavigationView? = null
protected lateinit var appBarLayout: AppBarLayout
protected lateinit var toolbar: Toolbar
private var tabLayout: TabLayout? = null
protected lateinit var audioPlayer: AudioPlayer
private lateinit var audioPlayerContainer: FrameLayout
lateinit var playerBehavior: PlayerBehavior<*>
protected lateinit var fragmentContainer: View
protected var originalBottomPadding: Int = 0
private var scanProgressLayout: View? = null
private var scanProgressText: TextView? = null
private var scanProgressBar: ProgressBar? = null
private lateinit var resumeCard: Snackbar
private var preventRescan = false
protected val currentFragment: Fragment?
get() = supportFragmentManager.findFragmentById(R.id.fragment_placeholder)
val menu: Menu
get() = toolbar.menu
@Suppress("LeakingThis")
protected val handler: Handler = ProgressHandler(this)
val isAudioPlayerReady: Boolean
get() = ::audioPlayer.isInitialized
val isAudioPlayerExpanded: Boolean
get() = isAudioPlayerReady && playerBehavior.state == STATE_EXPANDED
var bottomIsHiddden: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
//Init Medialibrary if KO
if (savedInstanceState != null) {
this.startMedialibrary(firstRun = false, upgrade = false, parse = true)
bottomIsHiddden = savedInstanceState.getBoolean(BOTTOM_IS_HIDDEN, false)
}
super.onCreate(savedInstanceState)
volumeControlStream = AudioManager.STREAM_MUSIC
registerLiveData()
}
protected open fun initAudioPlayerContainerActivity() {
findViewById<View>(R.id.fragment_placeholder)?.let {
fragmentContainer = it
originalBottomPadding = fragmentContainer.paddingBottom
}
toolbar = findViewById(R.id.main_toolbar)
setSupportActionBar(toolbar)
appBarLayout = findViewById(R.id.appbar)
tabLayout = findViewById(R.id.sliding_tabs)
appBarLayout.setExpanded(true)
bottomBar = findViewById(R.id.navigation)
if (bottomIsHiddden) {
bottomBar?.let {
val bottomBehavior = BottomNavigationBehavior.from(it) as BottomNavigationBehavior<*>
bottomBehavior.isPlayerHidden = true
it.getHeightWhenReady { height -> it.translationY = height.toFloat() }
}
}
tabLayout?.viewTreeObserver?.addOnGlobalLayoutListener {
//add a shadow if there are tabs
if (AndroidUtil.isLolliPopOrLater) appBarLayout.elevation = if (tabLayout?.isVisible() == true) 4.dp.toFloat() else 0.dp.toFloat()
}
audioPlayerContainer = findViewById(R.id.audio_player_container)
}
fun setTabLayoutVisibility(show: Boolean) {
tabLayout?.visibility = if (show) View.VISIBLE else View.GONE
}
private fun initAudioPlayer() {
findViewById<View>(R.id.audio_player_stub).visibility = View.VISIBLE
audioPlayer = supportFragmentManager.findFragmentById(R.id.audio_player) as AudioPlayer
playerBehavior = from(audioPlayerContainer) as PlayerBehavior<*>
val bottomBehavior = bottomBar?.let { BottomNavigationBehavior.from(it) as BottomNavigationBehavior<*> }
?: null
playerBehavior.peekHeight = resources.getDimensionPixelSize(R.dimen.player_peek_height)
playerBehavior.addBottomSheetCallback(object : BottomSheetCallback() {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
audioPlayer.onSlide(slideOffset)
}
override fun onStateChanged(bottomSheet: View, newState: Int) {
onPlayerStateChanged(bottomSheet, newState)
audioPlayer.onStateChanged(newState)
if (newState == STATE_COLLAPSED || newState == STATE_HIDDEN) removeTipViewIfDisplayed()
bottomBehavior?.let { bottomBehavior ->
bottomBar?.let { bottomBar ->
if (newState == STATE_DRAGGING) {
bottomBehavior.animateBarVisibility(bottomBar, false)
bottomBehavior.isPlayerHidden = true
}
if (newState == STATE_COLLAPSED) {
bottomBehavior.animateBarVisibility(bottomBar, true)
bottomBehavior.isPlayerHidden = false
}
}
}
}
})
showTipViewIfNeeded(R.id.audio_player_tips, PREF_AUDIOPLAYER_TIPS_SHOWN)
}
override fun onSaveInstanceState(outState: Bundle) {
outState.putBoolean(BOTTOM_IS_HIDDEN, bottomBar?.let { BottomNavigationBehavior.from(it) as BottomNavigationBehavior<*> }?.isPlayerHidden
?: false)
super.onSaveInstanceState(outState)
}
fun expandAppBar() {
appBarLayout.setExpanded(true)
}
override fun onStart() {
ExternalMonitor.subscribeStorageCb(this)
super.onStart()
}
override fun onRestart() {
super.onRestart()
preventRescan = true
}
override fun onStop() {
super.onStop()
ExternalMonitor.unsubscribeStorageCb(this)
}
override fun onDestroy() {
handler.removeMessages(ACTION_SHOW_PLAYER)
super.onDestroy()
}
override fun onBackPressed() {
if (slideDownAudioPlayer()) return
super.onBackPressed()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle item selection
when (item.itemId) {
android.R.id.home -> {
// Current fragment loaded
val current = currentFragment
if (current is StorageBrowserFragment && current.goBack())
return true
finish()
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
fun updateLib() {
if (preventRescan) {
preventRescan = false
return
}
val fm = supportFragmentManager
val current = fm.findFragmentById(R.id.fragment_placeholder)
if (current is IRefreshable) (current as IRefreshable).refresh()
}
/**
* Show a tip view.
* @param stubId the stub of the tip view
* @param settingKey the setting key to check if the view must be displayed or not.
*/
@SuppressLint("RestrictedApi")
fun showTipViewIfNeeded(stubId: Int, settingKey: String) {
if (BuildConfig.DEBUG || PlaybackService.hasRenderer()) return
val vsc = findViewById<View>(stubId)
if (vsc != null && !settings.getBoolean(settingKey, false) && !Settings.showTvUi) {
val v = (vsc as ViewStubCompat).inflate()
v.setOnClickListener { removeTipViewIfDisplayed() }
val okGotIt = v.findViewById<TextView>(R.id.okgotit_button)
okGotIt.setOnClickListener {
removeTipViewIfDisplayed()
settings.putSingle(settingKey, true)
}
}
}
/**
* Remove the current tip view if there is one displayed.
*/
fun removeTipViewIfDisplayed() {
findViewById<View>(R.id.audio_tips)?.let { (it.parent as ViewGroup).removeView(it) }
}
/**
* Show the audio player.
*/
private fun showAudioPlayer() {
if (isFinishing) return
handler.sendEmptyMessageDelayed(ACTION_SHOW_PLAYER, 100L)
}
private fun showAudioPlayerImpl() {
if (isFinishing) return
if (!isAudioPlayerReady) initAudioPlayer()
if (audioPlayerContainer.visibility != View.VISIBLE) {
audioPlayerContainer.visibility = View.VISIBLE
}
playerBehavior.run {
if (state == STATE_HIDDEN) state = STATE_COLLAPSED
isHideable = false
lock(false)
}
}
/**
* Slide down the audio player.
* @return true on success else false.
*/
fun slideDownAudioPlayer(): Boolean {
if (isAudioPlayerReady && playerBehavior.state == STATE_EXPANDED) {
playerBehavior.state = STATE_COLLAPSED
return true
}
return false
}
/**
* Slide up and down the audio player depending on its current state.
*/
fun slideUpOrDownAudioPlayer() {
if (!isAudioPlayerReady || playerBehavior.state == STATE_HIDDEN) return
playerBehavior.state = if (playerBehavior.state == STATE_EXPANDED)
STATE_COLLAPSED
else
STATE_EXPANDED
}
/**
* Hide the audio player.
*/
fun hideAudioPlayer() {
if (isFinishing) return
handler.removeMessages(ACTION_SHOW_PLAYER)
handler.sendEmptyMessage(ACTION_HIDE_PLAYER)
}
private fun hideAudioPlayerImpl() {
if (!isAudioPlayerReady) return
playerBehavior.isHideable = true
playerBehavior.state = STATE_HIDDEN
}
private fun updateProgressVisibility(show: Boolean, discovery: String? = null, parsing: Int = -1) {
val visibility = if (show) View.VISIBLE else View.GONE
if (scanProgressLayout?.visibility == visibility) return
if (show) {
val msg = handler.obtainMessage(ACTION_DISPLAY_PROGRESSBAR, parsing, 0, discovery)
handler.sendMessageDelayed(msg, 1000L)
} else {
handler.removeMessages(ACTION_DISPLAY_PROGRESSBAR)
scanProgressLayout.setVisibility(visibility)
}
}
private fun showProgressBar(discovery: String, parsing: Int) {
if (!Medialibrary.getInstance().isWorking) return
val vsc = findViewById<View>(R.id.scan_viewstub)
if (vsc != null) {
vsc.visibility = View.VISIBLE
scanProgressLayout = findViewById(R.id.scan_progress_layout)
scanProgressText = findViewById(R.id.scan_progress_text)
scanProgressBar = findViewById(R.id.scan_progress_bar)
} else scanProgressLayout?.visibility = View.VISIBLE
scanProgressText?.text = discovery
scanProgressBar?.progress = parsing
}
protected fun updateContainerPadding(show: Boolean) {
if (!::fragmentContainer.isInitialized) return
val factor = if (show) 1 else 0
val peekHeight = if (show && isAudioPlayerReady) playerBehavior.peekHeight else 0
fragmentContainer.run {
setPadding(paddingLeft, paddingTop, paddingRight, originalBottomPadding + factor * peekHeight)
}
}
private fun applyMarginToProgressBar(marginValue: Int) {
if (scanProgressLayout != null && scanProgressLayout?.visibility == View.VISIBLE) {
val lp = scanProgressLayout!!.layoutParams as CoordinatorLayout.LayoutParams
lp.bottomMargin = marginValue
scanProgressLayout?.layoutParams = lp
}
}
protected open fun onPlayerStateChanged(bottomSheet: View, newState: Int) {}
private fun registerLiveData() {
PlaylistManager.showAudioPlayer.observe(this, Observer { showPlayer ->
if (showPlayer == true) showAudioPlayer()
else {
hideAudioPlayer()
if (isAudioPlayerReady) playerBehavior.lock(true)
}
})
MediaParsingService.progress.observe(this, Observer { scanProgress ->
if (scanProgress == null || !Medialibrary.getInstance().isWorking) {
updateProgressVisibility(false)
return@Observer
}
updateProgressVisibility(true, scanProgress.discovery, scanProgress.parsing)
scanProgressText?.text = scanProgress.discovery
scanProgressBar?.progress = scanProgress.parsing
})
MediaParsingService.newStorages.observe(this, Observer<List<String>> { devices ->
if (devices == null) return@Observer
for (device in devices) UiTools.newStorageDetected(this@AudioPlayerContainerActivity, device)
MediaParsingService.newStorages.setValue(null)
})
}
@SuppressLint("RestrictedApi")
fun proposeCard() = lifecycleScope.launchWhenStarted {
delay(1000L)
if (PlaylistManager.showAudioPlayer.value == true) return@launchWhenStarted
val song = settings.getString("current_song", null) ?: return@launchWhenStarted
val media = getFromMl { getMedia(Uri.parse(song)) } ?: return@launchWhenStarted
val title = media.title
resumeCard = Snackbar.make(appBarLayout, getString(R.string.resume_card_message, title), Snackbar.LENGTH_LONG)
.setAction(R.string.play) { PlaybackService.loadLastAudio(it.context) }
resumeCard.show()
}
private class ProgressHandler(owner: AudioPlayerContainerActivity) : WeakHandler<AudioPlayerContainerActivity>(owner) {
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
val owner = owner ?: return
when (msg.what) {
ACTION_DISPLAY_PROGRESSBAR -> {
removeMessages(ACTION_DISPLAY_PROGRESSBAR)
owner.showProgressBar(msg.obj as String, msg.arg1)
}
ACTION_SHOW_PLAYER -> owner.run {
if (this::resumeCard.isInitialized && resumeCard.isShown) resumeCard.dismiss()
showAudioPlayerImpl()
updateContainerPadding(true)
if (::playerBehavior.isInitialized) owner.applyMarginToProgressBar(playerBehavior.peekHeight)
}
ACTION_HIDE_PLAYER -> owner.run {
hideAudioPlayerImpl()
updateContainerPadding(false)
applyMarginToProgressBar(0)
}
}
}
}
}
|
gpl-2.0
|
19ca536eae78481e096c858bb2ca6274
| 38.310502 | 145 | 0.653851 | 5.127457 | false | false | false | false |
benkyokai/tumpaca
|
app/src/main/kotlin/com/tumpaca/tp/fragment/post/PhotoPostFragment.kt
|
1
|
10305
|
package com.tumpaca.tp.fragment.post
/**
* Created by yabu on 7/11/16.
*/
import android.app.Dialog
import android.graphics.Color
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.webkit.WebView
import android.widget.ImageView
import android.widget.LinearLayout
import com.felipecsl.gifimageview.library.GifImageView
import com.tumblr.jumblr.types.PhotoPost
import com.tumpaca.tp.R
import com.tumpaca.tp.activity.MainActivity
import com.tumpaca.tp.util.*
import com.tumpaca.tp.view.GifSquareImageView
class PhotoPostFragment : PostFragment() {
companion object {
private const val LOADING_VIEW_ID = 1
private var loadingGifBytes: ByteArray? = null
private const val TAG = "PhotoPost"
private val tmpRect = Rect()
}
// このViewが実際に画面に表示されているかどうか。
// ViewPagerでの使用を想定しているので、isVisible()は信用できない
// (ViewPagerのcurrentItemでなくても事前ロードされるときからtrueが返るため)
// この値はsetUserVisibleHint()で受け取って、onPause()やonResume()で
// 変更しない(アプリがバックグラウンドにいるときなど実際に画面に描画されて
// いなくてもこのステートはそのまま。
var isVisibleToUser = false
var imageLayout: LinearLayout? = null
// GIFの可視判定を行う呼び出しに渡す必要があるが、中身は使っていない
var mView: View? = null
val onScrollChangedListener = object : ViewTreeObserver.OnScrollChangedListener {
override fun onScrollChanged() {
startStopAnimations()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = inflater.inflate(R.layout.post_photo, container, false)
mView = view
getPost {
if (isAdded && it is PhotoPost) {
update(view, it)
}
}
val webView = view.findViewById<WebView>(R.id.sub)
UIUtil.loadCss(webView)
return view
}
override fun onDetach() {
mView?.viewTreeObserver?.removeOnScrollChangedListener(onScrollChangedListener)
super.onDetach()
}
private fun update(view: View, post: PhotoPost) {
// データを取得
val sizes = post.photos.map { it.getBestSizeForScreen(resources.displayMetrics) }
initStandardViews(view, post.blogName, post.caption, post.rebloggedFromName, post.noteCount)
setIcon(view, post)
// ImageViewを挿入するPhotoListLayoutを取得
imageLayout = view.findViewById<LinearLayout>(R.id.photo_list)
// このポストにGIFがあったら、再生/停止判定を行うリスナーを追加する
if (sizes.map { pair -> pair.first.url }.any { it.endsWith(".gif") }) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
view.setOnScrollChangeListener { _, _, _, _, _ ->
// スクロール位置によって見えてきたものを再生、見えなくなったものを停止
startStopAnimations()
}
} else {
view.viewTreeObserver.addOnScrollChangedListener {
onScrollChangedListener
}
}
imageLayout?.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
// ローディングなどでレイアウトが変わると見えるものも変わるので再判定
startStopAnimations()
}
}
if (loadingGifBytes == null) {
loadingGifBytes = resources.openRawResource(R.raw.tumpaca_run).readBytes()
}
val loadingGifView = createLoadingGifImageView()
loadingGifView.id = LOADING_VIEW_ID
loadingGifView.setBackgroundColor(Color.parseColor("#35465c"))
imageLayout?.addView(loadingGifView)
loadingGifView.setBytes(loadingGifBytes)
loadingGifView.gotoFrame(0)
/**
* urls.size個の画像があるので、個数分のImageViewを生成して、PhotoListLayoutに追加する
*/
for ((i, size) in sizes.enumerate()) {
// gifだった場合はGif用のcustom image viewを使う
if (size.first.url.endsWith(".gif")) {
val gifView = createGifImageView(i != 0)
imageLayout?.addView(gifView)
attachImageSaveListener(gifView, size.second.url)
DownloadUtils.downloadGif(size.first.url)
.subscribe { gif: ByteArray ->
gifView.setBytes(gif)
if (isVisibleToUser) {
// すでに見えているので今すぐアニメーションを開始
gifView.startAnimation()
} else {
// まだ見えていないけれど、何も描画しないと可視判定ができないので
// とりあえず最初のコマだけ表示しておく
gifView.gotoFrame(0)
}
imageLayout?.removeView(loadingGifView)
}
} else {
val iView = createImageView(i != 0)
imageLayout?.addView(iView)
attachImageSaveListener(iView, size.second.url)
DownloadUtils.downloadPhoto(size.first.url)
.subscribe { photo ->
iView.setImageBitmap(photo)
imageLayout?.removeView(loadingGifView)
}
}
}
}
// ロングタップによる画像保存を実行するためのイベントを attach
private fun attachImageSaveListener(imageView: ImageView, url: String) {
imageView.setOnLongClickListener {
val fragment = ImageSaveDialogFragment()
val args = Bundle()
args.putString(ImageSaveDialogFragment.URL_KEY, url)
fragment.arguments = args
fragment.show(childFragmentManager, null)
true
}
}
private fun startStopAnimations() {
imageLayout?.children()?.forEach {
(it as? GifImageView)?.let { startStopByVisibility(it) }
}
}
private fun startStopByVisibility(view: GifImageView) {
if (isVisibleToUser && view.getLocalVisibleRect(tmpRect)) {
if (!view.isAnimating) {
view.startAnimation()
Log.d(TAG, "Page $page: アニメーション開始")
}
} else if (view.isAnimating) {
view.stopAnimation()
Log.d(TAG, "Page $page: アニメーション停止")
}
}
override fun onPause() {
super.onPause()
if (isVisibleToUser) {
imageLayout?.children()?.forEach { (it as? GifImageView)?.stopAnimation() }
}
}
override fun onResume() {
super.onResume()
startStopAnimations()
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
// FragmentをViewPagerの中で使うとisVisible()はほぼ常にtrueになる。
// 実際表示されているかどうかはこのメソッドでリスンする
super.setUserVisibleHint(isVisibleToUser)
this.isVisibleToUser = isVisibleToUser
startStopAnimations()
}
private fun createLoadingGifImageView(): GifSquareImageView {
val gifView = GifSquareImageView(context)
val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
gifView.layoutParams = layoutParams
gifView.scaleType = ImageView.ScaleType.CENTER
return gifView
}
private fun createGifImageView(withTopMargin: Boolean): GifImageView {
val gifView = GifImageView(context)
setParameterToImageView(gifView, withTopMargin)
return gifView
}
private fun createImageView(withTopMargin: Boolean): ImageView {
val iView = ImageView(context)
setParameterToImageView(iView, withTopMargin)
return iView
}
private fun setParameterToImageView(iView: ImageView, withTopMargin: Boolean) {
// レイアウト生成
val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
if (withTopMargin) {
/* なぜかmarginが効かない (多分何か間違ってる)
val marginLayoutParams = ViewGroup.MarginLayoutParams(layoutParams)
marginLayoutParams.topMargin = 20
iView.layoutParams = marginLayoutParams
*/
iView.layoutParams = layoutParams
iView.setPadding(0, 20, 0, 0)
} else {
iView.layoutParams = layoutParams
}
iView.scaleType = ImageView.ScaleType.FIT_CENTER
iView.adjustViewBounds = true
}
}
class ImageSaveDialogFragment : DialogFragment() {
companion object {
private const val TAG = "ImageSaveDialogFragment"
const val URL_KEY = "url"
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(activity)
.setMessage(R.string.save_image)
.setPositiveButton(R.string.yes) { _, _ ->
startSaveImage()
}.setNegativeButton(R.string.no, null)
.create()
}
override fun onPause() {
super.onPause()
dismiss()
}
private fun startSaveImage() {
val url: String? = arguments.getString(ImageSaveDialogFragment.URL_KEY, null)
if (url != null) {
DownloadUtils.saveImage(activity as MainActivity, url)
}
}
}
|
gpl-3.0
|
5561a16516f72081b1d959427000dc8d
| 33.380074 | 123 | 0.611785 | 4.567157 | false | false | false | false |
tasks/tasks
|
app/src/main/java/org/tasks/tasklist/ItemCallback.kt
|
1
|
364
|
package org.tasks.tasklist
import androidx.recyclerview.widget.DiffUtil
import org.tasks.data.TaskContainer
internal class ItemCallback : DiffUtil.ItemCallback<TaskContainer>() {
override fun areItemsTheSame(old: TaskContainer, new: TaskContainer) = old.id == new.id
override fun areContentsTheSame(old: TaskContainer, new: TaskContainer) = old == new
}
|
gpl-3.0
|
3aa57c32e3a1e82ba4f108bc804561e5
| 35.5 | 91 | 0.788462 | 4.55 | false | false | false | false |
AoEiuV020/PaNovel
|
server/src/main/java/cc/aoeiuv020/panovel/server/dal/model/MobResponse.kt
|
1
|
939
|
package cc.aoeiuv020.panovel.server.dal.model
import cc.aoeiuv020.panovel.server.common.ErrorCode
import cc.aoeiuv020.panovel.server.common.toBean
import cc.aoeiuv020.panovel.server.common.toJson
import java.lang.reflect.Type
/**
*
* Created by AoEiuV020 on 2018.04.02-11:21:33.
*/
class MobResponse(
var code: Int = ErrorCode.UNKNOWN_ERROR.code,
val data: String = "{}"
) {
companion object {
fun success(data: Any = Any()): MobResponse {
return MobResponse(ErrorCode.SUCCESS.code, data.toJson())
}
fun error(error: ErrorCode = ErrorCode.UNKNOWN_ERROR): MobResponse {
return MobResponse(error.code)
}
}
inline fun <reified T> getRealData(): T {
return data.toBean()
}
fun <T> getRealData(type: Type): T {
return data.toBean(type)
}
fun isSuccess(): Boolean {
return code == ErrorCode.SUCCESS.code
}
}
|
gpl-3.0
|
1bcc26c88fc1b69d889c563a8dd7b2d9
| 24.378378 | 76 | 0.641108 | 3.864198 | false | false | false | false |
arturbosch/detekt
|
detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/RedundantVisibilityModifierRule.kt
|
1
|
5505
|
package io.gitlab.arturbosch.detekt.rules.style
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.isInternal
import io.gitlab.arturbosch.detekt.rules.isOverride
import org.jetbrains.kotlin.config.AnalysisFlags
import org.jetbrains.kotlin.config.ExplicitApiMode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.isPrivate
/**
* This rule checks for redundant visibility modifiers.
* One exemption is the
* [explicit API mode](https://kotlinlang.org/docs/reference/whatsnew14.html#explicit-api-mode-for-library-authors)
* In this mode, the visibility modifier should be defined explicitly even if it is public.
* Hence, the rule ignores the visibility modifiers in explicit API mode.
*
* <noncompliant>
* public interface Foo { // public per default
*
* public fun bar() // public per default
* }
* </noncompliant>
*
* <compliant>
* interface Foo {
*
* fun bar()
* }
* </compliant>
*/
class RedundantVisibilityModifierRule(config: Config = Config.empty) : Rule(config) {
override val defaultRuleIdAliases: Set<String> = setOf("RedundantVisibilityModifier")
override val issue: Issue = Issue(
"RedundantVisibilityModifierRule",
Severity.Style,
"Checks for redundant visibility modifiers.",
Debt.FIVE_MINS
)
private val classVisitor = ClassVisitor()
private val childrenVisitor = ChildrenVisitor()
private fun KtModifierListOwner.isExplicitlyPublicNotOverridden() = isExplicitlyPublic() && !isOverride()
private fun KtModifierListOwner.isExplicitlyPublic() = this.hasModifier(KtTokens.PUBLIC_KEYWORD)
/**
* Explicit API mode was added in Kotlin 1.4
* It prevents libraries' authors from making APIs public unintentionally.
* In this mode, the visibility modifier should be defined explicitly even if it is public.
* See: https://kotlinlang.org/docs/reference/whatsnew14.html#explicit-api-mode-for-library-authors
*/
private fun isExplicitApiModeActive(): Boolean {
val resources = compilerResources ?: return false
val flag = resources.languageVersionSettings.getFlag(AnalysisFlags.explicitApiMode)
return flag == ExplicitApiMode.STRICT
}
override fun visitKtFile(file: KtFile) {
super.visitKtFile(file)
if (!isExplicitApiModeActive()) {
file.declarations.forEach {
it.accept(classVisitor)
it.acceptChildren(childrenVisitor)
}
}
}
override fun visitDeclaration(declaration: KtDeclaration) {
super.visitDeclaration(declaration)
if (
declaration.isInternal() &&
declaration.containingClassOrObject?.let { it.isLocal || it.isPrivate() } == true
) {
report(
CodeSmell(
issue,
Entity.from(declaration),
"The `internal` modifier on ${declaration.name} is redundant and should be removed."
)
)
}
}
private inner class ClassVisitor : DetektVisitor() {
override fun visitClass(klass: KtClass) {
super.visitClass(klass)
if (klass.isExplicitlyPublic()) {
report(
CodeSmell(
issue,
Entity.atName(klass),
message = "${klass.name} is explicitly marked as public. " +
"Public is the default visibility for classes. The public modifier is redundant."
)
)
}
}
}
private inner class ChildrenVisitor : DetektVisitor() {
override fun visitNamedFunction(function: KtNamedFunction) {
super.visitNamedFunction(function)
if (function.isExplicitlyPublicNotOverridden()) {
report(
CodeSmell(
issue,
Entity.atName(function),
message = "${function.name} is explicitly marked as public. " +
"Functions are public by default so this modifier is redundant."
)
)
}
}
override fun visitProperty(property: KtProperty) {
super.visitProperty(property)
if (property.isExplicitlyPublicNotOverridden()) {
report(
CodeSmell(
issue,
Entity.atName(property),
message = "${property.name} is explicitly marked as public. " +
"Properties are public by default so this modifier is redundant."
)
)
}
}
}
}
|
apache-2.0
|
de546e568c7316c529fad31e8b22c2c6
| 36.195946 | 115 | 0.634151 | 5.050459 | false | false | false | false |
mockk/mockk
|
modules/mockk/src/commonMain/kotlin/io/mockk/impl/recording/CallRecorderFactories.kt
|
2
|
1504
|
package io.mockk.impl.recording
import io.mockk.MockKGateway.*
import io.mockk.impl.recording.states.CallRecordingState
typealias VerifierFactory = (VerificationParameters) -> CallVerifier
typealias SignatureMatcherDetectorFactory = () -> SignatureMatcherDetector
typealias CallRoundBuilderFactory = () -> CallRoundBuilder
typealias ChildHinterFactory = () -> ChildHinter
typealias PermanentMockerFactory = () -> PermanentMocker
typealias StateFactory = (recorder: CommonCallRecorder) -> CallRecordingState
typealias VerifyingStateFactory = (recorder: CommonCallRecorder, verificationParams: VerificationParameters) -> CallRecordingState
typealias ExclusionStateFactory = (recorder: CommonCallRecorder, exclusionParams: ExclusionParameters) -> CallRecordingState
typealias ChainedCallDetectorFactory = () -> ChainedCallDetector
typealias VerificationCallSorterFactory = () -> VerificationCallSorter
data class CallRecorderFactories(
val signatureMatcherDetector: SignatureMatcherDetectorFactory,
val callRoundBuilder: CallRoundBuilderFactory,
val childHinter: ChildHinterFactory,
val verifier: VerifierFactory,
val permanentMocker: PermanentMockerFactory,
val verificationCallSorter: VerificationCallSorterFactory,
val answeringState: StateFactory,
val stubbingState: StateFactory,
val verifyingState: VerifyingStateFactory,
val exclusionState: ExclusionStateFactory,
val stubbingAwaitingAnswerState: StateFactory,
val safeLoggingState: StateFactory
)
|
apache-2.0
|
1d49205bc0eaa36d8fde2fda8438c27b
| 47.516129 | 130 | 0.827793 | 5.829457 | false | false | false | false |
REBOOTERS/AndroidAnimationExercise
|
imitate/src/main/java/com/engineer/imitate/util/ContextExt.kt
|
1
|
1217
|
package com.engineer.imitate.util
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.util.Log
import android.widget.Toast
/**
*
* @author: Rookie
* @date: 2018-08-21 09:54
* @version V1.0
*/
fun Context?.toastShort(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
@SuppressLint("LogNotTimber")
fun String.lg(tag:String) {
Log.e(tag,this)
}
fun Context.toastLong(message: String) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
fun Context.dp2px(dp: Float): Float {
val scale = resources.displayMetrics.density
return dp * scale
}
fun Context.px2dp(px: Float): Float {
val scale = resources.displayMetrics.density
return px / scale
}
fun Context.getActivity(): Activity? {
var context = this
while (context is ContextWrapper) {
if (context is Activity) {
return context
}
context = context.baseContext
}
return null
}
inline fun <reified T:Activity> Context.startActivity() {
val intent = Intent(this, T::class.java)
startActivity(intent)
}
|
apache-2.0
|
f17bcf26aa17b6c04a9f96715db38b67
| 19.627119 | 60 | 0.69926 | 3.643713 | false | false | false | false |
jitsi/jicofo
|
jicofo-selector/src/test/kotlin/org/jitsi/jicofo/bridge/BridgeSelectionStrategyTest.kt
|
1
|
9820
|
/*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2021-Present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jicofo.bridge
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import org.jitsi.config.withNewConfig
import org.jxmpp.jid.impl.JidCreate
class BridgeSelectionStrategyTest : ShouldSpec() {
init {
val localRegion = "local-region"
val strategy: RegionBasedBridgeSelectionStrategy = createWithNewConfig("jicofo.local-region=$localRegion") {
RegionBasedBridgeSelectionStrategy()
}
context("testRegionBasedSelection") {
val region1 = "region1"
val region2 = localRegion
val region3 = "region3"
val bridge1 = Bridge(JidCreate.from("bridge1")).apply { setStats(region = region1) }
val bridge2 = Bridge(JidCreate.from("bridge2")).apply { setStats(region = region2) }
val bridge3 = Bridge(JidCreate.from("bridge3")).apply { setStats(region = region3) }
val localBridge = bridge2
val props1 = ParticipantProperties(region1)
val props2 = ParticipantProperties(region2)
val props3 = ParticipantProperties(region3)
val propsInvalid = ParticipantProperties("invalid region")
val propsNull = ParticipantProperties(null)
val allBridges = listOf(bridge1, bridge2, bridge3)
val conferenceBridges: MutableMap<Bridge, ConferenceBridgeProperties> = HashMap()
// Initial selection should select a bridge in the participant's region/ if possible
strategy.select(allBridges, conferenceBridges, props1, true) shouldBe bridge1
strategy.select(allBridges, conferenceBridges, props2, true) shouldBe bridge2
// Or a bridge in the local region otherwise
strategy.select(allBridges, conferenceBridges, propsInvalid, true) shouldBe localBridge
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe localBridge
conferenceBridges[bridge3] = ConferenceBridgeProperties(1)
strategy.select(allBridges, conferenceBridges, props3, true) shouldBe bridge3
strategy.select(allBridges, conferenceBridges, props2, true) shouldBe bridge2
// A participant in an unknown region should be allocated on a local bridge.
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe localBridge
conferenceBridges[bridge2] = ConferenceBridgeProperties(1)
// A participant in an unknown region should be allocated on the least loaded (according to the order of
// 'allBridges') existing conference bridge.
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe bridge2
// A participant in a region with no bridges should also be allocated on the least loaded (according to the
// order of 'allBridges') existing conference bridge.
strategy.select(allBridges, conferenceBridges, propsInvalid, true) shouldBe bridge2
}
context("Port of BridgeSelectionStrategyTest.java#preferLowestStress") {
val lowStressRegion = "lowStressRegion"
val mediumStressRegion = "mediumStressRegion"
val highStressRegion = "highStressRegion"
val lowStressBridge = createBridge(lowStressRegion, 0.1)
val mediumStressBridge = createBridge(mediumStressRegion, 0.3)
val highStressBridge = createBridge(highStressRegion, 0.8)
val allBridges = listOf(lowStressBridge, mediumStressBridge, highStressBridge)
val lowStressProps = ParticipantProperties(lowStressRegion)
val mediumStressProps = ParticipantProperties(mediumStressRegion)
val highStressProps = ParticipantProperties(highStressRegion)
val propsInvalid = ParticipantProperties("invalid region")
val propsNull = ParticipantProperties(null)
val conferenceBridges = mutableMapOf<Bridge, ConferenceBridgeProperties>()
// Initial selection should select a bridge in the participant's region.
strategy.select(allBridges, conferenceBridges, highStressProps, true) shouldBe highStressBridge
strategy.select(allBridges, conferenceBridges, mediumStressProps, true) shouldBe mediumStressBridge
strategy.select(allBridges, conferenceBridges, propsInvalid, true) shouldBe lowStressBridge
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe lowStressBridge
// Now assume that the low-stressed bridge is in the conference.
conferenceBridges[lowStressBridge] = ConferenceBridgeProperties(1)
strategy.select(allBridges, conferenceBridges, lowStressProps, true) shouldBe lowStressBridge
strategy.select(allBridges, conferenceBridges, mediumStressProps, true) shouldBe mediumStressBridge
// A participant in an unknown region should be allocated on the
// existing conference bridge.
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe lowStressBridge
// Now assume that a medium-stressed bridge is also in the conference.
conferenceBridges[mediumStressBridge] = ConferenceBridgeProperties(1)
// A participant in an unknown region should be allocated on the least
// loaded (according to the order of 'allBridges') existing conference
// bridge.
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe lowStressBridge
// A participant in a region with no bridges should also be allocated
// on the least loaded (according to the order of 'allBridges') existing
// conference bridge.
strategy.select(allBridges, conferenceBridges, propsInvalid, true) shouldBe lowStressBridge
}
context("Port of BridgeSelectionStrategyTest.java#preferRegionWhenStressIsEqual") {
// Here we specify 3 bridges in 3 different regions: one high-stressed and two medium-stressed.
val mediumStressRegion1 = "mediumStressRegion1"
val mediumStressRegion2 = "mediumStressRegion2"
val highStressRegion = "highStressRegion"
val mediumStressBridge1 = createBridge(mediumStressRegion1, 0.25)
val mediumStressBridge2 = createBridge(mediumStressRegion2, 0.3)
val highStressBridge = createBridge(highStressRegion, 0.8)
val allBridges = listOf(mediumStressBridge1, mediumStressBridge2, highStressBridge)
val mediumStressProps1 = ParticipantProperties(mediumStressRegion1)
val mediumStressProps2 = ParticipantProperties(mediumStressRegion2)
val highStressProps = ParticipantProperties(highStressRegion)
val propsInvalid = ParticipantProperties("invalid region")
val propsNull = ParticipantProperties(null)
val conferenceBridges = mutableMapOf<Bridge, ConferenceBridgeProperties>()
// Initial selection should select a bridge in the participant's region.
strategy.select(allBridges, conferenceBridges, highStressProps, true) shouldBe highStressBridge
strategy.select(allBridges, conferenceBridges, mediumStressProps2, true) shouldBe mediumStressBridge2
strategy.select(allBridges, conferenceBridges, propsInvalid, true) shouldBe mediumStressBridge1
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe mediumStressBridge1
conferenceBridges[mediumStressBridge2] = ConferenceBridgeProperties(1)
strategy.select(allBridges, conferenceBridges, mediumStressProps1, true) shouldBe mediumStressBridge1
strategy.select(allBridges, conferenceBridges, mediumStressProps2, true) shouldBe mediumStressBridge2
// A participant in an unknown region should be allocated on the existing conference bridge.
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe mediumStressBridge2
// Now assume that a high-stressed bridge is in the conference.
conferenceBridges[highStressBridge] = ConferenceBridgeProperties(1)
// A participant in an unknown region should be allocated on the least
// loaded (according to the order of 'allBridges') existing conference
// bridge.
strategy.select(allBridges, conferenceBridges, propsNull, true) shouldBe mediumStressBridge2
// A participant in a region with no bridges should also be allocated
// on the least loaded (according to the order of 'allBridges') existing
// conference bridge.
strategy.select(allBridges, conferenceBridges, propsInvalid, true) shouldBe mediumStressBridge2
}
}
}
private fun createBridge(region: String, stress: Double) = Bridge(JidCreate.from(region)).apply {
setStats(stress = stress, region = region)
}
private fun <T : Any> createWithNewConfig(config: String, block: () -> T): T {
lateinit var ret: T
withNewConfig(config) {
ret = block()
}
return ret
}
|
apache-2.0
|
61272c1a44ecaf225c2c3e81277fde07
| 55.436782 | 119 | 0.70723 | 5.699362 | false | false | false | false |
vanita5/twittnuker
|
twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/OnLinkClickHandler.kt
|
1
|
9012
|
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.Uri
import android.os.BadParcelableException
import android.support.v4.content.ContextCompat
import okhttp3.HttpUrl
import org.mariotaku.kpreferences.get
import de.vanita5.twittnuker.TwittnukerConstants.USER_TYPE_TWITTER_COM
import de.vanita5.twittnuker.activity.WebLinkHandlerActivity
import de.vanita5.twittnuker.app.TwittnukerApplication
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_ACCOUNT_HOST
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_ACCOUNT_KEY
import de.vanita5.twittnuker.constant.displaySensitiveContentsKey
import de.vanita5.twittnuker.constant.newDocumentApiKey
import de.vanita5.twittnuker.extension.model.AcctPlaceholderUserKey
import de.vanita5.twittnuker.extension.toUri
import de.vanita5.twittnuker.model.UserKey
import de.vanita5.twittnuker.model.util.ParcelableMediaUtils
import de.vanita5.twittnuker.util.TwidereLinkify.OnLinkClickListener
import de.vanita5.twittnuker.util.TwidereLinkify.USER_TYPE_FANFOU_COM
import de.vanita5.twittnuker.util.media.preview.PreviewMediaExtractor
open class OnLinkClickHandler(
protected val context: Context,
protected val manager: MultiSelectManager?,
protected val preferences: SharedPreferences
) : OnLinkClickListener {
override fun onLinkClick(link: String, orig: String?, accountKey: UserKey?,
extraId: Long, type: Int, sensitive: Boolean,
start: Int, end: Int): Boolean {
if (manager != null && manager.isActive) return false
when (type) {
TwidereLinkify.LINK_TYPE_MENTION -> {
IntentUtils.openUserProfile(context, accountKey, null, link, null,
preferences[newDocumentApiKey], null)
return true
}
TwidereLinkify.LINK_TYPE_HASHTAG -> {
IntentUtils.openTweetSearch(context, accountKey, "#" + link)
return true
}
TwidereLinkify.LINK_TYPE_LINK_IN_TEXT -> {
if (accountKey != null && isMedia(link, extraId)) {
openMedia(accountKey, extraId, sensitive, link, start, end)
} else {
openLink(accountKey, link)
}
return true
}
TwidereLinkify.LINK_TYPE_ENTITY_URL -> {
if (accountKey != null && isMedia(link, extraId)) {
openMedia(accountKey, extraId, sensitive, link, start, end)
} else {
val authority = UriUtils.getAuthority(link)
if (authority == "fanfou.com") {
if (accountKey != null && handleFanfouLink(link, orig, accountKey)) {
return true
}
} else if (IntentUtils.isWebLinkHandled(context, Uri.parse(link))) {
openTwitterLink(accountKey, link)
return true
}
openLink(accountKey, link)
}
return true
}
TwidereLinkify.LINK_TYPE_LIST -> {
val mentionList = link.split("/")
if (mentionList.size != 2) {
return false
}
IntentUtils.openUserListDetails(context, accountKey, null, null, mentionList[0],
mentionList[1])
return true
}
TwidereLinkify.LINK_TYPE_CASHTAG -> {
IntentUtils.openTweetSearch(context, accountKey, link)
return true
}
TwidereLinkify.LINK_TYPE_USER_ID -> {
IntentUtils.openUserProfile(context, accountKey, UserKey.valueOf(link), null, null,
preferences[newDocumentApiKey], null)
return true
}
TwidereLinkify.LINK_TYPE_USER_ACCT -> {
val acctKey = UserKey.valueOf(link)
IntentUtils.openUserProfile(context, accountKey, AcctPlaceholderUserKey(acctKey.host),
acctKey.id, null, preferences[newDocumentApiKey], null)
return true
}
}
return false
}
protected open fun isMedia(link: String, extraId: Long): Boolean {
return PreviewMediaExtractor.isSupported(link)
}
protected open fun openMedia(accountKey: UserKey, extraId: Long, sensitive: Boolean, link: String, start: Int, end: Int) {
val media = arrayOf(ParcelableMediaUtils.image(link))
IntentUtils.openMedia(context, accountKey, media, null, sensitive, preferences[newDocumentApiKey],
preferences[displaySensitiveContentsKey])
}
protected open fun openLink(accountKey: UserKey?, link: String) {
if (manager != null && manager.isActive) return
val uri = Uri.parse(link)
if (uri.isRelative && accountKey != null && accountKey.host != null) {
val absUri = HttpUrl.parse("http://${accountKey.host}/")?.resolve(link)?.toUri()!!
openLink(context, preferences, absUri)
return
}
openLink(context, preferences, uri)
}
protected fun openTwitterLink(accountKey: UserKey?, link: String) {
if (manager != null && manager.isActive) return
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
intent.setClass(context, WebLinkHandlerActivity::class.java)
if (accountKey != null && accountKey.host == USER_TYPE_TWITTER_COM) {
intent.putExtra(EXTRA_ACCOUNT_KEY, accountKey)
} else {
intent.putExtra(EXTRA_ACCOUNT_HOST, USER_TYPE_TWITTER_COM)
}
intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader)
if (intent.resolveActivity(context.packageManager) != null) {
try {
context.startActivity(intent)
} catch (e: BadParcelableException) {
// Ignore
}
}
}
private fun handleFanfouLink(link: String, orig: String?, accountKey: UserKey): Boolean {
if (orig == null) return false
// Process special case for fanfou
val ch = orig[0]
// Extend selection
val length = orig.length
if (TwidereLinkify.isAtSymbol(ch)) {
var id = UriUtils.getPath(link)
if (id != null) {
val idxOfSlash = id.indexOf('/')
if (idxOfSlash == 0) {
id = id.substring(1)
}
val screenName = orig.substring(1, length)
IntentUtils.openUserProfile(context, accountKey, UserKey.valueOf(id), screenName,
null, preferences[newDocumentApiKey], null)
return true
}
} else if (TwidereLinkify.isHashSymbol(ch) && TwidereLinkify.isHashSymbol(orig[length - 1])) {
IntentUtils.openSearch(context, accountKey, orig.substring(1, length - 1))
return true
}
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
intent.setClass(context, WebLinkHandlerActivity::class.java)
if (accountKey.host == USER_TYPE_FANFOU_COM) {
intent.putExtra(EXTRA_ACCOUNT_KEY, accountKey)
}
context.startActivity(intent)
return true
}
companion object {
fun openLink(context: Context, preferences: SharedPreferences, uri: Uri) {
val (intent, options) = IntentUtils.browse(context, preferences, uri = uri,
forceBrowser = false)
try {
ContextCompat.startActivity(context, intent, options)
} catch (e: ActivityNotFoundException) {
Analyzer.logException(e)
DebugLog.w(tr = e)
}
}
}
}
|
gpl-3.0
|
efce838eb4a54cbf72abd6a195524449
| 42.119617 | 126 | 0.615513 | 4.850377 | false | false | false | false |
syrop/Victor-Events
|
events/src/main/kotlin/pl/org/seva/events/comm/CommAdapter.kt
|
1
|
2297
|
/*
* Copyright (C) 2017 Wiktor Nizio
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.events.comm
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import kotlinx.android.synthetic.main.row_comm.view.*
import pl.org.seva.events.R
import pl.org.seva.events.main.extension.inflate
import pl.org.seva.events.main.extension.onClick
import pl.org.seva.events.main.init.instance
open class CommAdapter(private val onClick: (Int) -> Unit) :
RecyclerView.Adapter<CommAdapter.ViewHolder>() {
private val comms by instance<Comms>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(parent.inflate(R.layout.row_comm), onClick)
override fun getItemCount() = comms.size
protected open fun getItem(position: Int): Comm = comms[position]
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
getItem(position).apply {
holder.communityName.text = name
holder.iconText.text = name.substring(0, 1)
holder.iconProfile.setImageResource(R.drawable.bg_circle)
holder.iconProfile.setColorFilter(color)
}
}
class ViewHolder(view: View, onClick: (Int) -> Unit) : RecyclerView.ViewHolder(view) {
init { view onClick { onClick(adapterPosition) } }
val communityName: TextView = view.comm
val iconProfile: ImageView = view.icon_profile
val iconText: TextView = view.icon_text
}
}
|
gpl-3.0
|
dca6e3445021f2d4ec2e4ad96c0b133c
| 36.048387 | 98 | 0.727035 | 4.022767 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/ide/utils/BooleanExprSimplifier.kt
|
3
|
4395
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.utils
import com.intellij.openapi.project.Project
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.consts.asBool
import org.rust.lang.core.types.ty.TyBool
import org.rust.lang.utils.evaluation.evaluate
import org.rust.lang.utils.negate
class BooleanExprSimplifier(val project: Project) {
private val factory = RsPsiFactory(project)
/**
* Simplifies a boolean expression if can.
*
* @returns `null` if expr cannot be simplified, `expr` otherwise
*/
fun simplify(expr: RsExpr): RsExpr? {
if (expr is RsLitExpr) return null
val value = eval(expr)
if (value != null) {
return factory.createExpression(value.toString())
}
return when (expr) {
is RsBinaryExpr -> {
val left = expr.left
val right = expr.right ?: return null
val op = expr.operatorType
val lhs = simplify(left) ?: left
val rhs = simplify(right) ?: right
when {
lhs is RsLitExpr -> simplifyBinaryOperation(op, lhs, rhs)
rhs is RsLitExpr -> simplifyBinaryOperation(op, rhs, lhs)
else -> factory.createExpression("${lhs.text} ${expr.binaryOp.text} ${rhs.text}")
}
}
is RsUnaryExpr -> {
val parenExpr = expr.expr as? RsParenExpr ?: return expr
val interior = parenExpr.expr
if (expr.operatorType == UnaryOperator.NOT && interior is RsBinaryExpr) {
interior.negate() as RsExpr
} else {
null
}
}
is RsParenExpr -> {
val wrapped = expr.expr
if (wrapped != null) {
val interiorSimplified = simplify(wrapped)
interiorSimplified?.let { factory.createExpression("(${it.text})") }
} else {
null
}
}
else -> null
}
}
private fun simplifyBinaryOperation(op: BinaryOperator, const: RsLitExpr, expr: RsExpr): RsExpr? {
val literal = const.boolLiteral?.text ?: return null
return when (op) {
LogicOp.AND -> if (literal == "false") factory.createExpression("false") else expr
LogicOp.OR -> if (literal == "true") factory.createExpression("true") else expr
EqualityOp.EQ -> if (literal == "false") factory.createExpression("!${expr.text}") else expr
EqualityOp.EXCLEQ -> if (literal == "true") factory.createExpression("!${expr.text}") else expr
else -> null
}
}
companion object {
fun canBeSimplified(expr: RsExpr): Boolean {
if (expr is RsLitExpr) return false
if (canBeEvaluated(expr)) return true
when (expr) {
is RsBinaryExpr -> {
val left = expr.left
val right = expr.right ?: return false
if (expr.operatorType in setOf(LogicOp.AND, LogicOp.OR, EqualityOp.EQ, EqualityOp.EXCLEQ)) {
if (canBeSimplified(left) || canBeSimplified(right)) return true
if (canBeEvaluated(left) || canBeEvaluated(right)) return true
}
}
is RsParenExpr -> {
val wrapped = expr.expr
return wrapped != null && canBeSimplified(wrapped)
}
is RsUnaryExpr -> {
if (expr.operatorType != UnaryOperator.NOT) {
return false
}
val parenExpr = expr.expr as? RsParenExpr ?: return false
val binOp = (parenExpr.expr as? RsBinaryExpr)?.operatorType ?: return false
return binOp is EqualityOp || binOp is ComparisonOp
}
}
return false
}
private fun canBeEvaluated(expr: RsExpr): Boolean = eval(expr) != null
private fun eval(expr: RsExpr): Boolean? = expr.evaluate(TyBool.INSTANCE, resolver = null).asBool()
}
}
|
mit
|
96a9f09c0690ddb1d1c85d07a040f335
| 35.02459 | 112 | 0.535381 | 5 | false | false | false | false |
arcuri82/testing_security_development_enterprise_systems
|
advanced/exercise-solutions/card-game/part-10/user-collections/src/test/kotlin/org/tsdes/advanced/exercises/cardgame/usercollections/FakeData.kt
|
8
|
1503
|
package org.tsdes.advanced.exercises.cardgame.usercollections
import org.tsdes.advanced.exercises.cardgame.cards.dto.CardDto
import org.tsdes.advanced.exercises.cardgame.cards.dto.CollectionDto
import org.tsdes.advanced.exercises.cardgame.cards.dto.Rarity.BRONZE
import org.tsdes.advanced.exercises.cardgame.cards.dto.Rarity.SILVER
import org.tsdes.advanced.exercises.cardgame.cards.dto.Rarity.GOLD
import org.tsdes.advanced.exercises.cardgame.cards.dto.Rarity.PINK_DIAMOND
object FakeData {
fun getCollectionDto() : CollectionDto{
val dto = CollectionDto()
dto.prices[BRONZE] = 100
dto.prices[SILVER] = 500
dto.prices[GOLD] = 1_000
dto.prices[PINK_DIAMOND] = 100_000
dto.prices.forEach { dto.millValues[it.key] = it.value / 4 }
dto.prices.keys.forEach { dto.rarityProbabilities[it] = 0.25 }
dto.cards.run {
add(CardDto(cardId = "c00", rarity = BRONZE))
add(CardDto(cardId = "c01", rarity = BRONZE))
add(CardDto(cardId = "c02", rarity = BRONZE))
add(CardDto(cardId = "c03", rarity = BRONZE))
add(CardDto(cardId = "c04", rarity = SILVER))
add(CardDto(cardId = "c05", rarity = SILVER))
add(CardDto(cardId = "c06", rarity = SILVER))
add(CardDto(cardId = "c07", rarity = GOLD))
add(CardDto(cardId = "c08", rarity = GOLD))
add(CardDto(cardId = "c09", rarity = PINK_DIAMOND))
}
return dto
}
}
|
lgpl-3.0
|
1ece14829f9c2605bbe42f688a436593
| 36.6 | 74 | 0.646707 | 3.7575 | false | false | false | false |
deva666/anko
|
anko/library/generated/sdk25-coroutines/src/ListenersWithCoroutines.kt
|
2
|
34431
|
@file:JvmName("Sdk25CoroutinesListenersWithCoroutinesKt")
package org.jetbrains.anko.sdk25.coroutines
import kotlin.coroutines.experimental.CoroutineContext
import kotlinx.coroutines.experimental.android.UI
import kotlinx.coroutines.experimental.CoroutineScope
import kotlinx.coroutines.experimental.launch
import android.view.WindowInsets
fun android.view.View.onLayoutChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(v: android.view.View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) -> Unit
) {
addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
launch(context) {
handler(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom)
}
}
}
fun android.view.View.onAttachStateChangeListener(
context: CoroutineContext = UI,
init: __View_OnAttachStateChangeListener.() -> Unit
) {
val listener = __View_OnAttachStateChangeListener(context)
listener.init()
addOnAttachStateChangeListener(listener)
}
class __View_OnAttachStateChangeListener(private val context: CoroutineContext) : android.view.View.OnAttachStateChangeListener {
private var _onViewAttachedToWindow: (suspend CoroutineScope.(android.view.View) -> Unit)? = null
override fun onViewAttachedToWindow(v: android.view.View) {
val handler = _onViewAttachedToWindow ?: return
launch(context) {
handler(v)
}
}
fun onViewAttachedToWindow(
listener: suspend CoroutineScope.(android.view.View) -> Unit
) {
_onViewAttachedToWindow = listener
}
private var _onViewDetachedFromWindow: (suspend CoroutineScope.(android.view.View) -> Unit)? = null
override fun onViewDetachedFromWindow(v: android.view.View) {
val handler = _onViewDetachedFromWindow ?: return
launch(context) {
handler(v)
}
}
fun onViewDetachedFromWindow(
listener: suspend CoroutineScope.(android.view.View) -> Unit
) {
_onViewDetachedFromWindow = listener
}
}fun android.widget.TextView.textChangedListener(
context: CoroutineContext = UI,
init: __TextWatcher.() -> Unit
) {
val listener = __TextWatcher(context)
listener.init()
addTextChangedListener(listener)
}
class __TextWatcher(private val context: CoroutineContext) : android.text.TextWatcher {
private var _beforeTextChanged: (suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit)? = null
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
val handler = _beforeTextChanged ?: return
launch(context) {
handler(s, start, count, after)
}
}
fun beforeTextChanged(
listener: suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit
) {
_beforeTextChanged = listener
}
private var _onTextChanged: (suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit)? = null
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val handler = _onTextChanged ?: return
launch(context) {
handler(s, start, before, count)
}
}
fun onTextChanged(
listener: suspend CoroutineScope.(CharSequence?, Int, Int, Int) -> Unit
) {
_onTextChanged = listener
}
private var _afterTextChanged: (suspend CoroutineScope.(android.text.Editable?) -> Unit)? = null
override fun afterTextChanged(s: android.text.Editable?) {
val handler = _afterTextChanged ?: return
launch(context) {
handler(s)
}
}
fun afterTextChanged(
listener: suspend CoroutineScope.(android.text.Editable?) -> Unit
) {
_afterTextChanged = listener
}
}fun android.gesture.GestureOverlayView.onGestureListener(
context: CoroutineContext = UI,
init: __GestureOverlayView_OnGestureListener.() -> Unit
) {
val listener = __GestureOverlayView_OnGestureListener(context)
listener.init()
addOnGestureListener(listener)
}
class __GestureOverlayView_OnGestureListener(private val context: CoroutineContext) : android.gesture.GestureOverlayView.OnGestureListener {
private var _onGestureStarted: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
val handler = _onGestureStarted ?: return
launch(context) {
handler(overlay, event)
}
}
fun onGestureStarted(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit
) {
_onGestureStarted = listener
}
private var _onGesture: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
val handler = _onGesture ?: return
launch(context) {
handler(overlay, event)
}
}
fun onGesture(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit
) {
_onGesture = listener
}
private var _onGestureEnded: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
val handler = _onGestureEnded ?: return
launch(context) {
handler(overlay, event)
}
}
fun onGestureEnded(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit
) {
_onGestureEnded = listener
}
private var _onGestureCancelled: (suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) {
val handler = _onGestureCancelled ?: return
launch(context) {
handler(overlay, event)
}
}
fun onGestureCancelled(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit
) {
_onGestureCancelled = listener
}
}fun android.gesture.GestureOverlayView.onGesturePerformed(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(overlay: android.gesture.GestureOverlayView?, gesture: android.gesture.Gesture?) -> Unit
) {
addOnGesturePerformedListener { overlay, gesture ->
launch(context) {
handler(overlay, gesture)
}
}
}
fun android.gesture.GestureOverlayView.onGesturingListener(
context: CoroutineContext = UI,
init: __GestureOverlayView_OnGesturingListener.() -> Unit
) {
val listener = __GestureOverlayView_OnGesturingListener(context)
listener.init()
addOnGesturingListener(listener)
}
class __GestureOverlayView_OnGesturingListener(private val context: CoroutineContext) : android.gesture.GestureOverlayView.OnGesturingListener {
private var _onGesturingStarted: (suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) {
val handler = _onGesturingStarted ?: return
launch(context) {
handler(overlay)
}
}
fun onGesturingStarted(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit
) {
_onGesturingStarted = listener
}
private var _onGesturingEnded: (suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) {
val handler = _onGesturingEnded ?: return
launch(context) {
handler(overlay)
}
}
fun onGesturingEnded(
listener: suspend CoroutineScope.(android.gesture.GestureOverlayView?) -> Unit
) {
_onGesturingEnded = listener
}
}fun android.media.tv.TvView.onUnhandledInputEvent(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(event: android.view.InputEvent?) -> Unit
) {
setOnUnhandledInputEventListener { event ->
launch(context) {
handler(event)
}
returnValue
}
}
fun android.view.View.onApplyWindowInsets(
context: CoroutineContext = UI,
returnValue: WindowInsets,
handler: suspend CoroutineScope.(v: android.view.View?, insets: android.view.WindowInsets?) -> Unit
) {
setOnApplyWindowInsetsListener { v, insets ->
launch(context) {
handler(v, insets)
}
returnValue
}
}
fun android.view.View.onClick(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnClickListener { v ->
launch(context) {
handler(v)
}
}
}
fun android.view.View.onContextClick(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnContextClickListener { v ->
launch(context) {
handler(v)
}
returnValue
}
}
fun android.view.View.onCreateContextMenu(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(menu: android.view.ContextMenu?, v: android.view.View?, menuInfo: android.view.ContextMenu.ContextMenuInfo?) -> Unit
) {
setOnCreateContextMenuListener { menu, v, menuInfo ->
launch(context) {
handler(menu, v, menuInfo)
}
}
}
fun android.view.View.onDrag(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, event: android.view.DragEvent) -> Unit
) {
setOnDragListener { v, event ->
launch(context) {
handler(v, event)
}
returnValue
}
}
fun android.view.View.onFocusChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(v: android.view.View, hasFocus: Boolean) -> Unit
) {
setOnFocusChangeListener { v, hasFocus ->
launch(context) {
handler(v, hasFocus)
}
}
}
fun android.view.View.onGenericMotion(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit
) {
setOnGenericMotionListener { v, event ->
launch(context) {
handler(v, event)
}
returnValue
}
}
fun android.view.View.onHover(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit
) {
setOnHoverListener { v, event ->
launch(context) {
handler(v, event)
}
returnValue
}
}
fun android.view.View.onKey(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, keyCode: Int, event: android.view.KeyEvent?) -> Unit
) {
setOnKeyListener { v, keyCode, event ->
launch(context) {
handler(v, keyCode, event)
}
returnValue
}
}
fun android.view.View.onLongClick(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnLongClickListener { v ->
launch(context) {
handler(v)
}
returnValue
}
}
fun android.view.View.onScrollChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(v: android.view.View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) -> Unit
) {
setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
launch(context) {
handler(v, scrollX, scrollY, oldScrollX, oldScrollY)
}
}
}
fun android.view.View.onSystemUiVisibilityChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(visibility: Int) -> Unit
) {
setOnSystemUiVisibilityChangeListener { visibility ->
launch(context) {
handler(visibility)
}
}
}
fun android.view.View.onTouch(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.view.View, event: android.view.MotionEvent) -> Unit
) {
setOnTouchListener { v, event ->
launch(context) {
handler(v, event)
}
returnValue
}
}
fun android.view.ViewGroup.onHierarchyChangeListener(
context: CoroutineContext = UI,
init: __ViewGroup_OnHierarchyChangeListener.() -> Unit
) {
val listener = __ViewGroup_OnHierarchyChangeListener(context)
listener.init()
setOnHierarchyChangeListener(listener)
}
class __ViewGroup_OnHierarchyChangeListener(private val context: CoroutineContext) : android.view.ViewGroup.OnHierarchyChangeListener {
private var _onChildViewAdded: (suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) {
val handler = _onChildViewAdded ?: return
launch(context) {
handler(parent, child)
}
}
fun onChildViewAdded(
listener: suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit
) {
_onChildViewAdded = listener
}
private var _onChildViewRemoved: (suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) {
val handler = _onChildViewRemoved ?: return
launch(context) {
handler(parent, child)
}
}
fun onChildViewRemoved(
listener: suspend CoroutineScope.(android.view.View?, android.view.View?) -> Unit
) {
_onChildViewRemoved = listener
}
}fun android.view.ViewStub.onInflate(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(stub: android.view.ViewStub?, inflated: android.view.View?) -> Unit
) {
setOnInflateListener { stub, inflated ->
launch(context) {
handler(stub, inflated)
}
}
}
fun android.widget.AbsListView.onScrollListener(
context: CoroutineContext = UI,
init: __AbsListView_OnScrollListener.() -> Unit
) {
val listener = __AbsListView_OnScrollListener(context)
listener.init()
setOnScrollListener(listener)
}
class __AbsListView_OnScrollListener(private val context: CoroutineContext) : android.widget.AbsListView.OnScrollListener {
private var _onScrollStateChanged: (suspend CoroutineScope.(android.widget.AbsListView?, Int) -> Unit)? = null
override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) {
val handler = _onScrollStateChanged ?: return
launch(context) {
handler(view, scrollState)
}
}
fun onScrollStateChanged(
listener: suspend CoroutineScope.(android.widget.AbsListView?, Int) -> Unit
) {
_onScrollStateChanged = listener
}
private var _onScroll: (suspend CoroutineScope.(android.widget.AbsListView?, Int, Int, Int) -> Unit)? = null
override fun onScroll(view: android.widget.AbsListView?, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
val handler = _onScroll ?: return
launch(context) {
handler(view, firstVisibleItem, visibleItemCount, totalItemCount)
}
}
fun onScroll(
listener: suspend CoroutineScope.(android.widget.AbsListView?, Int, Int, Int) -> Unit
) {
_onScroll = listener
}
}fun android.widget.ActionMenuView.onMenuItemClick(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(item: android.view.MenuItem?) -> Unit
) {
setOnMenuItemClickListener { item ->
launch(context) {
handler(item)
}
returnValue
}
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemClick(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit
) {
setOnItemClickListener { p0, p1, p2, p3 ->
launch(context) {
handler(p0, p1, p2, p3)
}
}
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemLongClick(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) -> Unit
) {
setOnItemLongClickListener { p0, p1, p2, p3 ->
launch(context) {
handler(p0, p1, p2, p3)
}
returnValue
}
}
fun android.widget.AdapterView<out android.widget.Adapter>.onItemSelectedListener(
context: CoroutineContext = UI,
init: __AdapterView_OnItemSelectedListener.() -> Unit
) {
val listener = __AdapterView_OnItemSelectedListener(context)
listener.init()
setOnItemSelectedListener(listener)
}
class __AdapterView_OnItemSelectedListener(private val context: CoroutineContext) : android.widget.AdapterView.OnItemSelectedListener {
private var _onItemSelected: (suspend CoroutineScope.(android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) {
val handler = _onItemSelected ?: return
launch(context) {
handler(p0, p1, p2, p3)
}
}
fun onItemSelected(
listener: suspend CoroutineScope.(android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit
) {
_onItemSelected = listener
}
private var _onNothingSelected: (suspend CoroutineScope.(android.widget.AdapterView<*>?) -> Unit)? = null
override fun onNothingSelected(p0: android.widget.AdapterView<*>?) {
val handler = _onNothingSelected ?: return
launch(context) {
handler(p0)
}
}
fun onNothingSelected(
listener: suspend CoroutineScope.(android.widget.AdapterView<*>?) -> Unit
) {
_onNothingSelected = listener
}
}fun android.widget.AutoCompleteTextView.onDismiss(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.() -> Unit
) {
setOnDismissListener { ->
launch(context, block = handler)
}
}
fun android.widget.CalendarView.onDateChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(view: android.widget.CalendarView?, year: Int, month: Int, dayOfMonth: Int) -> Unit
) {
setOnDateChangeListener { view, year, month, dayOfMonth ->
launch(context) {
handler(view, year, month, dayOfMonth)
}
}
}
fun android.widget.Chronometer.onChronometerTick(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(chronometer: android.widget.Chronometer?) -> Unit
) {
setOnChronometerTickListener { chronometer ->
launch(context) {
handler(chronometer)
}
}
}
fun android.widget.CompoundButton.onCheckedChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(buttonView: android.widget.CompoundButton?, isChecked: Boolean) -> Unit
) {
setOnCheckedChangeListener { buttonView, isChecked ->
launch(context) {
handler(buttonView, isChecked)
}
}
}
fun android.widget.ExpandableListView.onChildClick(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, childPosition: Int, id: Long) -> Unit
) {
setOnChildClickListener { parent, v, groupPosition, childPosition, id ->
launch(context) {
handler(parent, v, groupPosition, childPosition, id)
}
returnValue
}
}
fun android.widget.ExpandableListView.onGroupClick(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(parent: android.widget.ExpandableListView?, v: android.view.View?, groupPosition: Int, id: Long) -> Unit
) {
setOnGroupClickListener { parent, v, groupPosition, id ->
launch(context) {
handler(parent, v, groupPosition, id)
}
returnValue
}
}
fun android.widget.ExpandableListView.onGroupCollapse(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(groupPosition: Int) -> Unit
) {
setOnGroupCollapseListener { groupPosition ->
launch(context) {
handler(groupPosition)
}
}
}
fun android.widget.ExpandableListView.onGroupExpand(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(groupPosition: Int) -> Unit
) {
setOnGroupExpandListener { groupPosition ->
launch(context) {
handler(groupPosition)
}
}
}
fun android.widget.NumberPicker.onScroll(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(view: android.widget.NumberPicker?, scrollState: Int) -> Unit
) {
setOnScrollListener { view, scrollState ->
launch(context) {
handler(view, scrollState)
}
}
}
fun android.widget.NumberPicker.onValueChanged(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(picker: android.widget.NumberPicker?, oldVal: Int, newVal: Int) -> Unit
) {
setOnValueChangedListener { picker, oldVal, newVal ->
launch(context) {
handler(picker, oldVal, newVal)
}
}
}
fun android.widget.RadioGroup.onCheckedChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(group: android.widget.RadioGroup?, checkedId: Int) -> Unit
) {
setOnCheckedChangeListener { group, checkedId ->
launch(context) {
handler(group, checkedId)
}
}
}
fun android.widget.RatingBar.onRatingBarChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(ratingBar: android.widget.RatingBar?, rating: Float, fromUser: Boolean) -> Unit
) {
setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
launch(context) {
handler(ratingBar, rating, fromUser)
}
}
}
fun android.widget.SearchView.onClose(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.() -> Unit
) {
setOnCloseListener { ->
launch(context, block = handler)
returnValue
}
}
fun android.widget.SearchView.onQueryTextFocusChange(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(v: android.view.View, hasFocus: Boolean) -> Unit
) {
setOnQueryTextFocusChangeListener { v, hasFocus ->
launch(context) {
handler(v, hasFocus)
}
}
}
fun android.widget.SearchView.onQueryTextListener(
context: CoroutineContext = UI,
init: __SearchView_OnQueryTextListener.() -> Unit
) {
val listener = __SearchView_OnQueryTextListener(context)
listener.init()
setOnQueryTextListener(listener)
}
class __SearchView_OnQueryTextListener(private val context: CoroutineContext) : android.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: (suspend CoroutineScope.(String?) -> Boolean)? = null
private var _onQueryTextSubmit_returnValue: Boolean = false
override fun onQueryTextSubmit(query: String?) : Boolean {
val returnValue = _onQueryTextSubmit_returnValue
val handler = _onQueryTextSubmit ?: return returnValue
launch(context) {
handler(query)
}
return returnValue
}
fun onQueryTextSubmit(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(String?) -> Boolean
) {
_onQueryTextSubmit = listener
_onQueryTextSubmit_returnValue = returnValue
}
private var _onQueryTextChange: (suspend CoroutineScope.(String?) -> Boolean)? = null
private var _onQueryTextChange_returnValue: Boolean = false
override fun onQueryTextChange(newText: String?) : Boolean {
val returnValue = _onQueryTextChange_returnValue
val handler = _onQueryTextChange ?: return returnValue
launch(context) {
handler(newText)
}
return returnValue
}
fun onQueryTextChange(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(String?) -> Boolean
) {
_onQueryTextChange = listener
_onQueryTextChange_returnValue = returnValue
}
}fun android.widget.SearchView.onSearchClick(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnSearchClickListener { v ->
launch(context) {
handler(v)
}
}
}
fun android.widget.SearchView.onSuggestionListener(
context: CoroutineContext = UI,
init: __SearchView_OnSuggestionListener.() -> Unit
) {
val listener = __SearchView_OnSuggestionListener(context)
listener.init()
setOnSuggestionListener(listener)
}
class __SearchView_OnSuggestionListener(private val context: CoroutineContext) : android.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: (suspend CoroutineScope.(Int) -> Boolean)? = null
private var _onSuggestionSelect_returnValue: Boolean = false
override fun onSuggestionSelect(position: Int) : Boolean {
val returnValue = _onSuggestionSelect_returnValue
val handler = _onSuggestionSelect ?: return returnValue
launch(context) {
handler(position)
}
return returnValue
}
fun onSuggestionSelect(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(Int) -> Boolean
) {
_onSuggestionSelect = listener
_onSuggestionSelect_returnValue = returnValue
}
private var _onSuggestionClick: (suspend CoroutineScope.(Int) -> Boolean)? = null
private var _onSuggestionClick_returnValue: Boolean = false
override fun onSuggestionClick(position: Int) : Boolean {
val returnValue = _onSuggestionClick_returnValue
val handler = _onSuggestionClick ?: return returnValue
launch(context) {
handler(position)
}
return returnValue
}
fun onSuggestionClick(
returnValue: Boolean = false,
listener: suspend CoroutineScope.(Int) -> Boolean
) {
_onSuggestionClick = listener
_onSuggestionClick_returnValue = returnValue
}
}fun android.widget.SeekBar.onSeekBarChangeListener(
context: CoroutineContext = UI,
init: __SeekBar_OnSeekBarChangeListener.() -> Unit
) {
val listener = __SeekBar_OnSeekBarChangeListener(context)
listener.init()
setOnSeekBarChangeListener(listener)
}
class __SeekBar_OnSeekBarChangeListener(private val context: CoroutineContext) : android.widget.SeekBar.OnSeekBarChangeListener {
private var _onProgressChanged: (suspend CoroutineScope.(android.widget.SeekBar?, Int, Boolean) -> Unit)? = null
override fun onProgressChanged(seekBar: android.widget.SeekBar?, progress: Int, fromUser: Boolean) {
val handler = _onProgressChanged ?: return
launch(context) {
handler(seekBar, progress, fromUser)
}
}
fun onProgressChanged(
listener: suspend CoroutineScope.(android.widget.SeekBar?, Int, Boolean) -> Unit
) {
_onProgressChanged = listener
}
private var _onStartTrackingTouch: (suspend CoroutineScope.(android.widget.SeekBar?) -> Unit)? = null
override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) {
val handler = _onStartTrackingTouch ?: return
launch(context) {
handler(seekBar)
}
}
fun onStartTrackingTouch(
listener: suspend CoroutineScope.(android.widget.SeekBar?) -> Unit
) {
_onStartTrackingTouch = listener
}
private var _onStopTrackingTouch: (suspend CoroutineScope.(android.widget.SeekBar?) -> Unit)? = null
override fun onStopTrackingTouch(seekBar: android.widget.SeekBar?) {
val handler = _onStopTrackingTouch ?: return
launch(context) {
handler(seekBar)
}
}
fun onStopTrackingTouch(
listener: suspend CoroutineScope.(android.widget.SeekBar?) -> Unit
) {
_onStopTrackingTouch = listener
}
}fun android.widget.SlidingDrawer.onDrawerClose(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.() -> Unit
) {
setOnDrawerCloseListener { ->
launch(context, block = handler)
}
}
fun android.widget.SlidingDrawer.onDrawerOpen(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.() -> Unit
) {
setOnDrawerOpenListener { ->
launch(context, block = handler)
}
}
fun android.widget.SlidingDrawer.onDrawerScrollListener(
context: CoroutineContext = UI,
init: __SlidingDrawer_OnDrawerScrollListener.() -> Unit
) {
val listener = __SlidingDrawer_OnDrawerScrollListener(context)
listener.init()
setOnDrawerScrollListener(listener)
}
class __SlidingDrawer_OnDrawerScrollListener(private val context: CoroutineContext) : android.widget.SlidingDrawer.OnDrawerScrollListener {
private var _onScrollStarted: (suspend CoroutineScope.() -> Unit)? = null
override fun onScrollStarted() {
val handler = _onScrollStarted ?: return
launch(context, block = handler)
}
fun onScrollStarted(
listener: suspend CoroutineScope.() -> Unit
) {
_onScrollStarted = listener
}
private var _onScrollEnded: (suspend CoroutineScope.() -> Unit)? = null
override fun onScrollEnded() {
val handler = _onScrollEnded ?: return
launch(context, block = handler)
}
fun onScrollEnded(
listener: suspend CoroutineScope.() -> Unit
) {
_onScrollEnded = listener
}
}fun android.widget.TabHost.onTabChanged(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(tabId: String?) -> Unit
) {
setOnTabChangedListener { tabId ->
launch(context) {
handler(tabId)
}
}
}
fun android.widget.TextView.onEditorAction(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(v: android.widget.TextView?, actionId: Int, event: android.view.KeyEvent?) -> Unit
) {
setOnEditorActionListener { v, actionId, event ->
launch(context) {
handler(v, actionId, event)
}
returnValue
}
}
fun android.widget.TimePicker.onTimeChanged(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(view: android.widget.TimePicker?, hourOfDay: Int, minute: Int) -> Unit
) {
setOnTimeChangedListener { view, hourOfDay, minute ->
launch(context) {
handler(view, hourOfDay, minute)
}
}
}
fun android.widget.Toolbar.onMenuItemClick(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(item: android.view.MenuItem?) -> Unit
) {
setOnMenuItemClickListener { item ->
launch(context) {
handler(item)
}
returnValue
}
}
fun android.widget.VideoView.onCompletion(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?) -> Unit
) {
setOnCompletionListener { mp ->
launch(context) {
handler(mp)
}
}
}
fun android.widget.VideoView.onError(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Unit
) {
setOnErrorListener { mp, what, extra ->
launch(context) {
handler(mp, what, extra)
}
returnValue
}
}
fun android.widget.VideoView.onInfo(
context: CoroutineContext = UI,
returnValue: Boolean = false,
handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?, what: Int, extra: Int) -> Unit
) {
setOnInfoListener { mp, what, extra ->
launch(context) {
handler(mp, what, extra)
}
returnValue
}
}
fun android.widget.VideoView.onPrepared(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(mp: android.media.MediaPlayer?) -> Unit
) {
setOnPreparedListener { mp ->
launch(context) {
handler(mp)
}
}
}
fun android.widget.ZoomControls.onZoomInClick(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnZoomInClickListener { v ->
launch(context) {
handler(v)
}
}
}
fun android.widget.ZoomControls.onZoomOutClick(
context: CoroutineContext = UI,
handler: suspend CoroutineScope.(v: android.view.View?) -> Unit
) {
setOnZoomOutClickListener { v ->
launch(context) {
handler(v)
}
}
}
|
apache-2.0
|
2047eac7e34d8c57c3af75fadf6b0c14
| 30.1875 | 175 | 0.653539 | 4.897027 | false | false | false | false |
charleskorn/batect
|
app/src/main/kotlin/batect/ui/interleaved/InterleavedEventLogger.kt
|
1
|
10389
|
/*
Copyright 2017-2020 Charles Korn.
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 batect.ui.interleaved
import batect.config.Container
import batect.config.ImageSource
import batect.execution.RunOptions
import batect.execution.model.events.ContainerBecameHealthyEvent
import batect.execution.model.events.ContainerCreationFailedEvent
import batect.execution.model.events.ContainerDidNotBecomeHealthyEvent
import batect.execution.model.events.ContainerRemovalFailedEvent
import batect.execution.model.events.ContainerRunFailedEvent
import batect.execution.model.events.ContainerStartedEvent
import batect.execution.model.events.ContainerStopFailedEvent
import batect.execution.model.events.ContainerStoppedEvent
import batect.execution.model.events.ExecutionFailedEvent
import batect.execution.model.events.ImageBuildFailedEvent
import batect.execution.model.events.ImageBuiltEvent
import batect.execution.model.events.ImagePullFailedEvent
import batect.execution.model.events.ImagePulledEvent
import batect.execution.model.events.RunningSetupCommandEvent
import batect.execution.model.events.SetupCommandsCompletedEvent
import batect.execution.model.events.StepStartingEvent
import batect.execution.model.events.TaskEvent
import batect.execution.model.events.TaskFailedEvent
import batect.execution.model.events.TaskNetworkCreationFailedEvent
import batect.execution.model.events.TaskNetworkDeletionFailedEvent
import batect.execution.model.events.TemporaryDirectoryDeletionFailedEvent
import batect.execution.model.events.TemporaryFileDeletionFailedEvent
import batect.execution.model.events.UserInterruptedExecutionEvent
import batect.execution.model.steps.BuildImageStep
import batect.execution.model.steps.CleanupStep
import batect.execution.model.steps.CreateContainerStep
import batect.execution.model.steps.PullImageStep
import batect.execution.model.steps.RunContainerStep
import batect.os.Command
import batect.ui.EventLogger
import batect.ui.FailureErrorMessageFormatter
import batect.ui.containerio.ContainerIOStreamingOptions
import batect.ui.humanise
import batect.ui.text.Text
import batect.ui.text.TextRun
import java.time.Duration
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
class InterleavedEventLogger(
val taskContainer: Container,
val containers: Set<Container>,
private val output: InterleavedOutput,
val failureErrorMessageFormatter: FailureErrorMessageFormatter,
val runOptions: RunOptions
) : EventLogger {
private val haveStartedCleanup = AtomicBoolean(false)
private val commands = ConcurrentHashMap<Container, Command>()
override fun onTaskStarting(taskName: String) {
output.printForTask(Text.white(Text("Running ") + Text.bold(taskName) + Text("...")))
}
override fun onTaskFinished(taskName: String, exitCode: Int, duration: Duration) {
output.printForTask(Text.white(Text.bold(taskName) + Text(" finished with exit code $exitCode in ${duration.humanise()}.")))
}
override fun onTaskFinishedWithCleanupDisabled(manualCleanupInstructions: TextRun) {
output.printErrorForTask(manualCleanupInstructions)
}
override fun onTaskFailed(taskName: String, manualCleanupInstructions: TextRun) {
val message = Text.red(Text("The task ") + Text.bold(taskName) + Text(" failed. See above for details."))
if (manualCleanupInstructions != TextRun()) {
output.printErrorForTask(manualCleanupInstructions + Text("\n\n") + message)
} else {
output.printErrorForTask(message)
}
}
override val ioStreamingOptions: ContainerIOStreamingOptions by lazy { InterleavedContainerIOStreamingOptions(output, containers) }
override fun postEvent(event: TaskEvent) {
when (event) {
is ImageBuiltEvent -> onImageBuilt(event)
is ImagePulledEvent -> onImagePulled(event)
is ContainerStartedEvent -> onContainerStarted(event)
is ContainerBecameHealthyEvent -> onContainerBecameHealthyEvent(event)
is ContainerStoppedEvent -> onContainerStoppedEvent(event)
is RunningSetupCommandEvent -> onRunningSetupCommandEvent(event)
is SetupCommandsCompletedEvent -> onSetupCommandsCompletedEvent(event)
is StepStartingEvent -> onStepStarting(event)
is TaskFailedEvent -> onTaskFailed(event)
}
}
private fun onContainerBecameHealthyEvent(event: ContainerBecameHealthyEvent) {
output.printForContainer(event.container, TextRun(Text.white("Container became healthy.")))
}
private fun onImageBuilt(event: ImageBuiltEvent) {
val text = TextRun(Text.white("Image built."))
containers
.filter { it.imageSource == event.source }
.forEach { output.printForContainer(it, text) }
}
private fun onImagePulled(event: ImagePulledEvent) {
val text = Text.white(Text("Pulled ") + Text.bold(event.source.imageName) + Text("."))
containers
.filter { it.imageSource == event.source }
.forEach { output.printForContainer(it, text) }
}
private fun onContainerStarted(event: ContainerStartedEvent) {
if (event.container != taskContainer) {
output.printForContainer(event.container, TextRun(Text.white("Container started.")))
}
}
private fun onContainerStoppedEvent(event: ContainerStoppedEvent) {
output.printForContainer(event.container, TextRun(Text.white("Container stopped.")))
}
private fun onRunningSetupCommandEvent(event: RunningSetupCommandEvent) {
output.printForContainer(event.container, Text.white(Text("Running setup command ") + Text.bold(event.command.command.originalCommand) + Text(" (${event.commandIndex + 1} of ${event.container.setupCommands.size})...")))
}
private fun onSetupCommandsCompletedEvent(event: SetupCommandsCompletedEvent) {
output.printForContainer(event.container, TextRun(Text.white("Container has completed all setup commands.")))
}
private fun onStepStarting(event: StepStartingEvent) {
when (event.step) {
is BuildImageStep -> onBuildImageStepStarting(event.step)
is PullImageStep -> onPullImageStepStarting(event.step)
is RunContainerStep -> onRunContainerStepStarting(event.step)
is CreateContainerStep -> onCreateContainerStepStarting(event.step)
is CleanupStep -> onCleanupStepStarting()
}
}
private fun onBuildImageStepStarting(step: BuildImageStep) {
val text = TextRun(Text.white("Building image..."))
containers
.filter { it.imageSource == step.source }
.forEach { output.printForContainer(it, text) }
}
private fun onPullImageStepStarting(step: PullImageStep) {
val text = Text.white(Text("Pulling ") + Text.bold(step.source.imageName) + Text("..."))
containers
.filter { it.imageSource == step.source }
.forEach { output.printForContainer(it, text) }
}
private fun onRunContainerStepStarting(step: RunContainerStep) {
val command = commands.getOrDefault(step.container, null)
if (command != null) {
output.printForContainer(step.container, Text.white(Text("Running ") + Text.bold(command.originalCommand) + Text("...")))
} else {
output.printForContainer(step.container, TextRun(Text.white("Running...")))
}
}
private fun onCreateContainerStepStarting(step: CreateContainerStep) {
if (step.config.command != null) {
commands[step.container] = step.config.command
}
}
private fun onCleanupStepStarting() {
val haveStartedCleanupAlready = haveStartedCleanup.getAndSet(true)
if (haveStartedCleanupAlready) {
return
}
output.printForTask(TextRun(Text.white("Cleaning up...")))
}
private fun onTaskFailed(event: TaskFailedEvent) {
when (event) {
is ImageBuildFailedEvent -> printErrorForContainers(event.source, event)
is ImagePullFailedEvent -> printErrorForContainers(event.source, event)
is ContainerCreationFailedEvent -> printErrorForContainer(event.container, event)
is ContainerDidNotBecomeHealthyEvent -> printErrorForContainer(event.container, event)
is ContainerRunFailedEvent -> printErrorForContainer(event.container, event)
is ContainerStopFailedEvent -> printErrorForContainer(event.container, event)
is ContainerRemovalFailedEvent -> printErrorForContainer(event.container, event)
is ExecutionFailedEvent -> printErrorForTask(event)
is TaskNetworkCreationFailedEvent -> printErrorForTask(event)
is TaskNetworkDeletionFailedEvent -> printErrorForTask(event)
is TemporaryFileDeletionFailedEvent -> printErrorForTask(event)
is TemporaryDirectoryDeletionFailedEvent -> printErrorForTask(event)
is UserInterruptedExecutionEvent -> printErrorForTask(event)
}
}
private fun printErrorForContainers(imageSource: ImageSource, event: TaskFailedEvent) {
val containers = containers.filter { it.imageSource == imageSource }
if (containers.count() == 1) {
printErrorForContainer(containers.single(), event)
} else {
printErrorForTask(event)
}
}
private fun printErrorForContainer(container: Container, event: TaskFailedEvent) {
output.printErrorForContainer(container, failureErrorMessageFormatter.formatErrorMessage(event, runOptions))
}
private fun printErrorForTask(event: TaskFailedEvent) {
output.printErrorForTask(failureErrorMessageFormatter.formatErrorMessage(event, runOptions))
}
}
|
apache-2.0
|
eb0991d96c3c26a23dc67ede5981e12f
| 43.397436 | 227 | 0.734046 | 5.120256 | false | false | false | false |
nrizzio/Signal-Android
|
donations/lib/src/main/java/org/signal/donations/json/StripeIntentStatus.kt
|
1
|
862
|
package org.signal.donations.json
import com.fasterxml.jackson.annotation.JsonCreator
/**
* Stripe intent status, from:
*
* https://stripe.com/docs/api/setup_intents/object?lang=curl#setup_intent_object-status
* https://stripe.com/docs/api/payment_intents/object?lang=curl#payment_intent_object-status
*
* Note: REQUIRES_CAPTURE is only ever valid for a SetupIntent
*/
enum class StripeIntentStatus(private val code: String) {
REQUIRES_PAYMENT_METHOD("requires_payment_method"),
REQUIRES_CONFIRMATION("requires_confirmation"),
REQUIRES_ACTION("requires_action"),
REQUIRES_CAPTURE("requires_capture"),
PROCESSING("processing"),
CANCELED("canceled"),
SUCCEEDED("succeeded");
companion object {
@JvmStatic
@JsonCreator
fun fromCode(code: String): StripeIntentStatus = StripeIntentStatus.values().first { it.code == code }
}
}
|
gpl-3.0
|
f7ae93cd3c21a10ece07164275eef514
| 30.962963 | 106 | 0.7471 | 3.97235 | false | false | false | false |
androidx/androidx
|
activity/activity-compose/src/main/java/androidx/activity/compose/ComponentActivity.kt
|
3
|
3312
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.activity.compose
import android.view.ViewGroup
import androidx.activity.ComponentActivity
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionContext
import androidx.compose.ui.platform.ComposeView
import androidx.lifecycle.ViewTreeLifecycleOwner
import androidx.lifecycle.ViewTreeViewModelStoreOwner
import androidx.savedstate.findViewTreeSavedStateRegistryOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
/**
* Composes the given composable into the given activity. The [content] will become the root view
* of the given activity.
*
* This is roughly equivalent to calling [ComponentActivity.setContentView] with a [ComposeView]
* i.e.:
*
* ```
* setContentView(
* ComposeView(this).apply {
* setContent {
* MyComposableContent()
* }
* }
* )
* ```
*
* @param parent The parent composition reference to coordinate scheduling of composition updates
* @param content A `@Composable` function declaring the UI contents
*/
public fun ComponentActivity.setContent(
parent: CompositionContext? = null,
content: @Composable () -> Unit
) {
val existingComposeView = window.decorView
.findViewById<ViewGroup>(android.R.id.content)
.getChildAt(0) as? ComposeView
if (existingComposeView != null) with(existingComposeView) {
setParentCompositionContext(parent)
setContent(content)
} else ComposeView(this).apply {
// Set content and parent **before** setContentView
// to have ComposeView create the composition on attach
setParentCompositionContext(parent)
setContent(content)
// Set the view tree owners before setting the content view so that the inflation process
// and attach listeners will see them already present
setOwners()
setContentView(this, DefaultActivityContentLayoutParams)
}
}
private val DefaultActivityContentLayoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
/**
* These owners are not set before AppCompat 1.3+ due to a bug, so we need to set them manually in
* case developers are using an older version of AppCompat.
*/
private fun ComponentActivity.setOwners() {
val decorView = window.decorView
if (ViewTreeLifecycleOwner.get(decorView) == null) {
ViewTreeLifecycleOwner.set(decorView, this)
}
if (ViewTreeViewModelStoreOwner.get(decorView) == null) {
ViewTreeViewModelStoreOwner.set(decorView, this)
}
if (decorView.findViewTreeSavedStateRegistryOwner() == null) {
decorView.setViewTreeSavedStateRegistryOwner(this)
}
}
|
apache-2.0
|
1bbe755f1ecb439bdeddc080f9d4687a
| 35 | 98 | 0.740942 | 4.765468 | false | false | false | false |
bsmr-java/lwjgl3
|
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/EXT_window_rectangles.kt
|
1
|
4448
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val EXT_window_rectangles = "EXTWindowRectangles".nativeClassGL("EXT_window_rectangles", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension provides additional orthogonally aligned "window rectangles" specified in window-space coordinates that restrict rasterization of all
primitive types (geometry, images, paths) and framebuffer clears.
When rendering to the framebuffer of an on-screen window, these window rectangles are ignored so these window rectangles apply to rendering to non-zero
framebuffer objects only.
From zero to an implementation-dependent limit (specified by #MAX_WINDOW_RECTANGLES_EXT) number of window rectangles can be operational at once. When
one or more window rectangles are active, rasterized fragments can either survive if the fragment is within any of the operational window rectangles
(#INCLUSIVE_EXT mode) or be rejected if the fragment is within any of the operational window rectangles (#EXCLUSIVE_EXT mode).
These window rectangles operate orthogonally to the existing scissor test functionality.
This extension has specification language for both OpenGL and ES so {@code EXT_window_rectangles} can be implemented and advertised for either or both
API contexts.
Requires ${GL30.link} or ${EXT_draw_buffers2.link}.
"""
val Modes = IntConstant(
"Accepted by the {@code mode} parameter of #WindowRectanglesEXT().",
"INCLUSIVE_EXT"..0x8F10,
"EXCLUSIVE_EXT"..0x8F11
).javaDocLinks
IntConstant(
"""
Accepted by the {@code pname} parameter of GetIntegeri_v, GetInteger64i_v, GetBooleani_v, GetFloati_v, GetDoublei_v, GetIntegerIndexedvEXT,
GetFloatIndexedvEXT, GetDoubleIndexedvEXT, GetBooleanIndexedvEXT, and GetIntegeri_vEXT.
""",
"WINDOW_RECTANGLE_EXT"..0x8F12
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetInteger64v, GetFloatv, and GetDoublev.",
"WINDOW_RECTANGLE_MODE_EXT"..0x8F13,
"MAX_WINDOW_RECTANGLES_EXT"..0x8F14,
"NUM_WINDOW_RECTANGLES_EXT"..0x8F15
)
void(
"WindowRectanglesEXT",
"""
Sets the active window rectangles.
When the {@code WindowRectanglesEXT} command is processed without error, the i<sup>th</sup> window rectangle box is set to the corresponding four
parameters for values of {@code i} less then {@code n}. For values of {@code i} greater than {@code n}, each window rectangle box is set to (0,0,0,0).
Each four elements corresponds to the i<sup>th</sup> window rectangle indicating a box of pixels specified with window-space coordinates. Each window
rectangle box {@code i} has a lower-left origin at {@code (x_i,y_i)} and upper-right corner at {@code (x_i+w_i,y_i+h_i)}.
The #INVALID_VALUE error is generated if any element {@code w_i} or {@code h_i}, corresponding to each box's respective width and height, is negative.
Each rasterized or cleared fragment with a window-space position {@code (xw,yw)} is within the i<sup>th</sup> window rectangle box when both of these
equations are satisfied for all {@code i} less than {@code n}:
${codeBlock("""
x_i <= xw < x_i+w_i
y_i <= yw < y_i+h_i""")}
When the window rectangles mode is #INCLUSIVE_EXT mode and the bound framebuffer object is non-zero, a fragment passes the window rectangles test if
the fragment's window-space position is within at least one of the current {@code n} active window rectangles; otherwise the window rectangles test
fails and the fragment is discarded.
When the window rectangles mode is #EXCLUSIVE_EXT mode and the bound framebuffer object is non-zero, a fragment fails the window rectangles test and is
discarded if the fragment's window-space position is within at least one of the current {@code n} active window rectangles; otherwise the window
rectangles test passes and the fragment passes the window rectangles test.
When the bound framebuffer object is zero, the window rectangles test always passes.
""",
GLenum.IN("mode", "the rectangle mode", Modes),
AutoSize(4, "box")..GLsizei.IN("count", "the number of active window rectangles. Must be between zero and the value of #MAX_WINDOW_RECTANGLES_EXT."),
nullable..const..GLint_p.IN("box", "an array of {@code 4*count} window rectangle coordinates")
)
}
|
bsd-3-clause
|
becefaa5e64bc432e144c7da5ec5a57a
| 48.433333 | 153 | 0.75652 | 3.950266 | false | true | false | false |
vitorsalgado/android-boilerplate
|
utils/src/main/kotlin/br/com/vitorsalgado/example/utils/delegates/ViewProviderDelegate.kt
|
1
|
1404
|
package br.com.vitorsalgado.example.utils.delegates
import android.app.Activity
import android.app.Dialog
import android.view.View
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import kotlin.reflect.KProperty
open class ViewProviderDelegate<T : View>(@IdRes private val idRes: Int) {
private var view: T? = null
open operator fun getValue(thisRef: Activity, property: KProperty<*>): T {
view?.let { if (!it.isAttachedToWindow) view = null }
view = view ?: thisRef.findViewById(idRes)
return view!!
}
open operator fun getValue(thisRef: Fragment, property: KProperty<*>): T {
view?.let { if (!it.isAttachedToWindow) view = null }
view = view ?: thisRef.view?.findViewById(idRes)
return view!!
}
open operator fun getValue(thisRef: Dialog, property: KProperty<*>): T {
view?.let { if (!it.isAttachedToWindow) view = null }
view = view ?: thisRef.findViewById(idRes)
return view!!
}
open operator fun getValue(thisRef: View, property: KProperty<*>): T {
view = view ?: thisRef.findViewById(idRes)
return view!!
}
open operator fun getValue(thisRef: RecyclerView.ViewHolder, property: KProperty<*>): T {
view = view ?: thisRef.itemView.findViewById(idRes)
return view!!
}
}
fun <T : View> viewWithId(@IdRes idRes: Int) = ViewProviderDelegate<T>(idRes)
|
apache-2.0
|
a44c482669ebd6f33282b117cfea86f7
| 31.651163 | 91 | 0.712251 | 4.166172 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua
|
src/main/java/com/tang/intellij/lua/comment/psi/impl/LuaCommentImpl.kt
|
2
|
6139
|
/*
* Copyright (c) 2017. tangzx([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.tang.intellij.lua.comment.psi.impl
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.PsiTreeUtil
import com.tang.intellij.lua.comment.LuaCommentUtil
import com.tang.intellij.lua.comment.psi.*
import com.tang.intellij.lua.comment.psi.api.LuaComment
import com.tang.intellij.lua.project.LuaSettings
import com.tang.intellij.lua.psi.LuaCommentOwner
import com.tang.intellij.lua.psi.LuaTypes
import com.tang.intellij.lua.psi.LuaVisitor
import com.tang.intellij.lua.search.SearchContext
import com.tang.intellij.lua.ty.*
/**
* Created by Tangzx on 2016/11/21.
*
*/
class LuaCommentImpl(node: ASTNode) : ASTWrapperPsiElement(node), LuaComment {
override fun <T : LuaDocPsiElement> findTag(t:Class<T>): T? {
var element: PsiElement? = firstChild
while (element != null) {
if (t.isInstance(element)) {
return t.cast(element)
}
element = element.nextSibling
}
return null
}
override fun <T : LuaDocPsiElement> findTags(t:Class<T>): Collection<T> {
return PsiTreeUtil.findChildrenOfType(this, t)
}
override fun findTags(name: String): Collection<LuaDocTagDef> {
return PsiTreeUtil.findChildrenOfType(this, LuaDocTagDef::class.java).filter { it.tagName.text == name }
}
override fun getTokenType(): IElementType {
return LuaTypes.DOC_COMMENT
}
override val owner: LuaCommentOwner?
get() = LuaCommentUtil.findOwner(this)
override val moduleName: String?
get() {
val classDef = PsiTreeUtil.getChildOfType(this, LuaDocTagClass::class.java)
if (classDef != null && classDef.module != null) {
return classDef.name
}
return null
}
override val isDeprecated: Boolean
get() = findTags("deprecated").isNotEmpty()
override fun getParamDef(name: String): LuaDocTagParam? {
var element: PsiElement? = firstChild
while (element != null) {
if (element is LuaDocTagParam) {
val nameRef = element.paramNameRef
if (nameRef != null && nameRef.text == name)
return element
}
element = element.nextSibling
}
return null
}
override fun getFieldDef(name: String): LuaDocTagField? {
var element: PsiElement? = firstChild
while (element != null) {
if (element is LuaDocTagField) {
val nameRef = element.fieldName
if (nameRef != null && nameRef == name)
return element
}
element = element.nextSibling
}
return null
}
override val tagClass: LuaDocTagClass?
get() {
var element: PsiElement? = firstChild
while (element != null) {
if (element is LuaDocTagClass) {
return element
}
element = element.nextSibling
}
return null
}
override val tagReturn: LuaDocTagReturn?
get() {
var element: PsiElement? = firstChild
while (element != null) {
if (element is LuaDocTagReturn) {
return element
}
element = element.nextSibling
}
return null
}
override val tagType: LuaDocTagType?
get() {
var element: PsiElement? = firstChild
while (element != null) {
if (element is LuaDocTagType) {
return element
}
element = element.nextSibling
}
return null
}
override fun guessType(context: SearchContext): ITy {
val classDef = tagClass
if (classDef != null)
return classDef.type
val typeDef = tagType
return typeDef?.type ?: Ty.UNKNOWN
}
override fun isOverride(): Boolean {
var elem = firstChild
while (elem != null) {
if (elem is LuaDocTagDef) {
if (elem.text == "override") return true
}
elem = elem.nextSibling
}
return false
}
override fun createSubstitutor(): ITySubstitutor? {
if (!LuaSettings.instance.enableGeneric)
return null
val list = findTags(LuaDocGenericDef::class.java)
val map = mutableMapOf<String, String>()
for (def in list) {
val name = def.name
if (name != null) {
val base = def.classNameRef?.text
if (base != null) map[name] = base
}
}
if (map.isEmpty())
return null
return object : TySubstitutor() {
override fun substitute(clazz: ITyClass): ITy {
val base = map[clazz.className]
if (base != null) {
return TyParameter(clazz.className, base)
}
return super.substitute(clazz)
}
}
}
override fun toString(): String {
return "DOC_COMMENT"
}
fun accept(visitor: LuaVisitor) {
visitor.visitComment(this)
}
override fun accept(visitor: PsiElementVisitor) {
if (visitor is LuaVisitor) accept(visitor)
else super.accept(visitor)
}
}
|
apache-2.0
|
1f078b8e3246e79a089dc6c644425d21
| 29.849246 | 112 | 0.593908 | 4.68984 | false | false | false | false |
anlun/haskell-idea-plugin
|
plugin/src/org/jetbrains/haskell/actions/ShowTypeAction.kt
|
1
|
3810
|
package org.jetbrains.haskell.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.codeInsight.hint.HintManager
import org.jetbrains.haskell.util.getRelativePath
import org.jetbrains.haskell.util.LineColPosition
import com.intellij.psi.PsiElement
import org.jetbrains.haskell.external.GhcModi
import java.util.regex.Pattern
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.application.ModalityState
/**
* Created by atsky on 5/30/14.
*/
public class ShowTypeAction : AnAction() {
private data class TypeInfo(
val startLine: Int,
val startCol : Int,
val endLine: Int,
val endCol : Int,
val aType : String
)
fun typeInfoFromString(str : String) : TypeInfo? {
val matcher = Pattern.compile("(\\d+) (\\d+) (\\d+) (\\d+) \"(.*)\"").matcher(str)
if (matcher.matches()) {
return TypeInfo(
Integer.parseInt(matcher.group(1)!!),
Integer.parseInt(matcher.group(2)!!),
Integer.parseInt(matcher.group(3)!!),
Integer.parseInt(matcher.group(4)!!),
matcher.group(5)!!)
}
return null
}
override fun actionPerformed(e: AnActionEvent?) {
if (e == null) {
return
}
val editor = e.getData(CommonDataKeys.EDITOR)
val psiFile = e.getData(CommonDataKeys.PSI_FILE)
if (editor == null || psiFile == null) {
return
}
val offset = editor.getCaretModel().getOffset();
val selectionStartOffset = editor.getSelectionModel().getSelectionStart()
val selectionEndOffset = editor.getSelectionModel().getSelectionEnd()
val range = if (selectionStartOffset != selectionEndOffset) {
Pair(selectionStartOffset, selectionEndOffset)
} else {
val element = psiFile.findElementAt(offset)
val textRange = element?.getTextRange()
if (textRange == null) {
return
}
Pair(textRange.getStartOffset(), textRange.getEndOffset())
}
ApplicationManager.getApplication()!!.invokeAndWait(object : Runnable {
override fun run() {
FileDocumentManager.getInstance().saveAllDocuments()
}
}, ModalityState.any())
val start = LineColPosition.fromOffset(psiFile, range.first)!!
val end = LineColPosition.fromOffset(psiFile, range.second)!!
val lineColPosition = LineColPosition.fromOffset(psiFile, range.first)!!
val ghcModi = psiFile.getProject().getComponent(javaClass<GhcModi>())!!
val basePath = psiFile.getProject().getBasePath()!!
val relativePath = getRelativePath(basePath, psiFile.getVirtualFile()!!.getPath())
val line = lineColPosition.myLine
val column = lineColPosition.myColumn
val cmd = "type ${relativePath} ${line} ${column}"
val list = ghcModi.runCommand(cmd)
val result = list.map { typeInfoFromString(it) }.filterNotNull()
val typeInfo = result.firstOrNull {
it.startLine == start.myLine &&
it.startCol == start.myColumn &&
it.endLine == end.myLine &&
it.endCol == end.myColumn
}
if (typeInfo != null) {
HintManager.getInstance()!!.showInformationHint(editor, typeInfo.aType)
} else {
HintManager.getInstance()!!.showInformationHint(editor, "can't calculate type")
}
}
}
|
apache-2.0
|
d17d2b68f7da2cfd31ed3d1f0c94f0fa
| 35.295238 | 91 | 0.634383 | 4.954486 | false | false | false | false |
ohmae/DmsExplorer
|
mobile/src/main/java/net/mm2d/dmsexplorer/view/PhotoActivity.kt
|
1
|
5026
|
/*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.view
import android.content.res.Configuration
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import androidx.databinding.DataBindingUtil
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import net.mm2d.dmsexplorer.R
import net.mm2d.dmsexplorer.Repository
import net.mm2d.dmsexplorer.databinding.PhotoActivityBinding
import net.mm2d.dmsexplorer.domain.model.MediaServerModel
import net.mm2d.dmsexplorer.log.EventLogger
import net.mm2d.dmsexplorer.settings.Settings
import net.mm2d.dmsexplorer.util.FullscreenHelper
import net.mm2d.dmsexplorer.view.base.BaseActivity
import net.mm2d.dmsexplorer.view.view.ViewPagerAdapter
import net.mm2d.dmsexplorer.viewmodel.PhotoActivityModel
/**
* 静止画表示のActivity。
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class PhotoActivity : BaseActivity() {
private lateinit var settings: Settings
private lateinit var fullscreenHelper: FullscreenHelper
private lateinit var binding: PhotoActivityBinding
private lateinit var model: PhotoActivityModel
private lateinit var repository: Repository
private lateinit var serverModel: MediaServerModel
private val onPageChangeListener = object : OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) = Unit
override fun onPageSelected(position: Int) = Unit
override fun onPageScrollStateChanged(state: Int) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
onScrollIdle()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
settings = Settings.get()
setTheme(settings.themeParams.fullscreenThemeId)
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.photo_activity)
fullscreenHelper = FullscreenHelper(
rootView = binding.getRoot(),
topView = binding.toolbar
)
repository = Repository.get()
val serverModel = repository.mediaServerModel
if (serverModel == null) {
finish()
return
}
this.serverModel = serverModel
try {
model = PhotoActivityModel(this, repository)
} catch (ignored: IllegalStateException) {
finish()
return
}
binding.model = model
model.adjustPanel(this)
if (settings.shouldShowPhotoUiOnStart()) {
fullscreenHelper.showNavigation()
} else {
fullscreenHelper.hideNavigationImmediately()
}
val inflater = LayoutInflater.from(this)
binding.viewPager.adapter = ViewPagerAdapter().also {
it.add(inflater.inflate(R.layout.progress_view, binding.viewPager, false))
it.add(inflater.inflate(R.layout.transparent_view, binding.viewPager, false))
it.add(inflater.inflate(R.layout.progress_view, binding.viewPager, false))
}
binding.viewPager.setCurrentItem(1, false)
binding.viewPager.addOnPageChangeListener(onPageChangeListener)
}
override fun onDestroy() {
super.onDestroy()
fullscreenHelper.terminate()
}
override fun updateOrientationSettings() {
settings.photoOrientation
.setRequestedOrientation(this)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_UP && event.keyCode != KeyEvent.KEYCODE_BACK) {
fullscreenHelper.showNavigation()
}
return super.dispatchKeyEvent(event)
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
val result = super.dispatchTouchEvent(ev)
if (settings.shouldShowPhotoUiOnTouch()) {
fullscreenHelper.showNavigation()
}
return result
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
model.adjustPanel(this)
}
private fun onScrollIdle() {
val index = binding.viewPager.currentItem
if (index == 1) {
return
}
if (!move(index)) {
finish()
return
}
model = PhotoActivityModel(this, repository)
binding.model = model
binding.viewPager.setCurrentItem(1, false)
EventLogger.sendPlayContent(true)
}
private fun move(index: Int): Boolean {
return if (index == 0)
serverModel.selectPreviousEntity(MediaServerModel.SCAN_MODE_SEQUENTIAL)
else
serverModel.selectNextEntity(MediaServerModel.SCAN_MODE_SEQUENTIAL)
}
}
|
mit
|
e023180380f80e2b084ad386093d0762
| 32.530201 | 91 | 0.676541 | 4.869396 | false | false | false | false |
develar/mapsforge-tile-server
|
server/src/Responses.kt
|
1
|
6249
|
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.develar.mapsforgeTileServer.http
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelFutureListener
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.http.*
import io.netty.util.CharsetUtil
import java.nio.charset.Charset
import java.time.Instant
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoField
import java.util.Locale
private val DATE_FORMAT = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US)
private val GMT_ZONE_ID = ZoneId.of("GMT")
public fun formatTime(epochSecond: Long): String {
return DATE_FORMAT.format(ZonedDateTime.ofInstant(Instant.ofEpochSecond(epochSecond), GMT_ZONE_ID))
}
public fun parseTime(time: String): Long {
val temporalAccessor = DATE_FORMAT.parse(time)
if (ChronoField.INSTANT_SECONDS.isSupportedBy(temporalAccessor)) {
return temporalAccessor.getLong(ChronoField.INSTANT_SECONDS)
}
else {
return ZonedDateTime.from(temporalAccessor).toEpochSecond()
}
}
public fun response(status: HttpResponseStatus): FullHttpResponse {
return DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.EMPTY_BUFFER)
}
public fun response(contentType: String?, content: ByteBuf?): HttpResponse {
val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content ?: Unpooled.EMPTY_BUFFER)
if (contentType != null) {
response.headers().add(HttpHeaderNames.CONTENT_TYPE, contentType)
}
return response
}
public fun addAllowAnyOrigin(response: HttpResponse) {
response.headers().add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, "*")
}
public fun addDate(response: HttpResponse) {
if (!response.headers().contains(HttpHeaderNames.DATE)) {
addDate(response, ZonedDateTime.now(GMT_ZONE_ID))
}
}
public fun addDate(response: HttpResponse, temporal: ZonedDateTime) {
response.headers().set(HttpHeaderNames.DATE, DATE_FORMAT.format(temporal))
}
public fun addNoCache(response: HttpResponse) {
response.headers().add(HttpHeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate, max-age=0")
response.headers().add(HttpHeaderNames.PRAGMA, "no-cache")
}
public fun addServer(response: HttpResponse) {
response.headers().add(HttpHeaderNames.SERVER, "MapsforgeTileServer")
}
public fun send(response: HttpResponse, channel: Channel, request: HttpRequest?) {
if (response.status() != HttpResponseStatus.NOT_MODIFIED && !HttpHeaderUtil.isContentLengthSet(response)) {
HttpHeaderUtil.setContentLength(response, (if (response is FullHttpResponse) (response).content().readableBytes() else 0).toLong())
}
addCommonHeaders(response)
send(response, channel, request != null && !addKeepAliveIfNeed(response, request))
}
public fun addKeepAliveIfNeed(response: HttpResponse, request: HttpRequest): Boolean {
if (HttpHeaderUtil.isKeepAlive(request)) {
HttpHeaderUtil.setKeepAlive(response, true)
return true
}
return false
}
public fun addCommonHeaders(response: HttpResponse) {
addServer(response)
addDate(response)
addAllowAnyOrigin(response)
}
public fun send(content: CharSequence, channel: Channel, request: HttpRequest?) {
send(content, CharsetUtil.US_ASCII, channel, request)
}
public fun send(content: CharSequence, charset: Charset, channel: Channel, request: HttpRequest?) {
send(DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.copiedBuffer(content, charset)), channel, request)
}
private fun send(response: HttpResponse, channel: Channel, close: Boolean) {
if (!channel.isActive()) {
return
}
val future = channel.write(response)
if (response !is FullHttpResponse) {
channel.write(LastHttpContent.EMPTY_LAST_CONTENT)
}
channel.flush()
if (close) {
future.addListener(ChannelFutureListener.CLOSE)
}
}
public fun sendStatus(responseStatus: HttpResponseStatus, channel: Channel) {
sendStatus(responseStatus, channel, null)
}
public fun sendStatus(responseStatus: HttpResponseStatus, channel: Channel, request: HttpRequest?) {
sendStatus(responseStatus, channel, null, request)
}
public fun sendStatus(responseStatus: HttpResponseStatus, channel: Channel, description: String?, request: HttpRequest?) {
send(createStatusResponse(responseStatus, request, description), channel, request)
}
private fun createStatusResponse(responseStatus: HttpResponseStatus, request: HttpRequest?, description: String?): HttpResponse {
if (request != null && request.method() == HttpMethod.HEAD) {
return response(responseStatus)
}
val builder = StringBuilder()
val message = responseStatus.toString()
builder.append("<!doctype html><title>").append(message).append("</title>").append("<h1 style=\"text-align: center\">").append(message).append("</h1>")
if (description != null) {
builder.append("<p>").append(description).append("</p>")
}
builder.append("<hr/><p style=\"text-align: center\">").append("MapsforgeTileServer").append("</p>")
val response = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, responseStatus, Unpooled.copiedBuffer(builder, CharsetUtil.UTF_8))
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html")
return response
}
public fun sendOptionsResponse(allowHeaders: String, request: HttpRequest, context: ChannelHandlerContext) {
val response = response(HttpResponseStatus.OK)
response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, allowHeaders)
response.headers().set(HttpHeaderNames.ALLOW, allowHeaders)
send(response, context.channel(), request)
}
|
mit
|
6db217ccd8e5425468aaf1948672ccc1
| 36.42515 | 153 | 0.766043 | 4.166 | false | false | false | false |
ThomasVadeSmileLee/cyls
|
src/main/kotlin/org/smileLee/cyls/util/WebUtil.kt
|
1
|
868
|
package org.smileLee.cyls.util
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
object WebUtil {
/**
* @param urlString :请求接口
*
* @return 返回结果
*/
fun request(urlString: String, parameters: Map<String, String> = HashMap(), mode: String = "GET"): String {
val url = URL(urlString)
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = mode
for ((key, value) in parameters) {
connection.addRequestProperty(key, value)
}
connection.connect()
val reader = BufferedReader(InputStreamReader(connection.inputStream, "UTF-8"))
val ret = StringBuilder()
while (true) ret.append((reader.readLine() ?: break))
return ret.toString()
}
}
|
mit
|
b1feb5a327bacd88e693f60c0b77d328
| 28.37931 | 111 | 0.647887 | 4.369231 | false | false | false | false |
ligee/kotlin-jupyter
|
jupyter-lib/api/src/main/kotlin/org/jetbrains/kotlinx/jupyter/api/libraries/JupyterIntegration.kt
|
1
|
10497
|
package org.jetbrains.kotlinx.jupyter.api.libraries
import org.jetbrains.kotlinx.jupyter.api.AfterCellExecutionCallback
import org.jetbrains.kotlinx.jupyter.api.ClassAnnotationHandler
import org.jetbrains.kotlinx.jupyter.api.ClassDeclarationsCallback
import org.jetbrains.kotlinx.jupyter.api.Code
import org.jetbrains.kotlinx.jupyter.api.CodeCell
import org.jetbrains.kotlinx.jupyter.api.CodePreprocessor
import org.jetbrains.kotlinx.jupyter.api.ExecutionCallback
import org.jetbrains.kotlinx.jupyter.api.FieldHandler
import org.jetbrains.kotlinx.jupyter.api.FieldHandlerByClass
import org.jetbrains.kotlinx.jupyter.api.FieldHandlerExecution
import org.jetbrains.kotlinx.jupyter.api.FieldValue
import org.jetbrains.kotlinx.jupyter.api.FileAnnotationCallback
import org.jetbrains.kotlinx.jupyter.api.FileAnnotationHandler
import org.jetbrains.kotlinx.jupyter.api.InternalVariablesMarker
import org.jetbrains.kotlinx.jupyter.api.InterruptionCallback
import org.jetbrains.kotlinx.jupyter.api.KotlinKernelHost
import org.jetbrains.kotlinx.jupyter.api.Notebook
import org.jetbrains.kotlinx.jupyter.api.RendererHandler
import org.jetbrains.kotlinx.jupyter.api.RendererTypeHandler
import org.jetbrains.kotlinx.jupyter.api.ResultHandlerExecution
import org.jetbrains.kotlinx.jupyter.api.SubtypeRendererTypeHandler
import org.jetbrains.kotlinx.jupyter.api.SubtypeThrowableRenderer
import org.jetbrains.kotlinx.jupyter.api.ThrowableRenderer
import org.jetbrains.kotlinx.jupyter.api.TypeName
import org.jetbrains.kotlinx.jupyter.api.VariableDeclarationCallback
import org.jetbrains.kotlinx.jupyter.api.VariableUpdateCallback
import org.jetbrains.kotlinx.jupyter.util.AcceptanceRule
import org.jetbrains.kotlinx.jupyter.util.NameAcceptanceRule
import kotlin.reflect.KMutableProperty
/**
* Base class for library integration with Jupyter Kernel via DSL
* Derive from this class and pass registration callback into constructor
*/
abstract class JupyterIntegration : LibraryDefinitionProducer {
abstract fun Builder.onLoaded()
class Builder(val notebook: Notebook) {
private val renderers = mutableListOf<RendererHandler>()
private val throwableRenderers = mutableListOf<ThrowableRenderer>()
private val init = mutableListOf<ExecutionCallback<*>>()
private val beforeCellExecution = mutableListOf<ExecutionCallback<*>>()
private val afterCellExecution = mutableListOf<AfterCellExecutionCallback>()
private val shutdownCallbacks = mutableListOf<ExecutionCallback<*>>()
private val converters = mutableListOf<FieldHandler>()
private val classAnnotations = mutableListOf<ClassAnnotationHandler>()
private val fileAnnotations = mutableListOf<FileAnnotationHandler>()
private val resources = mutableListOf<LibraryResource>()
private val imports = mutableListOf<String>()
private val dependencies = mutableListOf<String>()
private val repositories = mutableListOf<String>()
private val codePreprocessors = mutableListOf<CodePreprocessor>()
private val internalVariablesMarkers = mutableListOf<InternalVariablesMarker>()
private val integrationTypeNameRules = mutableListOf<AcceptanceRule<String>>()
private val interruptionCallbacks = mutableListOf<InterruptionCallback>()
fun addRenderer(handler: RendererHandler) {
renderers.add(handler)
}
// Left for ABI compatibility
fun addRenderer(handler: RendererTypeHandler) {
renderers.add(handler)
}
fun addThrowableRenderer(renderer: ThrowableRenderer) {
throwableRenderers.add(renderer)
}
fun addTypeConverter(handler: FieldHandler) {
converters.add(handler)
}
fun addClassAnnotationHandler(handler: ClassAnnotationHandler) {
classAnnotations.add(handler)
}
fun addFileAnnotationHanlder(handler: FileAnnotationHandler) {
fileAnnotations.add(handler)
}
fun addCodePreprocessor(preprocessor: CodePreprocessor) {
codePreprocessors.add(preprocessor)
}
fun markVariableInternal(marker: InternalVariablesMarker) {
internalVariablesMarkers.add(marker)
}
inline fun <reified T : Any> render(noinline renderer: CodeCell.(T) -> Any) {
return renderWithHost { _, value: T -> renderer(this, value) }
}
inline fun <reified T : Any> renderWithHost(noinline renderer: CodeCell.(ExecutionHost, T) -> Any) {
val execution = ResultHandlerExecution { host, property ->
val currentCell = notebook.currentCell
?: throw IllegalStateException("Current cell should not be null on renderer invocation")
FieldValue(renderer(currentCell, host, property.value as T), property.name)
}
addRenderer(SubtypeRendererTypeHandler(T::class, execution))
}
inline fun <reified E : Throwable> renderThrowable(noinline renderer: (E) -> Any) {
addThrowableRenderer(SubtypeThrowableRenderer(E::class, renderer))
}
fun resource(resource: LibraryResource) {
resources.add(resource)
}
fun import(vararg paths: String) {
imports.addAll(paths)
}
inline fun <reified T> import() {
import(T::class.qualifiedName!!)
}
inline fun <reified T> importPackage() {
val name = T::class.qualifiedName!!
val lastDot = name.lastIndexOf(".")
if (lastDot != -1) {
import(name.substring(0, lastDot + 1) + "*")
}
}
fun dependencies(vararg paths: String) {
dependencies.addAll(paths)
}
fun repositories(vararg paths: String) {
repositories.addAll(paths)
}
fun onLoaded(callback: KotlinKernelHost.() -> Unit) {
init.add(callback)
}
fun onShutdown(callback: KotlinKernelHost.() -> Unit) {
shutdownCallbacks.add(callback)
}
fun beforeCellExecution(callback: KotlinKernelHost.() -> Unit) {
beforeCellExecution.add(callback)
}
fun afterCellExecution(callback: AfterCellExecutionCallback) {
afterCellExecution.add(callback)
}
inline fun <reified T : Any> onVariable(noinline callback: VariableDeclarationCallback<T>) {
val execution = FieldHandlerExecution(callback)
addTypeConverter(FieldHandlerByClass(T::class, execution))
}
inline fun <reified T : Any> updateVariable(noinline callback: VariableUpdateCallback<T>) {
val execution = FieldHandlerExecution<T> { host, value, property ->
val tempField = callback(host, value, property)
if (tempField != null) {
val valOrVar = if (property is KMutableProperty) "var" else "val"
val redeclaration = "$valOrVar ${property.name} = $tempField"
host.execute(redeclaration)
}
}
addTypeConverter(FieldHandlerByClass(T::class, execution))
}
inline fun <reified T : Annotation> onClassAnnotation(noinline callback: ClassDeclarationsCallback) {
addClassAnnotationHandler(ClassAnnotationHandler(T::class, callback))
}
inline fun <reified T : Annotation> onFileAnnotation(noinline callback: FileAnnotationCallback) {
addFileAnnotationHanlder(FileAnnotationHandler(T::class, callback))
}
fun preprocessCodeWithLibraries(callback: KotlinKernelHost.(Code) -> CodePreprocessor.Result) {
addCodePreprocessor(object : CodePreprocessor {
override fun process(code: String, host: KotlinKernelHost): CodePreprocessor.Result {
return host.callback(code)
}
})
}
fun preprocessCode(callback: KotlinKernelHost.(Code) -> Code) {
preprocessCodeWithLibraries { CodePreprocessor.Result(this.callback(it)) }
}
/**
* All integrations transitively loaded by this integration will be tested against
* passed acceptance rule and won't be loaded if the rule returned `false`.
* If there were no acceptance rules that returned not-null values, integration
* **will be loaded**. If there are several acceptance rules that returned not-null values,
* the latest one will be taken into account.
*/
fun addIntegrationTypeNameRule(rule: AcceptanceRule<TypeName>) {
integrationTypeNameRules.add(rule)
}
/**
* See [addIntegrationTypeNameRule]
*/
fun acceptIntegrationTypeNameIf(predicate: (TypeName) -> Boolean) {
addIntegrationTypeNameRule(NameAcceptanceRule(true, predicate))
}
/**
* See [addIntegrationTypeNameRule]
*/
fun discardIntegrationTypeNameIf(predicate: (TypeName) -> Boolean) {
addIntegrationTypeNameRule(NameAcceptanceRule(false, predicate))
}
fun onInterrupt(action: InterruptionCallback) {
interruptionCallbacks.add(action)
}
internal fun getDefinition() =
libraryDefinition {
it.init = init
it.renderers = renderers
it.throwableRenderers = throwableRenderers
it.converters = converters
it.imports = imports
it.dependencies = dependencies
it.repositories = repositories
it.initCell = beforeCellExecution
it.afterCellExecution = afterCellExecution
it.shutdown = shutdownCallbacks
it.classAnnotations = classAnnotations
it.fileAnnotations = fileAnnotations
it.resources = resources
it.codePreprocessors = codePreprocessors
it.internalVariablesMarkers = internalVariablesMarkers
it.integrationTypeNameRules = integrationTypeNameRules
it.interruptionCallbacks = interruptionCallbacks
}
}
override fun getDefinitions(notebook: Notebook): List<LibraryDefinition> {
val builder = Builder(notebook)
builder.onLoaded()
return listOf(builder.getDefinition())
}
}
|
apache-2.0
|
9155511bb8b79fbb1fa5e947c5a77b9c
| 38.761364 | 109 | 0.673812 | 5.355612 | false | false | false | false |
HabitRPG/habitica-android
|
Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/CustomizationRecyclerViewAdapter.kt
|
1
|
13673
|
package com.habitrpg.android.habitica.ui.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.habitrpg.android.habitica.HabiticaBaseApplication
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.CustomizationGridItemBinding
import com.habitrpg.android.habitica.databinding.CustomizationSectionFooterBinding
import com.habitrpg.android.habitica.databinding.CustomizationSectionHeaderBinding
import com.habitrpg.android.habitica.helpers.MainNavigationController
import com.habitrpg.android.habitica.models.inventory.Customization
import com.habitrpg.android.habitica.models.inventory.CustomizationSet
import com.habitrpg.android.habitica.models.shops.ShopItem
import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog
import com.habitrpg.android.habitica.ui.views.shops.PurchaseDialog
import com.habitrpg.common.habitica.extensions.dpToPx
import com.habitrpg.common.habitica.extensions.loadImage
import com.habitrpg.shared.habitica.models.Avatar
import com.habitrpg.common.habitica.views.AvatarView
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.subjects.PublishSubject
import java.util.Date
import java.util.EnumMap
import kotlin.math.min
class CustomizationRecyclerViewAdapter() : androidx.recyclerview.widget.RecyclerView.Adapter<androidx.recyclerview.widget.RecyclerView.ViewHolder>() {
var userSize: String? = null
var hairColor: String? = null
var avatar: Avatar? = null
var customizationType: String? = null
var gemBalance = 0
var columnCount = 1
var unsortedCustomizations: List<Customization> = ArrayList()
private var customizationList: MutableList<Any> = ArrayList()
var additionalSetItems: List<Customization> = ArrayList()
var activeCustomization: String? = null
set(value) {
field = value
}
var ownedCustomizations: List<String> = listOf()
private var pinnedItemKeys: List<String> = ArrayList()
private val selectCustomizationEvents = PublishSubject.create<Customization>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): androidx.recyclerview.widget.RecyclerView.ViewHolder {
return when (viewType) {
0 -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.customization_section_header, parent, false)
SectionViewHolder(view)
}
1 -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.customization_section_footer, parent, false)
SectionFooterViewHolder(view)
}
else -> {
val viewID: Int = if (customizationType == "background") {
R.layout.customization_grid_background_item
} else {
R.layout.customization_grid_item
}
val view = LayoutInflater.from(parent.context).inflate(viewID, parent, false)
CustomizationViewHolder(view)
}
}
}
override fun onBindViewHolder(
holder: androidx.recyclerview.widget.RecyclerView.ViewHolder,
position: Int
) {
val obj = customizationList[position]
if (getItemViewType(position) == 0) {
(holder as SectionViewHolder).bind(obj as CustomizationSet)
} else if (getItemViewType(position) == 1) {
(holder as SectionFooterViewHolder).bind(obj as CustomizationSet)
val count = min(columnCount, obj.customizations.size)
holder.buttonWidth = (count * 76.dpToPx(holder.itemView.context)) + ((count - 1) * 12.dpToPx(holder.itemView.context))
holder.additionalSetItems = additionalSetItems.filter { it.purchasable && (it.price ?: 0) > 0 }
} else {
(holder as CustomizationViewHolder).bind(customizationList[position] as Customization)
}
}
override fun getItemCount(): Int {
return customizationList.size
}
override fun getItemViewType(position: Int): Int {
if (customizationList.size <= position) return 0
return if (this.customizationList[position] is CustomizationSet &&
(position == (customizationList.size - 1) || (position < customizationList.size && customizationList[position + 1] is CustomizationSet))
) {
1
} else if (this.customizationList[position] is CustomizationSet) {
0
} else {
2
}
}
fun setCustomizations(newCustomizationList: List<Customization>) {
unsortedCustomizations = newCustomizationList
this.customizationList = ArrayList()
var lastSet = CustomizationSet()
val today = Date()
for (customization in newCustomizationList) {
if (customization.availableFrom != null || customization.availableUntil != null) {
if (((customization.availableFrom?.compareTo(today)
?: 0) > 0 || (customization.availableUntil?.compareTo(today)
?: 0) < 0) && !customization.isUsable(
ownedCustomizations.contains(
customization.id
)
)
) {
continue
}
}
if (customization.customizationSet != null && customization.customizationSet != lastSet.identifier) {
if (lastSet.hasPurchasable && lastSet.price > 0) {
customizationList.add(lastSet)
}
val set = CustomizationSet()
set.identifier = customization.customizationSet
set.text = customization.customizationSetName
set.price = customization.setPrice ?: 0
set.hasPurchasable = true
lastSet = set
customizationList.add(set)
}
customizationList.add(customization)
lastSet.customizations.add(customization)
if (customization.isUsable(ownedCustomizations.contains(customization.id)) && lastSet.hasPurchasable) {
lastSet.ownedCustomizations.add(customization)
if (!lastSet.isSetDeal()) {
lastSet.hasPurchasable = false
}
}
}
if (lastSet.hasPurchasable) {
customizationList.add(lastSet)
}
this.notifyDataSetChanged()
}
fun getSelectCustomizationEvents(): Flowable<Customization> {
return selectCustomizationEvents.toFlowable(BackpressureStrategy.DROP)
}
fun setPinnedItemKeys(pinnedItemKeys: List<String>) {
this.pinnedItemKeys = pinnedItemKeys
if (customizationList.size > 0) this.notifyDataSetChanged()
}
internal inner class CustomizationViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val binding = CustomizationGridItemBinding.bind(itemView)
var customization: Customization? = null
init {
itemView.setOnClickListener(this)
}
fun bind(customization: Customization) {
this.customization = customization
if (customization.type == "background" && customization.identifier == "") {
binding.imageView.setImageResource(R.drawable.no_background)
binding.imageView.bitmap = null
} else {
binding.imageView.loadImage(customization.getIconName(userSize, hairColor))
}
if (customization.isUsable(ownedCustomizations.contains(customization.id))) {
binding.buyButton.visibility = View.GONE
} else {
binding.buyButton.visibility = View.VISIBLE
if (customization.customizationSet?.contains("timeTravel") == true) {
binding.priceLabel.currency = "hourglasses"
} else {
binding.priceLabel.currency = "gems"
}
binding.priceLabel.value = customization.price?.toDouble() ?: 0.0
}
val identifier = if (customization.type == "chair") "chair_${customization.identifier}" else customization.identifier
if (activeCustomization == identifier) {
binding.wrapper.background = ContextCompat.getDrawable(itemView.context, R.drawable.layout_rounded_bg_window_tint_border)
} else {
binding.wrapper.background = ContextCompat.getDrawable(itemView.context, R.drawable.layout_rounded_bg_window)
}
}
override fun onClick(v: View) {
if (customization?.isUsable(ownedCustomizations.contains(customization?.id)) == false) {
if (customization?.customizationSet?.contains("timeTravel") == true) {
val dialog = HabiticaAlertDialog(itemView.context)
dialog.setMessage(R.string.purchase_from_timetravel_shop)
dialog.addButton(R.string.go_shopping, true) { _, _ ->
MainNavigationController.navigate(R.id.timeTravelersShopFragment)
}
dialog.addButton(R.string.reward_dialog_dismiss, false)
dialog.show()
} else {
customization?.let {
val dialog = PurchaseDialog(itemView.context, HabiticaBaseApplication.userComponent, ShopItem.fromCustomization(it, userSize, hairColor))
if (it.type == "background") dialog.isPinned = pinnedItemKeys.contains(ShopItem.fromCustomization(it, userSize, hairColor).key)
dialog.show()
}
}
return
}
if (customization?.type != "background" && customization?.identifier == activeCustomization) {
return
}
if (customization?.type == "background" && avatar != null){
val alert = HabiticaAlertDialog(context = itemView.context)
val purchasedCustomizationView: View = LayoutInflater.from(itemView.context).inflate(R.layout.purchased_equip_dialog, null)
val layerMap = EnumMap<AvatarView.LayerType, String>(AvatarView.LayerType::class.java)
layerMap[AvatarView.LayerType.BACKGROUND] = customization?.let { ShopItem.fromCustomization(it, userSize, hairColor).imageName }
purchasedCustomizationView.findViewById<AvatarView>(R.id.avatar_view).setAvatar(avatar!!, layerMap)
alert.setAdditionalContentView(purchasedCustomizationView)
alert.setTitle(customization?.text)
alert.setMessage(customization?.notes)
alert.addButton(R.string.equip, true) { _, _ ->
customization?.let {
selectCustomizationEvents.onNext(it)
}
}
alert.addButton(R.string.close, false) { _, _ ->
alert.dismiss()
}
alert.show()
} else {
customization?.let {
selectCustomizationEvents.onNext(it)
}
}
}
}
internal inner class SectionViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
private val binding = CustomizationSectionHeaderBinding.bind(itemView)
fun bind(set: CustomizationSet) {
binding.label.text = set.text
}
}
internal inner class SectionFooterViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView), View.OnClickListener {
private val binding = CustomizationSectionFooterBinding.bind(itemView)
var context: Context = itemView.context
private var set: CustomizationSet? = null
var additionalSetItems: List<Customization>? = null
var buttonWidth: Int
get() = binding.purchaseSetButton.width
set(value) {
val params = binding.purchaseSetButton.layoutParams
params.width = value
binding.purchaseSetButton.layoutParams = params
}
init {
binding.purchaseSetButton.setOnClickListener(this)
}
fun bind(set: CustomizationSet) {
this.set = set
if (set.hasPurchasable && set.identifier?.contains("timeTravel") != true) {
binding.purchaseSetButton.visibility = View.VISIBLE
binding.setPriceLabel.value = set.price.toDouble()
binding.setPriceLabel.currency = "gems"
} else {
binding.purchaseSetButton.visibility = View.GONE
}
}
override fun onClick(v: View) {
set?.let {
val dialog = PurchaseDialog(itemView.context, HabiticaBaseApplication.userComponent, ShopItem.fromCustomizationSet(it, additionalSetItems, userSize, hairColor))
dialog.show()
}
}
}
}
|
gpl-3.0
|
53233022555fa42e2dc6cd1fe5195c61
| 43.88255 | 176 | 0.613545 | 5.419342 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/fast_continue/ui/fragment/FastContinueNewHomeFragment.kt
|
2
|
7281
|
package org.stepik.android.view.fast_continue.ui.fragment
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.fragment_fast_continue_new_home.*
import kotlinx.android.synthetic.main.view_fast_continue_information.*
import kotlinx.android.synthetic.main.view_fast_continue_information.fastContinueCourseCover
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment
import org.stepic.droid.util.ProgressHelper
import org.stepic.droid.util.safeDiv
import org.stepic.droid.util.toFixed
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.last_step.model.LastStep
import org.stepik.android.model.Course
import org.stepik.android.presentation.course_continue.model.CourseContinueInteractionSource
import org.stepik.android.presentation.fast_continue.FastContinuePresenter
import org.stepik.android.presentation.fast_continue.FastContinueView
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import javax.inject.Inject
class FastContinueNewHomeFragment : Fragment(R.layout.fragment_fast_continue_new_home), FastContinueView {
companion object {
fun newInstance(): Fragment =
FastContinueNewHomeFragment()
}
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var analytic: Analytic
@Inject
internal lateinit var screenManager: ScreenManager
private val fastContinuePresenter: FastContinuePresenter by viewModels { viewModelFactory }
private lateinit var viewStateDelegate: ViewStateDelegate<FastContinueView.State>
private val progressDialogFragment: DialogFragment =
LoadingProgressDialogFragment.newInstance()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectComponent()
}
private fun injectComponent() {
App
.component()
.fastContinueComponentBuilder()
.build()
.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewStateDelegate = ViewStateDelegate()
viewStateDelegate.addState<FastContinueView.State.Idle>()
viewStateDelegate.addState<FastContinueView.State.Loading>()
viewStateDelegate.addState<FastContinueView.State.Empty>(fastContinueEmpty)
viewStateDelegate.addState<FastContinueView.State.Anonymous>(fastContinueEmpty)
viewStateDelegate.addState<FastContinueView.State.Content>(fastContinueInformation)
}
override fun onStart() {
super.onStart()
fastContinuePresenter.attachView(this)
}
override fun onStop() {
fastContinuePresenter.detachView(this)
super.onStop()
}
override fun setState(state: FastContinueView.State) {
viewStateDelegate.switchState(state)
onStateChange(state)
when (state) {
is FastContinueView.State.Empty -> {
analytic.reportEvent(Analytic.FastContinue.EMPTY_COURSES_SHOWN)
fastContinueEmpty.setOnClickListener {
analytic.reportEvent(Analytic.FastContinue.EMPTY_COURSES_CLICK)
screenManager.showCatalog(context)
}
}
is FastContinueView.State.Anonymous -> {
analytic.reportEvent(Analytic.FastContinue.AUTH_SHOWN)
fastContinueEmpty.setOnClickListener {
analytic.reportEvent(Analytic.FastContinue.AUTH_CLICK)
screenManager.showCatalog(context)
}
}
is FastContinueView.State.Content -> {
analytic.reportEvent(Analytic.FastContinue.CONTINUE_SHOWN)
setCourse(state.courseListItem)
fastContinueInformation.setOnClickListener { handleContinueCourseClick(state.courseListItem.course) }
}
}
}
private fun onStateChange(state: FastContinueView.State) {
when (state) {
is FastContinueView.State.Idle, FastContinueView.State.Loading -> {
(parentFragment as? Callback)?.onFastContinueLoaded(false)
}
else -> {
(parentFragment as? Callback)?.onFastContinueLoaded(true)
}
}
}
private fun setCourse(courseListItem: CourseListItem.Data) {
Glide
.with(requireContext())
.asBitmap()
.load(courseListItem.course.cover)
.placeholder(R.drawable.general_placeholder)
.fitCenter()
.into(fastContinueCourseCover)
fastContinueCourseTitle.text = courseListItem.course.title
val progress = courseListItem.courseStats.progress
val needShow = if (progress != null && progress.cost > 0f) {
val score = progress
.score
?.toFloatOrNull()
?: 0f
prepareViewForProgress(score, progress.cost)
true
} else {
false
}
fastContinueProgressView.isVisible = needShow
fastContinueProgressTitle.isVisible = needShow
}
private fun handleContinueCourseClick(course: Course) {
analytic.reportEvent(Analytic.FastContinue.CONTINUE_CLICK)
fastContinuePresenter.continueCourse(course, CourseViewSource.FastContinue, CourseContinueInteractionSource.HOME_WIDGET)
}
override fun showCourse(course: Course, source: CourseViewSource, isAdaptive: Boolean) {
if (isAdaptive) {
screenManager.continueAdaptiveCourse(activity, course)
} else {
screenManager.showCourseModules(activity, course, source)
}
}
override fun showSteps(course: Course, source: CourseViewSource, lastStep: LastStep) {
screenManager.continueCourse(activity, course.id, source, lastStep)
}
override fun setBlockingLoading(isLoading: Boolean) {
fastContinueInformation.isEnabled = !isLoading
fastContinueInformation.isEnabled = !isLoading
if (isLoading) {
ProgressHelper.activate(progressDialogFragment, parentFragmentManager, LoadingProgressDialogFragment.TAG)
} else {
ProgressHelper.dismiss(parentFragmentManager, LoadingProgressDialogFragment.TAG)
}
}
private fun prepareViewForProgress(score: Float, cost: Long) {
fastContinueProgressView.progress = (score * 100 safeDiv cost) / 100f
fastContinueProgressTitle.text = resources
.getString(R.string.course_content_text_progress, score.toFixed(resources.getInteger(R.integer.score_decimal_count)), cost)
}
interface Callback {
fun onFastContinueLoaded(isVisible: Boolean)
}
}
|
apache-2.0
|
f943b2a9bbf38474e71b11fb4f109ab0
| 38.150538 | 135 | 0.701415 | 5.238129 | false | false | false | false |
GKZX-HN/MyGithub
|
app/src/main/java/com/gkzxhn/mygithub/ui/wedgit/DragDispatchCardView.kt
|
1
|
2873
|
package com.gkzxhn.mygithub.ui.wedgit
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.widget.ImageView
import com.gkzxhn.mygithub.R
import com.gkzxhn.mygithub.extension.dp2px
/**
* Created by 方 on 2018/1/17.
*/
class DragDispatchCardView: ImageView {
private var mWidth = 40f.dp2px()
private var mHeight = 40f.dp2px()
var originalRawX = 0f
var originalRawY = 0f
private var mRawX = 0f
private var mRawY = 0f
private val mPaint = Paint()
private var drawableRes = R.drawable.note
private var onActionListener: OnActionListener? = null
private val PRESS_TIME = 800L
private var pressFlag = false
fun setOnActionListener(onActionListener: OnActionListener) {
this.onActionListener = onActionListener
}
constructor(context: Context): this(context, null)
constructor(context: Context, attrs: AttributeSet?): super(context, attrs){
initPaint()
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mWidth = w.toFloat()
mHeight = h.toFloat()
}
private fun initPaint() {
mPaint.color = Color.BLACK
mPaint.strokeWidth = 2.0f.dp2px()
mPaint.style = Paint.Style.FILL
mPaint.flags = Paint.ANTI_ALIAS_FLAG
}
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
return super.dispatchTouchEvent(event)
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent?): Boolean {
Log.i(javaClass.simpleName, "action : event ${event!!.action}")
when (event!!.action) {
MotionEvent.ACTION_MOVE -> {
val rawX = event.rawX
val rawY = event.rawY
translationX = rawX - originalRawX
translationY = rawY - originalRawY
invalidate()
return true
}
MotionEvent.ACTION_DOWN -> {
originalRawX = event.rawX
originalRawY = event.rawY
Log.i(javaClass.simpleName, "event_down rawX : $originalRawX ; \r\n rawY : $originalRawY")
return true
}
MotionEvent.ACTION_UP -> {
val rawX = event.rawX
val rawY = event.rawY
if (onActionListener != null) {
onActionListener!!.onActionUp(rawX, rawY)
}
return true
}
else -> {
}
}
return super.onTouchEvent(event)
}
interface OnActionListener {
fun onActionUp(rawX: Float, rawY: Float)
}
}
|
gpl-3.0
|
660907fb00605dec043ea5f12daf4df4
| 28.010101 | 106 | 0.610589 | 4.608347 | false | false | false | false |
exponentjs/exponent
|
packages/expo-camera/android/src/main/java/expo/modules/camera/events/CameraReadyEvent.kt
|
2
|
683
|
package expo.modules.camera.events
import android.os.Bundle
import androidx.core.util.Pools
import expo.modules.camera.CameraViewManager
import expo.modules.core.interfaces.services.EventEmitter.BaseEvent
class CameraReadyEvent private constructor() : BaseEvent() {
override fun getEventName() = CameraViewManager.Events.EVENT_CAMERA_READY.toString()
override fun getEventBody(): Bundle = Bundle.EMPTY
companion object {
private val EVENTS_POOL = Pools.SynchronizedPool<CameraReadyEvent>(3)
fun obtain(): CameraReadyEvent {
var event = EVENTS_POOL.acquire()
if (event == null) {
event = CameraReadyEvent()
}
return event
}
}
}
|
bsd-3-clause
|
6e7460fabe6f7d8f6fcd870a5d3802cd
| 28.695652 | 86 | 0.734993 | 4.378205 | false | false | false | false |
k9mail/k-9
|
app/core/src/main/java/com/fsck/k9/mailstore/SpecialFolderUpdater.kt
|
2
|
5785
|
package com.fsck.k9.mailstore
import com.fsck.k9.Account
import com.fsck.k9.Account.SpecialFolderSelection
import com.fsck.k9.Preferences
import com.fsck.k9.mail.FolderClass
import com.fsck.k9.preferences.Protocols
/**
* Updates special folders in [Account] if they are marked as [SpecialFolderSelection.AUTOMATIC] or if they are marked
* as [SpecialFolderSelection.MANUAL] but have been deleted from the server.
*/
// TODO: Find a better way to deal with local-only special folders
class SpecialFolderUpdater(
private val preferences: Preferences,
private val folderRepository: FolderRepository,
private val specialFolderSelectionStrategy: SpecialFolderSelectionStrategy,
private val account: Account
) {
fun updateSpecialFolders() {
val folders = folderRepository.getRemoteFolders(account)
updateInbox(folders)
if (!account.isPop3()) {
updateSpecialFolder(FolderType.ARCHIVE, folders)
updateSpecialFolder(FolderType.DRAFTS, folders)
updateSpecialFolder(FolderType.SENT, folders)
updateSpecialFolder(FolderType.SPAM, folders)
updateSpecialFolder(FolderType.TRASH, folders)
}
removeImportedSpecialFoldersData()
saveAccount()
}
private fun updateInbox(folders: List<RemoteFolder>) {
val oldInboxId = account.inboxFolderId
val newInboxId = folders.firstOrNull { it.type == FolderType.INBOX }?.id
if (newInboxId == oldInboxId) return
account.inboxFolderId = newInboxId
if (oldInboxId != null && folders.any { it.id == oldInboxId }) {
folderRepository.setIncludeInUnifiedInbox(account, oldInboxId, false)
}
if (newInboxId != null) {
folderRepository.setIncludeInUnifiedInbox(account, newInboxId, true)
folderRepository.setDisplayClass(account, newInboxId, FolderClass.FIRST_CLASS)
folderRepository.setSyncClass(account, newInboxId, FolderClass.FIRST_CLASS)
folderRepository.setPushClass(account, newInboxId, FolderClass.FIRST_CLASS)
folderRepository.setNotificationClass(account, newInboxId, FolderClass.FIRST_CLASS)
}
}
private fun updateSpecialFolder(type: FolderType, folders: List<RemoteFolder>) {
val importedServerId = getImportedSpecialFolderServerId(type)
if (importedServerId != null) {
val folderId = folders.firstOrNull { it.serverId == importedServerId }?.id
if (folderId != null) {
setSpecialFolder(type, folderId, getSpecialFolderSelection(type))
return
}
}
when (getSpecialFolderSelection(type)) {
SpecialFolderSelection.AUTOMATIC -> {
val specialFolder = specialFolderSelectionStrategy.selectSpecialFolder(folders, type)
setSpecialFolder(type, specialFolder?.id, SpecialFolderSelection.AUTOMATIC)
}
SpecialFolderSelection.MANUAL -> {
if (folders.none { it.id == getSpecialFolderId(type) }) {
setSpecialFolder(type, null, SpecialFolderSelection.MANUAL)
}
}
}
}
private fun getSpecialFolderSelection(type: FolderType) = when (type) {
FolderType.ARCHIVE -> account.archiveFolderSelection
FolderType.DRAFTS -> account.draftsFolderSelection
FolderType.SENT -> account.sentFolderSelection
FolderType.SPAM -> account.spamFolderSelection
FolderType.TRASH -> account.trashFolderSelection
else -> throw AssertionError("Unsupported: $type")
}
private fun getSpecialFolderId(type: FolderType): Long? = when (type) {
FolderType.ARCHIVE -> account.archiveFolderId
FolderType.DRAFTS -> account.draftsFolderId
FolderType.SENT -> account.sentFolderId
FolderType.SPAM -> account.spamFolderId
FolderType.TRASH -> account.trashFolderId
else -> throw AssertionError("Unsupported: $type")
}
private fun getImportedSpecialFolderServerId(type: FolderType): String? = when (type) {
FolderType.ARCHIVE -> account.importedArchiveFolder
FolderType.DRAFTS -> account.importedDraftsFolder
FolderType.SENT -> account.importedSentFolder
FolderType.SPAM -> account.importedSpamFolder
FolderType.TRASH -> account.importedTrashFolder
else -> throw AssertionError("Unsupported: $type")
}
private fun setSpecialFolder(type: FolderType, folderId: Long?, selection: SpecialFolderSelection) {
if (getSpecialFolderId(type) == folderId) return
when (type) {
FolderType.ARCHIVE -> account.setArchiveFolderId(folderId, selection)
FolderType.DRAFTS -> account.setDraftsFolderId(folderId, selection)
FolderType.SENT -> account.setSentFolderId(folderId, selection)
FolderType.SPAM -> account.setSpamFolderId(folderId, selection)
FolderType.TRASH -> account.setTrashFolderId(folderId, selection)
else -> throw AssertionError("Unsupported: $type")
}
if (folderId != null) {
folderRepository.setDisplayClass(account, folderId, FolderClass.FIRST_CLASS)
folderRepository.setSyncClass(account, folderId, FolderClass.NO_CLASS)
}
}
private fun removeImportedSpecialFoldersData() {
account.importedArchiveFolder = null
account.importedDraftsFolder = null
account.importedSentFolder = null
account.importedSpamFolder = null
account.importedTrashFolder = null
}
private fun saveAccount() {
preferences.saveAccount(account)
}
private fun Account.isPop3() = incomingServerSettings.type == Protocols.POP3
}
|
apache-2.0
|
7b3410c9e10a783f62d4094d27a5eec4
| 40.92029 | 118 | 0.685048 | 5.211712 | false | false | false | false |
Tandrial/Advent_of_Code
|
src/aoc2015/kot/Day02.kt
|
1
|
557
|
package aoc2015.kot
import java.io.File
object Day02 {
fun solve(input: List<String>, f: (Int, Int, Int) -> Int): Int = input.map {
val (x1, x2, x3) = it.split("x").map(String::toInt).sorted()
f(x1, x2, x3)
}.sum()
}
fun main(args: Array<String>) {
val input = File("./input/2015/Day02_input.txt").readLines().filter(String::isNotEmpty)
println("Part One = ${Day02.solve(input) { x1, x2, x3 -> 2 * (x1 * x2 + x1 * x3 + x2 * x3) + x1 * x2 }}")
println("Part Two = ${Day02.solve(input) { x1, x2, x3 -> 2 * (x1 + x2) + x1 * x2 * x3 }}")
}
|
mit
|
28b0325ed80ff5275828233d20b94f66
| 33.8125 | 107 | 0.579892 | 2.453744 | false | false | false | false |
laminr/aeroknow
|
app/src/main/java/biz/eventually/atpl/data/db/LastCall.kt
|
1
|
662
|
package biz.eventually.atpl.data.db
import android.arch.persistence.room.Entity
import android.arch.persistence.room.Ignore
import android.arch.persistence.room.PrimaryKey
import biz.eventually.atpl.data.dao.LastCallDao
import java.util.*
import javax.inject.Inject
/**
* Created by Thibault de Lambilly on 26/08/2017.
*
*/
@Entity(tableName = "last_call")
class LastCall(@PrimaryKey val type: String) {
companion object {
val TYPE_SOURCE = "source"
val TYPE_TOPIC = "topic"
}
var updatedAt: Long = Date().time
@Ignore
constructor(type: String, updatedAt: Long): this(type) {
this.updatedAt = updatedAt
}
}
|
mit
|
aed4e04a67ccfd8e9978eda7587b0c18
| 22.678571 | 60 | 0.705438 | 3.740113 | false | false | false | false |
Rin-Da/UCSY-News
|
app/src/main/java/io/github/rin_da/ucsynews/presentation/login/view/LoginView.kt
|
1
|
2778
|
package io.github.rin_da.ucsynews.presentation.login.view
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import com.pawegio.kandroid.dp
import io.github.rin_da.ucsynews.R
import io.github.rin_da.ucsynews.presentation.base.ui.*
import io.github.rin_da.ucsynews.presentation.login.activity.LoginActivity
import org.jetbrains.anko.*
/**
* Created by user on 12/4/16.
*/
class LoginView(var ankoActivity: LoginActivity) : AnkoComponent<LoginActivity> {
lateinit var error_text: TextView
lateinit var container: ViewGroup
lateinit var progress: ProgressBar
var loading = true
override fun createView(ui: AnkoContext<LoginActivity>): View {
with(ui) {
frameLayout {
container = verticalLayout {
gravity = Gravity.CENTER
visibility = if (loading) {
View.GONE
} else {
View.VISIBLE
}
appCompatImageView {
imageResource = R.drawable.ic_sad
setColorFilter(colorOf(R.color.yellow))
}.lparams(width = dp(intOf(R.integer.login_error_dimens)), height = dp(intOf(R.integer.login_error_dimens))) {
}
error_text = textView {
setRegularFont()
gravity = Gravity.CENTER
setTextColor(colorOf(android.R.color.white))
}.lparams(width = dp(intOf(R.integer.login_error_text_width)), height = wrapContent) {
topMargin = dp(intOf(R.integer.login_error_text_margin))
}
setOnClickListener {
showProgress()
hideContainer()
ankoActivity.login()
}
}
progress = progressBar {
visibility = if (loading) {
View.VISIBLE
} else {
View.GONE
}
}.lparams(width = wrapContent, height = wrapContent) {
gravity = Gravity.CENTER
}
}
}
return ui.view
}
fun setText(string: String) {
error_text.text = string
loading = false
hideProgress()
showContainer()
}
fun showContainer() {
container.show()
}
fun hideContainer() {
container.hide()
}
fun showProgress() {
progress.show()
}
fun hideProgress() {
progress.hide()
}
}
|
mit
|
7021a1fd17f533a9fc21b8682ffdf65d
| 29.195652 | 130 | 0.518719 | 5.144444 | false | false | false | false |
Hexworks/zircon
|
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/graphics/StyleSet.kt
|
1
|
3395
|
package org.hexworks.zircon.api.graphics
import org.hexworks.zircon.api.behavior.Cacheable
import org.hexworks.zircon.api.behavior.Copiable
import org.hexworks.zircon.api.builder.graphics.StyleSetBuilder
import org.hexworks.zircon.api.color.TileColor
import org.hexworks.zircon.api.modifier.Modifier
import org.hexworks.zircon.internal.graphics.DefaultStyleSet
import kotlin.jvm.JvmStatic
/**
* Represents style information which is handled by Zircon like
* - background color
* - foreground color and
* - modifiers
* and a set of useful operations on them.
*/
@Suppress("JVM_STATIC_IN_INTERFACE_1_6")
interface StyleSet : Cacheable, Copiable<StyleSet> {
val foregroundColor: TileColor
val backgroundColor: TileColor
val modifiers: Set<Modifier>
/**
* Creates a copy of this [StyleSet] with the given foreground color.
*/
fun withForegroundColor(foregroundColor: TileColor): StyleSet
/**
* Creates a copy of this [StyleSet] with the given background color.
*/
fun withBackgroundColor(backgroundColor: TileColor): StyleSet
/**
* Creates a copy of this [StyleSet] with the given modifiers.
*/
fun withModifiers(modifiers: Set<Modifier>): StyleSet
/**
* Creates a copy of this [StyleSet] with the given modifiers.
*/
fun withModifiers(vararg modifiers: Modifier): StyleSet =
withModifiers(modifiers.toSet())
/**
* Creates a copy of this [StyleSet] with the given modifiers added.
*/
fun withAddedModifiers(modifiers: Set<Modifier>): StyleSet
/**
* Creates a copy of this [StyleSet] with the given modifiers added.
*/
fun withAddedModifiers(vararg modifiers: Modifier): StyleSet =
withAddedModifiers(modifiers.toSet())
/**
* Creates a copy of this [StyleSet] with the given modifiers removed.
*/
fun withRemovedModifiers(modifiers: Set<Modifier>): StyleSet
/**
* Creates a copy of this [StyleSet] with the given modifiers removed.
*/
fun withRemovedModifiers(vararg modifiers: Modifier): StyleSet =
withRemovedModifiers(modifiers.toSet())
/**
* Creates a copy of this [StyleSet] with no modifiers.
*/
fun withNoModifiers(): StyleSet
companion object {
/**
* Shorthand for the default style which is:
* - default foreground color (white)
* - default background color (black)
* - no modifiers
*/
@JvmStatic
fun defaultStyle() = DEFAULT_STYLE
/**
* Shorthand for the empty style which has:
* - transparent foreground
* - and transparent background
* - and no modifiers.
*/
@JvmStatic
fun empty() = EMPTY
/**
* Creates a new [StyleSetBuilder] for creating [org.hexworks.zircon.api.graphics.StyleSet]s.
*/
@JvmStatic
fun newBuilder() = StyleSetBuilder.newBuilder()
private val DEFAULT_STYLE = DefaultStyleSet(
foregroundColor = TileColor.defaultForegroundColor(),
backgroundColor = TileColor.defaultBackgroundColor(),
modifiers = setOf()
)
private val EMPTY = DefaultStyleSet(
foregroundColor = TileColor.transparent(),
backgroundColor = TileColor.transparent(),
modifiers = setOf()
)
}
}
|
apache-2.0
|
c3f27ebb70a800c17508660f02482d6b
| 29.3125 | 101 | 0.656554 | 4.891931 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/test/java/org/wordpress/android/ui/jetpack/scan/history/ScanHistoryListViewModelTest.kt
|
1
|
10465
|
package org.wordpress.android.ui.jetpack.scan.history
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.InternalCoroutinesApi
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyBoolean
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.TEST_DISPATCHER
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.scan.threat.ThreatModel
import org.wordpress.android.fluxc.model.scan.threat.ThreatModel.GenericThreatModel
import org.wordpress.android.fluxc.model.scan.threat.ThreatModel.ThreatStatus
import org.wordpress.android.test
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.ThreatDateItemState
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.ThreatItemLoadingSkeletonState
import org.wordpress.android.ui.jetpack.scan.ScanListItemState.ThreatItemState
import org.wordpress.android.ui.jetpack.scan.ScanNavigationEvents.ShowThreatDetails
import org.wordpress.android.ui.jetpack.scan.ThreatTestData.genericThreatModel
import org.wordpress.android.ui.jetpack.scan.builders.ThreatItemBuilder
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryListViewModel.ScanHistoryUiState.ContentUiState
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryListViewModel.ScanHistoryUiState.EmptyUiState.EmptyHistory
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryViewModel.ScanHistoryTabType
import org.wordpress.android.ui.jetpack.scan.history.ScanHistoryViewModel.ScanHistoryTabType.ALL
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.analytics.ScanTracker
import org.wordpress.android.util.extensions.toFormattedDateString
import java.util.Calendar
private const val ON_ITEM_CLICKED_PARAM_POSITION = 1
@InternalCoroutinesApi
@RunWith(MockitoJUnitRunner::class)
class ScanHistoryListViewModelTest {
@Rule
@JvmField val rule = InstantTaskExecutorRule()
@Mock private lateinit var scanThreatItemBuilder: ThreatItemBuilder
@Mock private lateinit var scanHistoryViewModel: ScanHistoryViewModel
@Mock private lateinit var scanTracker: ScanTracker
private val captor = argumentCaptor<ThreatModel>()
private lateinit var viewModel: ScanHistoryListViewModel
private val site: SiteModel = SiteModel()
@Before
fun setUp() = test {
viewModel = ScanHistoryListViewModel(
scanThreatItemBuilder,
scanTracker,
TEST_DISPATCHER
)
val threats = listOf(
GenericThreatModel(genericThreatModel.baseThreatModel.copy(status = ThreatStatus.FIXED)),
GenericThreatModel(genericThreatModel.baseThreatModel.copy(status = ThreatStatus.UNKNOWN)),
GenericThreatModel(genericThreatModel.baseThreatModel.copy(status = ThreatStatus.FIXED)),
GenericThreatModel(genericThreatModel.baseThreatModel.copy(status = ThreatStatus.IGNORED)),
GenericThreatModel(genericThreatModel.baseThreatModel.copy(status = ThreatStatus.FIXED)),
GenericThreatModel(genericThreatModel.baseThreatModel.copy(status = ThreatStatus.CURRENT))
)
whenever(scanHistoryViewModel.threats).thenReturn(MutableLiveData(threats))
whenever(scanThreatItemBuilder.buildThreatItem(anyOrNull(), anyOrNull(), anyBoolean())).thenAnswer {
ThreatItemState(1L, true, mock(), mock(), mock(), 0, 0, 0) {
it.getArgument<(Long) -> Unit>(ON_ITEM_CLICKED_PARAM_POSITION)(1L)
}
}
}
@Test
fun `Loading skeletons shown, when the user opens the screen`() {
whenever(scanHistoryViewModel.threats).thenReturn(MutableLiveData())
viewModel.start(ALL, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
assertThat(viewModel.uiState.value).isInstanceOf(ContentUiState::class.java)
assertThat((viewModel.uiState.value as ContentUiState).items).allMatch { it is ThreatItemLoadingSkeletonState }
}
@Test
fun `Threat ui state items shown, when the data is available`() {
viewModel.start(ALL, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
assertThat(viewModel.uiState.value).isInstanceOf(ContentUiState::class.java)
assertThat((viewModel.uiState.value as ContentUiState).items).allMatch {
it is ThreatDateItemState || it is ThreatItemState
}
}
@Test
fun `Threat date is shown as first item, when data is available`() {
viewModel.start(ALL, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
assertThat(viewModel.uiState.value).isInstanceOf(ContentUiState::class.java)
assertThat((viewModel.uiState.value as ContentUiState).items.first())
.isInstanceOf(ThreatDateItemState::class.java)
}
@Test
fun `Threat date is shown again, when the date is different`() {
// assign
val calendar = Calendar.getInstance()
val threats = listOf(
GenericThreatModel(
genericThreatModel.baseThreatModel.copy(
firstDetected = calendar.time,
status = ThreatStatus.FIXED
)
),
GenericThreatModel(
genericThreatModel.baseThreatModel.copy(
firstDetected = calendar.apply {
add(Calendar.DAY_OF_YEAR, 1)
}.time,
status = ThreatStatus.FIXED
)
),
GenericThreatModel(
genericThreatModel.baseThreatModel.copy(
firstDetected = calendar.time,
status = ThreatStatus.FIXED
)
),
GenericThreatModel(
genericThreatModel.baseThreatModel.copy(
firstDetected = calendar.apply {
add(Calendar.DAY_OF_YEAR, 1)
}.time,
status = ThreatStatus.FIXED
)
),
GenericThreatModel(
genericThreatModel.baseThreatModel.copy(
firstDetected = calendar.apply {
add(Calendar.DAY_OF_YEAR, 1)
}.time,
status = ThreatStatus.FIXED
)
)
)
whenever(scanHistoryViewModel.threats).thenReturn(MutableLiveData(threats))
whenever(scanThreatItemBuilder.buildThreatItem(anyOrNull(), anyOrNull(), anyBoolean())).thenAnswer {
val threat = it.arguments[0] as GenericThreatModel
val date = threat.baseThreatModel.firstDetected.toFormattedDateString()
ThreatItemState(1L, true, UiStringText(date), mock(), mock(), 0, 0, 0) {
it.getArgument<(Long) -> Unit>(ON_ITEM_CLICKED_PARAM_POSITION)(1L)
}
}
// act
viewModel.start(ALL, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
// asset
assertThat(viewModel.uiState.value).isInstanceOf(ContentUiState::class.java)
val dateItemStates = (viewModel.uiState.value as ContentUiState)
.items
.filterIndexed { index, _ ->
index == 0 || index == 2 || index == 5 || index == 7
}
assertThat(dateItemStates)
.allMatch { it is ThreatDateItemState }
}
@Test
fun `Only fixed threats are shown, when fixed tab is selected`() {
viewModel.start(ScanHistoryTabType.FIXED, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
verify(scanThreatItemBuilder, times(3)).buildThreatItem(captor.capture(), anyOrNull(), anyBoolean())
assertThat(captor.allValues).allMatch { it.baseThreatModel.status == ThreatStatus.FIXED }
}
@Test
fun `Only ignored threats are shown, when ignore tab is selected`() {
viewModel.start(ScanHistoryTabType.IGNORED, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
verify(scanThreatItemBuilder, times(1)).buildThreatItem(captor.capture(), anyOrNull(), anyBoolean())
assertThat(captor.allValues).allMatch { it.baseThreatModel.status == ThreatStatus.IGNORED }
}
@Test
fun `Only fixed and ignored threats are shown, when all tab is selected`() {
viewModel.start(ALL, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
verify(scanThreatItemBuilder, times(4)).buildThreatItem(captor.capture(), anyOrNull(), anyBoolean())
assertThat(captor.allValues).allMatch {
it.baseThreatModel.status == ThreatStatus.FIXED || it.baseThreatModel.status == ThreatStatus.IGNORED
}
}
@Test
fun `Empty screen shown, when history is empty`() {
whenever(scanHistoryViewModel.threats).thenReturn(MutableLiveData(listOf()))
viewModel.start(ALL, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
assertThat(viewModel.uiState.value).isInstanceOf(EmptyHistory::class.java)
}
@Test
fun `Threat detail screen opened, when the user clicks on threat list item`() {
viewModel.start(ALL, site, scanHistoryViewModel)
viewModel.uiState.observeForever(mock())
viewModel.navigation.observeForever(mock())
// first item is date header
((viewModel.uiState.value!! as ContentUiState).items[1] as ThreatItemState).onClick.invoke()
assertThat(viewModel.navigation.value!!.peekContent()).isInstanceOf(ShowThreatDetails::class.java)
}
}
|
gpl-2.0
|
2ffa6330a0ed9a8c8c95e1f86d943340
| 44.30303 | 122 | 0.669565 | 5.372177 | false | true | false | false |
android/architecture-components-samples
|
MADSkillsNavigationSample/app/src/main/java/com/android/samples/donuttracker/DonutEntryViewModel.kt
|
1
|
2006
|
/*
* Copyright (C) 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 com.android.samples.donuttracker
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import androidx.lifecycle.viewModelScope
import com.android.samples.donuttracker.storage.DonutDao
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class DonutEntryViewModel(private val donutDao: DonutDao) : ViewModel() {
private var donutLiveData: LiveData<Donut>? = null
fun get(id: Long): LiveData<Donut> {
return donutLiveData ?: liveData {
emit(donutDao.get(id))
}.also {
donutLiveData = it
}
}
fun addData(
id: Long,
name: String,
description: String,
rating: Int,
setupNotification: (Long) -> Unit
) {
val donut = Donut(id, name, description, rating)
CoroutineScope(Dispatchers.Main.immediate).launch {
var actualId = id
if (id > 0) {
update(donut)
} else {
actualId = insert(donut)
}
setupNotification(actualId)
}
}
private suspend fun insert(donut: Donut): Long {
return donutDao.insert(donut)
}
private fun update(donut: Donut) = viewModelScope.launch(Dispatchers.IO) {
donutDao.update(donut)
}
}
|
apache-2.0
|
5096370221efcde77000706aa9c75646
| 28.5 | 78 | 0.665503 | 4.457778 | false | false | false | false |
SimpleMobileTools/Simple-Music-Player
|
app/src/main/kotlin/com/simplemobiletools/musicplayer/fragments/TracksFragment.kt
|
1
|
5198
|
package com.simplemobiletools.musicplayer.fragments
import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import com.google.gson.Gson
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.adapters.MyRecyclerViewAdapter
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.musicplayer.R
import com.simplemobiletools.musicplayer.activities.SimpleActivity
import com.simplemobiletools.musicplayer.activities.TrackActivity
import com.simplemobiletools.musicplayer.adapters.TracksAdapter
import com.simplemobiletools.musicplayer.dialogs.ChangeSortingDialog
import com.simplemobiletools.musicplayer.extensions.*
import com.simplemobiletools.musicplayer.helpers.RESTART_PLAYER
import com.simplemobiletools.musicplayer.helpers.TAB_TRACKS
import com.simplemobiletools.musicplayer.helpers.TRACK
import com.simplemobiletools.musicplayer.models.Album
import com.simplemobiletools.musicplayer.models.Track
import kotlinx.android.synthetic.main.fragment_tracks.view.*
// Artists -> Albums -> Tracks
class TracksFragment(context: Context, attributeSet: AttributeSet) : MyViewPagerFragment(context, attributeSet) {
private var tracksIgnoringSearch = ArrayList<Track>()
override fun setupFragment(activity: BaseSimpleActivity) {
ensureBackgroundThread {
val albums = ArrayList<Album>()
val artists = context.artistDAO.getAll()
artists.forEach { artist ->
albums.addAll(context.albumsDAO.getArtistAlbums(artist.id))
}
var tracks = ArrayList<Track>()
albums.forEach { album ->
tracks.addAll(context.tracksDAO.getTracksFromAlbum(album.id))
}
tracks = tracks.distinctBy { "${it.path}/${it.mediaStoreId}" }.toMutableList() as ArrayList<Track>
val excludedFolders = context.config.excludedFolders
tracks = tracks.filter {
!excludedFolders.contains(it.path.getParentPath())
}.toMutableList() as ArrayList<Track>
Track.sorting = context.config.trackSorting
tracks.sort()
tracksIgnoringSearch = tracks
activity.runOnUiThread {
tracks_placeholder.text = context.getString(R.string.no_items_found)
tracks_placeholder.beVisibleIf(tracks.isEmpty())
val adapter = tracks_list.adapter
if (adapter == null) {
TracksAdapter(activity, tracks, false, tracks_list) {
activity.hideKeyboard()
activity.handleNotificationPermission { granted ->
if (granted) {
activity.resetQueueItems(tracks) {
Intent(activity, TrackActivity::class.java).apply {
putExtra(TRACK, Gson().toJson(it))
putExtra(RESTART_PLAYER, true)
activity.startActivity(this)
}
}
} else {
context.toast(R.string.no_post_notifications_permissions)
}
}
}.apply {
tracks_list.adapter = this
}
if (context.areSystemAnimationsEnabled) {
tracks_list.scheduleLayoutAnimation()
}
} else {
(adapter as TracksAdapter).updateItems(tracks)
}
}
}
}
override fun finishActMode() {
(tracks_list.adapter as? MyRecyclerViewAdapter)?.finishActMode()
}
override fun onSearchQueryChanged(text: String) {
val filtered = tracksIgnoringSearch.filter { it.title.contains(text, true) }.toMutableList() as ArrayList<Track>
(tracks_list.adapter as? TracksAdapter)?.updateItems(filtered, text)
tracks_placeholder.beVisibleIf(filtered.isEmpty())
}
override fun onSearchOpened() {
tracksIgnoringSearch = (tracks_list?.adapter as? TracksAdapter)?.tracks ?: ArrayList()
}
override fun onSearchClosed() {
(tracks_list.adapter as? TracksAdapter)?.updateItems(tracksIgnoringSearch)
tracks_placeholder.beGoneIf(tracksIgnoringSearch.isNotEmpty())
}
override fun onSortOpen(activity: SimpleActivity) {
ChangeSortingDialog(activity, TAB_TRACKS) {
val adapter = tracks_list.adapter as? TracksAdapter ?: return@ChangeSortingDialog
val tracks = adapter.tracks
Track.sorting = activity.config.trackSorting
tracks.sort()
adapter.updateItems(tracks, forceUpdate = true)
}
}
override fun setupColors(textColor: Int, adjustedPrimaryColor: Int) {
tracks_placeholder.setTextColor(textColor)
tracks_fastscroller.updateColors(adjustedPrimaryColor)
}
}
|
gpl-3.0
|
54c63d0be02b66c46673abe4b37f49c3
| 42.680672 | 120 | 0.632743 | 5.512195 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/configuration/MultipleScriptDefinitionsChecker.kt
|
1
|
5535
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.script.configuration
import com.intellij.ide.actions.ShowSettingsUtilImpl
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotificationProvider
import com.intellij.ui.EditorNotificationProvider.*
import com.intellij.ui.EditorNotifications
import com.intellij.ui.HyperlinkLabel
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.StandardIdeScriptDefinition
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.idea.util.isKotlinFileType
import org.jetbrains.kotlin.parsing.KotlinParserDefinition
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.kotlin.scripting.resolve.KtFileScriptSource
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import java.util.function.Function
import javax.swing.JComponent
class MultipleScriptDefinitionsChecker : EditorNotificationProvider {
override fun collectNotificationData(project: Project, file: VirtualFile): Function<in FileEditor, out JComponent?> {
if (!file.isKotlinFileType()) return CONST_NULL
val ktFile = PsiManager.getInstance(project).findFile(file).safeAs<KtFile>()?.takeIf(KtFile::isScript) ?: return CONST_NULL
if (KotlinScriptingSettings.getInstance(project).suppressDefinitionsCheck ||
!ScriptDefinitionsManager.getInstance(project).isReady()) return CONST_NULL
val allApplicableDefinitions = ScriptDefinitionsManager.getInstance(project)
.getAllDefinitions()
.filter {
it.asLegacyOrNull<StandardIdeScriptDefinition>() == null && it.isScript(KtFileScriptSource(ktFile)) &&
KotlinScriptingSettings.getInstance(project).isScriptDefinitionEnabled(it)
}
.toList()
if (allApplicableDefinitions.size < 2 || areDefinitionsForGradleKts(allApplicableDefinitions)) return CONST_NULL
return Function { fileEditor: FileEditor ->
createNotification(fileEditor, project, allApplicableDefinitions)
}
}
private fun areDefinitionsForGradleKts(allApplicableDefinitions: List<ScriptDefinition>): Boolean {
return allApplicableDefinitions.all { definition ->
definition.asLegacyOrNull<KotlinScriptDefinitionFromAnnotatedTemplate>()?.let {
val pattern = it.scriptFilePattern.pattern
return@all pattern.endsWith("\\.gradle\\.kts") || pattern.endsWith("\\.gradle\\.kts$")
}
definition.fileExtension.endsWith("gradle.kts")
}
}
private fun createNotification(fileEditor: FileEditor, project: Project, defs: List<ScriptDefinition>): EditorNotificationPanel =
EditorNotificationPanel(fileEditor).apply {
text = KotlinBundle.message("script.text.multiple.script.definitions.are.applicable.for.this.script", defs.first().name)
createComponentActionLabel(
KotlinBundle.message("script.action.text.show.all")
) { label ->
val list = JBPopupFactory.getInstance().createListPopup(
object : BaseListPopupStep<ScriptDefinition>(null, defs) {
override fun getTextFor(value: ScriptDefinition): String {
@NlsSafe
val text = value.asLegacyOrNull<KotlinScriptDefinitionFromAnnotatedTemplate>()?.let {
it.name + " (${it.scriptFilePattern})"
} ?: value.asLegacyOrNull<StandardIdeScriptDefinition>()?.let {
it.name + " (${KotlinParserDefinition.STD_SCRIPT_EXT})"
} ?: (value.name + " (${value.fileExtension})")
return text
}
}
)
list.showUnderneathOf(label)
}
createComponentActionLabel(KotlinBundle.message("script.action.text.ignore")) {
KotlinScriptingSettings.getInstance(project).suppressDefinitionsCheck = true
EditorNotifications.getInstance(project).updateAllNotifications()
}
createComponentActionLabel(KotlinBundle.message("script.action.text.open.settings")) {
ShowSettingsUtilImpl.showSettingsDialog(project, KotlinScriptingSettingsConfigurable.ID, "")
}
}
private fun EditorNotificationPanel.createComponentActionLabel(@Nls labelText: String, callback: (HyperlinkLabel) -> Unit) {
val label: Ref<HyperlinkLabel> = Ref.create()
label.set(createActionLabel(labelText) {
callback(label.get())
})
}
}
|
apache-2.0
|
09c132245b8b54e668107faad44a0ed8
| 51.216981 | 158 | 0.703704 | 5.447835 | false | false | false | false |
byu-oit/android-byu-suite-v2
|
app/src/main/java/edu/byu/suite/features/myClasses/MyClassesClassDetailActivity.kt
|
2
|
3697
|
package edu.byu.suite.features.myClasses
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import android.widget.FrameLayout
import edu.byu.suite.R
import edu.byu.suite.features.addDrop.model.AddDropBasic
import edu.byu.support.activity.ByuActivity
import edu.byu.support.client.campusLocation.model.BuildingHelper
import edu.byu.support.client.campusLocation.model.BuildingsWrapper
import edu.byu.support.client.campusLocation.service.BuildingClientHelper
import edu.byu.support.client.studentClassScheduleClient.model.Course
import edu.byu.support.retrofit.ByuSuccessCallback
import kotlinx.android.synthetic.main.my_classes_class_detail_activity.*
import retrofit2.Call
import retrofit2.Response
/**
* Created by geogor37 on 1/18/18
*/
class MyClassesClassDetailActivity: ByuActivity() {
companion object {
const val COURSE_EXTRA = "course"
}
private var buildings: List<BuildingsWrapper.BuildingWrapper>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
showProgressDialog()
setContentView(R.layout.my_classes_class_detail_activity)
val selectedCourse = intent.getParcelableExtra<Parcelable>(COURSE_EXTRA)
when (selectedCourse) {
is Course -> {
loadBuildings(selectedCourse)
header.text = getString(R.string.class_detail_header, selectedCourse.course, selectedCourse.section)
courseTitle.text = selectedCourse.courseTitle
instructor.text = selectedCourse.instructor
credits.text = getString(R.string.class_detail_credit_hours, selectedCourse.creditHours)
classSchedule.text = getString(R.string.class_detail_two_string_format, selectedCourse.days, selectedCourse.classPeriod)
classLocation.text = getString(R.string.class_detail_two_string_format, selectedCourse.room, selectedCourse.building)
if (selectedCourse.hasChildClass()) {
childText.visibility = View.VISIBLE
childText.text = selectedCourse.childrenDetailText
}
}
is AddDropBasic -> {
findViewById<FrameLayout>(R.id.frameLayout).visibility = View.GONE
instructor.visibility = View.GONE
classSchedule.visibility = View.GONE
classLocation.visibility = View.GONE
header.text = getString(R.string.class_detail_header_historic, selectedCourse.teachingArea.value, selectedCourse.courseNumber.value, selectedCourse.sectionNumber.value)
courseTitle.text = selectedCourse.courseTitle.value
credits.text = getString(R.string.class_detail_credit_hours_historic, selectedCourse.creditHours.value.toDouble())
grade.visibility = View.VISIBLE
grade.text = getString(R.string.class_detail_grade_historic, selectedCourse.grade.value)
dismissProgressDialog()
}
}
}
private fun loadBuildings(selectedCourse: Course) {
BuildingClientHelper.getBuildings(this, object: ByuSuccessCallback<BuildingsWrapper>(this) {
override fun onSuccess(call: Call<BuildingsWrapper>?, response: Response<BuildingsWrapper>?) {
buildings = response?.body()?.buildingInformationList
setUpMap(selectedCourse)
}
})
}
private fun setUpMap(selectedCourse: Course) {
val courseBuildings = arrayListOf(BuildingHelper.getBuildingWithAcronym(selectedCourse.building, buildings))
for (child in selectedCourse.childClasses.orEmpty()) {
val childBuilding = BuildingHelper.getBuildingWithAcronym(child.building, buildings)
// We only want to add a marker if the child class is in a different building
if (childBuilding != null && !courseBuildings.contains(childBuilding)) {
courseBuildings.add(childBuilding)
}
}
supportFragmentManager.beginTransaction().add(R.id.frameLayout, MyClassesMapFragment.newInstance(courseBuildings)).commit()
}
}
|
apache-2.0
|
4cf38734231449d5fea993e95df275e2
| 42.505882 | 172 | 0.791453 | 4.031625 | false | false | false | false |
iPoli/iPoli-android
|
app/src/main/java/io/ipoli/android/event/calendar/picker/CalendarPickerViewState.kt
|
1
|
3197
|
package io.ipoli.android.event.calendar.picker
import io.ipoli.android.common.AppState
import io.ipoli.android.common.BaseViewStateReducer
import io.ipoli.android.common.DataLoadedAction
import io.ipoli.android.common.redux.Action
import io.ipoli.android.common.redux.BaseViewState
import io.ipoli.android.event.Calendar
import io.ipoli.android.pet.PetAvatar
import io.ipoli.android.player.data.Player
/**
* Created by Venelin Valkov <[email protected]>
* on 03/11/2018.
*/
sealed class CalendarPickerAction : Action {
object Load : CalendarPickerAction()
object SyncSelectedCalendars : CalendarPickerAction()
data class ToggleSelectedCalendar(
val isSelected: Boolean,
val id: String,
val name: String
) : CalendarPickerAction() {
override fun toMap() = mapOf("isSelected" to isSelected, "id" to id, "name" to name)
}
}
object CalendarPickerReducer :
BaseViewStateReducer<CalendarPickerViewState>() {
override val stateKey = key<CalendarPickerViewState>()
override fun reduce(
state: AppState,
subState: CalendarPickerViewState,
action: Action
) =
when (action) {
is DataLoadedAction.CalendarsChanged -> {
val newState = subState.copy(
calendars = action.calendars.filter { it.isVisible }
)
state.dataState.player?.let {
newState.copy(
type = CalendarPickerViewState.StateType.CALENDAR_DATA_CHANGED,
petAvatar = it.pet.avatar,
syncCalendars = it.preferences.syncCalendars
)
} ?: newState.copy(type = CalendarPickerViewState.StateType.LOADING)
}
is CalendarPickerAction.ToggleSelectedCalendar -> {
val syncCalendar = Player.Preferences.SyncCalendar(action.id, action.name)
val newSyncCalendars = if (subState.syncCalendars.contains(syncCalendar)) {
subState.syncCalendars - syncCalendar
} else {
subState.syncCalendars + syncCalendar
}
subState.copy(
type = CalendarPickerViewState.StateType.CALENDAR_DATA_CHANGED,
syncCalendars = newSyncCalendars
)
}
is CalendarPickerAction.SyncSelectedCalendars -> {
subState.copy(
type = CalendarPickerViewState.StateType.CALENDARS_SELECTED
)
}
else ->
subState
}
override fun defaultState() =
CalendarPickerViewState(
type = CalendarPickerViewState.StateType.LOADING,
petAvatar = PetAvatar.BEAR,
calendars = emptyList(),
syncCalendars = emptySet()
)
}
data class CalendarPickerViewState(
val type: StateType,
val petAvatar: PetAvatar,
val calendars: List<Calendar>,
val syncCalendars: Set<Player.Preferences.SyncCalendar>
) : BaseViewState() {
enum class StateType { LOADING, CALENDAR_DATA_CHANGED, CALENDARS_SELECTED}
}
|
gpl-3.0
|
d2a53f1780a4d3a5c7249614842d7537
| 32.652632 | 92 | 0.619018 | 5.293046 | false | false | false | false |
GunoH/intellij-community
|
plugins/textmate/src/org/jetbrains/plugins/textmate/actions/InstallVSCodePluginAction.kt
|
7
|
6450
|
package org.jetbrains.plugins.textmate.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.progress.PerformInBackgroundOption
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.IconButton
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.platform.templates.github.DownloadUtil
import com.intellij.ui.DoubleClickListener
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SortedListModel
import com.intellij.ui.components.JBList
import com.intellij.ui.speedSearch.ListWithFilter
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.ZipUtil
import com.intellij.util.ui.JBUI
import org.jetbrains.plugins.textmate.TextMateService
import org.jetbrains.plugins.textmate.configuration.BundleConfigBean
import org.jetbrains.plugins.textmate.configuration.TextMateSettings
import org.jetbrains.plugins.textmate.plist.JsonPlistReader
import java.awt.Component
import java.awt.Dimension
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.io.BufferedReader
import java.io.File
@Suppress("HardCodedStringLiteral")
class InstallVSCodePluginAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val model = SortedListModel<Plugin>(Comparator.comparing(Plugin::toString))
val list = JBList<Plugin>(model)
updateList(list, model)
val scroll = ScrollPaneFactory.createScrollPane(list)
scroll.border = JBUI.Borders.empty()
val pane = ListWithFilter.wrap(list, scroll, Plugin::toString)
val builder = JBPopupFactory
.getInstance()
.createComponentPopupBuilder(pane, list)
.setMayBeParent(true)
.setRequestFocus(true)
.setFocusable(true)
.setFocusOwners(arrayOf<Component>(list))
.setLocateWithinScreenBounds(true)
.setCancelOnOtherWindowOpen(true)
.setMovable(true)
.setResizable(true)
.setTitle("Install VSCode plugin")
.setCancelOnWindowDeactivation(false)
.setCancelOnClickOutside(true)
.setDimensionServiceKey(project, "install.vscode.plugin", true)
.setMinSize(Dimension(JBUI.scale(350), JBUI.scale(300)))
.setCancelButton(IconButton("Close", AllIcons.Actions.Close, AllIcons.Actions.CloseHovered))
val popup = builder.createPopup()
list.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent?) {
if (list.selectedValue == null) return
if (e?.keyCode == KeyEvent.VK_ENTER) {
e.consume()
install(project, list.selectedValue, popup)
}
}
})
object : DoubleClickListener() {
override fun onDoubleClick(event: MouseEvent): Boolean {
if (list.selectedValue == null) return true
install(project, list.selectedValue, popup)
return true
}
}.installOn(list)
popup.showCenteredInCurrentWindow(project)
}
private fun updateList(list: JBList<Plugin>, model: SortedListModel<Plugin>) {
list.setPaintBusy(true)
model.clear()
ApplicationManager.getApplication().executeOnPooledThread {
val plugins = fetchPlugins()
ApplicationManager.getApplication().invokeLater {
model.addAll(plugins)
list.setPaintBusy(false)
}
}
}
private fun fetchPlugins(): List<Plugin> {
var plugins = emptyList<Plugin>()
HttpRequests.request("https://vscode.blob.core.windows.net/gallery/index").connect { request ->
plugins = loadPlugins(request.reader)
}
return plugins
}
private fun loadPlugins(reader: BufferedReader): List<Plugin> {
val plugins = mutableListOf<Plugin>()
val response = JsonPlistReader.createJsonReader().readValue(reader, Object::class.java)
val results = (response as? Map<*, *>)?.get("results")
for (result in (results as? List<*> ?: emptyList<Any>())) {
val extensions = (result as? Map<*, *>)?.get("extensions")
for (extension in (extensions as? List<*> ?: emptyList<Any>())) {
val extensionName = (extension as? Map<*, *>)?.get("extensionName")
if (extensionName is String) {
val publisher = (extension as? Map<*, *>)?.get("publisher")
val publisherName = (publisher as? Map<*, *>)?.get("publisherName")
if (publisherName is String) {
val versions = (extension as? Map<*, *>)?.get("versions")
val version = (versions as? List<*>)?.first()
val url = (version as? Map<*, *>)?.get("assetUri")
if (url is String) {
plugins.add(Plugin(extensionName, publisherName, url))
}
}
}
}
}
return plugins
}
private fun install(project: Project, selectedValue: Plugin, popup: JBPopup) {
popup.closeOk(null)
ProgressManager.getInstance().run(object : Task.Backgroundable(project, "Installing $selectedValue", false, PerformInBackgroundOption.ALWAYS_BACKGROUND) {
override fun run(indicator: ProgressIndicator) {
indicator.text = "Downloading $selectedValue..."
val temp = File.createTempFile("vscode", "")
DownloadUtil.downloadAtomically(indicator, "${selectedValue.url}/Microsoft.VisualStudio.Services.VSIXPackage", temp)
indicator.text = "Unzipping $selectedValue..."
val extensionDir = PathManager.getConfigDir().resolve("vscode").resolve(selectedValue.name).toFile()
ZipUtil.extract(temp, extensionDir, null)
indicator.text = "Applying $selectedValue"
val state = TextMateSettings.getInstance().state ?: TextMateSettings.TextMateSettingsState()
state.bundles.add(BundleConfigBean(selectedValue.toString(), File(extensionDir, "extension").path, true))
TextMateService.getInstance().reloadEnabledBundles()
}
})
}
}
data class Plugin(val name:String, val publisher:String, val url:String) {
override fun toString(): String {
return "$publisher/$name"
}
}
|
apache-2.0
|
f277969c1f5f948ea8c65443e72f733d
| 39.062112 | 158 | 0.715969 | 4.460581 | false | false | false | false |
ktorio/ktor
|
ktor-io/posix/src/io/ktor/utils/io/bits/MemoryPrimitivesNative.kt
|
1
|
9352
|
@file:Suppress("NOTHING_TO_INLINE", "ConstantConditionIf")
package io.ktor.utils.io.bits
import kotlinx.cinterop.*
import kotlin.experimental.*
public actual inline fun Memory.loadShortAt(offset: Int): Short {
assertIndex(offset, 2)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<ShortVar>().pointed.value.toBigEndian()
else loadShortSlowAt(pointer)
}
public actual inline fun Memory.loadShortAt(offset: Long): Short {
assertIndex(offset, 2)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<ShortVar>().pointed.value.toBigEndian()
else loadShortSlowAt(pointer)
}
public actual inline fun Memory.loadIntAt(offset: Int): Int {
assertIndex(offset, 4)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<IntVar>().pointed.value.toBigEndian()
else loadIntSlowAt(pointer)
}
public actual inline fun Memory.loadIntAt(offset: Long): Int {
assertIndex(offset, 4)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<IntVar>().pointed.value.toBigEndian()
else loadIntSlowAt(pointer)
}
public actual inline fun Memory.loadLongAt(offset: Int): Long {
assertIndex(offset, 8)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<LongVar>().pointed.value.toBigEndian()
else loadLongSlowAt(pointer)
}
public actual inline fun Memory.loadLongAt(offset: Long): Long {
assertIndex(offset, 8)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<LongVar>().pointed.value.toBigEndian()
else loadLongSlowAt(pointer)
}
public actual inline fun Memory.loadFloatAt(offset: Int): Float {
assertIndex(offset, 4)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<FloatVar>().pointed.value.toBigEndian()
else loadFloatSlowAt(pointer)
}
public actual inline fun Memory.loadFloatAt(offset: Long): Float {
assertIndex(offset, 4)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<FloatVar>().pointed.value.toBigEndian()
else loadFloatSlowAt(pointer)
}
public actual inline fun Memory.loadDoubleAt(offset: Int): Double {
assertIndex(offset, 8)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<DoubleVar>().pointed.value.toBigEndian()
else loadDoubleSlowAt(pointer)
}
public actual inline fun Memory.loadDoubleAt(offset: Long): Double {
assertIndex(offset, 8)
val pointer = pointer.plus(offset)!!
return if (Platform.canAccessUnaligned) pointer.reinterpret<DoubleVar>().pointed.value.toBigEndian()
else loadDoubleSlowAt(pointer)
}
/**
* Write regular signed 32bit integer in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeIntAt(offset: Int, value: Int) {
assertIndex(offset, 4)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<IntVar>().pointed.value = value.toBigEndian()
} else {
storeIntSlowAt(pointer, value)
}
}
/**
* Write regular signed 32bit integer in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeIntAt(offset: Long, value: Int) {
assertIndex(offset, 4)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<IntVar>().pointed.value = value.toBigEndian()
} else {
storeIntSlowAt(pointer, value)
}
}
/**
* Write short signed 16bit integer in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeShortAt(offset: Int, value: Short) {
assertIndex(offset, 2)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<ShortVar>().pointed.value = value.toBigEndian()
} else {
storeShortSlowAt(pointer, value)
}
}
/**
* Write short signed 16bit integer in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeShortAt(offset: Long, value: Short) {
assertIndex(offset, 2)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<ShortVar>().pointed.value = value.toBigEndian()
} else {
storeShortSlowAt(pointer, value)
}
}
/**
* Write short signed 64bit integer in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeLongAt(offset: Int, value: Long) {
assertIndex(offset, 8)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<LongVar>().pointed.value = value.toBigEndian()
} else {
storeLongSlowAt(pointer, value)
}
}
/**
* Write short signed 64bit integer in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeLongAt(offset: Long, value: Long) {
assertIndex(offset, 8)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<LongVar>().pointed.value = value.toBigEndian()
} else {
storeLongSlowAt(pointer, value)
}
}
/**
* Write short signed 32bit floating point number in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeFloatAt(offset: Int, value: Float) {
assertIndex(offset, 4)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<FloatVar>().pointed.value = value.toBigEndian()
} else {
storeFloatSlowAt(pointer, value)
}
}
/**
* Write short signed 32bit floating point number in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeFloatAt(offset: Long, value: Float) {
assertIndex(offset, 4)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<FloatVar>().pointed.value = value.toBigEndian()
} else {
storeFloatSlowAt(pointer, value)
}
}
/**
* Write short signed 64bit floating point number in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeDoubleAt(offset: Int, value: Double) {
assertIndex(offset, 8)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<DoubleVar>().pointed.value = value.toBigEndian()
} else {
storeDoubleSlowAt(pointer, value)
}
}
/**
* Write short signed 64bit floating point number in the network byte order (Big Endian)
*/
public actual inline fun Memory.storeDoubleAt(offset: Long, value: Double) {
assertIndex(offset, 8)
val pointer = pointer.plus(offset)!!
if (Platform.canAccessUnaligned) {
pointer.reinterpret<DoubleVar>().pointed.value = value.toBigEndian()
} else {
storeDoubleSlowAt(pointer, value)
}
}
@PublishedApi
internal inline fun storeShortSlowAt(pointer: CPointer<ByteVar>, value: Short) {
pointer[0] = (value.toInt() ushr 8).toByte()
pointer[1] = (value and 0xff).toByte()
}
@PublishedApi
internal inline fun storeIntSlowAt(pointer: CPointer<ByteVar>, value: Int) {
pointer[0] = (value ushr 24).toByte()
pointer[1] = (value ushr 16).toByte()
pointer[2] = (value ushr 8).toByte()
pointer[3] = (value and 0xff).toByte()
}
@PublishedApi
internal inline fun storeLongSlowAt(pointer: CPointer<ByteVar>, value: Long) {
pointer[0] = (value ushr 56).toByte()
pointer[1] = (value ushr 48).toByte()
pointer[2] = (value ushr 40).toByte()
pointer[3] = (value ushr 32).toByte()
pointer[4] = (value ushr 24).toByte()
pointer[5] = (value ushr 16).toByte()
pointer[6] = (value ushr 8).toByte()
pointer[7] = (value and 0xff).toByte()
}
@PublishedApi
internal inline fun storeFloatSlowAt(pointer: CPointer<ByteVar>, value: Float) {
storeIntSlowAt(pointer, value.toRawBits())
}
@PublishedApi
internal inline fun storeDoubleSlowAt(pointer: CPointer<ByteVar>, value: Double) {
storeLongSlowAt(pointer, value.toRawBits())
}
@PublishedApi
internal inline fun loadShortSlowAt(pointer: CPointer<ByteVar>): Short {
return ((pointer[0].toInt() shl 8) or (pointer[1].toInt() and 0xff)).toShort()
}
@PublishedApi
internal inline fun loadIntSlowAt(pointer: CPointer<ByteVar>): Int {
return (
(pointer[0].toInt() shl 24) or
(pointer[1].toInt() shl 16) or
(pointer[2].toInt() shl 18) or
(pointer[3].toInt() and 0xff)
)
}
@PublishedApi
internal inline fun loadLongSlowAt(pointer: CPointer<ByteVar>): Long {
return (
(pointer[0].toLong() shl 56) or
(pointer[1].toLong() shl 48) or
(pointer[2].toLong() shl 40) or
(pointer[3].toLong() shl 32) or
(pointer[4].toLong() shl 24) or
(pointer[5].toLong() shl 16) or
(pointer[6].toLong() shl 8) or
(pointer[7].toLong() and 0xffL)
)
}
@PublishedApi
internal inline fun loadFloatSlowAt(pointer: CPointer<ByteVar>): Float {
return Float.fromBits(loadIntSlowAt(pointer))
}
@PublishedApi
internal inline fun loadDoubleSlowAt(pointer: CPointer<ByteVar>): Double {
return Double.fromBits(loadLongSlowAt(pointer))
}
|
apache-2.0
|
6ade59f02bbc43f297d9cb86580fa764
| 30.069767 | 104 | 0.695573 | 4.06079 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/util/MangaExtensions.kt
|
2
|
2761
|
package eu.kanade.tachiyomi.util
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.model.SManga
import java.util.Date
fun Manga.isLocal() = source == LocalSource.ID
/**
* Call before updating [Manga.thumbnail_url] to ensure old cover can be cleared from cache
*/
fun Manga.prepUpdateCover(coverCache: CoverCache, remoteManga: SManga, refreshSameUrl: Boolean) {
// Never refresh covers if the new url is null, as the current url has possibly become invalid
val newUrl = remoteManga.thumbnail_url ?: return
// Never refresh covers if the url is empty to avoid "losing" existing covers
if (newUrl.isEmpty()) return
if (!refreshSameUrl && thumbnail_url == newUrl) return
when {
isLocal() -> {
cover_last_modified = Date().time
}
hasCustomCover(coverCache) -> {
coverCache.deleteFromCache(this, false)
}
else -> {
cover_last_modified = Date().time
coverCache.deleteFromCache(this, false)
}
}
}
fun Manga.hasCustomCover(coverCache: CoverCache): Boolean {
return coverCache.getCustomCoverFile(this).exists()
}
fun Manga.removeCovers(coverCache: CoverCache) {
if (isLocal()) return
cover_last_modified = Date().time
coverCache.deleteFromCache(this, true)
}
fun Manga.updateCoverLastModified(db: DatabaseHelper) {
cover_last_modified = Date().time
db.updateMangaCoverLastModified(this).executeAsBlocking()
}
fun Manga.shouldDownloadNewChapters(db: DatabaseHelper, prefs: PreferencesHelper): Boolean {
if (!favorite) return false
// Boolean to determine if user wants to automatically download new chapters.
val downloadNew = prefs.downloadNew().get()
if (!downloadNew) return false
val categoriesToDownload = prefs.downloadNewCategories().get().map(String::toInt)
val categoriesToExclude = prefs.downloadNewCategoriesExclude().get().map(String::toInt)
// Default: download from all categories
if (categoriesToDownload.isEmpty() && categoriesToExclude.isEmpty()) return true
// Get all categories, else default category (0)
val categoriesForManga =
db.getCategoriesForManga(this).executeAsBlocking()
.mapNotNull { it.id }
.takeUnless { it.isEmpty() } ?: listOf(0)
// In excluded category
if (categoriesForManga.intersect(categoriesToExclude).isNotEmpty()) return false
// In included category
return categoriesForManga.intersect(categoriesToDownload).isNotEmpty()
}
|
apache-2.0
|
bbbd60a3832990f505de8e6a1febc105
| 33.949367 | 98 | 0.719305 | 4.474878 | false | false | false | false |
google/android-fhir
|
engine/src/main/java/com/google/android/fhir/db/impl/DbTypeConverters.kt
|
1
|
3268
|
/*
* Copyright 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.google.android.fhir.db.impl
import androidx.room.TypeConverter
import ca.uhn.fhir.model.api.TemporalPrecisionEnum
import com.google.android.fhir.db.impl.entities.LocalChangeEntity
import java.math.BigDecimal
import java.time.Instant
import java.util.Calendar
import org.hl7.fhir.r4.model.ResourceType
/**
* Type converters for Room to persist ResourceType as a string. see:
* https://developer.android.com/training/data-storage/room/referencing-data
*/
internal object DbTypeConverters {
private val resourceTypeLookup = ResourceType.values().associateBy { it.name }
/**
* Converts a [ResourceType] into a String to be persisted in the database. This allows us to save
* [ResourceType] into the database while keeping it as the real type in entities.
*/
@JvmStatic @TypeConverter fun typeToString(resourceType: ResourceType) = resourceType.name
/** Converts a String into a [ResourceType]. Called when a query returns a [ResourceType]. */
@JvmStatic
@TypeConverter
fun stringToResourceType(data: String) =
resourceTypeLookup[data] ?: throw IllegalArgumentException("invalid resource type: $data")
// Since we're narrowing BigDecimal to double, search/sort precision is limited.
// Search/sort for values that are close enough to resolve to the same double will be undefined.
@JvmStatic @TypeConverter fun bigDecimalToDouble(value: BigDecimal): Double = value.toDouble()
@JvmStatic @TypeConverter fun doubleToBigDecimal(value: Double): BigDecimal = value.toBigDecimal()
@JvmStatic
@TypeConverter
fun temporalPrecisionToInt(temporalPrecision: TemporalPrecisionEnum): Int =
temporalPrecision.calendarConstant
@JvmStatic
@TypeConverter
fun intToTemporalPrecision(intTp: Int): TemporalPrecisionEnum {
return when (intTp) {
Calendar.YEAR -> TemporalPrecisionEnum.YEAR
Calendar.MONTH -> TemporalPrecisionEnum.MONTH
Calendar.DATE -> TemporalPrecisionEnum.DAY
Calendar.MINUTE -> TemporalPrecisionEnum.MINUTE
Calendar.SECOND -> TemporalPrecisionEnum.SECOND
Calendar.MILLISECOND -> TemporalPrecisionEnum.MILLI
else -> throw IllegalArgumentException("Unknown TemporalPrecision int $intTp")
}
}
@JvmStatic
@TypeConverter
fun localChangeTypeToInt(updateType: LocalChangeEntity.Type): Int = updateType.value
@JvmStatic
@TypeConverter
fun intToLocalChangeType(value: Int): LocalChangeEntity.Type = LocalChangeEntity.Type.from(value)
@JvmStatic @TypeConverter fun instantToLong(value: Instant?): Long? = value?.toEpochMilli()
@JvmStatic
@TypeConverter
fun longToInstant(value: Long?): Instant? = value?.let { Instant.ofEpochMilli(it) }
}
|
apache-2.0
|
92317d60fb55317cb873e8166844834b
| 37.904762 | 100 | 0.763158 | 4.628895 | false | false | false | false |
CodeNinjaResearch/tailCallFibonacci
|
src/test/java/src/TailRecTest.kt
|
1
|
750
|
package src
import org.junit.Test
/**
* Created by vicboma on 01/11/15.
*/
class TailRecTest{
val expected = arrayOf<Long>(0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170)
@Test
fun testMethod() {
val fibonacci = TailRec()
val size = expected.size-1
for(sequence in 0..size) {
val result = fibonacci.method(sequence.toLong())
kotlin.test.assertTrue {
"Fail resutl"
result == expected.get(sequence)
}
}
}
}
|
mit
|
91d36c97899257a6b097215fb685d1ab
| 30.291667 | 304 | 0.642667 | 2.941176 | false | true | false | false |
mdanielwork/intellij-community
|
platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/utils.kt
|
1
|
2964
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.images.sync
import java.io.File
import java.util.concurrent.TimeUnit
import java.util.function.Consumer
internal lateinit var logger: Consumer<String>
internal fun log(msg: String) = logger.accept(msg)
internal fun String.splitWithSpace(): List<String> = this.splitNotBlank(" ")
internal fun String.splitNotBlank(delimiter: String): List<String> = this.split(delimiter).filter { it.isNotBlank() }
internal fun String.splitWithTab(): List<String> = this.split("\t".toRegex())
internal fun execute(workingDir: File?, vararg command: String, silent: Boolean = false): String {
val errOutputFile = File.createTempFile("errOutput", "txt")
val processCall = {
val process = ProcessBuilder(*command.filter { it.isNotBlank() }.toTypedArray())
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(errOutputFile)
.start()
val output = process.inputStream.bufferedReader().use { it.readText() }
process.waitFor(1, TimeUnit.MINUTES)
val error = errOutputFile.readText().trim()
if (process.exitValue() != 0) {
error("Command ${command.joinToString(" ")} failed in ${workingDir?.absolutePath} with ${process.exitValue()} : $output\n$error")
}
output
}
return try {
if (silent) processCall() else callWithTimer("Executing command ${command.joinToString(" ")}", processCall)
}
finally {
errOutputFile.delete()
}
}
internal fun <T> List<T>.split(eachSize: Int): List<List<T>> {
if (this.size < eachSize) return listOf(this)
val result = mutableListOf<List<T>>()
var start = 0
while (start < this.size) {
val sub = this.subList(start, Math.min(start + eachSize, this.size))
if (!sub.isEmpty()) result += sub
start += eachSize
}
return result
}
internal fun <T> callSafely(call: () -> T): T? = try {
call()
}
catch (e: Exception) {
e.printStackTrace()
log(e.message ?: e.javaClass.canonicalName)
null
}
internal fun <T> callWithTimer(msg: String? = null, call: () -> T): T {
if (msg != null) log(msg)
val start = System.currentTimeMillis()
try {
return call()
}
finally {
log("Took ${System.currentTimeMillis() - start} ms")
}
}
internal fun <T> retry(maxRetries: Int = 20,
secondsBeforeRetry: Long = 30,
doRetry: (Throwable) -> Boolean = { true },
action: () -> T): T {
repeat(maxRetries) {
val number = it + 1
try {
return action()
}
catch (e: Exception) {
if (number < maxRetries && doRetry(e)) {
log("$number attempt of $maxRetries has failed with ${e.message}. Retrying in ${secondsBeforeRetry}s..")
TimeUnit.SECONDS.sleep(secondsBeforeRetry)
}
else throw e
}
}
error("Unable to complete")
}
|
apache-2.0
|
68f81a55329e4871c6f5641d7e674c10
| 31.228261 | 140 | 0.656883 | 3.87451 | false | false | false | false |
mdanielwork/intellij-community
|
plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ULiteralLanguageReference.kt
|
4
|
1994
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
/*
* Copyright 2006 Sascha Weinreuter
*
* 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.intellij.plugins.intelliLang.inject.java
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.PsiReferenceBase
import org.intellij.plugins.intelliLang.inject.InjectLanguageAction
import org.intellij.plugins.intelliLang.inject.InjectedLanguage
import org.jetbrains.uast.ULiteralExpression
/**
* Provides completion for available Language-IDs in
* <pre>@Language("[ctrl-space]")</pre>
*/
class ULiteralLanguageReference(val uLiteralExpression: ULiteralExpression,
val host: PsiLanguageInjectionHost) : PsiReferenceBase<PsiLanguageInjectionHost>(host) {
override fun getValue(): String = uLiteralExpression.value as? String ?: ""
override fun resolve(): PsiElement? = if (InjectedLanguage.findLanguageById(value) != null) uLiteralExpression.sourcePsi else null
override fun isSoft(): Boolean = false
override fun getVariants(): Array<LookupElement> =
InjectLanguageAction.getAllInjectables().map {
LookupElementBuilder.create(it.id).withIcon(it.icon).withTailText("(${it.displayName})", true)
}.toTypedArray()
}
|
apache-2.0
|
6ef922e2dda6feb33293dc7060e3860d
| 43.311111 | 140 | 0.769308 | 4.583908 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/ModifiableRootModelBridgeTest.kt
|
2
|
3975
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.module.EmptyModuleType
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.impl.RootConfigurationAccessor
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.rules.ProjectModelRule
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleRootComponentBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModifiableRootModelBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.toBuilder
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
class ModifiableRootModelBridgeTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule(true)
@Test(expected = Test.None::class)
fun `removing module with modifiable model`() {
runWriteActionAndWait {
val module = projectModel.createModule()
val moduleRootManager = ModuleRootManager.getInstance(module) as ModuleRootComponentBridge
val diff = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.toBuilder()
val modifiableModel = moduleRootManager.getModifiableModel(diff,
RootConfigurationAccessor.DEFAULT_INSTANCE) as ModifiableRootModelBridge
(ModuleManager.getInstance(projectModel.project) as ModuleManagerBridgeImpl).getModifiableModel(diff).disposeModule(module)
modifiableModel.prepareForCommit()
modifiableModel.postCommit()
}
}
@Test(expected = Test.None::class)
fun `getting module root model from modifiable module`() {
runWriteActionAndWait {
val moduleModifiableModel = ModuleManager.getInstance(projectModel.project).modifiableModel
val newModule = moduleModifiableModel.newModule(projectModel.projectRootDir.resolve("myModule/myModule.iml"),
EmptyModuleType.EMPTY_MODULE) as ModuleBridge
val moduleRootManager = ModuleRootManager.getInstance(newModule) as ModuleRootComponentBridge
// Assert no exceptions
val model = moduleRootManager.getModifiableModel(newModule.diff!! as MutableEntityStorage,
RootConfigurationAccessor.DEFAULT_INSTANCE)
model.dispose()
moduleModifiableModel.dispose()
}
}
@Test(expected = Test.None::class)
fun `get modifiable models of renamed module`() {
runWriteActionAndWait {
val moduleModifiableModel = ModuleManager.getInstance(projectModel.project).modifiableModel
val newModule = moduleModifiableModel.newModule(projectModel.projectRootDir.resolve("myModule/myModule.iml"),
EmptyModuleType.EMPTY_MODULE) as ModuleBridge
moduleModifiableModel.commit()
val builder = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.toBuilder()
val anotherModifiableModel = (ModuleManager.getInstance(projectModel.project) as ModuleManagerBridgeImpl).getModifiableModel(builder)
anotherModifiableModel.renameModule(newModule, "newName")
val moduleRootManager = ModuleRootManager.getInstance(newModule) as ModuleRootComponentBridge
// Assert no exceptions
val model = moduleRootManager.getModifiableModel(builder, RootConfigurationAccessor.DEFAULT_INSTANCE)
anotherModifiableModel.dispose()
}
}
}
|
apache-2.0
|
64cf4fa24959383d15348106418545c2
| 44.170455 | 140 | 0.757987 | 5.828446 | false | true | false | false |
android/snippets
|
compose/snippets/src/main/java/com/example/compose/snippets/ui/theme/Color.kt
|
1
|
882
|
/*
* Copyright 2022 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.compose.snippets.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
|
apache-2.0
|
b74c6f6d690bfaffa14ee7020e7c4883
| 35.791667 | 92 | 0.763039 | 3.585366 | false | false | false | false |
zbeboy/ISY
|
src/main/java/top/zbeboy/isy/web/vo/graduate/design/replan/DefenseGroupAddVo.kt
|
1
|
543
|
package top.zbeboy.isy.web.vo.graduate.design.replan
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
/**
* Created by zbeboy 2018-02-06 .
**/
open class DefenseGroupAddVo {
@NotNull
@Size(max = 64)
var defenseArrangementId: String? = null
@NotNull
@Size(max = 20)
var defenseGroupName: String? = null
@NotNull
var schoolroomId: Int = 0
@Size(max = 100)
var note: String? = null
@NotNull
@Size(max = 64)
var graduationDesignReleaseId: String? = null
}
|
mit
|
ca415300ab86b5315509eff59089eb83
| 22.652174 | 52 | 0.679558 | 3.644295 | false | false | false | false |
gituser9/InvoiceManagement
|
app/src/main/java/com/user/invoicemanagement/presenter/ClosedInvoicePresenter.kt
|
1
|
5993
|
package com.user.invoicemanagement.presenter
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import com.user.invoicemanagement.R
import com.user.invoicemanagement.model.dto.ClosedInvoice
import com.user.invoicemanagement.other.Constant
import com.user.invoicemanagement.view.fragment.ClosedInvoiceFragment
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import jxl.Workbook
import jxl.WorkbookSettings
import jxl.write.Label
import jxl.write.WritableWorkbook
import jxl.write.WriteException
import jxl.write.biff.RowsExceededException
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class ClosedInvoicePresenter(val view: ClosedInvoiceFragment) : BasePresenter() {
fun getInvoice(invoiceId: Long) {
model.getInvoice(invoiceId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { invoice ->
view.show(invoice)
}
}
fun exportToExcel(invoiceId: Long, context: Context) {
if (invoiceId == 0L) {
view.showToast(R.string.export_error)
return
}
val preferences = context.getSharedPreferences(Constant.settingsName, Context.MODE_PRIVATE)
val email = preferences.getString(Constant.emailForReportsKey, "")
if (email.isEmpty()) {
view.showAlert(R.string.email_is_required)
return
}
model.getInvoice(invoiceId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { invoice: ClosedInvoice ->
createExcel(invoice)
sendEmail(context)
}
}
private fun createExcel(invoice: ClosedInvoice): Boolean {
val formattedDate = SimpleDateFormat("dd/MM/yyyy", Locale("ru"))
val netDate = Date(invoice.savedDate)
formattedDate.format(netDate)
val filename = "Invoice-$formattedDate.xls"
//Saving file in external storage
val sdCard = Environment.getExternalStorageDirectory()
val directory = File(sdCard.absolutePath + "/invoices")
if (!directory.isDirectory) {
directory.mkdirs()
}
val file = File(directory, filename)
val wbSettings = WorkbookSettings()
wbSettings.locale = Locale("en", "EN")
val workbook: WritableWorkbook
try {
workbook = Workbook.createWorkbook(file, wbSettings)
val sheet = workbook.createSheet("Invoice", 0)
var currentRow = 0
try {
val factories = invoice.factories ?: emptyList()
for (factory in factories) {
sheet.addCell(Label(0, currentRow, factory.name))
sheet.addCell(Label(8, currentRow, "Продажная"))
sheet.addCell(Label(9, currentRow, "Закупочная"))
++currentRow
if (factory.products == null || factory.products!!.isEmpty()) {
currentRow += 2
continue
}
for (product in factory.products!!) {
sheet.addCell(Label(0, currentRow, product.name))
sheet.addCell(Label(1, currentRow, product.weightOnStore.toString()))
sheet.addCell(Label(2, currentRow, product.weightInFridge.toString()))
sheet.addCell(Label(3, currentRow, product.weightInStorage.toString()))
sheet.addCell(Label(4, currentRow, product.weight4.toString()))
sheet.addCell(Label(5, currentRow, product.weight5.toString()))
sheet.addCell(Label(6, currentRow, Constant.priceFormat.format(product.sellingPrice)))
sheet.addCell(Label(7, currentRow, Constant.priceFormat.format(product.purchasePrice)))
sheet.addCell(Label(8, currentRow, Constant.priceFormat.format(product.sellingPriceSummary)))
sheet.addCell(Label(9, currentRow, Constant.priceFormat.format(product.purchasePriceSummary)))
++currentRow
}
++currentRow
}
} catch (e: RowsExceededException) {
return false
} catch (e: WriteException) {
return false
}
workbook.write()
try {
workbook.close()
} catch (e: WriteException) {
return false
}
} catch (e: IOException) {
return false
}
return true
}
private fun sendEmail(context: Context) {
val filename = "Invoice.xls"
val sdCard = Environment.getExternalStorageDirectory()
val directory = File(sdCard.absolutePath + "/invoices")
if (!directory.isDirectory) {
directory.mkdirs()
}
val file = File(directory, filename)
val path = Uri.fromFile(file)
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// set the type to 'email'
emailIntent.type = "vnd.android.cursor.dir/email"
val preferences = context.getSharedPreferences(Constant.settingsName, Context.MODE_PRIVATE)
val email = preferences.getString(Constant.emailForReportsKey, "")
val to = arrayOf(email)
emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path)
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject")
context.startActivity(Intent.createChooser(emailIntent, "Send email..."))
}
}
|
mit
|
0b35633e622a7777402ef71f29c54779
| 35.656442 | 118 | 0.60529 | 5.011745 | false | false | false | false |
paplorinc/intellij-community
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator30.kt
|
1
|
2900
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiModifier
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.annotator.intentions.AddParenthesisToLambdaParameterAction
import org.jetbrains.plugins.groovy.codeInspection.bugs.GrRemoveModifierFix
import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor
import org.jetbrains.plugins.groovy.lang.psi.api.GrLambdaExpression
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrParenthesizedExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
/**
* Check features introduced in groovy 3.0
*/
class GroovyAnnotator30(private val holder: AnnotationHolder) : GroovyElementVisitor() {
override fun visitModifierList(modifierList: GrModifierList) {
checkDefaultModifier(modifierList)
}
private fun checkDefaultModifier(modifierList: GrModifierList) {
val modifier = modifierList.getModifier(PsiModifier.DEFAULT) ?: return
val parentClass = PsiTreeUtil.getParentOfType(modifier, PsiClass::class.java) ?: return
if (!parentClass.isInterface || (parentClass as? GrTypeDefinition)?.isTrait == true) {
val annotation = holder.createWarningAnnotation(modifier, GroovyBundle.message("illegal.default.modifier"))
registerFix(annotation, GrRemoveModifierFix(PsiModifier.DEFAULT, GroovyBundle.message("illegal.default.modifier.fix")), modifier)
}
}
override fun visitLambdaExpression(expression: GrLambdaExpression) {
checkSingleArgumentLambda(expression)
super.visitLambdaExpression(expression)
}
private fun checkSingleArgumentLambda(lambda: GrLambdaExpression) {
val parameterList = lambda.parameterList
if (parameterList.lParen != null) return
val parent = lambda.parent
when (parent) {
is GrAssignmentExpression, is GrVariable, is GrParenthesizedExpression -> return
is GrArgumentList -> if (parent.parent is GrMethodCallExpression) return
}
holder.createErrorAnnotation(parameterList, GroovyBundle.message("illegal.single.argument.lambda")).apply {
registerFix(AddParenthesisToLambdaParameterAction(lambda))
}
}
}
|
apache-2.0
|
0f3edc2b4eb717b95df76b63b8204c2d
| 46.540984 | 140 | 0.810345 | 4.707792 | false | false | false | false |
google/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/wm/impl/headertoolbar/ProjectWidget.kt
|
1
|
8233
|
// 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.openapi.wm.impl.headertoolbar
import com.intellij.ide.*
import com.intellij.ide.impl.ProjectUtilCore
import com.intellij.ide.plugins.newui.ListPluginComponent
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.*
import com.intellij.openapi.ui.popup.util.PopupUtil
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.wm.impl.ToolbarComboWidget
import com.intellij.ui.GroupHeaderSeparator
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.dsl.builder.EmptySpacingConfiguration
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.JBGaps
import com.intellij.ui.dsl.gridLayout.VerticalAlign
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.ui.popup.PopupState
import com.intellij.ui.popup.list.ListPopupModel
import com.intellij.ui.popup.list.SelectablePanel
import com.intellij.util.PathUtil
import com.intellij.util.ui.JBFont
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.accessibility.AccessibleContextUtil
import java.awt.BorderLayout
import java.awt.Component
import java.awt.event.InputEvent
import java.util.function.Function
import javax.swing.*
private const val MAX_RECENT_COUNT = 100
internal val projectKey = Key.create<Project>("project-widget-project")
internal class ProjectWidget(private val presentation: Presentation) : ToolbarComboWidget() {
private val popupState = PopupState.forPopup()
private val project: Project?
get() = presentation.getClientProperty(projectKey)
init {
presentation.addPropertyChangeListener { updateWidget() }
}
private fun updateWidget() {
text = presentation.text
toolTipText = presentation.description
}
override fun doExpand(e: InputEvent) {
if (popupState.isShowing || popupState.isRecentlyHidden) return
val dataContext = DataManager.getInstance().getDataContext(this)
val anActionEvent = AnActionEvent.createFromInputEvent(e, ActionPlaces.PROJECT_WIDGET_POPUP, null, dataContext)
val step = createStep(createActionGroup(anActionEvent))
val widgetRenderer = ProjectWidgetRenderer()
val renderer = Function<ListCellRenderer<Any>, ListCellRenderer<out Any>> { base ->
ListCellRenderer<PopupFactoryImpl.ActionItem> { list, value, index, isSelected, cellHasFocus ->
val action = (value as PopupFactoryImpl.ActionItem).action
if (action is ReopenProjectAction) {
widgetRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
}
else {
base.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus)
}
}
}
project?.let { createPopup(it, step, renderer) }?.showAligned()
}
private fun createPopup(it: Project, step: ListPopupStep<Any>, renderer: Function<ListCellRenderer<Any>, ListCellRenderer<out Any>>): ListPopup {
val res = JBPopupFactory.getInstance().createListPopup(it, step, renderer)
res.setRequestFocus(false)
popupState.prepareToShow(res)
return res
}
private fun createActionGroup(initEvent: AnActionEvent): ActionGroup {
val res = DefaultActionGroup()
val group = ActionManager.getInstance().getAction("ProjectWidget.Actions") as ActionGroup
res.addAll(group.getChildren(initEvent).asList())
val openProjects = ProjectUtilCore.getOpenProjects()
val actionsMap: Map<Boolean, List<AnAction>> = RecentProjectListActionProvider.getInstance().getActions().take(MAX_RECENT_COUNT).groupBy(createSelector(openProjects))
actionsMap[true]?.let {
res.addSeparator(IdeBundle.message("project.widget.open.projects"))
res.addAll(it)
}
actionsMap[false]?.let {
res.addSeparator(IdeBundle.message("project.widget.recent.projects"))
res.addAll(it)
}
return res
}
private fun createSelector(openProjects: Array<Project>): (AnAction) -> Boolean {
val paths = openProjects.map { it.basePath }
return { action -> (action as? ReopenProjectAction)?.projectPath in paths }
}
private fun createStep(actionGroup: ActionGroup): ListPopupStep<Any> {
val context = DataManager.getInstance().getDataContext(this)
return JBPopupFactory.getInstance().createActionsStep(actionGroup, context, ActionPlaces.PROJECT_WIDGET_POPUP, false, false,
null, this, false, 0, false)
}
private class ProjectWidgetRenderer : ListCellRenderer<PopupFactoryImpl.ActionItem> {
override fun getListCellRendererComponent(list: JList<out PopupFactoryImpl.ActionItem>?,
value: PopupFactoryImpl.ActionItem?,
index: Int,
isSelected: Boolean,
cellHasFocus: Boolean): Component {
return createRecentProjectPane(value as PopupFactoryImpl.ActionItem, isSelected, getSeparator(list, value), index == 0)
}
private fun getSeparator(list: JList<out PopupFactoryImpl.ActionItem>?, value: PopupFactoryImpl.ActionItem?): ListSeparator? {
val model = list?.model as? ListPopupModel<*> ?: return null
val hasSeparator = model.isSeparatorAboveOf(value)
if (!hasSeparator) return null
return ListSeparator(model.getCaptionAboveOf(value))
}
private fun createRecentProjectPane(value: PopupFactoryImpl.ActionItem, isSelected: Boolean, separator: ListSeparator?, hideLine: Boolean): JComponent {
val action = value.action as ReopenProjectAction
val projectPath = action.projectPath
lateinit var nameLbl: JLabel
lateinit var pathLbl: JLabel
val content = panel {
customizeSpacingConfiguration(EmptySpacingConfiguration()) {
row {
icon(RecentProjectsManagerBase.getInstanceEx().getProjectIcon(projectPath, true))
.verticalAlign(VerticalAlign.TOP)
.customize(JBGaps(right = 8))
panel {
row {
nameLbl = label(action.projectNameToDisplay ?: "")
.customize(JBGaps(bottom = 4))
.applyToComponent {
foreground = if (isSelected) UIUtil.getListSelectionForeground(true) else UIUtil.getListForeground()
}.component
}
row {
pathLbl = label(FileUtil.getLocationRelativeToUserHome(PathUtil.toSystemDependentName(projectPath), false))
.applyToComponent {
font = JBFont.smallOrNewUiMedium()
foreground = UIUtil.getLabelInfoForeground()
}.component
}
}
}
}
}.apply {
border = JBUI.Borders.empty(8, 0)
isOpaque = false
}
val result = SelectablePanel.wrap(content, JBUI.CurrentTheme.Popup.BACKGROUND)
PopupUtil.configSelectablePanel(result)
if (isSelected) {
result.selectionColor = ListPluginComponent.SELECTION_COLOR
}
AccessibleContextUtil.setCombinedName(result, nameLbl, " - ", pathLbl)
AccessibleContextUtil.setCombinedDescription(result, nameLbl, " - ", pathLbl)
if (separator == null) {
return result
}
val res = NonOpaquePanel(BorderLayout())
res.border = JBUI.Borders.empty()
res.add(createSeparator(separator, hideLine), BorderLayout.NORTH)
res.add(result, BorderLayout.CENTER)
return res
}
private fun createSeparator(separator: ListSeparator, hideLine: Boolean): JComponent {
val res = GroupHeaderSeparator(JBUI.CurrentTheme.Popup.separatorLabelInsets())
res.caption = separator.text
res.setHideLine(hideLine)
val panel = JPanel(BorderLayout())
panel.border = JBUI.Borders.empty()
panel.isOpaque = true
panel.background = JBUI.CurrentTheme.Popup.BACKGROUND
panel.add(res)
return panel
}
}
}
|
apache-2.0
|
21804ff3be040ae1195b403264da5d16
| 39.357843 | 170 | 0.700352 | 4.883155 | false | false | false | false |
google/intellij-community
|
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SampleEntityImpl.kt
|
1
|
15314
|
package com.intellij.workspaceModel.storage.entities.test.api
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.EntityLink
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 com.intellij.workspaceModel.storage.impl.containers.MutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToManyChildrenOfParent
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
import java.util.UUID
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class SampleEntityImpl(val dataSource: SampleEntityData) : SampleEntity, WorkspaceEntityBase() {
companion object {
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(SampleEntity::class.java, ChildSampleEntity::class.java,
ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
CHILDREN_CONNECTION_ID,
)
}
override val booleanProperty: Boolean get() = dataSource.booleanProperty
override val stringProperty: String
get() = dataSource.stringProperty
override val stringListProperty: List<String>
get() = dataSource.stringListProperty
override val stringMapProperty: Map<String, String>
get() = dataSource.stringMapProperty
override val fileProperty: VirtualFileUrl
get() = dataSource.fileProperty
override val children: List<ChildSampleEntity>
get() = snapshot.extractOneToManyChildren<ChildSampleEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override val nullableData: String?
get() = dataSource.nullableData
override val randomUUID: UUID?
get() = dataSource.randomUUID
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: SampleEntityData?) : ModifiableWorkspaceEntityBase<SampleEntity>(), SampleEntity.Builder {
constructor() : this(SampleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity SampleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
index(this, "fileProperty", this.fileProperty)
// 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().isStringPropertyInitialized()) {
error("Field SampleEntity#stringProperty should be initialized")
}
if (!getEntityData().isStringListPropertyInitialized()) {
error("Field SampleEntity#stringListProperty should be initialized")
}
if (!getEntityData().isStringMapPropertyInitialized()) {
error("Field SampleEntity#stringMapProperty should be initialized")
}
if (!getEntityData().isFilePropertyInitialized()) {
error("Field SampleEntity#fileProperty should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field SampleEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field SampleEntity#children 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 SampleEntity
this.entitySource = dataSource.entitySource
this.booleanProperty = dataSource.booleanProperty
this.stringProperty = dataSource.stringProperty
this.stringListProperty = dataSource.stringListProperty.toMutableList()
this.stringMapProperty = dataSource.stringMapProperty.toMutableMap()
this.fileProperty = dataSource.fileProperty
this.nullableData = dataSource.nullableData
this.randomUUID = dataSource.randomUUID
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var booleanProperty: Boolean
get() = getEntityData().booleanProperty
set(value) {
checkModificationAllowed()
getEntityData().booleanProperty = value
changedProperty.add("booleanProperty")
}
override var stringProperty: String
get() = getEntityData().stringProperty
set(value) {
checkModificationAllowed()
getEntityData().stringProperty = value
changedProperty.add("stringProperty")
}
private val stringListPropertyUpdater: (value: List<String>) -> Unit = { value ->
changedProperty.add("stringListProperty")
}
override var stringListProperty: MutableList<String>
get() {
val collection_stringListProperty = getEntityData().stringListProperty
if (collection_stringListProperty !is MutableWorkspaceList) return collection_stringListProperty
collection_stringListProperty.setModificationUpdateAction(stringListPropertyUpdater)
return collection_stringListProperty
}
set(value) {
checkModificationAllowed()
getEntityData().stringListProperty = value
stringListPropertyUpdater.invoke(value)
}
override var stringMapProperty: Map<String, String>
get() = getEntityData().stringMapProperty
set(value) {
checkModificationAllowed()
getEntityData().stringMapProperty = value
changedProperty.add("stringMapProperty")
}
override var fileProperty: VirtualFileUrl
get() = getEntityData().fileProperty
set(value) {
checkModificationAllowed()
getEntityData().fileProperty = value
changedProperty.add("fileProperty")
val _diff = diff
if (_diff != null) index(this, "fileProperty", value)
}
// List of non-abstract referenced types
var _children: List<ChildSampleEntity>? = emptyList()
override var children: List<ChildSampleEntity>
get() {
// Getter of the list of non-abstract referenced types
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyChildren<ChildSampleEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true,
CHILDREN_CONNECTION_ID)] as? List<ChildSampleEntity>
?: emptyList())
}
else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<ChildSampleEntity> ?: emptyList()
}
}
set(value) {
// Setter of the list of non-abstract referenced types
checkModificationAllowed()
val _diff = diff
if (_diff != null) {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*> && (item_value as? ModifiableWorkspaceEntityBase<*>)?.diff == null) {
_diff.addEntity(item_value)
}
}
_diff.updateOneToManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value)
}
else {
for (item_value in value) {
if (item_value is ModifiableWorkspaceEntityBase<*>) {
item_value.entityLinks[EntityLink(false, CHILDREN_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
}
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] = value
}
changedProperty.add("children")
}
override var nullableData: String?
get() = getEntityData().nullableData
set(value) {
checkModificationAllowed()
getEntityData().nullableData = value
changedProperty.add("nullableData")
}
override var randomUUID: UUID?
get() = getEntityData().randomUUID
set(value) {
checkModificationAllowed()
getEntityData().randomUUID = value
changedProperty.add("randomUUID")
}
override fun getEntityData(): SampleEntityData = result ?: super.getEntityData() as SampleEntityData
override fun getEntityClass(): Class<SampleEntity> = SampleEntity::class.java
}
}
class SampleEntityData : WorkspaceEntityData<SampleEntity>() {
var booleanProperty: Boolean = false
lateinit var stringProperty: String
lateinit var stringListProperty: MutableList<String>
lateinit var stringMapProperty: Map<String, String>
lateinit var fileProperty: VirtualFileUrl
var nullableData: String? = null
var randomUUID: UUID? = null
fun isStringPropertyInitialized(): Boolean = ::stringProperty.isInitialized
fun isStringListPropertyInitialized(): Boolean = ::stringListProperty.isInitialized
fun isStringMapPropertyInitialized(): Boolean = ::stringMapProperty.isInitialized
fun isFilePropertyInitialized(): Boolean = ::fileProperty.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SampleEntity> {
val modifiable = SampleEntityImpl.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): SampleEntity {
return getCached(snapshot) {
val entity = SampleEntityImpl(this)
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun clone(): SampleEntityData {
val clonedEntity = super.clone()
clonedEntity as SampleEntityData
clonedEntity.stringListProperty = clonedEntity.stringListProperty.toMutableWorkspaceList()
return clonedEntity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return SampleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return SampleEntity(booleanProperty, stringProperty, stringListProperty, stringMapProperty, fileProperty, entitySource) {
this.nullableData = [email protected]
this.randomUUID = [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 SampleEntityData
if (this.entitySource != other.entitySource) return false
if (this.booleanProperty != other.booleanProperty) return false
if (this.stringProperty != other.stringProperty) return false
if (this.stringListProperty != other.stringListProperty) return false
if (this.stringMapProperty != other.stringMapProperty) return false
if (this.fileProperty != other.fileProperty) return false
if (this.nullableData != other.nullableData) return false
if (this.randomUUID != other.randomUUID) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as SampleEntityData
if (this.booleanProperty != other.booleanProperty) return false
if (this.stringProperty != other.stringProperty) return false
if (this.stringListProperty != other.stringListProperty) return false
if (this.stringMapProperty != other.stringMapProperty) return false
if (this.fileProperty != other.fileProperty) return false
if (this.nullableData != other.nullableData) return false
if (this.randomUUID != other.randomUUID) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + booleanProperty.hashCode()
result = 31 * result + stringProperty.hashCode()
result = 31 * result + stringListProperty.hashCode()
result = 31 * result + stringMapProperty.hashCode()
result = 31 * result + fileProperty.hashCode()
result = 31 * result + nullableData.hashCode()
result = 31 * result + randomUUID.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + booleanProperty.hashCode()
result = 31 * result + stringProperty.hashCode()
result = 31 * result + stringListProperty.hashCode()
result = 31 * result + stringMapProperty.hashCode()
result = 31 * result + fileProperty.hashCode()
result = 31 * result + nullableData.hashCode()
result = 31 * result + randomUUID.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
this.stringMapProperty?.let { collector.add(it::class.java) }
this.stringListProperty?.let { collector.add(it::class.java) }
this.randomUUID?.let { collector.addDataToInspect(it) }
this.fileProperty?.let { collector.add(it::class.java) }
collector.sameForAllEntities = false
}
}
|
apache-2.0
|
ceb432e7511525b92b235e234bf12c23
| 37.76962 | 184 | 0.703082 | 5.554588 | false | false | false | false |
google/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/JavaMapForEachInspection.kt
|
3
|
2962
|
// 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.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.core.getLastLambdaExpression
import org.jetbrains.kotlin.idea.inspections.collections.isMap
import org.jetbrains.kotlin.idea.util.textRangeIn
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.synthetic.isResolvedWithSamConversions
class JavaMapForEachInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(
KtCallExpression::class.java
) {
override fun isApplicable(element: KtCallExpression): Boolean {
val calleeExpression = element.calleeExpression ?: return false
if (calleeExpression.text != "forEach") return false
if (element.valueArguments.size != 1) return false
val lambda = element.lambda() ?: return false
val lambdaParameters = lambda.valueParameters
if (lambdaParameters.size != 2 || lambdaParameters.any { it.destructuringDeclaration != null }) return false
val context = element.analyze(BodyResolveMode.PARTIAL)
val resolvedCall = element.getResolvedCall(context) ?: return false
return resolvedCall.dispatchReceiver?.type?.isMap(DefaultBuiltIns.Instance) == true && resolvedCall.isResolvedWithSamConversions()
}
override fun inspectionHighlightRangeInElement(element: KtCallExpression): TextRange? = element.calleeExpression?.textRangeIn(element)
override fun inspectionText(element: KtCallExpression) =
KotlinBundle.message("java.map.foreach.method.call.should.be.replaced.with.kotlin.s.foreach")
override val defaultFixText get() = KotlinBundle.message("replace.with.kotlin.s.foreach")
override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) {
val lambda = element.lambda() ?: return
val valueParameters = lambda.valueParameters
lambda.functionLiteral.valueParameterList?.replace(
KtPsiFactory(element).createLambdaParameterList("(${valueParameters[0].text}, ${valueParameters[1].text})")
)
}
private fun KtCallExpression.lambda(): KtLambdaExpression? {
return lambdaArguments.singleOrNull()?.getArgumentExpression() as? KtLambdaExpression ?: getLastLambdaExpression()
}
}
|
apache-2.0
|
e677b01e149f5c2eeb4f2087a34c0635
| 50.964912 | 138 | 0.782242 | 5.003378 | false | false | false | false |
google/iosched
|
shared/src/staging/java/com/google/samples/apps/iosched/shared/data/FakeAppConfigDataSource.kt
|
1
|
6546
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.data
import android.content.res.Resources.NotFoundException
import com.google.samples.apps.iosched.model.ConferenceWifiInfo
import com.google.samples.apps.iosched.shared.data.config.AgendaTimestampsKey
import com.google.samples.apps.iosched.shared.data.config.AppConfigDataSource
import com.google.samples.apps.iosched.shared.util.TimeUtils
import org.threeten.bp.ZonedDateTime
import org.threeten.bp.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME
import kotlin.collections.Map.Entry
class FakeAppConfigDataSource() : AppConfigDataSource {
private val times1 = mutableMapOf(
AgendaTimestampsKey.BADGE_PICK_UP_DAY1_START_TIME.key to "",
AgendaTimestampsKey.BADGE_PICK_UP_DAY1_END_TIME.key to "",
AgendaTimestampsKey.BADGE_PICK_UP_DAY0_START_TIME.key to "",
AgendaTimestampsKey.BADGE_PICK_UP_DAY0_END_TIME.key to "",
AgendaTimestampsKey.BREAKFAST_DAY1_START_TIME.key to "",
AgendaTimestampsKey.BREAKFAST_DAY1_END_TIME.key to "",
AgendaTimestampsKey.GOOGLE_KEYNOTE_START_TIME.key to "",
AgendaTimestampsKey.GOOGLE_KEYNOTE_END_TIME.key to "",
AgendaTimestampsKey.IO_STORE_DAY1_START_TIME.key to "",
AgendaTimestampsKey.IO_STORE_DAY1_END_TIME.key to "",
AgendaTimestampsKey.LUNCH_DAY1_START_TIME.key to "",
AgendaTimestampsKey.BADGE_PICK_UP_DAY0_END_TIME.key to "",
AgendaTimestampsKey.LUNCH_DAY1_END_TIME.key to "",
AgendaTimestampsKey.DEVELOPER_KEYNOTE_START_TIME.key to "",
AgendaTimestampsKey.DEVELOPER_KEYNOTE_END_TIME.key to "",
AgendaTimestampsKey.SESSIONS_DAY1_START_TIME.key to "",
AgendaTimestampsKey.SESSIONS_DAY1_END_TIME.key to "",
AgendaTimestampsKey.CODELABS_DAY1_START_TIME.key to "",
AgendaTimestampsKey.CODELABS_DAY1_END_TIME.key to "",
AgendaTimestampsKey.OFFICE_HOURS_DAY1_START_TIME.key to "",
AgendaTimestampsKey.OFFICE_HOURS_DAY1_END_TIME.key to "",
AgendaTimestampsKey.SANDBOXES_DAY1_START_TIME.key to "",
AgendaTimestampsKey.SANDBOXES_DAY1_END_TIME.key to "",
AgendaTimestampsKey.AFTER_DARK_START_TIME.key to "",
AgendaTimestampsKey.AFTER_DARK_END_TIME.key to ""
)
private val times2 = mutableMapOf(
AgendaTimestampsKey.BADGE_DEVICE_PICK_UP_DAY2_START_TIME.key to "",
AgendaTimestampsKey.BADGE_DEVICE_PICK_UP_DAY2_END_TIME.key to "",
AgendaTimestampsKey.BREAKFAST_DAY2_START_TIME.key to "",
AgendaTimestampsKey.BREAKFAST_DAY2_END_TIME.key to "",
AgendaTimestampsKey.IO_STORE_DAY2_START_TIME.key to "",
AgendaTimestampsKey.IO_STORE_DAY2_END_TIME.key to "",
AgendaTimestampsKey.LUNCH_DAY2_START_TIME.key to "",
AgendaTimestampsKey.LUNCH_DAY2_END_TIME.key to "",
AgendaTimestampsKey.SESSIONS_DAY2_START_TIME.key to "",
AgendaTimestampsKey.SESSIONS_DAY2_END_TIME.key to "",
AgendaTimestampsKey.CODELABS_DAY2_START_TIME.key to "",
AgendaTimestampsKey.CODELABS_DAY2_END_TIME.key to "",
AgendaTimestampsKey.OFFICE_HOURS_DAY2_START_TIME.key to "",
AgendaTimestampsKey.OFFICE_HOURS_DAY2_END_TIME.key to "",
AgendaTimestampsKey.SANDBOXES_DAY2_START_TIME.key to "",
AgendaTimestampsKey.SANDBOXES_DAY2_END_TIME.key to "",
AgendaTimestampsKey.CONCERT_START_TIME.key to "",
AgendaTimestampsKey.CONCERT_END_TIME.key to ""
)
private val times3 = mutableMapOf(
AgendaTimestampsKey.BADGE_DEVICE_PICK_UP_DAY3_START_TIME.key to "",
AgendaTimestampsKey.BADGE_DEVICE_PICK_UP_DAY3_END_TIME.key to "",
AgendaTimestampsKey.BREAKFAST_DAY3_START_TIME.key to "",
AgendaTimestampsKey.BREAKFAST_DAY3_END_TIME.key to "",
AgendaTimestampsKey.IO_STORE_DAY3_START_TIME.key to "",
AgendaTimestampsKey.IO_STORE_DAY3_END_TIME.key to "",
AgendaTimestampsKey.LUNCH_DAY3_START_TIME.key to "",
AgendaTimestampsKey.LUNCH_DAY3_END_TIME.key to "",
AgendaTimestampsKey.SESSIONS_DAY3_START_TIME.key to "",
AgendaTimestampsKey.SESSIONS_DAY3_END_TIME.key to "",
AgendaTimestampsKey.CODELABS_DAY3_START_TIME.key to "",
AgendaTimestampsKey.CODELABS_DAY3_END_TIME.key to "",
AgendaTimestampsKey.OFFICE_HOURS_DAY3_START_TIME.key to "",
AgendaTimestampsKey.OFFICE_HOURS_DAY3_END_TIME.key to "",
AgendaTimestampsKey.SANDBOXES_DAY3_START_TIME.key to "",
AgendaTimestampsKey.SANDBOXES_DAY3_END_TIME.key to ""
)
init {
val startTimeDay1 = TimeUtils.ConferenceDays[0].start
initTimes(startTimeDay1, times1)
val startTimeDay2 = TimeUtils.ConferenceDays[1].start
initTimes(startTimeDay2, times2)
val startTimeDay3 = TimeUtils.ConferenceDays[2].start
initTimes(startTimeDay3, times3)
}
private fun initTimes(
startTimeDay: ZonedDateTime,
times: MutableMap<String, String>
) {
times.onEachIndexed { index, entry: Entry<String, String> ->
times[entry.key] = startTimeDay.plusMinutes(index.toLong()).format(ISO_OFFSET_DATE_TIME)
}
}
override fun getTimestamp(key: String): String {
return times1[key] ?: times2[key] ?: times3[key]
?: throw NotFoundException("Value for $key not found")
}
override suspend fun syncStrings() {}
override fun getWifiInfo(): ConferenceWifiInfo = ConferenceWifiInfo("", "")
override fun isMapFeatureEnabled(): Boolean = false
override fun isExploreArFeatureEnabled(): Boolean = false
override fun isCodelabsFeatureEnabled(): Boolean = true
override fun isSearchScheduleFeatureEnabled(): Boolean = true
override fun isSearchUsingRoomFeatureEnabled(): Boolean = true
override fun isAssistantAppFeatureEnabled(): Boolean = false
override fun isReservationFeatureEnabled(): Boolean = false
override fun isFeedEnabled(): Boolean = false
}
|
apache-2.0
|
a13ab871aa78e2e2af519d384ec28c2f
| 48.590909 | 100 | 0.712038 | 4.196154 | false | false | false | false |
JetBrains/intellij-community
|
platform/platform-impl/src/com/intellij/ui/dsl/builder/components/DslLabel.kt
|
1
|
7105
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.dsl.builder.components
import com.intellij.lang.documentation.DocumentationMarkup.EXTERNAL_LINK_ICON
import com.intellij.openapi.ui.panel.ComponentPanelBuilder
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.ColorUtil
import com.intellij.ui.dsl.UiDslException
import com.intellij.ui.dsl.builder.DEFAULT_COMMENT_WIDTH
import com.intellij.ui.dsl.builder.HyperlinkEventAction
import com.intellij.ui.dsl.builder.MAX_LINE_LENGTH_NO_WRAP
import com.intellij.ui.dsl.builder.MAX_LINE_LENGTH_WORD_WRAP
import com.intellij.util.ui.ExtendableHTMLViewFactory
import com.intellij.util.ui.HTMLEditorKitBuilder
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import java.awt.Dimension
import javax.swing.JEditorPane
import javax.swing.event.HyperlinkEvent
import javax.swing.text.DefaultCaret
import kotlin.math.min
/**
* Denied content and reasons
*/
private val DENIED_TAGS = mapOf(
Regex("<html>", RegexOption.IGNORE_CASE) to "tag <html> inserted automatically and shouldn't be used",
Regex("<body>", RegexOption.IGNORE_CASE) to "tag <body> inserted automatically and shouldn't be used",
Regex("""<a\s+href\s*=\s*(""|'')\s*>""", RegexOption.IGNORE_CASE) to "empty href like <a href=''> is denied, use <a> instead",
)
private const val LINK_GROUP = "link"
private val BROWSER_LINK_REGEX = Regex("""<a\s+href\s*=\s*['"]?(?<href>https?://[^>'"]*)['"]?\s*>(?<link>[^<]*)</a>""",
setOf(RegexOption.DOT_MATCHES_ALL, RegexOption.IGNORE_CASE))
@ApiStatus.Internal
enum class DslLabelType {
LABEL,
COMMENT
}
@ApiStatus.Internal
class DslLabel(private val type: DslLabelType) : JEditorPane() {
var action: HyperlinkEventAction? = null
var maxLineLength: Int = MAX_LINE_LENGTH_NO_WRAP
set(value) {
field = value
updateEditorPaneText()
}
var limitPreferredSize = false
@Nls
private var userText: String? = null
init {
contentType = UIUtil.HTML_MIME
editorKit = HTMLEditorKitBuilder()
.withViewFactoryExtensions(ExtendableHTMLViewFactory.Extensions.WORD_WRAP)
.build()
// JEditorPane.setText updates cursor and requests scrolling to cursor position if scrollable is used. Disable it
(caret as DefaultCaret).updatePolicy = DefaultCaret.NEVER_UPDATE
foreground = when (type) {
DslLabelType.COMMENT -> JBUI.CurrentTheme.ContextHelp.FOREGROUND
DslLabelType.LABEL -> JBUI.CurrentTheme.Label.foreground()
}
addHyperlinkListener { e ->
when (e?.eventType) {
HyperlinkEvent.EventType.ACTIVATED -> action?.hyperlinkActivated(e)
HyperlinkEvent.EventType.ENTERED -> action?.hyperlinkEntered(e)
HyperlinkEvent.EventType.EXITED -> action?.hyperlinkExited(e)
}
}
patchFont()
}
override fun updateUI() {
super.updateUI()
isFocusable = false
isEditable = false
border = null
background = UIUtil.TRANSPARENT_COLOR
isOpaque = false
disabledTextColor = JBUI.CurrentTheme.Label.disabledForeground()
patchFont()
updateEditorPaneText()
}
override fun getBaseline(width: Int, height: Int): Int {
// JEditorPane doesn't support baseline, calculate it manually from font
val fontMetrics = getFontMetrics(font)
return fontMetrics.ascent
}
override fun getMinimumSize(): Dimension {
val result = super.getMinimumSize()
return if (maxLineLength == MAX_LINE_LENGTH_WORD_WRAP && limitPreferredSize)
Dimension(min(getSupposedWidth(DEFAULT_COMMENT_WIDTH / 2), result.width), result.height)
else result
}
override fun getPreferredSize(): Dimension {
val result = super.getPreferredSize()
return if (maxLineLength == MAX_LINE_LENGTH_WORD_WRAP && limitPreferredSize)
Dimension(min(getSupposedWidth(DEFAULT_COMMENT_WIDTH), result.width), result.height)
else result
}
override fun setText(@Nls t: String?) {
userText = t
updateEditorPaneText()
}
private fun updateEditorPaneText() {
val text = userText
if (text == null) {
super.setText(null)
return
}
for ((regex, reason) in DENIED_TAGS) {
if (regex.find(text, 0) != null) {
UiDslException.error("Invalid html: $reason, text: $text")
}
}
@Suppress("HardCodedStringLiteral")
var processedText = text.replace("<a>", "<a href=''>", ignoreCase = true)
processedText = appendExternalLinkIcons(processedText)
var body = HtmlChunk.body()
if (maxLineLength > 0 && maxLineLength != MAX_LINE_LENGTH_NO_WRAP && text.length > maxLineLength) {
body = body.attr("width", getSupposedWidth(maxLineLength))
}
@NonNls val css = createCss()
super.setText(HtmlBuilder()
.append(HtmlChunk.raw(css))
.append(HtmlChunk.raw(processedText).wrapWith(body))
.wrapWith(HtmlChunk.html())
.toString())
// There is a bug in JDK: if JEditorPane gets height = 0 (text is null) then it never gets correct preferred size afterwards
// Below is a simple workaround to fix that, see details in BasicTextUI.getPreferredSize
// See also https://stackoverflow.com/questions/49273118/jeditorpane-getpreferredsize-not-always-working-in-java-9
size = Dimension(0, 0)
}
@Nls
private fun appendExternalLinkIcons(@Nls text: String): String {
val matchers = BROWSER_LINK_REGEX.findAll(text)
if (!matchers.any()) {
return text
}
val result = StringBuilder()
val externalLink = EXTERNAL_LINK_ICON.toString()
var i = 0
for (matcher in matchers) {
val linkEnd = matcher.groups[LINK_GROUP]!!.range.last
result.append(text.substring(i..linkEnd))
result.append(externalLink)
i = linkEnd + 1
}
result.append(text.substring(i))
@Suppress("HardCodedStringLiteral")
return result.toString()
}
private fun patchFont() {
if (type == DslLabelType.COMMENT) {
font = ComponentPanelBuilder.getCommentFont(font)
}
}
private fun createCss(): String {
val styles = mutableListOf(
"a, a:link {color:#${ColorUtil.toHex(JBUI.CurrentTheme.Link.Foreground.ENABLED)};}",
"a:visited {color:#${ColorUtil.toHex(JBUI.CurrentTheme.Link.Foreground.VISITED)};}",
"a:hover {color:#${ColorUtil.toHex(JBUI.CurrentTheme.Link.Foreground.HOVERED)};}",
"a:active {color:#${ColorUtil.toHex(JBUI.CurrentTheme.Link.Foreground.PRESSED)};}"
)
when (maxLineLength) {
MAX_LINE_LENGTH_NO_WRAP -> styles.add("body, p {white-space:nowrap;}")
}
return styles.joinToString(" ", "<head><style type='text/css'>", "</style></head>")
}
private fun getSupposedWidth(charCount: Int): Int {
return getFontMetrics(font).charWidth('0') * charCount
}
}
|
apache-2.0
|
8a476f4d838eed76ee21977133e68dfd
| 33.658537 | 158 | 0.697115 | 4.092742 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceGuardClauseWithFunctionCallInspection.kt
|
1
|
8407
|
// 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.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.psi.textRangeIn
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.codeinsight.utils.NegatedBinaryExpressionSimplificationUtils
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.parentOrNull
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class ReplaceGuardClauseWithFunctionCallInspection : AbstractApplicabilityBasedInspection<KtIfExpression>(
KtIfExpression::class.java
) {
companion object {
private const val ILLEGAL_STATE_EXCEPTION = "IllegalStateException"
private const val ILLEGAL_ARGUMENT_EXCEPTION = "IllegalArgumentException"
}
private enum class KotlinFunction(val functionName: String) {
CHECK("check"), CHECK_NOT_NULL("checkNotNull"), REQUIRE("require"), REQUIRE_NOT_NULL("requireNotNull");
val fqName: String
get() = "kotlin.$functionName"
}
override fun inspectionText(element: KtIfExpression) = KotlinBundle.message("replace.guard.clause.with.kotlin.s.function.call")
override val defaultFixText get() = KotlinBundle.message("replace.with.kotlin.s.function.call")
override fun fixText(element: KtIfExpression) =
element.getKotlinFunction()?.let { KotlinBundle.message("replace.with.0.call", it.functionName) } ?: defaultFixText
override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.ifKeyword.textRangeIn(element)
override fun isApplicable(element: KtIfExpression): Boolean {
val languageVersionSettings = element.languageVersionSettings
if (!languageVersionSettings.supportsFeature(LanguageFeature.UseReturnsEffect)) return false
if (element.condition == null) return false
val call = element.getCallExpression() ?: return false
val calleeText = call.calleeExpression?.text ?: return false
val valueArguments = call.valueArguments
if (valueArguments.size > 1) return false
if (calleeText != ILLEGAL_STATE_EXCEPTION && calleeText != ILLEGAL_ARGUMENT_EXCEPTION) return false
val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val argumentType = valueArguments.firstOrNull()?.getArgumentExpression()?.getType(context)
if (argumentType != null && !KotlinBuiltIns.isStringOrNullableString(argumentType)) return false
if (element.isUsedAsExpression(context)) return false
val fqName = call.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe?.parentOrNull()
return fqName == FqName("kotlin.$calleeText") || fqName == FqName("java.lang.$calleeText")
}
override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) {
val condition = element.condition ?: return
val call = element.getCallExpression() ?: return
val argument = call.valueArguments.firstOrNull()?.getArgumentExpression()
val commentSaver = CommentSaver(element)
val psiFactory = KtPsiFactory(project)
val replaced = when (val kotlinFunction = element.getKotlinFunction(call)) {
KotlinFunction.CHECK, KotlinFunction.REQUIRE -> {
val (excl, newCondition) = if (condition is KtPrefixExpression && condition.operationToken == KtTokens.EXCL) {
"" to (condition.baseExpression ?: return)
} else {
"!" to condition
}
val newExpression = if (argument == null) {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($excl$0)", newCondition)
} else {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($excl$0) { $1 }", newCondition, argument)
}
val replaced = element.replaceWith(newExpression, psiFactory)
val newCall = (replaced as? KtDotQualifiedExpression)?.callExpression
val negatedExpression = newCall?.valueArguments?.firstOrNull()?.getArgumentExpression() as? KtPrefixExpression
if (negatedExpression != null) {
NegatedBinaryExpressionSimplificationUtils.simplifyNegatedBinaryExpressionIfNeeded(negatedExpression)
}
replaced
}
KotlinFunction.CHECK_NOT_NULL, KotlinFunction.REQUIRE_NOT_NULL -> {
val nullCheckedExpression = condition.notNullCheckExpression() ?: return
val newExpression = if (argument == null) {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($0)", nullCheckedExpression)
} else {
psiFactory.createExpressionByPattern("${kotlinFunction.fqName}($0) { $1 }", nullCheckedExpression, argument)
}
element.replaceWith(newExpression, psiFactory)
}
else -> return
}
commentSaver.restore(replaced)
editor?.caretModel?.moveToOffset(replaced.startOffset)
ShortenReferences.DEFAULT.process(replaced)
}
private fun KtIfExpression.replaceWith(newExpression: KtExpression, psiFactory: KtPsiFactory): KtExpression {
val parent = parent
val elseBranch = `else`
return if (elseBranch != null) {
val added = parent.addBefore(newExpression, this) as KtExpression
parent.addBefore(psiFactory.createNewLine(), this)
replaceWithBranch(elseBranch, isUsedAsExpression = false, keepBraces = false)
added
} else {
replaced(newExpression)
}
}
private fun KtIfExpression.getCallExpression(): KtCallExpression? {
val throwExpression = this.then?.let {
it as? KtThrowExpression ?: (it as? KtBlockExpression)?.statements?.singleOrNull() as? KtThrowExpression
} ?: return null
return throwExpression.thrownExpression?.let {
it as? KtCallExpression ?: (it as? KtQualifiedExpression)?.callExpression
}
}
private fun KtIfExpression.getKotlinFunction(call: KtCallExpression? = getCallExpression()): KotlinFunction? {
val calleeText = call?.calleeExpression?.text ?: return null
val isNotNullCheck = condition.notNullCheckExpression() != null
return when (calleeText) {
ILLEGAL_STATE_EXCEPTION -> if (isNotNullCheck) KotlinFunction.CHECK_NOT_NULL else KotlinFunction.CHECK
ILLEGAL_ARGUMENT_EXCEPTION -> if (isNotNullCheck) KotlinFunction.REQUIRE_NOT_NULL else KotlinFunction.REQUIRE
else -> null
}
}
private fun KtExpression?.notNullCheckExpression(): KtExpression? {
if (this == null) return null
if (this !is KtBinaryExpression) return null
if (this.operationToken != KtTokens.EQEQ) return null
val left = this.left ?: return null
val right = this.right ?: return null
return when {
right.isNullConstant() -> left
left.isNullConstant() -> right
else -> null
}
}
private fun KtExpression.isNullConstant(): Boolean {
return (this as? KtConstantExpression)?.text == KtTokens.NULL_KEYWORD.value
}
}
|
apache-2.0
|
5d4c1ec433d0f359f6e3ff38616daac4
| 51.217391 | 131 | 0.701439 | 5.45201 | false | false | false | false |
java-graphics/assimp
|
src/main/kotlin/assimp/SpatialSort.kt
|
2
|
3889
|
package assimp
import glm_.vec3.Vec3
import java.util.*
class SpatialSort{
constructor()
private val mPlaneNormal = Vec3(0.8523f, 0.34321f, 0.5736f).normalize()
private val mPositions = ArrayList<Entry>()
private val CHAR_BIT = Character.SIZE
constructor(pPositions: List<AiVector3D>,pNumPositions: Int,pElementOffset: Int){
fill(pPositions,pNumPositions,pElementOffset)
}
fun fill(pPositions: List<AiVector3D>,pNumPositions: Int,pElementOffset: Int, pFinalize: Boolean = true)
{
mPositions.clear()
append(pPositions,pNumPositions,pElementOffset,pFinalize)
}
fun finalize() {
val array = mPositions.toTypedArray()
Arrays.sort(array)
mPositions.clear()
mPositions.addAll(array)
}
fun append(pPositions: List<AiVector3D>,pNumPositions: Int, pElementOffset: Int, pFinalize: Boolean = true)
{
// store references to all given positions along with their distance to the reference plane
val initial = mPositions.size
for(a in 0 until pNumPositions)
{
val vec = pPositions[a]
// store position by index and distance
val distance = vec.distance(mPlaneNormal)
mPositions.add( Entry( a+initial, vec, distance))
}
if (pFinalize) {
// now sort the array ascending by distance.
finalize()
}
}
fun findPositions(pPosition: AiVector3D,
pRadius: Float, poResults: ArrayList<Int>)
{
val dist = pPosition.distance(mPlaneNormal)
val minDist = dist - pRadius
val maxDist = dist + pRadius
// clear the array
poResults.clear()
// quick check for positions outside the range
if( mPositions.size == 0)
return
if( maxDist < mPositions[0].mDistance)
return
if( minDist > mPositions[mPositions.size - 1].mDistance)
return
// do a binary search for the minimal distance to start the iteration there
var index = mPositions.size / 2
var binaryStepSize = mPositions.size / 4
while( binaryStepSize > 1)
{
if( mPositions[index].mDistance < minDist)
index += binaryStepSize
else
index -= binaryStepSize
binaryStepSize /= 2
}
// depending on the direction of the last step we need to single step a bit back or forth
// to find the actual beginning element of the range
while( index > 0 && mPositions[index].mDistance > minDist)
index--
while( index < (mPositions.size - 1) && mPositions[index].mDistance < minDist)
index++
// Mow start iterating from there until the first position lays outside of the distance range.
// Add all positions inside the distance range within the given radius to the result aray
val iter = mPositions.iterator()
while(index > 0){
iter.next()
--index
}
val pSquared = pRadius*pRadius
var it = iter.next()
while( it.mDistance < maxDist)
{
if( (it.mPosition - pPosition).squareLength() < pSquared)
poResults.add(it.mIndex)
if(!iter.hasNext()) break
it = iter.next()
}
// that's it
}
private class Entry {
var mIndex = 0 ///< The vertex referred by this entry
var mPosition = AiVector3D() ///< Position
var mDistance = 0f ///< Distance of this vertex to the sorting plane
constructor(pIndex: Int, pPosition: AiVector3D, pDistance: Float) {
mIndex = pIndex
mPosition = pPosition
mDistance = pDistance
}
fun lessThan(e: Entry): Boolean {
return mDistance < e.mDistance
}
}
}
|
bsd-3-clause
|
89d4187da1eac57624466d0c09011c8a
| 31.14876 | 111 | 0.597583 | 4.618765 | false | false | false | false |
allotria/intellij-community
|
platform/lang-impl/src/com/intellij/refactoring/rename/impl/TextRenameUsage.kt
|
4
|
1308
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.rename.impl
import com.intellij.find.usages.api.PsiUsage
import com.intellij.model.Pointer
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiFile
import com.intellij.refactoring.rename.api.ModifiableRenameUsage
import com.intellij.refactoring.rename.api.ModifiableRenameUsage.FileUpdater
import com.intellij.refactoring.rename.api.PsiRenameUsage
import com.intellij.refactoring.rename.api.ReplaceTextTargetContext
internal class TextRenameUsage(
private val psiUsage: PsiUsage,
override val fileUpdater: FileUpdater,
val context: ReplaceTextTargetContext,
) : PsiRenameUsage, ModifiableRenameUsage {
override val declaration: Boolean get() = psiUsage.declaration
override val file: PsiFile get() = psiUsage.file
override val range: TextRange get() = psiUsage.range
override fun createPointer(): Pointer<out TextRenameUsage> {
val fileUpdater = fileUpdater // don't capture `this`
val context = context
return Pointer.delegatingPointer(psiUsage.createPointer(), listOf(TextRenameUsage::class.java, fileUpdater, context)) {
TextRenameUsage(it, fileUpdater, context)
}
}
}
|
apache-2.0
|
733114201cd5eaadcda4d8e7f31cd1c2
| 39.875 | 140 | 0.796636 | 4.418919 | false | false | false | false |
allotria/intellij-community
|
platform/usageView/src/com/intellij/usages/impl/UsageInGeneratedCode.kt
|
2
|
2721
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.usages.impl
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.GeneratedSourcesFilter
import com.intellij.usageView.UsageViewBundle
import com.intellij.usages.Usage
import com.intellij.usages.UsageTarget
import com.intellij.usages.UsageView
import com.intellij.usages.impl.actions.RuleAction
import com.intellij.usages.rules.UsageFilteringRule
import com.intellij.usages.rules.UsageFilteringRuleProvider
import com.intellij.usages.rules.UsageInFile
class UsageInGeneratedCodeFilteringRuleProvider : UsageFilteringRuleProvider {
override fun getActiveRules(project: Project): Array<UsageFilteringRule> {
if (GeneratedSourcesFilter.EP_NAME.hasAnyExtensions() && !state().enabled) {
return arrayOf(UsageInGeneratedCodeFilteringRule(project))
}
else {
return UsageFilteringRule.EMPTY_ARRAY
}
}
override fun createFilteringActions(view: UsageView): Array<AnAction> {
if (GeneratedSourcesFilter.EP_NAME.hasAnyExtensions()) {
return arrayOf(UsageInGeneratedCodeToggleAction())
}
else {
return AnAction.EMPTY_ARRAY
}
}
}
private class UsageInGeneratedCodeFilteringRule(private val project: Project) : UsageFilteringRule {
override fun isVisible(usage: Usage, targets: Array<out UsageTarget>?): Boolean {
return usage !is UsageInFile || usage.file.let { file ->
file == null || !GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(file, project)
}
}
}
private class UsageInGeneratedCodeToggleAction : RuleAction(
UsageViewBundle.messagePointer("action.show.in.generated.code"),
AllIcons.Actions.GeneratedFolder
) {
override fun getOptionValue(e: AnActionEvent): Boolean {
return state().enabled
}
override fun setOptionValue(e: AnActionEvent, value: Boolean) {
state().enabled = value
}
}
private fun state(): UsageInGeneratedCodeFilteringSetting = service()
@State(name = "UsageInGeneratedCodeFilteringSetting", storages = [Storage("usageView.xml")])
@Service
private class UsageInGeneratedCodeFilteringSetting(
var enabled: Boolean = true
) : PersistentStateComponent<UsageInGeneratedCodeFilteringSetting> {
override fun getState(): UsageInGeneratedCodeFilteringSetting {
return UsageInGeneratedCodeFilteringSetting(enabled)
}
override fun loadState(state: UsageInGeneratedCodeFilteringSetting) {
enabled = state.enabled
}
}
|
apache-2.0
|
b6803aebfdbbef60848c2f6893819eb1
| 33.884615 | 140 | 0.786476 | 4.867621 | false | false | false | false |
leafclick/intellij-community
|
platform/platform-tests/testSrc/com/intellij/internal/statistics/whitelist/StatisticsParseWhitelistWithBuildTest.kt
|
1
|
13754
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistics.whitelist
import com.intellij.internal.statistic.eventLog.EventLogBuildNumber
import com.intellij.internal.statistic.service.fus.FUSWhitelist
import com.intellij.internal.statistic.service.fus.FUStatisticsWhiteListGroupsService
import org.junit.Test
import kotlin.test.assertEquals
class StatisticsParseWhitelistWithBuildTest {
private fun doTest(content: String, expected: FUSWhitelist) {
val actual = FUStatisticsWhiteListGroupsService.parseApprovedGroups(content)
assertEquals(expected.size, actual.size)
assertEquals(expected, actual)
}
private fun newBuild(vararg args: Int): EventLogBuildNumber {
return EventLogBuildNumber(*args)
}
@Test
fun `with one build with from`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), null)
doTest(content, whitelist.build())
}
@Test
fun `with one build with to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"to" : "173.4284.118"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", null, newBuild(173, 4284, 118))
doTest(content, whitelist.build())
}
@Test
fun `with one build from and to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.231"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 231))
doTest(content, whitelist.build())
}
@Test
fun `with one build from snapshot and to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.0",
"to" : "181.231"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 0), newBuild(181, 231))
doTest(content, whitelist.build())
}
@Test
fun `with one build from and to snapshot`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.0"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 0))
doTest(content, whitelist.build())
}
@Test
fun `with one build from snapshot and to snapshot`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.0",
"to" : "181.0"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 0), newBuild(181, 0))
doTest(content, whitelist.build())
}
@Test
fun `with one number in from`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 0), null)
doTest(content, whitelist.build())
}
@Test
fun `with both from and to and one number in from`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173",
"to" : "182.31.3"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 0), newBuild(182, 31, 3))
doTest(content, whitelist.build())
}
@Test
fun `with one number in to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"to" : "183"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", null, newBuild(183, 0))
doTest(content, whitelist.build())
}
@Test
fun `with both from and to and one number in to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.332",
"to" : "182.0"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 332), newBuild(182, 0))
doTest(content, whitelist.build())
}
@Test
fun `with one number in from and to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "12",
"to" : "183"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(12, 0), newBuild(183, 0))
doTest(content, whitelist.build())
}
@Test
fun `with both from and to and negative from`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "-12",
"to" : "183.23"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(-12, 0), newBuild(183, 23))
doTest(content, whitelist.build())
}
@Test
fun `with both from and to and negative to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "12.2351.123",
"to" : "-183.23"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(12, 2351, 123), newBuild(-183, 23))
doTest(content, whitelist.build())
}
@Test
fun `with two build ranges with first from`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118"
},{
"from" : "182.421",
"to" : "183.5.1"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), null).
addBuild("test.group.id", newBuild(182, 421), newBuild(183, 5, 1))
doTest(content, whitelist.build())
}
@Test
fun `with two build ranges with second from`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.231"
},{
"from" : "182.421"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 231)).
addBuild("test.group.id", newBuild(182, 421), null)
doTest(content, whitelist.build())
}
@Test
fun `with two build ranges with first to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"to" : "181.231"
},{
"from" : "182.421",
"to" : "183.5.1"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", null, newBuild(181, 231)).
addBuild("test.group.id", newBuild(182, 421), newBuild(183, 5, 1))
doTest(content, whitelist.build())
}
@Test
fun `with two build ranges with second to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.231"
},{
"to" : "183.5.1"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 231)).
addBuild("test.group.id", null, newBuild(183, 5, 1))
doTest(content, whitelist.build())
}
@Test
fun `with two build ranges with from and to`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.231"
},{
"from" : "182.421",
"to" : "183.5.1"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 231)).
addBuild("test.group.id", newBuild(182, 421), newBuild(183, 5, 1))
doTest(content, whitelist.build())
}
@Test
fun `with build and version ranges`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.231"
}],
"versions" : [{
"from" : "10",
"to" : "15"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addVersion("test.group.id", 10, 15).
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 231))
doTest(content, whitelist.build())
}
@Test
fun `with multiple build and version ranges`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.231"
},{
"from" : "182.421",
"to" : "183.5.1"
}],
"versions" : [ {
"from" : "2",
"to" : "5"
},{
"from" : "10",
"to" : "15"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addVersion("test.group.id", 2, 5).
addVersion("test.group.id", 10, 15).
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 231)).
addBuild("test.group.id", newBuild(182, 421), newBuild(183, 5, 1))
doTest(content, whitelist.build())
}
@Test
fun `with build and empty version ranges`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.231"
}],
"versions" : [],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 231))
doTest(content, whitelist.build())
}
@Test
fun `with multiple build and empty version ranges`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [ {
"from" : "173.4284.118",
"to" : "181.231"
},{
"from" : "182.421",
"to" : "183.5.1"
}],
"versions" : [],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addBuild("test.group.id", newBuild(173, 4284, 118), newBuild(181, 231)).
addBuild("test.group.id", newBuild(182, 421), newBuild(183, 5, 1))
doTest(content, whitelist.build())
}
@Test
fun `with multiple version and empty build ranges`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [],
"versions" : [ {
"from" : "2",
"to" : "5"
},{
"from" : "10",
"to" : "15"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addVersion("test.group.id", 2, 5).
addVersion("test.group.id", 10, 15)
doTest(content, whitelist.build())
}
@Test
fun `with version and empty build ranges`() {
val content = """
{
"groups" : [{
"id" : "test.group.id",
"title" : "Test Group",
"description" : "Test group description",
"type" : "counter",
"builds" : [],
"versions" : [ {
"from" : "2",
"to" : "5"
}],
"context" : {
}
}]
}
"""
val whitelist = WhitelistBuilder().
addVersion("test.group.id", 2, 5)
doTest(content, whitelist.build())
}
}
|
apache-2.0
|
8b7e4e3fba76dee6661473e26046523d
| 21.365854 | 140 | 0.526029 | 3.323025 | false | true | false | false |
JoachimR/Bible2net
|
app/src/main/java/de/reiss/bible2net/theword/model/TheWord.kt
|
1
|
1077
|
package de.reiss.bible2net.theword.model
import android.os.Parcel
import android.os.Parcelable
import java.util.Date
data class TheWord(
val bible: String,
val date: Date,
val content: TheWordContent
) : Comparable<TheWord>, Parcelable {
companion object {
@JvmField
val CREATOR: Parcelable.Creator<TheWord> = object : Parcelable.Creator<TheWord> {
override fun createFromParcel(source: Parcel): TheWord = TheWord(source)
override fun newArray(size: Int): Array<TheWord?> = arrayOfNulls(size)
}
}
constructor(source: Parcel) : this(
source.readString()!!,
source.readSerializable() as Date,
source.readParcelable<TheWordContent>(TheWordContent::class.java.classLoader)!!
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeString(bible)
writeSerializable(date)
writeParcelable(content, 0)
}
override fun compareTo(other: TheWord): Int = this.date.compareTo(other.date)
}
|
gpl-3.0
|
9f82dbb3b91c8dc0dd225f999cfc801f
| 28.916667 | 89 | 0.67688 | 4.432099 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/NativePlatformKindResolution.kt
|
2
|
9687
|
// 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.ide.konan
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.PlatformAnalysisParameters
import org.jetbrains.kotlin.analyzer.ResolverForModuleFactory
import org.jetbrains.kotlin.analyzer.ResolverForProject
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.functions.functionInterfacePackageFragmentProvider
import org.jetbrains.kotlin.builtins.konan.KonanBuiltIns
import org.jetbrains.kotlin.caches.resolve.IdePlatformKindResolution
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.descriptors.ModuleCapability
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.konan.DeserializedKlibModuleOrigin
import org.jetbrains.kotlin.descriptors.konan.KlibModuleOrigin
import org.jetbrains.kotlin.ide.konan.CommonizerNativeTargetsCompat.commonizerNativeTargetsCompat
import org.jetbrains.kotlin.ide.konan.analyzer.NativeResolverForModuleFactory
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.caches.project.LibraryInfo
import org.jetbrains.kotlin.idea.caches.project.SdkInfo
import org.jetbrains.kotlin.idea.caches.project.lazyClosure
import org.jetbrains.kotlin.idea.caches.resolve.BuiltInsCacheKey
import org.jetbrains.kotlin.idea.compiler.IDELanguageSettingsProvider
import org.jetbrains.kotlin.idea.klib.AbstractKlibLibraryInfo
import org.jetbrains.kotlin.idea.klib.createKlibPackageFragmentProvider
import org.jetbrains.kotlin.idea.klib.isKlibLibraryRootForPlatform
import org.jetbrains.kotlin.idea.klib.safeRead
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.konan.library.KONAN_STDLIB_NAME
import org.jetbrains.kotlin.konan.properties.propertyList
import org.jetbrains.kotlin.konan.util.KlibMetadataFactories
import org.jetbrains.kotlin.library.BaseKotlinLibrary
import org.jetbrains.kotlin.library.KLIB_PROPERTY_NATIVE_TARGETS
import org.jetbrains.kotlin.library.isInterop
import org.jetbrains.kotlin.library.metadata.NullFlexibleTypeDeserializer
import org.jetbrains.kotlin.library.nativeTargets
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.platform.konan.NativePlatforms
import org.jetbrains.kotlin.platform.konan.NativePlatforms.nativePlatformByTargetNames
import org.jetbrains.kotlin.resolve.ImplicitIntegerCoercion
import org.jetbrains.kotlin.resolve.TargetEnvironment
import org.jetbrains.kotlin.serialization.konan.impl.KlibMetadataModuleDescriptorFactoryImpl
import org.jetbrains.kotlin.storage.StorageManager
class NativePlatformKindResolution : IdePlatformKindResolution {
override fun createLibraryInfo(project: Project, library: Library): List<LibraryInfo> {
return library.getFiles(OrderRootType.CLASSES).mapNotNull { file ->
if (!isLibraryFileForPlatform(file)) return@createLibraryInfo emptyList()
val path = PathUtil.getLocalPath(file) ?: return@createLibraryInfo emptyList()
NativeKlibLibraryInfo(project, library, path)
}
}
override fun createKlibPackageFragmentProvider(
moduleInfo: ModuleInfo,
storageManager: StorageManager,
languageVersionSettings: LanguageVersionSettings,
moduleDescriptor: ModuleDescriptor
): PackageFragmentProvider? {
return (moduleInfo as? NativeKlibLibraryInfo)
?.resolvedKotlinLibrary
?.createKlibPackageFragmentProvider(
storageManager = storageManager,
metadataModuleDescriptorFactory = metadataFactories.DefaultDeserializedDescriptorFactory,
languageVersionSettings = languageVersionSettings,
moduleDescriptor = moduleDescriptor,
lookupTracker = LookupTracker.DO_NOTHING
)
}
override fun isLibraryFileForPlatform(virtualFile: VirtualFile): Boolean =
virtualFile.isKlibLibraryRootForPlatform(NativePlatforms.unspecifiedNativePlatform)
override fun createResolverForModuleFactory(
settings: PlatformAnalysisParameters,
environment: TargetEnvironment,
platform: TargetPlatform
): ResolverForModuleFactory {
return NativeResolverForModuleFactory(settings, environment, platform)
}
override val libraryKind: PersistentLibraryKind<*>?
get() = NativeLibraryKind
override val kind get() = NativeIdePlatformKind
override fun getKeyForBuiltIns(moduleInfo: ModuleInfo, sdkInfo: SdkInfo?, stdlibInfo: LibraryInfo?): BuiltInsCacheKey = NativeBuiltInsCacheKey
override fun createBuiltIns(
moduleInfo: IdeaModuleInfo,
projectContext: ProjectContext,
resolverForProject: ResolverForProject<IdeaModuleInfo>,
sdkDependency: SdkInfo?,
stdlibDependency: LibraryInfo?,
) = createKotlinNativeBuiltIns(moduleInfo, projectContext)
private fun createKotlinNativeBuiltIns(moduleInfo: ModuleInfo, projectContext: ProjectContext): KotlinBuiltIns {
val stdlibInfo = moduleInfo.findNativeStdlib() ?: return DefaultBuiltIns.Instance
val project = projectContext.project
val storageManager = projectContext.storageManager
val builtInsModule = metadataFactories.DefaultDescriptorFactory.createDescriptorAndNewBuiltIns(
KotlinBuiltIns.BUILTINS_MODULE_NAME,
storageManager,
DeserializedKlibModuleOrigin(stdlibInfo.resolvedKotlinLibrary),
stdlibInfo.capabilities
)
val languageVersionSettings = IDELanguageSettingsProvider.getLanguageVersionSettings(
stdlibInfo,
project
)
val stdlibPackageFragmentProvider = createKlibPackageFragmentProvider(
stdlibInfo,
storageManager,
languageVersionSettings,
builtInsModule
) ?: return DefaultBuiltIns.Instance
builtInsModule.initialize(
CompositePackageFragmentProvider(
listOf(
stdlibPackageFragmentProvider,
functionInterfacePackageFragmentProvider(storageManager, builtInsModule),
(metadataFactories.DefaultDeserializedDescriptorFactory as KlibMetadataModuleDescriptorFactoryImpl)
.createForwardDeclarationHackPackagePartProvider(storageManager, builtInsModule)
)
)
)
builtInsModule.setDependencies(listOf(builtInsModule))
return builtInsModule.builtIns
}
object NativeBuiltInsCacheKey : BuiltInsCacheKey
companion object {
private val metadataFactories = KlibMetadataFactories(::KonanBuiltIns, NullFlexibleTypeDeserializer)
private fun ModuleInfo.findNativeStdlib(): NativeKlibLibraryInfo? =
dependencies().lazyClosure { it.dependencies() }
.filterIsInstance<NativeKlibLibraryInfo>()
.firstOrNull { it.isStdlib && it.compatibilityInfo.isCompatible }
}
}
class NativeKlibLibraryInfo(project: Project, library: Library, libraryRoot: String) :
AbstractKlibLibraryInfo(project, library, libraryRoot) {
// If you're changing this, please take a look at ideaModelDependencies as well
val isStdlib: Boolean get() = libraryRoot.endsWith(KONAN_STDLIB_NAME)
override val capabilities: Map<ModuleCapability<*>, Any?>
get() {
val capabilities = super.capabilities.toMutableMap()
capabilities += KlibModuleOrigin.CAPABILITY to DeserializedKlibModuleOrigin(resolvedKotlinLibrary)
capabilities += ImplicitIntegerCoercion.MODULE_CAPABILITY to resolvedKotlinLibrary.safeRead(false) { isInterop }
return capabilities
}
override val platform: TargetPlatform by lazy {
val targetNames = resolvedKotlinLibrary.safeRead(null) { commonizerNativeTargetsCompat }
?: resolvedKotlinLibrary.safeRead(emptyList()) { nativeTargets }
nativePlatformByTargetNames(targetNames)
}
}
/**
* Provides forward compatibility to klib's 'commonizer_native_targets' property (which is expected in 1.5.20)
*/
@Suppress("SpellCheckingInspection")
private object CommonizerNativeTargetsCompat {
/**
* Similar to [KLIB_PROPERTY_NATIVE_TARGETS] but this will also preserve targets
* that were unsupported on the host creating this artifact
*/
private const val KLIB_PROPERTY_COMMONIZER_NATIVE_TARGETS = "commonizer_native_targets"
/**
* Accessor for 'commonizer_native_targets' manifest property.
* Can be removed once bundled compiler reaches 1.5.20
*/
val BaseKotlinLibrary.commonizerNativeTargetsCompat: List<String>?
get() = if (manifestProperties.containsKey(KLIB_PROPERTY_COMMONIZER_NATIVE_TARGETS))
manifestProperties.propertyList(KLIB_PROPERTY_COMMONIZER_NATIVE_TARGETS)
else null
}
|
apache-2.0
|
d93314d07088ec37ff797da62f6c92d1
| 46.258537 | 158 | 0.771446 | 5.589729 | false | false | false | false |
smmribeiro/intellij-community
|
platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/OutputTest.kt
|
19
|
2474
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.testframework.sm.runner
import com.intellij.execution.testframework.sm.runner.ui.MockPrinter
import com.intellij.openapi.util.Disposer
class OutputTest : BaseSMTRunnerTestCase() {
fun testBeforeAfterOrder() {
val suite = createTestProxy("parent")
suite.setTreeBuildBeforeStart()
val child = createTestProxy("child", suite)
child.setTreeBuildBeforeStart()
suite.addStdOutput("before test started\n")
child.setStarted()
child.addStdOutput("inside test\n")
child.setFinished()
suite.addStdOutput("after test finished\n")
val printer = MockPrinter(true)
suite.printOn(printer)
assertEquals("before test started\ninside test\nafter test finished\n", printer.stdOut)
printer.resetIfNecessary()
child.printOn(printer)
assertEquals("inside test\n", printer.stdOut)
}
fun testBeforeAfterFailedOrder() {
val suite = createTestProxy("parent")
suite.setTreeBuildBeforeStart()
val child = createTestProxy("child", suite)
child.setTreeBuildBeforeStart()
suite.addStdOutput("before test started\n")
child.setStarted()
child.addStdOutput("inside test\n")
child.setTestFailed("fail", null, false)
suite.addStdOutput("after test finished\n")
val printer = MockPrinter(true)
suite.printOn(printer)
assertEquals("before test started\ninside test\nafter test finished\n", printer.stdOut)
printer.resetIfNecessary()
child.printOn(printer)
assertEquals("inside test\n", printer.stdOut)
}
fun testBeforeAfterOrderWhenFlushed() {
val suite = createTestProxy("parent")
suite.setTreeBuildBeforeStart()
val child = createTestProxy("child", suite)
child.setTreeBuildBeforeStart()
try {
suite.addStdOutput("before test started\n")
child.setStarted()
child.addStdOutput("inside test\n")
child.setFinished()
suite.flush()
suite.addStdOutput("after test finished\n")
val printer = MockPrinter(true)
suite.printOn(printer)
assertEquals("before test started\ninside test\nafter test finished\n", printer.stdOut)
printer.resetIfNecessary()
child.printOn(printer)
assertEquals("inside test\n", printer.stdOut)
}
finally {
Disposer.dispose(child)
Disposer.dispose(suite)
}
}
}
|
apache-2.0
|
0043ae7e8cd1549aa2763fa27a3e7f43
| 29.9375 | 140 | 0.716249 | 4.465704 | false | true | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/refactoring/rename/javaSetterToOrdinaryMethod/after/synthesize.kt
|
13
|
280
|
fun synthesize(p: SyntheticProperty) {
val v1 = p.syntheticA
p.foo(1)
p.foo(p.syntheticA + 2)
p.foo(p.syntheticA.inc())
val syntheticA = p.syntheticA
p.foo(syntheticA.inc())
val x = syntheticA
val i = p.syntheticA.inc()
p.foo(i)
val y = i
}
|
apache-2.0
|
143837a3429a9b0945472cfd3bdf5aae
| 22.416667 | 38 | 0.603571 | 3.010753 | false | false | false | false |
kickstarter/android-oss
|
app/src/main/java/com/kickstarter/ui/SharedPreferenceKey.kt
|
1
|
604
|
package com.kickstarter.ui
object SharedPreferenceKey {
const val ACCESS_TOKEN = "access_token"
const val CONFIG = "config"
const val FIRST_SESSION = "first_session"
const val HAS_SEEN_APP_RATING = "has_seen_app_rating"
const val HAS_SEEN_GAMES_NEWSLETTER = "has_seen_games_newsletter"
const val LAST_SEEN_ACTIVITY_ID = "last_seen_activity_id"
const val MESSAGE_THREAD_HAS_UNREAD_MESSAGES = "message_thread_has_unread_messages"
const val USER = "user"
const val FEATURE_FLAG = "feature_flags"
const val HAS_SEEN_NOTIF_PERMISSIONS = "has_seen_notif_permissions"
}
|
apache-2.0
|
73649b716fd2dab3119da39927b84c39
| 42.142857 | 87 | 0.720199 | 3.532164 | false | true | false | false |
ingokegel/intellij-community
|
platform/projectModel-api/src/com/intellij/configurationStore/xmlSerializer.kt
|
10
|
2644
|
// 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.
@file:JvmName("XmlSerializer")
package com.intellij.configurationStore
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.util.xmlb.SerializationFilter
import com.intellij.util.xmlb.SkipDefaultsSerializationFilter
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.net.URL
@ApiStatus.Internal
val jdomSerializer: JdomSerializer = run {
val implClass = JdomSerializer::class.java.classLoader.loadClass("com.intellij.configurationStore.JdomSerializerImpl")
MethodHandles.lookup().findConstructor(implClass, MethodType.methodType(Void.TYPE)).invoke() as JdomSerializer
}
@JvmOverloads
fun <T : Any> serialize(obj: T, filter: SerializationFilter? = jdomSerializer.getDefaultSerializationFilter(), createElementIfEmpty: Boolean = false): Element? {
return jdomSerializer.serialize(obj, filter, createElementIfEmpty)
}
inline fun <reified T: Any> deserialize(element: Element): T = jdomSerializer.deserialize(element, T::class.java)
fun <T> Element.deserialize(clazz: Class<T>): T = jdomSerializer.deserialize(this, clazz)
fun Element.deserializeInto(bean: Any) {
jdomSerializer.deserializeInto(bean, this)
}
@JvmOverloads
fun <T> deserializeAndLoadState(component: PersistentStateComponent<T>, element: Element, clazz: Class<T> = ComponentSerializationUtil.getStateClass(component::class.java)) {
val state = jdomSerializer.deserialize(element, clazz)
(state as? BaseState)?.resetModificationCount()
component.loadState(state)
}
@JvmOverloads
fun serializeObjectInto(o: Any, target: Element, filter: SerializationFilter? = null) {
jdomSerializer.serializeObjectInto(o, target, filter)
}
fun serializeStateInto(component: PersistentStateComponent<*>, element: Element) {
component.state?.let {
jdomSerializer.serializeObjectInto(it, element)
}
}
@ApiStatus.Internal
interface JdomSerializer {
fun <T : Any> serialize(obj: T, filter: SerializationFilter?, createElementIfEmpty: Boolean = false): Element?
fun serializeObjectInto(obj: Any, target: Element, filter: SerializationFilter? = null)
fun <T> deserialize(element: Element, clazz: Class<T>): T
fun deserializeInto(obj: Any, element: Element)
fun <T> deserialize(url: URL, aClass: Class<T>): T
@ApiStatus.Internal
fun getDefaultSerializationFilter(): SkipDefaultsSerializationFilter
fun clearSerializationCaches()
}
|
apache-2.0
|
2aba91e5658fb731d795d9ac5e19f745
| 37.897059 | 174 | 0.795008 | 4.377483 | false | false | false | false |
siosio/intellij-community
|
platform/indexing-impl/src/com/intellij/psi/impl/search/helper.kt
|
1
|
11713
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.search
import com.intellij.model.search.SearchParameters
import com.intellij.model.search.Searcher
import com.intellij.model.search.impl.*
import com.intellij.openapi.progress.*
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ClassExtension
import com.intellij.openapi.util.Computable
import com.intellij.psi.PsiElement
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.PsiSearchHelper
import com.intellij.psi.search.SearchSession
import com.intellij.util.Processor
import com.intellij.util.Query
import com.intellij.util.SmartList
import com.intellij.util.text.StringSearcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import org.jetbrains.annotations.ApiStatus.Internal
import java.util.*
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
private val searchersExtension = ClassExtension<Searcher<*, *>>("com.intellij.searcher")
@Suppress("UNCHECKED_CAST")
internal fun <R : Any> searchers(parameters: SearchParameters<R>): List<Searcher<SearchParameters<R>, R>> {
return searchersExtension.forKey(parameters.javaClass) as List<Searcher<SearchParameters<R>, R>>
}
internal val indicatorOrEmpty: ProgressIndicator
get() = EmptyProgressIndicator.notNullize(ProgressIndicatorProvider.getGlobalProgressIndicator())
fun <R> runSearch(cs: CoroutineScope, project: Project, query: Query<R>): ReceiveChannel<R> {
@Suppress("EXPERIMENTAL_API_USAGE")
return cs.produce(capacity = Channel.UNLIMITED) {
runUnderIndicator {
runSearch(project, query, Processor {
require(channel.offer(it))
true
})
}
}
}
@Internal
fun <R> runSearch(project: Project, query: Query<out R>, processor: Processor<in R>): Boolean {
val progress = indicatorOrEmpty
var currentQueries: Collection<Query<out R>> = listOf(query)
while (currentQueries.isNotEmpty()) {
progress.checkCanceled()
val layer = buildLayer(progress, project, currentQueries)
when (val layerResult = layer.runLayer(processor)) {
is LayerResult.Ok -> currentQueries = layerResult.subqueries
is LayerResult.Stop -> return false
}
}
return true
}
private fun <R> buildLayer(progress: ProgressIndicator, project: Project, queries: Collection<Query<out R>>): Layer<out R> {
val queue: Queue<Query<out R>> = ArrayDeque()
queue.addAll(queries)
val queryRequests = SmartList<QueryRequest<*, R>>()
val wordRequests = SmartList<WordRequest<R>>()
while (queue.isNotEmpty()) {
progress.checkCanceled()
val query: Query<out R> = queue.remove()
val primitives: Requests<R> = decompose(query)
queryRequests.addAll(primitives.queryRequests)
wordRequests.addAll(primitives.wordRequests)
for (parametersRequest in primitives.parametersRequests) {
progress.checkCanceled()
handleParamRequest(progress, parametersRequest) {
queue.offer(it)
}
}
}
return Layer(project, progress, queryRequests, wordRequests)
}
private fun <B, R> handleParamRequest(progress: ProgressIndicator,
request: ParametersRequest<B, R>,
queue: (Query<out R>) -> Unit) {
val searchRequests: Collection<Query<out B>> = collectSearchRequests(request.params)
for (query: Query<out B> in searchRequests) {
progress.checkCanceled()
queue(XQuery(query, request.transformation))
}
}
private fun <R : Any> collectSearchRequests(parameters: SearchParameters<R>): Collection<Query<out R>> {
return DumbService.getInstance(parameters.project).runReadActionInSmartMode(Computable {
if (parameters.areValid()) {
doCollectSearchRequests(parameters)
}
else {
emptyList()
}
})
}
private fun <R : Any> doCollectSearchRequests(parameters: SearchParameters<R>): Collection<Query<out R>> {
val queries = ArrayList<Query<out R>>()
queries.add(SearchersQuery(parameters))
val searchers = searchers(parameters)
for (searcher: Searcher<SearchParameters<R>, R> in searchers) {
ProgressManager.checkCanceled()
queries += searcher.collectSearchRequests(parameters)
}
return queries
}
private sealed class LayerResult<out T> {
object Stop : LayerResult<Nothing>()
class Ok<T>(val subqueries: Collection<Query<out T>>) : LayerResult<T>()
}
private class Layer<T>(
private val project: Project,
private val progress: ProgressIndicator,
private val queryRequests: Collection<QueryRequest<*, T>>,
private val wordRequests: Collection<WordRequest<T>>
) {
private val myHelper = PsiSearchHelper.getInstance(project) as PsiSearchHelperImpl
fun runLayer(processor: Processor<in T>): LayerResult<T> {
val subQueries = Collections.synchronizedList(ArrayList<Query<out T>>())
val xProcessor = Processor<XResult<T>> { result ->
when (result) {
is ValueResult -> processor.process(result.value)
is QueryResult -> {
subQueries.add(result.query)
true
}
}
}
if (!processQueryRequests(progress, queryRequests, xProcessor)) {
return LayerResult.Stop
}
if (!processWordRequests(xProcessor)) {
return LayerResult.Stop
}
return LayerResult.Ok(subQueries)
}
private fun processWordRequests(processor: Processor<in XResult<T>>): Boolean {
if (wordRequests.isEmpty()) {
return true
}
val allRequests: Collection<RequestAndProcessors> = distributeWordRequests(processor)
val globals = SmartList<RequestAndProcessors>()
val locals = SmartList<RequestAndProcessors>()
for (requestAndProcessor: RequestAndProcessors in allRequests) {
if (requestAndProcessor.request.searchScope is LocalSearchScope) {
locals += requestAndProcessor
}
else {
globals += requestAndProcessor
}
}
return processGlobalRequests(globals)
&& processLocalRequests(locals)
}
private fun distributeWordRequests(processor: Processor<in XResult<T>>): Collection<RequestAndProcessors> {
val theMap = LinkedHashMap<
WordRequestInfo,
Pair<
MutableCollection<OccurrenceProcessor>,
MutableMap<LanguageInfo, MutableCollection<OccurrenceProcessor>>
>
>()
for (wordRequest: WordRequest<T> in wordRequests) {
progress.checkCanceled()
val occurrenceProcessor: OccurrenceProcessor = wordRequest.occurrenceProcessor(processor)
val byRequest = theMap.getOrPut(wordRequest.searchWordRequest) {
Pair(SmartList(), LinkedHashMap())
}
val injectionInfo = wordRequest.injectionInfo
if (injectionInfo == InjectionInfo.NoInjection || injectionInfo == InjectionInfo.IncludeInjections) {
byRequest.first.add(occurrenceProcessor)
}
if (injectionInfo is InjectionInfo.InInjection || injectionInfo == InjectionInfo.IncludeInjections) {
val languageInfo: LanguageInfo = if (injectionInfo is InjectionInfo.InInjection) {
injectionInfo.languageInfo
}
else {
LanguageInfo.NoLanguage
}
byRequest.second.getOrPut(languageInfo) { SmartList() }.add(occurrenceProcessor)
}
}
return theMap.map { (wordRequest: WordRequestInfo, byRequest) ->
progress.checkCanceled()
val (hostProcessors, injectionProcessors) = byRequest
RequestAndProcessors(wordRequest, RequestProcessors(hostProcessors, injectionProcessors))
}
}
private fun processGlobalRequests(globals: Collection<RequestAndProcessors>): Boolean {
if (globals.isEmpty()) {
return true
}
else if (globals.size == 1) {
return processSingleRequest(globals.first())
}
val globalsIds: Map<PsiSearchHelperImpl.TextIndexQuery, List<WordRequestInfo>> = globals.groupBy(
{ (request: WordRequestInfo, _) -> PsiSearchHelperImpl.TextIndexQuery.fromWord(request.word, request.isCaseSensitive, null) },
{ (request: WordRequestInfo, _) -> progress.checkCanceled(); request }
)
return myHelper.processGlobalRequests(globalsIds, progress, scopeProcessors(globals))
}
private fun scopeProcessors(globals: Collection<RequestAndProcessors>): Map<WordRequestInfo, Processor<in PsiElement>> {
val result = HashMap<WordRequestInfo, Processor<in PsiElement>>()
for (requestAndProcessors: RequestAndProcessors in globals) {
progress.checkCanceled()
result[requestAndProcessors.request] = scopeProcessor(requestAndProcessors)
}
return result
}
private fun scopeProcessor(requestAndProcessors: RequestAndProcessors): Processor<in PsiElement> {
val (request: WordRequestInfo, processors: RequestProcessors) = requestAndProcessors
val searcher = StringSearcher(request.word, request.isCaseSensitive, true, false)
val adapted = MyBulkOccurrenceProcessor(project, processors)
return PsiSearchHelperImpl.localProcessor(searcher, adapted)
}
private fun processLocalRequests(locals: Collection<RequestAndProcessors>): Boolean {
if (locals.isEmpty()) {
return true
}
for (requestAndProcessors: RequestAndProcessors in locals) {
progress.checkCanceled()
if (!processSingleRequest(requestAndProcessors)) return false
}
return true
}
private fun processSingleRequest(requestAndProcessors: RequestAndProcessors): Boolean {
val (request: WordRequestInfo, processors: RequestProcessors) = requestAndProcessors
val options = EnumSet.of(PsiSearchHelperImpl.Options.PROCESS_ONLY_JAVA_IDENTIFIERS_IF_POSSIBLE)
if (request.isCaseSensitive) options.add(PsiSearchHelperImpl.Options.CASE_SENSITIVE_SEARCH)
return myHelper.bulkProcessElementsWithWord(
request.searchScope,
request.word,
request.searchContext,
options,
request.containerName,
SearchSession(),
MyBulkOccurrenceProcessor(project, processors)
)
}
}
private fun <R> processQueryRequests(progress: ProgressIndicator,
requests: Collection<QueryRequest<*, R>>,
processor: Processor<in XResult<R>>): Boolean {
if (requests.isEmpty()) {
return true
}
val map: Map<Query<*>, List<XTransformation<*, R>>> = requests.groupBy({ it.query }, { it.transformation })
for ((query: Query<*>, transforms: List<XTransformation<*, R>>) in map.iterator()) {
progress.checkCanceled()
@Suppress("UNCHECKED_CAST")
if (!runQueryRequest(query as Query<Any>, transforms as Collection<XTransformation<Any, R>>, processor)) {
return false
}
}
return true
}
private fun <B, R> runQueryRequest(query: Query<out B>,
transformations: Collection<Transformation<B, R>>,
processor: Processor<in R>): Boolean {
return query.forEach(fun(baseValue: B): Boolean {
for (transformation: Transformation<B, R> in transformations) {
for (resultValue: R in transformation(baseValue)) {
if (!processor.process(resultValue)) {
return false
}
}
}
return true
})
}
private data class RequestAndProcessors(
val request: WordRequestInfo,
val processors: RequestProcessors
)
internal class RequestProcessors(
val hostProcessors: Collection<OccurrenceProcessor>,
val injectionProcessors: Map<LanguageInfo, Collection<OccurrenceProcessor>>
)
|
apache-2.0
|
3532c2aecfaea35d6453fa8062f0069e
| 36.541667 | 158 | 0.719457 | 4.812243 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/tests/testData/inspections/redundantSuspendModifier/operators.kt
|
4
|
1040
|
// WITH_RUNTIME
class A(val x: Int) {
// Redundant
suspend operator fun plus(a: A): A {
return A(x + a.x)
}
}
// Not redundant
suspend fun foo(a1: A, a2: A): A {
return a1 + a2
}
// Not redundant
suspend fun bar(a1: A, a2: A): A {
var result = a1
result += a2
return result
}
class B(var x: Int) {
// Redundant
suspend operator fun minusAssign(b: B) {
x -= b.x
}
}
// Not redundant
suspend fun foo(b1: B, b2: B): B {
val result = b1
result -= b2
return result
}
class C(val x: Int, val y: Int) {
// Redundant
suspend operator fun invoke() = x + y
}
// Not redundant
suspend fun bar(): Int {
return C(1, 2)()
}
// Not redundant
suspend fun foo(c1: C, c2: C): Int {
return c1() + c2()
}
interface C {
// Not redundant
suspend fun foo()
}
class D : C {
// Not redundant
override suspend fun foo() {
}
}
open class E {
// Not redundant
open suspend fun bar() {
}
// Not redundant
abstract suspend fun baz()
}
|
apache-2.0
|
f803cebb254f49c9275f2aaefa034fac
| 14.086957 | 44 | 0.552885 | 3.058824 | false | false | false | false |
ncoe/rosetta
|
Super-d_numbers/Kotlin/src/SuperDNumbers.kt
|
1
|
634
|
import java.math.BigInteger
fun superD(d: Int, max: Int) {
val start = System.currentTimeMillis()
var test = ""
for (i in 0 until d) {
test += d
}
var n = 0
var i = 0
println("First $max super-$d numbers:")
while (n < max) {
i++
val value: Any = BigInteger.valueOf(d.toLong()) * BigInteger.valueOf(i.toLong()).pow(d)
if (value.toString().contains(test)) {
n++
print("$i ")
}
}
val end = System.currentTimeMillis()
println("\nRun time ${end - start} ms\n")
}
fun main() {
for (i in 2..9) {
superD(i, 10)
}
}
|
mit
|
7e3c4d673b7e89663139e8576eef369b
| 20.862069 | 95 | 0.509464 | 3.390374 | false | true | false | false |
JetBrains/kotlin-native
|
tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/konan/KonanPlugin.kt
|
1
|
20069
|
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.plugin.konan
import groovy.lang.Closure
import org.codehaus.groovy.runtime.GStringImpl
import org.gradle.api.*
import org.gradle.api.component.ComponentWithVariants
import org.gradle.api.component.SoftwareComponent
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.FeaturePreviews
import org.gradle.api.internal.component.SoftwareComponentInternal
import org.gradle.api.internal.component.UsageContext
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.plugins.BasePlugin
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.publish.maven.internal.publication.MavenPublicationInternal
import org.gradle.api.tasks.Exec
import org.gradle.language.cpp.internal.NativeVariantIdentity
import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry
import org.gradle.util.GradleVersion
import org.jetbrains.kotlin.gradle.plugin.konan.KonanPlugin.Companion.COMPILE_ALL_TASK_NAME
import org.jetbrains.kotlin.gradle.plugin.tasks.*
import org.jetbrains.kotlin.konan.CURRENT
import org.jetbrains.kotlin.konan.CompilerVersion
import org.jetbrains.kotlin.konan.parseCompilerVersion
import org.jetbrains.kotlin.konan.target.HostManager
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.konan.target.buildDistribution
import org.jetbrains.kotlin.konan.target.customerDistribution
import org.jetbrains.kotlin.konan.util.DependencyProcessor
import java.io.File
import javax.inject.Inject
/**
* We use the following properties:
* org.jetbrains.kotlin.native.home - directory where compiler is located (aka dist in konan project output).
* org.jetbrains.kotlin.native.version - a konan compiler version for downloading.
* konan.build.targets - list of targets to build (by default all the declared targets are built).
* konan.jvmArgs - additional args to be passed to a JVM executing the compiler/cinterop tool.
*/
internal fun Project.warnAboutDeprecatedProperty(property: KonanPlugin.ProjectProperty) =
property.deprecatedPropertyName?.let { deprecated ->
if (project.hasProperty(deprecated)) {
logger.warn("Project property '$deprecated' is deprecated. Use '${property.propertyName}' instead.")
}
}
internal fun Project.hasProperty(property: KonanPlugin.ProjectProperty) = with(property) {
when {
hasProperty(propertyName) -> true
deprecatedPropertyName != null && hasProperty(deprecatedPropertyName) -> true
else -> false
}
}
internal fun Project.findProperty(property: KonanPlugin.ProjectProperty): Any? = with(property) {
return findProperty(propertyName) ?: deprecatedPropertyName?.let { findProperty(it) }
}
internal fun Project.getProperty(property: KonanPlugin.ProjectProperty) = findProperty(property)
?: throw IllegalArgumentException("No such property in the project: ${property.propertyName}")
internal fun Project.getProperty(property: KonanPlugin.ProjectProperty, defaultValue: Any) =
findProperty(property) ?: defaultValue
internal fun Project.setProperty(property: KonanPlugin.ProjectProperty, value: Any) {
extensions.extraProperties.set(property.propertyName, value)
}
// konanHome extension is set by downloadKonanCompiler task.
internal val Project.konanHome: String
get() {
assert(hasProperty(KonanPlugin.ProjectProperty.KONAN_HOME))
return project.file(getProperty(KonanPlugin.ProjectProperty.KONAN_HOME)).canonicalPath
}
internal val Project.konanVersion: CompilerVersion
get() = project.findProperty(KonanPlugin.ProjectProperty.KONAN_VERSION)
?.toString()?.let { CompilerVersion.fromString(it) }
?: CompilerVersion.CURRENT
internal val Project.konanBuildRoot get() = buildDir.resolve("konan")
internal val Project.konanBinBaseDir get() = konanBuildRoot.resolve("bin")
internal val Project.konanLibsBaseDir get() = konanBuildRoot.resolve("libs")
internal val Project.konanBitcodeBaseDir get() = konanBuildRoot.resolve("bitcode")
internal fun File.targetSubdir(target: KonanTarget) = resolve(target.visibleName)
internal val Project.konanDefaultSrcFiles get() = fileTree("${projectDir.canonicalPath}/src/main/kotlin")
internal fun Project.konanDefaultDefFile(libName: String)
= file("${projectDir.canonicalPath}/src/main/c_interop/$libName.def")
@Suppress("UNCHECKED_CAST")
internal val Project.konanArtifactsContainer: KonanArtifactContainer
get() = extensions.getByName(KonanPlugin.ARTIFACTS_CONTAINER_NAME) as KonanArtifactContainer
// TODO: The Kotlin/Native compiler is downloaded manually by a special task so the compilation tasks
// are configured without the compile distribution. After target management refactoring
// we need .properties files from the distribution to configure targets. This is worked around here
// by using HostManager instead of PlatformManager. But we need to download the compiler at the configuration
// stage (e.g. by getting it from maven as a plugin dependency) and bring back the PlatformManager here.
internal val Project.hostManager: HostManager
get() = findProperty("hostManager") as HostManager? ?:
if (hasProperty("org.jetbrains.kotlin.native.experimentalTargets"))
HostManager(buildDistribution(rootProject.rootDir.absolutePath), true)
else
HostManager(customerDistribution(konanHome))
internal val Project.konanTargets: List<KonanTarget>
get() = hostManager.toKonanTargets(konanExtension.targets)
.filter{ hostManager.isEnabled(it) }
.distinct()
@Suppress("UNCHECKED_CAST")
internal val Project.konanExtension: KonanExtension
get() = extensions.getByName(KonanPlugin.KONAN_EXTENSION_NAME) as KonanExtension
internal val Project.konanCompilerDownloadTask
get() = tasks.getByName(KonanPlugin.KONAN_DOWNLOAD_TASK_NAME)
internal val Project.requestedTargets
get() = findProperty(KonanPlugin.ProjectProperty.KONAN_BUILD_TARGETS)?.let {
it.toString().trim().split("\\s+".toRegex())
}.orEmpty()
internal val Project.jvmArgs
get() = (findProperty(KonanPlugin.ProjectProperty.KONAN_JVM_ARGS) as String?)?.split("\\s+".toRegex()).orEmpty()
internal val Project.compileAllTask
get() = getOrCreateTask(COMPILE_ALL_TASK_NAME)
internal fun Project.targetIsRequested(target: KonanTarget): Boolean {
val targets = requestedTargets
return (targets.isEmpty() || targets.contains(target.visibleName) || targets.contains("all"))
}
/** Looks for task with given name in the given project. Throws [UnknownTaskException] if there's not such task. */
private fun Project.getTask(name: String): Task = tasks.getByPath(name)
/**
* Looks for task with given name in the given project.
* If such task isn't found, will create it. Returns created/found task.
*/
private fun Project.getOrCreateTask(name: String): Task = with(tasks) {
findByPath(name) ?: create(name, DefaultTask::class.java)
}
internal fun Project.konanCompilerName(): String =
"kotlin-native-${project.simpleOsName}-${project.konanVersion}"
internal fun Project.konanCompilerDownloadDir(): String =
DependencyProcessor.localKonanDir.resolve(project.konanCompilerName()).absolutePath
// region Useful extensions and functions ---------------------------------------
internal fun MutableList<String>.addArg(parameter: String, value: String) {
add(parameter)
add(value)
}
internal fun MutableList<String>.addArgs(parameter: String, values: Iterable<String>) {
values.forEach {
addArg(parameter, it)
}
}
internal fun MutableList<String>.addArgIfNotNull(parameter: String, value: String?) {
if (value != null) {
addArg(parameter, value)
}
}
internal fun MutableList<String>.addKey(key: String, enabled: Boolean) {
if (enabled) {
add(key)
}
}
internal fun MutableList<String>.addFileArgs(parameter: String, values: FileCollection) {
values.files.forEach {
addArg(parameter, it.canonicalPath)
}
}
internal fun MutableList<String>.addFileArgs(parameter: String, values: Collection<FileCollection>) {
values.forEach {
addFileArgs(parameter, it)
}
}
// endregion
internal fun dumpProperties(task: Task) {
fun Iterable<String>.dump() = joinToString(prefix = "[", separator = ",\n${" ".repeat(22)}", postfix = "]")
fun Collection<FileCollection>.dump() = flatMap { it.files }.map { it.canonicalPath }.dump()
when (task) {
is KonanCompileTask -> with(task) {
println()
println("Compilation task: $name")
println("destinationDir : $destinationDir")
println("artifact : ${artifact.canonicalPath}")
println("srcFiles : ${srcFiles.dump()}")
println("produce : $produce")
println("libraries : ${libraries.files.dump()}")
println(" : ${libraries.artifacts.map {
it.artifact.canonicalPath
}.dump()}")
println(" : ${libraries.namedKlibs.dump()}")
println("nativeLibraries : ${nativeLibraries.dump()}")
println("linkerOpts : $linkerOpts")
println("enableDebug : $enableDebug")
println("noStdLib : $noStdLib")
println("noMain : $noMain")
println("enableOptimization : $enableOptimizations")
println("enableAssertions : $enableAssertions")
println("noDefaultLibs : $noDefaultLibs")
println("noEndorsedLibs : $noEndorsedLibs")
println("target : $target")
println("languageVersion : $languageVersion")
println("apiVersion : $apiVersion")
println("konanVersion : ${CompilerVersion.CURRENT}")
println("konanHome : $konanHome")
println()
}
is KonanInteropTask -> with(task) {
println()
println("Stub generation task: $name")
println("destinationDir : $destinationDir")
println("artifact : $artifact")
println("libraries : ${libraries.files.dump()}")
println(" : ${libraries.artifacts.map {
it.artifact.canonicalPath
}.dump()}")
println(" : ${libraries.namedKlibs.dump()}")
println("defFile : $defFile")
println("target : $target")
println("packageName : $packageName")
println("compilerOpts : $compilerOpts")
println("linkerOpts : $linkerOpts")
println("headers : ${headers.dump()}")
println("linkFiles : ${linkFiles.dump()}")
println("konanVersion : ${CompilerVersion.CURRENT}")
println("konanHome : $konanHome")
println()
}
else -> {
println("Unsupported task.")
}
}
}
open class KonanExtension {
var targets = mutableListOf("host")
var languageVersion: String? = null
var apiVersion: String? = null
var jvmArgs = mutableListOf<String>()
}
open class KonanSoftwareComponent(val project: ProjectInternal?): SoftwareComponentInternal, ComponentWithVariants {
private val usages = mutableSetOf<UsageContext>()
override fun getUsages(): MutableSet<out UsageContext> = usages
private val variants = mutableSetOf<SoftwareComponent>()
override fun getName() = "main"
override fun getVariants(): Set<SoftwareComponent> = variants
fun addVariant(component: SoftwareComponent) = variants.add(component)
}
class KonanPlugin @Inject constructor(private val registry: ToolingModelBuilderRegistry)
: Plugin<ProjectInternal> {
enum class ProjectProperty(val propertyName: String, val deprecatedPropertyName: String? = null) {
KONAN_HOME ("org.jetbrains.kotlin.native.home", "konan.home"),
KONAN_VERSION ("org.jetbrains.kotlin.native.version"),
KONAN_BUILD_TARGETS ("konan.build.targets"),
KONAN_JVM_ARGS ("konan.jvmArgs"),
KONAN_USE_ENVIRONMENT_VARIABLES("konan.useEnvironmentVariables"),
DOWNLOAD_COMPILER ("download.compiler"),
// Properties used instead of env vars until https://github.com/gradle/gradle/issues/3468 is fixed.
// TODO: Remove them when an API for env vars is provided.
KONAN_CONFIGURATION_BUILD_DIR ("konan.configuration.build.dir"),
KONAN_DEBUGGING_SYMBOLS ("konan.debugging.symbols"),
KONAN_OPTIMIZATIONS_ENABLE ("konan.optimizations.enable"),
}
companion object {
internal const val ARTIFACTS_CONTAINER_NAME = "konanArtifacts"
internal const val KONAN_DOWNLOAD_TASK_NAME = "checkKonanCompiler"
internal const val KONAN_GENERATE_CMAKE_TASK_NAME = "generateCMake"
internal const val COMPILE_ALL_TASK_NAME = "compileKonan"
internal const val KONAN_EXTENSION_NAME = "konan"
internal val REQUIRED_GRADLE_VERSION = GradleVersion.version("4.7")
}
private fun Project.cleanKonan() = project.tasks.withType(KonanBuildingTask::class.java).forEach {
project.delete(it.artifact)
}
private fun checkGradleVersion() = GradleVersion.current().let { current ->
check(current >= REQUIRED_GRADLE_VERSION) {
"Kotlin/Native Gradle plugin is incompatible with this version of Gradle.\n" +
"The minimal required version is $REQUIRED_GRADLE_VERSION\n" +
"Current version is ${current}"
}
}
override fun apply(project: ProjectInternal?) {
if (project == null) {
return
}
checkGradleVersion()
project.plugins.apply("base")
// Create necessary tasks and extensions.
project.tasks.create(KONAN_DOWNLOAD_TASK_NAME, KonanCompilerDownloadTask::class.java)
project.extensions.create(KONAN_EXTENSION_NAME, KonanExtension::class.java)
val container = project.extensions.create(
KonanArtifactContainer::class.java,
ARTIFACTS_CONTAINER_NAME,
KonanArtifactContainer::class.java,
project
)
project.warnAboutDeprecatedProperty(ProjectProperty.KONAN_HOME)
// Set additional project properties like org.jetbrains.kotlin.native.home, konan.build.targets etc.
if (!project.hasProperty(ProjectProperty.KONAN_HOME)) {
project.setProperty(ProjectProperty.KONAN_HOME, project.konanCompilerDownloadDir())
project.setProperty(ProjectProperty.DOWNLOAD_COMPILER, true)
}
// Create and set up aggregate building tasks.
val compileKonanTask = project.getOrCreateTask(COMPILE_ALL_TASK_NAME).apply {
group = BasePlugin.BUILD_GROUP
description = "Compiles all the Kotlin/Native artifacts"
}
project.getTask("build").apply {
dependsOn(compileKonanTask)
}
project.getTask("clean").apply {
doLast { project.cleanKonan() }
}
project.afterEvaluate {
project.tasks
.withType(KonanCompileProgramTask::class.java)
.forEach { task ->
val isCrossCompile = (task.target != HostManager.host.visibleName)
if (!isCrossCompile && !project.hasProperty("konanNoRun"))
task.runTask = project.tasks.register("run${task.artifactName.capitalize()}", Exec::class.java) {
it.group= "run"
it.dependsOn(task)
val artifactPathClosure = object : Closure<String>(this) {
override fun call() = task.artifactPath
}
// Use GString to evaluate a path to the artifact lazily thus allow changing it at configuration phase.
val lazyArtifactPath = GStringImpl(arrayOf(artifactPathClosure), arrayOf(""))
it.executable(lazyArtifactPath)
// Add values passed in the runArgs project property as arguments.
it.argumentProviders.add(task.RunArgumentProvider())
}
}
}
val runTask = project.getOrCreateTask("run")
project.afterEvaluate {
project.konanArtifactsContainer
.filterIsInstance(KonanProgram::class.java)
.forEach { program ->
program.tasks().forEach { compile ->
compile.configure { it.runTask?.let { runTask.dependsOn(it) } }
}
}
}
// Enable multiplatform support
project.pluginManager.apply(KotlinNativePlatformPlugin::class.java)
project.afterEvaluate {
project.pluginManager.withPlugin("maven-publish") {
container.all { buildingConfig ->
val konanSoftwareComponent = buildingConfig.mainVariant
project.extensions.configure(PublishingExtension::class.java) {
val builtArtifact = buildingConfig.name
val mavenPublication = it.publications.maybeCreate(builtArtifact, MavenPublication::class.java)
mavenPublication.apply {
artifactId = builtArtifact
groupId = project.group.toString()
from(konanSoftwareComponent)
}
(mavenPublication as MavenPublicationInternal).publishWithOriginalFileName()
buildingConfig.pomActions.forEach {
mavenPublication.pom(it)
}
}
project.extensions.configure(PublishingExtension::class.java) {
val publishing = it
for (v in konanSoftwareComponent.variants) {
publishing.publications.create(v.name, MavenPublication::class.java) { mavenPublication ->
val coordinates = (v as NativeVariantIdentity).coordinates
project.logger.info("variant with coordinates($coordinates) and module: ${coordinates.module}")
mavenPublication.artifactId = coordinates.module.name
mavenPublication.groupId = coordinates.group
mavenPublication.version = coordinates.version
mavenPublication.from(v)
(mavenPublication as MavenPublicationInternal).publishWithOriginalFileName()
buildingConfig.pomActions.forEach {
mavenPublication.pom(it)
}
}
}
}
}
}
}
}
}
|
apache-2.0
|
478a9b9bff71d25209f43410abaa5a4a
| 44.715262 | 127 | 0.648662 | 5.073054 | false | false | false | false |
K0zka/kerub
|
src/main/kotlin/com/github/kerubistan/kerub/hypervisor/kvm/Utils.kt
|
1
|
4658
|
package com.github.kerubistan.kerub.hypervisor.kvm
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.VirtualMachine
import com.github.kerubistan.kerub.model.VirtualStorageLinkInfo
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageLvmAllocation
import com.github.kerubistan.kerub.model.services.IscsiService
import com.github.kerubistan.kerub.model.services.NfsService
import com.github.kerubistan.kerub.utils.storage.iscsiStorageId
import com.github.kerubistan.kerub.utils.storage.iscsiDefaultUser as iscsiUser
fun storagesToXml(disks: List<VirtualStorageLinkInfo>, targetHost: Host): String {
return buildString(disks.size * 256) {
var targetDev = 'a'
for (link in disks) {
append(storageToXml(link, targetHost, targetDev))
targetDev++
}
}
}
val allocationTypeToDiskType = mapOf(
VirtualStorageFsAllocation::class to "file",
VirtualStorageLvmAllocation::class to "block"
)
private fun storageToXml(
linkInfo: VirtualStorageLinkInfo, targetHost: Host, targetDev: Char): String = """
<disk type='${kvmDeviceType(linkInfo, targetHost)}' device='${linkInfo.link.device.name.toLowerCase()}'>
<driver name='qemu' type='${allocationType(linkInfo)}' cache='none'/>
${if (linkInfo.device.stat.readOnly || linkInfo.link.readOnly) "<readonly/>" else ""}
${allocationToXml(linkInfo, targetHost)}
<target dev='sd$targetDev' bus='${linkInfo.link.bus}'/>
</disk>
"""
private fun kvmDeviceType(linkInfo: VirtualStorageLinkInfo, targetHost: Host): String =
if (isRemoteHost(linkInfo, targetHost)) {
when (linkInfo.hostServiceUsed) {
is NfsService -> "file"
is IscsiService -> "network"
else -> TODO("not handled service type: $linkInfo")
}
} else {
allocationTypeToDiskType[linkInfo.allocation.javaClass.kotlin] ?: TODO()
}
fun allocationType(deviceDyn: VirtualStorageLinkInfo): String = deviceDyn.allocation.let {
when (it) {
is VirtualStorageLvmAllocation -> "raw"
is VirtualStorageFsAllocation -> it.type.name.toLowerCase()
else -> TODO("")
}
}
fun allocationToXml(linkInfo: VirtualStorageLinkInfo, targetHost: Host): String =
if (isRemoteHost(linkInfo, targetHost)) {
when (linkInfo.hostServiceUsed) {
is NfsService ->
"""
<!-- nfs -->
<source file='/mnt/${linkInfo.allocation.hostId}/${linkInfo.allocation.getPath(linkInfo.device.stat.id)}'/>
""".trimIndent()
is IscsiService -> {
val auth = if (linkInfo.hostServiceUsed.password != null) {
"""
<auth username="$iscsiUser">
<secret type='iscsi' uuid='${linkInfo.device.stat.id}'/>
</auth>
""".trimIndent()
} else "<!-- unauthenticated -->"
"""
<!-- iscsi -->
<source protocol='iscsi' name='${iscsiStorageId(linkInfo.device.stat.id)}/1'>
<host name='${linkInfo.storageHost.stat.address}' port='3260' />
</source>
$auth
""".trimIndent()
}
else -> TODO("not handled service type: $linkInfo")
}
} else {
val allocation = linkInfo.allocation
when (allocation) {
is VirtualStorageFsAllocation ->
"""
<!-- local ${allocation.type} file allocation -->
<source file='${allocation.fileName}'/>
""".trimIndent()
is VirtualStorageLvmAllocation ->
"""
<!-- local lvm allocation -->
<source dev='${allocation.path}'/>
""".trimMargin()
else -> TODO()
}
}
fun isRemoteHost(linkInfo: VirtualStorageLinkInfo, targetHost: Host) = linkInfo.allocation.hostId != targetHost.id
fun vmDefinitiontoXml(
vm: VirtualMachine, disks: List<VirtualStorageLinkInfo>, password: String, targetHost: Host
): String =
"""
<domain type='kvm'>
<name>${vm.id}</name>
<uuid>${vm.id}</uuid>
<memory unit='B'>${vm.memory.min}</memory>
<memtune>
<hard_limit unit='B'>${vm.memory.min}</hard_limit>
</memtune>
<memoryBacking>
<allocation mode="ondemand"/>
</memoryBacking>
<vcpu>${vm.nrOfCpus}</vcpu>
<os>
<type arch='x86_64'>hvm</type>
<boot dev='hd'/>
<boot dev='cdrom'/>
</os>
<features>
<acpi/>
<apic/>
<pae/>
<hap/>
</features>
<devices>
<input type='keyboard' bus='ps2'/>
<graphics type='spice' autoport='yes' listen='0.0.0.0' passwd='$password'>
<listen type='address' address='0.0.0.0'/>
<image compression='off'/>
</graphics>
<video>
<model type='qxl' ram='65536' vram='65536' vgamem='16384' heads='1'/>
<address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
</video>
${storagesToXml(disks, targetHost)}
</devices>
</domain>
"""
|
apache-2.0
|
6f6b14854a45ea34b4dcc78dbabfa74f
| 31.802817 | 114 | 0.676685 | 3.512821 | false | false | false | false |
bjansen/pebble-intellij
|
src/main/kotlin/com/github/bjansen/intellij/pebble/psi/PebbleComment.kt
|
1
|
3632
|
package com.github.bjansen.intellij.pebble.psi
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.impl.source.resolve.reference.impl.providers.JavaClassReferenceProvider
import com.intellij.psi.impl.source.tree.PsiCommentImpl
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.tree.IElementType
class PebbleComment(type: IElementType, text: CharSequence) : PsiCommentImpl(type, text), PsiNamedElement {
override fun setName(name: String): PsiElement {
val nameRange = getValueRange(text, "name")
if (nameRange != null) {
val newText = nameRange.replace(text, name)
return replace(PsiElementFactory.createComment(newText, project))
}
return this
}
override fun getName(): String? {
return extractValue(text, "name")
}
companion object {
fun getImplicitVariable(comment: PebbleComment): ImplicitVariable? {
if (comment.text.contains("@pebvariable")) {
val name = extractValue(comment.text, "name")
val type = extractValue(comment.text, "type")
if (name != null && PsiNameHelper.getInstance(comment.project).isIdentifier(name)
&& type != null && type.isNotEmpty()) {
val fragment = JavaCodeFragmentFactory.getInstance(comment.project)
.createTypeCodeFragment(type, null, false)
fragment.forceResolveScope(comment.resolveScope)
try {
return PebbleImplicitVariable(name, fragment.type, comment.containingFile, comment)
} catch (e: PsiTypeCodeFragment.IncorrectTypeException) {
e.printStackTrace()
}
}
}
return null
}
private fun extractValue(text: String, key: String): String? {
val range = getValueRange(text, key)
return range?.substring(text)
}
private fun getValueRange(text: String, key: String): TextRange? {
val prefix = "$key=\""
val start = text.indexOf(prefix)
if (start >= 0) {
val stop = text.indexOf("\"", start + prefix.length)
if (stop >= 0) {
return TextRange(start + prefix.length, stop)
}
}
return null
}
}
override fun getReferences(): Array<PsiReference> {
val refs = arrayListOf<PsiReference>()
if (text.contains("@pebvariable")) {
val nameRange = getValueRange(text, "name")
if (nameRange != null) {
refs.add(PebbleCommentReference(this, nameRange))
}
val typeRange = getValueRange(text, "type")
if (typeRange != null) {
refs.addAll(JavaClassReferenceProvider().getReferencesByString(typeRange.substring(text), this, typeRange.startOffset))
}
}
return refs.toTypedArray()
}
override fun processDeclarations(
processor: PsiScopeProcessor,
state: ResolveState,
lastParent: PsiElement?,
place: PsiElement
): Boolean {
val implicitVariable = getImplicitVariable(this)
if (implicitVariable != null) {
return processor.execute(implicitVariable, state)
}
return true
}
}
class PebbleCommentReference(comment: PebbleComment, range: TextRange)
: PsiReferenceBase.Immediate<PebbleComment>(comment, range, comment)
|
mit
|
38acaf9719a93d138e20201ca9844e9d
| 33.264151 | 135 | 0.597192 | 5.101124 | false | false | false | false |
apollographql/apollo-android
|
apollo-normalized-cache-sqlite/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/sql/internal/CacheQueriesHelpers.kt
|
1
|
3661
|
package com.apollographql.apollo3.cache.normalized.sql.internal
import com.apollographql.apollo3.cache.normalized.api.Record
import com.apollographql.apollo3.cache.normalized.api.RecordFieldJsonAdapter
import com.apollographql.apollo3.cache.normalized.sql.CacheQueries
internal object CacheQueriesHelpers {
fun CacheQueries.selectRecord(key: String): Record? {
return recordForKey(key)
.executeAsList()
.firstOrNull()
?.let {
Record(
key = it.key,
fields = RecordFieldJsonAdapter.fromJson(it.record)!!,
)
}
}
fun CacheQueries.selectRecords(keys: Collection<String>): Collection<Record> {
return keys.chunked(999).flatMap { chunkedKeys ->
recordsForKeys(chunkedKeys)
.executeAsList()
.map {
Record(
key = it.key,
fields = RecordFieldJsonAdapter.fromJson(it.record)!!,
)
}
}
}
fun CacheQueries.updateRecords(records: Collection<Record>): Set<String> {
var updatedRecordKeys: Set<String> = emptySet()
transaction {
val oldRecords = selectRecords(
keys = records.map { it.key },
).associateBy { it.key }
updatedRecordKeys = records.flatMap { record ->
val oldRecord = oldRecords[record.key]
if (oldRecord == null) {
insert(
key = record.key,
record = RecordFieldJsonAdapter.toJson(record.fields),
)
record.fieldKeys()
} else {
val (mergedRecord, changedKeys) = oldRecord.mergeWith(record)
if (mergedRecord.isNotEmpty()) {
update(
key = oldRecord.key,
record = RecordFieldJsonAdapter.toJson(mergedRecord.fields),
)
}
changedKeys
}
}.toSet()
}
return updatedRecordKeys
}
fun CacheQueries.updateRecord(record: Record): Set<String> {
var updatedRecordKeys: Set<String> = emptySet()
transaction {
val oldRecord = selectRecord(record.key)
updatedRecordKeys = if (oldRecord == null) {
insert(
key = record.key,
record = RecordFieldJsonAdapter.toJson(record.fields),
)
record.fieldKeys()
} else {
val (mergedRecord, changedKeys) = oldRecord.mergeWith(record)
if (mergedRecord.isNotEmpty()) {
update(
key = oldRecord.key,
record = RecordFieldJsonAdapter.toJson(mergedRecord.fields),
)
}
changedKeys
}
}
return updatedRecordKeys
}
fun CacheQueries.remove(pattern: String): Int {
var result = 0L
transaction {
deleteRecordsWithKeyMatching(pattern, "\\")
result = changes().executeAsOne()
}
return result.toInt()
}
fun CacheQueries.deleteRecord(key: String, cascade: Boolean): Boolean {
var result = false
transaction {
result = if (cascade) {
selectRecord(key)
?.referencedFields()
?.all {
deleteRecord(
key = it.key,
cascade = true,
)
}
?: false
} else {
delete(key)
changes().executeAsOne() > 0
}
}
return result
}
fun CacheQueries.deleteAllRecords() {
transaction {
deleteAll()
}
}
fun CacheQueries.selectAllRecords(): Map<String, Record> {
return selectRecords().executeAsList().map {
it.key to Record(
key = it.key,
fields = RecordFieldJsonAdapter.fromJson(it.record)!!,
)
}.toMap()
}
}
|
mit
|
d515d339af6d70a9fa47fa62a2fbc5bd
| 26.526316 | 80 | 0.577711 | 4.817105 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.