repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shlusiak/Freebloks-Android
|
game/src/main/java/de/saschahlusiak/freebloks/model/Game.kt
|
1
|
3338
|
package de.saschahlusiak.freebloks.model
import de.saschahlusiak.freebloks.model.Board.Companion.PLAYER_MAX
import java.io.Serializable
import java.util.*
/**
* A "game" contains everything about the state of a game, i.e. board, current player, type of players,
* game mode, game status.
*
* These information are usually updated via the [GameClientMessageHandler].
*
* @param board the board state
*/
class Game(val board: Board = Board()): Serializable {
/**
* The current player, or -1 if none.
*/
var currentPlayer = -1
/**
* For each player, whether it is controlled locally or remotely (aka computer)
*/
val playerTypes = IntArray(PLAYER_MAX) { PLAYER_COMPUTER }
/**
* The current game mode
*/
var gameMode = GameMode.GAMEMODE_4_COLORS_4_PLAYERS
/**
* Whether the game is officially over
*/
var isFinished = false
/**
* false if still in lobby, true if started, also true if finished
*/
var isStarted = false
/**
* The history of [Turn]
*/
val history = Turnpool()
/**
* @param player the player number to check or currentPlayer
* @return true if the given player is played on the local device
*/
fun isLocalPlayer(player: Int = currentPlayer): Boolean {
return if (player == -1) false else playerTypes[player] != PLAYER_COMPUTER
}
/**
* Set the given player number to either [PLAYER_COMPUTER] or [PLAYER_LOCAL].
*
* All remotely played users are from our point of view computer players.
*/
fun setPlayerType(player: Int, playerType: Int) {
playerTypes[player] = playerType
}
/**
* Build and return the end-of-game scores.
*
* Note that calling this function will populate the place of the players,
* something which [Board.calculatePlayerScore] does not.
*/
fun getPlayerScores(): List<PlayerScore> {
val scores = board.player.map { it.scores }
val data = when (gameMode) {
GameMode.GAMEMODE_2_COLORS_2_PLAYERS,
GameMode.GAMEMODE_DUO,
GameMode.GAMEMODE_JUNIOR -> {
arrayOf(
scores[0],
scores[2]
)
}
GameMode.GAMEMODE_4_COLORS_2_PLAYERS -> {
arrayOf(
PlayerScore(scores[0], scores[2]),
PlayerScore(scores[1], scores[3])
)
}
GameMode.GAMEMODE_4_COLORS_4_PLAYERS -> {
arrayOf(
scores[0],
scores[1],
scores[2],
scores[3]
)
}
}.sorted()
// first everybody gets the natural place number
data.forEachIndexed { index, p ->
p.place = index + 1
p.isLocal = isLocalPlayer(p.color1)
}
// then give everybody with equal points the same place
for (i in 1 until data.size) {
if (data[i].compareTo(data[i - 1]) == 0)
data[i].place = data[i - 1].place
}
return data
}
companion object {
private const val serialVersionUID = 1L
const val PLAYER_COMPUTER = -2
const val PLAYER_LOCAL = -1
}
}
|
gpl-2.0
|
9f6da1c36721897d83cf66c2ea00ce65
| 27.29661 | 103 | 0.561114 | 4.421192 | false | false | false | false |
tibbi/Simple-Calculator
|
app/src/main/kotlin/com/simplemobiletools/calculator/helpers/CalculatorImpl.kt
|
1
|
6219
|
package com.simplemobiletools.calculator.helpers
import android.content.Context
import com.simplemobiletools.calculator.R
import com.simplemobiletools.calculator.operation.OperationFactory
class CalculatorImpl(calculator: Calculator, val context: Context) {
var displayedNumber: String? = null
var displayedFormula: String? = null
var lastKey: String? = null
private var mLastOperation: String? = null
private var mCallback: Calculator? = calculator
private var mIsFirstOperation = false
private var mResetValue = false
private var mWasPercentLast = false
private var mBaseValue = 0.0
private var mSecondValue = 0.0
init {
resetValues()
setValue("0")
setFormula("")
}
private fun resetValueIfNeeded() {
if (mResetValue)
displayedNumber = "0"
mResetValue = false
}
private fun resetValues() {
mBaseValue = 0.0
mSecondValue = 0.0
mResetValue = false
mLastOperation = ""
displayedNumber = ""
displayedFormula = ""
mIsFirstOperation = true
lastKey = ""
}
fun setValue(value: String) {
mCallback!!.setValue(value, context)
displayedNumber = value
}
private fun setFormula(value: String) {
mCallback!!.setFormula(value, context)
displayedFormula = value
}
private fun updateFormula() {
val first = Formatter.doubleToString(mBaseValue)
val second = Formatter.doubleToString(mSecondValue)
val sign = getSign(mLastOperation)
if (sign == "√") {
setFormula(sign + first)
} else if (sign == "!") {
setFormula(first + sign)
} else if (!sign.isEmpty()) {
var formula = first + sign + second
if (mWasPercentLast) {
formula += "%"
}
setFormula(formula)
}
}
fun addDigit(number: Int) {
val currentValue = displayedNumber
val newValue = formatString(currentValue!! + number)
setValue(newValue)
}
private fun formatString(str: String): String {
// if the number contains a decimal, do not try removing the leading zero anymore, nor add group separator
// it would prevent writing values like 1.02
if (str.contains(".")) {
return str
}
val doubleValue = Formatter.stringToDouble(str)
return Formatter.doubleToString(doubleValue)
}
private fun updateResult(value: Double) {
setValue(Formatter.doubleToString(value))
mBaseValue = value
}
private fun getDisplayedNumberAsDouble() = Formatter.stringToDouble(displayedNumber!!)
fun handleResult() {
mSecondValue = getDisplayedNumberAsDouble()
calculateResult()
mBaseValue = getDisplayedNumberAsDouble()
}
private fun handleRoot() {
mBaseValue = getDisplayedNumberAsDouble()
calculateResult()
}
private fun handleFactorial() {
mBaseValue = getDisplayedNumberAsDouble()
calculateResult()
}
private fun calculateResult() {
updateFormula()
if (mWasPercentLast) {
mSecondValue *= mBaseValue / 100
}
val operation = OperationFactory.forId(mLastOperation!!, mBaseValue, mSecondValue)
if (operation != null) {
updateResult(operation.getResult())
}
mIsFirstOperation = false
}
fun handleOperation(operation: String) {
mWasPercentLast = operation == PERCENT
if (lastKey == DIGIT && operation != ROOT && operation != FACTORIAL) {
handleResult()
}
mResetValue = true
lastKey = operation
mLastOperation = operation
if (operation == ROOT) {
handleRoot()
mResetValue = false
}
if (operation == FACTORIAL) {
handleFactorial()
mResetValue = false
}
}
fun handleClear() {
if (displayedNumber.equals(NAN)) {
handleReset()
} else {
val oldValue = displayedNumber
var newValue = "0"
val len = oldValue!!.length
var minLen = 1
if (oldValue.contains("-"))
minLen++
if (len > minLen) {
newValue = oldValue.substring(0, len - 1)
}
newValue = newValue.replace("\\.$".toRegex(), "")
newValue = formatString(newValue)
setValue(newValue)
mBaseValue = Formatter.stringToDouble(newValue)
}
}
fun handleReset() {
resetValues()
setValue("0")
setFormula("")
}
fun handleEquals() {
if (lastKey == EQUALS)
calculateResult()
if (lastKey != DIGIT)
return
mSecondValue = getDisplayedNumberAsDouble()
calculateResult()
lastKey = EQUALS
}
private fun decimalClicked() {
var value = displayedNumber
if (!value!!.contains(".")) {
value += "."
}
setValue(value)
}
private fun zeroClicked() {
val value = displayedNumber
if (value != "0") {
addDigit(0)
}
}
private fun getSign(lastOperation: String?) = when (lastOperation) {
PLUS -> "+"
MINUS -> "-"
MULTIPLY -> "*"
DIVIDE -> "/"
PERCENT -> "%"
POWER -> "^"
ROOT -> "√"
FACTORIAL -> "!"
else -> ""
}
fun numpadClicked(id: Int) {
if (lastKey == EQUALS) {
mLastOperation = EQUALS
}
lastKey = DIGIT
resetValueIfNeeded()
when (id) {
R.id.btn_decimal -> decimalClicked()
R.id.btn_0 -> zeroClicked()
R.id.btn_1 -> addDigit(1)
R.id.btn_2 -> addDigit(2)
R.id.btn_3 -> addDigit(3)
R.id.btn_4 -> addDigit(4)
R.id.btn_5 -> addDigit(5)
R.id.btn_6 -> addDigit(6)
R.id.btn_7 -> addDigit(7)
R.id.btn_8 -> addDigit(8)
R.id.btn_9 -> addDigit(9)
}
}
}
|
gpl-2.0
|
40699016dcea159ca538ca8e43574901
| 25.446809 | 114 | 0.5535 | 4.67997 | false | false | false | false |
codeka/wwmmo
|
client/src/main/kotlin/au/com/codeka/warworlds/client/opengl/Scene.kt
|
1
|
961
|
package au.com.codeka.warworlds.client.opengl
/**
* A [Scene] is basically a collection of [SceneObject]s that we'll be rendering.
*/
class Scene(val dimensionResolver: DimensionResolver, val textureManager: TextureManager) {
/** Gets the root [SceneObject] that you should add all your sprites and stuff to. */
val rootObject = SceneObject(dimensionResolver, "ROOT", scene = this)
val spriteShader = SpriteShader()
private val textTexture = TextTexture()
// All modifications to the scene (adding children, modifying children, etc) should happen while
// synchronized on this lock.
val lock = Any()
fun createSprite(tmpl: SpriteTemplate, debugName: String): Sprite {
return Sprite(dimensionResolver, debugName, tmpl)
}
fun createText(text: String): TextSceneObject {
return TextSceneObject(dimensionResolver, spriteShader, textTexture, text)
}
fun draw(camera: Camera) {
rootObject.draw(camera.viewProjMatrix)
}
}
|
mit
|
30cd44deb23f6a0862d02555275aadf0
| 34.592593 | 98 | 0.742976 | 4.106838 | false | false | false | false |
Undin/intellij-rust
|
src/main/kotlin/org/rust/ide/inspections/lints/RsUnusedMustUseInspection.kt
|
2
|
5426
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.lints
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.RsBundle
import org.rust.ide.annotator.getFunctionCallContext
import org.rust.ide.inspections.RsProblemsHolder
import org.rust.ide.utils.template.newTemplateBuilder
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.types.implLookupAndKnownItems
import org.rust.lang.core.types.ty.TyAdt
import org.rust.lang.core.types.type
import org.rust.openapiext.createSmartPointer
private fun RsExpr.returnsStdResult(): Boolean {
val (_, knownItems) = implLookupAndKnownItems
val type = type as? TyAdt ?: return false
return type.item == knownItems.Result
}
private class FixAddLetUnderscore(anchor: PsiElement) : LocalQuickFixAndIntentionActionOnPsiElement(anchor) {
override fun getFamilyName() = RsBundle.message("inspection.UnusedMustUse.FixAddLetUnderscore.name")
override fun getText() = familyName
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
val originalExpr = startElement as RsExpr
val letExpr = RsPsiFactory(project).createLetDeclaration("_", originalExpr)
val newLetExpr = originalExpr.parent.replace(letExpr) as RsLetDecl
val patPointer = newLetExpr.pat?.createSmartPointer() ?: return
val template = editor?.newTemplateBuilder(newLetExpr) ?: return
val pat = patPointer.element ?: return
template.replaceElement(pat)
template.runInline()
}
}
private class FixAddUnwrap : LocalQuickFix {
override fun getFamilyName() = RsBundle.message("inspection.UnusedMustUse.FixAddUnwrap.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expr = descriptor.psiElement as RsExpr
expr.replace(RsPsiFactory(project).createExpression("${expr.text}.unwrap()"))
}
}
private class FixAddExpect(anchor: PsiElement) : LocalQuickFixAndIntentionActionOnPsiElement(anchor) {
override fun getFamilyName() = RsBundle.message("inspection.UnusedMustUse.FixAddExpect.family.name")
override fun getText() = familyName
override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) {
val dotExpr = RsPsiFactory(project).createExpression("${startElement.text}.expect(\"\")")
val newDotExpr = startElement.replace(dotExpr) as RsDotExpr
val expectArgs = newDotExpr.methodCall?.valueArgumentList?.exprList
val stringLiteralPointer = (expectArgs?.singleOrNull() as RsLitExpr).createSmartPointer()
val template = editor?.newTemplateBuilder(newDotExpr) ?: return
val stringLiteral = stringLiteralPointer.element ?: return
val rangeWithoutQuotes = TextRange(1, stringLiteral.textRange.length - 1)
template.replaceElement(stringLiteral, rangeWithoutQuotes, "TODO: panic message")
template.runInline()
}
}
private class InspectionResult(val description: String, val fixes: List<LocalQuickFix>)
private fun inspectAndProposeFixes(expr: RsExpr): InspectionResult? {
val mustUseAttrName = "must_use"
val type = expr.type as? TyAdt
val func = when (expr) {
is RsDotExpr -> expr.methodCall?.getFunctionCallContext()?.function
is RsCallExpr -> expr.getFunctionCallContext()?.function
else -> null
}
val attrType = type?.item?.findFirstMetaItem(mustUseAttrName)
val attrFunc = func?.findFirstMetaItem(mustUseAttrName)
val description = when {
attrType != null -> RsBundle.message("inspection.UnusedMustUse.description.type.attribute", type)
attrFunc != null -> RsBundle.message("inspection.UnusedMustUse.description.function.attribute", func.name.toString())
else -> return null
}
val fixes: MutableList<LocalQuickFix> = mutableListOf(FixAddLetUnderscore(expr))
if (expr.returnsStdResult()) {
fixes += FixAddExpect(expr)
fixes += FixAddUnwrap()
}
return InspectionResult(description, fixes)
}
/** Analogue of rustc's unused_must_use. See also [RsDoubleMustUseInspection]. */
class RsUnusedMustUseInspection : RsLintInspection() {
override fun getLint(element: PsiElement) = RsLint.UnusedMustUse
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean) = object : RsVisitor() {
override fun visitExprStmt(o: RsExprStmt) {
super.visitExprStmt(o)
val parent = o.parent
if (parent is RsBlock) {
// Ignore if o is actually a tail expr
val (_, tailExpr) = parent.expandedStmtsAndTailExpr
if (o.expr == tailExpr) return
}
val problem = inspectAndProposeFixes(o.expr)
if (problem != null) {
holder.registerLintProblem(o.expr, problem.description, RsLintHighlightingType.WEAK_WARNING, problem.fixes)
}
}
}
}
|
mit
|
7eab25d2934477ee57598948e733da38
| 44.596639 | 125 | 0.729082 | 4.451189 | false | false | false | false |
kotlinx/kotlinx.html
|
src/commonMain/kotlin/generated/gen-enums.kt
|
1
|
14113
|
package kotlinx.html
import kotlinx.html.*
/*******************************************************************************
DO NOT EDIT
This file was generated by module generate
*******************************************************************************/
@Suppress("unused")
enum class Dir(override val realValue : String) : AttributeEnum {
ltr("ltr"),
rtl("rtl")
}
internal val dirValues : Map<String, Dir> = Dir.values().associateBy { it.realValue }
@Suppress("unused")
enum class Draggable(override val realValue : String) : AttributeEnum {
htmlTrue("true"),
htmlFalse("false"),
auto("auto")
}
internal val draggableValues : Map<String, Draggable> = Draggable.values().associateBy { it.realValue }
@Suppress("unused")
enum class RunAt(override val realValue : String) : AttributeEnum {
server("server")
}
internal val runAtValues : Map<String, RunAt> = RunAt.values().associateBy { it.realValue }
@Suppress("unused")
object ATarget {
val blank : String = "_blank"
val parent : String = "_parent"
val self : String = "_self"
val top : String = "_top"
val values : List<String> = listOf("blank", "parent", "self", "top")
}
@Suppress("unused")
object ARel {
val alternate : String = "Alternate"
val appEndIx : String = "Appendix"
val bookmark : String = "Bookmark"
val chapter : String = "Chapter"
val contentS : String = "Contents"
val copyright : String = "Copyright"
val glossary : String = "Glossary"
val help : String = "Help"
val index : String = "Index"
val next : String = "Next"
val prev : String = "Prev"
val section : String = "Section"
val start : String = "Start"
val stylesheet : String = "Stylesheet"
val subsection : String = "Subsection"
val values : List<String> = listOf("alternate", "appEndIx", "bookmark", "chapter", "contentS", "copyright", "glossary", "help", "index", "next", "prev", "section", "start", "stylesheet", "subsection")
}
@Suppress("unused")
object AType {
val textAsp : String = "text/asp"
val textAsa : String = "text/asa"
val textCss : String = "text/css"
val textHtml : String = "text/html"
val textJavaScript : String = "text/javascript"
val textPlain : String = "text/plain"
val textScriptLet : String = "text/scriptlet"
val textXComponent : String = "text/x-component"
val textXHtmlInsertion : String = "text/x-html-insertion"
val textXml : String = "text/xml"
val values : List<String> = listOf("textAsp", "textAsa", "textCss", "textHtml", "textJavaScript", "textPlain", "textScriptLet", "textXComponent", "textXHtmlInsertion", "textXml")
}
@Suppress("unused")
enum class AreaShape(override val realValue : String) : AttributeEnum {
rect("rect"),
circle("circle"),
poly("poly"),
default("default")
}
internal val areaShapeValues : Map<String, AreaShape> = AreaShape.values().associateBy { it.realValue }
@Suppress("unused")
object AreaTarget {
val blank : String = "_blank"
val parent : String = "_parent"
val self : String = "_self"
val top : String = "_top"
val values : List<String> = listOf("blank", "parent", "self", "top")
}
@Suppress("unused")
object AreaRel {
val alternate : String = "Alternate"
val appEndIx : String = "Appendix"
val bookmark : String = "Bookmark"
val chapter : String = "Chapter"
val contentS : String = "Contents"
val copyright : String = "Copyright"
val glossary : String = "Glossary"
val help : String = "Help"
val index : String = "Index"
val next : String = "Next"
val prev : String = "Prev"
val section : String = "Section"
val start : String = "Start"
val stylesheet : String = "Stylesheet"
val subsection : String = "Subsection"
val values : List<String> = listOf("alternate", "appEndIx", "bookmark", "chapter", "contentS", "copyright", "glossary", "help", "index", "next", "prev", "section", "start", "stylesheet", "subsection")
}
@Suppress("unused")
object BaseTarget {
val blank : String = "_blank"
val parent : String = "_parent"
val self : String = "_self"
val top : String = "_top"
val values : List<String> = listOf("blank", "parent", "self", "top")
}
@Suppress("unused")
enum class ButtonFormEncType(override val realValue : String) : AttributeEnum {
multipartFormData("multipart/form-data"),
applicationXWwwFormUrlEncoded("application/x-www-form-urlencoded"),
textPlain("text/plain")
}
internal val buttonFormEncTypeValues : Map<String, ButtonFormEncType> = ButtonFormEncType.values().associateBy { it.realValue }
@Suppress("unused")
enum class ButtonFormMethod(override val realValue : String) : AttributeEnum {
get("get"),
post("post"),
@Deprecated("method is not allowed in browsers") put("put"),
@Deprecated("method is not allowed in browsers") delete("delete"),
@Deprecated("method is not allowed in browsers") patch("patch")
}
internal val buttonFormMethodValues : Map<String, ButtonFormMethod> = ButtonFormMethod.values().associateBy { it.realValue }
@Suppress("unused")
object ButtonFormTarget {
val blank : String = "_blank"
val parent : String = "_parent"
val self : String = "_self"
val top : String = "_top"
val values : List<String> = listOf("blank", "parent", "self", "top")
}
@Suppress("unused")
enum class ButtonType(override val realValue : String) : AttributeEnum {
button("button"),
reset("reset"),
submit("submit")
}
internal val buttonTypeValues : Map<String, ButtonType> = ButtonType.values().associateBy { it.realValue }
@Suppress("unused")
enum class CommandType(override val realValue : String) : AttributeEnum {
command("command"),
checkBox("checkbox"),
radio("radio")
}
internal val commandTypeValues : Map<String, CommandType> = CommandType.values().associateBy { it.realValue }
@Suppress("unused")
enum class FormEncType(override val realValue : String) : AttributeEnum {
multipartFormData("multipart/form-data"),
applicationXWwwFormUrlEncoded("application/x-www-form-urlencoded"),
textPlain("text/plain")
}
internal val formEncTypeValues : Map<String, FormEncType> = FormEncType.values().associateBy { it.realValue }
@Suppress("unused")
enum class FormMethod(override val realValue : String) : AttributeEnum {
get("get"),
post("post"),
@Deprecated("method is not allowed in browsers") put("put"),
@Deprecated("method is not allowed in browsers") delete("delete"),
@Deprecated("method is not allowed in browsers") patch("patch")
}
internal val formMethodValues : Map<String, FormMethod> = FormMethod.values().associateBy { it.realValue }
@Suppress("unused")
object FormTarget {
val blank : String = "_blank"
val parent : String = "_parent"
val self : String = "_self"
val top : String = "_top"
val values : List<String> = listOf("blank", "parent", "self", "top")
}
@Suppress("unused")
object IframeName {
val blank : String = "_blank"
val parent : String = "_parent"
val self : String = "_self"
val top : String = "_top"
val values : List<String> = listOf("blank", "parent", "self", "top")
}
@Suppress("unused")
enum class IframeSandbox(override val realValue : String) : AttributeEnum {
allowSameOrigin("allow-same-origin"),
allowFormS("allow-forms"),
allowScripts("allow-scripts")
}
internal val iframeSandboxValues : Map<String, IframeSandbox> = IframeSandbox.values().associateBy { it.realValue }
@Suppress("unused")
enum class InputType(override val realValue : String) : AttributeEnum {
button("button"),
checkBox("checkbox"),
color("color"),
date("date"),
dateTime("datetime"),
dateTimeLocal("datetime-local"),
email("email"),
file("file"),
hidden("hidden"),
image("image"),
month("month"),
number("number"),
password("password"),
radio("radio"),
range("range"),
reset("reset"),
search("search"),
submit("submit"),
text("text"),
tel("tel"),
time("time"),
url("url"),
week("week")
}
internal val inputTypeValues : Map<String, InputType> = InputType.values().associateBy { it.realValue }
@Suppress("unused")
enum class InputFormEncType(override val realValue : String) : AttributeEnum {
multipartFormData("multipart/form-data"),
applicationXWwwFormUrlEncoded("application/x-www-form-urlencoded"),
textPlain("text/plain")
}
internal val inputFormEncTypeValues : Map<String, InputFormEncType> = InputFormEncType.values().associateBy { it.realValue }
@Suppress("unused")
enum class InputFormMethod(override val realValue : String) : AttributeEnum {
get("get"),
post("post"),
@Deprecated("method is not allowed in browsers") put("put"),
@Deprecated("method is not allowed in browsers") delete("delete"),
@Deprecated("method is not allowed in browsers") patch("patch")
}
internal val inputFormMethodValues : Map<String, InputFormMethod> = InputFormMethod.values().associateBy { it.realValue }
@Suppress("unused")
object InputFormTarget {
val blank : String = "_blank"
val parent : String = "_parent"
val self : String = "_self"
val top : String = "_top"
val values : List<String> = listOf("blank", "parent", "self", "top")
}
@Suppress("unused")
enum class KeyGenKeyType(override val realValue : String) : AttributeEnum {
rsa("rsa")
}
internal val keyGenKeyTypeValues : Map<String, KeyGenKeyType> = KeyGenKeyType.values().associateBy { it.realValue }
@Suppress("unused")
object LinkRel {
val alternate : String = "Alternate"
val appEndIx : String = "Appendix"
val bookmark : String = "Bookmark"
val chapter : String = "Chapter"
val contentS : String = "Contents"
val copyright : String = "Copyright"
val glossary : String = "Glossary"
val help : String = "Help"
val index : String = "Index"
val next : String = "Next"
val prev : String = "Prev"
val section : String = "Section"
val start : String = "Start"
val stylesheet : String = "Stylesheet"
val subsection : String = "Subsection"
val values : List<String> = listOf("alternate", "appEndIx", "bookmark", "chapter", "contentS", "copyright", "glossary", "help", "index", "next", "prev", "section", "start", "stylesheet", "subsection")
}
@Suppress("unused")
object LinkMedia {
val screen : String = "screen"
val print : String = "print"
val tty : String = "tty"
val tv : String = "tv"
val projection : String = "projection"
val handheld : String = "handheld"
val braille : String = "braille"
val aural : String = "aural"
val all : String = "all"
val values : List<String> = listOf("screen", "print", "tty", "tv", "projection", "handheld", "braille", "aural", "all")
}
@Suppress("unused")
object LinkType {
val textAsp : String = "text/asp"
val textAsa : String = "text/asa"
val textCss : String = "text/css"
val textHtml : String = "text/html"
val textJavaScript : String = "text/javascript"
val textPlain : String = "text/plain"
val textScriptLet : String = "text/scriptlet"
val textXComponent : String = "text/x-component"
val textXHtmlInsertion : String = "text/x-html-insertion"
val textXml : String = "text/xml"
val values : List<String> = listOf("textAsp", "textAsa", "textCss", "textHtml", "textJavaScript", "textPlain", "textScriptLet", "textXComponent", "textXHtmlInsertion", "textXml")
}
@Suppress("unused")
object MetaHttpEquiv {
val contentLanguage : String = "content-language"
val contentType : String = "content-type"
val defaultStyle : String = "default-style"
val refresh : String = "refresh"
val values : List<String> = listOf("contentLanguage", "contentType", "defaultStyle", "refresh")
}
@Suppress("unused")
object ObjectName {
val blank : String = "_blank"
val parent : String = "_parent"
val self : String = "_self"
val top : String = "_top"
val values : List<String> = listOf("blank", "parent", "self", "top")
}
@Suppress("unused")
object ScriptType {
val textEcmaScript : String = "text/ecmascript"
val textJavaScript : String = "text/javascript"
val textJavaScript10 : String = "text/javascript1.0"
val textJavaScript11 : String = "text/javascript1.1"
val textJavaScript12 : String = "text/javascript1.2"
val textJavaScript13 : String = "text/javascript1.3"
val textJavaScript14 : String = "text/javascript1.4"
val textJavaScript15 : String = "text/javascript1.5"
val textJScript : String = "text/jscript"
val textXJavaScript : String = "text/x-javascript"
val textXEcmaScript : String = "text/x-ecmascript"
val textVbScript : String = "text/vbscript"
val values : List<String> = listOf("textEcmaScript", "textJavaScript", "textJavaScript10", "textJavaScript11", "textJavaScript12", "textJavaScript13", "textJavaScript14", "textJavaScript15", "textJScript", "textXJavaScript", "textXEcmaScript", "textVbScript")
}
@Suppress("unused")
object StyleType {
val textCss : String = "text/css"
val values : List<String> = listOf("textCss")
}
@Suppress("unused")
object StyleMedia {
val screen : String = "screen"
val print : String = "print"
val tty : String = "tty"
val tv : String = "tv"
val projection : String = "projection"
val handheld : String = "handheld"
val braille : String = "braille"
val aural : String = "aural"
val all : String = "all"
val values : List<String> = listOf("screen", "print", "tty", "tv", "projection", "handheld", "braille", "aural", "all")
}
@Suppress("unused")
enum class TextAreaWrap(override val realValue : String) : AttributeEnum {
hard("hard"),
soft("soft")
}
internal val textAreaWrapValues : Map<String, TextAreaWrap> = TextAreaWrap.values().associateBy { it.realValue }
@Suppress("unused")
enum class ThScope(override val realValue : String) : AttributeEnum {
col("col"),
colGroup("colgroup"),
row("row"),
rowGroup("rowgroup")
}
internal val thScopeValues : Map<String, ThScope> = ThScope.values().associateBy { it.realValue }
|
apache-2.0
|
ed5f0c9279accde1a131da2f107824a2
| 33.675676 | 263 | 0.660597 | 3.823625 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/subscription/Subscription.kt
|
1
|
5165
|
package org.thoughtcrime.securesms.subscription
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.view.View
import androidx.core.animation.doOnEnd
import androidx.lifecycle.DefaultLifecycleObserver
import org.signal.core.util.money.FiatMoney
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.badges.models.Badge
import org.thoughtcrime.securesms.components.settings.PreferenceModel
import org.thoughtcrime.securesms.databinding.SubscriptionPreferenceBinding
import org.thoughtcrime.securesms.payments.FiatMoneyUtil
import org.thoughtcrime.securesms.util.DateUtils
import org.thoughtcrime.securesms.util.adapter.mapping.BindingFactory
import org.thoughtcrime.securesms.util.adapter.mapping.BindingViewHolder
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
import org.thoughtcrime.securesms.util.visible
import java.util.Currency
import java.util.Locale
/**
* Represents a Subscription that a user can start.
*/
data class Subscription(
val id: String,
val name: String,
val badge: Badge,
val prices: Set<FiatMoney>,
val level: Int,
) {
companion object {
fun register(adapter: MappingAdapter) {
adapter.registerFactory(Model::class.java, BindingFactory(::ViewHolder, SubscriptionPreferenceBinding::inflate))
adapter.registerFactory(LoaderModel::class.java, LayoutFactory({ LoaderViewHolder(it) }, R.layout.subscription_preference_loader))
}
}
class LoaderModel : PreferenceModel<LoaderModel>() {
override fun areItemsTheSame(newItem: LoaderModel): Boolean = true
}
class LoaderViewHolder(itemView: View) : MappingViewHolder<LoaderModel>(itemView), DefaultLifecycleObserver {
private val animator: Animator = AnimatorSet().apply {
val fadeTo25Animator = ObjectAnimator.ofFloat(itemView, "alpha", 0.8f, 0.25f).apply {
duration = 1000L
}
val fadeTo80Animator = ObjectAnimator.ofFloat(itemView, "alpha", 0.25f, 0.8f).apply {
duration = 300L
}
playSequentially(fadeTo25Animator, fadeTo80Animator)
doOnEnd {
if (itemView.isAttachedToWindow) {
start()
}
}
}
override fun bind(model: LoaderModel) {
}
override fun onAttachedToWindow() {
if (animator.isStarted) {
animator.resume()
} else {
animator.start()
}
}
override fun onDetachedFromWindow() {
animator.pause()
}
}
class Model(
val activePrice: FiatMoney?,
val subscription: Subscription,
val isSelected: Boolean,
val isActive: Boolean,
val willRenew: Boolean,
override val isEnabled: Boolean,
val onClick: (Subscription) -> Unit,
val renewalTimestamp: Long,
val selectedCurrency: Currency
) : PreferenceModel<Model>(isEnabled = isEnabled) {
override fun areItemsTheSame(newItem: Model): Boolean {
return subscription.id == newItem.subscription.id
}
override fun areContentsTheSame(newItem: Model): Boolean {
return super.areContentsTheSame(newItem) &&
newItem.subscription == subscription &&
newItem.isSelected == isSelected &&
newItem.isActive == isActive &&
newItem.renewalTimestamp == renewalTimestamp &&
newItem.willRenew == willRenew &&
newItem.selectedCurrency == selectedCurrency
}
override fun getChangePayload(newItem: Model): Any? {
return if (newItem.subscription.badge == subscription.badge) {
Unit
} else {
null
}
}
}
class ViewHolder(binding: SubscriptionPreferenceBinding) : BindingViewHolder<Model, SubscriptionPreferenceBinding>(binding) {
override fun bind(model: Model) {
binding.root.isEnabled = model.isEnabled
binding.root.setOnClickListener { model.onClick(model.subscription) }
binding.root.isSelected = model.isSelected
if (payload.isEmpty()) {
binding.badge.setBadge(model.subscription.badge)
binding.badge.isClickable = false
}
val formattedPrice = FiatMoneyUtil.format(
context.resources,
model.activePrice ?: model.subscription.prices.first { it.currency == model.selectedCurrency },
FiatMoneyUtil.formatOptions().trimZerosAfterDecimal()
)
if (model.isActive && model.willRenew) {
binding.tagline.text = context.getString(R.string.Subscription__renews_s, DateUtils.formatDateWithYear(Locale.getDefault(), model.renewalTimestamp))
} else if (model.isActive) {
binding.tagline.text = context.getString(R.string.Subscription__expires_s, DateUtils.formatDateWithYear(Locale.getDefault(), model.renewalTimestamp))
} else {
binding.tagline.text = context.getString(R.string.Subscription__get_a_s_badge, model.subscription.badge.name)
}
binding.title.text = context.getString(
R.string.Subscription__s_per_month,
formattedPrice
)
binding.check.visible = model.isActive
}
}
}
|
gpl-3.0
|
59bfd5fd0df3a2a7ca48bbc23ffd9067
| 33.433333 | 157 | 0.721588 | 4.510917 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/account/AccountSettingsFragment.kt
|
1
|
8955
|
package org.thoughtcrime.securesms.components.settings.app.account
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.text.InputType
import android.util.DisplayMetrics
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.autofill.HintConstants
import androidx.core.app.DialogCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.contactshare.SimpleTextWatcher
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.lock.PinHashing
import org.thoughtcrime.securesms.lock.v2.CreateKbsPinActivity
import org.thoughtcrime.securesms.lock.v2.KbsConstants
import org.thoughtcrime.securesms.lock.v2.PinKeyboardType
import org.thoughtcrime.securesms.pin.RegistrationLockV2Dialog
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.navigation.safeNavigate
class AccountSettingsFragment : DSLSettingsFragment(R.string.AccountSettingsFragment__account) {
lateinit var viewModel: AccountSettingsViewModel
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == CreateKbsPinActivity.REQUEST_NEW_PIN && resultCode == CreateKbsPinActivity.RESULT_OK) {
Snackbar.make(requireView(), R.string.ConfirmKbsPinFragment__pin_created, Snackbar.LENGTH_LONG).show()
}
}
override fun onResume() {
super.onResume()
viewModel.refreshState()
}
override fun bindAdapter(adapter: MappingAdapter) {
viewModel = ViewModelProvider(this)[AccountSettingsViewModel::class.java]
viewModel.state.observe(viewLifecycleOwner) { state ->
adapter.submitList(getConfiguration(state).toMappingModelList())
}
}
private fun getConfiguration(state: AccountSettingsState): DSLConfiguration {
return configure {
sectionHeaderPref(R.string.preferences_app_protection__signal_pin)
@Suppress("DEPRECATION")
clickPref(
title = DSLSettingsText.from(if (state.hasPin) R.string.preferences_app_protection__change_your_pin else R.string.preferences_app_protection__create_a_pin),
onClick = {
if (state.hasPin) {
startActivityForResult(CreateKbsPinActivity.getIntentForPinChangeFromSettings(requireContext()), CreateKbsPinActivity.REQUEST_NEW_PIN)
} else {
startActivityForResult(CreateKbsPinActivity.getIntentForPinCreate(requireContext()), CreateKbsPinActivity.REQUEST_NEW_PIN)
}
}
)
switchPref(
title = DSLSettingsText.from(R.string.preferences_app_protection__pin_reminders),
summary = DSLSettingsText.from(R.string.AccountSettingsFragment__youll_be_asked_less_frequently),
isChecked = state.hasPin && state.pinRemindersEnabled,
isEnabled = state.hasPin,
onClick = {
setPinRemindersEnabled(!state.pinRemindersEnabled)
}
)
switchPref(
title = DSLSettingsText.from(R.string.preferences_app_protection__registration_lock),
summary = DSLSettingsText.from(R.string.AccountSettingsFragment__require_your_signal_pin),
isChecked = state.registrationLockEnabled,
isEnabled = state.hasPin,
onClick = {
setRegistrationLockEnabled(!state.registrationLockEnabled)
}
)
clickPref(
title = DSLSettingsText.from(R.string.preferences__advanced_pin_settings),
onClick = {
Navigation.findNavController(requireView()).safeNavigate(R.id.action_accountSettingsFragment_to_advancedPinSettingsActivity)
}
)
dividerPref()
sectionHeaderPref(R.string.AccountSettingsFragment__account)
if (SignalStore.account().isRegistered) {
clickPref(
title = DSLSettingsText.from(R.string.AccountSettingsFragment__change_phone_number),
onClick = {
Navigation.findNavController(requireView()).safeNavigate(R.id.action_accountSettingsFragment_to_changePhoneNumberFragment)
}
)
}
clickPref(
title = DSLSettingsText.from(R.string.preferences_chats__transfer_account),
summary = DSLSettingsText.from(R.string.preferences_chats__transfer_account_to_a_new_android_device),
onClick = {
Navigation.findNavController(requireView()).safeNavigate(R.id.action_accountSettingsFragment_to_oldDeviceTransferActivity)
}
)
clickPref(
title = DSLSettingsText.from(R.string.preferences__delete_account, ContextCompat.getColor(requireContext(), R.color.signal_alert_primary)),
onClick = {
Navigation.findNavController(requireView()).safeNavigate(R.id.action_accountSettingsFragment_to_deleteAccountFragment)
}
)
}
}
private fun setRegistrationLockEnabled(enabled: Boolean) {
if (enabled) {
RegistrationLockV2Dialog.showEnableDialog(requireContext()) { viewModel.refreshState() }
} else {
RegistrationLockV2Dialog.showDisableDialog(requireContext()) { viewModel.refreshState() }
}
}
private fun setPinRemindersEnabled(enabled: Boolean) {
if (!enabled) {
val context: Context = requireContext()
val metrics: DisplayMetrics = resources.displayMetrics
val dialog: AlertDialog = MaterialAlertDialogBuilder(context)
.setView(R.layout.pin_disable_reminders_dialog)
.create()
dialog.show()
dialog.window!!.setLayout((metrics.widthPixels * .80).toInt(), ViewGroup.LayoutParams.WRAP_CONTENT)
val pinEditText = DialogCompat.requireViewById(dialog, R.id.reminder_disable_pin) as EditText
val statusText = DialogCompat.requireViewById(dialog, R.id.reminder_disable_status) as TextView
val cancelButton = DialogCompat.requireViewById(dialog, R.id.reminder_disable_cancel)
val turnOffButton = DialogCompat.requireViewById(dialog, R.id.reminder_disable_turn_off)
val changeKeyboard = DialogCompat.requireViewById(dialog, R.id.reminder_change_keyboard) as Button
changeKeyboard.setOnClickListener {
if (pinEditText.inputType and InputType.TYPE_CLASS_NUMBER == 0) {
pinEditText.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
changeKeyboard.setText(R.string.PinRestoreEntryFragment_enter_alphanumeric_pin)
} else {
pinEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
changeKeyboard.setText(R.string.PinRestoreEntryFragment_enter_numeric_pin)
}
pinEditText.typeface = Typeface.DEFAULT
}
pinEditText.post {
ViewUtil.focusAndShowKeyboard(pinEditText)
}
ViewCompat.setAutofillHints(pinEditText, HintConstants.AUTOFILL_HINT_PASSWORD)
when (SignalStore.pinValues().keyboardType) {
PinKeyboardType.NUMERIC -> {
pinEditText.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
changeKeyboard.setText(R.string.PinRestoreEntryFragment_enter_alphanumeric_pin)
}
PinKeyboardType.ALPHA_NUMERIC -> {
pinEditText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
changeKeyboard.setText(R.string.PinRestoreEntryFragment_enter_numeric_pin)
}
}
pinEditText.addTextChangedListener(object : SimpleTextWatcher() {
override fun onTextChanged(text: String) {
turnOffButton.isEnabled = text.length >= KbsConstants.MINIMUM_PIN_LENGTH
}
})
pinEditText.typeface = Typeface.DEFAULT
turnOffButton.setOnClickListener {
val pin = pinEditText.text.toString()
val correct = PinHashing.verifyLocalPinHash(SignalStore.kbsValues().localPinHash!!, pin)
if (correct) {
SignalStore.pinValues().setPinRemindersEnabled(false)
viewModel.refreshState()
dialog.dismiss()
} else {
statusText.setText(R.string.preferences_app_protection__incorrect_pin_try_again)
}
}
cancelButton.setOnClickListener { dialog.dismiss() }
} else {
SignalStore.pinValues().setPinRemindersEnabled(true)
viewModel.refreshState()
}
}
}
|
gpl-3.0
|
24af7353a73417c97f9acbde5f4c645d
| 41.042254 | 164 | 0.737688 | 4.637494 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua
|
src/main/java/com/tang/intellij/lua/editor/LuaTypedHandler.kt
|
2
|
3362
|
/*
* 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.editor
import com.intellij.codeInsight.AutoPopupController
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.codeInsight.template.impl.MacroCallNode
import com.intellij.codeInsight.template.impl.TextExpression
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.tang.intellij.lua.codeInsight.template.macro.SuggestLuaParametersMacro
import com.tang.intellij.lua.lang.LuaFileType
import com.tang.intellij.lua.psi.LuaFuncBody
import com.tang.intellij.lua.psi.LuaFuncBodyOwner
import com.tang.intellij.lua.psi.LuaTypes
/**
* Created by TangZX on 2016/11/28.
*/
class LuaTypedHandler : TypedHandlerDelegate() {
override fun checkAutoPopup(charTyped: Char, project: Project, editor: Editor, file: PsiFile): Result {
if (file.fileType == LuaFileType.INSTANCE) {
if (charTyped == ':' || charTyped == '@') {
AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null)
return Result.STOP
}
if (charTyped == '.') {
val element = file.findElementAt(editor.caretModel.offset - 1)
when (element?.node?.elementType) {
LuaTypes.DOT,
LuaTypes.SHORT_COMMENT -> return Result.STOP
}
}
}
return super.checkAutoPopup(charTyped, project, editor, file)
}
override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result {
if (file.fileType == LuaFileType.INSTANCE) {
// function() <caret> end 自动加上end
if (c == '(') {
PsiDocumentManager.getInstance(project).commitDocument(editor.document)
val pos = editor.caretModel.offset - 1
val element = file.findElementAt(pos)
if (element != null && element.parent is LuaFuncBodyOwner) {
val templateManager = TemplateManager.getInstance(project)
val template = templateManager.createTemplate("", "", "(\$PARAMETERS\$) \$END\$ end")
template.addVariable("PARAMETERS", MacroCallNode(SuggestLuaParametersMacro(SuggestLuaParametersMacro.Position.TypedHandler)), TextExpression(""), false)
templateManager.startTemplate(editor, template)
return Result.STOP
}
}
}
return super.charTyped(c, project, editor, file)
}
}
|
apache-2.0
|
19c1d779d0df51469e2ec8a84cc802dc
| 43.131579 | 172 | 0.677996 | 4.581967 | false | false | false | false |
TUWien/DocScan
|
app/src/main/java/at/ac/tuwien/caa/docscan/repository/DocumentRepository.kt
|
1
|
23001
|
package at.ac.tuwien.caa.docscan.repository
import android.content.Context
import android.net.Uri
import androidx.annotation.WorkerThread
import androidx.room.withTransaction
import androidx.work.WorkManager
import at.ac.tuwien.caa.docscan.R
import at.ac.tuwien.caa.docscan.camera.ImageExifMetaData
import at.ac.tuwien.caa.docscan.db.AppDatabase
import at.ac.tuwien.caa.docscan.db.dao.DocumentDao
import at.ac.tuwien.caa.docscan.db.dao.ExportFileDao
import at.ac.tuwien.caa.docscan.db.dao.PageDao
import at.ac.tuwien.caa.docscan.db.model.*
import at.ac.tuwien.caa.docscan.db.model.boundary.SinglePageBoundary
import at.ac.tuwien.caa.docscan.db.model.error.DBErrorCode
import at.ac.tuwien.caa.docscan.db.model.error.IOErrorCode
import at.ac.tuwien.caa.docscan.db.model.exif.Rotation
import at.ac.tuwien.caa.docscan.db.model.state.ExportState
import at.ac.tuwien.caa.docscan.db.model.state.LockState
import at.ac.tuwien.caa.docscan.db.model.state.PostProcessingState
import at.ac.tuwien.caa.docscan.db.model.state.UploadState
import at.ac.tuwien.caa.docscan.extensions.DocumentContractNotifier
import at.ac.tuwien.caa.docscan.extensions.checksGoogleAPIAvailability
import at.ac.tuwien.caa.docscan.extensions.deleteFile
import at.ac.tuwien.caa.docscan.logic.*
import at.ac.tuwien.caa.docscan.worker.ExportWorker
import at.ac.tuwien.caa.docscan.worker.UploadWorker
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.io.File
import java.util.*
class DocumentRepository(
private val context: Context,
private val preferencesHandler: PreferencesHandler,
private val fileHandler: FileHandler,
private val pageDao: PageDao,
private val documentDao: DocumentDao,
private val exportFileDao: ExportFileDao,
private val db: AppDatabase,
private val imageProcessorRepository: ImageProcessorRepository,
private val workManager: WorkManager,
private val userRepository: UserRepository
) {
fun getPageByIdAsFlow(pageId: UUID) = documentDao.getPageAsFlow(pageId)
fun getPageById(pageId: UUID) = documentDao.getPage(pageId)
fun getDocumentWithPagesAsFlow(documentId: UUID) =
documentDao.getDocumentWithPagesAsFlow(documentId).sortByNumber()
suspend fun getDocumentWithPages(documentId: UUID) =
documentDao.getDocumentWithPages(documentId)?.sortByNumber()
@WorkerThread
suspend fun getDocumentResource(documentId: UUID): Resource<Document> {
val document = documentDao.getDocument(documentId)
?: return DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure()
return Success(document)
}
fun getAllDocumentsAsFlow() = documentDao.getAllDocumentWithPagesAsFlow()
fun getActiveDocumentAsFlow(): Flow<DocumentWithPages?> {
return documentDao.getActiveDocumentasFlow().sortByNumber()
}
/**
* Tries to sanitize documents and their states in order, basically all locked documents and
* pages are trying to be resolved:
* - Documents/Pages for which the upload has been already ongoing or scheduled, the worker job
* is retried again, in this case the document is not unlocked.
* - If the Document/Pages have been exporting previously, then the export job has been interrupted
* which cannot be retried, therefore, the export state is reset and possible exported files
* are also deleted.
* - If the document/pages are locked due to any other occurrence, then they are simply unlocked.
*/
@WorkerThread
suspend fun sanitizeDocuments(): Resource<Unit> {
Timber.i("Starting sanitizeDocuments...")
documentDao.getAllLockedDocumentWithPages().forEach {
if (it.document.lockState == LockState.PARTIAL_LOCK) {
it.pages.forEach { page ->
if (page.isProcessing()) {
Timber.i("Page ${page.id} is reset to draft state.")
pageDao.updatePageProcessingState(page.id, PostProcessingState.DRAFT)
}
tryToUnlockDoc(it.document.id, page.id)
}
} else if (it.document.lockState == LockState.FULL_LOCK) {
when {
it.isUploadInProgress() || it.isUploadScheduled() -> {
UploadWorker.spawnUploadJob(
workManager,
it.document.id,
preferencesHandler.isUploadOnMeteredNetworksAllowed
)
}
it.isExporting() -> {
// exporting operation are usually very fast, if this should ever occur
// then the doc is set to not exported.
pageDao.updatePageExportStateForDocument(it.document.id, ExportState.NONE)
// get all export files that are being processed for the current docId,
// the docId is not unique at this place as they might be several exported
// files for a single document.
exportFileDao.getProcessingExportFiles(it.document.id)
.forEach { exportFile ->
// try to delete the file that has been associated with the export file.
exportFile.fileUri?.let { documentUri ->
deleteFile(context, documentUri)
}
// delete the export file from the database - if the corresponding file
// might still exist, then this will get correctly refreshed as soon as
// the user visits the export fragment.
exportFileDao.deleteExportFileByFileName(exportFile.fileName)
// notify the UI as well to refresh in case the user quickly navigated
// to the export fragments.
DocumentContractNotifier.observableDocumentContract.postValue(
Event(
Unit
)
)
}
tryToUnlockDoc(it.document.id, null)
}
else -> {
tryToUnlockDoc(it.document.id, null)
}
}
}
}
// they might be still some export files around that are still in processing state
// this call will update them all to false.
exportFileDao.updatesAllProcessingStatesToFalse()
return Success(Unit)
}
@WorkerThread
suspend fun deletePages(pages: List<Page>): Resource<Unit> {
Timber.i("delete pages, n=${pages.size} for doc ${pages.firstOrNull()?.docId}")
// TODO: OPTIMIZATION: When adding/removing pages, add a generic check to adapt the page number correctly.
pages.forEach {
val result = performPageOperation(it.docId, it.id, operation = { _, page ->
documentDao.deletePage(page)
fileHandler.getFileByPage(it)?.safelyDelete()
return@performPageOperation Success(Unit)
})
when (result) {
is Failure -> {
return Failure(result.exception)
}
is Success -> {
// ignore - continue loop
}
}
}
// every time a doc is modified, the upload state has to be reset.
pages.firstOrNull()?.let {
clearUploadStateFor(it.docId)
}
return Success(Unit)
}
@WorkerThread
suspend fun deletePage(page: Page?): Resource<Unit> {
Timber.i("Delete page ${page?.id}")
page ?: return DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure()
return deletePages(listOf(page))
}
@WorkerThread
fun setDocumentAsActive(documentId: UUID) {
db.runInTransaction {
documentDao.setAllDocumentsInactive()
documentDao.setDocumentActive(documentId = documentId)
}
}
@WorkerThread
suspend fun checkPageLock(page: Page?): Resource<Page> {
page ?: return DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure()
return isPageLocked(page.docId, page.id)
}
@WorkerThread
suspend fun removeDocument(documentWithPages: DocumentWithPages): Resource<Unit> {
Timber.i("delete doc ${documentWithPages.document.id}")
return performDocOperation(documentWithPages.document.id, operation = { doc ->
fileHandler.deleteEntireDocumentFolder(doc.id)
pageDao.deletePages(documentWithPages.pages)
documentDao.deleteDocument(documentWithPages.document)
Success(Unit)
})
}
@WorkerThread
suspend fun shareDocument(documentId: UUID): Resource<List<Uri>> {
Timber.i("share doc ${documentId}")
val doc = documentDao.getDocumentWithPages(documentId)
?: return DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure()
when (val checkLockResult = checkLock(doc.document, null)) {
is Failure -> {
return Failure(checkLockResult.exception)
}
is Success -> {
val urisResults = doc.pages.map {
val uriResource = fileHandler.getUriByPageResource(
it,
doc.document.getFileName(it.index + 1, it.fileType)
)
when (uriResource) {
is Failure -> {
return Failure(uriResource.exception)
}
is Success -> {
uriResource.data
}
}
}
return Success(urisResults)
}
}
}
@WorkerThread
suspend fun cancelDocumentUpload(documentId: UUID): Resource<Unit> {
Timber.i("cancel upload for document: $documentId")
val docWithPages = documentDao.getDocumentWithPages(documentId)
// non-null checks are not performed here, this is for safety reasons so that the upload worker
// is always cancelled, despite the fact if the document does not exist anymore.
if (docWithPages?.isUploaded() == false) {
// at this point, we do not know if the worker is currently just scheduled or running
// if if it's just scheduled, than we need to repair the states first.
UploadWorker.cancelWorkByDocumentId(workManager, documentId)
clearUploadStateFor(documentId)
}
tryToUnlockDoc(documentId, null)
return Success(Unit)
}
private suspend fun clearUploadStateFor(documentId: UUID) {
// clear the uploadId from the doc
documentDao.updateUploadIdForDoc(documentId, null)
// clear the upload file names
pageDao.clearDocumentPagesUploadFileNames(documentId)
// update upload state to none
pageDao.updateUploadStateForDocument(documentId, UploadState.NONE)
}
/**
* Cancels all uploads in the state [UploadState.SCHEDULED] and [UploadState.UPLOAD_IN_PROGRESS]
*/
@WorkerThread
suspend fun cancelAllPendingUploads(): Resource<Boolean> {
Timber.i("cancel all pending uploads")
var cancellationsPerformed = false
pageDao.getAllDocIdsWithPendingUploadState().forEach {
cancelDocumentUpload(it)
cancellationsPerformed = true
}
return Success(cancellationsPerformed)
}
@WorkerThread
suspend fun uploadDocument(
documentWithPages: DocumentWithPages,
skipAlreadyUploadedRestriction: Boolean = false,
skipCropRestriction: Boolean = false
): Resource<Unit> {
Timber.i("init upload for doc ${documentWithPages.document.id}")
val docWithPages = documentDao.getDocumentWithPages(documentWithPages.document.id)
?: return DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure()
if (docWithPages.pages.isEmpty()
) {
return DBErrorCode.NO_IMAGES_TO_UPLOAD.asFailure()
}
if (!skipAlreadyUploadedRestriction && docWithPages.isUploaded()
) {
return DBErrorCode.DOCUMENT_ALREADY_UPLOADED.asFailure()
}
// if forced, then reset upload state to NONE
pageDao.updateUploadStateForDocument(
documentWithPages.document.id,
UploadState.NONE
)
if (!skipCropRestriction && documentDao.getDocumentWithPages(documentWithPages.document.id)
?.isCropped() != true
) {
return DBErrorCode.DOCUMENT_NOT_CROPPED.asFailure()
}
when (val result = userRepository.checkLogin()) {
is Failure -> {
return Failure(result.exception)
}
is Success -> {
// ignore - since user is logged in and therefore the upload can be started.
}
}
when (val result = lockDocForLongRunningOperation(documentWithPages.document.id)) {
is Failure -> {
// TODO: Add reason why the doc is locked
return Failure(result.exception)
}
is Success -> {
// ignore, and perform check
}
}
spawnUploadJob(documentWithPages.document.id)
return Success(Unit)
}
/**
* Pre-Condition:
* - document is already locked
*/
private fun spawnUploadJob(documentId: UUID) {
pageDao.updateUploadStateForDocument(
documentId,
UploadState.SCHEDULED
)
UploadWorker.spawnUploadJob(
workManager,
documentId,
preferencesHandler.isUploadOnMeteredNetworksAllowed
)
}
@WorkerThread
suspend fun exportDocument(
documentWithPages: DocumentWithPages,
skipCropRestriction: Boolean = false,
exportFormat: ExportFormat
): Resource<Unit> {
Timber.i("export doc ${documentWithPages.document.id} with format ${exportFormat.name}")
if (!PermissionHandler.isPermissionGiven(context, preferencesHandler.exportDirectoryUri)) {
return IOErrorCode.EXPORT_FILE_MISSING_PERMISSION.asFailure()
}
if (exportFormat == ExportFormat.PDF_WITH_OCR && !checksGoogleAPIAvailability(context)) {
return IOErrorCode.EXPORT_GOOGLE_PLAYSTORE_NOT_INSTALLED_FOR_OCR.asFailure()
}
if (!skipCropRestriction && documentDao.getDocumentWithPages(documentWithPages.document.id)
?.isCropped() != true
) {
return DBErrorCode.DOCUMENT_NOT_CROPPED.asFailure()
}
when (val result = lockDocForLongRunningOperation(documentWithPages.document.id)) {
is Failure -> {
return Failure(result.exception)
}
is Success -> {
// ignore, and perform check
}
}
pageDao.updatePageExportStateForDocument(
documentWithPages.document.id,
ExportState.EXPORTING
)
ExportWorker.spawnExportJob(workManager, documentWithPages.document.id, exportFormat)
return Success(Unit)
}
@WorkerThread
suspend fun cropDocument(documentWithPages: DocumentWithPages): Resource<Unit> {
Timber.i("crop doc ${documentWithPages.document.id}")
return when (val result = lockDocForLongRunningOperation(documentWithPages.document.id)) {
is Failure -> {
Failure(result.exception)
}
is Success -> {
imageProcessorRepository.cropDocument(documentWithPages.document)
// every time a doc is modified, the upload state has to be reset.
clearUploadStateFor(documentWithPages.document.id)
Success(Unit)
}
}
}
@WorkerThread
suspend fun rotatePagesBy90(pages: List<Page>): Resource<Unit> {
val firstPage = pages.firstOrNull() ?: return DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure()
return performDocOperation(firstPage.docId, operation = {
withContext(NonCancellable) {
imageProcessorRepository.rotatePages90CW(pages)
// every time a doc is modified, the upload state has to be reset.
pages.firstOrNull()?.let {
clearUploadStateFor(it.docId)
}
}
Success(Unit)
})
}
@WorkerThread
fun createNewActiveDocument(): Document {
Timber.d("creating new active document!")
val doc = Document(
id = UUID.randomUUID(),
context.getString(R.string.document_default_name),
isActive = true
)
documentDao.insertDocument(doc)
return doc
}
@WorkerThread
suspend fun createDocument(document: Document): Resource<Document> {
Timber.i("create doc ${document.id}")
return createOrUpdateDocument(document)
}
@WorkerThread
suspend fun updateDocument(document: Document): Resource<Document> {
Timber.i("update doc ${document.id}")
return performDocOperation(document.id, operation = {
createOrUpdateDocument(document)
})
}
@WorkerThread
private suspend fun createOrUpdateDocument(document: Document): Resource<Document> {
val docsByNewTitle = documentDao.getDocumentsByTitle(documentTitle = document.title)
return if (docsByNewTitle.isEmpty() || (docsByNewTitle.size == 1 && docsByNewTitle[0].id == document.id)) {
db.runInTransaction {
if (document.isActive) {
documentDao.setAllDocumentsInactive()
}
documentDao.insertDocument(document)
}
Success(document)
} else {
DBErrorCode.DUPLICATE.asFailure()
}
}
/**
* Currently used only for debugging purposes.
*/
@WorkerThread
suspend fun saveNewImportedImageForDocument(
document: Document,
uris: List<Uri>
): Resource<Unit> {
return withContext(NonCancellable) {
uris.forEach { uri ->
try {
fileHandler.readBytes(uri)?.let { bytes ->
val resource = saveNewImageForDocument(
document.id,
bytes,
null,
null
)
when (resource) {
is Failure -> {
return@withContext Failure<Unit>(resource.exception)
}
is Success -> {
// ignore
}
}
}
} catch (e: Exception) {
Timber.e(e)
}
}
return@withContext Success(Unit)
}
}
@WorkerThread
suspend fun saveNewImageForDocument(
documentId: UUID,
data: ByteArray,
fileId: UUID? = null,
exifMetaData: ImageExifMetaData?
): Resource<Page> {
Timber.d("save new image for doc $documentId")
val document = documentDao.getDocument(documentId) ?: kotlin.run {
return DBErrorCode.ENTRY_NOT_AVAILABLE.asFailure()
}
if (document.lockState == LockState.FULL_LOCK) {
return DBErrorCode.DOCUMENT_LOCKED.asFailure()
}
// TODO: Make a check here, if there is enough storage to save the file.
// if fileId is provided, then it means that a file is being replaced.
val newFileId = fileId ?: UUID.randomUUID()
val file = fileHandler.createDocumentFile(documentId, newFileId, PageFileType.JPEG)
var tempFile: File? = null
// 1. make a safe copy of the current file if it exists to rollback changes in case of something fails.
if (file.exists()) {
tempFile = fileHandler.createCacheFile(newFileId, PageFileType.JPEG)
try {
fileHandler.copyFile(file, tempFile)
} catch (e: Exception) {
tempFile.safelyDelete()
if (fileId == null) {
file.safelyDelete()
}
return IOErrorCode.FILE_COPY_ERROR.asFailure(e)
}
}
// 2. process byte array into file
try {
fileHandler.copyByteArray(data, file)
// in case we used the temp file, delete it safely
tempFile?.safelyDelete()
} catch (e: Exception) {
// rollback
tempFile?.let {
fileHandler.safelyCopyFile(it, file)
}
return IOErrorCode.FILE_COPY_ERROR.asFailure(e)
}
// TODO: Apply exif only here, not in the viewModels
// 3. apply external exif data if available, otherwise assume that exif is already set.
val rotation = if (exifMetaData != null) {
applyExifData(file, exifMetaData)
Rotation.getRotationByExif(exifMetaData.exifOrientation)
} else {
getRotation(file)
}
// TODO: When adding/removing pages, add a generic check to adapt the page number correctly.
// for a replacement, just take the number of the old page.
// for a new page, take the max number and add + 1 to it.
val pageNumber =
pageDao.getPageById(newFileId)?.index ?: (pageDao.getPagesByDoc(documentId)
.maxByOrNull { page -> page.index })?.index?.let {
// increment if there is an existing page
it + 1
} ?: 0
val newPage = Page(
newFileId,
document.id,
file.getFileHash(),
pageNumber,
rotation,
PageFileType.JPEG,
PostProcessingState.DRAFT,
ExportState.NONE,
SinglePageBoundary.getDefault()
)
// 4. Update file in database (create or update)
db.withTransaction {
// update document
documentDao.insertDocument(document)
// insert the new page
pageDao.insertPage(newPage)
}
// 5. Add a partial lock and spawn page detection
lockDoc(document.id, newPage.id)
imageProcessorRepository.spawnPageDetection(newPage)
return Success(data = newPage)
}
}
|
lgpl-3.0
|
55238add4131139c60d9faa7f5a4632e
| 38.794118 | 115 | 0.594235 | 5.056276 | false | false | false | false |
Etik-Tak/backend
|
src/main/kotlin/dk/etiktak/backend/service/trust/ContributionService.kt
|
1
|
19079
|
// Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package dk.etiktak.backend.service.trust
import dk.etiktak.backend.model.contribution.Contribution
import dk.etiktak.backend.model.contribution.ReferenceContribution
import dk.etiktak.backend.model.contribution.TextContribution
import dk.etiktak.backend.model.contribution.TrustVote
import dk.etiktak.backend.model.user.Client
import dk.etiktak.backend.repository.contribution.ContributionRepository
import dk.etiktak.backend.repository.contribution.ReferenceContributionRepository
import dk.etiktak.backend.repository.contribution.TextContributionRepository
import dk.etiktak.backend.repository.contribution.TrustVoteRepository
import dk.etiktak.backend.repository.user.ClientRepository
import dk.etiktak.backend.service.security.ClientVerified
import dk.etiktak.backend.util.CryptoUtil
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import org.springframework.util.Assert
@Service
@Transactional
open class ContributionService @Autowired constructor(
private val contributionRepository: ContributionRepository,
private val textContributionRepository: TextContributionRepository,
private val referenceContributionRepository: ReferenceContributionRepository,
private val trustVoteRepository: TrustVoteRepository,
private val clientRepository: ClientRepository) {
private val logger = LoggerFactory.getLogger(ContributionService::class.java)
companion object {
val initialClientTrustLevel = 0.5
val trustScoreContributionDelta = 0.05
val votedTrustWeightMax = 0.95
val votedTrustWeightLinearGrowthUpUntil = 5.0
}
/**
* Returns the current reference contribution.
*
* @param contributionType Contribution type, fx. AssignCompanyToProduct
* @param subjectUuid Subject UUID, fx. product UUID
* @param referenceUuid Reference UUID, fx. company UUID
* @return Current reference contribution
*/
open fun currentReferenceContribution(contributionType: Contribution.ContributionType, subjectUuid: String, referenceUuid: String): ReferenceContribution? {
val currentContributions = referenceContributionRepository.findBySubjectUuidAndReferenceUuidAndTypeAndEnabled(subjectUuid, referenceUuid, contributionType, pageable = PageRequest(0, 1, Sort(Sort.Direction.DESC, "creationTime")))
return if (currentContributions.size == 1) currentContributions[0] else null
}
/**
* Returns the current text contribution.
*
* @param contributionType Contribution type, fx. EditCompanyName
* @param subjectUuid Subject UUID, fx. company UUID
* @return Current text contribution
*/
open fun currentTextContribution(contributionType: Contribution.ContributionType, subjectUuid: String): TextContribution? {
val currentContributions = textContributionRepository.findBySubjectUuidAndTypeAndEnabled(subjectUuid, contributionType, pageable = PageRequest(0, 1, Sort(Sort.Direction.DESC, "creationTime")))
return if (currentContributions.size == 1) currentContributions[0] else null
}
/**
* Asserts that a contribution with given subject UUID and reference UUID is not already present.
*
* @param subjectUuid Subject UUID, fx. product UUID
* @param referenceUuid Reference UUID, fx. product tag UUID
* @param contributionType Contribution type
*/
fun assertReferenceContributionNotPresent(subjectUuid: String, referenceUuid: String, contributionType: Contribution.ContributionType) {
val contributions = referenceContributionRepository.findBySubjectUuidAndReferenceUuidAndTypeAndEnabled(subjectUuid, referenceUuid, contributionType, pageable = PageRequest(0, 1))
Assert.isTrue(
contributions.isEmpty(),
"Contribution with subject UUID $subjectUuid and reference UUID $referenceUuid already present")
}
/**
* Creates a new text contribution.
*
* @param contributionType Contribution type, fx. EditCompanyName
* @param inClient Client
* @param subjectUuid Subject UUID, fx. company UUID
* @param text Text
* @param modifyValues Function called with modified client
* @return Created contribution
*/
open fun createTextContribution(contributionType: Contribution.ContributionType, inClient: Client, subjectUuid: String, text: String, modifyValues: (Client) -> Unit = {}): Contribution {
var client = inClient
// Check sufficient trust
val currentContribution = currentTextContribution(contributionType, subjectUuid)
currentContribution?.let {
assertSufficientTrustToEditContribution(client, currentContribution)
}
// Disable current text contribution
currentContribution?.let {
client.contributions.remove(currentContribution)
currentContribution.enabled = false
contributionRepository.save(currentContribution)
}
// Create contribution
var contribution = TextContribution()
contribution.uuid = CryptoUtil().uuid()
contribution.type = contributionType
contribution.subjectUuid = subjectUuid
contribution.text = text
// Glue it together
contribution.client = client
client.contributions.add(contribution)
// Save it all
client = clientRepository.save(client)
contribution = contributionRepository.save(contribution)
// Update trust
updateTrust(contribution)
modifyValues(client)
return contribution
}
/**
* Creates a new reference contribution.
*
* @param contributionType Contribution type, fx. EditCompanyName
* @param inClient Client
* @param subjectUuid Subject UUID, fx. product UUID
* @param referenceUuid Reference UUID, fx. product tag UUID
* @param modifyValues Function called with modified client
* @return Created contribution
*/
open fun createReferenceContribution(contributionType: Contribution.ContributionType, inClient: Client, subjectUuid: String, referenceUuid: String, modifyValues: (Client) -> Unit = {}): Contribution {
var client = inClient
// Make sure it's not already present and enabled
assertReferenceContributionNotPresent(subjectUuid, referenceUuid, contributionType)
// Create contribution
var contribution = ReferenceContribution()
contribution.uuid = CryptoUtil().uuid()
contribution.type = contributionType
contribution.subjectUuid = subjectUuid
contribution.referenceUuid = referenceUuid
// Glue it together
contribution.client = client
client.contributions.add(contribution)
// Save it all
client = clientRepository.save(client)
contribution = contributionRepository.save(contribution)
// Update trust
updateTrust(contribution)
modifyValues(client)
return contribution
}
/**
* Disables a contribution.
*
* @param inContribution Contribution
* @param inClient Client
* @param modifyValues Function called with modified client and contribution
* @return Created contribution
*/
open fun disableContribution(inContribution: Contribution, inClient: Client, modifyValues: (Contribution) -> Unit = {}): Contribution {
// Check sufficient trust
assertSufficientTrustToEditContribution(inClient, inContribution)
// Disable contribution
inContribution.enabled = false
// Save it all
val contribution = contributionRepository.save(inContribution)
// Update trust
updateTrust(contribution)
modifyValues(contribution)
return contribution
}
/**
* Returns whether the given client has succicient trust to edit given contribution.
*
* @param client Client
* @param contribution Contribution
* @return True, if client can edit contribution, or else false. If contribution is null, true is returned
*/
open fun hasSufficientTrustToEditContribution(client: Client, contribution: Contribution?): Boolean {
if (contribution != null) {
return client.trustLevel >= contribution.trustScore - trustScoreContributionDelta
} else {
return true
}
}
/**
* Checks that client has succicient trust to edit given contribution.
*
* @param client Client
* @param contribution Contribution
*/
open fun assertSufficientTrustToEditContribution(client: Client, contribution: Contribution) {
Assert.isTrue(
hasSufficientTrustToEditContribution(client, contribution),
"Client with UUID ${client.uuid} does not have sufficient trust level to edit contribution with UUID ${contribution.uuid}. " +
"Client trust: ${client.trustLevel}. " +
"Contribution score: ${contribution.trustScore}."
)
}
/**
* Create trust vote on contribution.
*
* @param inClient Client
* @param inContribution Contribution
* @param vote Vote
* @param modifyValues Function called with modified client and contribution
* @return Trust vote
*/
@ClientVerified
open fun trustVoteItem(inClient: Client, inContribution: Contribution, vote: TrustVote.TrustVoteType, modifyValues: (Client, Contribution) -> Unit = {client, contribution -> Unit}): TrustVote {
var client = inClient
var contribution = inContribution
// Clients cannot vote on their own contribution
Assert.isTrue(
contribution.client.uuid != client.uuid,
"Client with uuid ${client.uuid} cannot vote on his own contribution with uuid ${contribution.uuid}"
)
// Clients can only vote once on same item
Assert.isNull(
trustVoteRepository.findByClientUuidAndContributionUuid(client.uuid, contribution.uuid),
"Client with uuid ${client.uuid} already trust voted contribution with uuid ${contribution.uuid}"
)
// Create trust vote
var trustVote = TrustVote()
trustVote.vote = vote
trustVote.client = client
// Glue it together
trustVote.contribution = contribution
contribution.trustVotes.add(trustVote)
client.trustVotes.add(trustVote)
// Save it all
trustVote = trustVoteRepository.save(trustVote)
client = clientRepository.save(client)
contribution = contributionRepository.save(contribution)
// Recalculate trust
updateTrust(contribution, modifyValues = {modifiedContribution -> contribution = modifiedContribution})
modifyValues(clientRepository.findByUuid(client.uuid)!!, contribution)
return trustVote
}
/**
* Recalculate trust score based on votes and client trust score.
*
* @param inContribution Contribution
* @param modifyValues Function called with modified contribution
*/
open fun updateTrust(inContribution: Contribution, modifyValues: (Contribution) -> Unit = {}) {
var contribution = inContribution
// Count votes
val trustedVotesCount = contributionRepository.countByUuidAndTrustVotesVote(contribution.uuid, TrustVote.TrustVoteType.Trusted)
val untrustedVotesCount = contributionRepository.countByUuidAndTrustVotesVote(contribution.uuid, TrustVote.TrustVoteType.NotTrusted)
val totalVotesCount = trustedVotesCount + untrustedVotesCount
// Update trust item
if (totalVotesCount > 0) {
// Voted trust score is simply the percentage of trusted votes out of total number of votes. Weight has linear growth.
val votedTrustScore = trustedVotesCount.toDouble() / totalVotesCount.toDouble()
val votedTrustScoreWeight = linearGrowthTrustWeight(totalVotesCount)
// Client trust level
val clientTrustLevel = contribution.client.trustLevel
val clientTrustLevelWeight = 1.0 - votedTrustScoreWeight
// Calculate trust by linearly interpolating between initial trust and voted trust
contribution.trustScore = (votedTrustScore * votedTrustScoreWeight) + (clientTrustLevel * clientTrustLevelWeight)
} else {
// Use client trust if no votes
contribution.trustScore = contribution.client.trustLevel
}
// Save contribution
contribution = contributionRepository.save(contribution)
// Recalculate creators trust level
recalculateClientTrustLevel(contribution.client)
// Recalculate all vote contributers trust level
for (trustVote in contribution.trustVotes) {
recalculateClientTrustLevel(trustVote.client)
}
modifyValues(contribution)
}
/**
* Recalculates client trust level.
*
* @param inClient Client
* @param modifyValues Function called with modified client
*/
open fun recalculateClientTrustLevel(inClient: Client, modifyValues: (Client) -> Unit = {}) {
var client = inClient
// Reset total score and weight
var totalScore = 0.0
var totalWeight = 0.0
// Initial trust level
totalScore += initialClientTrustLevel
totalWeight += 1.0
// Find client contributions
val contributions = contributionRepository.findByClientUuid(client.uuid)
// Find contributions voted on by client
val votedContributions = contributionRepository.findByTrustVotesClientUuid(client.uuid)
// Add trust from client contributions
for (contribution in contributions) {
totalScore += contribution.trustScore
totalWeight += 1.0
}
// Add trust from contributions voted on by client
for (contribution in votedContributions) {
// Count trusted and not-trusted votes
val trustedVoteCount = trustVoteRepository.countByVoteAndContributionUuid(TrustVote.TrustVoteType.Trusted, contribution.uuid)
val notTrustedVoteCount = trustVoteRepository.countByVoteAndContributionUuid(TrustVote.TrustVoteType.NotTrusted, contribution.uuid)
val totalVoteCount = trustedVoteCount + notTrustedVoteCount
// If none, ignore trust item
if (trustedVoteCount == 0L && notTrustedVoteCount == 0L) {
continue
}
// Find client's trust vote
val actualVote = trustVoteRepository.findByClientUuidAndContributionUuid(client.uuid, contribution.uuid)!!
// Weight is lowered if vote is of type trusted. This is done in an attempt to mitigate clients from easily
// gaining higher trust level from just contributing with votes that provide no real value.
val weightImpact = if (actualVote.vote == TrustVote.TrustVoteType.Trusted) 0.75 else 1.0
// Calculate weight. Weight increases quadratic with number of votes.
val ratio = Math.min(trustedVoteCount, notTrustedVoteCount).toDouble() / Math.max(trustedVoteCount, notTrustedVoteCount).toDouble()
val weight = Math.pow(1.0 - ratio, 3.0) * linearGrowthTrustWeight(totalVoteCount) * weightImpact
// Calculate score
val majorityVoteType = if (trustedVoteCount > notTrustedVoteCount) TrustVote.TrustVoteType.Trusted else TrustVote.TrustVoteType.NotTrusted
val score = if (actualVote.vote == majorityVoteType) 1.0 else 0.0
// Add to total
totalScore += score * weight
totalWeight += weight
}
// Average on trust contributions
val trustLevel = totalScore / totalWeight
// Update client
client.trustLevel = trustLevel
// Save client
client = clientRepository.save(client)
modifyValues(client)
}
/**
* Calculates the weight of the voted trust.
*
* @param votesCount Number of trust votes
* @return Weight of voted trust from 0 to 1
*/
open fun linearGrowthTrustWeight(votesCount: Long): Double {
val votedTrustWeightGrowth = votedTrustWeightMax / votedTrustWeightLinearGrowthUpUntil
return Math.min(votesCount * votedTrustWeightGrowth, votedTrustWeightMax)
}
/**
* Returns the unique contribution from the given list. Asserts that the list has size no more than one.
*
* @param contributions List of contributions
* @return Element at position 0, if any
*/
open fun <T: Contribution> uniqueContribution(contributions: List<T>): T? {
Assert.isTrue(
contributions.size <= 1,
"Expected only one active contribution, but found ${contributions.size}"
)
return if (contributions.isNotEmpty()) contributions[0] else null
}
}
|
bsd-3-clause
|
5f7497017a333cba8e3545dccb29f0c4
| 41.212389 | 236 | 0.693223 | 5.198638 | false | false | false | false |
anlun/haskell-idea-plugin
|
plugin/src/org/jetbrains/haskell/scope/ExpressionScope.kt
|
1
|
4931
|
package org.jetbrains.haskell.scope
import org.jetbrains.haskell.psi.Expression
import org.jetbrains.haskell.psi.SignatureDeclaration
import java.util.ArrayList
import org.jetbrains.haskell.psi.Module
import org.jetbrains.haskell.psi.RightHandSide
import org.jetbrains.haskell.psi.QVar
import org.jetbrains.haskell.psi.ValueDefinition
import org.jetbrains.haskell.psi.QNameExpression
import org.jetbrains.haskell.psi.ExpressionStatement
import org.jetbrains.haskell.psi.UnguardedRHS
import org.jetbrains.haskell.psi.CaseAlternative
import org.jetbrains.haskell.psi.LambdaExpression
import org.jetbrains.haskell.psi.Statement
import org.jetbrains.haskell.psi.Guard
import org.jetbrains.haskell.psi.DoExpression
import org.jetbrains.haskell.psi.LetStatement
import org.jetbrains.haskell.psi.BindStatement
/**
* Created by atsky on 11/21/14.
*/
public class ExpressionScope(val expression: Expression) {
fun getVisibleVariables(): List<QVar> {
val parent = expression.getParent()
val result = ArrayList<QVar>()
if (parent is Expression) {
if (parent is LambdaExpression) {
for (pattern in parent.getPatterns()) {
traverseExpression(pattern.getExpression(), result)
}
}
result.addAll(ExpressionScope(parent).getVisibleVariables())
return result
} else if (parent is Statement) {
return getStatementScopedDeclarations(parent)
} else if (parent is Guard) {
addRightHandSide(parent.getParent() as RightHandSide, result)
} else if (parent is UnguardedRHS) {
val caseAlternative = parent.getParent() as? CaseAlternative
if (caseAlternative != null) {
traverseExpression(caseAlternative.getExpressions().firstOrNull(), result)
result.addAll(ExpressionScope(caseAlternative.getParent() as Expression).getVisibleVariables())
return result;
}
} else if (parent is RightHandSide) {
addRightHandSide(parent, result)
val letStatement = parent.getLetStatement()
if (letStatement != null) {
return getStatementScopedDeclarations(letStatement)
} else {
return getModuleScopedDeclarations(result);
}
}
return getModuleScopedDeclarations(result);
}
fun getStatementScopedDeclarations(statement: Statement): List<QVar> {
val result = ArrayList<QVar>()
val parent = statement.getParent()
if (parent is DoExpression) {
val statementList = parent.getStatementList()
val index = statementList.indexOf(statement)
for (st in statementList.subList(0, index)) {
if (st is LetStatement) {
val list = st.getValueDefinitions()
.map { it.getQNameExpression()?.getQVar() }.filterNotNull()
result.addAll(list)
} else if (st is BindStatement) {
val qVar = st.getQVar()
if (qVar != null) {
result.add(qVar)
}
}
}
result.addAll(ExpressionScope(parent).getVisibleVariables())
return result
} else if (parent is Guard) {
addRightHandSide(parent.getParent() as RightHandSide, result)
}
return getModuleScopedDeclarations(result);
}
fun getModuleScopedDeclarations(result: ArrayList<QVar>): List<QVar> {
val module = Module.findModule(expression)
if (module == null) {
return listOf();
}
val signatureDeclaration = ModuleScope(module).getVisibleSignatureDeclaration()
result.addAll(signatureDeclaration.map({ it.getQNameExpression()?.getQVar() }).filterNotNull())
return result;
}
private fun addRightHandSide(rhs: RightHandSide, result: ArrayList<QVar>) {
val where = rhs.getWhereBindings()
if (where != null) {
val list1 = where.getSignatureDeclarationsList()
result.addAll(list1.flatMap { it.getValuesList() })
val list2 = where.getValueDefinitionList()
result.addAll(list2.map({ it.getQNameExpression()?.getQVar() }).filterNotNull())
}
val parent = rhs.getParent()
if (parent is ValueDefinition) {
val valueDefinition: ValueDefinition = parent;
traverseExpression(valueDefinition.getExpression(), result)
}
}
private fun traverseExpression(expression: Expression?, result: ArrayList<QVar>) {
expression?.traverse { node ->
if (node is QNameExpression) {
val qVar = node.getQVar()
if (qVar != null) {
result.add(qVar)
}
}
}
}
}
|
apache-2.0
|
7391f86adfbb7d70fdfbfed7c1965a0f
| 38.774194 | 111 | 0.624214 | 4.778101 | false | false | false | false |
inorichi/tachiyomi-extensions
|
src/en/vgperson/src/eu/kanade/tachiyomi/extension/en/vgperson/Vgperson.kt
|
1
|
5304
|
package eu.kanade.tachiyomi.extension.en.vgperson
import android.os.Build.VERSION
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Headers
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.nodes.TextNode
import rx.Observable
class Vgperson : ParsedHttpSource() {
override val name = "vgperson"
override val lang = "en"
override val supportsLatest = false
override val baseUrl = "https://vgperson.com/other/mangaviewer.php"
private val userAgent = "Mozilla/5.0 " +
"(Android ${VERSION.RELEASE}; Mobile) " +
"Tachiyomi/${BuildConfig.VERSION_NAME}"
override fun headersBuilder() = Headers.Builder().apply {
add("User-Agent", userAgent)
add("Referer", baseUrl)
}
override fun popularMangaSelector() = ".content a[href^=?m]"
override fun popularMangaNextPageSelector(): String? = null
override fun popularMangaRequest(page: Int) = GET(baseUrl, headers)
override fun popularMangaFromElement(element: Element) = SManga.create().apply {
title = element.text()
url = element.attr("href")
thumbnail_url = getCover(title)
}
override fun fetchMangaDetails(manga: SManga): Observable<SManga> =
client.newCall(mangaDetailsRequest(manga)).asObservableSuccess().map {
mangaDetailsParse(it).apply {
url = manga.url
title = manga.title
thumbnail_url = manga.thumbnail_url
initialized = true
}
}
override fun mangaDetailsParse(document: Document) = SManga.create().apply {
status = when (document.select(".chaptername").first().text()) {
"(Complete)" -> SManga.COMPLETED
"(Series in Progress)" -> SManga.ONGOING
else -> SManga.UNKNOWN
}
description = document.select(".content").first()
.childNodes().drop(5).takeWhile {
it.nodeName() != "table"
}.joinToString("") {
if (it is TextNode) it.text()
else when ((it as Element).tagName()) {
"br" -> "\n"
else -> it.text()
}
}
}
override fun chapterListSelector() = ".chaptertable tbody tr"
override fun chapterFromElement(element: Element) = SChapter.create().apply {
element.select("td > a").first().let {
name = it.text()
url = it.attr("href")
}
// append the name if it exists & remove the occasional hyphen
element.select(".chaptername")?.first()?.let {
name += " - ${it.text().substringAfter("- ")}"
}
// hardcode special chapter numbers for Three Days of Happiness
chapter_number = url.substringAfterLast("c=").toFloatOrNull()
?: 16.5f + "0.${url.substringAfterLast("b=")}".toFloat()
scanlator = "vgperson"
date_upload = 0L
}
override fun chapterListParse(response: Response) =
super.chapterListParse(response).sortedByDescending(SChapter::chapter_number)
override fun pageListParse(document: Document) =
document.select("img").mapIndexed { i, img -> Page(i, "", img.attr("src")) }
override fun fetchSearchManga(page: Int, query: String, filters: FilterList): Observable<MangasPage> = fetchPopularManga(1)
.map { mp -> MangasPage(mp.mangas.filter { it.title.contains(query, ignoreCase = true) }, false) }
// get known manga covers from imgur
private fun getCover(title: String) = when (title) {
"The Festive Monster's Cheerful Failure" -> "kEK10GL.png"
"Azure and Claude" -> "buXnlmh.jpg"
"Three Days of Happiness" -> "kL5dvnp.jpg"
else -> null
}?.let { "https://i.imgur.com/$it" }
override fun latestUpdatesSelector() = ""
override fun latestUpdatesNextPageSelector(): String? = null
override fun latestUpdatesRequest(page: Int) =
throw UnsupportedOperationException("This method should not be called!")
override fun latestUpdatesFromElement(element: Element) =
throw UnsupportedOperationException("This method should not be called!")
override fun searchMangaSelector() = ""
override fun searchMangaNextPageSelector(): String? = null
override fun searchMangaRequest(page: Int, query: String, filters: FilterList) =
throw UnsupportedOperationException("This method should not be called!")
override fun searchMangaFromElement(element: Element) =
throw UnsupportedOperationException("This method should not be called!")
override fun searchMangaParse(response: Response) =
throw UnsupportedOperationException("This method should not be called!")
override fun imageUrlParse(document: Document) =
throw UnsupportedOperationException("This method should not be called!")
}
|
apache-2.0
|
db63d5f5d8bc745d48ef57eb5948cd6e
| 37.158273 | 127 | 0.658183 | 4.673128 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/cache/attempt/structure/DbStructureAttempt.kt
|
2
|
912
|
package org.stepik.android.cache.attempt.structure
object DbStructureAttempt {
const val TABLE_NAME = "attempt"
object Columns {
const val ID = "id"
const val STEP = "step"
const val USER = "user"
const val DATASET = "dataset"
const val DATASET_URL = "dataset_url"
const val STATUS = "status"
const val TIME = "time"
const val TIME_LEFT = "time_left"
}
const val TABLE_SCHEMA =
"CREATE TABLE IF NOT EXISTS $TABLE_NAME (" +
"${Columns.ID} LONG," +
"${Columns.STEP} LONG," +
"${Columns.USER} LONG," +
"${Columns.DATASET} TEXT," +
"${Columns.DATASET_URL} TEXT," +
"${Columns.STATUS} TEXT," +
"${Columns.TIME} LONG," +
"${Columns.TIME_LEFT} TEXT," +
"PRIMARY KEY (${Columns.STEP}, ${Columns.USER})" +
")"
}
|
apache-2.0
|
0b073ec31049342e206ea86019e5e997
| 27.53125 | 62 | 0.519737 | 4.053333 | false | false | false | false |
StepicOrg/stepic-android
|
app/src/main/java/org/stepik/android/view/profile_courses/ui/fragment/ProfileCoursesFragment.kt
|
1
|
7525
|
package org.stepik.android.view.profile_courses.ui.fragment
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.error_no_connection_with_button_small.*
import kotlinx.android.synthetic.main.fragment_profile_courses.*
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.util.CoursesSnapHelper
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.course_list.model.CourseListQuery
import org.stepik.android.domain.course_payments.mapper.DefaultPromoCodeMapper
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.profile_courses.ProfileCoursesPresenter
import org.stepik.android.presentation.profile_courses.ProfileCoursesView
import org.stepik.android.view.base.ui.adapter.layoutmanager.TableLayoutManager
import org.stepik.android.view.course.mapper.DisplayPriceMapper
import org.stepik.android.view.course_list.delegate.CourseContinueViewDelegate
import org.stepik.android.view.course_list.resolver.TableLayoutHorizontalSpanCountResolver
import org.stepik.android.view.course_list.ui.adapter.delegate.CourseListItemAdapterDelegate
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.android.ui.adapters.DefaultDelegateAdapter
import ru.nobird.android.view.base.ui.extension.argument
import javax.inject.Inject
import kotlin.math.min
class ProfileCoursesFragment : Fragment(R.layout.fragment_profile_courses), ProfileCoursesView {
companion object {
fun newInstance(userId: Long): Fragment =
ProfileCoursesFragment()
.apply {
this.userId = userId
}
}
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var analytic: Analytic
@Inject
internal lateinit var screenManager: ScreenManager
@Inject
internal lateinit var defaultPromoCodeMapper: DefaultPromoCodeMapper
@Inject
internal lateinit var displayPriceMapper: DisplayPriceMapper
@Inject
internal lateinit var tableLayoutHorizontalSpanCountResolver: TableLayoutHorizontalSpanCountResolver
private var userId by argument<Long>()
private val profileCoursesPresenter: ProfileCoursesPresenter by viewModels { viewModelFactory }
private lateinit var courseContinueViewDelegate: CourseContinueViewDelegate
private lateinit var coursesAdapter: DefaultDelegateAdapter<CourseListItem>
private lateinit var viewStateDelegate: ViewStateDelegate<ProfileCoursesView.State>
private lateinit var tableLayoutManager: TableLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectComponent()
savedInstanceState?.let(profileCoursesPresenter::onRestoreInstanceState)
courseContinueViewDelegate = CourseContinueViewDelegate(
activity = requireActivity(),
analytic = analytic,
screenManager = screenManager
)
coursesAdapter = DefaultDelegateAdapter()
coursesAdapter += CourseListItemAdapterDelegate(
analytic,
onItemClicked = courseContinueViewDelegate::onCourseClicked,
onContinueCourseClicked = { courseListItem ->
profileCoursesPresenter
.continueCourse(
course = courseListItem.course,
viewSource = CourseViewSource.Query(CourseListQuery(teacher = userId)),
interactionSource = CourseContinueInteractionSource.COURSE_WIDGET
)
},
defaultPromoCodeMapper = defaultPromoCodeMapper,
displayPriceMapper = displayPriceMapper
)
}
private fun injectComponent() {
App.componentManager()
.profileComponent(userId)
.profileCoursesPresentationComponentBuilder()
.build()
.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewStateDelegate = ViewStateDelegate()
viewStateDelegate.addState<ProfileCoursesView.State.Idle>()
viewStateDelegate.addState<ProfileCoursesView.State.Loading>(view, profileCoursesPlaceholder)
viewStateDelegate.addState<ProfileCoursesView.State.Empty>()
viewStateDelegate.addState<ProfileCoursesView.State.Error>(view, profileCoursesLoadingError)
viewStateDelegate.addState<ProfileCoursesView.State.Content>(view, profileCoursesRecycler)
setDataToPresenter()
tryAgain.setOnClickListener { setDataToPresenter(forceUpdate = true) }
val rowCount = resources.getInteger(R.integer.course_list_rows)
val columnsCount = resources.getInteger(R.integer.course_list_columns)
tableLayoutManager = TableLayoutManager(requireContext(), columnsCount, rowCount, RecyclerView.HORIZONTAL, false)
with(profileCoursesRecycler) {
layoutManager = tableLayoutManager
adapter = coursesAdapter
itemAnimator?.changeDuration = 0
val snapHelper = CoursesSnapHelper(rowCount)
snapHelper.attachToRecyclerView(this)
}
}
private fun setDataToPresenter(forceUpdate: Boolean = false) {
profileCoursesPresenter.fetchCourses(forceUpdate)
}
override fun onStart() {
super.onStart()
profileCoursesPresenter.attachView(this)
}
override fun onStop() {
profileCoursesPresenter.detachView(this)
super.onStop()
}
override fun setState(state: ProfileCoursesView.State) {
viewStateDelegate.switchState(state)
when (state) {
is ProfileCoursesView.State.Content -> {
coursesAdapter.items = state.courseListDataItems
(profileCoursesRecycler.layoutManager as? GridLayoutManager)
?.spanCount = min(resources.getInteger(R.integer.course_list_rows), state.courseListDataItems.size)
}
}
tableLayoutHorizontalSpanCountResolver.resolveSpanCount(coursesAdapter.itemCount).let { resolvedSpanCount ->
if (tableLayoutManager.spanCount != resolvedSpanCount) {
tableLayoutManager.spanCount = resolvedSpanCount
}
}
}
override fun setBlockingLoading(isLoading: Boolean) {
courseContinueViewDelegate.setBlockingLoading(isLoading)
}
override fun showCourse(course: Course, source: CourseViewSource, isAdaptive: Boolean) {
courseContinueViewDelegate.showCourse(course, source, isAdaptive)
}
override fun showSteps(course: Course, source: CourseViewSource, lastStep: LastStep) {
courseContinueViewDelegate.showSteps(course, source, lastStep)
}
override fun onSaveInstanceState(outState: Bundle) {
profileCoursesPresenter.onSaveInstanceState(outState)
super.onSaveInstanceState(outState)
}
}
|
apache-2.0
|
918d853d86627326cddcbb805aa30124
| 39.681081 | 121 | 0.738206 | 5.405891 | false | false | false | false |
WangDaYeeeeee/GeometricWeather
|
app/src/main/java/wangdaye/com/geometricweather/theme/weatherView/materialWeatherView/MaterialWeatherThemeDelegate.kt
|
1
|
4664
|
package wangdaye.com.geometricweather.theme.weatherView.materialWeatherView
import android.content.Context
import android.graphics.Color
import android.view.Window
import androidx.core.graphics.ColorUtils
import wangdaye.com.geometricweather.R
import wangdaye.com.geometricweather.common.utils.DisplayUtils
import wangdaye.com.geometricweather.theme.weatherView.WeatherThemeDelegate
import wangdaye.com.geometricweather.theme.weatherView.WeatherView
import wangdaye.com.geometricweather.theme.weatherView.WeatherView.WeatherKindRule
import wangdaye.com.geometricweather.theme.weatherView.materialWeatherView.implementor.*
class MaterialWeatherThemeDelegate: WeatherThemeDelegate {
companion object {
private fun getBrighterColor(color: Int): Int {
val hsv = FloatArray(3)
Color.colorToHSV(color, hsv)
hsv[1] = hsv[1] - 0.25f
hsv[2] = hsv[2] + 0.25f
return Color.HSVToColor(hsv)
}
private fun innerGetBackgroundColor(
context: Context,
@WeatherKindRule weatherKind: Int,
daytime: Boolean
): Int = when (weatherKind) {
WeatherView.WEATHER_KIND_CLEAR -> if (daytime) {
SunImplementor.getThemeColor()
} else {
MeteorShowerImplementor.getThemeColor()
}
WeatherView.WEATHER_KIND_CLOUDY ->
CloudImplementor.getThemeColor(context, CloudImplementor.TYPE_CLOUDY, daytime)
WeatherView.WEATHER_KIND_CLOUD ->
CloudImplementor.getThemeColor(context, CloudImplementor.TYPE_CLOUD, daytime)
WeatherView.WEATHER_KIND_FOG ->
CloudImplementor.getThemeColor(context, CloudImplementor.TYPE_FOG, daytime)
WeatherView.WEATHER_KIND_HAIL ->
HailImplementor.getThemeColor(daytime)
WeatherView.WEATHER_KIND_HAZE ->
CloudImplementor.getThemeColor(context, CloudImplementor.TYPE_HAZE, daytime)
WeatherView.WEATHER_KIND_RAINY ->
RainImplementor.getThemeColor(context, RainImplementor.TYPE_RAIN, daytime)
WeatherView.WEATHER_KIND_SLEET ->
RainImplementor.getThemeColor(context, RainImplementor.TYPE_SLEET, daytime)
WeatherView.WEATHER_KIND_SNOW ->
SnowImplementor.getThemeColor(daytime)
WeatherView.WEATHER_KIND_THUNDERSTORM ->
RainImplementor.getThemeColor(context, RainImplementor.TYPE_THUNDERSTORM, daytime)
WeatherView.WEATHER_KIND_THUNDER ->
CloudImplementor.getThemeColor(context, CloudImplementor.TYPE_THUNDER, daytime)
WeatherView.WEATHER_KIND_WIND ->
WindImplementor.getThemeColor(daytime)
else -> Color.TRANSPARENT
}
}
override fun getWeatherView(context: Context): WeatherView = MaterialWeatherView(context)
override fun getThemeColors(
context: Context,
weatherKind: Int,
daylight: Boolean,
): IntArray {
var color = innerGetBackgroundColor(context, weatherKind, daylight)
if (!daylight) {
color = getBrighterColor(color)
}
return intArrayOf(
color,
color,
ColorUtils.setAlphaComponent(color, (0.5 * 255).toInt())
)
}
override fun getBackgroundColor(
context: Context,
weatherKind: Int,
daylight: Boolean,
): Int {
return innerGetBackgroundColor(context, weatherKind, daylight)
}
override fun getHeaderHeight(context: Context): Int = (
context.resources.displayMetrics.heightPixels * 0.66
).toInt()
override fun getHeaderTextColor(context: Context): Int {
return Color.WHITE
}
override fun setSystemBarStyle(
context: Context,
window: Window,
statusShader: Boolean,
lightStatus: Boolean,
navigationShader: Boolean,
lightNavigation: Boolean
) {
DisplayUtils.setSystemBarStyle(
context,
window,
statusShader,
lightNavigation,
navigationShader,
lightNavigation
)
}
override fun getHomeCardRadius(context: Context): Float = context
.resources
.getDimension(R.dimen.material3_card_list_item_corner_radius)
override fun getHomeCardElevation(context: Context): Float =
DisplayUtils.dpToPx(context, 2f)
override fun getHomeCardMargins(context: Context): Int = context
.resources
.getDimensionPixelSize(R.dimen.little_margin)
}
|
lgpl-3.0
|
5ae968510e50b57935bcd420ee7202d8
| 33.301471 | 98 | 0.654803 | 4.664 | false | false | false | false |
savvasdalkitsis/gameframe
|
kotlin/src/main/java/com/savvasdalkitsis/gameframe/kotlin/TypeAliases.kt
|
1
|
974
|
/**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.kotlin
import android.view.View
import java.io.InputStream
typealias OnLayerVisibilityChangedListener = (visible:Boolean) -> Unit
typealias InputStreamProvider = () -> InputStream
typealias Action = () -> Unit
typealias ViewAction = (View) -> Unit
typealias TypeAction<T> = (T) -> Unit
|
apache-2.0
|
18ed0968a36f785546f7d57c92e67624
| 36.5 | 75 | 0.755647 | 4.290749 | false | false | false | false |
monarezio/Takuzu
|
app/src/main/java/net/zdendukmonarezio/takuzu/domain/game/models/board/GameBoard.kt
|
1
|
6064
|
package net.zdendukmonarezio.takuzu.domain.game.models.game
import net.zdendukmonarezio.takuzu.domain.common.extensions.*
import net.zdendukmonarezio.takuzu.domain.common.utils.FieldPickerUtil
import net.zdendukmonarezio.takuzu.domain.common.utils.ListUtil
import net.zdendukmonarezio.takuzu.domain.game.models.solver.Solver
/**
* Created by samuelkodytek on 06/03/2017.
*/
class GameBoard private constructor(fields: List<List<Field>>, lockedFields: List<Pair<Int, Int>>): Board {
private val fields: List<List<Field>> = fields
private val lockedFields: List<Pair<Int, Int>> = lockedFields
private constructor(fields: List<List<Field>>): this(
fields,
ListUtil.returnLockedPairs(fields)
)
/**
* returns a new Gameboard with the edited fields, sets the field even if its locked
*/
override fun set(x: Int, y: Int, field: Field): Board {
val editedFields = fields.set(x, fields[x].set(y, field))
return createBoard(editedFields, lockedFields)
}
override fun getProgress(): Int {
val locked = lockedFields.size
val sum = rows() * columns() - locked
val colored = fields.map { i -> i.filter { j -> j != Field.ANON }.size }.sum() - locked
return (colored.toDouble() / sum * 100).toInt()
}
override fun getFields(): List<List<Field>> = fields
override fun getField(i: Int): List<Field> = getFields()[i]
override fun getLockedFields(): List<Pair<Int, Int>> = lockedFields
override fun rows(): Int = getFields().size
override fun columns(): Int = getFields()[0].size
override fun validateRowEquivalency(): Boolean {
for(i in 0..rows()-1) {
val first = fields[i]
for(j in 0..rows()-1) {
if(i != j && first == fields[j] && (first.contains(Field.BLUE) || first.contains(Field.RED)))
return false
}
}
return true
}
override fun validateColumnEquivalency(): Boolean {
for(i in 0..columns()-1) {
val first = fields.map { k -> k[i] } //Tranforming into column
for (j in 0..columns()-1) {
val second = fields.map { k -> k[j] }
if(i != j && first == second && (first.contains(Field.BLUE) || first.contains(Field.RED)))
return false
}
}
return true
}
override fun validateAdjacency(): Boolean {
for(i in 0..rows() - 1) {
for(j in 0..columns() - 3) {
if ((fields[i][j] != Field.ANON || fields[i][j + 1] != Field.ANON || fields[i][j + 1] != Field.ANON) &&
fields[i][j] == fields[i][j + 1] && fields[i][j + 1] == fields[i][j + 2])
return false
}
}
for(i in 0..rows() - 3) {
for(j in 0..columns() - 1) {
if ((fields[i][j] != Field.ANON || fields[i + 1][j] != Field.ANON || fields[i + 2][j] != Field.ANON) &&
fields[i][j] == fields[i + 1][j] && fields[i + 1][j] == fields[i + 2][j])
return false
}
}
return true
}
override fun validateFieldAmount(): Boolean {
return validateRowEquivalency() && validateColumnEquivalency()
}
private fun validateRowsColorAmount(): Boolean {
for(i in 0..rows() - 1) {
val row = getField(i)
val size = row.filter { i -> i == Field.ANON }.size
if(size != 0) {
val blue = row.filter { i -> i == Field.BLUE }.size
val red = row.filter { i -> i == Field.RED }.size
if(blue > rows() / 2 || red > rows() / 2)
return false
}
}
return true
}
private fun validateColumnsColorAmount(): Boolean {
for (i in 0..columns() - 1) {
val column = getFields().map { item -> item[i] }
val size = column.filter { i -> i == Field.ANON }.size
if (size != 0) {
val blue = column.filter { i -> i == Field.BLUE }.size
val red = column.filter { i -> i == Field.RED }.size
if(blue > rows() / 2 || red > rows() / 2)
return false
}
}
return true
}
/**
* returns true if fields don't contain Field.ANON
*/
override fun isFilledIn(): Boolean {
return !fields.layeredAny { item -> item == Field.ANON }
}
override fun validateColorAmount(): Boolean {
return validateColumnsColorAmount() && validateRowsColorAmount()
}
override fun validateAll(): Boolean {
return isFilledIn()
&& validateAdjacency()
&& validateColumnEquivalency()
&& validateRowEquivalency()
&& validateFieldAmount()
&& validateColorAmount()
}
fun getNextAvailableMove(): Pair<Int, Int>? {
for(i in 0..rows()-1) {
for(j in 0..columns()-1) {
if(fields[i][j] == Field.ANON)
return Pair(i, j)
}
}
return null
}
companion object GameBoard {
/**
* returns a new board with generated lockedFields
*/
fun createBlankBoard(rows: Int, columns: Int): Board {
val gb = GameBoard(ListUtil.createNewFields(List(rows) {List(rows) { Field.ANON }}, rows * columns / 4))
if(!(gb.validateColorAmount() && gb.validateAdjacency()
&& gb.validateFieldAmount() && Solver(gb).isSolvable())) //Using the famous ostrich algorithm https://en.wikipedia.org/wiki/Ostrich_algorithm
return createBlankBoard(rows, columns)
return gb
}
fun createBoard(fields: List<List<Field>>, lockedFields: List<Pair<Int, Int>>): Board = GameBoard(fields, lockedFields)
fun createBoard(board: Board): Board = GameBoard(board.getFields(), board.getLockedFields())
}
}
|
mit
|
0d2b8e9fb4638d29eb0f1943de75d599
| 32.694444 | 161 | 0.541227 | 4.007931 | false | false | false | false |
Mindera/skeletoid
|
rxjava/src/main/kotlin/com/mindera/skeletoid/rxjava/OnErrorDoAction.kt
|
1
|
1654
|
package com.mindera.skeletoid.rxjava
import io.reactivex.Observable
import io.reactivex.Single
private const val LOG_TAG = "OnErrorDoRequest"
class RequestWrapper<T>(val result: T? = null, val throwable: Throwable? = null)
class ActionOnErrorException(val error: Throwable) : Exception()
fun <R> Single<R>.onErrorDoActionBeforeFailing(doAction: (Throwable) -> Single<R>): Single<R> =
map { RequestWrapper(it) }
.onErrorReturn { e -> RequestWrapper(throwable = e) }
.flatMap { wrapper ->
wrapper.throwable?.let { throwable ->
doAction(throwable).flatMap {
throw ActionOnErrorException(throwable)
@Suppress("UNREACHABLE_CODE")
Single.just(it) //Needed for compiler to know which type is this...
}
} ?: Single.just(wrapper.result)
}
fun <R> Observable<R>.onErrorDoActionBeforeFailing(doAction: (Throwable) -> Observable<R>): Observable<R> =
map { RequestWrapper(it) }
.onErrorReturn { e -> RequestWrapper(throwable = e) }
.flatMap { wrapper ->
wrapper.throwable?.let { throwable ->
doAction(throwable).flatMap {
throw ActionOnErrorException(throwable)
@Suppress("UNREACHABLE_CODE")
Observable.just(it) //Needed for compiler to know which type is this...
}
} ?: Observable.just(wrapper.result)
}
|
mit
|
b4315729f0bbb4a54cccc62eb741342e
| 43.72973 | 107 | 0.54474 | 5.07362 | false | false | false | false |
Heiner1/AndroidAPS
|
shared/src/main/java/info/nightscout/shared/SafeParse.kt
|
1
|
1897
|
package info.nightscout.shared
object SafeParse {
// private static Logger log = StacktraceLoggerWrapper.getLogger(SafeParse.class);
fun stringToDouble(inputString: String?, defaultValue: Double = 0.0): Double {
var input = inputString ?: return defaultValue
var result = defaultValue
input = input.replace(",", ".")
input = input.replace("−", "-")
if (input == "") return defaultValue
try {
result = input.toDouble()
} catch (e: Exception) {
// log.error("Error parsing " + input + " to double");
}
return result
}
fun stringToFloat(inputString: String?): Float {
var input = inputString ?: return 0f
var result = 0f
input = input.replace(",", ".")
input = input.replace("−", "-")
if (input == "") return 0f
try {
result = input.toFloat()
} catch (e: Exception) {
// log.error("Error parsing " + input + " to float");
}
return result
}
fun stringToInt(inputString: String?): Int {
var input = inputString ?: return 0
var result = 0
input = input.replace(",", ".")
input = input.replace("−", "-")
if (input == "") return 0
try {
result = input.toInt()
} catch (e: Exception) {
// log.error("Error parsing " + input + " to int");
}
return result
}
fun stringToLong(inputString: String?): Long {
var input = inputString ?: return 0L
var result = 0L
input = input.replace(",", ".")
input = input.replace("−", "-")
if (input == "") return 0L
try {
result = input.toLong()
} catch (e: Exception) {
// log.error("Error parsing " + input + " to long");
}
return result
}
}
|
agpl-3.0
|
b4ea00fe6b0cd7468601a6ca97da5525
| 29.983607 | 89 | 0.51297 | 4.476303 | false | false | false | false |
exponentjs/exponent
|
packages/expo-calendar/android/src/main/java/expo/modules/calendar/JsValuesMappers.kt
|
2
|
7214
|
package expo.modules.calendar
import android.provider.CalendarContract
import android.util.Log
internal fun reminderStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Reminders.METHOD_ALARM -> "alarm"
CalendarContract.Reminders.METHOD_ALERT -> "alert"
CalendarContract.Reminders.METHOD_EMAIL -> "email"
CalendarContract.Reminders.METHOD_SMS -> "sms"
CalendarContract.Reminders.METHOD_DEFAULT -> "default"
else -> "default"
}
internal fun reminderConstantMatchingString(string: String?): Int =
when (string) {
"alert" -> CalendarContract.Reminders.METHOD_ALERT
"alarm" -> CalendarContract.Reminders.METHOD_ALARM
"email" -> CalendarContract.Reminders.METHOD_EMAIL
"sms" -> CalendarContract.Reminders.METHOD_SMS
else -> CalendarContract.Reminders.METHOD_DEFAULT
}
internal fun calendarAllowedRemindersFromDBString(dbString: String): ArrayList<String> {
val array = ArrayList<String>()
for (constant in dbString.split(",").toTypedArray()) {
try {
array.add(reminderStringMatchingConstant(constant.toInt()))
} catch (e: NumberFormatException) {
Log.e(CalendarModule.TAG, "Couldn't convert reminder constant into an int.", e)
}
}
return array
}
internal fun calendarAllowedAvailabilitiesFromDBString(dbString: String): ArrayList<String> {
val availabilitiesStrings = ArrayList<String>()
for (availabilityId in dbString.split(",").toTypedArray()) {
when (availabilityId.toInt()) {
CalendarContract.Events.AVAILABILITY_BUSY -> availabilitiesStrings.add("busy")
CalendarContract.Events.AVAILABILITY_FREE -> availabilitiesStrings.add("free")
CalendarContract.Events.AVAILABILITY_TENTATIVE -> availabilitiesStrings.add("tentative")
}
}
return availabilitiesStrings
}
internal fun availabilityStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Events.AVAILABILITY_BUSY -> "busy"
CalendarContract.Events.AVAILABILITY_FREE -> "free"
CalendarContract.Events.AVAILABILITY_TENTATIVE -> "tentative"
else -> "busy"
}
internal fun availabilityConstantMatchingString(string: String): Int =
when (string) {
"free" -> CalendarContract.Events.AVAILABILITY_FREE
"tentative" -> CalendarContract.Events.AVAILABILITY_TENTATIVE
else -> CalendarContract.Events.AVAILABILITY_BUSY
}
internal fun accessStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Events.ACCESS_CONFIDENTIAL -> "confidential"
CalendarContract.Events.ACCESS_PRIVATE -> "private"
CalendarContract.Events.ACCESS_PUBLIC -> "public"
CalendarContract.Events.ACCESS_DEFAULT -> "default"
else -> "default"
}
internal fun accessConstantMatchingString(string: String): Int =
when (string) {
"confidential" -> CalendarContract.Events.ACCESS_CONFIDENTIAL
"private" -> CalendarContract.Events.ACCESS_PRIVATE
"public" -> CalendarContract.Events.ACCESS_PUBLIC
else -> CalendarContract.Events.ACCESS_DEFAULT
}
internal fun calAccessStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR -> "contributor"
CalendarContract.Calendars.CAL_ACCESS_EDITOR -> "editor"
CalendarContract.Calendars.CAL_ACCESS_FREEBUSY -> "freebusy"
CalendarContract.Calendars.CAL_ACCESS_OVERRIDE -> "override"
CalendarContract.Calendars.CAL_ACCESS_OWNER -> "owner"
CalendarContract.Calendars.CAL_ACCESS_READ -> "read"
CalendarContract.Calendars.CAL_ACCESS_RESPOND -> "respond"
CalendarContract.Calendars.CAL_ACCESS_ROOT -> "root"
CalendarContract.Calendars.CAL_ACCESS_NONE -> "none"
else -> "none"
}
internal fun calAccessConstantMatchingString(string: String): Int =
when (string) {
"contributor" -> CalendarContract.Calendars.CAL_ACCESS_CONTRIBUTOR
"editor" -> CalendarContract.Calendars.CAL_ACCESS_EDITOR
"freebusy" -> CalendarContract.Calendars.CAL_ACCESS_FREEBUSY
"override" -> CalendarContract.Calendars.CAL_ACCESS_OVERRIDE
"owner" -> CalendarContract.Calendars.CAL_ACCESS_OWNER
"read" -> CalendarContract.Calendars.CAL_ACCESS_READ
"respond" -> CalendarContract.Calendars.CAL_ACCESS_RESPOND
"root" -> CalendarContract.Calendars.CAL_ACCESS_ROOT
else -> CalendarContract.Calendars.CAL_ACCESS_NONE
}
internal fun attendeeRelationshipStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Attendees.RELATIONSHIP_ATTENDEE -> "attendee"
CalendarContract.Attendees.RELATIONSHIP_ORGANIZER -> "organizer"
CalendarContract.Attendees.RELATIONSHIP_PERFORMER -> "performer"
CalendarContract.Attendees.RELATIONSHIP_SPEAKER -> "speaker"
CalendarContract.Attendees.RELATIONSHIP_NONE -> "none"
else -> "none"
}
internal fun attendeeRelationshipConstantMatchingString(string: String): Int =
when (string) {
"attendee" -> CalendarContract.Attendees.RELATIONSHIP_ATTENDEE
"organizer" -> CalendarContract.Attendees.RELATIONSHIP_ORGANIZER
"performer" -> CalendarContract.Attendees.RELATIONSHIP_PERFORMER
"speaker" -> CalendarContract.Attendees.RELATIONSHIP_SPEAKER
else -> CalendarContract.Attendees.RELATIONSHIP_NONE
}
internal fun attendeeTypeStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Attendees.TYPE_OPTIONAL -> "optional"
CalendarContract.Attendees.TYPE_REQUIRED -> "required"
CalendarContract.Attendees.TYPE_RESOURCE -> "resource"
CalendarContract.Attendees.TYPE_NONE -> "none"
else -> "none"
}
internal fun attendeeTypeConstantMatchingString(string: String): Int =
when (string) {
"optional" -> CalendarContract.Attendees.TYPE_OPTIONAL
"required" -> CalendarContract.Attendees.TYPE_REQUIRED
"resource" -> CalendarContract.Attendees.TYPE_RESOURCE
else -> CalendarContract.Attendees.TYPE_NONE
}
internal fun calendarAllowedAttendeeTypesFromDBString(dbString: String): ArrayList<String> {
val array = ArrayList<String>()
for (constant in dbString.split(",").toTypedArray()) {
try {
array.add(attendeeTypeStringMatchingConstant(constant.toInt()))
} catch (e: NumberFormatException) {
Log.e(CalendarModule.TAG, "Couldn't convert attendee constant into an int.", e)
}
}
return array
}
internal fun attendeeStatusStringMatchingConstant(constant: Int): String =
when (constant) {
CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED -> "accepted"
CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED -> "declined"
CalendarContract.Attendees.ATTENDEE_STATUS_INVITED -> "invited"
CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE -> "tentative"
CalendarContract.Attendees.ATTENDEE_STATUS_NONE -> "none"
else -> "none"
}
internal fun attendeeStatusConstantMatchingString(string: String): Int =
when (string) {
"accepted" -> CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED
"declined" -> CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED
"invited" -> CalendarContract.Attendees.ATTENDEE_STATUS_INVITED
"tentative" -> CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE
else -> CalendarContract.Attendees.ATTENDEE_STATUS_NONE
}
|
bsd-3-clause
|
3e047f4f541298f2d929a4bd21e1a3af
| 40.699422 | 94 | 0.751456 | 4.340554 | false | false | false | false |
realm/realm-java
|
examples/coroutinesExample/src/main/java/io/realm/examples/coroutinesexample/ui/details/DetailsFragment.kt
|
1
|
2541
|
/*
* Copyright 2020 Realm 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 io.realm.examples.coroutinesexample.ui.details
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import io.realm.examples.coroutinesexample.databinding.FragmentDetailsBinding
import kotlin.time.ExperimentalTime
@ExperimentalTime
class DetailsFragment : Fragment() {
private val viewModel: DetailsViewModel by viewModels()
private lateinit var binding: FragmentDetailsBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return FragmentDetailsBinding.inflate(inflater, container, false)
.also { binding ->
this.binding = binding
binding.lifecycleOwner = viewLifecycleOwner
binding.viewModel = viewModel
setupLiveData()
}.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val id = requireNotNull(requireArguments().getString(ARG_ID))
viewModel.loadDetails(id)
}
private fun setupLiveData() {
viewModel.read.observe(viewLifecycleOwner, Observer {
setRead()
})
}
private fun setRead() {
with(binding.read) {
animate().alpha(1.0f)
}
}
data class ArgsBundle(val id: String)
companion object {
const val TAG = "DetailsFragment"
private const val ARG_ID = "id"
fun instantiate(argsBundle: ArgsBundle): DetailsFragment {
return DetailsFragment().apply {
arguments = Bundle().apply {
putString(ARG_ID, argsBundle.id)
}
}
}
}
}
|
apache-2.0
|
1111feea34dd103850ac85c66a2cdae6
| 28.894118 | 77 | 0.661944 | 4.962891 | false | false | false | false |
bajdcc/jMiniLang
|
src/main/kotlin/com/bajdcc/util/lexer/automata/dfa/DFAStatus.kt
|
1
|
1514
|
package com.bajdcc.util.lexer.automata.dfa
import com.bajdcc.util.VisitBag
import com.bajdcc.util.lexer.automata.BreadthFirstSearch
/**
* DFA状态
*
* @author bajdcc
*/
class DFAStatus {
/**
* 出边集合
*/
var outEdges = mutableListOf<DFAEdge>()
/**
* 入边集合
*/
var inEdges = mutableListOf<DFAEdge>()
/**
* 数据
*/
var data = DFAStatusData()
/**
* 用于遍历包括该状态在内的所有状态(连通),结果存放在PATH中
*
* @param bfs 遍历算法
*/
fun visit(bfs: BreadthFirstSearch<DFAEdge, DFAStatus>) {
val stack = bfs.arrStatus
val set = mutableSetOf<DFAStatus>()
stack.clear()
set.add(this)
stack.add(this)
var i = 0
while (i < stack.size) {// 遍历每个状态
val status = stack[i]
val bag = VisitBag()
bfs.visitBegin(status, bag)
if (bag.visitChildren) {
// 遍历状态的出边
// 边未被访问,且边类型符合要求
status.outEdges.asSequence().filter { edge -> !set.contains(edge.end) && bfs.testEdge(edge) }.forEach {// 边未被访问,且边类型符合要求
edge ->
stack.add(edge.end!!)
set.add(edge.end!!)
}
}
if (bag.visitEnd) {
bfs.visitEnd(status)
}
i++
}
}
}
|
mit
|
fb54633fe1f880ed9cba505ba57034ad
| 22.206897 | 136 | 0.493314 | 3.59893 | false | false | false | false |
k9mail/k-9
|
app/ui/legacy/src/main/java/com/fsck/k9/activity/FolderInfoHolder.kt
|
2
|
1620
|
package com.fsck.k9.activity
import com.fsck.k9.Account
import com.fsck.k9.mailstore.Folder
import com.fsck.k9.mailstore.FolderType
import com.fsck.k9.mailstore.LocalFolder
import com.fsck.k9.ui.folders.FolderNameFormatter
class FolderInfoHolder(
private val folderNameFormatter: FolderNameFormatter,
localFolder: LocalFolder,
account: Account
) {
@JvmField val databaseId = localFolder.databaseId
@JvmField val displayName = getDisplayName(account, localFolder)
@JvmField var loading = false
@JvmField var moreMessages = localFolder.hasMoreMessages()
private fun getDisplayName(account: Account, localFolder: LocalFolder): String {
val folderId = localFolder.databaseId
val folder = Folder(
id = folderId,
name = localFolder.name,
type = getFolderType(account, folderId),
isLocalOnly = localFolder.isLocalOnly
)
return folderNameFormatter.displayName(folder)
}
companion object {
@JvmStatic
fun getFolderType(account: Account, folderId: Long): FolderType {
return when (folderId) {
account.inboxFolderId -> FolderType.INBOX
account.outboxFolderId -> FolderType.OUTBOX
account.archiveFolderId -> FolderType.ARCHIVE
account.draftsFolderId -> FolderType.DRAFTS
account.sentFolderId -> FolderType.SENT
account.spamFolderId -> FolderType.SPAM
account.trashFolderId -> FolderType.TRASH
else -> FolderType.REGULAR
}
}
}
}
|
apache-2.0
|
391f390e1d59e5ebbabf9d3c9188bda9
| 35 | 84 | 0.662963 | 4.954128 | false | false | false | false |
Maccimo/intellij-community
|
platform/platform-impl/src/com/intellij/ide/plugins/DynamicPlugins.kt
|
2
|
56634
|
// 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.ide.plugins
import com.fasterxml.jackson.databind.type.TypeFactory
import com.intellij.application.options.RegistryManager
import com.intellij.configurationStore.StoreUtil.Companion.saveDocumentsAndProjectsAndApp
import com.intellij.configurationStore.jdomSerializer
import com.intellij.configurationStore.runInAutoSaveDisabledMode
import com.intellij.diagnostic.MessagePool
import com.intellij.diagnostic.PerformanceWatcher
import com.intellij.diagnostic.hprof.action.SystemTempFilenameSupplier
import com.intellij.diagnostic.hprof.analysis.AnalyzeClassloaderReferencesGraph
import com.intellij.diagnostic.hprof.analysis.HProfAnalysis
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.ide.actions.RevealFileAction
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.plugins.cl.PluginAwareClassLoader
import com.intellij.ide.plugins.cl.PluginClassLoader
import com.intellij.ide.ui.TopHitCache
import com.intellij.ide.ui.UIThemeProvider
import com.intellij.ide.util.TipDialog
import com.intellij.idea.IdeaLogger
import com.intellij.lang.Language
import com.intellij.notification.NotificationType
import com.intellij.notification.NotificationsManager
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.impl.ActionManagerImpl
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.actionSystem.impl.PresentationFactory
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.application.impl.LaterInvocator
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.ExtensionDescriptor
import com.intellij.openapi.extensions.ExtensionPointDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.keymap.impl.BundledKeymapBean
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.util.PotemkinProgress
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.updateSettings.impl.UpdateChecker
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.objectTree.ThrowableInterner
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.newvfs.FileAttribute
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.IdeFrameImpl
import com.intellij.openapi.wm.impl.ProjectFrameHelper
import com.intellij.psi.util.CachedValuesManager
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.ui.IconDeferrer
import com.intellij.ui.mac.touchbar.TouchbarSupport
import com.intellij.util.CachedValuesManagerImpl
import com.intellij.util.MemoryDumpHelper
import com.intellij.util.ReflectionUtil
import com.intellij.util.SystemProperties
import com.intellij.util.containers.WeakList
import com.intellij.util.messages.impl.MessageBusEx
import com.intellij.util.ref.GCWatcher
import net.sf.cglib.core.ClassNameReader
import java.awt.KeyboardFocusManager
import java.awt.Window
import java.nio.channels.FileChannel
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import java.text.SimpleDateFormat
import java.util.*
import java.util.function.Predicate
import javax.swing.JComponent
import javax.swing.ToolTipManager
import kotlin.collections.component1
import kotlin.collections.component2
private val LOG = logger<DynamicPlugins>()
private val classloadersFromUnloadedPlugins = mutableMapOf<PluginId, WeakList<PluginClassLoader>>()
object DynamicPlugins {
@JvmStatic
@JvmOverloads
fun allowLoadUnloadWithoutRestart(descriptor: IdeaPluginDescriptorImpl,
baseDescriptor: IdeaPluginDescriptorImpl? = null,
context: List<IdeaPluginDescriptorImpl> = emptyList()): Boolean {
val reason = checkCanUnloadWithoutRestart(module = descriptor, parentModule = baseDescriptor, context = context)
if (reason != null) {
LOG.info(reason)
}
return reason == null
}
/**
* @return true if the requested enabled state was applied without restart, false if restart is required
*/
fun loadPlugins(descriptors: Collection<IdeaPluginDescriptor>): Boolean {
return updateDescriptorsWithoutRestart(descriptors, load = true) {
loadPlugin(it, checkImplementationDetailDependencies = true)
}
}
/**
* @return true if the requested enabled state was applied without restart, false if restart is required
*/
fun unloadPlugins(
descriptors: Collection<IdeaPluginDescriptor>,
project: Project? = null,
parentComponent: JComponent? = null,
options: UnloadPluginOptions = UnloadPluginOptions(disable = true),
): Boolean {
return updateDescriptorsWithoutRestart(descriptors, load = false) {
unloadPluginWithProgress(project, parentComponent, it, options)
}
}
private fun updateDescriptorsWithoutRestart(
plugins: Collection<IdeaPluginDescriptor>,
load: Boolean,
executor: (IdeaPluginDescriptorImpl) -> Boolean,
): Boolean {
if (plugins.isEmpty()) {
return true
}
val pluginSet = PluginManagerCore.getPluginSet()
@Suppress("UNCHECKED_CAST")
val descriptors = (plugins as Collection<IdeaPluginDescriptorImpl>).filter { pluginSet.isPluginEnabled(it.pluginId) != load }
val operationText = if (load) "load" else "unload"
val message = descriptors.joinToString(prefix = "Plugins to $operationText: [", postfix = "]")
LOG.info(message)
if (!descriptors.all { allowLoadUnloadWithoutRestart(it, context = descriptors) }) {
return false
}
// todo plugin installation should be done not in this method
var allPlugins = pluginSet.allPlugins
for (descriptor in descriptors) {
if (!allPlugins.contains(descriptor)) {
allPlugins = allPlugins + descriptor
}
}
// todo make internal:
// 1) ModuleGraphBase;
// 2) SortedModuleGraph;
// 3) SortedModuleGraph.topologicalComparator;
// 4) PluginSetBuilder.sortedModuleGraph.
var comparator = PluginSetBuilder(allPlugins)
.moduleGraph
.topologicalComparator
if (!load) {
comparator = comparator.reversed()
}
for (descriptor in descriptors.sortedWith(comparator)) {
descriptor.isEnabled = load
if (!executor.invoke(descriptor)) {
LOG.info("Failed to $operationText: $descriptor, restart required")
InstalledPluginsState.getInstance().isRestartRequired = true
return false
}
}
return true
}
fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl): String? {
return checkCanUnloadWithoutRestart(module, parentModule = null)
}
/**
* @param context Plugins which are being loaded at the same time as [module]
*/
private fun checkCanUnloadWithoutRestart(module: IdeaPluginDescriptorImpl,
parentModule: IdeaPluginDescriptorImpl?,
optionalDependencyPluginId: PluginId? = null,
context: List<IdeaPluginDescriptorImpl> = emptyList(),
checkImplementationDetailDependencies: Boolean = true): String? {
if (parentModule == null) {
if (module.isRequireRestart) {
return "Plugin ${module.pluginId} is explicitly marked as requiring restart"
}
if (module.productCode != null && !module.isBundled && !PluginManagerCore.isDevelopedByJetBrains(module)) {
return "Plugin ${module.pluginId} is a paid plugin"
}
if (InstalledPluginsState.getInstance().isRestartRequired) {
return InstalledPluginsState.RESTART_REQUIRED_MESSAGE
}
}
val pluginSet = PluginManagerCore.getPluginSet()
if (classloadersFromUnloadedPlugins[module.pluginId]?.isEmpty() == false) {
return "Not allowing load/unload of ${module.pluginId} because of incomplete previous unload operation for that plugin"
}
findMissingRequiredDependency(module, context, pluginSet)?.let { pluginDependency ->
return "Required dependency ${pluginDependency} of plugin ${module.pluginId} is not currently loaded"
}
val app = ApplicationManager.getApplication()
if (parentModule == null) {
if (!RegistryManager.getInstance().`is`("ide.plugins.allow.unload")) {
if (!allowLoadUnloadSynchronously(module)) {
return "ide.plugins.allow.unload is disabled and synchronous load/unload is not possible for ${module.pluginId}"
}
return null
}
try {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).checkUnloadPlugin(module)
}
catch (e: CannotUnloadPluginException) {
return e.cause?.localizedMessage ?: "checkUnloadPlugin listener blocked plugin unload"
}
}
if (!Registry.`is`("ide.plugins.allow.unload.from.sources")) {
if (pluginSet.findEnabledPlugin(module.pluginId) != null && module === parentModule && !module.isUseIdeaClassLoader) {
val pluginClassLoader = module.pluginClassLoader
if (pluginClassLoader != null && pluginClassLoader !is PluginClassLoader && !app.isUnitTestMode) {
return "Plugin ${module.pluginId} is not unload-safe because of use of ${pluginClassLoader.javaClass.name} as the default class loader. " +
"For example, the IDE is started from the sources with the plugin."
}
}
}
val epNameToExtensions = module.epNameToExtensions
if (epNameToExtensions != null) {
doCheckExtensionsCanUnloadWithoutRestart(
extensions = epNameToExtensions,
descriptor = module,
baseDescriptor = parentModule,
app = app,
optionalDependencyPluginId = optionalDependencyPluginId,
context = context,
pluginSet = pluginSet,
)?.let { return it }
}
checkNoComponentsOrServiceOverrides(module)?.let { return it }
ActionManagerImpl.checkUnloadActions(module)?.let { return it }
for (moduleRef in module.content.modules) {
if (pluginSet.isModuleEnabled(moduleRef.name)) {
val subModule = moduleRef.requireDescriptor()
checkCanUnloadWithoutRestart(module = subModule,
parentModule = module,
optionalDependencyPluginId = null,
context = context)?.let {
return "$it in optional dependency on ${subModule.pluginId}"
}
}
}
for (dependency in module.pluginDependencies) {
if (pluginSet.isPluginEnabled(dependency.pluginId)) {
checkCanUnloadWithoutRestart(dependency.subDescriptor ?: continue, parentModule ?: module, null, context)?.let {
return "$it in optional dependency on ${dependency.pluginId}"
}
}
}
// if not a sub plugin descriptor, then check that any dependent plugin also reloadable
if (parentModule != null && module !== parentModule) {
return null
}
var dependencyMessage: String? = null
processOptionalDependenciesOnPlugin(module, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor ->
if (subDescriptor.packagePrefix == null
|| mainDescriptor.pluginId.idString == "org.jetbrains.kotlin" || mainDescriptor.pluginId == PluginManagerCore.JAVA_PLUGIN_ID) {
dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId}" +
" does not have a separate classloader for the dependency"
return@processOptionalDependenciesOnPlugin false
}
dependencyMessage = checkCanUnloadWithoutRestart(subDescriptor, mainDescriptor, subDescriptor.pluginId, context)
if (dependencyMessage == null) {
true
}
else {
dependencyMessage = "Plugin ${subDescriptor.pluginId} that optionally depends on ${module.pluginId} requires restart: $dependencyMessage"
false
}
}
if (dependencyMessage == null && checkImplementationDetailDependencies) {
val contextWithImplementationDetails = context.toMutableList()
contextWithImplementationDetails.add(module)
processImplementationDetailDependenciesOnPlugin(module, pluginSet, contextWithImplementationDetails::add)
processImplementationDetailDependenciesOnPlugin(module, pluginSet) { dependentDescriptor ->
// don't check a plugin that is an implementation-detail dependency on the current plugin if it has other disabled dependencies
// and won't be loaded anyway
if (findMissingRequiredDependency(dependentDescriptor, contextWithImplementationDetails, pluginSet) == null) {
dependencyMessage = checkCanUnloadWithoutRestart(module = dependentDescriptor,
parentModule = null,
context = contextWithImplementationDetails,
checkImplementationDetailDependencies = false)
if (dependencyMessage != null) {
dependencyMessage = "implementation-detail plugin ${dependentDescriptor.pluginId} which depends on ${module.pluginId}" +
" requires restart: $dependencyMessage"
}
}
dependencyMessage == null
}
}
return dependencyMessage
}
private fun findMissingRequiredDependency(descriptor: IdeaPluginDescriptorImpl,
context: List<IdeaPluginDescriptorImpl>,
pluginSet: PluginSet): PluginId? {
for (dependency in descriptor.pluginDependencies) {
if (!dependency.isOptional &&
!PluginManagerCore.isModuleDependency(dependency.pluginId) &&
!pluginSet.isPluginEnabled(dependency.pluginId) &&
context.none { it.pluginId == dependency.pluginId }) {
return dependency.pluginId
}
}
return null
}
/**
* Checks if the plugin can be loaded/unloaded immediately when the corresponding action is invoked in the
* plugins settings, without pressing the Apply button.
*/
@JvmStatic
fun allowLoadUnloadSynchronously(module: IdeaPluginDescriptorImpl): Boolean {
val extensions = (module.unsortedEpNameToExtensionElements.takeIf { it.isNotEmpty() } ?: module.appContainerDescriptor.extensions)
if (extensions != null && !extensions.all {
it.key == UIThemeProvider.EP_NAME.name ||
it.key == BundledKeymapBean.EP_NAME.name
}) {
return false
}
return checkNoComponentsOrServiceOverrides(module) == null && module.actions.isEmpty()
}
private fun checkNoComponentsOrServiceOverrides(module: IdeaPluginDescriptorImpl): String? {
val id = module.pluginId
return checkNoComponentsOrServiceOverrides(id, module.appContainerDescriptor)
?: checkNoComponentsOrServiceOverrides(id, module.projectContainerDescriptor)
?: checkNoComponentsOrServiceOverrides(id, module.moduleContainerDescriptor)
}
private fun checkNoComponentsOrServiceOverrides(pluginId: PluginId?, containerDescriptor: ContainerDescriptor): String? {
if (!containerDescriptor.components.isNullOrEmpty()) {
return "Plugin $pluginId is not unload-safe because it declares components"
}
if (containerDescriptor.services.any { it.overrides }) {
return "Plugin $pluginId is not unload-safe because it overrides services"
}
return null
}
fun unloadPluginWithProgress(project: Project? = null,
parentComponent: JComponent?,
pluginDescriptor: IdeaPluginDescriptorImpl,
options: UnloadPluginOptions): Boolean {
var result = false
if (!allowLoadUnloadSynchronously(pluginDescriptor)) {
runInAutoSaveDisabledMode {
val saveAndSyncHandler = SaveAndSyncHandler.getInstance()
saveAndSyncHandler.saveSettingsUnderModalProgress(ApplicationManager.getApplication())
for (openProject in ProjectUtil.getOpenProjects()) {
saveAndSyncHandler.saveSettingsUnderModalProgress(openProject)
}
}
}
val indicator = PotemkinProgress(IdeBundle.message("plugins.progress.unloading.plugin.title", pluginDescriptor.name),
project,
parentComponent,
null)
indicator.runInSwingThread {
result = unloadPlugin(pluginDescriptor, options.withSave(false))
}
return result
}
data class UnloadPluginOptions(
var disable: Boolean = true,
var isUpdate: Boolean = false,
var save: Boolean = true,
var requireMemorySnapshot: Boolean = false,
var waitForClassloaderUnload: Boolean = false,
var checkImplementationDetailDependencies: Boolean = true,
var unloadWaitTimeout: Int? = null,
) {
fun withUpdate(isUpdate: Boolean): UnloadPluginOptions = also {
this.isUpdate = isUpdate
}
fun withWaitForClassloaderUnload(waitForClassloaderUnload: Boolean) = also {
this.waitForClassloaderUnload = waitForClassloaderUnload
}
fun withDisable(disable: Boolean) = also {
this.disable = disable
}
fun withRequireMemorySnapshot(requireMemorySnapshot: Boolean) = also {
this.requireMemorySnapshot = requireMemorySnapshot
}
fun withUnloadWaitTimeout(unloadWaitTimeout: Int) = also {
this.unloadWaitTimeout = unloadWaitTimeout
}
fun withSave(save: Boolean) = also {
this.save = save
}
fun withCheckImplementationDetailDependencies(checkImplementationDetailDependencies: Boolean) = also {
this.checkImplementationDetailDependencies = checkImplementationDetailDependencies
}
}
@JvmOverloads
fun unloadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl,
options: UnloadPluginOptions = UnloadPluginOptions(disable = true)): Boolean {
val app = ApplicationManager.getApplication() as ApplicationImpl
val pluginId = pluginDescriptor.pluginId
val pluginSet = PluginManagerCore.getPluginSet()
if (options.checkImplementationDetailDependencies) {
processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor ->
dependentDescriptor.isEnabled = false
unloadPlugin(dependentDescriptor, UnloadPluginOptions(save = false,
waitForClassloaderUnload = false,
checkImplementationDetailDependencies = false))
true
}
}
try {
if (options.save) {
saveDocumentsAndProjectsAndApp(true)
}
TipDialog.hideForProject(null)
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginUnload(pluginDescriptor, options.isUpdate)
IdeEventQueue.getInstance().flushQueue()
}
catch (e: Exception) {
logger<DynamicPlugins>().error(e)
logDescriptorUnload(pluginDescriptor, success = false)
return false
}
var classLoaderUnloaded: Boolean
val classLoaders = WeakList<PluginClassLoader>()
try {
app.runWriteAction {
// must be after flushQueue (e.g. https://youtrack.jetbrains.com/issue/IDEA-252010)
val forbidGettingServicesToken = app.forbidGettingServices("Plugin $pluginId being unloaded.")
try {
(pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.let {
classLoaders.add(it)
}
// https://youtrack.jetbrains.com/issue/IDEA-245031
// mark plugin classloaders as being unloaded to ensure that new extension instances will be not created during unload
setClassLoaderState(pluginDescriptor, PluginClassLoader.UNLOAD_IN_PROGRESS)
unloadLoadedOptionalDependenciesOnPlugin(pluginDescriptor, pluginSet = pluginSet, classLoaders = classLoaders)
unloadDependencyDescriptors(pluginDescriptor, pluginSet, classLoaders)
unloadModuleDescriptorNotRecursively(pluginDescriptor)
clearPluginClassLoaderParentListCache(pluginSet)
app.extensionArea.clearUserCache()
for (project in ProjectUtil.getOpenProjects()) {
(project.extensionArea as ExtensionsAreaImpl).clearUserCache()
}
clearCachedValues()
jdomSerializer.clearSerializationCaches()
TypeFactory.defaultInstance().clearCache()
app.getServiceIfCreated(TopHitCache::class.java)?.clear()
ActionToolbarImpl.resetAllToolbars()
PresentationFactory.clearPresentationCaches()
TouchbarSupport.reloadAllActions()
(serviceIfCreated<NotificationsManager>() as? NotificationsManagerImpl)?.expireAll()
MessagePool.getInstance().clearErrors()
LaterInvocator.purgeExpiredItems()
FileAttribute.resetRegisteredIds()
resetFocusCycleRoot()
clearNewFocusOwner()
hideTooltip()
PerformanceWatcher.getInstance().clearFreezeStacktraces()
for (classLoader in classLoaders) {
IconLoader.detachClassLoader(classLoader)
Language.unregisterAllLanguagesIn(classLoader, pluginDescriptor)
}
serviceIfCreated<IconDeferrer>()?.clearCache()
(ApplicationManager.getApplication().messageBus as MessageBusEx).clearPublisherCache()
@Suppress("TestOnlyProblems")
(ProjectManager.getInstanceIfCreated() as? ProjectManagerImpl)?.disposeDefaultProjectAndCleanupComponentsForDynamicPluginTests()
val newPluginSet = pluginSet.withoutModule(
module = pluginDescriptor,
disable = options.disable,
).createPluginSetWithEnabledModulesMap()
PluginManagerCore.setPluginSet(newPluginSet)
}
finally {
try {
forbidGettingServicesToken.finish()
}
finally {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginUnloaded(pluginDescriptor, options.isUpdate)
}
}
}
}
catch (e: Exception) {
logger<DynamicPlugins>().error(e)
}
finally {
IdeEventQueue.getInstance().flushQueue()
// do it after IdeEventQueue.flushQueue() to ensure that Disposer.isDisposed(...) works as expected in flushed tasks.
Disposer.clearDisposalTraces() // ensure we don't have references to plugin classes in disposal backtraces
ThrowableInterner.clearInternedBacktraces()
IdeaLogger.ourErrorsOccurred = null // ensure we don't have references to plugin classes in exception stacktraces
clearTemporaryLostComponent()
clearCglibStopBacktrace()
if (app.isUnitTestMode && pluginDescriptor.pluginClassLoader !is PluginClassLoader) {
classLoaderUnloaded = true
}
else {
classloadersFromUnloadedPlugins[pluginId] = classLoaders
ClassLoaderTreeChecker(pluginDescriptor, classLoaders).checkThatClassLoaderNotReferencedByPluginClassLoader()
val checkClassLoaderUnload = options.waitForClassloaderUnload ||
options.requireMemorySnapshot ||
Registry.`is`("ide.plugins.snapshot.on.unload.fail")
val timeout = if (checkClassLoaderUnload) {
options.unloadWaitTimeout ?: Registry.intValue("ide.plugins.unload.timeout", 5000)
}
else {
0
}
classLoaderUnloaded = unloadClassLoader(pluginDescriptor, timeout)
if (classLoaderUnloaded) {
LOG.info("Successfully unloaded plugin $pluginId (classloader unload checked=$checkClassLoaderUnload)")
classloadersFromUnloadedPlugins.remove(pluginId)
}
else {
if ((options.requireMemorySnapshot || (Registry.`is`("ide.plugins.snapshot.on.unload.fail") && !app.isUnitTestMode)) &&
MemoryDumpHelper.memoryDumpAvailable()) {
classLoaderUnloaded = saveMemorySnapshot(pluginId)
}
else {
LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded")
}
}
if (!classLoaderUnloaded) {
InstalledPluginsState.getInstance().isRestartRequired = true
}
logDescriptorUnload(pluginDescriptor, success = classLoaderUnloaded)
}
}
if (!classLoaderUnloaded) {
setClassLoaderState(pluginDescriptor, PluginAwareClassLoader.ACTIVE)
}
ActionToolbarImpl.updateAllToolbarsImmediately(true)
return classLoaderUnloaded
}
private fun resetFocusCycleRoot() {
val focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager()
var focusCycleRoot = focusManager.currentFocusCycleRoot
if (focusCycleRoot != null) {
while (focusCycleRoot != null && focusCycleRoot !is IdeFrameImpl) {
focusCycleRoot = focusCycleRoot.parent
}
if (focusCycleRoot is IdeFrameImpl) {
focusManager.setGlobalCurrentFocusCycleRoot(focusCycleRoot)
}
else {
focusCycleRoot = focusManager.currentFocusCycleRoot
val dataContext = DataManager.getInstance().getDataContext(focusCycleRoot)
val project = CommonDataKeys.PROJECT.getData(dataContext)
if (project != null) {
val projectFrame = WindowManager.getInstance().getFrame(project)
if (projectFrame != null) {
focusManager.setGlobalCurrentFocusCycleRoot(projectFrame)
}
}
}
}
}
private fun unloadLoadedOptionalDependenciesOnPlugin(dependencyPlugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
classLoaders: WeakList<PluginClassLoader>) {
val dependencyClassloader = dependencyPlugin.classLoader
processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = true) { mainDescriptor, subDescriptor ->
val classLoader = subDescriptor.classLoader
unloadModuleDescriptorNotRecursively(subDescriptor)
// this additional code is required because in unit tests PluginClassLoader is not used
if (mainDescriptor !== subDescriptor) {
subDescriptor.pluginClassLoader = null
}
if (dependencyClassloader is PluginClassLoader && classLoader is PluginClassLoader) {
LOG.info("Detach classloader $dependencyClassloader from $classLoader")
if (mainDescriptor !== subDescriptor && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
classLoader.state = PluginClassLoader.UNLOAD_IN_PROGRESS
}
}
true
}
}
private fun unloadDependencyDescriptors(plugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
classLoaders: WeakList<PluginClassLoader>) {
for (dependency in plugin.pluginDependencies) {
val subDescriptor = dependency.subDescriptor ?: continue
val classLoader = subDescriptor.pluginClassLoader
if (!pluginSet.isPluginEnabled(dependency.pluginId)) {
LOG.assertTrue(classLoader == null,
"Expected not to have any sub descriptor classloader when dependency ${dependency.pluginId} is not loaded")
continue
}
if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
}
unloadDependencyDescriptors(subDescriptor, pluginSet, classLoaders)
unloadModuleDescriptorNotRecursively(subDescriptor)
subDescriptor.pluginClassLoader = null
}
for (module in plugin.content.modules) {
val subDescriptor = module.requireDescriptor()
val classLoader = subDescriptor.pluginClassLoader ?: continue
if (classLoader is PluginClassLoader && classLoader.pluginDescriptor === subDescriptor) {
classLoaders.add(classLoader)
}
unloadModuleDescriptorNotRecursively(subDescriptor)
subDescriptor.pluginClassLoader = null
}
}
internal fun notify(@NlsContexts.NotificationContent text: String, notificationType: NotificationType, vararg actions: AnAction) {
val notification = UpdateChecker.getNotificationGroupForPluginUpdateResults().createNotification(text, notificationType)
for (action in actions) {
notification.addAction(action)
}
notification.notify(null)
}
// PluginId cannot be used to unload related resources because one plugin descriptor may consist of several sub descriptors,
// each of them depends on presense of another plugin, here not the whole plugin is unloaded, but only one part.
private fun unloadModuleDescriptorNotRecursively(module: IdeaPluginDescriptorImpl) {
val app = ApplicationManager.getApplication() as ApplicationImpl
(ActionManager.getInstance() as ActionManagerImpl).unloadActions(module)
val openedProjects = ProjectUtil.getOpenProjects().asList()
val appExtensionArea = app.extensionArea
val priorityUnloadListeners = mutableListOf<Runnable>()
val unloadListeners = mutableListOf<Runnable>()
unregisterUnknownLevelExtensions(module.unsortedEpNameToExtensionElements, module, appExtensionArea, openedProjects,
priorityUnloadListeners, unloadListeners)
for (epName in (module.appContainerDescriptor.extensions?.keys ?: emptySet())) {
appExtensionArea.unregisterExtensions(epName, module, priorityUnloadListeners, unloadListeners)
}
for (epName in (module.projectContainerDescriptor.extensions?.keys ?: emptySet())) {
for (project in openedProjects) {
(project.extensionArea as ExtensionsAreaImpl).unregisterExtensions(epName, module, priorityUnloadListeners,
unloadListeners)
}
}
// not an error - unsorted goes to module level, see registerExtensions
unregisterUnknownLevelExtensions(module.moduleContainerDescriptor.extensions, module, appExtensionArea, openedProjects,
priorityUnloadListeners, unloadListeners)
for (priorityUnloadListener in priorityUnloadListeners) {
priorityUnloadListener.run()
}
for (unloadListener in unloadListeners) {
unloadListener.run()
}
// first, reset all plugin extension points before unregistering, so that listeners don't see plugin in semi-torn-down state
processExtensionPoints(module, openedProjects) { points, area ->
area.resetExtensionPoints(points, module)
}
// unregister plugin extension points
processExtensionPoints(module, openedProjects) { points, area ->
area.unregisterExtensionPoints(points, module)
}
val pluginId = module.pluginId
app.unloadServices(module.appContainerDescriptor.services, pluginId)
val appMessageBus = app.messageBus as MessageBusEx
module.appContainerDescriptor.listeners?.let { appMessageBus.unsubscribeLazyListeners(module, it) }
for (project in openedProjects) {
(project as ComponentManagerImpl).unloadServices(module.projectContainerDescriptor.services, pluginId)
module.projectContainerDescriptor.listeners?.let {
((project as ComponentManagerImpl).messageBus as MessageBusEx).unsubscribeLazyListeners(module, it)
}
val moduleServices = module.moduleContainerDescriptor.services
for (ideaModule in ModuleManager.getInstance(project).modules) {
(ideaModule as ComponentManagerImpl).unloadServices(moduleServices, pluginId)
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ideaModule, it) }
}
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(project, it) }
}
appMessageBus.disconnectPluginConnections(Predicate { aClass ->
(aClass.classLoader as? PluginClassLoader)?.pluginDescriptor === module
})
createDisposeTreePredicate(module)?.let { Disposer.disposeChildren(ApplicationManager.getApplication(), it) }
}
private fun unregisterUnknownLevelExtensions(extensionMap: Map<String, List<ExtensionDescriptor>>?,
pluginDescriptor: IdeaPluginDescriptorImpl,
appExtensionArea: ExtensionsAreaImpl,
openedProjects: List<Project>,
priorityUnloadListeners: MutableList<Runnable>,
unloadListeners: MutableList<Runnable>) {
for (epName in (extensionMap?.keys ?: return)) {
val isAppLevelEp = appExtensionArea.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners,
unloadListeners)
if (isAppLevelEp) {
continue
}
for (project in openedProjects) {
val isProjectLevelEp = (project.extensionArea as ExtensionsAreaImpl)
.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners)
if (!isProjectLevelEp) {
for (module in ModuleManager.getInstance(project).modules) {
(module.extensionArea as ExtensionsAreaImpl)
.unregisterExtensions(epName, pluginDescriptor, priorityUnloadListeners, unloadListeners)
}
}
}
}
}
private inline fun processExtensionPoints(pluginDescriptor: IdeaPluginDescriptorImpl,
projects: List<Project>,
processor: (points: List<ExtensionPointDescriptor>, area: ExtensionsAreaImpl) -> Unit) {
pluginDescriptor.appContainerDescriptor.extensionPoints?.let {
processor(it, ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
}
pluginDescriptor.projectContainerDescriptor.extensionPoints?.let { extensionPoints ->
for (project in projects) {
processor(extensionPoints, project.extensionArea as ExtensionsAreaImpl)
}
}
pluginDescriptor.moduleContainerDescriptor.extensionPoints?.let { extensionPoints ->
for (project in projects) {
for (module in ModuleManager.getInstance(project).modules) {
processor(extensionPoints, module.extensionArea as ExtensionsAreaImpl)
}
}
}
}
fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl): Boolean {
return loadPlugin(pluginDescriptor, checkImplementationDetailDependencies = true)
}
private fun loadPlugin(pluginDescriptor: IdeaPluginDescriptorImpl, checkImplementationDetailDependencies: Boolean = true): Boolean {
if (classloadersFromUnloadedPlugins[pluginDescriptor.pluginId]?.isEmpty() == false) {
LOG.info("Requiring restart for loading plugin ${pluginDescriptor.pluginId}" +
" because previous version of the plugin wasn't fully unloaded")
return false
}
val loadStartTime = System.currentTimeMillis()
val pluginSet = PluginManagerCore.getPluginSet()
.withModule(pluginDescriptor)
.createPluginSetWithEnabledModulesMap()
val classLoaderConfigurator = ClassLoaderConfigurator(pluginSet)
// todo loadPlugin should be called per each module, temporary solution
val pluginWithContentModules = pluginSet.getEnabledModules()
.filter { it.pluginId == pluginDescriptor.pluginId }
.filter(classLoaderConfigurator::configureModule)
.toList()
val app = ApplicationManager.getApplication() as ApplicationImpl
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).beforePluginLoaded(pluginDescriptor)
app.runWriteAction {
try {
PluginManagerCore.setPluginSet(pluginSet)
val listenerCallbacks = mutableListOf<Runnable>()
// 4. load into service container
loadModules(pluginWithContentModules, app, listenerCallbacks)
loadModules(
optionalDependenciesOnPlugin(pluginDescriptor, classLoaderConfigurator, pluginSet),
app,
listenerCallbacks,
)
clearPluginClassLoaderParentListCache(pluginSet)
clearCachedValues()
listenerCallbacks.forEach(Runnable::run)
logDescriptorLoad(pluginDescriptor)
LOG.info("Plugin ${pluginDescriptor.pluginId} loaded without restart in ${System.currentTimeMillis() - loadStartTime} ms")
}
finally {
app.messageBus.syncPublisher(DynamicPluginListener.TOPIC).pluginLoaded(pluginDescriptor)
}
}
if (checkImplementationDetailDependencies) {
var implementationDetailsLoadedWithoutRestart = true
processImplementationDetailDependenciesOnPlugin(pluginDescriptor, pluginSet) { dependentDescriptor ->
val dependencies = dependentDescriptor.pluginDependencies
if (dependencies.all { it.isOptional || PluginManagerCore.getPlugin(it.pluginId) != null }) {
if (!loadPlugin(dependentDescriptor, checkImplementationDetailDependencies = false)) {
implementationDetailsLoadedWithoutRestart = false
}
}
implementationDetailsLoadedWithoutRestart
}
return implementationDetailsLoadedWithoutRestart
}
return true
}
fun onPluginUnload(parentDisposable: Disposable, callback: Runnable) {
ApplicationManager.getApplication().messageBus.connect(parentDisposable)
.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener {
override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) {
callback.run()
}
})
}
}
private fun clearTemporaryLostComponent() {
try {
val clearMethod = Window::class.java.declaredMethods.find { it.name == "setTemporaryLostComponent" }
if (clearMethod == null) {
LOG.info("setTemporaryLostComponent method not found")
return
}
clearMethod.isAccessible = true
loop@ for (frame in WindowManager.getInstance().allProjectFrames) {
val window = when (frame) {
is ProjectFrameHelper -> frame.frame
is Window -> frame
else -> continue@loop
}
clearMethod.invoke(window, null)
}
}
catch (e: Throwable) {
LOG.info("Failed to clear Window.temporaryLostComponent", e)
}
}
private fun hideTooltip() {
try {
val showMethod = ToolTipManager::class.java.declaredMethods.find { it.name == "show" }
if (showMethod == null) {
LOG.info("ToolTipManager.show method not found")
return
}
showMethod.isAccessible = true
showMethod.invoke(ToolTipManager.sharedInstance(), null)
}
catch (e: Throwable) {
LOG.info("Failed to hide tooltip", e)
}
}
private fun clearCglibStopBacktrace() {
val field = ReflectionUtil.getDeclaredField(ClassNameReader::class.java, "EARLY_EXIT")
if (field != null) {
try {
ThrowableInterner.clearBacktrace((field[null] as Throwable))
}
catch (e: Throwable) {
LOG.info(e)
}
}
}
private fun clearNewFocusOwner() {
val field = ReflectionUtil.getDeclaredField(KeyboardFocusManager::class.java, "newFocusOwner")
if (field != null) {
try {
field.set(null, null)
}
catch (e: Throwable) {
LOG.info(e)
}
}
}
private fun saveMemorySnapshot(pluginId: PluginId): Boolean {
val snapshotDate = SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(Date())
val snapshotFileName = "unload-$pluginId-$snapshotDate.hprof"
val snapshotPath = System.getProperty("memory.snapshots.path", SystemProperties.getUserHome()) + "/" + snapshotFileName
MemoryDumpHelper.captureMemoryDump(snapshotPath)
if (classloadersFromUnloadedPlugins[pluginId]?.isEmpty() != false) {
LOG.info("Successfully unloaded plugin $pluginId (classloader collected during memory snapshot generation)")
return true
}
if (Registry.`is`("ide.plugins.analyze.snapshot")) {
val analysisResult = analyzeSnapshot(snapshotPath, pluginId)
@Suppress("ReplaceSizeZeroCheckWithIsEmpty")
if (analysisResult.length == 0) {
LOG.info("Successfully unloaded plugin $pluginId (no strong references to classloader in .hprof file)")
classloadersFromUnloadedPlugins.remove(pluginId)
return true
}
else {
LOG.info("Snapshot analysis result: $analysisResult")
}
}
DynamicPlugins.notify(
IdeBundle.message("memory.snapshot.captured.text", snapshotPath, snapshotFileName),
NotificationType.WARNING,
object : AnAction(IdeBundle.message("ide.restart.action")), DumbAware {
override fun actionPerformed(e: AnActionEvent) = ApplicationManager.getApplication().restart()
},
object : AnAction(
IdeBundle.message("memory.snapshot.captured.action.text", snapshotFileName, RevealFileAction.getFileManagerName())), DumbAware {
override fun actionPerformed(e: AnActionEvent) = RevealFileAction.openFile(Paths.get(snapshotPath))
}
)
LOG.info("Plugin $pluginId is not unload-safe because class loader cannot be unloaded. Memory snapshot created at $snapshotPath")
return false
}
private fun processImplementationDetailDependenciesOnPlugin(pluginDescriptor: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
processor: (descriptor: IdeaPluginDescriptorImpl) -> Boolean) {
processDependenciesOnPlugin(dependencyPlugin = pluginDescriptor,
pluginSet = pluginSet,
loadStateFilter = LoadStateFilter.ANY,
onlyOptional = false) { _, module ->
if (module.isImplementationDetail) {
processor(module)
}
else {
true
}
}
}
/**
* Load all sub plugins that depend on specified [dependencyPlugin].
*/
private fun optionalDependenciesOnPlugin(
dependencyPlugin: IdeaPluginDescriptorImpl,
classLoaderConfigurator: ClassLoaderConfigurator,
pluginSet: PluginSet,
): Set<IdeaPluginDescriptorImpl> {
// 1. collect optional descriptors
val modulesToMain = LinkedHashMap<IdeaPluginDescriptorImpl, IdeaPluginDescriptorImpl>()
processOptionalDependenciesOnPlugin(dependencyPlugin, pluginSet, isLoaded = false) { main, module ->
modulesToMain[module] = main
true
}
if (modulesToMain.isEmpty()) {
return emptySet()
}
// 2. sort topologically
val topologicalComparator = PluginSetBuilder(modulesToMain.values)
.moduleGraph
.topologicalComparator
return modulesToMain.toSortedMap(topologicalComparator)
.filter { (moduleDescriptor, mainDescriptor) ->
// 3. setup classloaders
classLoaderConfigurator.configureDependency(mainDescriptor, moduleDescriptor)
}.keys
}
private fun loadModules(
modules: Collection<IdeaPluginDescriptorImpl>,
app: ApplicationImpl,
listenerCallbacks: MutableList<Runnable>,
) {
fun registerComponents(componentManager: ComponentManager) {
(componentManager as ComponentManagerImpl).registerComponents(
modules = modules.asSequence(),
app = app,
precomputedExtensionModel = null,
listenerCallbacks = listenerCallbacks,
)
}
registerComponents(app)
for (openProject in ProjectUtil.getOpenProjects()) {
registerComponents(openProject)
for (module in ModuleManager.getInstance(openProject).modules) {
registerComponents(module)
}
}
(ActionManager.getInstance() as ActionManagerImpl).registerActions(modules)
}
private fun analyzeSnapshot(hprofPath: String, pluginId: PluginId): String {
FileChannel.open(Paths.get(hprofPath), StandardOpenOption.READ).use { channel ->
val analysis = HProfAnalysis(channel, SystemTempFilenameSupplier()) { analysisContext, progressIndicator ->
AnalyzeClassloaderReferencesGraph(analysisContext, pluginId.idString).analyze(progressIndicator)
}
analysis.onlyStrongReferences = true
analysis.includeClassesAsRoots = false
analysis.setIncludeMetaInfo(false)
return analysis.analyze(ProgressManager.getGlobalProgressIndicator() ?: EmptyProgressIndicator())
}
}
private fun createDisposeTreePredicate(pluginDescriptor: IdeaPluginDescriptorImpl): Predicate<Disposable>? {
val classLoader = pluginDescriptor.pluginClassLoader as? PluginClassLoader
?: return null
return Predicate {
if (it is PluginManager.PluginAwareDisposable) {
it.classLoaderId == classLoader.instanceId
}
else {
it::class.java.classLoader === classLoader
}
}
}
private fun processOptionalDependenciesOnPlugin(
dependencyPlugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
isLoaded: Boolean,
processor: (pluginDescriptor: IdeaPluginDescriptorImpl, moduleDescriptor: IdeaPluginDescriptorImpl) -> Boolean,
) {
processDependenciesOnPlugin(
dependencyPlugin = dependencyPlugin,
pluginSet = pluginSet,
onlyOptional = true,
loadStateFilter = if (isLoaded) LoadStateFilter.LOADED else LoadStateFilter.NOT_LOADED,
processor = processor,
)
}
private fun processDependenciesOnPlugin(
dependencyPlugin: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
loadStateFilter: LoadStateFilter,
onlyOptional: Boolean,
processor: (pluginDescriptor: IdeaPluginDescriptorImpl, moduleDescriptor: IdeaPluginDescriptorImpl) -> Boolean,
) {
val wantedIds = HashSet<String>(1 + dependencyPlugin.content.modules.size)
wantedIds.add(dependencyPlugin.pluginId.idString)
for (module in dependencyPlugin.content.modules) {
wantedIds.add(module.name)
}
for (plugin in pluginSet.enabledPlugins) {
if (plugin === dependencyPlugin) {
continue
}
if (!processOptionalDependenciesInOldFormatOnPlugin(dependencyPluginId = dependencyPlugin.pluginId,
mainDescriptor = plugin,
loadStateFilter = loadStateFilter,
onlyOptional = onlyOptional,
processor = processor)) {
return
}
for (moduleItem in plugin.content.modules) {
val module = moduleItem.requireDescriptor()
if (loadStateFilter != LoadStateFilter.ANY) {
val isModuleLoaded = module.pluginClassLoader != null
if (isModuleLoaded != (loadStateFilter == LoadStateFilter.LOADED)) {
continue
}
}
for (item in module.dependencies.modules) {
if (wantedIds.contains(item.name) && !processor(plugin, module)) {
return
}
}
for (item in module.dependencies.plugins) {
if (dependencyPlugin.pluginId == item.id && !processor(plugin, module)) {
return
}
}
}
}
}
private enum class LoadStateFilter {
LOADED, NOT_LOADED, ANY
}
private fun processOptionalDependenciesInOldFormatOnPlugin(
dependencyPluginId: PluginId,
mainDescriptor: IdeaPluginDescriptorImpl,
loadStateFilter: LoadStateFilter,
onlyOptional: Boolean,
processor: (main: IdeaPluginDescriptorImpl, sub: IdeaPluginDescriptorImpl) -> Boolean
): Boolean {
for (dependency in mainDescriptor.pluginDependencies) {
if (!dependency.isOptional) {
if (!onlyOptional && dependency.pluginId == dependencyPluginId && !processor(mainDescriptor, mainDescriptor)) {
return false
}
continue
}
val subDescriptor = dependency.subDescriptor ?: continue
if (loadStateFilter != LoadStateFilter.ANY) {
val isModuleLoaded = subDescriptor.pluginClassLoader != null
if (isModuleLoaded != (loadStateFilter == LoadStateFilter.LOADED)) {
continue
}
}
if (dependency.pluginId == dependencyPluginId && !processor(mainDescriptor, subDescriptor)) {
return false
}
if (!processOptionalDependenciesInOldFormatOnPlugin(
dependencyPluginId = dependencyPluginId,
mainDescriptor = subDescriptor,
loadStateFilter = loadStateFilter,
onlyOptional = onlyOptional,
processor = processor)) {
return false
}
}
return true
}
private fun doCheckExtensionsCanUnloadWithoutRestart(
extensions: Map<String, List<ExtensionDescriptor>>,
descriptor: IdeaPluginDescriptorImpl,
baseDescriptor: IdeaPluginDescriptorImpl?,
app: Application,
optionalDependencyPluginId: PluginId?,
context: List<IdeaPluginDescriptorImpl>,
pluginSet: PluginSet,
): String? {
val firstProject = ProjectUtil.getOpenProjects().firstOrNull()
val anyProject = firstProject ?: ProjectManager.getInstance().defaultProject
val anyModule = firstProject?.let { ModuleManager.getInstance(it).modules.firstOrNull() }
val seenPlugins: MutableSet<IdeaPluginDescriptorImpl> = Collections.newSetFromMap(IdentityHashMap())
epLoop@ for (epName in extensions.keys) {
seenPlugins.clear()
fun getNonDynamicUnloadError(optionalDependencyPluginId: PluginId?): String = optionalDependencyPluginId?.let {
"Plugin ${baseDescriptor?.pluginId} is not unload-safe because of use of non-dynamic EP $epName in plugin $it that optionally depends on it"
} ?: "Plugin ${descriptor.pluginId} is not unload-safe because of extension to non-dynamic EP $epName"
val result = findLoadedPluginExtensionPointRecursive(
pluginDescriptor = baseDescriptor ?: descriptor,
epName = epName,
pluginSet = pluginSet,
context = context,
seenPlugins = seenPlugins,
)
if (result != null) {
val (pluginExtensionPoint, foundInDependencies) = result // descriptor.pluginId is null when we check the optional dependencies of the plugin which is being loaded
// if an optional dependency of a plugin extends a non-dynamic EP of that plugin, it shouldn't prevent plugin loading
if (!pluginExtensionPoint.isDynamic) {
if (baseDescriptor == null || foundInDependencies) {
return getNonDynamicUnloadError(null)
}
else if (descriptor === baseDescriptor) {
return getNonDynamicUnloadError(descriptor.pluginId)
}
}
continue
}
@Suppress("RemoveExplicitTypeArguments") val ep = app.extensionArea.getExtensionPointIfRegistered<Any>(epName)
?: anyProject.extensionArea.getExtensionPointIfRegistered<Any>(epName)
?: anyModule?.extensionArea?.getExtensionPointIfRegistered<Any>(epName)
if (ep != null) {
if (!ep.isDynamic) {
return getNonDynamicUnloadError(optionalDependencyPluginId)
}
continue
}
if (anyModule == null) {
val corePlugin = pluginSet.findEnabledPlugin(PluginManagerCore.CORE_ID)
if (corePlugin != null) {
val coreEP = findPluginExtensionPoint(corePlugin, epName)
if (coreEP != null) {
if (!coreEP.isDynamic) {
return getNonDynamicUnloadError(optionalDependencyPluginId)
}
continue
}
}
}
for (contextPlugin in context) {
val contextEp = findPluginExtensionPoint(contextPlugin, epName) ?: continue
if (!contextEp.isDynamic) {
return getNonDynamicUnloadError(null)
}
continue@epLoop
}
// special case Kotlin EPs registered via code in Kotlin compiler
if (epName.startsWith("org.jetbrains.kotlin") && descriptor.pluginId.idString == "org.jetbrains.kotlin") {
continue
}
return "Plugin ${descriptor.pluginId} is not unload-safe because of unresolved extension $epName"
}
return null
}
private fun findPluginExtensionPoint(pluginDescriptor: IdeaPluginDescriptorImpl, epName: String): ExtensionPointDescriptor? {
fun findContainerExtensionPoint(containerDescriptor: ContainerDescriptor): ExtensionPointDescriptor? {
return containerDescriptor.extensionPoints?.find { it.nameEquals(epName, pluginDescriptor) }
}
return findContainerExtensionPoint(pluginDescriptor.appContainerDescriptor)
?: findContainerExtensionPoint(pluginDescriptor.projectContainerDescriptor)
?: findContainerExtensionPoint(pluginDescriptor.moduleContainerDescriptor)
}
private fun findLoadedPluginExtensionPointRecursive(pluginDescriptor: IdeaPluginDescriptorImpl,
epName: String,
pluginSet: PluginSet,
context: List<IdeaPluginDescriptorImpl>,
seenPlugins: MutableSet<IdeaPluginDescriptorImpl>): Pair<ExtensionPointDescriptor, Boolean>? {
if (!seenPlugins.add(pluginDescriptor)) {
return null
}
findPluginExtensionPoint(pluginDescriptor, epName)?.let { return it to false }
for (dependency in pluginDescriptor.pluginDependencies) {
if (pluginSet.isPluginEnabled(dependency.pluginId) || context.any { it.pluginId == dependency.pluginId }) {
dependency.subDescriptor?.let { subDescriptor ->
findLoadedPluginExtensionPointRecursive(subDescriptor, epName, pluginSet, context, seenPlugins)?.let { return it }
}
pluginSet.findEnabledPlugin(dependency.pluginId)?.let { dependencyDescriptor ->
findLoadedPluginExtensionPointRecursive(dependencyDescriptor, epName, pluginSet, context, seenPlugins)?.let { return it.first to true }
}
}
}
processDirectDependencies(pluginDescriptor, pluginSet) { dependency ->
findLoadedPluginExtensionPointRecursive(dependency, epName, pluginSet, context, seenPlugins)?.let { return it.first to true }
}
return null
}
private inline fun processDirectDependencies(module: IdeaPluginDescriptorImpl,
pluginSet: PluginSet,
processor: (IdeaPluginDescriptorImpl) -> Unit) {
for (item in module.dependencies.modules) {
val descriptor = pluginSet.findEnabledModule(item.name)
if (descriptor != null) {
processor(descriptor)
}
}
for (item in module.dependencies.plugins) {
val descriptor = pluginSet.findEnabledPlugin(item.id)
if (descriptor != null) {
processor(descriptor)
}
}
}
private fun unloadClassLoader(pluginDescriptor: IdeaPluginDescriptorImpl, timeoutMs: Int): Boolean {
if (timeoutMs == 0) {
pluginDescriptor.pluginClassLoader = null
return true
}
val watcher = GCWatcher.tracking(pluginDescriptor.pluginClassLoader)
pluginDescriptor.pluginClassLoader = null
return watcher.tryCollect(timeoutMs)
}
private fun setClassLoaderState(pluginDescriptor: IdeaPluginDescriptorImpl, state: Int) {
(pluginDescriptor.pluginClassLoader as? PluginClassLoader)?.state = state
for (dependency in pluginDescriptor.pluginDependencies) {
dependency.subDescriptor?.let { setClassLoaderState(it, state) }
}
}
private fun clearPluginClassLoaderParentListCache(pluginSet: PluginSet) {
// yes, clear not only enabled plugins, but all, just to be sure; it's a cheap operation
for (descriptor in pluginSet.allPlugins) {
(descriptor.pluginClassLoader as? PluginClassLoader)?.clearParentListCache()
}
}
private fun clearCachedValues() {
for (project in ProjectUtil.getOpenProjects()) {
(CachedValuesManager.getManager(project) as? CachedValuesManagerImpl)?.clearCachedValues()
}
}
|
apache-2.0
|
c26bbd6327029155d331b956d1142417
| 40.61205 | 169 | 0.703588 | 5.835549 | false | false | false | false |
SirWellington/alchemy-http-mock
|
src/main/java/tech/sirwellington/alchemy/http/mock/AlchemyHttpMockFactory.kt
|
1
|
6078
|
/*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.http.mock
import com.google.gson.Gson
import com.google.gson.JsonElement
import sir.wellington.alchemy.collections.maps.Maps
import tech.sirwellington.alchemy.annotations.access.Internal
import tech.sirwellington.alchemy.annotations.designs.FluidAPIDesign
import tech.sirwellington.alchemy.arguments.Arguments.checkThat
import tech.sirwellington.alchemy.arguments.assertions.nonEmptyString
import tech.sirwellington.alchemy.arguments.assertions.nonNullReference
import tech.sirwellington.alchemy.arguments.assertions.notNull
import tech.sirwellington.alchemy.arguments.assertions.validURL
import tech.sirwellington.alchemy.http.AlchemyHttp
import tech.sirwellington.alchemy.http.HttpRequest
import tech.sirwellington.alchemy.http.HttpResponse
import tech.sirwellington.alchemy.http.RequestMethod.DELETE
import tech.sirwellington.alchemy.http.RequestMethod.GET
import tech.sirwellington.alchemy.http.RequestMethod.POST
import tech.sirwellington.alchemy.http.RequestMethod.PUT
import tech.sirwellington.alchemy.http.mock.AlchemyHttpMock.At
import tech.sirwellington.alchemy.http.mock.AlchemyHttpMock.Body
import tech.sirwellington.alchemy.http.mock.AlchemyHttpMock.Then
import tech.sirwellington.alchemy.http.mock.AlchemyHttpMock.When
import java.net.MalformedURLException
import java.net.URL
import java.util.concurrent.Callable
@Internal
@FluidAPIDesign
internal class AlchemyHttpMockFactory : AlchemyHttpMock.When, AlchemyHttpMock.Body, AlchemyHttpMock.At, AlchemyHttpMock.Then
{
private val gson = Gson()
private val actions: MutableMap<MockRequest, Callable<*>> = Maps.createSynchronized()
private var currentExpectedRequest: MockRequest? = null
private var httpRequest: HttpRequest? = null
override fun build(): AlchemyHttp
{
return MockAlchemyHttp(actions)
}
override fun whenPost(): Body
{
currentExpectedRequest = MockRequest()
currentExpectedRequest!!.method = POST
httpRequest = HttpRequest.Builder.newInstance().build()
return this
}
override fun whenGet(): Body
{
currentExpectedRequest = MockRequest()
currentExpectedRequest!!.method = GET
return this
}
override fun whenPut(): Body
{
currentExpectedRequest = MockRequest()
currentExpectedRequest!!.method = PUT
return this
}
override fun whenDelete(): Body
{
currentExpectedRequest = MockRequest()
currentExpectedRequest!!.method = DELETE
return this
}
override fun noBody(): At
{
currentExpectedRequest!!.body = MockRequest.NO_BODY
return this
}
override fun anyBody(): At
{
currentExpectedRequest!!.body = MockRequest.ANY_BODY
return this
}
override fun body(pojo: Any): At
{
currentExpectedRequest!!.body = pojo
return this
}
override fun body(jsonBody: JsonElement): At
{
checkThat(jsonBody)
.usingMessage("jsonBody cannot be null")
.isA(notNull())
currentExpectedRequest!!.body = jsonBody
return this
}
override fun body(jsonString: String): At
{
checkThat(jsonString)
.usingMessage("jsonString cannot be empty")
.isA(nonEmptyString())
currentExpectedRequest!!.body = jsonString
return this
}
@Throws(MalformedURLException::class)
override fun at(url: String): Then
{
checkThat(url)
.usingMessage("empty url")
.isA(nonEmptyString())
.isA(validURL())
return at(URL(url))
}
override fun at(url: URL): Then
{
currentExpectedRequest!!.url = url
return this
}
override fun atAnyURL(): Then
{
currentExpectedRequest?.url = MockRequest.ANY_URL
return this
}
override fun thenDo(operation: Callable<*>): When
{
checkThat(operation)
.usingMessage("operation cannot be null")
.isA(nonNullReference())
actions[currentExpectedRequest!!] = operation
currentExpectedRequest = null
return this
}
override fun thenThrow(ex: Exception): When
{
actions[currentExpectedRequest!!] = Actions.throwException<Any>(ex)
currentExpectedRequest = null
return this
}
override fun thenReturnPOJO(pojo: Any): When
{
actions[currentExpectedRequest!!] = Actions.returnPojo(pojo)
currentExpectedRequest = null
return this
}
override fun thenReturnPOJOAsJSON(pojo: Any): When
{
actions[currentExpectedRequest!!] = Actions.returnPojoAsJSON(pojo, gson)
currentExpectedRequest = null
return this
}
override fun thenReturnJson(json: JsonElement): When
{
checkThat(json)
.usingMessage("json cannot be null")
.isA(notNull())
actions[currentExpectedRequest!!] = Actions.returnJson(json)
currentExpectedRequest = null
return this
}
override fun thenReturnResponse(response: HttpResponse): When
{
checkThat(response)
.usingMessage("response cannot be null")
.isA(notNull())
actions[currentExpectedRequest!!] = Actions.returnResponse(response)
currentExpectedRequest = null
return this
}
}
|
apache-2.0
|
624e8df8c5c2cc3fddad8ebbca069e0f
| 26.497738 | 124 | 0.68389 | 4.815372 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/jetpack/java/org/wordpress/android/ui/accounts/login/LoginPrologueViewModel.kt
|
1
|
4145
|
package org.wordpress.android.ui.accounts.login
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.accounts.LoginNavigationEvents
import org.wordpress.android.ui.accounts.LoginNavigationEvents.ShowEmailLoginScreen
import org.wordpress.android.ui.accounts.LoginNavigationEvents.ShowLoginViaSiteAddressScreen
import org.wordpress.android.ui.accounts.UnifiedLoginTracker
import org.wordpress.android.ui.accounts.UnifiedLoginTracker.Click.CONTINUE_WITH_WORDPRESS_COM
import org.wordpress.android.ui.accounts.UnifiedLoginTracker.Click.LOGIN_WITH_SITE_ADDRESS
import org.wordpress.android.ui.accounts.UnifiedLoginTracker.Flow
import org.wordpress.android.ui.accounts.UnifiedLoginTracker.Step.PROLOGUE
import org.wordpress.android.ui.accounts.login.LoginPrologueViewModel.ButtonUiState.ContinueWithWpcomButtonState
import org.wordpress.android.ui.accounts.login.LoginPrologueViewModel.ButtonUiState.EnterYourSiteAddressButtonState
import org.wordpress.android.util.BuildConfigWrapper
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
@HiltViewModel
class LoginPrologueViewModel @Inject constructor(
private val unifiedLoginTracker: UnifiedLoginTracker,
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper,
private val buildConfigWrapper: BuildConfigWrapper,
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher
) : ScopedViewModel(mainDispatcher) {
private val _navigationEvents = MediatorLiveData<Event<LoginNavigationEvents>>()
val navigationEvents: LiveData<Event<LoginNavigationEvents>> = _navigationEvents
private val _uiState: MutableLiveData<UiState> = MutableLiveData()
val uiState: LiveData<UiState> = _uiState
private var isStarted = false
fun start() {
if (isStarted) return
isStarted = true
analyticsTrackerWrapper.track(stat = Stat.LOGIN_PROLOGUE_VIEWED)
unifiedLoginTracker.track(flow = Flow.PROLOGUE, step = PROLOGUE)
_uiState.value = UiState(
enterYourSiteAddressButtonState = EnterYourSiteAddressButtonState(::onEnterYourSiteAddressButtonClick),
continueWithWpcomButtonState = ContinueWithWpcomButtonState(
title = if (buildConfigWrapper.isSignupEnabled) {
R.string.continue_with_wpcom
} else {
R.string.continue_with_wpcom_no_signup
},
onClick = ::onContinueWithWpcomButtonClick
)
)
}
fun onFragmentResume() {
unifiedLoginTracker.setFlowAndStep(Flow.PROLOGUE, PROLOGUE)
}
private fun onContinueWithWpcomButtonClick() {
unifiedLoginTracker.trackClick(CONTINUE_WITH_WORDPRESS_COM)
_navigationEvents.postValue(Event(ShowEmailLoginScreen))
}
private fun onEnterYourSiteAddressButtonClick() {
unifiedLoginTracker.trackClick(LOGIN_WITH_SITE_ADDRESS)
_navigationEvents.postValue(Event(ShowLoginViaSiteAddressScreen))
}
data class UiState(
val enterYourSiteAddressButtonState: EnterYourSiteAddressButtonState,
val continueWithWpcomButtonState: ContinueWithWpcomButtonState
)
sealed class ButtonUiState {
abstract val title: Int
abstract val onClick: (() -> Unit)
data class ContinueWithWpcomButtonState(
override val title: Int,
override val onClick: () -> Unit
) : ButtonUiState()
data class EnterYourSiteAddressButtonState(override val onClick: () -> Unit) : ButtonUiState() {
override val title = R.string.enter_your_site_address
}
}
}
|
gpl-2.0
|
44810cebd705060be5b28df82c772aaf
| 43.095745 | 119 | 0.753679 | 4.887972 | false | false | false | false |
mdaniel/intellij-community
|
plugins/git4idea/src/git4idea/search/GitSearchEverywhereFilterConfiguration.kt
|
9
|
1531
|
// 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 git4idea.search
import com.intellij.ide.util.TypeVisibilityStateHolder
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.project.Project
import kotlinx.serialization.Serializable
@Service
@State(name = "GitSEFilterConfiguration", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)])
class GitSearchEverywhereFilterConfiguration(@Suppress("unused") private val project: Project)
: TypeVisibilityStateHolder<GitSearchEverywhereItemType>, PersistentStateComponent<FilterState> {
@Volatile
private var state = FilterState()
override fun getState(): FilterState = state
override fun loadState(state: FilterState) {
this.state = state
}
override fun isVisible(type: GitSearchEverywhereItemType) = state.visibleItems.contains(type)
override fun setVisible(type: GitSearchEverywhereItemType, visible: Boolean) {
val visibleItems = state.visibleItems
if(visible) {
visibleItems.add(type)
} else {
visibleItems.remove(type)
}
}
}
@Serializable
data class FilterState(val visibleItems: MutableSet<GitSearchEverywhereItemType> = mutableSetOf(GitSearchEverywhereItemType.COMMIT_BY_HASH))
|
apache-2.0
|
452f5c17f6accef52eb993535da8fcbe
| 37.275 | 140 | 0.803396 | 4.570149 | false | false | false | false |
androidstarters/androidstarters.com
|
templates/androidstarters-kotlin/app/src/main/java/io/mvpstarter/sample/injection/component/ActivityComponent.kt
|
1
|
575
|
package <%= appPackage %>.injection.component
import <%= appPackage %>.injection.PerActivity
import <%= appPackage %>.injection.module.ActivityModule
import <%= appPackage %>.features.base.BaseActivity
import <%= appPackage %>.features.detail.DetailActivity
import <%= appPackage %>.features.main.MainActivity
import dagger.Subcomponent
@PerActivity
@Subcomponent(modules = arrayOf(ActivityModule::class))
interface ActivityComponent {
fun inject(baseActivity: BaseActivity)
fun inject(mainActivity: MainActivity)
fun inject(detailActivity: DetailActivity)
}
|
mit
|
5d9653114820a351c0a267da6bd6dfee
| 30.944444 | 56 | 0.78087 | 5.275229 | false | false | false | false |
iPoli/iPoli-android
|
app/src/main/java/io/ipoli/android/friends/ReactionHistoryDialogViewController.kt
|
1
|
7519
|
package io.ipoli.android.friends
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.support.annotation.DrawableRes
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import io.ipoli.android.R
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.common.view.ReduxDialogController
import io.ipoli.android.common.view.attrResourceId
import io.ipoli.android.common.view.colorRes
import io.ipoli.android.common.view.recyclerview.BaseRecyclerViewAdapter
import io.ipoli.android.common.view.recyclerview.RecyclerViewViewModel
import io.ipoli.android.common.view.recyclerview.SimpleViewHolder
import io.ipoli.android.friends.ReactionHistoryDialogViewState.StateType.*
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.friends.usecase.CreateReactionHistoryItemsUseCase
import io.ipoli.android.pet.AndroidPetAvatar
import io.ipoli.android.pet.PetAvatar
import io.ipoli.android.player.data.AndroidAvatar
import kotlinx.android.synthetic.main.dialog_reaction_history.view.*
import kotlinx.android.synthetic.main.item_reaction_history.view.*
import kotlinx.android.synthetic.main.view_dialog_header.view.*
/**
* Created by Polina Zhelyazkova <[email protected]>
* on 7/13/18.
*/
sealed class ReactionHistoryDialogAction : Action {
data class Load(val reactions: List<Post.Reaction>) : ReactionHistoryDialogAction()
}
object ReactionHistoryDialogReducer : BaseViewStateReducer<ReactionHistoryDialogViewState>() {
override val stateKey = key<ReactionHistoryDialogViewState>()
override fun reduce(
state: AppState,
subState: ReactionHistoryDialogViewState,
action: Action
): ReactionHistoryDialogViewState {
return when (action) {
is DataLoadedAction.ReactionHistoryItemsChanged -> {
val player = state.dataState.player
if (player != null) {
subState.copy(
type = DATA_CHANGED,
playerId = player.id,
petAvatar = player.pet.avatar,
reactions = action.items
)
} else {
subState.copy(
type = LOADING,
reactions = action.items
)
}
}
is DataLoadedAction.PlayerChanged ->
subState.copy(
type = PET_AVATAR_CHANGED,
petAvatar = action.player.pet.avatar
)
else -> subState
}
}
override fun defaultState() = ReactionHistoryDialogViewState(
type = LOADING,
playerId = null,
petAvatar = null,
reactions = null
)
}
data class ReactionHistoryDialogViewState(
val type: StateType,
val playerId: String?,
val petAvatar: PetAvatar?,
val reactions: List<CreateReactionHistoryItemsUseCase.ReactionHistoryItem>?
) : BaseViewState() {
enum class StateType {
LOADING,
DATA_CHANGED,
PET_AVATAR_CHANGED
}
}
class ReactionHistoryDialogViewController(args: Bundle? = null) :
ReduxDialogController<ReactionHistoryDialogAction, ReactionHistoryDialogViewState, ReactionHistoryDialogReducer>(
args
) {
private lateinit var reactions: List<Post.Reaction>
constructor(reactions: List<Post.Reaction>) : this() {
this.reactions = reactions
}
override val reducer = ReactionHistoryDialogReducer
override fun onCreateContentView(inflater: LayoutInflater, savedViewState: Bundle?): View {
val view = inflater.inflate(R.layout.dialog_reaction_history, null)
view.reactionList.layoutManager = LinearLayoutManager(view.context)
view.reactionList.adapter = ReactionHistoryAdapter()
return view
}
override fun onHeaderViewCreated(headerView: View) {
headerView.dialogHeaderTitle.setText(R.string.history)
}
override fun onCreateLoadAction() =
ReactionHistoryDialogAction.Load(reactions)
override fun onCreateDialog(
dialogBuilder: AlertDialog.Builder,
contentView: View,
savedViewState: Bundle?
): AlertDialog = dialogBuilder
.setNegativeButton(R.string.cancel, null)
.create()
override fun render(state: ReactionHistoryDialogViewState, view: View) {
when (state.type) {
DATA_CHANGED -> {
changeIcon(AndroidPetAvatar.valueOf(state.petAvatar!!.name).headImage)
(view.reactionList.adapter as ReactionHistoryAdapter).updateAll(state.viewModels)
}
PET_AVATAR_CHANGED -> changeIcon(AndroidPetAvatar.valueOf(state.petAvatar!!.name).headImage)
else -> {
}
}
}
data class ReactionViewModel(
override val id: String,
val avatar: AndroidAvatar,
val name: String,
val username: String,
val time: String,
@DrawableRes val reactionImage: Int
) : RecyclerViewViewModel
inner class ReactionHistoryAdapter :
BaseRecyclerViewAdapter<ReactionViewModel>(R.layout.item_reaction_history) {
override fun onBindViewModel(vm: ReactionViewModel, view: View, holder: SimpleViewHolder) {
Glide.with(view.context).load(vm.avatar.image)
.apply(RequestOptions.circleCropTransform())
.into(view.playerAvatar)
val gradientDrawable = view.playerAvatar.background as GradientDrawable
gradientDrawable.mutate()
gradientDrawable.setColor(colorRes(vm.avatar.backgroundColor))
Glide.with(view.context).load(vm.reactionImage)
.apply(RequestOptions.circleCropTransform())
.into(view.reactionImage)
(view.reactionImage.background as GradientDrawable).setColor(Color.WHITE)
view.playerName.text = vm.name
view.playerUsername.text = vm.username
view.reactionTime.text = vm.time
view.setBackgroundResource(attrResourceId(android.R.attr.selectableItemBackground))
view.isClickable = true
view.onDebounceClick {
navigateFromRoot().toProfile(vm.id)
}
}
}
private val ReactionHistoryDialogViewState.viewModels: List<ReactionViewModel>
get() = reactions!!.map {
ReactionViewModel(
id = it.player.id,
avatar = AndroidAvatar.valueOf(it.player.avatar.name),
name = it.player.displayName ?: "Unknown Hero",
username = "@${it.player.username}",
time = DateUtils.getRelativeTimeSpanString(
it.reaction.createdAt.toEpochMilli(),
System.currentTimeMillis(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL
).toString(),
reactionImage = it.reaction.reactionType.androidType.image
)
}
}
|
gpl-3.0
|
9e95a645e2cf58d2ce6f931afb851f67
| 34.809524 | 117 | 0.666046 | 4.992696 | false | false | false | false |
GunoH/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/injection/aliases/CodeFenceLanguageAliases.kt
|
5
|
2145
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.intellij.plugins.markdown.injection.aliases
import com.intellij.openapi.util.text.StringUtil
/**
* Service to work with Markdown code fence's info-string.
*
* [CodeFenceLanguageAliases] is able to find possible IntelliJ Language ID
* for info string (including resolution of standard aliases) and
* (backwards) suggest correct info string for IntelliJ Language ID
*/
internal object CodeFenceLanguageAliases {
private data class Entry(
val id: String,
val main: String,
val aliases: Set<String>
)
private val aliases = setOf(
Entry("go", "go", setOf("golang")),
Entry("HCL", "hcl", setOf("hcl")),
Entry("ApacheConfig", "apacheconf", setOf("aconf", "apache", "apacheconfig")),
Entry("Batch", "batch", setOf("bat", "batchfile")),
Entry("CoffeeScript", "coffeescript", setOf("coffee", "coffee-script")),
Entry("JavaScript", "javascript", setOf("js", "node")),
Entry("Markdown", "markdown", setOf("md")),
Entry("PowerShell", "powershell", setOf("posh", "pwsh")),
Entry("Python", "python", setOf("python2", "python3", "py")),
Entry("R", "r", setOf("rlang", "rscript")),
Entry("RegExp", "regexp", setOf("regex")),
Entry("Ruby", "ruby", setOf("ruby", "rb")),
Entry("Yaml", "yaml", setOf("yml")),
Entry("Kotlin", "kotlin", setOf("kt", "kts")),
Entry("HCL-Terraform", "terraform", setOf("hcl-terraform", "tf")),
Entry("C#", "csharp", setOf("cs", "c#")),
Entry("F#", "fsharp", setOf("fs", "f#")),
Entry("Shell Script", "shell", setOf("shell script", "bash", "zsh", "sh"))
)
fun findRegisteredEntry(value: String): String? {
val lower = value.lowercase()
val entry = aliases.singleOrNull { lower == it.main || lower in it.aliases }
return entry?.id
}
/**
* Get recommended alias for [id]
* @return recommended alias if any or just [id]
*/
fun findMainAlias(id: String): String {
val alias = aliases.singleOrNull { id == it.id }?.main
return alias ?: StringUtil.toLowerCase(id)
}
}
|
apache-2.0
|
398d1b2f0711a66fc87b471726e7afbf
| 38 | 120 | 0.643823 | 3.75 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildWithNullsImpl.kt
|
2
|
6273
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.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.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.UsedClassesCollector
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildWithNullsImpl(val dataSource: ChildWithNullsData) : ChildWithNulls, WorkspaceEntityBase() {
companion object {
val connections = listOf<ConnectionId>(
)
}
override val childData: String
get() = dataSource.childData
override val entitySource: EntitySource
get() = dataSource.entitySource
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(result: ChildWithNullsData?) : ModifiableWorkspaceEntityBase<ChildWithNulls, ChildWithNullsData>(
result), ChildWithNulls.Builder {
constructor() : this(ChildWithNullsData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildWithNulls is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// After adding entity data to the builder, we need to unbind it and move the control over entity data to builder
// Builder may switch to snapshot at any moment and lock entity data to modification
this.currentEntityData = null
// 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().isChildDataInitialized()) {
error("Field ChildWithNulls#childData 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 ChildWithNulls
if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource
if (this.childData != dataSource.childData) this.childData = dataSource.childData
if (parents != null) {
}
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData(true).entitySource = value
changedProperty.add("entitySource")
}
override var childData: String
get() = getEntityData().childData
set(value) {
checkModificationAllowed()
getEntityData(true).childData = value
changedProperty.add("childData")
}
override fun getEntityClass(): Class<ChildWithNulls> = ChildWithNulls::class.java
}
}
class ChildWithNullsData : WorkspaceEntityData<ChildWithNulls>() {
lateinit var childData: String
fun isChildDataInitialized(): Boolean = ::childData.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<ChildWithNulls> {
val modifiable = ChildWithNullsImpl.Builder(null)
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildWithNulls {
return getCached(snapshot) {
val entity = ChildWithNullsImpl(this)
entity.snapshot = snapshot
entity.id = createEntityId()
entity
}
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildWithNulls::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity {
return ChildWithNulls(childData, entitySource) {
}
}
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.javaClass != other.javaClass) return false
other as ChildWithNullsData
if (this.entitySource != other.entitySource) return false
if (this.childData != other.childData) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this.javaClass != other.javaClass) return false
other as ChildWithNullsData
if (this.childData != other.childData) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun hashCodeIgnoringEntitySource(): Int {
var result = javaClass.hashCode()
result = 31 * result + childData.hashCode()
return result
}
override fun collectClassUsagesData(collector: UsedClassesCollector) {
collector.sameForAllEntities = true
}
}
|
apache-2.0
|
6301a4532859bf3c6a7efab038a93c5b
| 31.502591 | 120 | 0.731388 | 5.30262 | false | false | false | false |
ClearVolume/scenery
|
src/main/kotlin/graphics/scenery/backends/vulkan/VulkanComputePass.kt
|
2
|
6045
|
package graphics.scenery.backends.vulkan
import graphics.scenery.geometry.GeometryType
import graphics.scenery.Node
import graphics.scenery.backends.vulkan.VulkanPostprocessPass.setRequiredDescriptorSetsPostprocess
import graphics.scenery.compute.ComputeMetadata
import graphics.scenery.utils.LazyLogger
import org.joml.Vector3i
import org.lwjgl.system.MemoryUtil
import org.lwjgl.vulkan.KHRSwapchain
import org.lwjgl.vulkan.VK10
/**
* Helper object for compute pass command buffer recording.
*
* @author Ulrik Guenther <[email protected]>
*/
object VulkanComputePass {
val logger by LazyLogger()
/**
* Records a new compute render [pass] into the [commandBuffer] given. Eventual further buffers
* are allocated from [commandPools]. Global [sceneUBOs] and [descriptorSets] need to be given.
*/
fun record(
pass: VulkanRenderpass,
commandBuffer: VulkanCommandBuffer,
commandPools: VulkanRenderer.CommandPools,
sceneUBOs: List<Node>,
descriptorSets: Map<String, Long>
) {
with(commandBuffer.prepareAndStartRecording(commandPools.Compute)) {
val metadata = ComputeMetadata(Vector3i(pass.getOutput().width, pass.getOutput().height, 1))
val pipeline = pass.getDefaultPipeline()
val vulkanPipeline = pipeline.getPipelineForGeometryType(GeometryType.TRIANGLES)
if (pass.vulkanMetadata.descriptorSets.capacity() != pipeline.descriptorSpecs.count()) {
MemoryUtil.memFree(pass.vulkanMetadata.descriptorSets)
pass.vulkanMetadata.descriptorSets = MemoryUtil.memAllocLong(pipeline.descriptorSpecs.count())
}
// allocate more vertexBufferOffsets than needed, set limit lateron
pass.vulkanMetadata.uboOffsets.position(0)
pass.vulkanMetadata.uboOffsets.limit(16)
(0..15).forEach { pass.vulkanMetadata.uboOffsets.put(it, 0) }
VK10.vkCmdBindPipeline(this, VK10.VK_PIPELINE_BIND_POINT_COMPUTE, vulkanPipeline.pipeline)
// set the required descriptor sets for this render pass
pass.vulkanMetadata.setRequiredDescriptorSetsPostprocess(pass, pipeline, sceneUBOs, descriptorSets)
if(pipeline.pushConstantSpecs.containsKey("currentEye")) {
VK10.vkCmdPushConstants(this, vulkanPipeline.layout, VK10.VK_SHADER_STAGE_ALL, 0, pass.vulkanMetadata.eye)
}
if(pass.vulkanMetadata.descriptorSets.limit() > 0) {
logger.debug("${pass.name}: Binding ${pass.vulkanMetadata.descriptorSets.limit()} descriptor sets with ${pass.vulkanMetadata.uboOffsets.limit()} required offsets")
VK10.vkCmdBindDescriptorSets(this, VK10.VK_PIPELINE_BIND_POINT_COMPUTE,
vulkanPipeline.layout, 0, pass.vulkanMetadata.descriptorSets, pass.vulkanMetadata.uboOffsets)
}
val localSizes = pipeline.shaderStages.first().localSize
if(localSizes.first == 0 || localSizes.second == 0 || localSizes.third == 0) {
logger.error("${pass.name}: Compute local sizes $localSizes must not be zero, setting to 1.")
}
val loadStoreAttachments = hashMapOf(false to pass.inputs, true to pass.output)
loadStoreAttachments
.forEach { (isOutput, fb) ->
val originalLayout = if(isOutput && pass.isViewportRenderpass) {
KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
} else {
VK10.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
}
fb.values
.flatMap { it.attachments.values }
.filter { it.type != VulkanFramebuffer.VulkanFramebufferType.DEPTH_ATTACHMENT}
.forEach { att ->
VulkanTexture.transitionLayout(att.image,
from = originalLayout,
to = VK10.VK_IMAGE_LAYOUT_GENERAL,
srcStage = VK10.VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
srcAccessMask = VK10.VK_ACCESS_SHADER_READ_BIT,
dstStage = VK10.VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
dstAccessMask = VK10.VK_ACCESS_SHADER_WRITE_BIT,
commandBuffer = this)
}
}
VK10.vkCmdDispatch(this,
metadata.workSizes.x() / maxOf(localSizes.first, 1),
metadata.workSizes.y() / maxOf(localSizes.second, 1),
metadata.workSizes.z() / maxOf(localSizes.third, 1))
loadStoreAttachments
.forEach { (isOutput, fb) ->
val originalLayout = if(isOutput && pass.isViewportRenderpass) {
KHRSwapchain.VK_IMAGE_LAYOUT_PRESENT_SRC_KHR
} else {
VK10.VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL
}
fb.values
.flatMap { it.attachments.values }
.filter { it.type != VulkanFramebuffer.VulkanFramebufferType.DEPTH_ATTACHMENT}
.forEach { att ->
VulkanTexture.transitionLayout(att.image,
from = VK10.VK_IMAGE_LAYOUT_GENERAL,
to = originalLayout,
srcStage = VK10.VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
srcAccessMask = VK10.VK_ACCESS_SHADER_WRITE_BIT,
dstStage = VK10.VK_PIPELINE_STAGE_VERTEX_SHADER_BIT,
dstAccessMask = VK10.VK_ACCESS_SHADER_READ_BIT,
commandBuffer = this)
}
}
commandBuffer.stale = false
commandBuffer.endCommandBuffer()
}
}
}
|
lgpl-3.0
|
f835848f4ac5172474c3d5bbf0e1529f
| 46.226563 | 179 | 0.588751 | 4.836 | false | false | false | false |
google/ground-android
|
ground/src/main/java/com/google/android/ground/ui/map/LocationController.kt
|
1
|
2230
|
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.ground.ui.map
import android.location.Location
import com.google.android.ground.rx.annotations.Hot
import com.google.android.ground.system.LocationManager
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class LocationController @Inject constructor(private val locationManager: LocationManager) {
private val locationLockChangeRequests: @Hot Subject<Boolean> = PublishSubject.create()
/** Emits a stream of location lock requests. */
fun getLocationLockUpdates(): Flowable<Result<Boolean>> =
locationLockChangeRequests
.switchMapSingle { toggleLocationUpdates(it) }
.toFlowable(BackpressureStrategy.LATEST)
.share()
/** Emits a stream of updated locations. */
fun getLocationUpdates(): Flowable<Location> =
getLocationLockUpdates()
.map { it.getOrDefault(false) }
.switchMap { result: Boolean ->
if (!result) {
Flowable.empty()
} else {
locationManager.getLocationUpdates()
}
}
private fun toggleLocationUpdates(result: Boolean): Single<Result<Boolean>> =
if (result) locationManager.enableLocationUpdates()
else locationManager.disableLocationUpdates()
/** Enables location lock by requesting location updates. */
fun lock() = locationLockChangeRequests.onNext(true)
/** Releases location lock by disabling location updates. */
fun unlock() = locationLockChangeRequests.onNext(false)
}
|
apache-2.0
|
937c94b2c9d9cd961b653337638d110c
| 34.967742 | 92 | 0.747534 | 4.569672 | false | false | false | false |
fyookball/electrum
|
android/app/src/main/java/org/electroncash/electroncash3/LivePreferences.kt
|
1
|
1978
|
package org.electroncash.electroncash3
import androidx.lifecycle.MutableLiveData
import android.content.SharedPreferences
class LivePreferences(val sp: SharedPreferences) {
private val booleans = HashMap<String, LivePreference<Boolean>>()
private val strings = HashMap<String, LivePreference<String>>()
fun getBoolean(key: String) =
get(booleans, key, { LiveBooleanPreference(sp, key) })
fun getString(key: String) =
get(strings, key, { LiveStringPreference(sp, key) })
private fun <T> get(map: MutableMap<String, T>, key: String, create: () -> T): T {
var result = map.get(key)
if (result != null) {
return result
} else {
result = create()
map.put(key, result)
return result
}
}
}
abstract class LivePreference<T>(val sp: SharedPreferences, val key: String)
: MutableLiveData<T>(), SharedPreferences.OnSharedPreferenceChangeListener {
abstract fun spGet(): T
abstract fun spSet(value: T)
init {
update(sp)
sp.registerOnSharedPreferenceChangeListener(this)
}
override fun setValue(value: T) {
spSet(value)
}
override fun onSharedPreferenceChanged(sp: SharedPreferences, key: String) {
if (key == this.key) {
update(sp)
}
}
private fun update(sp: SharedPreferences) {
super.setValue(if (sp.contains(key)) spGet() else null)
}
}
class LiveBooleanPreference(sp: SharedPreferences, key: String) : LivePreference<Boolean>(sp, key) {
override fun spGet(): Boolean { return sp.getBoolean(key, false) }
override fun spSet(value: Boolean) { sp.edit().putBoolean(key, value).apply() }
}
class LiveStringPreference(sp: SharedPreferences, key: String) : LivePreference<String>(sp, key) {
override fun spGet(): String { return sp.getString(key, null)!! }
override fun spSet(value: String) { sp.edit().putString(key, value).apply() }
}
|
mit
|
09fd2fab862674bea4762d79df1cc1c4
| 29.446154 | 100 | 0.654702 | 4.129436 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ArtifactRootElementEntityImpl.kt
|
2
|
13645
|
package com.intellij.workspaceModel.storage.bridgeEntities.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.ModifiableReferableWorkspaceEntity
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.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyChildren
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent
import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneParent
import com.intellij.workspaceModel.storage.impl.extractOneToManyChildren
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyChildrenOfParent
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild
import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneParentOfChild
import com.intellij.workspaceModel.storage.referrersx
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ArtifactRootElementEntityImpl: ArtifactRootElementEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
internal val ARTIFACT_CONNECTION_ID: ConnectionId = ConnectionId.create(ArtifactEntity::class.java, CompositePackagingElementEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true)
internal val CHILDREN_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
ARTIFACT_CONNECTION_ID,
CHILDREN_CONNECTION_ID,
)
}
override val parentEntity: CompositePackagingElementEntity?
get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this)
override val artifact: ArtifactEntity?
get() = snapshot.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this)
override val children: List<PackagingElementEntity>
get() = snapshot.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList()
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ArtifactRootElementEntityData?): ModifiableWorkspaceEntityBase<ArtifactRootElementEntity>(), ArtifactRootElementEntity.Builder {
constructor(): this(ArtifactRootElementEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ArtifactRootElementEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isEntitySourceInitialized()) {
error("Field CompositePackagingElementEntity#entitySource should be initialized")
}
// Check initialization for list with ref type
if (_diff != null) {
if (_diff.extractOneToManyChildren<WorkspaceEntityBase>(CHILDREN_CONNECTION_ID, this) == null) {
error("Field CompositePackagingElementEntity#children should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] == null) {
error("Field CompositePackagingElementEntity#children should be initialized")
}
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var parentEntity: CompositePackagingElementEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override var artifact: ArtifactEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractOneParent(ARTIFACT_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity
} else {
this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] as? ArtifactEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToAbstractOneParentOfChild(ARTIFACT_CONNECTION_ID, this, value)
}
else {
if (value is ModifiableWorkspaceEntityBase<*>) {
value.entityLinks[EntityLink(true, ARTIFACT_CONNECTION_ID)] = this
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, ARTIFACT_CONNECTION_ID)] = value
}
changedProperty.add("artifact")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var children: List<PackagingElementEntity>
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToAbstractManyChildren<PackagingElementEntity>(CHILDREN_CONNECTION_ID, this)!!.toList() + (this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as? List<PackagingElementEntity> ?: emptyList())
} else {
this.entityLinks[EntityLink(true, CHILDREN_CONNECTION_ID)] as List<PackagingElementEntity> ?: emptyList()
}
}
set(value) {
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.updateOneToAbstractManyChildrenOfParent(CHILDREN_CONNECTION_ID, this, value.asSequence())
}
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 fun getEntityData(): ArtifactRootElementEntityData = result ?: super.getEntityData() as ArtifactRootElementEntityData
override fun getEntityClass(): Class<ArtifactRootElementEntity> = ArtifactRootElementEntity::class.java
}
}
class ArtifactRootElementEntityData : WorkspaceEntityData<ArtifactRootElementEntity>() {
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ArtifactRootElementEntity> {
val modifiable = ArtifactRootElementEntityImpl.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): ArtifactRootElementEntity {
val entity = ArtifactRootElementEntityImpl()
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ArtifactRootElementEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactRootElementEntityData
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ArtifactRootElementEntityData
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
return result
}
}
|
apache-2.0
|
91961a0f76aab6fbedbe2bbb169f2ec9
| 47.390071 | 238 | 0.622426 | 6.193827 | false | false | false | false |
DreierF/MyTargets
|
app/src/androidTest/java/de/dreier/mytargets/test/utils/actions/LowLevelActions.kt
|
1
|
4499
|
/*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.test.utils.actions
import android.graphics.Matrix
import android.graphics.RectF
import android.view.MotionEvent
import android.view.View
import androidx.test.espresso.UiController
import androidx.test.espresso.ViewAction
import androidx.test.espresso.action.MotionEvents
import androidx.test.espresso.action.Press
import androidx.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast
import androidx.test.platform.app.InstrumentationRegistry
import de.dreier.mytargets.shared.targets.drawable.TargetDrawable
import org.hamcrest.Matcher
object LowLevelActions {
private var sMotionEventDownHeldView: MotionEvent? = null
fun pressAndHold(coordinates: FloatArray): PressAndHoldAction {
return PressAndHoldAction(coordinates)
}
fun release(coordinates: FloatArray): ReleaseAction {
return ReleaseAction(coordinates)
}
fun tearDown() {
sMotionEventDownHeldView = null
}
fun getTargetCoordinates(v: View, coordinates: FloatArray): FloatArray {
val screenPos = IntArray(2)
v.getLocationOnScreen(screenPos)
val contentWidth = v.width.toFloat()
val contentHeight = v.height.toFloat()
val density = InstrumentationRegistry.getInstrumentation().targetContext.resources
.displayMetrics.density
val targetRectExt = RectF(0f, 80 * density, contentWidth, contentHeight)
targetRectExt.inset(10 * density, 10 * density)
if (targetRectExt.height() > targetRectExt.width()) {
targetRectExt.top = targetRectExt.bottom - targetRectExt.width()
}
targetRectExt.inset(30 * density, 30 * density)
val fullExtendedMatrix = Matrix()
fullExtendedMatrix
.setRectToRect(TargetDrawable.SRC_RECT, targetRectExt, Matrix.ScaleToFit.CENTER)
val shotPos = FloatArray(2)
fullExtendedMatrix.mapPoints(shotPos, coordinates)
shotPos[0] += screenPos[0].toFloat()
shotPos[1] += screenPos[1].toFloat()
return shotPos
}
fun getAbsoluteCoordinates(v: View, coordinates: FloatArray): FloatArray {
val screenPos = IntArray(2)
v.getLocationOnScreen(screenPos)
coordinates[0] += screenPos[0].toFloat()
coordinates[1] += screenPos[1].toFloat()
return coordinates
}
class PressAndHoldAction internal constructor(internal val coordinates: FloatArray) :
ViewAction {
override fun getConstraints(): Matcher<View> {
return isDisplayingAtLeast(90)
}
override fun getDescription(): String {
return "Press and hold action"
}
override fun perform(uiController: UiController, view: View) {
if (sMotionEventDownHeldView != null) {
throw AssertionError("Only one view can be held at a time")
}
val precision = Press.FINGER.describePrecision()
sMotionEventDownHeldView = MotionEvents
.sendDown(
uiController, getTargetCoordinates(view, coordinates),
precision
).down
// TODO: save view information and make sure release() is on same view
}
}
class ReleaseAction(private val coordinates: FloatArray) : ViewAction {
override fun getConstraints(): Matcher<View> {
return isDisplayingAtLeast(90)
}
override fun getDescription(): String {
return "Release action"
}
override fun perform(uiController: UiController, view: View) {
if (sMotionEventDownHeldView == null) {
throw AssertionError(
"Before calling release(), you must call pressAndHold() on a view"
)
}
MotionEvents.sendUp(
uiController, sMotionEventDownHeldView!!,
getTargetCoordinates(view, coordinates)
)
}
}
}
|
gpl-2.0
|
455a74e6535f34c936622b58522c3e06
| 33.343511 | 92 | 0.666148 | 4.863784 | false | true | false | false |
auricgoldfinger/Memento-Namedays
|
memento/src/main/java/com/alexstyl/gsc/SoundRules.kt
|
4
|
10652
|
package com.alexstyl.gsc
import kotlin.coroutines.experimental.buildIterator
/**
* Holds all rules based on which we make the comparisons.
*/
class SoundRules private constructor() {
/**
* A dictionary to hold all double character sounds like 'TS' and 'PS'.
*/
private val doubleSounds = HashMap<String, Sound>()
/**
* A dictionary to hold all single symbol sounds like 'A' and 'S'
*/
private val singleSounds = HashMap<Char, Sound>()
/**
* A dictionary to provide an easy way to change Greek accented vowels to
* their non accented form.
*/
private val accentCapitals = HashMap<Char, Char>()
/**
* A string which contains all chars appearing as the first character of a
* double character sound.
* ex. AI, OI , AY, EI => "AOE"
*/
private var startOfDouble = ""
// Define all possible sound symbols which can be found in the Greek language.
private val ALPHA = 'Α'
private val SIGMA = 'Σ'
private val DELTA = 'Δ'
private val DI = 'D'
private val FI = 'Φ'
private val GAMMA = 'Γ'
private val GKOU = 'G'
private val HI = 'Χ'
private val JI = 'J'
private val KAPPA = 'Κ'
private val LAMBDA = 'Λ'
private val ZITA = 'Ζ'
private val XI = 'Ξ'
private val PSI = 'Ψ'
private val BETA = 'Β'
private val NI = 'Ν'
private val MI = 'Μ'
private val PI = 'Π'
private val OMIKRON = 'Ο'
private val IOTA = 'Ι'
private val THITA = 'Θ'
private val RO = 'Ρ'
private val EPSILON = 'Ε'
private val TAU = 'Τ'
private val BI = '~'
private val OY = '!'
private val EPSILON_YPSILON = '$'
private val ALPHA_YPSILONOY = '#'
init {
this.initialize()
}
private fun initialize() {
/// chars and CSV are implicitly converted to Sounds
/// Associate all letters to their sound
/// English double sounds
doubleSounds.put("TH", sound(THITA))
doubleSounds.put("PS", sound(PSI))
doubleSounds.put("PH", sound(FI))
doubleSounds.put("KS", sound(XI))
doubleSounds.put("CH", sound(HI))
doubleSounds.put("GG", sound(GKOU))
doubleSounds.put("OY", sound(OY))
doubleSounds.put("OU", sound(OY))
doubleSounds.put("TZ", sound(JI))
doubleSounds.put("MP", sound(BI))
doubleSounds.put("AI", sound(EPSILON))
doubleSounds.put("EY", sound(EPSILON_YPSILON))
doubleSounds.put("EF", sound(EPSILON_YPSILON))
doubleSounds.put("AF", sound(ALPHA_YPSILONOY))
doubleSounds.put("AY", sound(ALPHA_YPSILONOY))
doubleSounds.put("AU", sound(ALPHA_YPSILONOY))
doubleSounds.put("EI", sound(IOTA))
doubleSounds.put("OI", sound(IOTA))
/// Greek double sounds
doubleSounds.put("ΓΓ", sound(GKOU))
doubleSounds.put("ΑΙ", sound(EPSILON))
doubleSounds.put("ΓΚ", sound(GKOU))
doubleSounds.put("ΤΖ", sound(JI))
doubleSounds.put("ΟΥ", sound(OY))
doubleSounds.put("ΜΠ", sound(BI))
doubleSounds.put("ΕΥ", sound(EPSILON_YPSILON))
doubleSounds.put("ΕΦ", sound(EPSILON_YPSILON))
doubleSounds.put("ΑΦ", sound(ALPHA_YPSILONOY))
doubleSounds.put("ΑΥ", sound(ALPHA_YPSILONOY))
doubleSounds.put("ΟΙ", sound(IOTA))
doubleSounds.put("ΕΙ", sound(IOTA))
doubleSounds.put("ΚΣ", sound(XI))
doubleSounds.put("ΠΣ", sound(PSI))
/// English Sounds
this.singleSounds.put('Q', sound(KAPPA))
this.singleSounds.put('8', sound(THITA))
this.singleSounds.put('9', sound(THITA))
this.singleSounds.put('3', sound(EPSILON))
this.singleSounds.put('4', sound(ALPHA))
this.singleSounds.put('0', sound(OMIKRON))
this.singleSounds.put('W', sound(OMIKRON))
this.singleSounds.put('O', sound(OMIKRON))
this.singleSounds.put('E', sound(EPSILON + "," + IOTA))
this.singleSounds.put('R', sound(RO))
this.singleSounds.put('T', sound(TAU))
this.singleSounds.put('Y', sound(IOTA + "," + GAMMA))
this.singleSounds.put('U', sound(IOTA + "," + OY))
this.singleSounds.put('I', sound(IOTA))
this.singleSounds.put('P', sound(PI))
this.singleSounds.put('A', sound(ALPHA))
this.singleSounds.put('S', sound(SIGMA))
this.singleSounds.put('D', sound(DELTA + "," + DI))
this.singleSounds.put('F', sound(FI))
this.singleSounds.put('G', sound(GKOU + "," + GAMMA))
this.singleSounds.put('H', sound(IOTA + "," + HI))
this.singleSounds.put('J', sound(JI))
this.singleSounds.put('K', sound(KAPPA))
this.singleSounds.put('L', sound(LAMBDA))
this.singleSounds.put('Z', sound(ZITA))
this.singleSounds.put('X', sound(HI + "," + XI))
this.singleSounds.put('C', sound(KAPPA + "," + SIGMA))
this.singleSounds.put('V', sound(BETA))
this.singleSounds.put('B', sound(BETA + "," + BI))
this.singleSounds.put('N', sound(NI))
this.singleSounds.put('M', sound(MI))
/// Greek letters
this.singleSounds.put('Γ', sound(GAMMA))
this.singleSounds.put('Ω', sound(OMIKRON))
this.singleSounds.put('Η', sound(IOTA))
this.singleSounds.put('Ι', sound(IOTA))
this.singleSounds.put('Υ', sound(IOTA))
this.singleSounds.put('Η', sound(IOTA))
this.singleSounds.put('ς', sound(SIGMA))
this.singleSounds.put('Ξ', sound(XI))
this.accentCapitals.put('Ά', ALPHA)
this.accentCapitals.put('Ί', IOTA)
this.accentCapitals.put('Ό', OMIKRON)
this.accentCapitals.put('Ύ', IOTA)
this.accentCapitals.put('Ή', IOTA)
this.accentCapitals.put('Έ', EPSILON)
this.accentCapitals.put('Ώ', OMIKRON)
this.accentCapitals.put('Ί', IOTA)
this.accentCapitals.put('Ϊ', IOTA)
this.accentCapitals.put('\u0390', IOTA) // small iota with dyalitika and tonos does not have a upper case counter part
/// Find all characters which may start a double symbol sound
val str = StringBuilder()
val var2 = this.doubleSounds.keys.iterator()
while (var2.hasNext()) {
val charA = var2.next()[0].toString()
if (!str.toString().contains(charA)) {
str.append(charA)
}
}
this.startOfDouble = str.toString()
}
/**
* Compare the two given string and determines if they sound the same.
*/
fun compare(first: String, second: String, startsWith: Boolean): Boolean {
val enumerator2 = getNextSound(second, startsWith).iterator()
getNextSound(first, startsWith).forEach { sound1 ->
if (enumerator2.hasNext()) {
sound1 as Sound
val sound2 = enumerator2.next() as Sound
if (!sound1.soundsLike(sound2)) {
/// Found a non matching sound thus
/// we are sure the two words don't sound the same
return false
}
} else {
/// The first word sounds exactly as second up until now.
/// Return true if we check that first starts with second
/// Return false if first and second must sound the same.
return startsWith
}
}
/// Special case where first is a substring of second
/// We need to make sure that both string have reached their end.
if (enumerator2.hasNext()) {
return false
}
return true
}
/**
* The core function of the library.
* Returns the next sound of the string.
*
*/
fun getNextSound(string: String, retrieveAll: Boolean) = buildIterator {
/// Used to indicate the beginning of a double char sound
var doubleSoundPending = false
/// Store the first char of a double symbol sound
var previousCharacter = 0.toChar()
val stringUpper = string.toUpperCase()
stringUpper.forEach { c ->
var character = c
/// Remove the acute accent from the character if present
if (accentCapitals.containsKey(character)) {
character = accentCapitals[character]!!
}
/// We have a pending double sound.
/// Check if the previousCharacter followed up by character is a
/// doubleSymbol Sound
if (doubleSoundPending) {
doubleSoundPending = false
/// Create the key and check if it exists as a double symbol sounds
val key = (previousCharacter + "" + character)
if (doubleSounds.containsKey(key)) {
yield(doubleSounds[key])
return@forEach
} else {
yield(getSound(previousCharacter))
}
}
if (startOfDouble.indexOf(character) >= 0) {
doubleSoundPending = true
previousCharacter = character
} else {
yield(getSound(character))
}
}
/// Return any pending sounds
if (doubleSoundPending) {
if (retrieveAll) {
yield(getAllSoundsInternal(previousCharacter))
} else {
yield(getSound(previousCharacter))
}
}
}
/**
* Get the sound of a single character
*
* @param character
* @return
*/
private fun getSound(character: Char): Sound {
return if (singleSounds.containsKey(character)) {
singleSounds[character]!!
} else sound(character)
}
/**
* Returns all sounds which are possible starting with the given character.
*
* p => P, PS, PH
*
*/
private fun getAllSoundsInternal(upperCharacter: Char): Sound {
var sound = getSound(upperCharacter)
if (startOfDouble.indexOf(upperCharacter) >= 0) {
val map = doubleSounds.filter {
it.key[0] == upperCharacter
}.map {
it.value
}
sound += Sound.flatten(map);
}
return sound
}
companion object {
private var sInstance: SoundRules? = null
val INSTANCE: SoundRules
get() {
if (sInstance == null) {
sInstance = SoundRules()
}
return sInstance!!
}
}
}
|
mit
|
996855548b02a194e283e664508b4ef6
| 33.148387 | 126 | 0.568392 | 3.860686 | false | false | false | false |
paplorinc/intellij-community
|
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUCallableReferenceExpression.kt
|
2
|
1729
|
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.java
import com.intellij.psi.*
import org.jetbrains.uast.UCallableReferenceExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.UMultiResolvable
class JavaUCallableReferenceExpression(
override val psi: PsiMethodReferenceExpression,
givenParent: UElement?
) : JavaAbstractUExpression(givenParent), UCallableReferenceExpression, UMultiResolvable {
override val qualifierExpression: UExpression? by lz { JavaConverter.convertOrNull(psi.qualifierExpression, this) }
override val qualifierType: PsiType?
get() = psi.qualifierType?.type
override val callableName: String
get() = psi.referenceName.orAnonymous()
override fun resolve(): PsiElement? = psi.resolve()
override fun multiResolve(): Iterable<ResolveResult> = psi.multiResolve(false).asIterable()
override val resolvedName: String?
get() = (psi.resolve() as? PsiNamedElement)?.name
override val referenceNameElement: UElement? by lz {
psi.referenceNameElement?.let { JavaUSimpleNameReferenceExpression(it, callableName, this, it.reference) }
}
}
|
apache-2.0
|
fa84702df2df90176d8f1b7132898d4b
| 35.041667 | 117 | 0.772701 | 4.598404 | false | false | false | false |
google/intellij-community
|
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/firstStep/FirstWizardStepComponent.kt
|
3
|
10025
|
// 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.tools.projectWizard.wizard.ui.firstStep
import com.intellij.icons.AllIcons
import com.intellij.ide.util.projectWizard.JavaModuleBuilder
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.roots.ui.configuration.JdkComboBox
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.TitledSeparator
import com.intellij.ui.dsl.builder.BottomGap
import com.intellij.ui.dsl.builder.panel
import com.intellij.ui.dsl.gridLayout.HorizontalAlign
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.components.BorderLayoutPanel
import org.jetbrains.kotlin.idea.statistics.WizardStatsService
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.wizard.IdeWizard
import org.jetbrains.kotlin.tools.projectWizard.wizard.KotlinNewProjectWizardUIBundle
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.*
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.PathSettingComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.StringSettingComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.TitledComponentsList
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.createSettingComponent
import java.awt.Cursor
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
class FirstWizardStepComponent(ideWizard: IdeWizard) : WizardStepComponent(ideWizard.context) {
private val projectSettingsComponent = ProjectSettingsComponent(ideWizard).asSubComponent()
override val component: JComponent = projectSettingsComponent.component
}
class ProjectSettingsComponent(ideWizard: IdeWizard) : DynamicComponent(ideWizard.context) {
private val context = ideWizard.context
private val projectTemplateComponent = ProjectTemplateSettingComponent(context).asSubComponent()
private val buildSystemSetting = BuildSystemTypeSettingComponent(context).asSubComponent().apply {
component.addBorder(JBUI.Borders.empty(0, /*left&right*/4))
}
private var locationWasUpdatedByHand: Boolean = false
private var artifactIdWasUpdatedByHand: Boolean = false
private val buildSystemAdditionalSettingsComponent =
BuildSystemAdditionalSettingsComponent(
ideWizard,
onUserTypeInArtifactId = { artifactIdWasUpdatedByHand = true },
).asSubComponent()
private val jdkComponent = JdkComponent(ideWizard).asSubComponent()
private val nameAndLocationComponent = TitledComponentsList(
listOf(
StructurePlugin.name.reference.createSettingComponent(context),
StructurePlugin.projectPath.reference.createSettingComponent(context).also {
(it as? PathSettingComponent)?.onUserType { locationWasUpdatedByHand = true }
},
projectTemplateComponent,
buildSystemSetting,
jdkComponent
),
context,
stretchY = true,
useBigYGap = true,
xPadding = 0,
yPadding = 0
).asSubComponent()
override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) {
panel {
row {
cell(nameAndLocationComponent.component)
.horizontalAlign(HorizontalAlign.FILL)
.resizableColumn()
bottomGap(BottomGap.SMALL)
}
row {
cell(buildSystemAdditionalSettingsComponent.component)
.horizontalAlign(HorizontalAlign.FILL)
.resizableColumn()
bottomGap(BottomGap.SMALL)
}
}.addBorder(IdeBorderFactory.createEmptyBorder(JBInsets(20, 20, 20, 20)))
}
override fun onValueUpdated(reference: SettingReference<*, *>?) {
super.onValueUpdated(reference)
when (reference?.path) {
StructurePlugin.name.path -> {
val isNameValid = read { StructurePlugin.name.reference.validate().isOk }
if (isNameValid) {
tryUpdateLocationByProjectName()
tryArtifactIdByProjectName()
}
}
}
}
private fun tryUpdateLocationByProjectName() {
if (!locationWasUpdatedByHand) {
val location = read { StructurePlugin.projectPath.settingValue }
if (location.parent != null) modify {
StructurePlugin.projectPath.reference.setValue(location.resolveSibling(StructurePlugin.name.settingValue))
locationWasUpdatedByHand = false
}
}
}
private fun tryArtifactIdByProjectName() {
if (!artifactIdWasUpdatedByHand) modify {
StructurePlugin.artifactId.reference.setValue(StructurePlugin.name.settingValue)
artifactIdWasUpdatedByHand = false
}
}
}
class BuildSystemAdditionalSettingsComponent(
ideWizard: IdeWizard,
onUserTypeInArtifactId: () -> Unit,
) : DynamicComponent(ideWizard.context) {
private val pomSettingsList = PomSettingsComponent(ideWizard.context, onUserTypeInArtifactId).asSubComponent()
override fun onValueUpdated(reference: SettingReference<*, *>?) {
super.onValueUpdated(reference)
if (reference == BuildSystemPlugin.type.reference) {
updateBuildSystemComponent()
}
}
override fun onInit() {
super.onInit()
updateBuildSystemComponent()
}
private fun updateBuildSystemComponent() {
val buildSystemType = read { BuildSystemPlugin.type.settingValue }
section.isVisible = buildSystemType != BuildSystemType.Jps
}
private val section = HideableSection(
KotlinNewProjectWizardUIBundle.message("additional.buildsystem.settings.artifact.coordinates"),
pomSettingsList.component
)
override val component: JComponent = section
}
private class PomSettingsComponent(context: Context, onUserTypeInArtifactId: () -> Unit) : TitledComponentsList(
listOf(
StructurePlugin.groupId.reference.createSettingComponent(context),
StructurePlugin.artifactId.reference.createSettingComponent(context).also {
(it as? StringSettingComponent)?.onUserType(onUserTypeInArtifactId)
},
StructurePlugin.version.reference.createSettingComponent(context)
),
context,
stretchY = true
)
private class JdkComponent(ideWizard: IdeWizard) : TitledComponent(ideWizard.context) {
private val javaModuleBuilder = JavaModuleBuilder()
private val jdkComboBox: JdkComboBox
private val sdksModel: ProjectSdksModel
init {
val project = ProjectManager.getInstance().defaultProject
sdksModel = ProjectSdksModel()
sdksModel.reset(project)
jdkComboBox = JdkComboBox(
project,
sdksModel,
Condition(javaModuleBuilder::isSuitableSdkType),
null,
null,
null
).apply {
reloadModel()
getDefaultJdk()?.let { jdk -> selectedJdk = jdk }
ideWizard.jdk = selectedJdk
addActionListener {
ideWizard.jdk = selectedJdk
WizardStatsService.logDataOnJdkChanged(ideWizard.context.contextComponents.get())
}
}
}
private fun getDefaultJdk(): Sdk? {
val defaultProject = ProjectManagerEx.getInstanceEx().defaultProject
return ProjectRootManagerEx.getInstanceEx(defaultProject).projectSdk ?: run {
val sdks = ProjectJdkTable.getInstance().allJdks
.filter { it.homeDirectory?.isValid == true && javaModuleBuilder.isSuitableSdkType(it.sdkType) }
.groupBy(Sdk::getSdkType)
.entries.firstOrNull()
?.value?.filterNotNull() ?: return@run null
sdks.maxWithOrNull(sdks.firstOrNull()?.sdkType?.versionComparator() ?: return@run null)
}
}
override val title: String = KotlinNewProjectWizardUIBundle.message("additional.buildsystem.settings.project.jdk")
override val component: JComponent = jdkComboBox
}
private class HideableSection(@NlsContexts.Separator text: String, component: JComponent) : BorderLayoutPanel() {
private val titledSeparator = TitledSeparator(text)
private val contentPanel = borderPanel {
addBorder(JBUI.Borders.emptyLeft(20))
addToCenter(component)
}
private var isExpanded = false
init {
titledSeparator.label.cursor = Cursor(Cursor.HAND_CURSOR)
addToTop(titledSeparator)
addToCenter(contentPanel)
update(isExpanded)
titledSeparator.addMouseListener(object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent) = update(!isExpanded)
})
}
private fun update(isExpanded: Boolean) {
this.isExpanded = isExpanded
contentPanel.isVisible = isExpanded
titledSeparator.label.icon = if (isExpanded) AllIcons.General.ArrowDown else AllIcons.General.ArrowRight
}
}
|
apache-2.0
|
12fa1820b1dee802406509859f8f508f
| 39.922449 | 122 | 0.714115 | 5.052923 | false | false | false | false |
google/intellij-community
|
tools/ideTestingFramework/intellij.tools.ide.starter/src/com/intellij/ide/starter/utils/Git.kt
|
2
|
1919
|
package com.intellij.ide.starter.utils
import com.intellij.ide.starter.process.exec.ExecOutputRedirect
import com.intellij.ide.starter.process.exec.ProcessExecutor
import java.io.IOException
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.Path
import kotlin.time.Duration.Companion.minutes
object Git {
val branch by lazy { getShortBranchName() }
val localBranch by lazy { getLocalGitBranch() }
@Throws(IOException::class, InterruptedException::class)
private fun getLocalGitBranch(): String {
val stdout = ExecOutputRedirect.ToString()
ProcessExecutor(
"git-local-branch-get",
workDir = null, timeout = 1.minutes,
args = listOf("git", "rev-parse", "--abbrev-ref", "HEAD"),
stdoutRedirect = stdout
).start()
return stdout.read().trim()
}
private fun getShortBranchName(): String {
val master = "master"
return runCatching {
when (val branch = getLocalGitBranch().substringBefore(".")) {
master -> return branch
else -> when (branch.toIntOrNull()) {
null -> return master
else -> return "IjPlatform$branch"
}
}
}.getOrElse { master }
}
fun getRepoRoot(): Path {
val stdout = ExecOutputRedirect.ToString()
try {
ProcessExecutor(
"git-repo-root-get",
workDir = null, timeout = 1.minutes,
args = listOf("git", "rev-parse", "--show-toplevel", "HEAD"),
stdoutRedirect = stdout
).start()
}
catch (e: Exception) {
val workDir = Paths.get("").toAbsolutePath()
logError("There is a problem in detecting git repo root. Trying to acquire working dir path: '$workDir'")
return workDir
}
// Takes first line from output like this:
// /opt/REPO/intellij
// 1916dc2bef46b51cfb02ad9f7e87d12aa1aa9fdc
return Path(stdout.read().split("\n").first().trim()).toAbsolutePath()
}
}
|
apache-2.0
|
fdcfc5a93b136a43c53227c4550da097
| 28.523077 | 111 | 0.657634 | 4.135776 | false | false | false | false |
Masterzach32/SwagBot
|
src/main/kotlin/features/games/BaseGameImpl.kt
|
1
|
1599
|
package xyz.swagbot.features.games
import discord4j.core.`object`.entity.*
import discord4j.core.`object`.entity.channel.*
import io.facet.common.*
import io.facet.common.dsl.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import xyz.swagbot.util.*
class BaseGameImpl(override val channel: GuildMessageChannel, scope: CoroutineScope) : Game, CoroutineScope by scope {
override val players: Set<Member> = mutableSetOf()
private val playerQueue: SendChannel<Member> = actor {
players as MutableSet<Member>
for (member in channel) {
if (currentStage !is Game.Stage.PreGame) {
[email protected](errorTemplate.and {
description = "Sorry, the game has already started!"
})
} else {
if (players.add(member)) {
[email protected](baseTemplate.and {
description = getJoinMessageForPlayer(member)
})
} else {
[email protected](errorTemplate.and {
description = "You have already joined the game! It should be starting shortly."
})
}
}
}
}
override var currentStage: Game.Stage = Game.Stage.PreGame
override suspend fun join(player: Member) {
playerQueue.send(player)
}
override fun getJoinMessageForPlayer(player: Member): String {
return "**${player.displayName}** joined the game!"
}
}
|
gpl-2.0
|
ea765770f631e66c15708d0569149c07
| 34.533333 | 118 | 0.611632 | 4.68915 | false | false | false | false |
JetBrains/intellij-community
|
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/preview/html/PreviewEncodingUtil.kt
|
1
|
725
|
package org.intellij.plugins.markdown.ui.preview.html
import java.net.URLEncoder
import java.nio.charset.Charset
import java.util.*
internal object PreviewEncodingUtil {
private val contentCharset: Charset
get() = Charsets.UTF_8
fun encodeContent(content: String): String {
val encoder = Base64.getEncoder()
val bytes = encoder.encode(content.toByteArray(contentCharset))
return bytes.toString(contentCharset)
}
fun decodeContent(content: String): String {
val decoder = Base64.getDecoder()
val bytes = decoder.decode(content)
return bytes.toString(contentCharset)
}
fun encodeUrl(url: String): String {
return URLEncoder.encode(url, contentCharset).replace("+", "%20")
}
}
|
apache-2.0
|
addb6e7e8ee91248208b0f064eb7b29c
| 26.884615 | 69 | 0.735172 | 4.027778 | false | false | false | false |
HITGIF/SchoolPower
|
app/src/main/java/com/carbonylgroup/schoolpower/adapter/AssignmentFlagAdapter.kt
|
1
|
1741
|
package com.carbonylgroup.schoolpower.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.carbonylgroup.schoolpower.R
import com.carbonylgroup.schoolpower.data.AssignmentItem
import com.carbonylgroup.schoolpower.utils.Utils
import kotterknife.bindView
/**
* Created by carbonyl on 21/01/2018.
*/
class AssignmentFlagAdapter(private val context: Context, private val assignmentItem: AssignmentItem) :
RecyclerView.Adapter<AssignmentFlagAdapter.AssignmentFlagViewHolder>() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
private val utils: Utils = Utils(context)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AssignmentFlagViewHolder {
val view = inflater.inflate(R.layout.assignment_flag_item, parent, false)
return AssignmentFlagViewHolder(view)
}
override fun onBindViewHolder(viewHolder: AssignmentFlagViewHolder, position: Int) {
val (icon, descrip) = utils.getAssignmentFlag(assignmentItem.trueFlags[position].first)
viewHolder.assignment_flag_image.setImageResource(icon)
viewHolder.assignment_flag_description.text = descrip
}
override fun getItemCount(): Int {
return assignmentItem.trueFlags.count()
}
class AssignmentFlagViewHolder internal constructor(view: View) : RecyclerView.ViewHolder(view) {
val assignment_flag_image: ImageView by bindView(R.id.assignment_flag_image)
val assignment_flag_description: TextView by bindView(R.id.assignment_flag_description)
}
}
|
apache-2.0
|
899c42081d0b22dc123c4bb0176faf2c
| 36.847826 | 103 | 0.775991 | 4.533854 | false | false | false | false |
square/okio
|
okio/src/commonMain/kotlin/okio/Path.kt
|
1
|
15422
|
/*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import okio.Path.Companion.toPath
/**
* A hierarchical address on a file system. A path is an identifier only; a [FileSystem] is required
* to access the file that a path refers to, if any.
*
* UNIX and Windows Paths
* ----------------------
*
* Paths follow different rules on UNIX vs. Windows operating systems. On UNIX operating systems
* (including Linux, Android, macOS, and iOS), the `/` slash character separates path segments. On
* Windows, the `\` backslash character separates path segments. The two platforms each have their
* own rules for path resolution. This class implements all rules on all platforms; for example you
* can model a Linux path in a native Windows application.
*
* Absolute and Relative Paths
* ---------------------------
*
* * **Absolute paths** identify a location independent of any working directory. On UNIX, absolute
* paths are prefixed with a slash, `/`. On Windows, absolute paths are one of two forms. The
* first is a volume letter, a colon, and a backslash, like `C:\`. The second is called a
* Universal Naming Convention (UNC) path, and it is prefixed by two backslashes `\\`. The term
* ‘fully-qualified path’ is a synonym of ‘absolute path’.
*
* * **Relative paths** are everything else. On their own, relative paths do not identify a
* location on a file system; they are relative to the system's current working directory. Use
* [FileSystem.canonicalize] to convert a relative path to its absolute path on a particular
* file system.
*
* There are some special cases when working with relative paths.
*
* On Windows, each volume (like `A:\` and `C:\`) has its own current working directory. A path
* prefixed with a volume letter and colon but no slash (like `A:letter.doc`) is relative to the
* working directory on the named volume. For example, if the working directory on `A:\` is
* `A:\jesse`, then the path `A:letter.doc` resolves to `A:\jesse\letter.doc`.
*
* The path string `C:\Windows` is an absolute path when following Windows rules and a relative
* path when following UNIX rules. For example, if the current working directory is
* `/Users/jesse`, then `C:\Windows` resolves to `/Users/jesse/C:/Windows`.
*
* This class decides which rules to follow by inspecting the first slash character in the path
* string. If the path contains no slash characters, it uses the host platform's rules. Or you may
* explicitly specify which rules to use by specifying the `directorySeparator` parameter in
* [toPath]. Pass `"/"` to get UNIX rules and `"\"` to get Windows rules.
*
* Path Traversal
* --------------
*
* After the optional path root (like `/` on UNIX, like `X:\` or `\\` on Windows), the remainder of
* the path is a sequence of segments separated by `/` or `\` characters. Segments satisfy these
* rules:
*
* * Segments are always non-empty.
* * If the segment is `.`, then the full path must be `.`.
* * For normalized paths, if the segment is `..`, then the path must be relative. All `..`
* segments precede all other segments. In all cases, a segment `..` cannot be the first segment
* of an absolute path.
*
* The only path that ends with `/` is the file system root, `/`. The dot path `.` is a relative
* path that resolves to whichever path it is resolved against.
*
* The [name] is the last segment in a path. It is typically a file or directory name, like
* `README.md` or `Desktop`. The name may be another special value:
*
* * The empty string is the name of the file system root path (full path `/`).
* * `.` is the name of the identity relative path (full path `.`).
* * `..` is the name of a path consisting of only `..` segments (such as `../../..`).
*
* Comparing Paths
* ---------------
*
* Path implements [Comparable], [equals], and [hashCode]. If two paths are equal then they operate
* on the same file on the file system.
*
* Note that the converse is not true: **if two paths are non-equal, they may still resolve to the
* same file on the file system.** Here are some of the ways non-equal paths resolve to the same
* file:
*
* * **Case differences.** The default file system on macOS is case-insensitive. The paths
* `/Users/jesse/notes.txt` and `/USERS/JESSE/NOTES.TXT` are non-equal but these paths resolve to
* the same file.
* * **Mounting differences.** Volumes may be mounted at multiple paths. On macOS,
* `/Users/jesse/notes.txt` and `/Volumes/Macintosh HD/Users/jesse/notes.txt` typically resolve
* to the same file. On Windows, `C:\project\notes.txt` and `\\localhost\c$\project\notes.txt`
* typically resolve to the same file.
* * **Hard links.** UNIX file systems permit multiple paths to refer for same file. The paths may
* be wildly different, like `/Users/jesse/bruce_wayne.vcard` and
* `/Users/jesse/batman.vcard`, but changes via either path are reflected in both.
* * **Symlinks.** Symlinks permit multiple paths and directories to refer to the same file. On
* macOS `/tmp` is symlinked to `/private/tmp`, so `/tmp/notes.txt` and `/private/tmp/notes.txt`
* resolve to the same file.
*
* To test whether two paths refer to the same file, try [FileSystem.canonicalize] first. This
* follows symlinks and looks up the preserved casing for case-insensitive case-preserved paths.
* **This method does not guarantee a unique result, however.** For example, each hard link to a
* file may return its own canonical path.
*
* Paths are sorted in case-sensitive order.
*
* Sample Paths
* ------------
*
* <table>
* <tr><th> Path <th> Parent <th> Root <th> Name <th> Notes </tr>
* <tr><td> `/` <td> null <td> `/` <td> (empty) <td> root </tr>
* <tr><td> `/home/jesse/notes.txt` <td> `/home/jesse` <td> `/` <td> `notes.txt` <td> absolute path </tr>
* <tr><td> `project/notes.txt` <td> `project` <td> null <td> `notes.txt` <td> relative path </tr>
* <tr><td> `../../project/notes.txt` <td> `../../project` <td> null <td> `notes.txt` <td> relative path with traversal </tr>
* <tr><td> `../../..` <td> null <td> null <td> `..` <td> relative path with traversal </tr>
* <tr><td> `.` <td> null <td> null <td> `.` <td> current working directory </tr>
* <tr><td> `C:\` <td> null <td> `C:\` <td> (empty) <td> volume root (Windows) </tr>
* <tr><td> `C:\Windows\notepad.exe` <td> `C:\Windows` <td> `C:\` <td> `notepad.exe` <td> volume absolute path (Windows) </tr>
* <tr><td> `\` <td> null <td> `\` <td> (empty) <td> absolute path (Windows) </tr>
* <tr><td> `\Windows\notepad.exe` <td> `\Windows` <td> `\` <td> `notepad.exe` <td> absolute path (Windows) </tr>
* <tr><td> `C:` <td> null <td> null <td> (empty) <td> volume-relative path (Windows) </tr>
* <tr><td> `C:project\notes.txt` <td> `C:project` <td> null <td> `notes.txt` <td> volume-relative path (Windows) </tr>
* <tr><td> `\\server` <td> null <td> `\\server` <td> `server` <td> UNC server (Windows) </tr>
* <tr><td> `\\server\project\notes.txt` <td> `\\server\project` <td> `\\server` <td> `notes.txt` <td> UNC absolute path (Windows) </tr>
* </table>
*/
expect class Path internal constructor(bytes: ByteString) : Comparable<Path> {
/**
* This is the root path if this is an absolute path, or null if it is a relative path. UNIX paths
* have a single root, `/`. Each volume on Windows is its own root, like `C:\` and `D:\`. The
* path to the current volume `\` is its own root. Windows UNC paths like `\\server` are also
* roots.
*/
val root: Path?
/**
* The components of this path that are usually delimited by slashes. If the root is not null it
* precedes these segments. If this path is a root its segments list is empty.
*/
val segments: List<String>
val segmentsBytes: List<ByteString>
internal val bytes: ByteString
/** This is true if [root] is not null. */
val isAbsolute: Boolean
/** This is true if [root] is null. */
val isRelative: Boolean
/**
* This is the volume letter like "C" on Windows paths that starts with a volume letter. For
* example, on the path "C:\Windows" this returns "C". This property is null if this is not a
* Windows path, or if it doesn't have a volume letter.
*
* Note that paths that start with a volume letter are not necessarily absolute paths. For
* example, the path "C:notepad.exe" is relative to whatever the current working directory is on
* the C: drive.
*/
val volumeLetter: Char?
val nameBytes: ByteString
val name: String
/**
* Returns the path immediately enclosing this path.
*
* This returns null if this has no parent. That includes these paths:
*
* * The file system root (`/`)
* * The identity relative path (`.`)
* * A Windows volume root (like `C:\`)
* * A Windows Universal Naming Convention (UNC) root path (`\\server`)
* * A reference to the current working directory on a Windows volume (`C:`).
* * A series of relative paths (like `..` and `../..`).
*/
val parent: Path?
/** Returns true if `this == this.root`. That is, this is an absolute path with no parent. */
val isRoot: Boolean
/**
* Returns a path that resolves [child] relative to this path. Note that the result isn't
* guaranteed to be normalized even if this and [child] are both normalized themselves.
*
* If [child] is an [absolute path][isAbsolute] or [has a volume letter][hasVolumeLetter] then
* this function is equivalent to `child.toPath()`.
*/
operator fun div(child: String): Path
/**
* Returns a path that resolves [child] relative to this path. Note that the result isn't
* guaranteed to be normalized even if this and [child] are both normalized themselves.
*
* If [child] is an [absolute path][isAbsolute] or [has a volume letter][hasVolumeLetter] then
* this function is equivalent to `child.toPath()`.
*/
operator fun div(child: ByteString): Path
/**
* Returns a path that resolves [child] relative to this path. Note that the result isn't
* guaranteed to be normalized even if this and [child] are both normalized themselves.
*
* If [child] is an [absolute path][isAbsolute] or [has a volume letter][hasVolumeLetter] then
* this function is equivalent to `child.toPath()`.
*/
operator fun div(child: Path): Path
/**
* Returns a path that resolves [child] relative to this path.
*
* Set [normalize] to true to eagerly consume `..` segments on the resolved path. In all cases,
* leading `..` on absolute paths will be removed. If [normalize] is false, note that the result
* isn't guaranteed to be normalized even if this and [child] are both normalized themselves.
*
* If [child] is an [absolute path][isAbsolute] or [has a volume letter][hasVolumeLetter] then
* this function is equivalent to `child.toPath(normalize)`.
*/
fun resolve(child: String, normalize: Boolean = false): Path
/**
* Returns a path that resolves [child] relative to this path.
*
* Set [normalize] to true to eagerly consume `..` segments on the resolved path. In all cases,
* leading `..` on absolute paths will be removed. If [normalize] is false, note that the result
* isn't guaranteed to be normalized even if this and [child] are both normalized themselves.
*
* If [child] is an [absolute path][isAbsolute] or [has a volume letter][hasVolumeLetter] then
* this function is equivalent to `child.toPath(normalize)`.
*/
fun resolve(child: ByteString, normalize: Boolean = false): Path
/**
* Returns a path that resolves [child] relative to this path.
*
* Set [normalize] to true to eagerly consume `..` segments on the resolved path. In all cases,
* leading `..` on absolute paths will be removed. If [normalize] is false, note that the result
* isn't guaranteed to be normalized even if this and [child] are both normalized themselves.
*
* If [child] is an [absolute path][isAbsolute] or [has a volume letter][hasVolumeLetter] then
* this function is equivalent to `child.toPath(normalize)`.
*/
fun resolve(child: Path, normalize: Boolean = false): Path
/**
* Returns this path relative to [other]. This effectively inverts the resolve operator, `/`. For
* any two paths `a` and `b` that have the same root, `a / (b.relativeTo(a))` is equal to `b`. If
* both paths don't use the same slash, the resolved path will use the slash of the [other] path.
*
* @throws IllegalArgumentException if this path and the [other] path are not both
* [absolute paths][isAbsolute] or both [relative paths][isRelative], or if they are both
* [absolute paths][isAbsolute] but of different roots (C: vs D:, or C: vs \\server, etc.).
* It will also throw if the relative path is impossible to resolve. For instance, it is
* impossible to resolve the path `../a` relative to `../../b`.
*/
@Throws(IllegalArgumentException::class)
fun relativeTo(other: Path): Path
/**
* Returns the normalized version of this path. This has the same effect as
* `this.toString().toPath(normalize = true)`.
*/
fun normalized(): Path
override fun compareTo(other: Path): Int
override fun equals(other: Any?): Boolean
override fun hashCode(): Int
override fun toString(): String
companion object {
/**
* Either `/` (on UNIX-like systems including Android, iOS, and Linux) or `\` (on Windows
* systems).
*
* This separator is used by `FileSystem.SYSTEM` and possibly other file systems on the host
* system. Some file system implementations may not use this separator.
*/
val DIRECTORY_SEPARATOR: String
/**
* Returns the [Path] representation for this string.
*
* Set [normalize] to true to eagerly consume `..` segments in your path. In all cases, leading
* `..` on absolute paths will be removed.
*
* ```
* "/Users/jesse/Documents/../notes.txt".toPath(normalize = false).toString() => "/Users/jesse/Documents/../notes.txt"
* "/Users/jesse/Documents/../notes.txt".toPath(normalize = true).toString() => "/Users/jesse/notes.txt"
* ```
*/
fun String.toPath(normalize: Boolean = false): Path
}
}
|
apache-2.0
|
86d5bfe1e29d3c65e442adbfbca6a8ec
| 48.883495 | 141 | 0.645452 | 3.847728 | false | false | false | false |
vanshg/KrazyKotlin
|
src/main/kotlin/com/vanshgandhi/krazykotlin/IntExtensions.kt
|
1
|
3502
|
package com.vanshgandhi.krazykotlin
import java.util.concurrent.ThreadLocalRandom
/**
* Created by Vansh Gandhi on 8/2/17.
* All functions in this class take precedence over any prefix operator (such as negative sign)
*/
/** Returns the absolute value */
val Int.abs get() = Math.abs(this)
/** Returns an array of the digits in the number. If the int is negative, the minus sign is omitted */
val Int.digits get() = toString()
.filter { it.isDigit() }
.map { it.toInt() - '0'.toInt() }
/** Returns number of digits in this number */
val Int.numberOfDigits get() = toString().length
/** Returns if the number is even */
val Int.isEven get() = this % 2 == 0
/** Returns if the number is odd */
val Int.isOdd get() = this % 2 != 0
/** Returns if the number is positive */
val Int.isPositive get() = this > 0
/** Returns if the number is negative */
val Int.isNegative get() = this < 0
/** Returns the Roman Numeral representation of this integer. Returns null for non-positive numbers */
val Int.romanNumeral: String? get() {
var romanValue: String? = null
val romanValues = listOf(
Pair("M", 1000),
Pair("CM", 900),
Pair("D", 500),
Pair("CD", 400),
Pair("C", 100),
Pair("XC", 90),
Pair("L", 50),
Pair("XL", 40),
Pair("X", 10),
Pair("IX", 9),
Pair("V", 5),
Pair("IV", 4),
Pair("I", 1)
)
// this calculation is only valid for positive numbers
if (this > 0) {
romanValue = ""
var startingValue = this
romanValues.forEach {
val (romanChar, arabicValue) = it
val div = startingValue / arabicValue
if (div > 0) {
for (i in 1..div) {
romanValue += romanChar
}
startingValue -= arabicValue * div
}
}
}
return romanValue
}
val Int.tenth get() = this / 10
val Int.fourth get() = this / 4
val Int.quarter get() = fourth
val Int.third get() = this / 3
val Int.half get() = this / 2
val Int.doubled get() = this * 2
val Int.tripled get() = this * 3
val Int.quadrupled get() = this * 4
val Int.squared get() = this * this
val Int.cubed get() = this * this * this
val Int.sqrt get() = Math.sqrt(this.toDouble())
val Int.cbrt get() = Math.cbrt(this.toDouble())
/** Returns the GCD of this integer and n */
fun Int.gcd(n: Int): Int {
return if (n == 0) this else n.gcd(this % n)
}
/** Returns the LCM of this integer and n */
fun Int.lcm(n: Int): Int {
return (this / this.gcd(n) * n).abs
}
/** Returns this integer raised to the passed in integer */
infix fun Int.pow(power: Number): Double {
return Math.pow(this.toDouble(), power.toDouble())
}
/** Returns this integer raised to the passed in integer */
infix fun Int.toThe(power: Number): Double {
return pow(power)
}
/** Returns the nth root of this integer */
infix fun Int.root(n: Number): Double {
return pow(1/n.toDouble())
}
/** Return a range, represented as a Pair */
infix fun Int.plusMinus(range: Int): IntRange {
return IntRange(this - range, this + range)
}
/** Return a range, represented as a Pair */
infix fun Int.`±`(range: Int): IntRange {
return plusMinus(range)
}
/** Returns a pseudorandom Int value between zero (inclusive) and max (exclusive). */
fun Int.Companion.random(max: Int): Int {
return ThreadLocalRandom.current().nextInt(max)
}
|
mit
|
11c50c49bce0599d55004971fc5c856f
| 27.463415 | 102 | 0.601257 | 3.52568 | false | false | false | false |
Kotlin/kotlinx.coroutines
|
kotlinx-coroutines-core/common/src/CoroutineScope.kt
|
1
|
14077
|
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:OptIn(ExperimentalContracts::class)
package kotlinx.coroutines
import kotlinx.coroutines.internal.*
import kotlinx.coroutines.intrinsics.*
import kotlin.contracts.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
/**
* Defines a scope for new coroutines. Every **coroutine builder** (like [launch], [async], etc.)
* is an extension on [CoroutineScope] and inherits its [coroutineContext][CoroutineScope.coroutineContext]
* to automatically propagate all its elements and cancellation.
*
* The best ways to obtain a standalone instance of the scope are [CoroutineScope()] and [MainScope()] factory functions,
* taking care to cancel these coroutine scopes when they are no longer needed (see section on custom usage below for
* explanation and example).
*
* Additional context elements can be appended to the scope using the [plus][CoroutineScope.plus] operator.
*
* ### Convention for structured concurrency
*
* Manual implementation of this interface is not recommended, implementation by delegation should be preferred instead.
* By convention, the [context of a scope][CoroutineScope.coroutineContext] should contain an instance of a
* [job][Job] to enforce the discipline of **structured concurrency** with propagation of cancellation.
*
* Every coroutine builder (like [launch], [async], and others)
* and every scoping function (like [coroutineScope] and [withContext]) provides _its own_ scope
* with its own [Job] instance into the inner block of code it runs.
* By convention, they all wait for all the coroutines inside their block to complete before completing themselves,
* thus enforcing the structured concurrency. See [Job] documentation for more details.
*
* ### Android usage
*
* Android has first-party support for coroutine scope in all entities with the lifecycle.
* See [the corresponding documentation](https://developer.android.com/topic/libraries/architecture/coroutines#lifecyclescope).
*
* ### Custom usage
*
* `CoroutineScope` should be declared as a property on entities with a well-defined lifecycle that are
* responsible for launching child coroutines. The corresponding instance of `CoroutineScope` shall be created
* with either `CoroutineScope()` or `MainScope()`:
*
* * `CoroutineScope()` uses the [context][CoroutineContext] provided to it as a parameter for its coroutines
* and adds a [Job] if one is not provided as part of the context.
* * `MainScope()` uses [Dispatchers.Main] for its coroutines and has a [SupervisorJob].
*
* **The key part of custom usage of `CoroutineScope` is cancelling it at the end of the lifecycle.**
* The [CoroutineScope.cancel] extension function shall be used when the entity that was launching coroutines
* is no longer needed. It cancels all the coroutines that might still be running on behalf of it.
*
* For example:
*
* ```
* class MyUIClass {
* val scope = MainScope() // the scope of MyUIClass, uses Dispatchers.Main
*
* fun destroy() { // destroys an instance of MyUIClass
* scope.cancel() // cancels all coroutines launched in this scope
* // ... do the rest of cleanup here ...
* }
*
* /*
* * Note: if this instance is destroyed or any of the launched coroutines
* * in this method throws an exception, then all nested coroutines are cancelled.
* */
* fun showSomeData() = scope.launch { // launched in the main thread
* // ... here we can use suspending functions or coroutine builders with other dispatchers
* draw(data) // draw in the main thread
* }
* }
* ```
*/
public interface CoroutineScope {
/**
* The context of this scope.
* Context is encapsulated by the scope and used for implementation of coroutine builders that are extensions on the scope.
* Accessing this property in general code is not recommended for any purposes except accessing the [Job] instance for advanced usages.
*
* By convention, should contain an instance of a [job][Job] to enforce structured concurrency.
*/
public val coroutineContext: CoroutineContext
}
/**
* Adds the specified coroutine context to this scope, overriding existing elements in the current
* scope's context with the corresponding keys.
*
* This is a shorthand for `CoroutineScope(thisScope + context)`.
*/
public operator fun CoroutineScope.plus(context: CoroutineContext): CoroutineScope =
ContextScope(coroutineContext + context)
/**
* Creates the main [CoroutineScope] for UI components.
*
* Example of use:
* ```
* class MyAndroidActivity {
* private val scope = MainScope()
*
* override fun onDestroy() {
* super.onDestroy()
* scope.cancel()
* }
* }
* ```
*
* The resulting scope has [SupervisorJob] and [Dispatchers.Main] context elements.
* If you want to append additional elements to the main scope, use [CoroutineScope.plus] operator:
* `val scope = MainScope() + CoroutineName("MyActivity")`.
*/
@Suppress("FunctionName")
public fun MainScope(): CoroutineScope = ContextScope(SupervisorJob() + Dispatchers.Main)
/**
* Returns `true` when the current [Job] is still active (has not completed and was not cancelled yet).
*
* Check this property in long-running computation loops to support cancellation:
* ```
* while (isActive) {
* // do some computation
* }
* ```
*
* This property is a shortcut for `coroutineContext.isActive` in the scope when
* [CoroutineScope] is available.
* See [coroutineContext][kotlin.coroutines.coroutineContext],
* [isActive][kotlinx.coroutines.isActive] and [Job.isActive].
*/
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
public val CoroutineScope.isActive: Boolean
get() = coroutineContext[Job]?.isActive ?: true
/**
* A global [CoroutineScope] not bound to any job.
* Global scope is used to launch top-level coroutines which are operating on the whole application lifetime
* and are not cancelled prematurely.
*
* Active coroutines launched in `GlobalScope` do not keep the process alive. They are like daemon threads.
*
* This is a **delicate** API. It is easy to accidentally create resource or memory leaks when
* `GlobalScope` is used. A coroutine launched in `GlobalScope` is not subject to the principle of structured
* concurrency, so if it hangs or gets delayed due to a problem (e.g. due to a slow network), it will stay working
* and consuming resources. For example, consider the following code:
*
* ```
* fun loadConfiguration() {
* GlobalScope.launch {
* val config = fetchConfigFromServer() // network request
* updateConfiguration(config)
* }
* }
* ```
*
* A call to `loadConfiguration` creates a coroutine in the `GlobalScope` that works in background without any
* provision to cancel it or to wait for its completion. If a network is slow, it keeps waiting in background,
* consuming resources. Repeated calls to `loadConfiguration` will consume more and more resources.
*
* ### Possible replacements
*
* In many cases uses of `GlobalScope` should be removed, marking the containing operation with `suspend`, for example:
*
* ```
* suspend fun loadConfiguration() {
* val config = fetchConfigFromServer() // network request
* updateConfiguration(config)
* }
* ```
*
* In cases when `GlobalScope.launch` was used to launch multiple concurrent operations, the corresponding
* operations shall be grouped with [coroutineScope] instead:
*
* ```
* // concurrently load configuration and data
* suspend fun loadConfigurationAndData() {
* coroutineScope {
* launch { loadConfiguration() }
* launch { loadData() }
* }
* }
* ```
*
* In top-level code, when launching a concurrent operation from a non-suspending context, an appropriately
* confined instance of [CoroutineScope] shall be used instead of a `GlobalScope`. See docs on [CoroutineScope] for
* details.
*
* ### GlobalScope vs custom scope
*
* Do not replace `GlobalScope.launch { ... }` with `CoroutineScope().launch { ... }` constructor function call.
* The latter has the same pitfalls as `GlobalScope`. See [CoroutineScope] documentation on the intended usage of
* `CoroutineScope()` constructor function.
*
* ### Legitimate use-cases
*
* There are limited circumstances under which `GlobalScope` can be legitimately and safely used, such as top-level background
* processes that must stay active for the whole duration of the application's lifetime. Because of that, any use
* of `GlobalScope` requires an explicit opt-in with `@OptIn(DelicateCoroutinesApi::class)`, like this:
*
* ```
* // A global coroutine to log statistics every second, must be always active
* @OptIn(DelicateCoroutinesApi::class)
* val globalScopeReporter = GlobalScope.launch {
* while (true) {
* delay(1000)
* logStatistics()
* }
* }
* ```
*/
@DelicateCoroutinesApi
public object GlobalScope : CoroutineScope {
/**
* Returns [EmptyCoroutineContext].
*/
override val coroutineContext: CoroutineContext
get() = EmptyCoroutineContext
}
/**
* Creates a [CoroutineScope] and calls the specified suspend block with this scope.
* The provided scope inherits its [coroutineContext][CoroutineScope.coroutineContext] from the outer scope, but overrides
* the context's [Job].
*
* This function is designed for _parallel decomposition_ of work. When any child coroutine in this scope fails,
* this scope fails and all the rest of the children are cancelled (for a different behavior see [supervisorScope]).
* This function returns as soon as the given block and all its children coroutines are completed.
* A usage example of a scope looks like this:
*
* ```
* suspend fun showSomeData() = coroutineScope {
* val data = async(Dispatchers.IO) { // <- extension on current scope
* ... load some UI data for the Main thread ...
* }
*
* withContext(Dispatchers.Main) {
* doSomeWork()
* val result = data.await()
* display(result)
* }
* }
* ```
*
* The scope in this example has the following semantics:
* 1) `showSomeData` returns as soon as the data is loaded and displayed in the UI.
* 2) If `doSomeWork` throws an exception, then the `async` task is cancelled and `showSomeData` rethrows that exception.
* 3) If the outer scope of `showSomeData` is cancelled, both started `async` and `withContext` blocks are cancelled.
* 4) If the `async` block fails, `withContext` will be cancelled.
*
* The method may throw a [CancellationException] if the current job was cancelled externally
* or may throw a corresponding unhandled [Throwable] if there is any unhandled exception in this scope
* (for example, from a crashed coroutine that was started with [launch][CoroutineScope.launch] in this scope).
*/
public suspend fun <R> coroutineScope(block: suspend CoroutineScope.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return suspendCoroutineUninterceptedOrReturn { uCont ->
val coroutine = ScopeCoroutine(uCont.context, uCont)
coroutine.startUndispatchedOrReturn(coroutine, block)
}
}
/**
* Creates a [CoroutineScope] that wraps the given coroutine [context].
*
* If the given [context] does not contain a [Job] element, then a default `Job()` is created.
* This way, failure of any child coroutine in this scope or [cancellation][CoroutineScope.cancel] of the scope itself
* cancels all the scope's children, just like inside [coroutineScope] block.
*/
@Suppress("FunctionName")
public fun CoroutineScope(context: CoroutineContext): CoroutineScope =
ContextScope(if (context[Job] != null) context else context + Job())
/**
* Cancels this scope, including its job and all its children with an optional cancellation [cause].
* A cause can be used to specify an error message or to provide other details on
* a cancellation reason for debugging purposes.
* Throws [IllegalStateException] if the scope does not have a job in it.
*/
public fun CoroutineScope.cancel(cause: CancellationException? = null) {
val job = coroutineContext[Job] ?: error("Scope cannot be cancelled because it does not have a job: $this")
job.cancel(cause)
}
/**
* Cancels this scope, including its job and all its children with a specified diagnostic error [message].
* A [cause] can be specified to provide additional details on a cancellation reason for debugging purposes.
* Throws [IllegalStateException] if the scope does not have a job in it.
*/
public fun CoroutineScope.cancel(message: String, cause: Throwable? = null): Unit = cancel(CancellationException(message, cause))
/**
* Ensures that current scope is [active][CoroutineScope.isActive].
*
* If the job is no longer active, throws [CancellationException].
* If the job was cancelled, thrown exception contains the original cancellation cause.
* This function does not do anything if there is no [Job] in the scope's [coroutineContext][CoroutineScope.coroutineContext].
*
* This method is a drop-in replacement for the following code, but with more precise exception:
* ```
* if (!isActive) {
* throw CancellationException()
* }
* ```
*
* @see CoroutineContext.ensureActive
*/
public fun CoroutineScope.ensureActive(): Unit = coroutineContext.ensureActive()
/**
* Returns the current [CoroutineContext] retrieved by using [kotlin.coroutines.coroutineContext].
* This function is an alias to avoid name clash with [CoroutineScope.coroutineContext] in a receiver position:
*
* ```
* launch { // this: CoroutineScope
* val flow = flow<Unit> {
* coroutineContext // Resolves into the context of outer launch, which is incorrect, see KT-38033
* currentCoroutineContext() // Retrieves actual context where the flow is collected
* }
* }
* ```
*/
public suspend inline fun currentCoroutineContext(): CoroutineContext = coroutineContext
|
apache-2.0
|
bcd66955a1bfcb1b91ce60ae359f29d0
| 41.787234 | 139 | 0.721532 | 4.475994 | false | false | false | false |
leafclick/intellij-community
|
plugins/git4idea/src/git4idea/ui/branch/dashboard/BranchesTreeModel.kt
|
1
|
5336
|
// 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 git4idea.ui.branch.dashboard
import com.intellij.openapi.actionSystem.DataKey
import com.intellij.util.ThreeState
import git4idea.i18n.GitBundle.message
import git4idea.repo.GitRepository
import java.util.*
import javax.swing.tree.DefaultMutableTreeNode
internal val GIT_BRANCHES = DataKey.create<Set<BranchInfo>>("GitBranchKey")
internal data class BranchInfo(val branchName: String,
val isLocal: Boolean,
val isCurrent: Boolean,
val repositories: List<GitRepository>) {
var isMy: ThreeState = ThreeState.UNSURE
var isFavorite = false
override fun toString() = branchName
}
internal data class BranchNodeDescriptor(val type: NodeType,
val branchInfo: BranchInfo? = null,
val displayName: String? = branchInfo?.branchName,
val parent: BranchNodeDescriptor? = null) {
override fun toString(): String {
val suffix = branchInfo?.branchName ?: displayName
return if (suffix != null) "$type:$suffix" else "$type"
}
fun getDisplayText() = displayName ?: branchInfo?.branchName
}
internal enum class NodeType {
ROOT, LOCAL_ROOT, REMOTE_ROOT, BRANCH, GROUP_NODE
}
internal class BranchTreeNode(nodeDescriptor: BranchNodeDescriptor) : DefaultMutableTreeNode(nodeDescriptor) {
fun getTextRepresentation(): String {
val nodeDescriptor = userObject as? BranchNodeDescriptor ?: return super.toString()
return when (nodeDescriptor.type) {
NodeType.LOCAL_ROOT -> message("group.Git.Local.Branch.title")
NodeType.REMOTE_ROOT -> message("group.Git.Remote.Branch.title")
else -> nodeDescriptor.getDisplayText() ?: super.toString()
}
}
fun getNodeDescriptor() = userObject as BranchNodeDescriptor
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
if (other !is BranchTreeNode) return false
return Objects.equals(this.userObject, other.userObject)
}
override fun hashCode() = Objects.hash(userObject)
}
internal class NodeDescriptorsModel(private val localRootNodeDescriptor: BranchNodeDescriptor,
private val remoteRootNodeDescriptor: BranchNodeDescriptor,
private val isNodeDescriptorAccepted: (BranchNodeDescriptor) -> Boolean) {
/**
* Parent node descriptor to direct children map
*/
private val branchNodeDescriptors = hashMapOf<BranchNodeDescriptor, MutableSet<BranchNodeDescriptor>>()
fun clear() = branchNodeDescriptors.clear()
fun getChildrenForParent(parent: BranchNodeDescriptor): Set<BranchNodeDescriptor> =
branchNodeDescriptors.getOrDefault(parent, emptySet())
fun populateFrom(branches: Sequence<BranchInfo>, useGrouping: Boolean) {
branches.forEach { branch -> populateFrom(branch, useGrouping) }
}
private fun populateFrom(branch: BranchInfo, useGrouping: Boolean) {
var curParent: BranchNodeDescriptor = if (branch.isLocal) localRootNodeDescriptor else remoteRootNodeDescriptor
if (!useGrouping) {
addChild(curParent, BranchNodeDescriptor(NodeType.BRANCH, branch))
return
}
val iter = branch.branchName.split("/").iterator()
while (iter.hasNext()) {
val branchNamePart = iter.next()
val groupNode = iter.hasNext()
val nodeType = if (groupNode) NodeType.GROUP_NODE else NodeType.BRANCH
val branchInfo = if (nodeType == NodeType.BRANCH) branch else null
val branchNodeDescriptor = BranchNodeDescriptor(nodeType, branchInfo, displayName = branchNamePart, parent = curParent)
addChild(curParent, branchNodeDescriptor)
curParent = branchNodeDescriptor
}
}
private fun addChild(parent: BranchNodeDescriptor, child: BranchNodeDescriptor) {
if (!isNodeDescriptorAccepted(child)) return
val directChildren = branchNodeDescriptors.computeIfAbsent(parent) { sortedSetOf(BRANCH_TREE_NODE_COMPARATOR) }
directChildren.add(child)
branchNodeDescriptors[parent] = directChildren
}
}
internal val BRANCH_TREE_NODE_COMPARATOR = Comparator<BranchNodeDescriptor> { d1, d2 ->
val b1 = d1.branchInfo
val b2 = d2.branchInfo
val displayText1 = d1.getDisplayText()
val displayText2 = d2.getDisplayText()
val b1GroupNode = d1.type == NodeType.GROUP_NODE
val b2GroupNode = d2.type == NodeType.GROUP_NODE
val b1Current = b1 != null && b1.isCurrent
val b2Current = b2 != null && b2.isCurrent
val b1Favorite = b1 != null && b1.isFavorite
val b2Favorite = b2 != null && b2.isFavorite
fun compareByDisplayTextOrType() =
if (displayText1 != null && displayText2 != null) displayText1.compareTo(displayText2) else d1.type.compareTo(d2.type)
when {
b1Current && b2Current -> compareByDisplayTextOrType()
b1Current -> -1
b2Current -> 1
b1Favorite && b2Favorite -> compareByDisplayTextOrType()
b1Favorite -> -1
b2Favorite -> 1
b1GroupNode && b2GroupNode -> compareByDisplayTextOrType()
b1GroupNode -> -1
b2GroupNode -> 1
else -> compareByDisplayTextOrType()
}
}
|
apache-2.0
|
6034eae337e69bd073849d0a136b1c21
| 38.242647 | 140 | 0.704648 | 4.811542 | false | false | false | false |
mpcjanssen/simpletask-android
|
app/src/main/java/nl/mpcjanssen/simpletask/AddTask.kt
|
1
|
19934
|
/**
* This file is part of Simpletask.
*
* @copyright 2013- Mark Janssen
*/
package nl.mpcjanssen.simpletask
import android.app.DatePickerDialog
import android.content.*
import android.os.Bundle
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.appcompat.app.AlertDialog
import android.text.InputType
import android.text.Selection
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.Window
import android.view.WindowManager
import hirondelle.date4j.DateTime
import nl.mpcjanssen.simpletask.databinding.AddTaskBinding
import nl.mpcjanssen.simpletask.databinding.LoginBinding
import nl.mpcjanssen.simpletask.task.Priority
import nl.mpcjanssen.simpletask.task.Task
import nl.mpcjanssen.simpletask.task.TodoList
import nl.mpcjanssen.simpletask.util.*
import java.util.*
class AddTask : ThemedActionBarActivity() {
private var startText: String = ""
private val shareText: String? = null
// private val m_backup = ArrayList<Task>()
private var mBroadcastReceiver: BroadcastReceiver? = null
private var localBroadcastManager: LocalBroadcastManager? = null
private lateinit var binding: AddTaskBinding
/*
Deprecated functions still work fine.
For now keep using the old version, will updated if it breaks.
*/
@Suppress("DEPRECATION")
public override fun onCreate(savedInstanceState: Bundle?) {
Log.d(TAG, "onCreate()")
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS)
super.onCreate(savedInstanceState)
TodoApplication.app.loadTodoList("before adding tasks")
val intentFilter = IntentFilter()
intentFilter.addAction(Constants.BROADCAST_SYNC_START)
intentFilter.addAction(Constants.BROADCAST_SYNC_DONE)
localBroadcastManager = TodoApplication.app.localBroadCastManager
val broadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Constants.BROADCAST_SYNC_START) {
setProgressBarIndeterminateVisibility(true)
} else if (intent.action == Constants.BROADCAST_SYNC_DONE) {
setProgressBarIndeterminateVisibility(false)
}
}
}
localBroadcastManager!!.registerReceiver(broadcastReceiver, intentFilter)
mBroadcastReceiver = broadcastReceiver
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
binding = AddTaskBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp)
if (!TodoApplication.config.useListAndTagIcons) {
binding.btnContext.setImageResource(R.drawable.ic_action_todotxt_lists)
binding.btnProject.setImageResource(R.drawable.ic_action_todotxt_tags)
}
if (shareText != null) {
binding.taskText.setText(shareText)
}
setTitle(R.string.addtask)
Log.d(TAG, "Fill addtask")
val taskId = intent.getStringExtra(Constants.EXTRA_TASK_ID)
if (taskId != null) {
val task = TodoApplication.todoList.getTaskWithId(taskId)
if (task != null) TodoApplication.todoList.pendingEdits.add(task)
}
val pendingTasks = TodoApplication.todoList.pendingEdits.map { it.inFileFormat(TodoApplication.config.useUUIDs) }
val preFillString: String = when {
pendingTasks.isNotEmpty() -> {
setTitle(R.string.updatetask)
join(pendingTasks, "\n")
}
intent.hasExtra(Constants.EXTRA_PREFILL_TEXT) -> intent.getStringExtra(Constants.EXTRA_PREFILL_TEXT) ?: ""
intent.hasExtra(Query.INTENT_JSON) -> Query(intent, luaModule = "from_intent").prefill
else -> ""
}
startText = preFillString
// Avoid discarding changes on rotate
if (binding.taskText.text.isEmpty()) {
binding.taskText.setText(preFillString)
}
setInputType()
// Set button callbacks
binding.btnContext.setOnClickListener { showListMenu() }
binding.btnProject.setOnClickListener { showTagMenu() }
binding.btnPrio.setOnClickListener { showPriorityMenu() }
binding.btnDue.setOnClickListener { insertDate(DateType.DUE) }
binding.btnThreshold.setOnClickListener { insertDate(DateType.THRESHOLD) }
binding.btnNext.setOnClickListener { addPrefilledTask() }
binding.btnSave.setOnClickListener { saveTasksAndClose() }
binding.taskText.requestFocus()
Selection.setSelection(binding.taskText.text,0)
}
private fun addPrefilledTask() {
val position = binding.taskText.selectionStart
val remainingText = binding.taskText.text.toString().substring(position)
val endOfLineDistance = remainingText.indexOf('\n')
var endOfLine: Int
endOfLine = if (endOfLineDistance == -1) {
binding.taskText.length()
} else {
position + endOfLineDistance
}
binding.taskText.setSelection(endOfLine)
replaceTextAtSelection("\n", false)
val precedingText = binding.taskText.text.toString().substring(0, endOfLine)
val lineStart = precedingText.lastIndexOf('\n')
val line: String
line = if (lineStart != -1) {
precedingText.substring(lineStart, endOfLine)
} else {
precedingText
}
val t = Task(line)
val prefillItems = mutableListOf<String>()
t.lists?.let {lists ->
prefillItems.addAll(lists.map { "@$it" })
}
t.tags?.let {tags ->
prefillItems.addAll(tags.map { "+$it" })
}
replaceTextAtSelection(join(prefillItems, " "), true)
endOfLine++
binding.taskText.setSelection(endOfLine)
}
private fun setWordWrap(bool: Boolean) {
binding.taskText.setHorizontallyScrolling(!bool)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
val inflater = menuInflater
inflater.inflate(R.menu.add_task, menu)
// Set checkboxes
val menuWordWrap = menu.findItem(R.id.menu_word_wrap)
menuWordWrap.isChecked = TodoApplication.config.isWordWrap
val menuCapitalizeTasks = menu.findItem(R.id.menu_capitalize_tasks)
menuCapitalizeTasks.isChecked = TodoApplication.config.isCapitalizeTasks
return true
}
private fun setInputType() {
val basicType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE
if (TodoApplication.config.isCapitalizeTasks) {
binding.taskText.inputType = basicType or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
} else {
binding.taskText.inputType = basicType
}
setWordWrap(TodoApplication.config.isWordWrap)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
// Respond to the action bar's Up/Home button
android.R.id.home -> {
finishEdit(confirmation = true)
}
R.id.menu_word_wrap -> {
val newVal = !TodoApplication.config.isWordWrap
TodoApplication.config.isWordWrap = newVal
setWordWrap(newVal)
item.isChecked = !item.isChecked
}
R.id.menu_capitalize_tasks -> {
TodoApplication.config.isCapitalizeTasks = !TodoApplication.config.isCapitalizeTasks
setInputType()
item.isChecked = !item.isChecked
}
R.id.menu_help -> {
showHelp()
}
else -> return super.onOptionsItemSelected(item)
}
return true
}
private fun showHelp() {
val i = Intent(this, HelpScreen::class.java)
i.putExtra(Constants.EXTRA_HELP_PAGE, getText(R.string.help_add_task))
startActivity(i)
}
private fun saveTasksAndClose() {
val todoList = TodoApplication.todoList
// strip line breaks
val input: String = binding.taskText.text.toString()
// Don't add empty tasks
if (input.trim { it <= ' ' }.isEmpty()) {
Log.i(TAG, "Not adding empty line")
finish()
return
}
// Update the TodoList with changes
val enteredTasks = getTasks().dropLastWhile { it.text.isEmpty() }.map { task ->
if (TodoApplication.config.hasPrependDate) {
Task(task.text, todayAsString)
} else {
task
}
}
val origTasks = todoList.pendingEdits
Log.i(TAG, "Saving ${enteredTasks.size} tasks, updating $origTasks tasks")
todoList.update(origTasks, enteredTasks, TodoApplication.config.hasAppendAtEnd)
// Save
todoList.notifyTasklistChanged(TodoApplication.config.todoFile, save = true, refreshMainUI = false)
finishEdit(confirmation = false)
}
private fun finishEdit(confirmation: Boolean) {
val close = DialogInterface.OnClickListener { _, _ ->
TodoApplication.todoList.clearPendingEdits()
finish()
}
if (confirmation && (binding.taskText.text.toString() != startText)) {
showConfirmationDialog(this, R.string.cancel_changes, close, null)
} else {
close.onClick(null, 0)
}
}
override fun onBackPressed() {
saveTasksAndClose()
super.onBackPressed()
}
private fun insertDate(dateType: DateType) {
var titleId = R.string.defer_due
if (dateType === DateType.THRESHOLD) {
titleId = R.string.defer_threshold
}
val d = createDeferDialog(this, titleId, object : InputDialogListener {
/*
Deprecated functions still work fine.
For now keep using the old version, will updated if it breaks.
*/
@Suppress("DEPRECATION")
override fun onClick(input: String) {
if (input == "pick") {
/* Note on some Android versions the OnDateSetListener can fire twice
* https://code.google.com/p/android/issues/detail?id=34860
* With the current implementation which replaces the dates this is not an
* issue. The date is just replaced twice
*/
val today = DateTime.today(TimeZone.getDefault())
val dialog = DatePickerDialog(this@AddTask, DatePickerDialog.OnDateSetListener { _, year, month, day ->
val date = DateTime.forDateOnly(year, month + 1, day)
insertDateAtSelection(dateType, date)
},
today.year!!,
today.month!! - 1,
today.day!!)
val showCalendar = TodoApplication.config.showCalendar
dialog.datePicker.calendarViewShown = showCalendar
dialog.datePicker.spinnersShown = !showCalendar
dialog.show()
} else {
if (!input.isEmpty()) {
insertDateAtSelection(dateType, addInterval(DateTime.today(TimeZone.getDefault()), input))
} else {
replaceDate(dateType, input)
}
}
}
})
d.show()
}
private fun replaceDate(dateType: DateType, date: String) {
if (dateType === DateType.DUE) {
replaceDueDate(date)
} else {
replaceThresholdDate(date)
}
}
private fun insertDateAtSelection(dateType: DateType, date: DateTime?) {
date?.let {
replaceDate(dateType, date.format("YYYY-MM-DD"))
}
}
private fun showTagMenu() {
val items = TreeSet<String>()
items.addAll(TodoApplication.todoList.projects)
// Also display projects in tasks being added
val tasks = getTasks()
if (tasks.size == 0) {
tasks.add(Task(""))
}
tasks.forEach {task ->
task.tags?.let {items.addAll(it)}
}
val idx = getCurrentCursorLine()
val task = getTasks().getOrElse(idx) { Task("") }
updateItemsDialog(
TodoApplication.config.tagTerm,
listOf(task),
ArrayList(items),
Task::tags,
Task::addTag,
Task::removeTag
) {
if (idx != -1) {
tasks[idx] = task
} else {
tasks.add(task)
}
binding.taskText.setText(tasks.joinToString("\n") { it.text })
}
}
private fun showPriorityMenu() {
val builder = AlertDialog.Builder(this)
val priorities = Priority.values()
val priorityCodes = priorities.mapTo(ArrayList()) { it.code }
builder.setItems(priorityCodes.toArray<String>(arrayOfNulls<String>(priorityCodes.size))
) { _, which -> replacePriority(priorities[which].code) }
// Create the AlertDialog
val dialog = builder.create()
dialog.setTitle(R.string.priority_prompt)
dialog.show()
}
private fun getTasks(): MutableList<Task> {
val input = binding.taskText.text.toString()
return input.split("\r\n|\r|\n".toRegex()).asSequence().map(::Task).toMutableList()
}
private fun showListMenu() {
val items = TreeSet<String>()
items.addAll(TodoApplication.todoList.contexts)
// Also display contexts in tasks being added
val tasks = getTasks()
if (tasks.size == 0) {
tasks.add(Task(""))
}
tasks.forEach {task ->
task.lists?.let {items.addAll(it)}
}
val idx = getCurrentCursorLine()
val task = getTasks().getOrElse(idx) { Task("") }
updateItemsDialog(
TodoApplication.config.listTerm,
listOf(task),
ArrayList(items),
Task::lists,
Task::addList,
Task::removeList
) {
if (idx != -1) {
tasks[idx] = task
} else {
tasks.add(task)
}
binding.taskText.setText(tasks.joinToString("\n") { it.text })
}
}
private fun getCurrentCursorLine(): Int {
val selectionStart = binding.taskText.selectionStart
if (selectionStart == -1) {
return -1
}
val chars = binding.taskText.text.subSequence(0, selectionStart)
return (0 until chars.length).count { chars[it] == '\n' }
}
private fun replaceDueDate(newDueDate: CharSequence) {
// save current selection and length
val start = binding.taskText.selectionStart
val length = binding.taskText.text.length
val lines = ArrayList<String>()
Collections.addAll(lines, *binding.taskText.text.toString().split("\\n".toRegex()).toTypedArray())
// For some reason the currentLine can be larger than the amount of lines in the EditText
// Check for this case to prevent any array index out of bounds errors
var currentLine = getCurrentCursorLine()
if (currentLine > lines.size - 1) {
currentLine = lines.size - 1
}
if (currentLine != -1) {
val t = Task(lines[currentLine])
t.dueDate = newDueDate.toString()
lines[currentLine] = t.inFileFormat(TodoApplication.config.useUUIDs)
binding.taskText.setText(join(lines, "\n"))
}
restoreSelection(start, length, false)
}
private fun replaceThresholdDate(newThresholdDate: CharSequence) {
// save current selection and length
val start = binding.taskText.selectionStart
val length = binding.taskText.text.length
val lines = ArrayList<String>()
Collections.addAll(lines, *binding.taskText.text.toString().split("\\n".toRegex()).toTypedArray())
// For some reason the currentLine can be larger than the amount of lines in the EditText
// Check for this case to prevent any array index out of bounds errors
var currentLine = getCurrentCursorLine()
if (currentLine > lines.size - 1) {
currentLine = lines.size - 1
}
if (currentLine != -1) {
val t = Task(lines[currentLine])
t.thresholdDate = newThresholdDate.toString()
lines[currentLine] = t.inFileFormat(TodoApplication.config.useUUIDs)
binding.taskText.setText(join(lines, "\n"))
}
restoreSelection(start, length, false)
}
private fun restoreSelection(location: Int, oldLength: Int, moveCursor: Boolean) {
var newLocation = location
val newLength = binding.taskText.text.length
val deltaLength = newLength - oldLength
// Check if we want the cursor to move by delta (for priority changes)
// or not (for due and threshold changes
if (moveCursor) {
newLocation += deltaLength
}
// Don't go out of bounds
newLocation = Math.min(newLocation, newLength)
newLocation = Math.max(0, newLocation)
binding.taskText.setSelection(newLocation, newLocation)
}
private fun replacePriority(newPriority: CharSequence) {
// save current selection and length
val start = binding.taskText.selectionStart
val end = binding.taskText.selectionEnd
Log.d(TAG, "Current selection: $start-$end")
val length = binding.taskText.text.length
val lines = ArrayList<String>()
Collections.addAll(lines, *binding.taskText.text.toString().split("\\n".toRegex()).toTypedArray())
// For some reason the currentLine can be larger than the amount of lines in the EditText
// Check for this case to prevent any array index out of bounds errors
var currentLine = getCurrentCursorLine()
if (currentLine > lines.size - 1) {
currentLine = lines.size - 1
}
if (currentLine != -1) {
val t = Task(lines[currentLine])
Log.d(TAG, "Changing priority from " + t.priority.toString() + " to " + newPriority.toString())
t.priority = Priority.toPriority(newPriority.toString())
lines[currentLine] = t.inFileFormat(TodoApplication.config.useUUIDs)
binding.taskText.setText(join(lines, "\n"))
}
restoreSelection(start, length, true)
}
private fun replaceTextAtSelection(newText: CharSequence, spaces: Boolean) {
var text = newText
val start = binding.taskText.selectionStart
val end = binding.taskText.selectionEnd
if (start == end && start != 0 && spaces) {
// no selection prefix with space if needed
if (binding.taskText.text[start - 1] != ' ') {
text = " $text"
}
}
binding.taskText.text.replace(Math.min(start, end), Math.max(start, end),
text, 0, text.length)
}
public override fun onDestroy() {
super.onDestroy()
mBroadcastReceiver?.let {
localBroadcastManager?.unregisterReceiver(it)
}
}
companion object {
private const val TAG = "AddTask"
}
}
|
gpl-3.0
|
dd46e6452bc04cc745bdf185ca88b37f
| 36.469925 | 123 | 0.603793 | 4.76434 | false | false | false | false |
mpcjanssen/simpletask-android
|
app/src/main/java/nl/mpcjanssen/simpletask/task/TaskAdapter.kt
|
1
|
15098
|
package nl.mpcjanssen.simpletask.task
import android.graphics.Color
import android.graphics.Paint
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.text.SpannableString
import android.text.Spanned.*
import android.text.TextUtils
import android.text.style.StrikethroughSpan
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import nl.mpcjanssen.simpletask.*
import nl.mpcjanssen.simpletask.databinding.ListHeaderBinding
import nl.mpcjanssen.simpletask.databinding.ListItemBinding
import nl.mpcjanssen.simpletask.util.*
import java.util.ArrayList
class TaskViewHolder(itemView: View, val viewType : Int) : RecyclerView.ViewHolder(itemView)
class TaskAdapter(val completeAction: (Task) -> Unit,
val unCompleteAction: (Task) -> Unit,
val onClickAction: (Task) -> Unit,
val onLongClickAction: (Task) -> Boolean,
val startDrag: (RecyclerView.ViewHolder) -> Unit) : RecyclerView.Adapter <TaskViewHolder>() {
lateinit var query: Query
val tag = "TaskAdapter"
var textSize: Float = 14.0F
override fun getItemCount(): Int {
return visibleLines.size + 1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val view = when (viewType) {
0 -> {
// Header
val layout = if (TodoApplication.config.uppercaseHeaders) {
R.layout.drawer_list_header_uppercase
} else {
R.layout.drawer_list_header
}
LayoutInflater.from(parent.context).inflate(layout, parent, false)
}
1 -> {
// Task
LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
}
else -> {
// Empty at end
LayoutInflater.from(parent.context).inflate(R.layout.empty_list_item, parent, false)
}
}
return TaskViewHolder(view, viewType)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
when (holder.viewType) {
0 -> bindHeader(holder, position)
1 -> bindTask(holder, position)
else -> return
}
}
private fun bindHeader(holder : TaskViewHolder, position: Int) {
val binding = ListHeaderBinding.bind(holder.itemView)
val t = binding.listHeaderTitle
val line = visibleLines[position]
t.text = line.title
t.textSize = textSize
}
private fun bindTask (holder : TaskViewHolder, position: Int) {
val binding = ListItemBinding.bind(holder.itemView)
val line = visibleLines[position]
val task = line.task ?: return
val view = holder.itemView
val taskText = binding.tasktext
val taskAge = binding.taskage
val taskDue = binding.taskdue
val taskThreshold = binding.taskthreshold
val taskDragArea = binding.taskdragarea
if (TodoApplication.config.showCompleteCheckbox) {
binding.checkBox.visibility = View.VISIBLE
} else {
binding.checkBox.visibility = View.GONE
}
if (!TodoApplication.config.hasExtendedTaskView) {
binding.datebar.visibility = View.GONE
}
val tokensToShowFilter: (it: TToken) -> Boolean = {
when (it) {
is UUIDToken -> false
is CreateDateToken -> false
is CompletedToken -> false
is CompletedDateToken -> !TodoApplication.config.hasExtendedTaskView
is DueDateToken -> !TodoApplication.config.hasExtendedTaskView
is ThresholdDateToken -> !TodoApplication.config.hasExtendedTaskView
is ListToken -> !query.hideLists
is TagToken -> !query.hideTags
else -> true
}
}
val txt = Interpreter.onDisplayCallback(query.luaModule, task) ?: task.showParts(tokensToShowFilter)
val ss = SpannableString(txt)
task.lists?.mapTo(ArrayList()) { "@$it" }?.let { setColor(ss, Color.GRAY, it) }
task.tags?.mapTo(ArrayList()) { "+$it" }?.let { setColor(ss, Color.GRAY, it) }
val priorityColor: Int
val priority = task.priority
priorityColor = when (priority) {
Priority.A -> ContextCompat.getColor(TodoApplication.app, R.color.simple_red_dark)
Priority.B -> ContextCompat.getColor(TodoApplication.app, R.color.simple_orange_dark)
Priority.C -> ContextCompat.getColor(TodoApplication.app, R.color.simple_green_dark)
Priority.D -> ContextCompat.getColor(TodoApplication.app, R.color.simple_blue_dark)
else -> ContextCompat.getColor(TodoApplication.app, R.color.gray67)
}
setColor(ss, priorityColor, priority.fileFormat)
val completed = task.isCompleted()
taskAge.textSize = textSize * TodoApplication.config.dateBarRelativeSize
taskDue.textSize = textSize * TodoApplication.config.dateBarRelativeSize
taskThreshold.textSize = textSize * TodoApplication.config.dateBarRelativeSize
val cb = binding.checkBox
if (completed) {
// Log.i( "Striking through " + task.getText());
ss.setSpan(StrikethroughSpan(), 0 , ss.length, SPAN_INCLUSIVE_INCLUSIVE)
taskAge.paintFlags = taskAge.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
cb.setOnClickListener { unCompleteAction(task) }
} else {
taskAge.paintFlags = taskAge.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
cb.setOnClickListener { completeAction(task) }
}
taskText.text = ss
taskText.textSize = textSize
handleEllipsis(taskText)
cb.isChecked = completed
val relAge = getRelativeAge(task, TodoApplication.app)
val relDue = getRelativeDueDate(task, TodoApplication.app)
val relativeThresholdDate = getRelativeThresholdDate(task, TodoApplication.app)
if (!relAge.isNullOrEmpty() && !query.hideCreateDate) {
taskAge.text = relAge
taskAge.visibility = View.VISIBLE
} else {
taskAge.text = ""
taskAge.visibility = View.GONE
}
if (relDue != null) {
taskDue.text = relDue
taskDue.visibility = View.VISIBLE
} else {
taskDue.text = ""
taskDue.visibility = View.GONE
}
if (!relativeThresholdDate.isNullOrEmpty()) {
taskThreshold.text = relativeThresholdDate
taskThreshold.visibility = View.VISIBLE
} else {
taskThreshold.text = ""
taskThreshold.visibility = View.GONE
}
// Set selected state
// Log.d(tag, "Setting selected state ${TodoList.isSelected(item)}")
view.isActivated = TodoApplication.todoList.isSelected(task)
taskDragArea.visibility = dragIndicatorVisibility(position)
// Set click listeners
view.setOnClickListener {
onClickAction (task)
it.isActivated = !it.isActivated
taskDragArea.visibility = dragIndicatorVisibility(position)
}
view.setOnLongClickListener { onLongClickAction (task) }
taskDragArea.setOnTouchListener { view, motionEvent ->
if (motionEvent.actionMasked == MotionEvent.ACTION_DOWN) {
startDrag(holder)
}
false
}
}
internal var visibleLines = ArrayList<VisibleLine>()
internal fun setFilteredTasks(caller: Simpletask, newQuery: Query) {
textSize = TodoApplication.config.tasklistTextSize
Log.i(tag, "Text size = $textSize")
query = newQuery
caller.runOnUiThread {
caller.showListViewProgress(true)
}
Log.i(tag, "setFilteredTasks called: ${TodoApplication.todoList}")
val (visibleTasks, total) = TodoApplication.todoList.getSortedTasks(newQuery, TodoApplication.config.sortCaseSensitive)
countTotalTasks = total
countVisibleTasks = visibleTasks.size
val newVisibleLines = ArrayList<VisibleLine>()
newVisibleLines.addAll(addHeaderLines(visibleTasks, newQuery, getString(R.string.no_header)))
caller.runOnUiThread {
// Replace the array in the main thread to prevent OutOfIndex exceptions
visibleLines = newVisibleLines
caller.showListViewProgress(false)
if (TodoApplication.config.lastScrollPosition != -1) {
val manager = caller.listView.layoutManager as LinearLayoutManager?
val position = TodoApplication.config.lastScrollPosition
val offset = TodoApplication.config.lastScrollOffset
Log.i(tag, "Restoring scroll offset $position, $offset")
manager?.scrollToPositionWithOffset(position, offset)
}
notifyDataSetChanged()
}
}
var countVisibleTasks = 0
var countTotalTasks = 0
/*
** Get the adapter position for task
*/
fun getPosition(task: Task): Int {
val line = TaskLine(task = task)
return visibleLines.indexOf(line)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getItemViewType(position: Int): Int {
if (position == visibleLines.size) {
return 2
}
val line = visibleLines[position]
return if (line.header) {
0
} else {
1
}
}
private fun handleEllipsis(taskText: TextView) {
val noEllipsizeValue = "no_ellipsize"
val ellipsizeKey = TodoApplication.app.getString(R.string.task_text_ellipsizing_pref_key)
val ellipsizePref = TodoApplication.config.prefs.getString(ellipsizeKey, noEllipsizeValue)
if (noEllipsizeValue != ellipsizePref) {
taskText.ellipsize = when (ellipsizePref) {
"start" -> TextUtils.TruncateAt.START
"end" -> TextUtils.TruncateAt.END
"middle" -> TextUtils.TruncateAt.MIDDLE
"marquee" -> TextUtils.TruncateAt.MARQUEE
else -> {
Log.w(tag, "Unrecognized preference value for task text ellipsis: {} ! $ellipsizePref")
TextUtils.TruncateAt.MIDDLE
}
}
taskText.maxLines = 1
taskText.setHorizontallyScrolling(true)
}
}
fun dragIndicatorVisibility(visibleLineIndex: Int): Int {
if (!TodoApplication.config.hasTaskDrag) {
return View.GONE
}
val line = visibleLines[visibleLineIndex]
if (line.header) return View.GONE
val task = line.task ?: throw IllegalStateException("If it's not a header, it must be a task")
val shouldShow = TodoApplication.todoList.isSelected(task)
&& canMoveLineUpOrDown(visibleLineIndex)
return if (shouldShow) View.VISIBLE else View.GONE
}
fun canMoveLineUpOrDown(fromIndex: Int): Boolean {
return canMoveVisibleLine(fromIndex, fromIndex - 1)
|| canMoveVisibleLine(fromIndex, fromIndex + 1)
}
fun canMoveVisibleLine(fromIndex: Int, toIndex: Int): Boolean {
if (fromIndex < 0 || fromIndex >= visibleLines.size) return false
if (toIndex < 0 || toIndex >= visibleLines.size) return false
val from = visibleLines[fromIndex]
val to = visibleLines[toIndex]
if (from.header) return false
if (to.header) return false
val comp = TodoApplication.todoList.getMultiComparator(query,
TodoApplication.config.sortCaseSensitive)
val comparison = comp.comparator.compare(from.task, to.task)
return comparison == 0
}
// Updates the UI, but avoids the red line
fun visuallyMoveLine(fromVisibleLineIndex: Int, toVisibleLineIndex: Int) {
val lineToMove = visibleLines.removeAt(fromVisibleLineIndex)
visibleLines.add(toVisibleLineIndex, lineToMove)
notifyItemMoved(fromVisibleLineIndex, toVisibleLineIndex)
}
fun getMovableTaskAt(visibleLineIndex: Int): Task {
return visibleLines[visibleLineIndex].task
?: throw IllegalStateException("Should only be called after canMoveVisibleLine")
}
fun persistLineMove(fromTask: Task, toTask: Task, isMoveBelow: Boolean) {
// -- What is the meaning of isMoveBelow, moveBelow, moveAbove etc? --
//
// Example todo.txt file:
//
// First (index 0)
// Above-Middle (index 1)
// Middle (index 2)
// Last (index 3)
//
// The interpretation of which position we mean with `toTask` depends on
// whether we're moving the item upwards or downwards:
//
// * If you move "Middle" below "Last" (fromTask=2, toTask=3), moving it
// to the position of task 3 means it should be placed directly
// *below* that task in the todo.txt file. In this case, we're given
// moveBelow=true and we call `moveBelow`.
//
// * If instead you move "Middle" above "First" (fromTask=2, toTask=0),
// it is also moved to the position of that task, but now that means
// it should be placed *above* that task. We're given moveBelow=false
// and we call `moveAbove`.
//
// * If instead you drag "First" to the very bottom, then move it up to
// between "Above-Middle" and "Middle", the last task it will move
// past is "Middle". This means the `DragTasksCallback` will call
// persistLineMove with fromTask=0, toTask=2. However, it doesn't
// want us to move "First" just below "Middle"! It wants us to move
// "First" just *above* "Middle". To communicate this difference, it
// passes isMoveBelow=false. We call `moveAbove`.
//
// -------------------------------------------------------------------
val comp = TodoApplication.todoList.getMultiComparator(query,
TodoApplication.config.sortCaseSensitive)
// If we're sorting by reverse file order, the meaning of above/below
// is swapped in the todo.txt file vs in the displayed lines
if (isMoveBelow xor !comp.fileOrder) {
TodoApplication.todoList.moveBelow(toTask, fromTask)
} else {
TodoApplication.todoList.moveAbove(toTask, fromTask)
}
TodoApplication.todoList.notifyTasklistChanged(
TodoApplication.config.todoFile,
save = true,
refreshMainUI = true,
forceKeepSelection = true);
}
}
|
gpl-3.0
|
c8ffb3399bb8cd2aba205032d53382fd
| 38.52356 | 127 | 0.624652 | 4.721076 | false | false | false | false |
JoachimR/Bible2net
|
app/src/main/java/de/reiss/bible2net/theword/model/Note.kt
|
1
|
1068
|
package de.reiss.bible2net.theword.model
import android.os.Parcel
import android.os.Parcelable
import java.util.Date
data class Note(
val date: Date,
val noteText: String,
val theWordContent: TheWordContent
) : Comparable<Note>, Parcelable {
override fun compareTo(other: Note) = this.date.compareTo(other.date)
constructor(source: Parcel) : this(
source.readSerializable() as Date,
source.readString()!!,
source.readParcelable<TheWordContent>(TheWordContent::class.java.classLoader)!!
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
writeSerializable(date)
writeString(noteText)
writeParcelable(theWordContent, 0)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<Note> = object : Parcelable.Creator<Note> {
override fun createFromParcel(source: Parcel): Note = Note(source)
override fun newArray(size: Int): Array<Note?> = arrayOfNulls(size)
}
}
}
|
gpl-3.0
|
11bbcdc4224b004ce847e11c5e5814a2
| 28.666667 | 87 | 0.67603 | 4.341463 | false | false | false | false |
miketrewartha/positional
|
app/src/main/kotlin/io/trewartha/positional/ui/sun/DuskFragment.kt
|
1
|
1712
|
package io.trewartha.positional.ui.sun
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.hilt.navigation.fragment.hiltNavGraphViewModels
import dagger.hilt.android.AndroidEntryPoint
import io.trewartha.positional.R
import io.trewartha.positional.databinding.DuskFragmentBinding
@AndroidEntryPoint
class DuskFragment : Fragment() {
private var _viewBinding: DuskFragmentBinding? = null
private val viewBinding get() = _viewBinding!!
private val viewModel: SunViewModel by hiltNavGraphViewModels(R.id.nav_graph)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_viewBinding = DuskFragmentBinding.inflate(inflater, container, false)
return viewBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
viewModel.sunState.observe(viewLifecycleOwner, ::observeSunState)
}
override fun onDestroyView() {
super.onDestroyView()
_viewBinding = null
}
private fun observeSunState(sunState: SunViewModel.SunState) {
with(viewBinding) {
progressIndicator.animate()
.alpha(0f)
.withEndAction { progressIndicator.visibility = View.GONE }
dateTextView.text = sunState.date
astronomicalValueTextView.text = sunState.astronomicalDusk
nauticalValueTextView.text = sunState.nauticalDusk
civilValueTextView.text = sunState.civilDusk
sunsetValueTextView.text = sunState.sunset
}
}
}
|
mit
|
a96582decef30a35de1f50634ad8fc41
| 33.24 | 81 | 0.715537 | 4.493438 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/tests/testData/script/definition/highlighting/doNotSpeakAboutJava/template/template.kt
|
8
|
2073
|
package custom.scriptDefinition
import kotlin.script.dependencies.*
import kotlin.script.experimental.dependencies.*
import kotlin.script.templates.*
import java.io.File
import kotlin.script.experimental.location.*
class TestDependenciesResolver : DependenciesResolver {
override fun resolve(scriptContents: ScriptContents, environment: Environment): DependenciesResolver.ResolveResult {
val reports = ArrayList<ScriptReport>()
scriptContents.text?.let { text ->
text.lines().forEachIndexed { lineIndex, line ->
val adjustedLine = line.replace(Regex("(<error descr=\"Can't use\">)|(</error>)|(<warning descr=\"Shouldn't use\">)|(</warning>)"), "")
Regex("java").findAll(adjustedLine).forEach {
reports.add(
ScriptReport(
"Can't use",
ScriptReport.Severity.ERROR,
ScriptReport.Position(lineIndex, it.range.first, lineIndex, it.range.last + 1)
)
)
}
Regex("scala").findAll(adjustedLine).forEach {
reports.add(
ScriptReport(
"Shouldn't use",
ScriptReport.Severity.WARNING,
ScriptReport.Position(lineIndex, it.range.first, lineIndex, it.range.last + 1)
)
)
}
}
}
return DependenciesResolver.ResolveResult.Success(
ScriptDependencies(
classpath = listOf(environment["template-classes"] as File)
),
reports
)
}
}
@ScriptExpectedLocations([ScriptExpectedLocation.Everywhere])
@ScriptTemplateDefinition(TestDependenciesResolver::class, scriptFilePattern = "script.kts")
class Template : Base()
open class Base {
val i = 3
val str = ""
}
|
apache-2.0
|
9ad29a980071bd67f28798397c26afdf
| 38.884615 | 151 | 0.534973 | 5.679452 | false | false | false | false |
craftsmenlabs/gareth-jvm
|
gareth-core/src/main/kotlin/org/craftsmenlabs/gareth/validator/services/ExperimentService.kt
|
1
|
5873
|
package org.craftsmenlabs.gareth.validator.services
import org.craftsmenlabs.gareth.validator.BadRequestException
import org.craftsmenlabs.gareth.validator.model.*
import org.craftsmenlabs.gareth.validator.mongo.ExperimentConverter
import org.craftsmenlabs.gareth.validator.mongo.ExperimentDao
import org.craftsmenlabs.gareth.validator.mongo.ExperimentEntity
import org.craftsmenlabs.gareth.validator.mongo.ExperimentTemplateEntity
import org.craftsmenlabs.gareth.validator.time.DateFormatUtils
import org.craftsmenlabs.gareth.validator.time.TimeService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class ExperimentService @Autowired constructor(val experimentDao: ExperimentDao,
val templateService: TemplateService,
val converter: ExperimentConverter,
val timeService: TimeService) {
var saveListener: ((ExperimentDTO) -> Unit)? = null
fun setListener(listener: ((ExperimentDTO) -> Unit)?) {
saveListener = listener
}
fun getExperimentById(id: String): ExperimentDTO {
return converter.toDTO(findById(id))
}
fun getFiltered(projectId: String,
createdAfter: String? = null,
status: ExecutionStatus? = null,
completed: Boolean?): List<ExperimentDTO> =
getFilteredEntities(projectId, createdAfter, status, completed).map { converter.toDTO(it) }
fun getFilteredEntities(templateId: String,
createdAfter: String? = null,
status: ExecutionStatus? = null,
onlyFinished: Boolean? = null): List<ExperimentEntity> {
validateFilterCriteria(status, onlyFinished)
val createdAfter = if (createdAfter == null) null else DateFormatUtils.parseDateStringToMidnight(createdAfter)
val creationFilter: (ExperimentEntity) -> Boolean = {
createdAfter == null || it.dateCreated.isAfter(createdAfter)
}
val finishedFilter: (ExperimentEntity) -> Boolean = {
onlyFinished == null || onlyFinished == (it.dateCompleted != null)
}
val statusFilter: (ExperimentEntity) -> Boolean = {
status == null || status == it.result
}
return experimentDao.findByTemplateId(templateId)
.filter(creationFilter)
.filter(finishedFilter)
.filter(statusFilter)
}
private fun validateFilterCriteria(status: ExecutionStatus? = null,
onlyFinished: Boolean?) {
if (onlyFinished != null) {
if (onlyFinished == true && status != null && !status.isCompleted())
throw IllegalArgumentException("Cannot filter on running status when querying only for finished experiments.")
}
}
fun createExperiment(dto: ExperimentCreateDTO): ExperimentDTO {
val entity = createEntityForTemplate(dto.templateId)
val now = timeService.now()
entity.dateCreated = now
entity.dateDue = if (dto.dueDate == null) now else timeService.toDate(dto.dueDate as DateTimeDTO)
//template is ready
entity.environment = if (dto.environment == null) setOf() else converter.getEnvironmentItems(dto.environment!!).toSet()
entity.result = ExecutionStatus.PENDING
val saved = experimentDao.save(entity)
val dto = converter.toDTO(saved)
saveListener?.invoke(dto)
return dto
}
private fun createEntityForTemplate(templateId: String): ExperimentEntity {
val template: ExperimentTemplateEntity = templateService.findByid(templateId)
if (template.ready == null) {
throw BadRequestException("You cannot start an experiment that is not ready.")
}
val entity = ExperimentEntity()
entity.projectId = template.projectId
entity.templateId = templateId
//When the template is not ready this code is never reached, hence these exceptions should never be thrown
entity.baseline = template.baseline ?: throw IllegalStateException("baseline cannot be null")
entity.assume = template.assume ?: throw IllegalStateException("assume cannot be null")
entity.timeline = template.timeline ?: throw IllegalStateException("timeline cannot be null")
entity.success = template.success
entity.failure = template.failure
entity.name = template.name
return entity
}
fun updateExperiment(experiment: ExperimentDTO): ExperimentDTO {
val updated = converter.copyEditableValues(findById(experiment.id), experiment)
val savedEntity = experimentDao.save(updated)
val dto = converter.toDTO(savedEntity)
saveListener?.invoke(dto)
return dto
}
fun loadAllExperiments(): List<ExperimentDTO> {
return experimentDao.findAll().map { converter.toDTO(it) }
}
/**
* Bases on the template's interval pattern, returns the creation dto for the next experiment,
* or null if the template has no repeat
*/
fun scheduleNewInstance(dto: ExperimentDTO): ExperimentCreateDTO? {
val template = templateService.findByid(findById(dto.id).templateId)
if (template.interval != ExecutionInterval.NO_REPEAT) {
val delay = timeService.getDelay(timeService.now(), template.interval)
return ExperimentCreateDTO(templateId = template.id!!, dueDate = DateTimeDTO(delay), environment = dto.environment)
} else
return null
}
fun findById(id: String): ExperimentEntity =
experimentDao.findOne(id) ?: throw IllegalArgumentException("No experiment with id $id")
}
|
gpl-2.0
|
bc52a980bebce2d00e5ca17536e66ae9
| 45.992 | 127 | 0.66644 | 5.120314 | false | false | false | false |
android/compose-samples
|
Owl/app/src/main/java/com/example/owl/ui/theme/Shape.kt
|
1
|
1041
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.owl.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
val shapes = Shapes(
small = RoundedCornerShape(percent = 50),
medium = RoundedCornerShape(size = 0f),
large = RoundedCornerShape(
topStart = 16.dp,
topEnd = 0.dp,
bottomEnd = 0.dp,
bottomStart = 16.dp
)
)
|
apache-2.0
|
d5acd273ba08302442a414afd405cbde
| 31.53125 | 75 | 0.720461 | 4.114625 | false | false | false | false |
Flank/flank
|
flank-scripts/src/test/kotlin/flank/scripts/FuelMockServer.kt
|
1
|
965
|
package flank.scripts
import com.github.kittinunf.fuel.core.Client
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.core.requests.DefaultBody
import flank.scripts.ops.firebase.testContent
class FuelMockServer : Client {
override fun executeRequest(request: Request): Response {
val url = request.url.toString()
return when {
url.startsWith("https://api.github.com/repos/flank/flank/", ignoreCase = true) -> handleGithubMockRequest(url, request)
url == "http://test.account.service" -> request.buildResponse(testContent, 200)
else -> Response(request.url)
}
}
}
fun Request.buildResponse(body: String, statusCode: Int) =
Response(
url, statusCode = statusCode, responseMessage = body,
body = DefaultBody(
{ body.byteInputStream() },
{ body.length.toLong() }
)
)
|
apache-2.0
|
99234fe5e01c9cc1593b1e10481f8b4e
| 34.740741 | 131 | 0.675648 | 4.123932 | false | true | false | false |
jotomo/AndroidAPS
|
danar/src/main/java/info/nightscout/androidaps/danar/comm/MsgHistoryAll.kt
|
1
|
6617
|
package info.nightscout.androidaps.danar.comm
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.db.DanaRHistoryRecord
import info.nightscout.androidaps.events.EventDanaRSyncStatus
import info.nightscout.androidaps.logging.LTag
open class MsgHistoryAll(
injector: HasAndroidInjector
) : MessageBase(injector) {
init {
SetCommand(0x41F2)
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(bytes: ByteArray) {
val recordCode = intFromBuff(bytes, 0, 1).toByte()
val date = dateFromBuff(bytes, 1) // 3 bytes
val dailyBasal = intFromBuff(bytes, 4, 2) * 0.01
val dailyBolus = intFromBuff(bytes, 6, 2) * 0.01
//val paramByte5 = intFromBuff(bytes, 4, 1).toByte()
//val paramByte6 = intFromBuff(bytes, 5, 1).toByte()
val paramByte7 = intFromBuff(bytes, 6, 1).toByte()
val paramByte8 = intFromBuff(bytes, 7, 1).toByte()
val value = intFromBuff(bytes, 8, 2).toDouble()
val danaRHistoryRecord = DanaRHistoryRecord()
danaRHistoryRecord.recordCode = recordCode
danaRHistoryRecord.setBytes(bytes)
var messageType = ""
when (recordCode) {
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_BOLUS -> {
val datetime = dateTimeFromBuff(bytes, 1) // 5 bytes
danaRHistoryRecord.recordDate = datetime
when (0xF0 and paramByte8.toInt()) {
0xA0 -> {
danaRHistoryRecord.bolusType = "DS"
messageType += "DS bolus"
}
0xC0 -> {
danaRHistoryRecord.bolusType = "E"
messageType += "E bolus"
}
0x80 -> {
danaRHistoryRecord.bolusType = "S"
messageType += "S bolus"
}
0x90 -> {
danaRHistoryRecord.bolusType = "DE"
messageType += "DE bolus"
}
else -> danaRHistoryRecord.bolusType = "None"
}
danaRHistoryRecord.recordDuration = (paramByte8.toInt() and 0x0F) * 60 + paramByte7.toInt()
danaRHistoryRecord.recordValue = value * 0.01
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_DAILY -> {
messageType += "dailyinsulin"
danaRHistoryRecord.recordDate = date
danaRHistoryRecord.recordDailyBasal = dailyBasal
danaRHistoryRecord.recordDailyBolus = dailyBolus
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_PRIME -> {
messageType += "prime"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
danaRHistoryRecord.recordValue = value * 0.01
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_ERROR -> {
messageType += "error"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
danaRHistoryRecord.recordValue = value * 0.01
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_REFILL -> {
messageType += "refill"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
danaRHistoryRecord.recordValue = value * 0.01
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_BASALHOUR -> {
messageType += "basal hour"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
danaRHistoryRecord.recordValue = value * 0.01
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_TB -> {
messageType += "tb"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
danaRHistoryRecord.recordValue = value * 0.01
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_GLUCOSE -> {
messageType += "glucose"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
danaRHistoryRecord.recordValue = value
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_CARBO -> {
messageType += "carbo"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
danaRHistoryRecord.recordValue = value
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_ALARM -> {
messageType += "alarm"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
var strAlarm = "None"
when (paramByte8.toInt()) {
67 -> strAlarm = "Check"
79 -> strAlarm = "Occlusion"
66 -> strAlarm = "Low Battery"
83 -> strAlarm = "Shutdown"
}
danaRHistoryRecord.recordAlarm = strAlarm
danaRHistoryRecord.recordValue = value * 0.01
}
info.nightscout.androidaps.dana.comm.RecordTypes.RECORD_TYPE_SUSPEND -> {
messageType += "suspend"
val datetimewihtsec = dateTimeSecFromBuff(bytes, 1) // 6 bytes
danaRHistoryRecord.recordDate = datetimewihtsec
var strRecordValue = "Off"
if (paramByte8.toInt() == 79) strRecordValue = "On"
danaRHistoryRecord.stringRecordValue = strRecordValue
}
17.toByte() -> failed = true
}
databaseHelper.createOrUpdate(danaRHistoryRecord)
rxBus.send(EventDanaRSyncStatus(dateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType))
}
}
|
agpl-3.0
|
9a8790ade10f131d816b0c9b044c6210
| 44.020408 | 119 | 0.565664 | 4.676325 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberSelectionTable.kt
|
1
|
2860
|
// 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.refactoring.memberInfo
import com.intellij.icons.AllIcons
import com.intellij.refactoring.classMembers.MemberInfoModel
import com.intellij.refactoring.ui.AbstractMemberSelectionTable
import com.intellij.ui.RowIcon
import org.jetbrains.kotlin.idea.KotlinIconProviderBase
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import javax.swing.Icon
class KotlinMemberSelectionTable(
memberInfos: List<KotlinMemberInfo>,
memberInfoModel: MemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>?,
abstractColumnHeader: String?
) : AbstractMemberSelectionTable<KtNamedDeclaration, KotlinMemberInfo>(memberInfos, memberInfoModel, abstractColumnHeader) {
override fun getAbstractColumnValue(memberInfo: KotlinMemberInfo): Any? {
if (memberInfo.isStatic || memberInfo.isCompanionMember) return null
val member = memberInfo.member
if (member !is KtNamedFunction && member !is KtProperty && member !is KtParameter) return null
if (member.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
myMemberInfoModel.isFixedAbstract(memberInfo)?.let { return it }
}
if (myMemberInfoModel.isAbstractEnabled(memberInfo)) return memberInfo.isToAbstract
return myMemberInfoModel.isAbstractWhenDisabled(memberInfo)
}
override fun isAbstractColumnEditable(rowIndex: Int): Boolean {
val memberInfo = myMemberInfos[rowIndex]
if (memberInfo.isStatic) return false
val member = memberInfo.member
if (member !is KtNamedFunction && member !is KtProperty && member !is KtParameter) return false
if (member.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
myMemberInfoModel.isFixedAbstract(memberInfo)?.let { return false }
}
return memberInfo.isChecked && myMemberInfoModel.isAbstractEnabled(memberInfo)
}
override fun setVisibilityIcon(memberInfo: KotlinMemberInfo, icon: RowIcon) {
icon.setIcon(KotlinIconProviderBase.getVisibilityIcon(memberInfo.member.modifierList), 1)
}
override fun getOverrideIcon(memberInfo: KotlinMemberInfo): Icon? {
val defaultIcon = EMPTY_OVERRIDE_ICON
val member = memberInfo.member
if (member !is KtNamedFunction && member !is KtProperty && member !is KtParameter) return defaultIcon
return when (memberInfo.overrides) {
true -> AllIcons.General.OverridingMethod
false -> AllIcons.General.ImplementingMethod
else -> defaultIcon
}
}
}
|
apache-2.0
|
17502af83e466f316c5500fac42bdafc
| 42.348485 | 158 | 0.75035 | 5.098039 | false | false | false | false |
BijoySingh/Quick-Note-Android
|
scarlet/src/main/java/com/bijoysingh/quicknote/firebase/data/FirebaseFolder.kt
|
1
|
791
|
package com.bijoysingh.quicknote.firebase.data
import com.google.firebase.database.Exclude
import com.maubis.scarlet.base.core.folder.IFolderContainer
import java.util.*
// TODO: Remove this on Firebase deprecation
class FirebaseFolder(
val uuid: String,
val title: String,
val timestamp: Long,
val updateTimestamp: Long,
val color: Int) : IFolderContainer {
@Exclude
override fun uuid(): String = uuid
@Exclude
override fun title(): String = title
@Exclude
override fun timestamp(): Long = timestamp
@Exclude
override fun updateTimestamp(): Long = updateTimestamp
@Exclude
override fun color(): Int = color
constructor() : this(
"invalid",
"",
Calendar.getInstance().timeInMillis,
Calendar.getInstance().timeInMillis,
-0xff8695)
}
|
gpl-3.0
|
1263a711de8f98b10d514a5c7b822bc7
| 21 | 59 | 0.723135 | 4.275676 | false | false | false | false |
vovagrechka/fucking-everything
|
hot-reloadable-idea-piece-of-shit/src/main/java/APSBackPHPDevTools.kt
|
1
|
2517
|
@file:Suppress("Unused")
package vgrechka.idea.hripos
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.type.TypeFactory
import com.intellij.execution.ExecutionManager
import com.intellij.execution.Executor
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.filters.TextConsoleBuilderFactory
import com.intellij.execution.impl.ConsoleViewImpl
import com.intellij.execution.impl.ConsoleViewUtil
import com.intellij.execution.ui.*
import com.intellij.execution.ui.actions.CloseAction
import com.intellij.ide.impl.ProjectUtil
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.wm.WindowManager
import com.intellij.project.stateStore
import com.intellij.unscramble.AnnotateStackTraceAction
import com.intellij.util.containers.ConcurrentIntObjectMap
import java.awt.BorderLayout
import javax.swing.JPanel
import vgrechka.*
import java.io.PrintWriter
import java.io.StringWriter
import java.util.*
import vgrechka.*
import vgrechka.idea.*
import java.awt.Frame
import java.util.*
import javax.swing.JFrame
import kotlin.properties.Delegates.notNull
import kotlin.reflect.KFunction0
object APSBackPHPDevTools {
class InterestingFile(val shortNames: List<String>, val fullPath: String, val firstAdditionalFile: String? = null) {
val shortName get() = shortNames.first()
}
val interestingFiles = listOf(
InterestingFile(listOf("aps-back.php"), "E:/fegh/phizdets/phizdetsc/src/phizdets/php/fuckaroundapsback/aps-back.php", firstAdditionalFile = "E:/fegh/out/phi-tests/aps-back/aps-back.php--1"),
InterestingFile(listOf("phizdets-stdlib.php"), "E:/fegh/phizdets/phizdetsc/src/phizdets/php/phizdets-stdlib.php", firstAdditionalFile = "E:/fegh/phizdets/phizdetsc/src/phizdets/php/phizdets-stdlib.php--1"),
InterestingFile(listOf("phi-engine.php"), "E:/fegh/phizdets/phizdetsc/src/phizdets/php/phi-engine.php")
)
fun findInterestingFile(shortName: String): InterestingFile? =
interestingFiles.find {it.shortNames.contains(shortName)}
fun link(con: Mumbler, item: FileLine) {
val path = findInterestingFile(item.file)?.fullPath
?: item.file
con.link(item.file + ":" + item.line, path, item.line)
}
}
|
apache-2.0
|
5acc8a90340c9164aec656193bdf6cf2
| 40.95 | 214 | 0.790624 | 3.860429 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/testIntegration/framework/KotlinTestFrameworkUtils.kt
|
3
|
2268
|
// 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.testIntegration.framework
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.psi.util.PsiModificationTracker
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
internal object KotlinTestFrameworkUtils {
/**
* Checks whether a class with [qualifiedName] exists in the (module + its dependencies) scope.
* @param namedDeclaration defines the module.
*/
fun hasClass(qualifiedName: String, namedDeclaration: KtNamedDeclaration) =
JavaPsiFacade.getInstance(namedDeclaration.project)
.findClass(qualifiedName, namedDeclaration.resolveScope) != null
inline fun <reified T : Any, E : KtElement> cached(element: E, crossinline function: (E) -> T?): T? {
return CachedValuesManager.getCachedValue(element) {
CachedValueProvider.Result.create({ function(element) }, PsiModificationTracker.MODIFICATION_COUNT)
}.invoke()
}
fun getTopmostClass(psiClass: KtClassOrObject): KtClassOrObject {
var topLevelClass: KtClassOrObject? = psiClass
while (topLevelClass != null && !topLevelClass.isTopLevel()) {
topLevelClass = topLevelClass.getParentOfType(true) // call for anonymous object might result in 'null'
}
return topLevelClass ?: psiClass
}
fun KtAnnotated.isAnnotated(fqName: String): Boolean = annotationEntries.any {
it.isFqName(fqName)
}
private fun KtAnnotationEntry?.isFqName(fqName: String): Boolean {
val shortName = this?.shortName?.asString() ?: return false
return containingKtFile.isResolvable(fqName, shortName)
}
fun KtFile.isResolvable(fqName: String, shortName: String): Boolean {
return fqName.endsWith(shortName) && importDirectives.filter { it.isValidImport }.any {
// TODO: aliases
val name = it.importedFqName?.asString()
name != null &&
fqName == if (!it.isAllUnder) name else "$name.$shortName"
}
}
}
|
apache-2.0
|
a784af1857824c537a9992affecbc292
| 43.490196 | 120 | 0.703704 | 4.856531 | false | false | false | false |
dahlstrom-g/intellij-community
|
platform/diff-impl/src/com/intellij/diff/impl/ui/DiffToolChooser.kt
|
5
|
2554
|
// 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.diff.impl.ui
import com.intellij.diff.DiffTool
import com.intellij.diff.FrameDiffTool
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.dsl.builder.IntelliJSpacingConfiguration
import com.intellij.ui.dsl.builder.components.SegmentedButtonToolbar
import javax.swing.JComponent
abstract class DiffToolChooser(private val targetComponent: JComponent? = null) : DumbAwareAction(), CustomComponentAction {
private val actions = arrayListOf<MyDiffToolAction>()
override fun update(e: AnActionEvent) {
val presentation = e.presentation
val activeTool = getActiveTool()
presentation.text = activeTool.name
if (getForcedDiffTool() != null) {
presentation.isEnabledAndVisible = false
return
}
for (tool in getTools()) {
if (tool !== activeTool) {
presentation.isEnabledAndVisible = true
return
}
}
presentation.isEnabledAndVisible = false
}
override fun actionPerformed(e: AnActionEvent) {
//do nothing
}
abstract fun onSelected(e: AnActionEvent, diffTool: DiffTool)
abstract fun getTools(): List<FrameDiffTool>
abstract fun getActiveTool(): DiffTool
abstract fun getForcedDiffTool(): DiffTool?
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
actions.clear()
for (tool in getTools()) {
actions.add(MyDiffToolAction(tool, tool == getActiveTool()))
}
return SegmentedButtonToolbar(DefaultActionGroup(actions), IntelliJSpacingConfiguration())
.also { it.targetComponent = targetComponent }
}
private inner class MyDiffToolAction(private val diffTool: DiffTool, private var state: Boolean) :
ToggleAction(diffTool.name), DumbAware {
override fun isSelected(e: AnActionEvent): Boolean = state
override fun setSelected(e: AnActionEvent, state: Boolean) {
if (getActiveTool() === diffTool) return
actions.forEach { action -> action.state = !state }
this.state = state
onSelected(e, diffTool)
}
}
}
|
apache-2.0
|
38411b355ca0213dd5f55cee562bd7c6
| 32.168831 | 158 | 0.751762 | 4.686239 | false | false | false | false |
SimpleMobileTools/Simple-Commons
|
commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ExportBlockedNumbersDialog.kt
|
1
|
3171
|
package com.simplemobiletools.commons.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.BLOCKED_NUMBERS_EXPORT_EXTENSION
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import kotlinx.android.synthetic.main.dialog_export_blocked_numbers.view.*
import java.io.File
class ExportBlockedNumbersDialog(
val activity: BaseSimpleActivity,
val path: String,
val hidePath: Boolean,
callback: (file: File) -> Unit,
) {
private var realPath = if (path.isEmpty()) activity.internalStoragePath else path
private val config = activity.baseConfig
init {
val view = activity.layoutInflater.inflate(R.layout.dialog_export_blocked_numbers, null).apply {
export_blocked_numbers_folder.text = activity.humanizePath(realPath)
export_blocked_numbers_filename.setText("${activity.getString(R.string.blocked_numbers)}_${activity.getCurrentFormattedDateTime()}")
if (hidePath) {
export_blocked_numbers_folder_label.beGone()
export_blocked_numbers_folder.beGone()
} else {
export_blocked_numbers_folder.setOnClickListener {
FilePickerDialog(activity, realPath, false, showFAB = true) {
export_blocked_numbers_folder.text = activity.humanizePath(it)
realPath = it
}
}
}
}
activity.getAlertDialogBuilder()
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.apply {
activity.setupDialogStuff(view, this, R.string.export_blocked_numbers) { alertDialog ->
alertDialog.showKeyboard(view.export_blocked_numbers_filename)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val filename = view.export_blocked_numbers_filename.value
when {
filename.isEmpty() -> activity.toast(R.string.empty_name)
filename.isAValidFilename() -> {
val file = File(realPath, "$filename$BLOCKED_NUMBERS_EXPORT_EXTENSION")
if (!hidePath && file.exists()) {
activity.toast(R.string.name_taken)
return@setOnClickListener
}
ensureBackgroundThread {
config.lastBlockedNumbersExportPath = file.absolutePath.getParentPath()
callback(file)
alertDialog.dismiss()
}
}
else -> activity.toast(R.string.invalid_name)
}
}
}
}
}
}
|
gpl-3.0
|
312cb47d232af692cd0545c24712e521
| 45.632353 | 144 | 0.569852 | 5.534031 | false | false | false | false |
androidx/androidx
|
compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/input/mouse/MouseHoverFilterTest.kt
|
3
|
6420
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION") // https://github.com/JetBrains/compose-jb/issues/1514
package androidx.compose.ui.input.mouse
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.TestComposeWindow
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@OptIn(ExperimentalComposeUiApi::class)
@RunWith(JUnit4::class)
class MouseHoverFilterTest {
private val window = TestComposeWindow(width = 100, height = 100, density = Density(2f))
@Test
fun `inside window`() {
var moveCount = 0
var enterCount = 0
var exitCount = 0
window.setContent {
Box(
modifier = Modifier
.pointerMove(
onMove = {
moveCount++
},
onEnter = {
enterCount++
},
onExit = {
exitCount++
}
)
.size(10.dp, 20.dp)
)
}
window.onMouseEntered(
x = 0,
y = 0
)
window.onMouseMoved(
x = 10,
y = 20
)
assertThat(enterCount).isEqualTo(1)
assertThat(exitCount).isEqualTo(0)
assertThat(moveCount).isEqualTo(1)
window.onMouseMoved(
x = 10,
y = 15
)
assertThat(enterCount).isEqualTo(1)
assertThat(exitCount).isEqualTo(0)
assertThat(moveCount).isEqualTo(2)
window.onMouseMoved(
x = 30,
y = 30
)
assertThat(enterCount).isEqualTo(1)
assertThat(exitCount).isEqualTo(1)
assertThat(moveCount).isEqualTo(2)
}
@Test
fun `window enter`() {
var moveCount = 0
var enterCount = 0
var exitCount = 0
window.setContent {
Box(
modifier = Modifier
.pointerMove(
onMove = {
moveCount++
},
onEnter = {
enterCount++
},
onExit = {
exitCount++
}
)
.size(10.dp, 20.dp)
)
}
window.onMouseEntered(
x = 10,
y = 20
)
assertThat(enterCount).isEqualTo(1)
assertThat(exitCount).isEqualTo(0)
assertThat(moveCount).isEqualTo(0)
window.onMouseExited()
assertThat(enterCount).isEqualTo(1)
assertThat(exitCount).isEqualTo(1)
assertThat(moveCount).isEqualTo(0)
}
@Test
fun `scroll should trigger enter and exit`() {
val boxCount = 3
val enterCounts = Array(boxCount) { 0 }
val exitCounts = Array(boxCount) { 0 }
window.setContent {
Column(
Modifier
.size(10.dp, 20.dp)
.verticalScroll(rememberScrollState())
) {
repeat(boxCount) { index ->
Box(
modifier = Modifier
.pointerMove(
onMove = {},
onEnter = {
enterCounts[index] = enterCounts[index] + 1
},
onExit = {
exitCounts[index] = exitCounts[index] + 1
}
)
.size(10.dp, 20.dp)
)
}
}
}
window.onMouseEntered(0, 0)
window.onMouseScroll(
0,
0,
MouseScrollEvent(MouseScrollUnit.Page(1f), MouseScrollOrientation.Vertical)
)
window.render() // synthetic enter/exit will trigger only on relayout
assertThat(enterCounts.toList()).isEqualTo(listOf(1, 1, 0))
assertThat(exitCounts.toList()).isEqualTo(listOf(1, 0, 0))
window.onMouseMoved(1, 1)
window.onMouseScroll(
2,
2,
MouseScrollEvent(MouseScrollUnit.Page(1f), MouseScrollOrientation.Vertical)
)
window.render()
assertThat(enterCounts.toList()).isEqualTo(listOf(1, 1, 1))
assertThat(exitCounts.toList()).isEqualTo(listOf(1, 1, 0))
window.onMouseExited()
assertThat(enterCounts.toList()).isEqualTo(listOf(1, 1, 1))
assertThat(exitCounts.toList()).isEqualTo(listOf(1, 1, 1))
}
}
private fun Modifier.pointerMove(
onMove: () -> Unit,
onExit: () -> Unit,
onEnter: () -> Unit,
): Modifier = pointerInput(onMove, onExit, onEnter) {
awaitPointerEventScope {
while (true) {
val event = awaitPointerEvent()
when (event.type) {
PointerEventType.Move -> onMove()
PointerEventType.Enter -> onEnter()
PointerEventType.Exit -> onExit()
}
}
}
}
|
apache-2.0
|
afccb47206fdc5da95daeb681b7720c9
| 30.317073 | 92 | 0.524611 | 4.874715 | false | false | false | false |
androidx/androidx
|
compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/visualaid/EasingTransformationDemo.kt
|
3
|
3339
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.visualaid
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.unit.dp
@Composable
internal fun AlphaBoxDemo(animatedFloat: Float) {
Rect(color = androidGreen.copy(alpha = animatedFloat.coerceIn(0f, 1f)))
}
@Composable
internal fun ScalingBoxDemo(animatedFloat: Float) {
Rect(modifier = Modifier.scale(animatedFloat))
}
@Composable
internal fun RotatingBoxDemo(animatedFloat: Float) {
Rect(modifier = Modifier.rotate(animatedFloat * 360f))
}
@Composable
internal fun TranslationBoxDemo(animatedFloat: Float) {
Box(modifier = Modifier.height(100.dp).width(50.dp)) {
OutlinedSquare(modifier = Modifier.fillMaxSize())
Canvas(modifier = Modifier.fillMaxSize(), onDraw = {
val sizePx = 16.dp.toPx()
val strokeThickness = 1.dp.toPx()
val size = Size(sizePx, sizePx)
drawRect(
androidGreen,
topLeft = Offset(
this.size.width / 2f - sizePx / 2f,
animatedFloat * (this.size.height - sizePx - strokeThickness)
),
size = size
)
})
}
}
@Composable
internal fun ColorBoxDemo(animatedFloat: Float) {
Rect(color = lerp(androidGreen, AndroidBlue, animatedFloat))
}
@Composable
internal fun Rect(
modifier: Modifier = Modifier,
color: Color = androidGreen
) {
Box {
OutlinedSquare(boxSize)
Canvas(modifier = modifier.then(boxSize), onDraw = {
val sizePx = 16.dp.toPx()
val size = Size(sizePx, sizePx)
drawRect(
color,
topLeft = Offset(
this.size.width / 2f - sizePx / 2f,
this.size.height / 2f - sizePx / 2f
),
size = size
)
})
}
}
@Composable
internal fun OutlinedSquare(modifier: Modifier = Modifier) {
Canvas(modifier = modifier) {
drawRect(AndroidNavy, style = Stroke(1.dp.toPx()))
}
}
private val boxSize = Modifier.size(50.dp)
|
apache-2.0
|
7528e3ea63d9dc595fdfdf035eef3abc
| 30.8 | 81 | 0.675951 | 4.112069 | false | false | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/KDocCopyPastePreProcessorTest.kt
|
4
|
5446
|
// 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.editor
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.testFramework.EditorTestUtil
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import java.awt.datatransfer.StringSelection
class KDocCopyPastePreProcessorTest : KotlinLightCodeInsightFixtureTestCase() {
fun testDefaultPaste() = doTypeTest(
"""
Hello
World
""".trimIndent(),
"""
/**
* <caret>
*/
""".trimIndent(),
"""
/**
* Hello
* World
*/
""".trimIndent()
)
fun testPasteRightAfterAsterisks() = doTypeTest(
"""
Hello
World
""".trimIndent(),
"""
/**
*<caret>
*/
""".trimIndent(),
"""
/**
*Hello
* World
*/
""".trimIndent()
)
fun testPasteNotAlignedText() = doTypeTest(
"""
Hello
World
""".trimIndent(),
"""
/**
* <caret>
*/
""".trimIndent(),
"""
/**
* Hello
* World
*/
""".trimIndent()
)
fun testPasteFirstLineNotAlignedText() = doTypeTest(
"""
Hello
World
""".trimIndent(),
"""
/**
* <caret>
*/
""".trimIndent(),
"""
/**
* Hello
* World
*/
""".trimIndent()
)
fun testPasteTextWithTrailingEmptyLines() = doTypeTest(
"""
Hello
World
""".trimIndent(),
"""
/**
* <caret>
*/
""".trimIndent(),
"""
/**
* Hello
* World
*/
""".trimIndent()
)
fun testPasteTextWithLeadingEmptyLines() = doTypeTest(
"""
Hello
World
""".trimIndent(),
"""
/**
* <caret>
*/
""".trimIndent(),
"""
/**
* Hello
* World
*/
""".trimIndent()
)
fun testPasteTextWithLeadingAndTrailingEmptyLines() = doTypeTest(
"""
Hello
World
""".trimIndent(),
"""
/**
* <caret>
*/
""".trimIndent(),
"""
/**
* Hello
* World
*/
""".trimIndent()
)
fun testPasteKotlinCode() = doTypeTest(
"""
fun main(args: Array<String>) {
println("Hello, world")
}
""".trimIndent(),
"""
/**
* Example usage:
*
* ```
* <caret>
* ```
*/
""".trimIndent(),
"""
/**
* Example usage:
*
* ```
* fun main(args: Array<String>) {
* println("Hello, world")
* }
* ```
*/
""".trimIndent()
)
fun testPasteComplexMarkdownCode() = doTypeTest(
"""
# Heading
Some long
text.
1. Item 1
2. Item 2
```kotlin
fun main(args: Array<String>) {
println("Hello, world")
}
```
> Quote
| id | name |
|----|------|
| 1 | John |
| 2 | Jack |
""".trimIndent(),
"""
/**
* <caret>
*/
""".trimIndent(),
"""
/**
* # Heading
*
* Some long
* text.
*
* 1. Item 1
* 2. Item 2
*
* ```kotlin
* fun main(args: Array<String>) {
* println("Hello, world")
* }
* ```
*
* > Quote
*
* | id | name |
* |----|------|
* | 1 | John |
* | 2 | Jack |
*/
""".trimIndent()
)
fun testNonDocComment() = doTypeTest(
"""
Hello
World
""".trimIndent(),
"""
/*
* <caret>
*/
""".trimIndent(),
"""
/*
* Hello
World
*/
""".trimIndent()
)
private fun doTypeTest(text: String, beforeText: String, afterText: String) {
myFixture.configureByText("a.kt", beforeText.trimMargin())
CopyPasteManager.getInstance().setContents(StringSelection(text))
EditorTestUtil.performPaste(myFixture.editor)
myFixture.checkResult(afterText.trimMargin())
}
}
|
apache-2.0
|
8bc5603d5ca8c9fbf4eb18159a3f5021
| 20.611111 | 120 | 0.34025 | 5.874865 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/base/scripting/projectStructure/ScriptModuleInfo.kt
|
2
|
3723
|
// 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.base.scripting.projectStructure
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.idea.base.projectStructure.KotlinBaseProjectStructureBundle
import org.jetbrains.kotlin.idea.base.projectStructure.LibraryInfoCache
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LanguageSettingsOwner
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleOrigin
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo
import org.jetbrains.kotlin.idea.base.projectStructure.sourceModuleInfos
import org.jetbrains.kotlin.idea.base.scripting.ScriptingTargetPlatformDetector
import org.jetbrains.kotlin.idea.core.script.dependencies.KotlinScriptSearchScope
import org.jetbrains.kotlin.idea.core.script.dependencies.ScriptAdditionalIdeaDependenciesProvider
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.TargetPlatformVersion
import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
data class ScriptModuleInfo(
override val project: Project,
val scriptFile: VirtualFile,
val scriptDefinition: ScriptDefinition
) : IdeaModuleInfo, LanguageSettingsOwner {
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.OTHER
override val name: Name = Name.special("<script ${scriptFile.name} ${scriptDefinition.name}>")
override val displayedName: String
get() = KotlinBaseProjectStructureBundle.message("script.0.1", scriptFile.presentableName, scriptDefinition.name)
override val contentScope
get() = GlobalSearchScope.fileScope(project, scriptFile)
override val moduleContentScope: GlobalSearchScope
get() = KotlinScriptSearchScope(project, contentScope)
override fun dependencies(): List<IdeaModuleInfo> = mutableSetOf<IdeaModuleInfo>(this).apply {
val scriptDependentModules = ScriptAdditionalIdeaDependenciesProvider.getRelatedModules(scriptFile, project)
scriptDependentModules.forEach {
addAll(it.sourceModuleInfos)
}
val scriptDependentLibraries = ScriptAdditionalIdeaDependenciesProvider.getRelatedLibraries(scriptFile, project)
val libraryInfoCache = LibraryInfoCache.getInstance(project)
scriptDependentLibraries.forEach {
addAll(libraryInfoCache[it])
}
val dependenciesInfo = ScriptDependenciesInfo.ForFile(project, scriptFile, scriptDefinition)
add(dependenciesInfo)
dependenciesInfo.sdk?.let { add(SdkInfo(project, it)) }
}.toList()
override val platform: TargetPlatform
get() = ScriptingTargetPlatformDetector.getPlatform(project, scriptFile, scriptDefinition)
override val analyzerServices: PlatformDependentAnalyzerServices
get() = JvmPlatformAnalyzerServices
override val languageVersionSettings: LanguageVersionSettings
get() = ScriptingTargetPlatformDetector.getLanguageVersionSettings(project, scriptFile, scriptDefinition)
override val targetPlatformVersion: TargetPlatformVersion
get() = ScriptingTargetPlatformDetector.getTargetPlatformVersion(project, scriptFile, scriptDefinition)
}
|
apache-2.0
|
572cf0b1acfcc54a755fb85630574b5e
| 50.013699 | 121 | 0.809294 | 5.419214 | false | false | false | false |
jwren/intellij-community
|
plugins/repository-search/src/test/java/org/jetbrains/idea/reposearch/DependencySearchServiceTest.kt
|
1
|
2137
|
package org.jetbrains.idea.reposearch
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.LightPlatformTestCase
import com.intellij.util.WaitFor
import junit.framework.TestCase
import org.jetbrains.concurrency.isPending
import java.util.function.Consumer
class DependencySearchServiceTest : LightPlatformTestCase() {
private lateinit var dependencySearchService: DependencySearchService
override fun setUp() {
super.setUp()
dependencySearchService = DependencySearchService(project)
Disposer.register(testRootDisposable, dependencySearchService)
}
fun testShouldReturnDataFromCache() {
var requests = 0;
val searchParameters = SearchParameters(true, false)
dependencySearchService.setProviders(emptyList(), listOf(object : TestSearchProvider() {
override fun isLocal() = false
override fun fulltextSearch(searchString: String, consumer: Consumer<RepositoryArtifactData>) {
requests++;
consumer.accept(RepositoryArtifactData { searchString })
}
}))
val promise = dependencySearchService.fulltextSearch("something", searchParameters) {}
object : WaitFor(500) {
override fun condition() = !promise.isPending
}
assertTrue(promise.isSucceeded)
TestCase.assertEquals(1, requests)
dependencySearchService.fulltextSearch("something", searchParameters) {}
TestCase.assertEquals(1, requests)
val promise1 = dependencySearchService.fulltextSearch("something", SearchParameters(false, false)) {}
object : WaitFor(500) {
override fun condition() = !promise1.isPending
}
assertTrue(promise1.isSucceeded)
TestCase.assertEquals(2, requests)
}
open class TestSearchProvider : DependencySearchProvider {
override fun suggestPrefix(groupId: String?, artifactId: String?, consumer: Consumer<RepositoryArtifactData>) {
TODO("Not yet implemented")
}
override fun isLocal(): Boolean {
TODO("Not yet implemented")
}
override fun fulltextSearch(searchString: String, consumer: Consumer<RepositoryArtifactData>) {
TODO("Not yet implemented")
}
}
}
|
apache-2.0
|
cd7ddac705d11f42e09037e62779930b
| 31.892308 | 115 | 0.746841 | 5.199513 | false | true | false | false |
aedans/Quartz
|
compiler/src/main/kotlin/io/quartz/gen/jvm/sym/JvmSymTable.kt
|
1
|
844
|
package io.quartz.gen.jvm.sym
import io.quartz.tree.util.QualifiedName
interface JvmSymTable {
fun getMemLoc(name: QualifiedName): JvmMemLoc
companion object {
val default = object : JvmSymTable {
override fun getMemLoc(name: QualifiedName) = JvmMemLoc.Global(name)
}
}
}
fun JvmSymTable.mapMemLoc(map: (QualifiedName, JvmMemLoc) -> JvmMemLoc) =
object : JvmSymTable {
override fun getMemLoc(name: QualifiedName) = map(name, [email protected](name))
}
fun JvmSymTable.withMemLoc(name: QualifiedName, jvmMemLoc: JvmMemLoc) = run {
@Suppress("UnnecessaryVariable", "LocalVariableName")
val _name = name
object : JvmSymTable {
override fun getMemLoc(name: QualifiedName) = if (name == _name) jvmMemLoc else [email protected](name)
}
}
|
mit
|
dfefd78ca624e6639c5183164f613f56
| 31.461538 | 119 | 0.687204 | 3.622318 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/gradle/src/org/jetbrains/plugins/gradle/issue/GradleBuildCancelledIssueChecker.kt
|
12
|
2199
|
// 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.gradle.issue
import com.intellij.build.FilePosition
import com.intellij.build.events.BuildEvent
import com.intellij.build.issue.BuildIssue
import com.intellij.build.issue.BuildIssueQuickFix
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.service.execution.GradleExecutionErrorHandler.getRootCauseAndLocation
import java.util.function.Consumer
/**
* This issue checker provides common handling of the errors caused by build cancellation.
*
* @author Vladislav.Soroka
*/
@ApiStatus.Experimental
class GradleBuildCancelledIssueChecker : GradleIssueChecker {
override fun check(issueData: GradleIssueData): BuildIssue? {
if (issueData.error !is ProcessCanceledException) {
val rootCause = getRootCauseAndLocation(issueData.error).first
if (!rootCause.toString().contains("Build cancelled.")) return null
}
val description = "Build cancelled"
val title = "Build cancelled"
return object : BuildIssue {
override val title: String = title
override val description: String = description
override val quickFixes = emptyList<BuildIssueQuickFix>()
override fun getNavigatable(project: Project): Navigatable? = null
}
}
override fun consumeBuildOutputFailureMessage(message: String,
failureCause: String,
stacktrace: String?,
location: FilePosition?,
parentEventId: Any,
messageConsumer: Consumer<in BuildEvent>): Boolean {
// Build cancellation errors should be handled by GradleBuildCancelledIssueChecker.check method based on exceptions come from Gradle TAPI
if (failureCause.contains("Build cancelled.")) return true
return false
}
}
|
apache-2.0
|
dc37aaaae0134f7fa57dc82ffa8a15c8
| 43.877551 | 141 | 0.700318 | 5.311594 | false | false | false | false |
smmribeiro/intellij-community
|
platform/projectModel-impl/src/com/intellij/configurationStore/SchemeManagerIprProvider.kt
|
6
|
4338
|
// 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.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.PathUtilRt
import com.intellij.util.isEmpty
import com.intellij.util.text.UniqueNameGenerator
import com.intellij.util.toByteArray
import org.jdom.Element
import java.io.InputStream
import java.util.*
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.collections.LinkedHashMap
import kotlin.concurrent.read
import kotlin.concurrent.write
class SchemeManagerIprProvider(private val subStateTagName: String, private val comparator: Comparator<String>? = null) : StreamProvider, SimpleModificationTracker() {
private val lock = ReentrantReadWriteLock()
private var nameToData = LinkedHashMap<String, ByteArray>()
override val isExclusive = false
override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean {
lock.read {
consumer(nameToData.get(PathUtilRt.getFileName(fileSpec))?.let(ByteArray::inputStream))
}
return true
}
override fun delete(fileSpec: String, roamingType: RoamingType): Boolean {
lock.write {
nameToData.remove(PathUtilRt.getFileName(fileSpec))
}
incModificationCount()
return true
}
override fun processChildren(path: String,
roamingType: RoamingType,
filter: (String) -> Boolean,
processor: (String, InputStream, Boolean) -> Boolean): Boolean {
lock.read {
for ((name, data) in nameToData) {
if (filter(name) && !data.inputStream().use { processor(name, it, false) }) {
break
}
}
}
return true
}
override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
LOG.assertTrue(content.isNotEmpty())
lock.write {
nameToData.put(PathUtilRt.getFileName(fileSpec), ArrayUtil.realloc(content, size))
}
incModificationCount()
}
fun load(state: Element?, keyGetter: ((Element) -> String)? = null) {
if (state == null) {
lock.write {
nameToData.clear()
}
incModificationCount()
return
}
val nameToData = LinkedHashMap<String, ByteArray>()
val nameGenerator = UniqueNameGenerator()
for (child in state.getChildren(subStateTagName)) {
// https://youtrack.jetbrains.com/issue/RIDER-10052
// ignore empty elements
if (child.isEmpty()) {
continue
}
var name = keyGetter?.invoke(child) ?: child.getAttributeValue("name")
if (name == null) {
for (optionElement in child.getChildren("option")) {
if (optionElement.getAttributeValue("name") == "myName") {
name = optionElement.getAttributeValue("value")
}
}
}
if (name.isNullOrEmpty()) {
continue
}
nameToData.put(nameGenerator.generateUniqueName("${FileUtil.sanitizeFileName(name, false)}.xml"), child.toByteArray())
}
lock.write {
if (comparator == null) {
this.nameToData = nameToData
}
else {
this.nameToData.clear()
this.nameToData.putAll(nameToData.toSortedMap(comparator))
}
}
incModificationCount()
}
fun writeState(state: Element) {
lock.read {
val names = nameToData.keys.toTypedArray()
if (comparator == null) {
names.sort()
}
else {
names.sortWith(comparator)
}
for (name in names) {
nameToData.get(name)?.let { state.addContent(JDOMUtil.load(it.inputStream())) }
}
}
}
// copy not existent data from this provider to specified
fun copyIfNotExists(provider: SchemeManagerIprProvider) {
lock.read {
provider.lock.write {
for (key in nameToData.keys) {
if (!provider.nameToData.containsKey(key)) {
provider.nameToData.put(key, nameToData.get(key)!!)
provider.incModificationCount()
}
}
}
}
}
}
|
apache-2.0
|
63a96242a470a494a03d703c248be43b
| 30.442029 | 167 | 0.659059 | 4.585624 | false | false | false | false |
testIT-LivingDoc/livingdoc2
|
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/ScenarioFixtureModel.kt
|
2
|
2073
|
package org.livingdoc.engine.execution.examples.scenarios
import org.livingdoc.api.fixtures.scenarios.Step
import org.livingdoc.engine.execution.ScopedFixtureModel
import org.livingdoc.engine.execution.examples.scenarios.matching.ScenarioStepMatcher
import org.livingdoc.engine.execution.examples.scenarios.matching.ScenarioStepMatcher.MatchingResult
import org.livingdoc.engine.execution.examples.scenarios.matching.StepTemplate
import java.lang.reflect.Method
import kotlin.reflect.KClass
internal class ScenarioFixtureModel(
val fixtureClass: Class<*>
) : ScopedFixtureModel(fixtureClass) {
val stepMethods: List<Method>
val stepTemplateToMethod: Map<StepTemplate, Method>
private val stepMatcher: ScenarioStepMatcher
init {
// method analysis
val stepMethods = mutableListOf<Method>()
fixtureClass.declaredMethods.forEach { method ->
if (method.isAnnotatedWith(Step::class)) stepMethods.add(method)
if (method.isAnnotatedWith(Step.Steps::class)) stepMethods.add(method)
}
this.stepMethods = stepMethods
// step alias analysis
val stepAliases = mutableSetOf<String>()
val stepTemplateToMethod = mutableMapOf<StepTemplate, Method>()
stepMethods.forEach { method ->
method.getAnnotationsByType(Step::class.java)
.flatMap { it.value.asIterable() }
.forEach { alias ->
stepAliases.add(alias)
stepTemplateToMethod[StepTemplate.parse(alias)] = method
}
}
this.stepTemplateToMethod = stepTemplateToMethod
this.stepMatcher = ScenarioStepMatcher(stepTemplateToMethod.keys.toList())
}
fun getMatchingStepTemplate(step: String): MatchingResult = stepMatcher.match(step)
fun getStepMethod(template: StepTemplate): Method = stepTemplateToMethod[template]!!
private fun Method.isAnnotatedWith(annotationClass: KClass<out Annotation>): Boolean {
return this.isAnnotationPresent(annotationClass.java)
}
}
|
apache-2.0
|
a9e491ff03d41aa772a5db4cb686e5f6
| 36.690909 | 100 | 0.717318 | 4.754587 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/DialogAction.kt
|
1
|
2171
|
package ch.rmy.android.http_shortcuts.scripting.actions.types
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.databinding.DialogTextBinding
import ch.rmy.android.http_shortcuts.extensions.reloadImageSpans
import ch.rmy.android.http_shortcuts.extensions.showAndAwaitDismissal
import ch.rmy.android.http_shortcuts.scripting.ExecutionContext
import ch.rmy.android.http_shortcuts.utils.ActivityProvider
import ch.rmy.android.http_shortcuts.utils.DialogBuilder
import ch.rmy.android.http_shortcuts.utils.HTMLUtil
import ch.rmy.android.http_shortcuts.variables.Variables
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class DialogAction(private val message: String, private val title: String) : BaseAction() {
@Inject
lateinit var activityProvider: ActivityProvider
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override suspend fun execute(executionContext: ExecutionContext) {
val finalMessage = Variables.rawPlaceholdersToResolvedValues(
message,
executionContext.variableManager.getVariableValuesByIds(),
)
if (finalMessage.isEmpty()) {
return
}
withContext(Dispatchers.Main) {
val activity = activityProvider.getActivity()
val view = DialogTextBinding.inflate(LayoutInflater.from(activity))
val textView = view.text
textView.text = HTMLUtil.formatWithImageSupport(
string = finalMessage,
context = activity,
onImageLoaded = textView::reloadImageSpans,
coroutineScope = this,
)
textView.movementMethod = LinkMovementMethod.getInstance()
DialogBuilder(activity)
.title(title)
.view(view.root)
.positive(R.string.dialog_ok)
.showAndAwaitDismissal()
}
}
}
|
mit
|
93aa6d31cc423c95a8ea370d6970c2dd
| 38.472727 | 91 | 0.712575 | 4.878652 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/LocaleHelper.kt
|
1
|
1834
|
package ch.rmy.android.http_shortcuts.utils
import android.app.LocaleManager
import android.content.Context
import android.os.Build
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.getSystemService
import androidx.core.os.LocaleListCompat
import ch.rmy.android.framework.extensions.runIfNotNull
import java.util.Locale
import javax.inject.Inject
class LocaleHelper
@Inject
constructor(
private val context: Context,
private val settings: Settings,
) {
fun applyLocaleFromSettings() {
val storedPreferredLanguage = settings.language
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.getSystemService<LocaleManager>()!!.applicationLocales
.get(0)
.let { locale ->
if (locale?.language != storedPreferredLanguage?.split('-')?.first()) {
settings.language = locale?.language.runIfNotNull(locale?.country) {
plus("-$it")
}
}
}
}
applyLocale(storedPreferredLanguage)
}
fun applyLocale(locale: String?) {
val preferredLocale = locale
?.let(::getLocale)
setLocale(preferredLocale)
}
private fun setLocale(locale: Locale?) {
AppCompatDelegate.setApplicationLocales(
if (locale != null) LocaleListCompat.create(locale) else LocaleListCompat.getEmptyLocaleList()
)
}
private fun getLocale(localeSpec: String): Locale {
val localeParts = localeSpec.split('-')
val language = localeParts[0]
val country = localeParts.getOrNull(1)
return if (country != null) {
Locale(language, country)
} else {
Locale(language)
}
}
}
|
mit
|
d66c3747e1653f4e94aaebb91f33ed50
| 30.62069 | 106 | 0.625954 | 4.890667 | false | false | false | false |
masm11/contextplayer
|
app/src/main/java/me/masm11/contextplayer/ui/MainActivity.kt
|
1
|
9959
|
/* Context Player - Audio Player with Contexts
Copyright (C) 2016, 2018 Yuuki Harano
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 me.masm11.contextplayer.ui
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.content.ContextCompat
import androidx.core.util.Pair
import android.app.Service
import android.app.AlertDialog
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentActivity
import android.os.IBinder
import android.os.Bundle
import android.view.View
import android.view.Menu
import android.view.MenuItem
import android.view.MenuInflater
import android.net.Uri
import android.widget.Button
import android.widget.TextView
import android.widget.SeekBar
import android.content.Intent
import android.content.Context
import android.content.ServiceConnection
import android.content.ComponentName
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.content.pm.PackageInfo
import android.content.BroadcastReceiver
import android.content.IntentFilter
import android.Manifest
import kotlinx.android.synthetic.main.activity_main.*
import java.io.IOException
import java.util.Locale
import me.masm11.contextplayer.R
import me.masm11.contextplayer.service.PlayerService
import me.masm11.contextplayer.util.Metadata
import me.masm11.contextplayer.fs.MFile
import me.masm11.contextplayer.db.AppDatabase
import me.masm11.contextplayer.db.PlayContext
import me.masm11.contextplayer.db.PlayContextList
import me.masm11.contextplayer.Application
import me.masm11.logger.Log
class MainActivity : FragmentActivity(), ActivityCompat.OnRequestPermissionsResultCallback {
private lateinit var playContexts: PlayContextList
private lateinit var curContext: PlayContext
private lateinit var onContextChangedListener: (PlayContext) -> Unit
private lateinit var onContextSwitchListener: (PlayContext) -> Unit
private val rootDir = MFile("//")
private var curPath: String? = null
private var curTopDir: String? = null
private var curPos: Int = 0 // msec
private var maxPos: Int = 0 // msec
private var seeking: Boolean = false
private var vol: Int = 100
private var needSwitchContext: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
playContexts = (getApplication() as Application).getPlayContextList()
Log.d("rootDir=${rootDir.absolutePath}")
context_name.setOnClickListener {
val i = Intent(this@MainActivity, ContextActivity::class.java)
val pair_1 = Pair<View, String>(context_name, "transit_cat")
val pair_2 = Pair<View, String>(findViewById(R.id.op_frag), "transit_op")
val opt = ActivityOptionsCompat.makeSceneTransitionAnimation(
this@MainActivity, pair_1, pair_2
)
startActivity(i, opt.toBundle())
}
playing_info.setOnClickListener {
val i = Intent(this@MainActivity, ExplorerActivity::class.java)
val pair_1 = Pair<View, String>(playing_info, "transit_title")
val pair_2 = Pair<View, String>(findViewById(R.id.op_frag), "transit_op")
val opt = ActivityOptionsCompat.makeSceneTransitionAnimation(
this@MainActivity, pair_1, pair_2
)
startActivity(i, opt.toBundle())
}
playing_pos.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
if (fromUser)
PlayerService.seek(this@MainActivity, progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
seeking = true
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
seeking = false
}
})
volume.max = 100 - VOLUME_BASE
volume.progress = vol - VOLUME_BASE
volume.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(volume: SeekBar, progress: Int, fromUser: Boolean) {
PlayerService.setVolume(this@MainActivity, VOLUME_BASE + progress)
vol = VOLUME_BASE + progress
}
override fun onStartTrackingTouch(volume: SeekBar) {
/*NOP*/
}
override fun onStopTrackingTouch(volume: SeekBar) {
/*NOP*/
}
})
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
// permission がない && 説明必要 => 説明
val dialog = AlertDialog.Builder(this)
.setMessage(R.string.please_grant_permission)
.setPositiveButton(android.R.string.ok) { _, _ ->
val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
ActivityCompat.requestPermissions(this@MainActivity, permissions, REQ_PERMISSION_ON_CREATE)
}
.create()
dialog.show()
} else {
// permission がない && 説明不要 => request。
val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
ActivityCompat.requestPermissions(this, permissions, REQ_PERMISSION_ON_CREATE)
}
} else {
// permission がある
// rootDir.mkdirs()
}
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>,
grantResults: IntArray) {
if (requestCode == REQ_PERMISSION_ON_CREATE) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED)
finish()
else {
// rootDir.mkdirs()
}
}
}
fun setContextListener() {
onContextSwitchListener = { ctxt ->
curContext.removeOnChangedListener(onContextChangedListener)
curContext = ctxt
curContext.addOnChangedListener(onContextChangedListener)
updateTrackInfo(ctxt)
updateContextName(ctxt)
}
onContextChangedListener = { ctxt ->
updateTrackInfo(ctxt)
}
curContext = playContexts.getCurrent()
curContext.addOnChangedListener(onContextChangedListener)
playContexts.addOnContextSwitchListener(onContextSwitchListener)
updateContextName(curContext)
updateTrackInfo(curContext)
}
fun unsetContextListener() {
playContexts.removeOnContextSwitchListener(onContextSwitchListener)
curContext.removeOnChangedListener(onContextChangedListener)
}
override fun onResume() {
setContextListener()
super.onResume()
}
override fun onPause() {
unsetContextListener()
super.onPause()
}
override fun onDestroy() {
super.onDestroy()
}
private fun updateContextName(ctxt: PlayContext) {
context_name.text = ctxt.name
Log.d("Id=${ctxt.uuid}")
Log.d("name=${ctxt.name}")
}
private fun updateTrackInfo(ctxt: PlayContext) {
val path = ctxt.path
val topDir = ctxt.topDir
val vol1 = ctxt.volume
val pos = ctxt.realtimePos.toInt()
val duration = ctxt.realtimeDuration.toInt()
Log.d("path=${path}")
var p = path
if (p == null)
p = "//"
if (curPath != p) {
curPath = p
playing_filename.rootDir = rootDir.absolutePath
playing_filename.path = p
val meta = Metadata(MFile(p).file.absolutePath)
var title: String? = null
var artist: String? = null
if (meta.extract()) {
title = meta.title
artist = meta.artist
}
if (title == null)
title = resources.getString(R.string.unknown_title)
if (artist == null)
artist = resources.getString(R.string.unknown_artist)
playing_title.text = title
playing_artist.text = artist
}
if (curTopDir != topDir) {
curTopDir = topDir
val dir = curTopDir
playing_filename.topDir = if (dir != null) dir else "//"
}
if (maxPos != duration) {
maxPos = duration
playing_pos.max = maxPos
val sec = maxPos / 1000
val maxTime = String.format(Locale.US, "%d:%02d", sec / 60, sec % 60)
playing_maxtime.text = maxTime
}
if (curPos != pos) {
curPos = pos
playing_pos.progress = curPos
val sec = curPos / 1000
val curTime = String.format(Locale.US, "%d:%02d", sec / 60, sec % 60)
playing_curtime.text = curTime
}
if (vol != vol1) {
vol = vol1
volume.progress = vol - VOLUME_BASE
}
}
companion object {
private val REQ_PERMISSION_ON_CREATE = 1
private val VOLUME_BASE = 50
}
}
|
apache-2.0
|
cb90856c798c833fae186e5a3e434c95
| 32.623729 | 134 | 0.653897 | 4.529224 | false | false | false | false |
hazuki0x0/YuzuBrowser
|
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/debug/FileEditFragment.kt
|
1
|
2657
|
/*
* Copyright 2020 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.debug
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.legacy.databinding.FragmentDebugFileEditBinding
import jp.hazuki.yuzubrowser.legacy.debug.file.FileEditViewModel
import jp.hazuki.yuzubrowser.ui.extensions.applyIconColor
import java.io.File
class FileEditFragment : Fragment() {
private lateinit var binding: FragmentDebugFileEditBinding
private val viewModel by viewModels<FileEditViewModel> {
FileEditViewModel.Factory(requireArguments().getSerializable(ARG_FILE) as File)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentDebugFileEditBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.lifecycleOwner = viewLifecycleOwner
binding.model = viewModel
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.debug_file_edit, menu)
applyIconColor(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.save -> {
viewModel.save()
parentFragmentManager.popBackStack()
true
}
else -> super.onOptionsItemSelected(item)
}
}
companion object {
private const val ARG_FILE = "file"
operator fun invoke(file: File): FileEditFragment {
return FileEditFragment().apply {
arguments = Bundle().apply {
putSerializable(ARG_FILE, file)
}
}
}
}
}
|
apache-2.0
|
892a19b736044322434c161b3e69ea08
| 31.012048 | 87 | 0.683101 | 4.796029 | false | false | false | false |
soywiz/vitaorganizer
|
src/com/soywiz/vitaorganizer/GameListTable.kt
|
2
|
9857
|
package com.soywiz.vitaorganizer
import com.soywiz.util.stream
import com.soywiz.vitaorganizer.ext.getResourceBytes
import com.soywiz.vitaorganizer.ext.getScaledImage
import java.awt.BorderLayout
import java.awt.Font
import java.awt.Point
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.io.ByteArrayInputStream
import javax.imageio.ImageIO
import javax.swing.*
import javax.swing.event.RowSorterEvent
import javax.swing.table.DefaultTableCellRenderer
import javax.swing.table.DefaultTableModel
import javax.swing.table.TableModel
import javax.swing.table.TableRowSorter
open class GameListTable : JPanel(BorderLayout()) {
val model2 = object : DefaultTableModel() {
override fun isCellEditable(row: Int, column: Int): Boolean {
return false
}
}
val table = object : JTable(model2) {
override fun getColumnClass(column: Int): Class<*> {
return getValueAt(0, column).javaClass
}
}
val scrollPanel = JScrollPane(table)
lateinit var sorter: TableRowSorter<TableModel>
var filter = ""
set(value) {
field = value
updateRowFilter(value)
}
get() = field
private fun updateRowFilter(value: String) {
if (value.isNullOrEmpty()) {
sorter.rowFilter = null
} else {
val matcher = Regex("(?i)$value")
sorter.rowFilter = RowFilter.regexFilter("(?i)$value")
sorter.rowFilter = object : RowFilter<TableModel, Any>() {
override fun include(value: Entry<out TableModel, out Any>): Boolean {
//matcher.matches(entry.getStringValue(entry.))
//val model = entry.model
//table.cell
//return true
for (index in 0 until value.valueCount) {
if (index < value.valueCount) {
if (include(value.getValue(index))) return true
}
}
return false
}
private fun include(item: Any): Boolean {
when (item) {
is CachedVpkEntry -> {
for (value in item.psf.values) {
if (matcher.containsMatchIn(value.toString())) return true
}
return false
}
else -> return matcher.containsMatchIn(item.toString())
}
}
}
}
}
fun setSorter() {
sorter = TableRowSorter<TableModel>(model2).apply {
setComparator(5, { a, b -> (a as Comparable<Any>).compareTo((b as Comparable<Any>)) })
//rowFilter = object : RowFilter<TableModel, Any>() {
// override fun include(entry: Entry<out TableModel, out Any>?): Boolean {
// return true
// }
//}
}
sorter.addRowSorterListener { e ->
if (e.type === RowSorterEvent.Type.SORTED) {
// We need to call both revalidate() and repaint()
table.revalidate()
table.repaint()
}
}
table.rowSorter = sorter
}
//val sorter = (rowSorter as DefaultRowSorter<DefaultTableModel, Any?>)
init {
add(scrollPanel, BorderLayout.CENTER)
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ENTER"), "none")
//table.rowSorter
//table.rowSorter = sorter
//sorter.rowFilter = RowFilter.regexFilter(".*foo.*")
//sorter.sortsOnUpdates = true
table.rowHeight = 64
//JTable table = new JTable(myModel);
//table.setRowSorter(sorter);
//table.autoCreateRowSorter = true
//rowSorter.rowFilter = RowFilter.regexFilter<TableModel, Any>("Plant")
/*
rowSorter.rowFilter = object : RowFilter<TableModel, Any>() {
override fun include(entry: Entry<out TableModel, out Any>?): Boolean {
return false
}
}
*/
//table.getColumnModel().getColumn(0).cellRenderer = JTable.IconRenderer()
//(table.model2 as DefaultTableModel).addRow(arrayOf("John", "Doe", "Rowing", 3, true))
table.fillsViewportHeight = true
fun createColumn(text: String): Int {
val id = model2.columnCount
model2.addColumn(text.toString())
//return table.columnModel.getColumn(id)
return id
//return table.getColumn(text.toString())
}
val ID_COLUMN_ICON = createColumn(Texts.format("COLUMN_ICON"))
val ID_COLUMN_ID = createColumn(Texts.format("COLUMN_ID"))
//val ID_COLUMN_WHERE = createColumn(Texts.format("COLUMN_WHERE"))
val ID_COLUMN_TYPE = createColumn(Texts.format("COLUMN_TYPE"))
val ID_COLUMN_VERSION = createColumn(Texts.format("COLUMN_VERSION"))
val ID_COLUMN_PERMISSIONS = createColumn(Texts.format("COLUMN_PERMISSIONS"))
val ID_COLUMN_SIZE = createColumn(Texts.format("COLUMN_SIZE"))
val ID_COLUMN_TITLE = createColumn(Texts.format("COLUMN_TITLE"))
//table.autoResizeMode = JTable.AUTO_RESIZE_OFF
table.autoResizeMode = JTable.AUTO_RESIZE_ALL_COLUMNS
val COLUMN_ICON = table.columnModel.getColumn(ID_COLUMN_ICON)
val COLUMN_ID = table.columnModel.getColumn(ID_COLUMN_ID)
val COLUMN_TYPE = table.columnModel.getColumn(ID_COLUMN_TYPE)
//val COLUMN_WHERE = table.columnModel.getColumn(ID_COLUMN_WHERE)
val COLUMN_VERSION = table.columnModel.getColumn(ID_COLUMN_VERSION)
val COLUMN_PERMISSIONS = table.columnModel.getColumn(ID_COLUMN_PERMISSIONS)
val COLUMN_SIZE = table.columnModel.getColumn(ID_COLUMN_SIZE)
val COLUMN_TITLE = table.columnModel.getColumn(ID_COLUMN_TITLE)
COLUMN_ICON.apply {
//headerValue = Texts2.COLUMN_ICON
minWidth = 64
maxWidth = 64
preferredWidth = 64
resizable = false
}
COLUMN_ID.apply {
minWidth = 96
preferredWidth = 96
resizable = false
cellRenderer = DefaultTableCellRenderer().apply {
horizontalAlignment = JLabel.CENTER;
}
}
COLUMN_TYPE.apply {
minWidth = 80
preferredWidth = 80
resizable = false
cellRenderer = DefaultTableCellRenderer().apply {
horizontalAlignment = JLabel.CENTER;
}
}
//COLUMN_WHERE.apply {
// width = 64
// minWidth = 64
// maxWidth = 64
// preferredWidth = 64
// resizable = false
// cellRenderer = DefaultTableCellRenderer().apply {
// horizontalAlignment = JLabel.CENTER;
// }
//}
COLUMN_VERSION.apply {
minWidth = 64
preferredWidth = 64
resizable = false
cellRenderer = DefaultTableCellRenderer().apply {
horizontalAlignment = JLabel.CENTER;
}
}
COLUMN_PERMISSIONS.apply {
minWidth = 96
preferredWidth = 96
resizable = false
cellRenderer = DefaultTableCellRenderer().apply {
horizontalAlignment = JLabel.CENTER
}
}
COLUMN_SIZE.apply {
minWidth = 96
preferredWidth = 96
resizable = false
cellRenderer = DefaultTableCellRenderer().apply {
horizontalAlignment = JLabel.CENTER
}
}
setSorter()
//table.rowSorter = TableRowSorter<TableModel>(table.model).apply {
// setComparator(COLUMN_SIZE.modelIndex, { a, b -> (a as Comparable<Any>).compareTo((b as Comparable<Any>)) })
//}
COLUMN_TITLE.apply {
width = 512
preferredWidth = 512
//resizable = false
}
table.font = Font(Font.MONOSPACED, Font.PLAIN, VitaOrganizerSettings.tableFontSize)
//table.selectionModel.addListSelectionListener { e -> println(e) };
table.selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
table.columnModel.selectionModel.selectionMode = ListSelectionModel.SINGLE_SELECTION
table.addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_ENTER) {
showMenu()
} else {
super.keyPressed(e)
}
}
})
table.addMouseListener(object : MouseAdapter() {
override fun mouseReleased(e: MouseEvent) {
super.mouseReleased(e)
table.clearSelection()
val row = table.rowAtPoint(Point(e.x, e.y))
if (row < 0 || row > table.rowCount)
return;
try {
table.addRowSelectionInterval(row, row)
showMenu()
} catch (t: Throwable) {
t.printStackTrace()
}
}
})
updateRowFilter(filter)
//filter = "Plant"
}
fun getEntryAtRow(row: Int): CachedVpkEntry = model2.getValueAt(table.convertRowIndexToModel(row), 1) as CachedVpkEntry
val currentEntry: CachedVpkEntry get() = getEntryAtRow(table.selectedRow)
fun showMenuForRow(row: Int) {
val rect = table.getCellRect(row, 1, true)
showMenuAtFor(rect.x, rect.y + rect.height, getEntryAtRow(row))
}
open fun showMenuAtFor(x: Int, y: Int, entry: CachedVpkEntry) {
}
fun showMenu() {
if (table.selectedRow !== -1)
showMenuForRow(table.selectedRow)
}
override fun processKeyEvent(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ENTER -> showMenu()
else -> super.processKeyEvent(e)
}
}
fun setEntries(games: List<CachedVpkEntry>) {
val newRows = arrayListOf<Array<Any>>()
val dummyIcon = getResourceBytes("com/soywiz/vitaorganizer/dummy128.png")
for (entry in games.sortedBy { it.title }) {
try {
val entry2 = entry.entry
val icon = entry2.icon0File
val iconBytes = icon.readBytes()
val image = ImageIO.read(ByteArrayInputStream(when {
iconBytes.isEmpty() -> dummyIcon
else -> iconBytes
}))
val psf = PSF.read(entry2.paramSfoFile.readBytes().stream)
val extendedPermissions = entry.hasExtendedPermissions
val type = entry.type
//if (entry.inVita && entry.inPC) {
// Texts.format("LOCATION_BOTH")
//} else if (entry.inVita) {
// Texts.format("LOCATION_VITA")
//} else if (entry.inPC) {
// Texts.format("LOCATION_PC")
//} else {
// Texts.format("LOCATION_NONE")
//},
//println(psf)
if (image != null) {
newRows.add(arrayOf(
ImageIcon(image.getScaledImage(64, 64)),
entry,
type,
psf["APP_VER"] ?: psf["VERSION"] ?: Texts.format("UNKNOWN_VERSION"),
(if (extendedPermissions) Texts.format("PERMISSIONS_UNSAFE") else Texts.format("PERMISSIONS_SAFE")),
FileSize(entry.size),
entry.title
))
}
} catch (e: Throwable) {
println("Error processing: ${entry.gameId} : ${entry.file}")
e.printStackTrace()
}
}
if (newRows.any()) {
model2.rowCount = 0
for (row in newRows)
model2.addRow(row)
model2.fireTableDataChanged()
}
//sorter.sort()
}
}
|
gpl-3.0
|
8aa5fc7ffe7fb53765e3be8290d1c8d2
| 26.610644 | 120 | 0.687227 | 3.465893 | false | false | false | false |
virvar/magnetic-ball-2
|
MagneticBallLogic/src/main/kotlin/ru/virvar/apps/magneticBall2/levelGenerators/FromFileLevelGenerator.kt
|
1
|
2829
|
package ru.virvar.apps.magneticBall2.levelGenerators
import ru.virvar.apps.magneticBallCore.*
import ru.virvar.apps.magneticBall2.MagneticBallLevel
import java.util.HashMap
import java.io.BufferedReader
import java.io.FileReader
import ru.virvar.apps.magneticBall2.blocks.*
class FromFileLevelGenerator (fileName: String, moveBehavior: IMoveBehavior) : ILevelGenerator {
private val fileName: String
private val moveBehavior: IMoveBehavior
init {
this.fileName = fileName
this.moveBehavior = moveBehavior
}
override fun generate(): Level {
val bReader = BufferedReader(FileReader(fileName))
val lines = bReader.lines().toArray() //.asList<String>()
var lineNumber = 0
val portals = HashMap<Char, PortalBlock>()
val level = MagneticBallLevel((lines[0] as String).length, moveBehavior)
for (line in lines) {
for (i in (line as String).indices) {
val cellValue = line[i]
if (cellValue != '0') {
val block = createBlock(cellValue)
block.x = i
block.y = lineNumber
level.addBlock(block)
if (block is Player) {
level.player = block
} else if (block is PortalBlock) {
val portal = block
if (portals.containsKey(portal.groupId)) {
portal.portalEnd = portals[portal.groupId]
portals[portal.groupId]!!.portalEnd = portal
} else {
portals[portal.groupId] = portal
}
}
}
}
lineNumber++
}
bReader.close()
return level
}
private fun createBlock(blockCode: Char): Block {
val block: Block
when (blockCode) {
'1' ->
block = Player()
'2' ->
block = SquareBlock()
'3' ->
block = TriangleBlock(TriangleBlock.ReflectionDirection.BOTTOM_LEFT)
'4' ->
block = TriangleBlock(TriangleBlock.ReflectionDirection.BOTTOM_RIGHT)
'5' ->
block = TriangleBlock(TriangleBlock.ReflectionDirection.UP_LEFT)
'6' ->
block = TriangleBlock(TriangleBlock.ReflectionDirection.UP_RIGHT)
'7' ->
block = TargetBlock()
'8' -> // TODO: deprecated, destroy
block = PortalBlock('a')
in 'a'..'z' ->
block = PortalBlock(blockCode)
else ->
throw IllegalArgumentException("Incorrect blockCode")
}
return block
}
}
|
gpl-2.0
|
199351d78711ada2e9ff118c5e203e47
| 35.24359 | 96 | 0.525646 | 4.916522 | false | false | false | false |
gradle/gradle
|
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/PluginAwareExtensions.kt
|
3
|
2170
|
/*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.PluginAware
/**
* Applies the given plugin or script.
*
* @param from a script to apply, evaluated as per [Project.file]
* @param plugin a id of the plugin to apply
* @param to the plugin target object or collection of objects, target is self when null
* @see [PluginAware.apply]
*/
fun PluginAware.apply(from: Any? = null, plugin: String? = null, to: Any? = null) {
require(from != null || plugin != null) { "At least one of 'from' or 'plugin' must be given." }
apply {
if (plugin != null) this.plugin(plugin)
if (from != null) this.from(from)
if (to != null) this.to(to)
}
}
/**
* Applies the plugin of the given type [T]. Does nothing if the plugin has already been applied.
*
* The given class should implement the [Plugin] interface.
*
* @param T the plugin type.
* @see [PluginAware.apply]
*/
inline fun <reified T : Plugin<*>> PluginAware.apply() {
apply {
plugin(T::class.java)
}
}
/**
* Applies the plugin of the given type [T] to the specified object. Does nothing if the plugin has already been applied.
*
* The given class should implement the [Plugin] interface.
*
* @param T the plugin type.
* @param targets the plugin target objects or collections of objects
* @see [PluginAware.apply]
*/
inline fun <reified T : Plugin<*>> PluginAware.applyTo(vararg targets: Any) {
apply {
plugin(T::class.java)
to(*targets)
}
}
|
apache-2.0
|
b3f5101c4d093307c7bb736eeab3bb1e
| 30 | 121 | 0.685253 | 3.741379 | false | false | false | false |
NephyProject/Penicillin
|
src/main/kotlin/jp/nephy/penicillin/extensions/models/builder/CustomStatusBuilder.kt
|
1
|
6700
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
@file:Suppress("UNUSED")
package jp.nephy.penicillin.extensions.models.builder
import jp.nephy.jsonkt.*
import jp.nephy.penicillin.core.experimental.PenicillinExperimentalApi
import jp.nephy.penicillin.extensions.parseModel
import jp.nephy.penicillin.models.Status
import kotlinx.atomicfu.atomic
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
import java.util.*
import kotlin.collections.set
/**
* Custom payload builder for [Status].
*/
class CustomStatusBuilder: JsonBuilder<Status>, JsonMap by jsonMapOf(
"created_at" to null,
"id" to null,
"id_str" to null,
"text" to "",
"source" to null,
"truncated" to false,
"in_reply_to_status_id" to null,
"in_reply_to_status_id_str" to null,
"in_reply_to_user_id" to null,
"in_reply_to_user_id_str" to null,
"in_reply_to_screen_name" to null,
"user" to null,
"geo" to null,
"coordinates" to null,
"place" to null,
"contributors" to null,
"is_quote_status" to false,
"quote_count" to 0,
"reply_count" to 0,
"retweet_count" to 0,
"favorite_count" to 0,
"entities" to jsonObjectOf(
"hashtags" to jsonArrayOf(), "symbols" to jsonArrayOf(), "user_mentions" to jsonArrayOf(), "urls" to jsonArrayOf()
),
"favorited" to false,
"retweeted" to false,
"filter_level" to "low",
"lang" to "ja",
"timestamp_ms" to null
) {
private lateinit var text: String
/**
* Sets text.
*/
fun text(value: String) {
text = value
}
/**
* Sets text.
*/
fun text(operation: () -> Any?) {
text = operation.invoke().toString()
}
/**
* Sets text with builder.
*/
fun textBuilder(builder: StringBuilder.() -> Unit) {
text = buildString(builder)
}
private var sourceName = "Tweetstorm"
private var sourceUrl = "https://github.com/SlashNephy/Tweetstorm"
/**
* Sets source.
*/
fun source(name: String, url: String) {
sourceName = name
sourceUrl = url
}
private var createdAt: TemporalAccessor? = null
/**
* Sets created_at.
*/
fun createdAt(time: TemporalAccessor? = null) {
createdAt = time
}
private var user = CustomUserBuilder()
/**
* Sets user.
*/
fun user(builder: CustomUserBuilder.() -> Unit) {
user.apply(builder)
}
private var inReplyToStatusId: Long? = null
private var inReplyToUserId: Long? = null
private var inReplyToScreenName: String? = null
/**
* Sets in_reply_to.
*/
fun inReplyTo(statusId: Long, userId: Long, screenName: String) {
inReplyToStatusId = statusId
inReplyToUserId = userId
inReplyToScreenName = screenName
}
private var retweeted = false
/**
* Sets retweeted.
*/
fun alreadyRetweeted() {
retweeted = true
}
private var favorited = false
/**
* Sets favorited.
*/
fun alreadyFavorited() {
favorited = true
}
private var retweetCount = 0
private var favoriteCount = 0
/**
* Sets count.
*/
fun count(retweet: Int = 0, favorite: Int = 0) {
retweetCount = retweet
favoriteCount = favorite
}
private data class UrlEntity(val url: String, val start: Int, val end: Int)
private val urls = mutableListOf<UrlEntity>()
/**
* Sets url.
*/
fun url(url: String, start: Int, end: Int) {
urls += UrlEntity(url, start, end)
}
@UseExperimental(PenicillinExperimentalApi::class)
override fun build(): Status {
val id = generateId()
val user = user.build()
this["text"] = text
this["id"] = id
this["id_str"] = id.toString()
this["source"] = "<a href=\"$sourceUrl\" rel=\"nofollow\">$sourceName</a>"
this["user"] = user
this["created_at"] = createdAt.toCreatedAt()
this["timestamp_ms"] = (Instant.from(createdAt) ?: Instant.now()).toEpochMilli().toString()
this["retweeted"] = retweeted
this["favorited"] = favorited
this["retweet_count"] = retweetCount
this["favorite_count"] = favoriteCount
this["in_reply_to_status_id"] = inReplyToStatusId
this["in_reply_to_status_id_str"] = inReplyToStatusId.toString()
this["in_reply_to_user_id"] = inReplyToUserId
this["in_reply_to_user_id_str"] = inReplyToUserId.toString()
this["in_reply_to_screen_name"] = inReplyToScreenName
val entities = this["entities"].asJsonElement().jsonObject
this["entities"] = entities.edit { entity ->
entity["urls"] = urls.map { urlEntity ->
jsonObjectOf(
"display_url" to urlEntity.url.removePrefix("https://").removePrefix("http://"),
"url" to urlEntity.url,
"indices" to jsonArrayOf(urlEntity.start, urlEntity.end),
"expanded_url" to urlEntity.url
)
}
}
return toJsonObject().parseModel()
}
}
internal fun TemporalAccessor?.toCreatedAt(): String {
val dateFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH).withZone(ZoneId.of("UTC"))
return dateFormatter.format(this ?: Instant.now())
}
private var id = atomic(100000001L)
internal fun generateId(): Long {
return id.also {
id.plusAssign(2)
}.value
}
|
mit
|
cccdde19b127cd3aaff4cd9a9b38f0da
| 28.646018 | 128 | 0.631343 | 4.068002 | false | false | false | false |
gradle/gradle
|
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/problems/ConfigurationCacheProblemsSummary.kt
|
3
|
6543
|
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.problems
import com.google.common.collect.Ordering
import io.usethesource.capsule.Set
import org.gradle.api.Task
import org.gradle.api.internal.DocumentationRegistry
import org.gradle.configurationcache.extensions.capitalized
import org.gradle.internal.logging.ConsoleRenderer
import java.io.File
import java.util.Comparator.comparing
import java.util.concurrent.atomic.AtomicReference
private
const val maxReportedProblems = 4096
private
const val maxConsoleProblems = 15
private
const val maxCauses = 5
internal
enum class ProblemSeverity {
Warn,
Failure,
/**
* A problem produced by a task marked as [notCompatibleWithConfigurationCache][Task.notCompatibleWithConfigurationCache].
*/
Suppressed
}
internal
class ConfigurationCacheProblemsSummary {
private
val summary = AtomicReference(Summary.empty)
fun get(): Summary =
summary.get()
fun onProblem(problem: PropertyProblem, severity: ProblemSeverity): Boolean =
summary
.updateAndGet { it.insert(problem, severity) }
.overflowed.not()
}
internal
class Summary private constructor(
/**
* Total of all problems, regardless of severity.
*/
val problemCount: Int,
/**
* Total number of problems that are failures.
*/
val failureCount: Int,
/**
* Total number of [suppressed][ProblemSeverity.Suppressed] problems.
*/
val suppressedCount: Int,
private
val uniqueProblems: Set.Immutable<UniquePropertyProblem>,
val causes: List<Throwable>,
val overflowed: Boolean
) {
companion object {
val empty = Summary(
problemCount = 0,
failureCount = 0,
suppressedCount = 0,
uniqueProblems = Set.Immutable.of(),
causes = emptyList(),
overflowed = false
)
}
val nonSuppressedProblemCount: Int
get() = problemCount - suppressedCount
fun insert(problem: PropertyProblem, severity: ProblemSeverity): Summary {
val newProblemCount = problemCount + 1
val newFailureCount = if (severity == ProblemSeverity.Failure) failureCount + 1 else failureCount
val newSuppressedCount = if (severity == ProblemSeverity.Suppressed) suppressedCount + 1 else suppressedCount
if (overflowed || newProblemCount > maxReportedProblems) {
return Summary(
newProblemCount,
newFailureCount,
newSuppressedCount,
uniqueProblems,
causes,
true
)
}
val uniqueProblem = UniquePropertyProblem.of(problem)
val newUniqueProblems = uniqueProblems.__insert(uniqueProblem)
val newCauses = problem
.takeIf { newUniqueProblems !== uniqueProblems && causes.size < maxCauses }
?.exception?.let { causes + it }
?: causes
return Summary(
newProblemCount,
newFailureCount,
newSuppressedCount,
newUniqueProblems,
newCauses,
false
)
}
fun textForConsole(cacheActionText: String, htmlReportFile: File): String {
val documentationRegistry = DocumentationRegistry()
val uniqueProblemCount = uniqueProblems.size
return StringBuilder().apply {
appendLine()
appendSummaryHeader(cacheActionText, problemCount, uniqueProblemCount)
appendLine()
Ordering.from(consoleComparator()).leastOf(uniqueProblems, maxConsoleProblems).forEach { problem ->
append("- ")
append(problem.userCodeLocation.capitalized())
append(": ")
appendLine(problem.message)
problem.documentationSection?.let<String, Unit> {
appendLine(" See ${documentationRegistry.getDocumentationFor("configuration_cache", it)}")
}
}
if (uniqueProblemCount > maxConsoleProblems) {
appendLine("plus ${uniqueProblemCount - maxConsoleProblems} more problems. Please see the report for details.")
}
appendLine()
append(buildSummaryReportLink(htmlReportFile))
}.toString()
}
private
fun StringBuilder.appendSummaryHeader(
cacheAction: String,
totalProblemCount: Int,
uniqueProblemCount: Int
) {
append(totalProblemCount)
append(if (totalProblemCount == 1) " problem was found " else " problems were found ")
append(cacheAction)
append(" the configuration cache")
if (overflowed) {
append(", only the first ")
append(maxReportedProblems)
append(" were considered")
}
if (totalProblemCount != uniqueProblemCount) {
append(", ")
append(uniqueProblemCount)
append(" of which ")
append(if (uniqueProblemCount == 1) "seems unique" else "seem unique")
}
append(".")
}
private
fun buildSummaryReportLink(reportFile: File) =
"See the complete report at ${clickableUrlFor(reportFile)}"
private
fun clickableUrlFor(file: File) =
ConsoleRenderer().asClickableFileUrl(file)
}
private
fun consoleComparator() =
comparing { p: UniquePropertyProblem -> p.userCodeLocation }
.thenComparing { p: UniquePropertyProblem -> p.message }
private
data class UniquePropertyProblem(
val userCodeLocation: String,
val message: String,
val documentationSection: String?
) {
companion object {
fun of(problem: PropertyProblem) = problem.run {
UniquePropertyProblem(
trace.containingUserCode,
message.toString(),
documentationSection?.anchor
)
}
}
}
|
apache-2.0
|
d2a7ffefe34dd01dd60c6705d03bd3bb
| 29.152074 | 127 | 0.640838 | 4.975665 | false | false | false | false |
Team-SOFTsk/ObservableAdapter
|
app/src/main/java/sk/teamsoft/observableadapterdemo/simple/Data.kt
|
1
|
425
|
package sk.teamsoft.observableadapterdemo.simple
import androidx.annotation.NonNull
import sk.teamsoft.observablecollection.DiffResolver
/**
* @author Dusan Bartos
*/
data class Data(var label: String, var detail: String) : DiffResolver<Data> {
override fun equalsItem(@NonNull other: Data): Boolean = label == other.label
override fun areContentsTheSame(@NonNull other: Data): Boolean = detail == other.detail
}
|
apache-2.0
|
bd307b1372c14c4263a00bec5360d9ac
| 31.769231 | 91 | 0.767059 | 4.086538 | false | false | false | false |
McGars/Zoomimage
|
app/src/main/java/zoom/mcgars/com/zoom/MainActivity.kt
|
1
|
5301
|
package zoom.mcgars.com.zoom
import android.content.Context
import android.graphics.Bitmap
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache
import com.nostra13.universalimageloader.core.DisplayImageOptions
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener
import mcgars.com.zoomimage.ZoomImageController
import mcgars.com.zoomimage.adapter.ZoomViewHolder
import mcgars.com.zoomimage.fabric.AnimatorBuilder
import mcgars.com.zoomimage.model.IPhoto
import mcgars.com.zoomimage.model.Photo
import mcgars.com.zoomimage.ui.Displayer
import mcgars.com.zoomimage.ui.UiContainer
class MainActivity : AppCompatActivity(), View.OnClickListener {
private lateinit var zoomImageController: ZoomImageController
private val urlImages = listOf<IPhoto>(
Photo(
"http://images4.fanpop.com/image/photos/23100000/-Nature-god-the-creator-23175770-670-446.jpg",
"http://fantasyartdesign.com/free-wallpapers/imgs/mid/decktop-Dino-game-m.jpg"
),
Photo(
"http://fantasyartdesign.com/free-wallpapers/imgs/mid/decktop-Dino-game-m.jpg",
"http://images4.fanpop.com/image/photos/18200000/Lovely-nature-god-the-creator-18227423-500-333.jpg"
),
Photo(
"http://images4.fanpop.com/image/photos/18200000/Lovely-nature-god-the-creator-18227423-500-333.jpg",
"http://images4.fanpop.com/image/photos/18200000/Lovely-nature-god-the-creator-18227423-500-333.jpg"
)
)
private var views = mutableListOf<ImageView>()
private val container: ViewGroup by lazy { findViewById<ViewGroup>(R.id.container) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
zoomImageController = ZoomImageController(UiContainer(findViewById(R.id.rootView)), object : Displayer {
// load fullscreen image
override fun displayImage(photo: IPhoto?, v: ZoomViewHolder) {
displayImg(photo ?: return, v)
}
override fun cancel(imageView: ImageView) {
ImageLoader.getInstance().cancelDisplayTask(imageView)
}
})
initImageLoader(this)
fitImages()
// ImageLoader.getInstance().displayImage("https://graceologydotcom.files.wordpress.com/2014/04/perma-glory.jpg", ivTest);
}
private fun fitImages() {
views.add(findViewById<View>(R.id.ivTest) as ImageView)
views.add(findViewById<View>(R.id.ivTest2) as ImageView)
views.add(findViewById<View>(R.id.ivTest3) as ImageView)
views.forEachIndexed { index, imageView ->
imageView.setOnClickListener(this)
ImageLoader.getInstance().displayImage(urlImages[index].preview, imageView)
}
}
override fun onClick(v: View) {
val position = container.indexOfChild(v)
zoomImageController.setPhotos(AnimatorBuilder.from(views), urlImages)
zoomImageController.show(position)
}
override fun onBackPressed() {
if (zoomImageController.onBackPressed())
return
super.onBackPressed()
}
override fun onDestroy() {
super.onDestroy()
zoomImageController.onDestroy()
}
/**
* Display
* @param photo
* @param v
*/
private fun displayImg(photo: IPhoto, v: ZoomViewHolder) {
ImageLoader.getInstance().displayImage(photo.original, v.image, object : SimpleImageLoadingListener() {
override fun onLoadingStarted(imageUri: String?, view: View?) {
}
override fun onLoadingComplete(imageUri: String?, view: View?, loadedImage: Bitmap?) {
// v.loadComplete()
}
})
}
companion object {
/**
* Init loader images
* @param c
* @return
*/
fun initImageLoader(c: Context): ImageLoader {
if (ImageLoader.getInstance().isInited)
return ImageLoader.getInstance()
val config = ImageLoaderConfiguration.Builder(c)
.defaultDisplayImageOptions(imageLoaderOptions)
.diskCacheSize(50 * 1024 * 1024)
.diskCacheFileCount(100)
.memoryCache(UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // 2 Mb
.build()
ImageLoader.getInstance().init(config)
return ImageLoader.getInstance()
}
val imageLoaderOptions: DisplayImageOptions
get() = imageLoaderOptionsBuilder.build()
val imageLoaderOptionsBuilder: DisplayImageOptions.Builder
get() = DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.resetViewBeforeLoading(false)
}
}
|
apache-2.0
|
875b4c722e589f728fceccda414e42f5
| 34.577181 | 137 | 0.654971 | 4.450882 | false | false | false | false |
FWDekker/intellij-randomness
|
src/test/kotlin/com/fwdekker/randomness/ActionToolbarHelper.kt
|
1
|
1011
|
package com.fwdekker.randomness
import com.intellij.openapi.actionSystem.impl.ActionButton
import com.intellij.ui.AnActionButton
import org.assertj.swing.fixture.FrameFixture
/**
* Returns the `ActionButton` that has [accessibleName].
*
* @param accessibleName the name of the button to return
*/
fun FrameFixture.getActionButton(accessibleName: String) =
robot().finder()
.find(matcher(ActionButton::class.java) { it.isValid && it.accessibleContext.accessibleName == accessibleName })
/**
* Returns the `AnActionButton` in the `ActionButton` that has [accessibleName].
*
* @param accessibleName the name of the button action to return
*/
fun FrameFixture.getAnActionButton(accessibleName: String) =
getActionButton(accessibleName).action as AnActionButton
/**
* Clicks the `ActionButton` that has [accessibleName].
*
* @param accessibleName the name of the button to click
*/
fun FrameFixture.clickActionButton(accessibleName: String) = getActionButton(accessibleName).click()
|
mit
|
c481797d8d306b5dc893a23dd2f16e86
| 32.7 | 120 | 0.769535 | 4.453744 | false | false | false | false |
carmenlau/chat-SDK-Android
|
chat/src/main/java/io/skygear/plugins/chat/ui/ImagePreviewActivity.kt
|
1
|
1522
|
package io.skygear.plugins.chat.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import com.squareup.picasso.Picasso
import io.skygear.plugins.chat.R
class ImagePreviewActivity : AppCompatActivity() {
companion object {
val ImageURLIntentKey = "IMAGE_URL"
fun newIntent(context: Context, imageURL: String): Intent {
val intent = Intent(context, ImagePreviewActivity::class.java)
intent.putExtra(ImageURLIntentKey, imageURL)
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_preview)
setTitle("")
val photoView = findViewById<ImageView>(R.id.iv_photo)
var url = intent.getStringExtra(ImageURLIntentKey)
Picasso.with(this)
.load(url)
.into(photoView)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.image_preview, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.close -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
|
apache-2.0
|
0adfe6590d7fc18c0dbf9975a65743b6
| 26.178571 | 74 | 0.652431 | 4.640244 | false | false | false | false |
zhengjiong/ZJ_KotlinStudy
|
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/35.HelloKotlin-object(总结).kt
|
1
|
6541
|
package com.zj.example.kotlin.shengshiyuan.helloworld
/**
*
* CreateTime: 18/3/8 10:22
* @author 郑炯
*/
/*
1. object 可以作为变量的定义也可以是表达式
2. object 匿名类可以继承并超越 Java 中匿名类而实现多个接口
3. object 表达式当场实例化,但定义的 object 变量是延迟实例化的
4. object 和 companion object 都可以为其取名也可以隐姓埋名
5. object 匿名内部类甚至可以引用并更改局部变量
6. companion object 甚至还可以被扩展
*/
/*
1. OBJECT基本定义
object 可以轻松实现 Kotlin 单例模式, 它可以定义在全局之中,也可以定义在类的内部。但是要注意几点:
(1).object用做对象表达式, 定义后即刻实例化,
(2).因此 object 不能有定义构造函数
(3).定义在类内部的 object 并不能访问类的成员
(4).对象声明是延迟初始化的,在首次访问的时候实例化
*/
class OutClass2 {
val outParam = "outParam"
//对象声明: 单例InnerObject1
object InnerObject1 {
val innerParam = "innerParam"
fun innerFun() {
//println(outParam) //error,(3).定义在类内部的 object 并不能访问类的成员
}
}
//对象表达式: 可以访问类的成员变量
val a = object: Any() {
fun print() {
println(outParam) //success,(3).定义在类内部的 对象表达式 可以访问类的成员
}
}
companion object {
@JvmStatic
fun innerFun() {
//println(outParam) //error,(3).定义在类内部的 object 并不能访问类的成员
}
}
}
/*
2. OBJECT作为表达式
在 Android 开发中,我们经常会设置一个接口匿名类作为点击事件的参数: setOnClickListener(View.OnClickListener) ,
这个时候在 Kotlin 中就可以使用 object 来表达那些匿名内部类。同时 object 相比 Java 更加强大,在用其表达内部类的时候有这几个注意点:
(1).object 继承父类必须立刻传递父类构造参数
(2).object 匿名类可以同时实现多个接口
(3).object 匿名类作为参数并没有名字定义,但是可以为其定义一个变量名,如果实现多接口不能直接用类型推断,拗口吧,请看下面代码:
*/
class OutClass3 {
interface MyInterface1
interface MyInterface2
open class MySuperClass(parameter: String)
//对象声明
object AnonymousSubClass : MySuperClass("abc"), MyInterface1, MyInterface2 {
//do something...
}
val anonymousClass = AnonymousSubClass
//对象声明
object AnonymousClass : MyInterface1, MyInterface2 {
}
//对象表达式, 将实例化的匿名类赋值给anotherAnonymous
val anotherAnonymous = object : MyInterface1 {
}
//对象表达式, 将实例化的匿名类赋值给againAnonymous
val againAnonymous: MyInterface1 = object : MyInterface1, MyInterface2 {
}
}
/*
3. OBJECT可以访问非FINAL局部变量
我们知道在 Java 中,内部类是不可以访问外部的非 final 成员变量的,也就是
说:它不允许更改变量值!但是, Kotlin 的 object 可以。看代码:
*/
class OutClass4 {
interface MyInterface {
fun operateVariable()
}
interface MyInterface1
class MyClass {
fun operationWithInterface(anonymous: MyInterface) {
anonymous.operateVariable()
}
init {
var localVariable = 1
this.operationWithInterface(object : MyInterface, MyInterface1 {
override fun operateVariable() {
//object中可以访问外部类的变量, 而且还可以修改该变量的值, 和java完全不同
localVariable++
}
})
//输出:localVariable = 2
println("localVariable = $localVariable")
}
}
}
/*
4. COMPANION OBJECT使用方法
和 object 不同, companion object 的定义完全属于类的本身,所以 companion object 肯定是不能
脱离类而定义在全局之中。它就像 Java 里的 static 变量,所以我们定义 companion object 变量的时候也一般会使用大写的命名方式。
同时,和 object 类似,可以给 companion object 命名,也可以不给名字,这个时候它会有个默认的名字:
Companion ,而且,它只在类里面能定义一次:
*/
class OutClass5 {
companion object CompanionName {
@JvmField
val PARAMS = "params"
@JvmStatic
fun newInstance() = OutClass5()
}
fun test1() {
//输出: true
println(OutClass5.CompanionName.PARAMS == OutClass5.PARAMS)
}
}
class OutClass6 {
companion object {
@JvmField
val PARAMS = "params"
}
fun test1() {
//输出: true
println(OutClass6.Companion.PARAMS == OutClass6.PARAMS)
}
}
/*
5. 类名可作为接口参数传入
和 object 还是一样, companion object 也可以实现接口,因为 companion object 寄
生于类,甚至类还可以直接作为实现了相应得接口的参数形式传入,拗口,看代码:
*/
class OutClass7 {
interface MyInterface {
fun operateVariable()
}
fun operateClass(interfaceObject: MyInterface) {
interfaceObject.operateVariable()
}
class InnerClass {
companion object : MyInterface {
override fun operateVariable() {
println("operateVariable")
}
}
}
fun test1() {
//下面两种写法都可以
operateClass(InnerClass.Companion)
operateClass(InnerClass)
}
}
/*
6. 扩展类的静态成员
Kotlin 的扩展功能非常强大,是程序猿爱不释口且口口相传的实用特性之一。那么我们怎么扩展类的静
态成员呢?这个时候当然是 companion object 派上用场的时刻了!
*/
class OutClass8 {
companion object {
const val INNER_PARAMETER = "param"
}
}
fun main(args: Array<String>) {
//给OutClass8中的Companion扩展一个方法
fun OutClass8.Companion.operateVariable(){
println("OutClass8 operateVariable")
}
//调用扩展方法
OutClass8.Companion.operateVariable()
}
|
mit
|
34717a030cba50a8047e98fa39345a64
| 20.8 | 89 | 0.619604 | 3.275273 | false | false | false | false |
coil-kt/coil
|
coil-base/src/test/java/coil/memory/WeakMemoryCacheTest.kt
|
1
|
6472
|
package coil.memory
import android.content.Context
import android.graphics.Bitmap
import androidx.test.core.app.ApplicationProvider
import coil.memory.MemoryCache.Key
import coil.util.allocationByteCountCompat
import coil.util.createBitmap
import coil.util.forEachIndices
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21, 28])
class WeakMemoryCacheTest {
private lateinit var context: Context
private lateinit var weakMemoryCache: RealWeakMemoryCache
private lateinit var references: MutableSet<Any>
@Before
fun before() {
context = ApplicationProvider.getApplicationContext()
weakMemoryCache = RealWeakMemoryCache()
references = mutableSetOf()
}
@Test
fun `can retrieve cached value`() {
val key = Key("key")
val bitmap = reference(createBitmap())
val extras = mapOf("test" to 4)
val size = bitmap.allocationByteCountCompat
weakMemoryCache.set(key, bitmap, extras, size)
val value = weakMemoryCache.get(key)
assertNotNull(value)
assertEquals(bitmap, value.bitmap)
assertEquals(extras, value.extras)
}
@Test
fun `can hold multiple values`() {
val bitmap1 = reference(createBitmap())
weakMemoryCache.set(Key("key1"), bitmap1, emptyMap(), 100)
val bitmap2 = reference(createBitmap())
weakMemoryCache.set(Key("key2"), bitmap2, emptyMap(), 100)
val bitmap3 = reference(createBitmap())
weakMemoryCache.set(Key("key3"), bitmap3, emptyMap(), 100)
assertEquals(bitmap1, weakMemoryCache.get(Key("key1"))?.bitmap)
assertEquals(bitmap2, weakMemoryCache.get(Key("key2"))?.bitmap)
assertEquals(bitmap3, weakMemoryCache.get(Key("key3"))?.bitmap)
weakMemoryCache.clear(bitmap2)
assertEquals(bitmap1, weakMemoryCache.get(Key("key1"))?.bitmap)
assertNull(weakMemoryCache.get(Key("key2")))
assertEquals(bitmap3, weakMemoryCache.get(Key("key3"))?.bitmap)
}
@Test
fun `empty references are removed from cache`() {
val key = Key("key")
val bitmap = reference(createBitmap())
weakMemoryCache.set(key, bitmap, emptyMap(), 100)
weakMemoryCache.clear(bitmap)
assertNull(weakMemoryCache.get(key))
}
@Test
fun `bitmaps with same key are retrieved by size descending`() {
val bitmap1 = reference(createBitmap())
val bitmap2 = reference(createBitmap())
val bitmap3 = reference(createBitmap())
val bitmap4 = reference(createBitmap())
val bitmap5 = reference(createBitmap())
val bitmap6 = reference(createBitmap())
val bitmap7 = reference(createBitmap())
val bitmap8 = reference(createBitmap())
weakMemoryCache.set(Key("key"), bitmap1, emptyMap(), 1)
weakMemoryCache.set(Key("key"), bitmap3, emptyMap(), 3)
weakMemoryCache.set(Key("key"), bitmap5, emptyMap(), 5)
weakMemoryCache.set(Key("key"), bitmap7, emptyMap(), 7)
weakMemoryCache.set(Key("key"), bitmap8, emptyMap(), 8)
weakMemoryCache.set(Key("key"), bitmap4, emptyMap(), 4)
weakMemoryCache.set(Key("key"), bitmap6, emptyMap(), 6)
weakMemoryCache.set(Key("key"), bitmap2, emptyMap(), 2)
assertEquals(bitmap8, weakMemoryCache.get(Key("key"))?.bitmap)
weakMemoryCache.clear(bitmap8)
assertEquals(bitmap7, weakMemoryCache.get(Key("key"))?.bitmap)
weakMemoryCache.clear(bitmap7)
assertEquals(bitmap6, weakMemoryCache.get(Key("key"))?.bitmap)
weakMemoryCache.clear(bitmap6)
assertEquals(bitmap5, weakMemoryCache.get(Key("key"))?.bitmap)
weakMemoryCache.clear(bitmap5)
assertEquals(bitmap4, weakMemoryCache.get(Key("key"))?.bitmap)
weakMemoryCache.clear(bitmap4)
assertEquals(bitmap3, weakMemoryCache.get(Key("key"))?.bitmap)
weakMemoryCache.clear(bitmap3)
assertEquals(bitmap2, weakMemoryCache.get(Key("key"))?.bitmap)
weakMemoryCache.clear(bitmap2)
assertEquals(bitmap1, weakMemoryCache.get(Key("key"))?.bitmap)
weakMemoryCache.clear(bitmap1)
// All the values are invalidated.
assertNull(weakMemoryCache.get(Key("key")))
}
@Test
fun `cleanUp clears all collected values`() {
val bitmap1 = reference(createBitmap())
weakMemoryCache.set(Key("key1"), bitmap1, emptyMap(), 100)
val bitmap2 = reference(createBitmap())
weakMemoryCache.set(Key("key2"), bitmap2, emptyMap(), 100)
val bitmap3 = reference(createBitmap())
weakMemoryCache.set(Key("key3"), bitmap3, emptyMap(), 100)
weakMemoryCache.clear(bitmap1)
assertNull(weakMemoryCache.get(Key("key1")))
weakMemoryCache.clear(bitmap3)
assertNull(weakMemoryCache.get(Key("key3")))
assertEquals(3, weakMemoryCache.keys.size)
weakMemoryCache.cleanUp()
assertEquals(1, weakMemoryCache.keys.size)
assertNull(weakMemoryCache.get(Key("key1")))
assertEquals(bitmap2, weakMemoryCache.get(Key("key2"))?.bitmap)
assertNull(weakMemoryCache.get(Key("key3")))
}
@Test
fun `value is removed after invalidate is called`() {
val key = Key("1")
val bitmap = createBitmap()
weakMemoryCache.set(key, bitmap, emptyMap(), bitmap.allocationByteCountCompat)
weakMemoryCache.remove(key)
assertNull(weakMemoryCache.get(key))
}
/**
* Clears [bitmap]'s weak reference without removing its entry from
* [RealWeakMemoryCache.cache]. This simulates garbage collection.
*/
private fun RealWeakMemoryCache.clear(bitmap: Bitmap) {
cache.values.forEach { values ->
values.forEachIndices { value ->
if (value.bitmap.get() === bitmap) {
value.bitmap.clear()
return
}
}
}
}
/**
* Hold a strong reference to the value for the duration of the test
* to prevent it from being garbage collected.
*/
private fun <T : Any> reference(value: T): T {
references += value
return value
}
}
|
apache-2.0
|
c3c7e51a0587f5f28d3b1683293e4c27
| 32.884817 | 86 | 0.658529 | 4.580326 | false | true | false | false |
sugarmanz/Pandroid
|
app/src/main/java/com/jeremiahzucker/pandroid/ui/station/StationListFragment.kt
|
1
|
5699
|
package com.jeremiahzucker.pandroid.ui.station
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.jeremiahzucker.pandroid.R
import com.jeremiahzucker.pandroid.request.json.v5.model.ExpandedStationModel
import com.jeremiahzucker.pandroid.ui.main.MainActivity
import kotlinx.android.synthetic.main.fragment_station_list.*
/**
* A fragment representing a list of Items.
*
*
* Activities containing this fragment MUST implement the [OnListFragmentInteractionListener]
* interface.
*/
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
class StationListFragment : Fragment(), StationListContract.View {
private val TAG: String = StationListFragment::class.java.simpleName
private var presenter: StationListContract.Presenter = StationListPresenter() // TODO: Inject
// TODO: Customize parameters
private var mColumnCount = 1
private var mListener: OnListFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mColumnCount = arguments?.getInt(ARG_COLUMN_COUNT) ?: 1
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater!!.inflate(R.layout.fragment_station_list, container, false)
// presenter.getStationList()
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnListFragmentInteractionListener) {
mListener = context
} else {
throw RuntimeException("$context must implement OnListFragmentInteractionListener")
}
}
override fun onResume() {
super.onResume()
presenter.attach(this)
// TODO: Check station list checksum here!
}
override fun onDetach() {
super.onDetach()
mListener = null
}
/**
* Shows the progress UI and hides the login form.
*/
override fun showProgress(show: Boolean) {
val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime).toLong()
recycler_view_station_list.visibility = if (show) View.GONE else View.VISIBLE
recycler_view_station_list.animate()
.setDuration(shortAnimTime)
.alpha((if (show) 0 else 1).toFloat())
.setListener(
object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
recycler_view_station_list.visibility = if (show) View.GONE else View.VISIBLE
}
}
)
progress_bar_station_list.visibility = if (show) View.VISIBLE else View.GONE
progress_bar_station_list.animate()
.setDuration(shortAnimTime)
.alpha((if (show) 1 else 0).toFloat())
.setListener(
object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
progress_bar_station_list.visibility = if (show) View.VISIBLE else View.GONE
}
}
)
if (recycler_view_station_list.visibility == View.VISIBLE)
setupRecyclerView() // TODO: Pretty dumb way to handle it (Should improve soon)
}
override fun updateStationList(stations: List<ExpandedStationModel>) {
Log.i(TAG, stations.toString())
(recycler_view_station_list.adapter as StationListAdapter).updateStationList(stations)
}
private fun setupRecyclerView() {
val context = recycler_view_station_list.context
if (mColumnCount <= 1) {
recycler_view_station_list.layoutManager = LinearLayoutManager(context)
} else {
recycler_view_station_list.layoutManager = GridLayoutManager(context, mColumnCount)
}
// TODO: Setup local persistence and initially load from local storage
recycler_view_station_list.adapter = StationListAdapter(context, listOf(), mListener)
}
override fun showAuth() {
(activity as MainActivity).showAuth()
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) for more information.
*/
interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
fun onListFragmentInteraction(item: ExpandedStationModel)
}
companion object {
// TODO: Customize parameter argument names
private val ARG_COLUMN_COUNT = "column-count"
// TODO: Customize parameter initialization
fun newInstance(columnCount: Int): StationListFragment {
val fragment = StationListFragment()
val args = Bundle()
args.putInt(ARG_COLUMN_COUNT, columnCount)
fragment.arguments = args
return fragment
}
}
}
|
mit
|
a2ec7d9c2515c3b20629f15daac06e0d
| 34.842767 | 172 | 0.671521 | 5.007909 | false | false | false | false |
tmurakami/mockito4k
|
src/main/kotlin/com/github/tmurakami/mockito4k/AdditionalMatchers.kt
|
1
|
2852
|
@file:Suppress("NOTHING_TO_INLINE")
package com.github.tmurakami.mockito4k
import org.mockito.AdditionalMatchers
/**
* The delegation to [AdditionalMatchers.and].
*/
inline fun <reified T> and(first: T?, second: T?): T = AdditionalMatchers.and(first, second) ?: first ?: by(second)
/**
* The delegation to [AdditionalMatchers.or].
*/
inline fun <reified T> or(first: T?, second: T?): T = AdditionalMatchers.or(first, second) ?: first ?: by(second)
/**
* The delegation to [AdditionalMatchers.not].
*/
inline fun <reified T> not(matcher: T?): T = AdditionalMatchers.not(matcher) ?: by(matcher)
/**
* The delegation to [AdditionalMatchers.geq].
*/
inline fun <reified T : Comparable<T>> geq(value: T): T = AdditionalMatchers.geq(value) ?: value
/**
* The delegation to [AdditionalMatchers.gt].
*/
inline fun <reified T : Comparable<T>> gt(value: T): T = AdditionalMatchers.gt(value) ?: value
/**
* The delegation to [AdditionalMatchers.leq].
*/
inline fun <reified T : Comparable<T>> leq(value: T): T = AdditionalMatchers.leq(value) ?: value
/**
* The delegation to [AdditionalMatchers.lt].
*/
inline fun <reified T : Comparable<T>> lt(value: T): T = AdditionalMatchers.lt(value) ?: value
/**
* The delegation to [AdditionalMatchers.cmpEq].
*/
inline fun <reified T : Comparable<T>> cmpEq(value: T): T = AdditionalMatchers.cmpEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.find].
*/
inline fun find(regex: String): String = AdditionalMatchers.find(regex) ?: regex
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun aryEq(value: BooleanArray): BooleanArray = AdditionalMatchers.aryEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun aryEq(value: ByteArray): ByteArray = AdditionalMatchers.aryEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun aryEq(value: CharArray): CharArray = AdditionalMatchers.aryEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun aryEq(value: DoubleArray): DoubleArray = AdditionalMatchers.aryEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun aryEq(value: FloatArray): FloatArray = AdditionalMatchers.aryEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun aryEq(value: IntArray): IntArray = AdditionalMatchers.aryEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun aryEq(value: LongArray): LongArray = AdditionalMatchers.aryEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun aryEq(value: ShortArray): ShortArray = AdditionalMatchers.aryEq(value) ?: value
/**
* The delegation to [AdditionalMatchers.aryEq].
*/
inline fun <reified T> aryEq(value: Array<T>): Array<T> = AdditionalMatchers.aryEq(value) ?: value
|
mit
|
8a81b65354c771457a8e479af24db436
| 29.021053 | 115 | 0.713184 | 3.503686 | false | false | false | false |
lunabox/leetcode
|
kotlin/problems/src/case/Extense.kt
|
1
|
623
|
package case
/**
* 扩展IntArray的打印方法
*/
inline fun <T> Iterable<T>.print() {
val list = this.toList()
list.forEachIndexed { index, t ->
if (index == 0) {
print("[")
}
print(t)
if (index == list.size - 1) {
println("]")
} else {
print(",")
}
}
}
inline fun IntArray.print() {
this.forEachIndexed { index, i ->
if (index == 0) {
print("[")
}
print(i)
if (index == this.size - 1) {
println("]")
} else {
print(",")
}
}
}
|
apache-2.0
|
852a06bf79cb1086cd3f5d90dec79811
| 16.428571 | 37 | 0.392447 | 3.903846 | false | false | false | false |
jitsi/jibri
|
src/test/kotlin/org/jitsi/jibri/util/ProcessWrapperTest.kt
|
1
|
8329
|
/*
* Copyright @ 2018 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.jitsi.jibri.util
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldContain
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import org.jitsi.jibri.helpers.seconds
import org.jitsi.jibri.helpers.within
import org.jitsi.utils.logging2.Logger
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.time.Duration
import java.util.concurrent.TimeUnit
@Suppress("BlockingMethodInNonBlockingContext")
internal class ProcessWrapperTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
private val processBuilder: ProcessBuilder = mockk(relaxed = true)
private val process: Process = mockk(relaxed = true)
private val runtime: Runtime = mockk(relaxed = true)
private lateinit var outputStream: PipedOutputStream
private lateinit var inputStream: PipedInputStream
private lateinit var processWrapper: ProcessWrapper
private val logger: Logger = mockk(relaxed = true)
init {
beforeTest {
outputStream = PipedOutputStream()
inputStream = PipedInputStream(outputStream)
every { process.inputStream } returns inputStream
every { process.destroyForcibly() } returns process
every { processBuilder.start() } returns process
processWrapper = ProcessWrapper(
listOf(),
parentLogger = logger,
processBuilder = processBuilder,
runtime = runtime
)
processWrapper.start()
}
context("getOutput") {
should("return independent streams") {
val op1 = processWrapper.getOutput()
val reader1 = BufferedReader(InputStreamReader(op1))
val op2 = processWrapper.getOutput()
val reader2 = BufferedReader(InputStreamReader(op2))
outputStream.write("hello\n".toByteArray())
// Both output streams should see 'hello'
reader1.readLine() shouldBe "hello"
reader2.readLine() shouldBe "hello"
}
}
context("getMostRecentLine") {
should("return empty string at first") {
processWrapper.getMostRecentLine() shouldBe ""
}
should("be equal to the process stdout") {
outputStream.write("hello\n".toByteArray())
within(5.seconds) {
processWrapper.getMostRecentLine() shouldBe "hello"
}
}
should("update to the most recent line") {
outputStream.write("hello\n".toByteArray())
outputStream.write("goodbye\n".toByteArray())
within(5.seconds) {
processWrapper.getMostRecentLine() shouldBe "goodbye"
}
}
}
context("isAlive") {
should("return false if the process is dead") {
every { process.isAlive } returns false
processWrapper.isAlive shouldBe false
}
should("return true if the process is alive") {
every { process.isAlive } returns true
processWrapper.isAlive shouldBe true
}
}
context("exitValue") {
context("when the process has exited") {
should("return its exit code") {
every { process.exitValue() } returns 42
processWrapper.exitValue shouldBe 42
}
}
context("when the process has not exited") {
should("throw IllegalThreadStateException") {
every { process.exitValue() } throws IllegalThreadStateException()
shouldThrow<IllegalThreadStateException> {
processWrapper.exitValue
}
}
}
}
context("waitFor") {
should("call the process' waitFor") {
processWrapper.waitFor()
verify { process.waitFor() }
}
}
context("waitFor(timeout)") {
should("call the process' waitFor(timeout')") {
processWrapper.waitFor(10, TimeUnit.SECONDS)
verify { process.waitFor(10, TimeUnit.SECONDS) }
}
}
context("destroyForcibly") {
should("call the process' destroyForcibly") {
processWrapper.destroyForcibly()
verify { process.destroyForcibly() }
}
}
context("stop") {
should("invoke the correct command") {
val execCaptor = slot<String>()
every { runtime.exec(capture(execCaptor)) } returns process
processWrapper.stop()
execCaptor.captured shouldContain "kill -s SIGINT"
}
context("when the runtime throws IOException") {
every { runtime.exec(any<String>()) } throws IOException()
should("let the exception bubble up") {
shouldThrow<IOException> { processWrapper.stop() }
}
}
context("when the runtime throws RuntimeException") {
every { runtime.exec(any<String>()) } throws RuntimeException()
should("let the exception bubble up") {
shouldThrow<RuntimeException> { processWrapper.stop() }
}
}
}
context("stopAndWaitFor") {
should("invoke the correct command") {
val execCaptor = slot<String>()
every { runtime.exec(capture(execCaptor)) } returns process
every { process.waitFor(any(), any()) } returns true
processWrapper.stopAndWaitFor(Duration.ofSeconds(10)) shouldBe true
execCaptor.captured shouldContain "kill -s SIGINT"
}
context("when the runtime throws IOException") {
every { runtime.exec(any<String>()) } throws IOException()
should("handle it correctly") {
processWrapper.stopAndWaitFor(Duration.ofSeconds(10)) shouldBe false
}
}
context("when the runtime throws RuntimeException") {
every { runtime.exec(any<String>()) } throws RuntimeException()
should("handle it correctly") {
processWrapper.stopAndWaitFor(Duration.ofSeconds(10)) shouldBe false
}
}
}
context("destroyForciblyAndWaitFor") {
should("invoke the correct command") {
every { process.waitFor(any(), any()) } returns true
processWrapper.destroyForciblyAndWaitFor(Duration.ofSeconds(10)) shouldBe true
verify { process.destroyForcibly() }
}
context("when waitFor returns false") {
every { process.waitFor(any(), any()) } returns false
processWrapper.destroyForciblyAndWaitFor(Duration.ofSeconds(10)) shouldBe false
}
context("when waitFor throws") {
every { process.waitFor(any(), any()) } throws InterruptedException()
processWrapper.destroyForciblyAndWaitFor(Duration.ofSeconds(10)) shouldBe false
}
}
}
}
|
apache-2.0
|
e15f0e21a42e452077ad066ac1d27fb5
| 40.437811 | 95 | 0.586985 | 5.429596 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/RankingGenerator.kt
|
1
|
4065
|
package net.perfectdreams.loritta.morenitta.utils
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.utils.extensions.readImage
import java.awt.Color
import java.awt.Graphics2D
import java.awt.Rectangle
import java.awt.geom.Path2D
import java.awt.image.BufferedImage
import java.io.File
object RankingGenerator {
/**
* Generates a ranking image
*/
suspend fun generateRanking(
loritta: LorittaBot,
title: String,
guildIconUrl: String?,
rankedUsers: List<UserRankInformation>,
onNullUser: (suspend (Long) -> (CachedUserInfo?))? = null
): BufferedImage {
val rankHeader = readImage(File(LorittaBot.ASSETS, "rank_header.png"))
val base = BufferedImage(400, 300, BufferedImage.TYPE_INT_ARGB_PRE)
val graphics = base.graphics.enableFontAntiAliasing()
val serverIconUrl = if (guildIconUrl != null) {
guildIconUrl.replace("jpg", "png")
} else {
"${loritta.config.loritta.website.url}assets/img/unknown.png"
}
val serverIcon = (LorittaUtils.downloadImage(loritta, serverIconUrl) ?: Constants.DEFAULT_DISCORD_BLUE_AVATAR)
.getScaledInstance(141, 141, BufferedImage.SCALE_SMOOTH)
graphics.drawImage(serverIcon, 259, -52, null)
graphics.drawImage(rankHeader, 0, 0, null)
val oswaldRegular10 = Constants.OSWALD_REGULAR
.deriveFont(10F)
val oswaldRegular16 = oswaldRegular10
.deriveFont(16F)
val oswaldRegular20 = oswaldRegular10
.deriveFont(20F)
graphics.font = oswaldRegular16
ImageUtils.drawCenteredString(graphics, title, Rectangle(0, 0, 268, 37), oswaldRegular16)
var idx = 0
var currentY = 37
for (profile in rankedUsers) {
if (idx >= 5) {
break
}
val member = loritta.lorittaShards.retrieveUserInfoById(profile.userId) ?: onNullUser?.invoke(profile.userId)
if (member != null) {
val rankBackground = loritta.getUserProfileBackground(member.id)
graphics.drawImage(rankBackground.getScaledInstance(400, 300, BufferedImage.SCALE_SMOOTH)
.toBufferedImage()
.getSubimage(0, idx * 52, 400, 53), 0, currentY, null)
graphics.color = Color(0, 0, 0, 127)
graphics.fillRect(0, currentY, 400, 53)
graphics.color = Color(255, 255, 255)
graphics.font = oswaldRegular20
ImageUtils.drawTextWrap(loritta, member.name, 143, currentY + 21, 9999, 9999, graphics.fontMetrics, graphics)
graphics.font = oswaldRegular16
if (profile.subtitle != null)
ImageUtils.drawTextWrap(loritta, profile.subtitle, 144, currentY + 38, 9999, 9999, graphics.fontMetrics, graphics)
graphics.font = oswaldRegular10
// Show the user's ID in the subsubtitle
ImageUtils.drawTextWrap(loritta, (profile.subsubtitle?.let { "$it // " } ?: "") + "ID: ${profile.userId}", 145, currentY + 48, 9999, 9999, graphics.fontMetrics, graphics)
val avatar = (
LorittaUtils.downloadImage(
loritta,
member.getEffectiveAvatarUrl(ImageFormat.PNG)
) ?: Constants.DEFAULT_DISCORD_BLUE_AVATAR
).getScaledInstance(143, 143, BufferedImage.SCALE_SMOOTH)
var editedAvatar = BufferedImage(143, 143, BufferedImage.TYPE_INT_ARGB)
val avatarGraphics = editedAvatar.graphics as Graphics2D
val path = Path2D.Double()
path.moveTo(0.0, 45.0)
path.lineTo(132.0, 45.0)
path.lineTo(143.0, 98.0)
path.lineTo(0.0, 98.0)
path.closePath()
avatarGraphics.clip = path
avatarGraphics.drawImage(avatar, 0, 0, null)
editedAvatar = editedAvatar.getSubimage(0, 45, 143, 53)
graphics.drawImage(editedAvatar, 0, currentY, null)
idx++
currentY += 53
}
}
return base
}
/**
* Checks if the user is trying to retrieve a valid ranking page
*
* To avoid overloading the database with big useless ranking queries, we only allow
* pages from 1 to 100 to be retrieved
*
* @param input the page input
* @return if the input is in a valid range
*/
suspend fun isValidRankingPage(input: Long) = input in 1..100
data class UserRankInformation(
val userId: Long,
val subtitle: String? = null,
val subsubtitle: String? = null
)
}
|
agpl-3.0
|
600f0b7549901e4d10c118f021cfe15d
| 29.343284 | 174 | 0.717097 | 3.486278 | false | false | false | false |
ElectroWeak1/libGDX_Jam
|
core/src/com/electroweak/game/entity/system/CollisionSystem.kt
|
1
|
2216
|
package com.electroweak.game.entity.system
import com.badlogic.ashley.core.Engine
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.EntitySystem
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.utils.ImmutableArray
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.math.Rectangle
import com.electroweak.game.entity.component.CollisionComponent
import com.electroweak.game.entity.component.PositionComponent
import com.electroweak.game.entity.component.SizeComponent
import com.electroweak.game.entity.component.TextureComponent
class CollisionSystem : EntitySystem() {
lateinit var entities: ImmutableArray<Entity>
override fun addedToEngine(engine: Engine) {
entities = engine.getEntitiesFor(Family.all(CollisionComponent::class.java, PositionComponent::class.java,
SizeComponent::class.java).get())
}
override fun update(deltaTime: Float) {
for (entity in entities) {
var collisionComponent1 = Mappers.COLLISION_MAPPER.get(entity)
var positionComponent = Mappers.POSITION_MAPPER.get(entity)
var sizeComponent = Mappers.SIZE_MAPPER.get(entity)
val boundingBox = Rectangle(positionComponent.position!!.x, positionComponent.position!!.y,
sizeComponent.width, sizeComponent.height)
for (i in 0..entities.size() - 1) {
val secondEntity = entities.get(i)
if (secondEntity == entity) continue
var collisionComponent2 = Mappers.COLLISION_MAPPER.get(secondEntity)
var positionComponent = Mappers.POSITION_MAPPER.get(secondEntity)
var sizeComponent = Mappers.SIZE_MAPPER.get(secondEntity)
val secondBox = Rectangle(positionComponent.position!!.x, positionComponent.position!!.y,
sizeComponent.width, sizeComponent.height)
if (boundingBox.overlaps(secondBox)) {
collisionComponent1.collisionHandler.collision(entity, secondEntity)
collisionComponent2.collisionHandler.collision(secondEntity, entity)
}
}
}
}
}
|
mit
|
d3c11014cd6175becb65649c616ab0cb
| 41.634615 | 114 | 0.6963 | 4.735043 | false | false | false | false |
android/app-bundle-samples
|
PlayCoreKtx/app/src/main/java/com/google/android/samples/dynamicfeatures/state/ReviewViewModel.kt
|
1
|
3281
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.samples.dynamicfeatures.state
import androidx.annotation.Keep
import androidx.annotation.MainThread
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.google.android.play.core.ktx.requestReview
import com.google.android.play.core.review.ReviewInfo
import com.google.android.play.core.review.ReviewManager
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
class ReviewViewModel @Keep constructor(private val reviewManager: ReviewManager) : ViewModel() {
/**
* For this sample, we check if the user has been asked to review during this application session
* already. Every time the app process starts fresh, it will be reset.
*
* In a real app, you should implement your own back-off strategy, for example:
* you could persist the last time the user was asked in a database,
* and only ask if at least a week has passed from the previous request.
*/
private var alreadyAskedForReview = false
private var reviewInfo: Deferred<ReviewInfo>? = null
/**
* Start requesting the review info that will be needed later in advance.
*/
@MainThread
fun preWarmReview() {
if (!alreadyAskedForReview && reviewInfo == null) {
reviewInfo = viewModelScope.async { reviewManager.requestReview() }
}
}
/**
* Only return ReviewInfo object if the prewarming has already completed,
* i.e. if the review can be launched immediately.
*/
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun obtainReviewInfo(): ReviewInfo? = withContext(Dispatchers.Main.immediate) {
if (reviewInfo?.isCompleted == true && reviewInfo?.isCancelled == false) {
reviewInfo?.getCompleted().also {
reviewInfo = null
}
} else null
}
/**
* The view should call this to let the ViewModel know that an attemt to show the review dialog
* was made.
*
* A real app could record the time when this request was made to implement a back-off strategy.
*
* @see alreadyAskedForReview
*/
fun notifyAskedForReview() {
alreadyAskedForReview = true
}
}
class ReviewViewModelProviderFactory(
private val manager: ReviewManager
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return modelClass.getConstructor(ReviewManager::class.java).newInstance(manager)
}
}
|
apache-2.0
|
2d005bf473809ca784af733ae3d6c6d7
| 37.151163 | 101 | 0.719293 | 4.582402 | false | false | false | false |
lanhuaguizha/Christian
|
app/src/main/java/eightbitlab/com/blurview/BlurViewExtendsFrameLayout.kt
|
1
|
4331
|
package eightbitlab.com.blurview
import android.content.Context
import android.widget.FrameLayout
import eightbitlab.com.blurview.BlurController
import eightbitlab.com.blurview.NoOpController
import android.content.res.TypedArray
import android.graphics.Canvas
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup
import android.view.Window
import androidx.annotation.ColorInt
import com.christian.R
import com.eightbitlab.supportrenderscriptblur.SupportRenderScriptBlur
import eightbitlab.com.blurview.BlurViewFacade
/**
* FrameLayout that blurs its underlying content.
* Can have children and draw them over blurred background.
*/
class BlurViewExtendsFrameLayout : FrameLayout {
private var blurController: BlurController = NoOpController()
@ColorInt
private var overlayColor = 0
constructor(context: Context?) : super(context!!) {
init(null, 0)
}
constructor(context: Context?, attrs: AttributeSet?) : super(
context!!, attrs
) {
init(attrs, 0)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
context!!, attrs, defStyleAttr
) {
init(attrs, defStyleAttr)
}
private fun init(attrs: AttributeSet?, defStyleAttr: Int) {
val a = context.obtainStyledAttributes(attrs, R.styleable.BlurView, defStyleAttr, 0)
overlayColor =
a.getColor(R.styleable.BlurView_blurOverlayColor, BlockingBlurController.TRANSPARENT)
a.recycle()
}
override fun draw(canvas: Canvas) {
val shouldDraw = blurController.draw(canvas)
if (shouldDraw) {
super.draw(canvas)
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
blurController.updateBlurViewSize()
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
blurController.setBlurAutoUpdate(false)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (!isHardwareAccelerated) {
Log.e(TAG, "BlurView can't be used in not hardware-accelerated window!")
} else {
blurController.setBlurAutoUpdate(true)
}
}
/**
* @param rootView root to start blur from.
* Can be Activity's root content layout (android.R.id.content)
* or (preferably) some of your layouts. The lower amount of Views are in the root, the better for performance.
* @return [BlurViewExtendsFrameLayout] to setup needed params.
*/
fun setupWith(rootView: ViewGroup): BlurViewFacade {
val blurController: BlurController = BlockingBlurController(this, rootView, overlayColor)
this.blurController.destroy()
this.blurController = blurController
return blurController
}
// Setters duplicated to be able to conveniently change these settings outside of setupWith chain
/**
* @see BlurViewFacade.setBlurRadius
*/
fun setBlurRadius(radius: Float): BlurViewFacade {
return blurController.setBlurRadius(radius)
}
/**
* @see BlurViewFacade.setOverlayColor
*/
fun setOverlayColor(@ColorInt overlayColor: Int): BlurViewFacade {
this.overlayColor = overlayColor
return blurController.setOverlayColor(overlayColor)
}
/**
* @see BlurViewFacade.setBlurAutoUpdate
*/
fun setBlurAutoUpdate(enabled: Boolean): BlurViewFacade {
return blurController.setBlurAutoUpdate(enabled)
}
/**
* @see BlurViewFacade.setBlurEnabled
*/
fun setBlurEnabled(enabled: Boolean): BlurViewFacade {
return blurController.setBlurEnabled(enabled)
}
companion object {
private val TAG = BlurViewExtendsFrameLayout::class.java.simpleName
}
}
fun makeViewBlurExtendsFrameLayout(blurViewExtendsFrameLayout: BlurViewExtendsFrameLayout, parent: ViewGroup, window: Window, boolean: Boolean = false) {
val windowBackground = window.decorView.background
val radius = 25f
blurViewExtendsFrameLayout.setupWith(parent)
.setFrameClearDrawable(windowBackground)
.setBlurAlgorithm(SupportRenderScriptBlur(parent.context))
.setBlurRadius(radius)
.setHasFixedTransformationMatrix(boolean)
}
|
gpl-3.0
|
913bd7666ebd78165b227c26907fe08e
| 31.818182 | 153 | 0.703302 | 4.483437 | false | false | false | false |
moyheen/barcode-detector
|
app/src/main/java/com/moyinoluwa/barcodedetection/MainActivity.kt
|
1
|
2155
|
package com.moyinoluwa.barcodedetection
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.google.android.gms.vision.Frame
import com.google.android.gms.vision.barcode.Barcode
import com.google.android.gms.vision.barcode.BarcodeDetector
private const val EMPTY_STRING = ""
private const val NO_INFO = "No information available"
private const val ERROR_MESSAGE = "Barcode detector could not be set up on your device :("
class MainActivity : AppCompatActivity() {
private lateinit var barcodeBitmap: Bitmap
private lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val imageView = findViewById<ImageView>(R.id.image_view)
textView = findViewById(R.id.text_view)
barcodeBitmap = BitmapFactory.decodeResource(resources, R.drawable.images)
imageView.setImageBitmap(barcodeBitmap)
}
fun processBarcode(view: View) {
val barcodeDetector = BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.ALL_FORMATS)
.build()
if (barcodeDetector.isOperational.not()) {
AlertDialog.Builder(this)
.setMessage(ERROR_MESSAGE)
.show()
} else {
val frame = Frame.Builder().setBitmap(barcodeBitmap).build()
val barcode = barcodeDetector.detect(frame)
val size = barcode.size()
textView.text = if (size == 0) {
NO_INFO
} else {
var barcodeValue = EMPTY_STRING
for (i in 0 until size) {
barcodeValue += "${barcode.valueAt(i).displayValue}\n"
}
barcodeValue
}
}
barcodeDetector.release()
}
}
|
mit
|
6aa1ba052ec47b9f7a59d4e55df2ea1e
| 31.651515 | 90 | 0.636195 | 4.778271 | false | false | false | false |
anton-okolelov/intellij-rust
|
src/main/kotlin/org/rust/ide/intentions/UnwrapSingleExprIntention.kt
|
2
|
1717
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.RsBlockExpr
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsMatchArm
import org.rust.lang.core.psi.RsPsiFactory
import org.rust.lang.core.psi.ext.ancestorStrict
import org.rust.lang.core.psi.ext.getNextNonCommentSibling
class UnwrapSingleExprIntention : RsElementBaseIntentionAction<RsBlockExpr>() {
override fun getText() = "Remove braces from single expression"
override fun getFamilyName() = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): RsBlockExpr? {
val blockExpr = element.ancestorStrict<RsBlockExpr>() ?: return null
if (blockExpr.unsafe != null) return null
val block = blockExpr.block
return if (block.expr != null && block.lbrace.getNextNonCommentSibling() == block.expr)
blockExpr
else
null
}
override fun invoke(project: Project, editor: Editor, ctx: RsBlockExpr) {
val blockBody = ctx.block.expr ?: return
val parent = ctx.parent
if (parent is RsMatchArm && parent.comma == null) {
parent.add(RsPsiFactory(project).createComma())
}
val relativeCaretPosition = Math.min(Math.max(editor.caretModel.offset - blockBody.textOffset, 0), blockBody.textLength)
val offset = (ctx.replace(blockBody) as RsExpr).textOffset
editor.caretModel.moveToOffset(offset + relativeCaretPosition)
}
}
|
mit
|
db93820a602184a30b4be4e52868499d
| 38.022727 | 128 | 0.718113 | 4.346835 | false | false | false | false |
google/horologist
|
media-ui/src/main/java/com/google/android/horologist/media/ui/components/animated/AnimatedPlayerScreenMediaDisplay.kt
|
1
|
1862
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.media.ui.components.animated
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.R
import com.google.android.horologist.media.ui.components.InfoMediaDisplay
import com.google.android.horologist.media.ui.components.LoadingMediaDisplay
import com.google.android.horologist.media.ui.state.PlayerUiState
/**
* Animated [MediaDisplay] implementation for [PlayerScreen] including player status.
*/
@ExperimentalHorologistMediaUiApi
@Composable
public fun AnimatedPlayerScreenMediaDisplay(
playerUiState: PlayerUiState,
modifier: Modifier = Modifier
) {
val media = playerUiState.media
if (!playerUiState.connected) {
LoadingMediaDisplay(modifier)
} else if (media != null) {
MarqueeTextMediaDisplay(
modifier = modifier,
title = media.title,
artist = media.artist
)
} else {
InfoMediaDisplay(
message = stringResource(R.string.horologist_nothing_playing),
modifier = modifier
)
}
}
|
apache-2.0
|
d704f241706b09f4e7a1c4f708a64222
| 34.807692 | 85 | 0.740602 | 4.381176 | false | false | false | false |
gravidence/gravifon
|
lastfm4k/src/main/kotlin/org/gravidence/lastfm4k/api/track/TrackApiResponse.kt
|
1
|
4517
|
package org.gravidence.lastfm4k.api.track
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import org.gravidence.lastfm4k.misc.BooleanAsIntSerializer
@Serializable
class NowPlayingResponse(
@SerialName("nowplaying")
val result: ScrobbleResult
)
@Serializable
class ScrobbleResponse(
@SerialName("scrobbles")
val responseHolder: ScrobbleResponseHolder
)
@Serializable
class ScrobbleResponseHolder(
@SerialName("scrobble")
val result: ScrobbleResult,
@SerialName("@attr")
val summary: ScrobbleSummary
)
@Serializable
class BatchScrobbleResponse(
@SerialName("scrobbles")
val responseHolder: BatchScrobbleResponseHolder
)
@Serializable
class BatchScrobbleResponseHolder(
@SerialName("scrobble")
val results: List<ScrobbleResult>,
@SerialName("@attr")
val summary: ScrobbleSummary
)
@Serializable
class ScrobbleResult(
@SerialName("timestamp")
val timestamp: Long? = null,
@SerialName("ignoredMessage")
val scrobbleCorrectionSummary: ScrobbleCorrectionSummary,
@SerialName("track")
val trackCorrectionSummary: ParamCorrectionSummary,
@SerialName("artist")
val artistCorrectionSummary: ParamCorrectionSummary,
@SerialName("album")
val albumCorrectionSummary: ParamCorrectionSummary,
@SerialName("albumArtist")
val albumArtistCorrectionSummary: ParamCorrectionSummary,
)
@Serializable(with = IgnoreStatus.AsStringSerializer::class)
enum class IgnoreStatus(val code: Int) {
OK(0),
ARTIST_IGNORED(1),
TRACK_IGNORED(2),
TIMESTAMP_IN_THE_PAST(3),
TIMESTAMP_IN_THE_FUTURE(4),
DAILY_SCROBBLE_LIMIT_EXCEEDED(5);
companion object {
fun valueOfCode(code: String): IgnoreStatus {
return values().first { it.code == code.toInt() }
}
}
object AsStringSerializer : KSerializer<IgnoreStatus> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("IgnoreStatus", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): IgnoreStatus {
return valueOfCode(decoder.decodeString())
}
override fun serialize(encoder: Encoder, value: IgnoreStatus) {
encoder.encodeString(value.code.toString())
}
}
}
@Serializable
class ScrobbleCorrectionSummary(
@SerialName("code")
val status: IgnoreStatus,
@SerialName("#text")
val value: String
)
@Serializable(with = CorrectionStatus.AsStringSerializer::class)
enum class CorrectionStatus(val code: Int) {
UNCHANGED(0),
CORRECTED(1);
companion object {
fun valueOfCode(code: String): CorrectionStatus {
return values().first { it.code == code.toInt() }
}
}
object AsStringSerializer : KSerializer<CorrectionStatus> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("CorrectionStatus", PrimitiveKind.STRING)
override fun deserialize(decoder: Decoder): CorrectionStatus {
return valueOfCode(decoder.decodeString())
}
override fun serialize(encoder: Encoder, value: CorrectionStatus) {
encoder.encodeString(value.code.toString())
}
}
}
@Serializable
class ParamCorrectionSummary(
@SerialName("corrected")
val status: CorrectionStatus,
@SerialName("#text")
val value: String
)
@Serializable
class ScrobbleSummary(
@SerialName("accepted")
val accepted: Int,
@SerialName("ignored")
val ignored: Int
)
@Serializable
class TrackInfoResponse(
@SerialName("track")
val trackInfo: TrackInfo
)
@Serializable
class TrackInfo(
@SerialName("listeners")
val listeners: Long,
@SerialName("playcount")
val playcount: Long,
@SerialName("userplaycount")
val userPlaycount: Long? = null,
@SerialName("userloved")
@Serializable(with = BooleanAsIntSerializer::class)
val userLoved: Boolean? = null,
)
fun ScrobbleResponse.toBatchScrobbleResponse(): BatchScrobbleResponse {
return BatchScrobbleResponse(
BatchScrobbleResponseHolder(
results = listOf(responseHolder.result),
summary = responseHolder.summary
)
)
}
|
mit
|
913096be6d56cb194e0f74816f656c21
| 25.115607 | 119 | 0.721054 | 4.553427 | false | false | false | false |
yyued/CodeX-UIKit-Android
|
library/src/main/java/com/yy/codex/uikit/UITextView.kt
|
1
|
8950
|
package com.yy.codex.uikit
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Build
import android.support.annotation.RequiresApi
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.View
/**
* Created by cuiminghui on 2017/2/8.
*/
class UITextView : UIScrollView, UITextInput.Delegate {
interface Delegate: UIScrollView.Delegate {
fun shouldBeginEditing(textView: UITextView): Boolean
fun shouldEndEditing(textView: UITextView): Boolean
fun didBeginEditing(textView: UITextView)
fun didEndEditing(textView: UITextView)
fun shouldChangeTextInRange(textView: UITextView, inRange: NSRange, replacementString: String): Boolean
fun didChange(textView: UITextView)
}
constructor(context: Context, view: View) : super(context, view) {}
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {}
override fun init() {
super.init()
input = UITextInput()
label = UILabel(context)
label.numberOfLines = 0
addSubview(label)
tapGestureRecognizer = UITapGestureRecognizer(this, "onTapped:")
longPressGestureRecognizer = UILongPressGestureRecognizer(this, "onLongPressed:")
longPressGestureRecognizer.minimumPressDuration = 0.20
addGestureRecognizer(tapGestureRecognizer)
addGestureRecognizer(longPressGestureRecognizer)
cursorView = UIView(context)
cursorView.hidden = true
label.addSubview(cursorView)
}
override fun didMoveToSuperview() {
super.didMoveToSuperview()
input.view = this
}
override fun becomeFirstResponder() {
if (!editable) {
return
}
(delegate as? Delegate)?.let {
if (!it.shouldBeginEditing(this)) {
return
}
}
super.becomeFirstResponder()
input.beginEditing()
showCursorView()
(delegate as? Delegate)?.let {
it.didBeginEditing(this)
}
}
override fun resignFirstResponder() {
(delegate as? Delegate)?.let {
if (!it.shouldEndEditing(this)) {
return
}
}
if (isFirstResponder()) {
selection = null
input.endEditing()
hideCursorView()
}
super.resignFirstResponder()
resetLayouts()
(delegate as? Delegate)?.let {
it.didEndEditing(this)
}
}
fun onLongPressed(sender: UILongPressGestureRecognizer) {
if (sender.state == UIGestureRecognizerState.Began && isFirstResponder()) {
touchStartTimestamp = System.currentTimeMillis()
touchStartInputPosition = input.cursorPosition
UIMenuController.sharedMenuController.setMenuVisible(false, true)
operateCursor(sender)
}
if (sender.state == UIGestureRecognizerState.Changed && isFirstResponder()) {
UIMenuController.sharedMenuController.setMenuVisible(false, true)
operateCursor(sender)
}
else if (sender.state == UIGestureRecognizerState.Ended) {
if (UIViewHelpers.pointInside(this, sender.location(this))) {
if (!isFirstResponder()) {
becomeFirstResponder()
operateCursor(sender)
}
else {
operateCursor(sender)
if (selection == null && touchStartTimestamp + 300 > System.currentTimeMillis()) {
if (touchStartInputPosition == input.cursorPosition) {
showPositionMenu()
}
}
}
}
}
}
fun onTapped(sender: UITapGestureRecognizer) {
if (!isFirstResponder()) {
becomeFirstResponder()
operateCursor(sender)
}
else {
val menuVisible = UIMenuController.sharedMenuController.menuVisible
if (!menuVisible) {
touchStartInputPosition = input.cursorPosition
}
else {
UIMenuController.sharedMenuController.setMenuVisible(false, true)
}
operateCursor(sender)
if (!menuVisible && selection == null) {
if (touchStartInputPosition == input.cursorPosition) {
showPositionMenu()
}
}
}
}
override fun keyboardPressDown(event: UIKeyEvent) {
super.keyboardPressDown(event)
if (event.keyCode == KeyEvent.KEYCODE_DEL) {
input.delete(selection)
}
}
var contentInsets: UIEdgeInsets = UIEdgeInsets(0.0, 6.0, 0.0, 6.0)
set(value) {
field = value
resetLayouts()
}
var text: String?
get() = input?.editor?.text.toString()
set(value) {
label.text = value
input.editor?.text?.clear()
input.editor?.text?.append(text)
input.editor?.setSelection(value?.length ?: 0)
}
var attributedText: NSAttributedString?
get() = label.attributedText
set(value) { label.attributedText = value }
var textColor: UIColor?
get() = label.textColor
set(value) { value?.let { label.textColor = it } }
var font: UIFont?
get() = label.font
set(value) { value?.let { label.font = it } }
var defaultTextAttributes: Map<String, Any>? = null
var editable = true
var selectable = true
var selection: NSRange? = null
set(value) {
field = value
resetSelection()
}
override fun didChanged(onDelete: Boolean) {
resetText(onDelete)
selection?.let {
selection = null
}
(delegate as? Delegate)?.let {
it.didChange(this)
}
}
override fun shouldChange(range: NSRange, replacementString: String): Boolean {
(delegate as? Delegate)?.let {
return it.shouldChangeTextInRange(this, range, replacementString)
}
return true
}
override fun shouldClear(): Boolean {
return true
}
override fun shouldReturn(): Boolean {
return true
}
/* Content Props */
lateinit internal var input: UITextInput
lateinit internal var label: UILabel
lateinit private var tapGestureRecognizer: UITapGestureRecognizer
lateinit private var longPressGestureRecognizer: UILongPressGestureRecognizer
/* Cursor Private Props */
lateinit internal var cursorView: UIView
internal var cursorOptID: Long = 0
internal var cursorViewAnimation: UIViewAnimation? = null
internal var cursorMoveNextTiming: Long = 0
internal var cursorMovingPrevious = false
internal var cursorMovingNext = false
internal var touchStartTimestamp: Long = 0
internal var touchStartInputPosition: Int = 0
internal var selectionOperatingLeft = false
internal var selectionOperatingRight = false
private fun onChoose() {
val textLength = label.text?.length ?: return
if (input.cursorPosition >= 2) {
selection = NSRange(input.cursorPosition - 2, 2)
}
else if (textLength > 0) {
onChooseAll()
}
}
private fun onChooseAll() {
selection = NSRange(0, label.text?.length ?: 0)
}
private fun onCrop() {
selection?.let {
text?.substring(it.location, it.location + it.length)?.let {
val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
manager.primaryClip = ClipData.newPlainText(it, it)
}
input.delete(it)
}
}
private fun onCopy() {
selection?.let {
text?.substring(it.location, it.location + it.length)?.let {
val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
manager.primaryClip = ClipData.newPlainText(it, it)
}
}
}
private fun onPaste() {
val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
if (manager.hasPrimaryClip() && manager.primaryClip.itemCount > 0) {
manager.primaryClip.getItemAt(0).text?.let {
input.editor?.text?.insert(input.cursorPosition, it)
}
}
}
}
|
gpl-3.0
|
e9a483c85164dcb3b8d6842f90f2615d
| 32.02952 | 145 | 0.606034 | 4.958449 | false | false | false | false |
ntemplon/legends-of-omterra
|
core/src/com/jupiter/europa/entity/stats/characterclass/CharacterClass.kt
|
1
|
9664
|
/*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jupiter.europa.entity.stats.characterclass
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.Json.Serializable
import com.badlogic.gdx.utils.JsonValue
import com.jupiter.europa.EuropaGame
import com.jupiter.europa.entity.Mappers
import com.jupiter.europa.entity.effects.Effect
import com.jupiter.europa.entity.messaging.RequestEffectAddMessage
import com.jupiter.europa.entity.stats.AttributeSet
import com.jupiter.europa.entity.stats.SkillSet.Skills
import com.jupiter.europa.entity.traits.EffectPool
import com.jupiter.europa.entity.traits.EffectPool.TraitPoolEvent
import com.jupiter.europa.entity.traits.feat.Feat
import com.jupiter.europa.entity.traits.feat.FeatPool
import com.jupiter.europa.util.Initializable
import com.jupiter.ganymede.event.Event
import com.jupiter.ganymede.event.Listener
import org.reflections.Reflections
import java.util.LinkedHashSet
/**
* @author Nathan Templon
*/
public abstract class CharacterClass : Serializable, Initializable {
// Properties
private val levelUp = Event<LevelUpArgs>()
private var ownerId: Long = -1
protected val abilityPoolsInternal: MutableSet<EffectPool<out Effect>> = LinkedHashSet<EffectPool<out Effect>>()
public var level: Int = 0
private set
public var owner: Entity? = null
get() = this.$owner
set(value: Entity?) {
this.$owner = value
this.abilityPoolsInternal.forEach { pool ->
pool.owner = this.owner
pool.autoQualify = true
pool.reassesQualifications()
}
}
public val abilityPools: Set<EffectPool<out Effect>>
get() = this.abilityPoolsInternal
public val maxPointsPerSkill: Int
get() = 5 * (this.level + 3)
public var featPool: FeatPool = FeatPool()
private set
public var availableSkillPoints: Int = 0
private set
public abstract val healthPerLevel: Int
public abstract val startingHealth: Int
public abstract val skillPointsPerLevel: Int
public abstract val attackBonus: Int
public abstract val fortitude: Int
public abstract val reflexes: Int
public abstract val will: Int
public abstract val stamina: Int
public abstract val mana: Int
public abstract val manaAttribute: AttributeSet.Attributes
public abstract val aether: Int
public abstract val aetherAttribute: AttributeSet.Attributes
public abstract val classSkills: Set<Skills>
public abstract val textureSetName: String
init {
this.level = 1
// Feats
this.featPool.increaseCapacity(1)
this.abilityPoolsInternal.add(this.featPool)
this.featPool.addSelectionListener { args -> this.onFeatSelection(args) }
}
override fun initialize() {
if (this.ownerId > 0) {
this.owner = EuropaGame.game.lastIdMapping.get(this.ownerId)
}
// Skills
this.computeAvailableSkillPoints()
if (this.owner != null) {
this.abilityPoolsInternal.forEach { pool ->
pool.owner = this.owner
pool.autoQualify = true
pool.reassesQualifications()
}
}
}
public open fun onFirstCreation() {
}
// Public Methods
public open fun levelUp() {
if (this.level < MAX_LEVEL) {
this.level++
if (this.level % 3 == 0) {
this.featPool.increaseCapacity(1)
}
this.levelUp.dispatch(LevelUpArgs(this, this.level))
}
}
public fun addLevelUpListener(listener: Listener<LevelUpArgs>): Boolean {
return this.levelUp.addListener(listener)
}
public fun removeLevelUpListener(listener: Listener<LevelUpArgs>): Boolean {
return this.levelUp.removeListener(listener)
}
// Private Methods
private fun computeAvailableSkillPoints() {
val comp = Mappers.attributes[this.owner]
val intelligence = comp.baseAttributes.getAttribute(AttributeSet.Attributes.INTELLIGENCE)
val race = Mappers.race.get(this.owner).race
val pointsPerLevel = this.skillPointsPerLevel +
(race?.bonusSkillPoints ?: 0) +
intelligence / 2
this.availableSkillPoints = pointsPerLevel * (3 + this.level)
}
private fun onFeatSelection(event: TraitPoolEvent<Feat>) {
val owner = this.owner
if (owner != null) {
EuropaGame.game.messageSystem.publish(RequestEffectAddMessage(owner, event.effect))
}
}
// Serializable (Json) Implementation
override fun write(json: Json) {
json.writeValue(LEVEL_KEY, this.level)
json.writeValue(OWNER_ID_KEY, this.owner!!.getId())
json.writeValue(FEAT_POOL_KEY, this.featPool, this.featPool.javaClass)
json.writeValue(AVAILABLE_SKILL_POINTS_KEY, this.availableSkillPoints)
}
override fun read(json: Json, jsonData: JsonValue) {
if (jsonData.has(LEVEL_KEY)) {
this.level = jsonData.getInt(LEVEL_KEY)
}
if (jsonData.has(OWNER_ID_KEY)) {
this.ownerId = jsonData.getLong(OWNER_ID_KEY)
}
if (jsonData.has(FEAT_POOL_KEY)) {
this.abilityPoolsInternal.remove(this.featPool)
this.featPool = json.fromJson(javaClass<FeatPool>(), jsonData.get(FEAT_POOL_KEY).prettyPrint(EuropaGame.PRINT_SETTINGS))
this.featPool.addSelectionListener { args -> this.onFeatSelection(args) }
this.abilityPoolsInternal.add(this.featPool)
}
if (jsonData.has(AVAILABLE_SKILL_POINTS_KEY)) {
this.availableSkillPoints = jsonData.getInt(AVAILABLE_SKILL_POINTS_KEY)
}
}
// Nested Classes
public class LevelUpArgs(public val characterClass: CharacterClass, public val level: Int)
companion object {
// Constants
public val MAX_LEVEL: Int = 20
public val CLASS_LOOKUP: Map<String, Class<out CharacterClass>> = getClassMapping()
public val AVAILABLE_CLASSES: List<String> = CLASS_LOOKUP.keySet().toList().sort()
private val LEVEL_KEY = "level"
private val OWNER_ID_KEY = "owner-id"
private val FEAT_POOL_KEY = "feats"
public val AVAILABLE_SKILL_POINTS_KEY: String = "skill-points"
// Static Methods
public fun getInstance(className: String): CharacterClass? {
if (CLASS_LOOKUP.containsKey(className)) {
val cc = CLASS_LOOKUP.get(className)
try {
return cc?.newInstance()
} catch (ex: IllegalAccessException) {
return null
} catch (ex: InstantiationException) {
return null
}
} else {
return null
}
}
public fun goodSave(level: Int): Int {
return (10.0 + (50.0 * ((level - 1.0) / (MAX_LEVEL - 1.0)))).toInt()
}
public fun poorSave(level: Int): Int {
return (30.0 * ((level - 1.0) / (MAX_LEVEL - 1.0))).toInt()
}
public fun goodAttackBonus(level: Int): Int {
var totalBonus = 0.0
var currentBonus = level.toDouble()
while (currentBonus > 0) {
totalBonus += 5 * currentBonus
currentBonus -= 5.0
}
return Math.round(totalBonus).toInt()
}
public fun averageAttackBonus(level: Int): Int {
var totalBonus = 0.0
var currentBonus = level * 0.75
while (currentBonus > 0) {
totalBonus += 5 * currentBonus
currentBonus -= 5.0
}
return Math.round(totalBonus).toInt()
}
public fun poorAttackBonus(level: Int): Int {
var totalBonus = 0.0
var currentBonus = level * 0.5
while (currentBonus > 0) {
totalBonus += 5 * currentBonus
currentBonus -= 5.0
}
return Math.round(totalBonus).toInt()
}
private fun getClassMapping(): Map<String, Class<out CharacterClass>> {
val refl = Reflections("com.jupiter.europa")
val classes = refl.getSubTypesOf(javaClass<CharacterClass>())
return classes.map { type ->
Pair(type.getSimpleName(), type)
}.toMap()
}
}
}
|
mit
|
7e7122ae752e9971c07132c803228bdb
| 31.982935 | 132 | 0.637107 | 4.368897 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.