repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
JuliusKunze/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/optimizations/CallGraphBuilder.kt
1
5266
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.optimizations import org.jetbrains.kotlin.backend.konan.DirectedGraph import org.jetbrains.kotlin.backend.konan.DirectedGraphNode import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.KonanConfigKeys import org.jetbrains.kotlin.backend.konan.llvm.findMainEntryPoint import org.jetbrains.kotlin.konan.target.CompilerOutputKind internal class CallGraphNode(val graph: CallGraph, val symbol: DataFlowIR.FunctionSymbol) : DirectedGraphNode<DataFlowIR.FunctionSymbol> { override val key get() = symbol override val directEdges: List<DataFlowIR.FunctionSymbol> by lazy { graph.directEdges[symbol]!!.callSites .map { it.actualCallee } .filter { graph.reversedEdges.containsKey(it) } } override val reversedEdges: List<DataFlowIR.FunctionSymbol> by lazy { graph.reversedEdges[symbol]!! } class CallSite(val call: DataFlowIR.Node.Call, val actualCallee: DataFlowIR.FunctionSymbol) val callSites = mutableListOf<CallSite>() } internal class CallGraph(val directEdges: Map<DataFlowIR.FunctionSymbol, CallGraphNode>, val reversedEdges: Map<DataFlowIR.FunctionSymbol, MutableList<DataFlowIR.FunctionSymbol>>) : DirectedGraph<DataFlowIR.FunctionSymbol, CallGraphNode> { override val nodes get() = directEdges.values override fun get(key: DataFlowIR.FunctionSymbol) = directEdges[key]!! fun addEdge(caller: DataFlowIR.FunctionSymbol, callSite: CallGraphNode.CallSite) { directEdges[caller]!!.callSites += callSite reversedEdges[callSite.actualCallee]?.add(caller) } } internal class CallGraphBuilder(val context: Context, val moduleDFG: ModuleDFG, val externalModulesDFG: ExternalModulesDFG) { private val DEBUG = 0 private inline fun DEBUG_OUTPUT(severity: Int, block: () -> Unit) { if (DEBUG > severity) block() } private val hasMain = context.config.configuration.get(KonanConfigKeys.PRODUCE) == CompilerOutputKind.PROGRAM private val symbolTable = moduleDFG.symbolTable private fun DataFlowIR.Type.resolved(): DataFlowIR.Type.Declared { if (this is DataFlowIR.Type.Declared) return this val hash = (this as DataFlowIR.Type.External).hash return externalModulesDFG.publicTypes[hash] ?: error("Unable to resolve exported type $hash") } private fun DataFlowIR.FunctionSymbol.resolved(): DataFlowIR.FunctionSymbol { if (this is DataFlowIR.FunctionSymbol.External) return externalModulesDFG.publicFunctions[this.hash] ?: this return this } private fun DataFlowIR.Type.Declared.isSubtypeOf(other: DataFlowIR.Type.Declared): Boolean { return this == other || this.superTypes.any { it.resolved().isSubtypeOf(other) } } private val directEdges = mutableMapOf<DataFlowIR.FunctionSymbol, CallGraphNode>() private val reversedEdges = mutableMapOf<DataFlowIR.FunctionSymbol, MutableList<DataFlowIR.FunctionSymbol>>() private val callGraph = CallGraph(directEdges, reversedEdges) fun build(): CallGraph { val rootSet = if (hasMain) { listOf(symbolTable.mapFunction(findMainEntryPoint(context)!!).resolved()) + moduleDFG.functions .filter { it.value.isGlobalInitializer } .map { it.key } } else { moduleDFG.functions.keys.filterIsInstance<DataFlowIR.FunctionSymbol.Public>() } @Suppress("LoopToCallChain") for (symbol in rootSet) { if (!directEdges.containsKey(symbol)) dfs(symbol) } return callGraph } private fun dfs(symbol: DataFlowIR.FunctionSymbol) { val node = CallGraphNode(callGraph, symbol) directEdges.put(symbol, node) val list = mutableListOf<DataFlowIR.FunctionSymbol>() reversedEdges.put(symbol, list) val function = moduleDFG.functions[symbol] ?: externalModulesDFG.functionDFGs[symbol] val body = function!!.body body.nodes.filterIsInstance<DataFlowIR.Node.Call>() .forEach { val callee = it.callee.resolved() callGraph.addEdge(symbol, CallGraphNode.CallSite(it, callee)) if (callee is DataFlowIR.FunctionSymbol.Declared && it !is DataFlowIR.Node.VirtualCall && !directEdges.containsKey(callee)) dfs(callee) } } }
apache-2.0
d317229be07e4b2b6f86beab96ac9b52
39.829457
115
0.680213
4.921495
false
false
false
false
smmribeiro/intellij-community
java/java-features-trainer/src/com/intellij/java/ift/lesson/navigation/JavaInheritanceHierarchyLesson.kt
1
5662
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.ift.lesson.navigation import com.intellij.codeInsight.CodeInsightBundle import com.intellij.icons.AllIcons import com.intellij.ide.IdeBundle import com.intellij.java.analysis.JavaAnalysisBundle import com.intellij.java.ift.JavaLessonsBundle import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.impl.content.BaseLabel import com.intellij.ui.InplaceButton import com.intellij.ui.UIBundle import training.dsl.* import training.dsl.LessonUtil.restoreIfModifiedOrMoved import training.learn.course.KLesson class JavaInheritanceHierarchyLesson : KLesson("java.inheritance.hierarchy.lesson", JavaLessonsBundle.message("java.inheritance.hierarchy.lesson.name")) { override val existedFile: String = "src/InheritanceHierarchySample.java" override val lessonContent: LessonContext.() -> Unit = { caret("foo(demo)") actionTask("GotoImplementation") { restoreIfModifiedOrMoved() JavaLessonsBundle.message("java.inheritance.hierarchy.goto.implementation", action(it), code("SomeInterface#foo")) } task { text(JavaLessonsBundle.message("java.inheritance.hierarchy.choose.any.implementation", LessonUtil.rawEnter())) stateCheck { (virtualFile.name == "DerivedClass1.java" || virtualFile.name == "DerivedClass2.java") && atDeclarationPosition() } restoreAfterStateBecomeFalse { focusOwner is EditorComponentImpl } test { Thread.sleep(1000) invokeActionViaShortcut("ENTER") } } task("GotoSuperMethod") { text(JavaLessonsBundle.message("java.inheritance.hierarchy.navigate.to.base", action(it), icon(AllIcons.Gutter.ImplementingMethod))) stateCheck { virtualFile.name == "SomeInterface.java" && atDeclarationPosition() } restoreIfModifiedOrMoved() test { actions(it) } } task("GotoImplementation") { text(JavaLessonsBundle.message("java.inheritance.hierarchy.invoke.implementations.again", icon(AllIcons.Gutter.ImplementedMethod), action(it))) triggerByUiComponentAndHighlight { ui: InplaceButton -> ui.toolTipText == IdeBundle.message("show.in.find.window.button.name") } restoreIfModifiedOrMoved() test { actions(it) } } task { before { closeAllFindTabs() } text(JavaLessonsBundle.message("java.inheritance.hierarchy.open.in.find.tool.window", findToolWindow(), icon(ToolWindowManager.getInstance(project).getLocationIcon(ToolWindowId.FIND, AllIcons.General.Pin_tab)))) triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { ui: BaseLabel -> ui.text == (CodeInsightBundle.message("goto.implementation.findUsages.title", "foo")) || ui.text == (JavaAnalysisBundle.message("navigate.to.overridden.methods.title", "foo")) } restoreState(delayMillis = defaultRestoreDelay) { focusOwner is EditorComponentImpl } test { ideFrame { val target = previous.ui!! jComponent(target).click() jComponent(target).click() // for some magic reason one click sometimes doesn't work :( } } } task("HideActiveWindow") { text(JavaLessonsBundle.message("java.inheritance.hierarchy.hide.find.tool.window", action(it), findToolWindow())) checkToolWindowState("Find", false) restoreIfModifiedOrMoved() test { actions(it) } } actionTask("MethodHierarchy") { restoreIfModifiedOrMoved() JavaLessonsBundle.message("java.inheritance.hierarchy.open.method.hierarchy", action(it)) } task("HideActiveWindow") { text(JavaLessonsBundle.message("java.inheritance.hierarchy.hide.method.hierarchy", hierarchyToolWindow(), action(it))) checkToolWindowState("Hierarchy", false) restoreIfModifiedOrMoved() test { actions(it) } } actionTask("TypeHierarchy") { restoreIfModifiedOrMoved() JavaLessonsBundle.message("java.inheritance.hierarchy.open.class.hierarchy", action(it)) } text(JavaLessonsBundle.message("java.inheritance.hierarchy.last.note", action("GotoImplementation"), action("GotoSuperMethod"), action("MethodHierarchy"), action("TypeHierarchy"), action("GotoAction"), strong("hierarchy"))) } private fun TaskRuntimeContext.atDeclarationPosition(): Boolean { return editor.document.charsSequence.let { it.subSequence(editor.caretModel.currentCaret.offset, it.length).startsWith("foo(FileStructureDemo demo)") } } private fun TaskContext.findToolWindow() = strong(UIBundle.message("tool.window.name.find")) private fun TaskContext.hierarchyToolWindow() = strong(UIBundle.message("tool.window.name.hierarchy")) override val suitableTips = listOf("HierarchyBrowser") override val helpLinks: Map<String, String> get() = mapOf( Pair(JavaLessonsBundle.message("java.inheritance.hierarchy.help.link"), LessonUtil.getHelpLink("viewing-structure-and-hierarchy-of-the-source-code.html")), ) }
apache-2.0
501f720673497ca3b11fff01b59b27e6
39.156028
140
0.676616
5.046346
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/new/tests/testData/inference/mutability/setMutableCalls.kt
13
1083
fun a( l0: /*T1@*/MutableSet</*T0@*/Int>, l1: /*T3@*/MutableSet</*T2@*/Int>, l2: /*T5@*/MutableSet</*T4@*/Int>, l3: /*T7@*/MutableSet</*T6@*/Int>, l4: /*T9@*/MutableSet</*T8@*/Int> ) { l0/*T1@MutableSet<T0@Int>*/.add(1/*LIT*/) l1/*T3@MutableSet<T2@Int>*/.addAll(l1/*T3@MutableSet<T2@Int>*/) l2/*T5@MutableSet<T4@Int>*/.clear() l3/*T7@MutableSet<T6@Int>*/.removeAll(l1/*T3@MutableSet<T2@Int>*/) l4/*T9@MutableSet<T8@Int>*/.retainAll(l1/*T3@MutableSet<T2@Int>*/) } //T0 := T0 due to 'RECEIVER_PARAMETER' //T1 := LOWER due to 'USE_AS_RECEIVER' //T2 := T2 due to 'RECEIVER_PARAMETER' //T2 := T2 due to 'PARAMETER' //T3 <: UPPER due to 'PARAMETER' //T3 := LOWER due to 'USE_AS_RECEIVER' //T4 := T4 due to 'RECEIVER_PARAMETER' //T5 := LOWER due to 'USE_AS_RECEIVER' //T6 := T6 due to 'RECEIVER_PARAMETER' //T6 := T2 due to 'PARAMETER' //T3 <: UPPER due to 'PARAMETER' //T7 := LOWER due to 'USE_AS_RECEIVER' //T8 := T8 due to 'RECEIVER_PARAMETER' //T8 := T2 due to 'PARAMETER' //T3 <: UPPER due to 'PARAMETER' //T9 := LOWER due to 'USE_AS_RECEIVER'
apache-2.0
b68a462ee3ea81061c5c63bcc3254605
35.1
70
0.608495
2.548235
false
false
false
false
serssp/reakt
todo/src/main/kotlin/todo/actions/Actions.kt
3
1081
package todo.actions import com.github.andrewoma.flux.ActionDef import todo.stores.Todo import todo.stores.todoDispatcher object TodoActions { val create = ActionDef<CreatePayload>(todoDispatcher) val update = ActionDef<UpdatePayload>(todoDispatcher) val complete = ActionDef<CompletePayload>(todoDispatcher) val undoComplete = ActionDef<UndoCompletePayload>(todoDispatcher) val toggleCompleteAll = ActionDef<Nothing?>(todoDispatcher) val destroy = ActionDef<DestroyPayload>(todoDispatcher) val destroyCompleted = ActionDef<Nothing?>(todoDispatcher) fun toggleComplete(todo: Todo) { if (todo.complete) { undoComplete(UndoCompletePayload(todo.id)) } else { complete(CompletePayload(todo.id)) } } } interface TodoAction class CreatePayload(val text: String) : TodoAction class UpdatePayload(val id: String, val text: String) : TodoAction class UndoCompletePayload(val id: String) : TodoAction class CompletePayload(val id: String) : TodoAction class DestroyPayload(val id: String) : TodoAction
mit
8f9dbbcfbc8da5ebb22a4be2f19da02b
33.870968
69
0.750231
4.679654
false
false
false
false
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/model/mesh/FaceIndex.kt
1
1889
package com.cout970.modeler.core.model.mesh import com.cout970.modeler.api.model.mesh.IFaceIndex import com.cout970.modeler.api.model.mesh.IMesh import com.cout970.vector.api.IVector2 /** * Created by cout970 on 2017/05/07. */ class FaceIndex( val size: Int, val pos0: Int, val pos1: Int, val pos2: Int, val pos3: Int, val tex0: Int, val tex1: Int, val tex2: Int, val tex3: Int ) : IFaceIndex { override val vertexCount: Int get() = size override val pos: List<Int> get() = when (size) { 0 -> emptyList() 1 -> listOf(pos0) 2 -> listOf(pos0, pos1) 3 -> listOf(pos0, pos1, pos2) else -> listOf(pos0, pos1, pos2, pos3) } override val tex: List<Int> get() = when (size) { 0 -> emptyList() 1 -> listOf(tex0) 2 -> listOf(tex0, tex1) 3 -> listOf(tex0, tex1, tex2) else -> listOf(tex0, tex1, tex2, tex3) } companion object { fun from(pos: List<Int>, tex: List<Int>): FaceIndex { require(pos.size == tex.size) { "Sizes don't match: pos = ${pos.size}, tex = ${tex.size}" } return FaceIndex(pos.size, pos.getOrNull(0) ?: 0, pos.getOrNull(1) ?: 0, pos.getOrNull(2) ?: 0, pos.getOrNull(3) ?: 0, tex.getOrNull(0) ?: 0, tex.getOrNull(1) ?: 0, tex.getOrNull(2) ?: 0, tex.getOrNull(3) ?: 0 ) } } } fun IFaceIndex.getTextureVertex(mesh: IMesh): List<IVector2> { if (this.tex.size == 4 && this.tex[2] == this.tex[3]) { return listOf( mesh.tex[this.tex[0]], mesh.tex[this.tex[1]], mesh.tex[this.tex[2]] ) } return this.tex.map { mesh.tex[it] } }
gpl-3.0
651df684207839ebb974ac666232ba22
25.619718
103
0.505558
3.349291
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2018/Day18.kt
1
1092
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import com.nibado.projects.advent.collect.CharMap import com.nibado.projects.advent.resourceLines object Day18 : Day { private val input = resourceLines(2018, 18) private fun sim(minutes: Int): Int { var map = CharMap.from(input) for (i in 1..minutes) { val nextMap = map.clone() for (p in map.points()) { val neighbors = p.neighbors().filter { map.inBounds(it) } fun count(c: Char) = neighbors.count { map[it] == c } if (map[p] == '.' && count('|') >= 3) { nextMap[p] = '|' } else if (map[p] == '|' && count('#') >= 3) { nextMap[p] = '#' } else if (map[p] == '#' && (count('#') < 1 || count('|') < 1)) { nextMap[p] = '.' } } map = nextMap } return map.count('|') * map.count('#') } override fun part1() = sim(10) override fun part2() = sim(1000) }
mit
6f5e1bb4b6ac7a0ca1c5adf5f8e60032
28.540541
81
0.475275
3.886121
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/Keyboard.kt
1
8302
package tornadofx import javafx.beans.property.SimpleDoubleProperty import javafx.beans.property.SimpleObjectProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.event.EventTarget import javafx.scene.control.Button import javafx.scene.control.Control import javafx.scene.control.SkinBase import javafx.scene.paint.Color import javax.json.Json import javax.json.JsonObject fun EventTarget.keyboard(op: KeyboardLayout.() -> Unit) = opcr(this, KeyboardLayout(), op) class KeyboardStyles : Stylesheet() { init { keyboard { keyboardKey { borderWidth += box(1.px) borderColor += box(Color.BLACK) borderRadius += box(3.px) padding = box(3.px) backgroundInsets += box(5.px) backgroundRadius += box(5.px) backgroundColor += Color.WHITE and(armed) { borderRadius += box(5.px) backgroundInsets += box(7.px) backgroundRadius += box(7.px) } } } } } class KeyboardLayout : Control() { val rows = FXCollections.observableArrayList<KeyboardRow>() val unitSizeProperty = SimpleDoubleProperty(50.0) var unitSize by unitSizeProperty init { addClass(Stylesheet.keyboard) } override fun getUserAgentStylesheet() = KeyboardStyles().base64URL.toExternalForm() override fun createDefaultSkin() = KeyboardSkin(this) fun row(op: KeyboardRow.() -> Unit) = KeyboardRow(this).apply { rows.add(this) op(this) } fun load(json: JsonObject) { json.getJsonArray("rows").mapTo(rows) { KeyboardRow.fromJSON(this, it as JsonObject) } } fun toJSON() = JsonBuilder() .add("rows", Json.createArrayBuilder().let { jsonRows -> rows.forEach { jsonRows.add(it.toJSON()) } jsonRows.build() }) .build() fun toKeyboardLayoutEditorFormat(): String { val output = StringBuilder() rows.forEachIndexed { rowIndex, row -> output.append("[") row.keys.forEachIndexed { colIndex, key -> if (colIndex > 0) output.append(",") if (key is SpacerKeyboardKey) { output.append("{x:${key.keyWidth}}") } else { if (key.keyWidth != 1.0 || key.keyHeight != 1.0) { output.append("{") if (key.keyWidth != 1.0) output.append("w:${key.keyWidth}") if (key.keyHeight != 1.0) output.append("h:${key.keyHeight}") output.append("},") } output.append("\"${key.text?.replace("\\", "\\\\") ?: ""}\"") } } output.append("]") if (rowIndex < rows.size - 1) output.append(",") output.append("\n") } return output.toString() } internal fun addKeys(added: List<KeyboardKey>) = children.addAll(added) internal fun removeKeys(removed: List<KeyboardKey>) = children.removeAll(removed) } class KeyboardSkin(control: KeyboardLayout) : SkinBase<KeyboardLayout>(control) { val keyboard: KeyboardLayout = control override fun layoutChildren(contentX: Double, contentY: Double, contentWidth: Double, contentHeight: Double) { var currentX: Double var currentY = contentY keyboard.rows.forEach { row -> currentX = contentX row.keys.forEach { key -> if (key !is SpacerKeyboardKey) key.resizeRelocate(currentX, currentY, key.prefWidth, key.prefHeight) currentX += key.prefWidth } if (!row.keys.isEmpty()) { currentY += row.keys.map { it.prefHeight(-1.0) }.min() ?: 0.0 } } } override fun computePrefHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = keyboard.rows.sumByDouble { row -> if (row.keys.isEmpty()) 0.0 else row.keys.map { it.prefHeight(width) }.min() ?: 0.0 } + topInset + bottomInset override fun computePrefWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = (keyboard.rows.map { row -> if (row.keys.isEmpty()) 0.0 else row.keys.sumByDouble { it.prefWidth(height) } }.max() ?: 0.0) + leftInset + rightInset override fun computeMinWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = computePrefWidth(height, topInset, rightInset, bottomInset, leftInset) override fun computeMinHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double) = computePrefHeight(width, topInset, rightInset, bottomInset, leftInset) } class KeyboardRow(val keyboard: KeyboardLayout) { val keys = FXCollections.observableArrayList<KeyboardKey>() fun spacer(width: Number = 1.0, height: Number = 1.0) = SpacerKeyboardKey(keyboard, width, height).apply { keys.add(this) } fun key(text: String? = null, svg: String? = null, code: Int? = null, width: Number = 1.0, height: Number = 1.0, op: KeyboardKey.() -> Unit = {}): KeyboardKey { val key = KeyboardKey(keyboard, text, svg, code, width, height) op(key) keys.add(key) return key } init { keys.addListener(ListChangeListener { while (it.next()) { if (it.wasAdded()) keyboard.addKeys(it.addedSubList) if (it.wasRemoved()) keyboard.removeKeys(it.removed) } }) } companion object { fun fromJSON(keyboard: KeyboardLayout, json: JsonObject) = KeyboardRow(keyboard).apply { json.getJsonArray("keys").mapTo(keys) { KeyboardKey.fromJSON(keyboard, it as JsonObject) } } } fun toJSON() = JsonBuilder() .add("keys", Json.createArrayBuilder().let { jsonKeys -> keys.forEach { jsonKeys.add(it.toJSON()) } jsonKeys.build() }) .build() } class SpacerKeyboardKey(keyboard: KeyboardLayout, width: Number, height: Number) : KeyboardKey(keyboard, null, null, null, width, height) { init { addClass(Stylesheet.keyboardSpacerKey) } constructor(keyboard: KeyboardLayout, json: JsonObject) : this(keyboard, json.getDouble("width"), json.getDouble("height")) } open class KeyboardKey(keyboard: KeyboardLayout, text: String?, svg: String?, code: Int? = null, width: Number, height: Number) : Button(text) { val svgProperty = SimpleStringProperty(svg) var svg by svgProperty val keyWidthProperty = SimpleDoubleProperty(width.toDouble()) var keyWidth by keyWidthProperty val keyHeightProperty = SimpleDoubleProperty(height.toDouble()) var keyHeight by keyHeightProperty val codeProperty = SimpleObjectProperty<Int>(code) var code by codeProperty init { addClass(Stylesheet.keyboardKey) prefWidthProperty().bind(keyWidthProperty * keyboard.unitSizeProperty) prefHeightProperty().bind(keyHeightProperty * keyboard.unitSizeProperty) svgProperty.onChange { updateGraphic() } updateGraphic() } private fun updateGraphic() { graphic = if (svg != null) svgpath(svg) else null } fun toJSON() = JsonBuilder() .add("type", if (this is SpacerKeyboardKey) "spacer" else null) .add("text", text) .add("svg", svg) .add("code", code) .add("width", keyWidth) .add("height", keyHeight) .build() constructor(keyboard: KeyboardLayout, json: JsonObject) : this(keyboard, json.string("text"), json.string("svg"), json.int("code"), json.getDouble("width"), json.getDouble("height")) companion object { fun fromJSON(keyboard: KeyboardLayout, json: JsonObject): KeyboardKey = if (json.getString("type", null) == "spacer") SpacerKeyboardKey(keyboard, json) else KeyboardKey(keyboard, json) } }
apache-2.0
88c2494e8a486d3fa16171dba1cefb52
36.740909
199
0.611901
4.536612
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/stories/viewer/reply/group/StoryGroupReplyViewModel.kt
1
2247
package org.thoughtcrime.securesms.stories.viewer.reply.group import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy import org.signal.paging.ProxyPagingController import org.thoughtcrime.securesms.conversation.colors.NameColors import org.thoughtcrime.securesms.database.model.MessageId import org.thoughtcrime.securesms.groups.GroupId import org.thoughtcrime.securesms.recipients.Recipient import org.thoughtcrime.securesms.util.rx.RxStore class StoryGroupReplyViewModel(storyId: Long, repository: StoryGroupReplyRepository) : ViewModel() { private val sessionMemberCache: MutableMap<GroupId, Set<Recipient>> = NameColors.createSessionMembersCache() private val store = RxStore(StoryGroupReplyState()) private val disposables = CompositeDisposable() val stateSnapshot: StoryGroupReplyState = store.state val state: Flowable<StoryGroupReplyState> = store.stateFlowable val pagingController: ProxyPagingController<MessageId> = ProxyPagingController() init { disposables += repository.getThreadId(storyId).subscribe { threadId -> store.update { it.copy(threadId = threadId) } } disposables += repository.getPagedReplies(storyId) .doOnNext { pagingController.set(it.controller) } .flatMap { it.data } .subscribeBy { data -> store.update { state -> state.copy( replies = data, loadState = StoryGroupReplyState.LoadState.READY ) } } disposables += repository.getNameColorsMap(storyId, sessionMemberCache) .subscribeBy { nameColors -> store.update { state -> state.copy(nameColors = nameColors) } } } override fun onCleared() { disposables.clear() store.dispose() } class Factory(private val storyId: Long, private val repository: StoryGroupReplyRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return modelClass.cast(StoryGroupReplyViewModel(storyId, repository)) as T } } }
gpl-3.0
f7a506ef927dcb4680d9e00af71ff523
35.241935
123
0.747664
4.661826
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/TransformGestureDetector.kt
3
10304
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.gestures import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.PointerEvent import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.PointerInputScope import androidx.compose.ui.input.pointer.positionChanged import androidx.compose.ui.util.fastAny import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastSumBy import kotlin.math.PI import kotlin.math.abs import kotlin.math.atan2 /** * A gesture detector for rotation, panning, and zoom. Once touch slop has been reached, the * user can use rotation, panning and zoom gestures. [onGesture] will be called when any of the * rotation, zoom or pan occurs, passing the rotation angle in degrees, zoom in scale factor and * pan as an offset in pixels. Each of these changes is a difference between the previous call * and the current gesture. This will consume all position changes after touch slop has * been reached. [onGesture] will also provide centroid of all the pointers that are down. * * If [panZoomLock] is `true`, rotation is allowed only if touch slop is detected for rotation * before pan or zoom motions. If not, pan and zoom gestures will be detected, but rotation * gestures will not be. If [panZoomLock] is `false`, once touch slop is reached, all three * gestures are detected. * * Example Usage: * @sample androidx.compose.foundation.samples.DetectTransformGestures */ suspend fun PointerInputScope.detectTransformGestures( panZoomLock: Boolean = false, onGesture: (centroid: Offset, pan: Offset, zoom: Float, rotation: Float) -> Unit ) { awaitEachGesture { var rotation = 0f var zoom = 1f var pan = Offset.Zero var pastTouchSlop = false val touchSlop = viewConfiguration.touchSlop var lockedToPanZoom = false awaitFirstDown(requireUnconsumed = false) do { val event = awaitPointerEvent() val canceled = event.changes.fastAny { it.isConsumed } if (!canceled) { val zoomChange = event.calculateZoom() val rotationChange = event.calculateRotation() val panChange = event.calculatePan() if (!pastTouchSlop) { zoom *= zoomChange rotation += rotationChange pan += panChange val centroidSize = event.calculateCentroidSize(useCurrent = false) val zoomMotion = abs(1 - zoom) * centroidSize val rotationMotion = abs(rotation * PI.toFloat() * centroidSize / 180f) val panMotion = pan.getDistance() if (zoomMotion > touchSlop || rotationMotion > touchSlop || panMotion > touchSlop ) { pastTouchSlop = true lockedToPanZoom = panZoomLock && rotationMotion < touchSlop } } if (pastTouchSlop) { val centroid = event.calculateCentroid(useCurrent = false) val effectiveRotation = if (lockedToPanZoom) 0f else rotationChange if (effectiveRotation != 0f || zoomChange != 1f || panChange != Offset.Zero ) { onGesture(centroid, panChange, zoomChange, effectiveRotation) } event.changes.fastForEach { if (it.positionChanged()) { it.consume() } } } } } while (!canceled && event.changes.fastAny { it.pressed }) } } /** * Returns the rotation, in degrees, of the pointers between the * [PointerInputChange.previousPosition] and [PointerInputChange.position] states. Only * the pointers that are down in both previous and current states are considered. * * Example Usage: * @sample androidx.compose.foundation.samples.CalculateRotation */ fun PointerEvent.calculateRotation(): Float { val pointerCount = changes.fastSumBy { if (it.previousPressed && it.pressed) 1 else 0 } if (pointerCount < 2) { return 0f } val currentCentroid = calculateCentroid(useCurrent = true) val previousCentroid = calculateCentroid(useCurrent = false) var rotation = 0f var rotationWeight = 0f // We want to weigh each pointer differently so that motions farther from the // centroid have more weight than pointers close to the centroid. Essentially, // a small distance change near the centroid could equate to a large angle // change and we don't want it to affect the rotation as much as pointers farther // from the centroid, which should be more stable. changes.fastForEach { change -> if (change.pressed && change.previousPressed) { val currentPosition = change.position val previousPosition = change.previousPosition val previousOffset = previousPosition - previousCentroid val currentOffset = currentPosition - currentCentroid val previousAngle = previousOffset.angle() val currentAngle = currentOffset.angle() val angleDiff = currentAngle - previousAngle val weight = (currentOffset + previousOffset).getDistance() / 2f // We weigh the rotation with the distance to the centroid. This gives // more weight to angle changes from pointers farther from the centroid than // those that are closer. rotation += when { angleDiff > 180f -> angleDiff - 360f angleDiff < -180f -> angleDiff + 360f else -> angleDiff } * weight // weight its contribution by the distance to the centroid rotationWeight += weight } } return if (rotationWeight == 0f) 0f else rotation / rotationWeight } /** * Returns the angle of the [Offset] between -180 and 180, or 0 if [Offset.Zero]. */ private fun Offset.angle(): Float = if (x == 0f && y == 0f) 0f else -atan2(x, y) * 180f / PI.toFloat() /** * Uses the change of the centroid size between the [PointerInputChange.previousPosition] and * [PointerInputChange.position] to determine how much zoom was intended. * * Example Usage: * @sample androidx.compose.foundation.samples.CalculateZoom */ fun PointerEvent.calculateZoom(): Float { val currentCentroidSize = calculateCentroidSize(useCurrent = true) val previousCentroidSize = calculateCentroidSize(useCurrent = false) if (currentCentroidSize == 0f || previousCentroidSize == 0f) { return 1f } return currentCentroidSize / previousCentroidSize } /** * Returns the change in the centroid location between the previous and the current pointers that * are down. Pointers that are newly down or raised are not considered in the centroid * movement. * * Example Usage: * @sample androidx.compose.foundation.samples.CalculatePan */ fun PointerEvent.calculatePan(): Offset { val currentCentroid = calculateCentroid(useCurrent = true) if (currentCentroid == Offset.Unspecified) { return Offset.Zero } val previousCentroid = calculateCentroid(useCurrent = false) return currentCentroid - previousCentroid } /** * Returns the average distance from the centroid for all pointers that are currently * and were previously down. If no pointers are down, `0` is returned. * If [useCurrent] is `true`, the size of the [PointerInputChange.position] is returned and * if `false`, the size of [PointerInputChange.previousPosition] is returned. Only pointers that * are down in both the previous and current state are used to calculate the centroid size. * * Example Usage: * @sample androidx.compose.foundation.samples.CalculateCentroidSize */ fun PointerEvent.calculateCentroidSize(useCurrent: Boolean = true): Float { val centroid = calculateCentroid(useCurrent) if (centroid == Offset.Unspecified) { return 0f } var distanceToCentroid = 0f var distanceWeight = 0 changes.fastForEach { change -> if (change.pressed && change.previousPressed) { val position = if (useCurrent) change.position else change.previousPosition distanceToCentroid += (position - centroid).getDistance() distanceWeight++ } } return distanceToCentroid / distanceWeight.toFloat() } /** * Returns the centroid of all pointers that are down and were previously down. If no pointers * are down, [Offset.Unspecified] is returned. If [useCurrent] is `true`, the centroid of the * [PointerInputChange.position] is returned and if `false`, the centroid of the * [PointerInputChange.previousPosition] is returned. Only pointers that are down in both the * previous and current state are used to calculate the centroid. * * Example Usage: * @sample androidx.compose.foundation.samples.CalculateCentroidSize */ fun PointerEvent.calculateCentroid( useCurrent: Boolean = true ): Offset { var centroid = Offset.Zero var centroidWeight = 0 changes.fastForEach { change -> if (change.pressed && change.previousPressed) { val position = if (useCurrent) change.position else change.previousPosition centroid += position centroidWeight++ } } return if (centroidWeight == 0) { Offset.Unspecified } else { centroid / centroidWeight.toFloat() } }
apache-2.0
161536f00ecc46986630f638f2af7d23
39.566929
97
0.664693
4.862671
false
false
false
false
SimpleMobileTools/Simple-Notes
app/src/main/kotlin/com/simplemobiletools/notes/pro/adapters/WidgetAdapter.kt
1
6451
package com.simplemobiletools.notes.pro.adapters import android.content.Context import android.content.Intent import android.graphics.Paint import android.view.View import android.widget.RemoteViews import android.widget.RemoteViewsService import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.simplemobiletools.commons.extensions.adjustAlpha import com.simplemobiletools.commons.extensions.setText import com.simplemobiletools.commons.extensions.setTextSize import com.simplemobiletools.commons.helpers.WIDGET_TEXT_COLOR import com.simplemobiletools.notes.pro.R import com.simplemobiletools.notes.pro.R.id.widget_text_holder import com.simplemobiletools.notes.pro.extensions.config import com.simplemobiletools.notes.pro.extensions.getPercentageFontSize import com.simplemobiletools.notes.pro.extensions.notesDB import com.simplemobiletools.notes.pro.helpers.* import com.simplemobiletools.notes.pro.models.ChecklistItem import com.simplemobiletools.notes.pro.models.Note class WidgetAdapter(val context: Context, val intent: Intent) : RemoteViewsService.RemoteViewsFactory { private val textIds = arrayOf( R.id.widget_text_left, R.id.widget_text_center, R.id.widget_text_right, R.id.widget_text_left_monospace, R.id.widget_text_center_monospace, R.id.widget_text_right_monospace ) private val checklistIds = arrayOf( R.id.checklist_text_left, R.id.checklist_text_center, R.id.checklist_text_right, R.id.checklist_text_left_monospace, R.id.checklist_text_center_monospace, R.id.checklist_text_right_monospace ) private var widgetTextColor = DEFAULT_WIDGET_TEXT_COLOR private var note: Note? = null private var checklistItems = ArrayList<ChecklistItem>() override fun getViewAt(position: Int): RemoteViews { val noteId = intent.getLongExtra(NOTE_ID, 0L) val remoteView: RemoteViews if (note == null) { return RemoteViews(context.packageName, R.layout.widget_text_layout) } val textSize = context.getPercentageFontSize() / context.resources.displayMetrics.density if (note!!.type == NoteType.TYPE_CHECKLIST.value) { remoteView = RemoteViews(context.packageName, R.layout.item_checklist_widget).apply { val checklistItem = checklistItems.getOrNull(position) ?: return@apply val widgetNewTextColor = if (checklistItem.isDone) widgetTextColor.adjustAlpha(DONE_CHECKLIST_ITEM_ALPHA) else widgetTextColor val paintFlags = if (checklistItem.isDone) Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG else Paint.ANTI_ALIAS_FLAG for (id in checklistIds) { setText(id, checklistItem.title) setTextColor(id, widgetNewTextColor) setTextSize(id, textSize) setInt(id, "setPaintFlags", paintFlags) setViewVisibility(id, View.GONE) } setViewVisibility(getProperChecklistTextView(context), View.VISIBLE) Intent().apply { putExtra(OPEN_NOTE_ID, noteId) setOnClickFillInIntent(R.id.checklist_text_holder, this) } } } else { remoteView = RemoteViews(context.packageName, R.layout.widget_text_layout).apply { val noteText = note!!.getNoteStoredValue(context) ?: "" for (id in textIds) { setText(id, noteText) setTextColor(id, widgetTextColor) setTextSize(id, textSize) setViewVisibility(id, View.GONE) } setViewVisibility(getProperTextView(context), View.VISIBLE) Intent().apply { putExtra(OPEN_NOTE_ID, noteId) setOnClickFillInIntent(widget_text_holder, this) } } } return remoteView } private fun getProperTextView(context: Context): Int { val gravity = context.config.gravity val isMonospaced = context.config.monospacedFont return when { gravity == GRAVITY_CENTER && isMonospaced -> R.id.widget_text_center_monospace gravity == GRAVITY_CENTER -> R.id.widget_text_center gravity == GRAVITY_RIGHT && isMonospaced -> R.id.widget_text_right_monospace gravity == GRAVITY_RIGHT -> R.id.widget_text_right isMonospaced -> R.id.widget_text_left_monospace else -> R.id.widget_text_left } } private fun getProperChecklistTextView(context: Context): Int { val gravity = context.config.gravity val isMonospaced = context.config.monospacedFont return when { gravity == GRAVITY_CENTER && isMonospaced -> R.id.checklist_text_center_monospace gravity == GRAVITY_CENTER -> R.id.checklist_text_center gravity == GRAVITY_RIGHT && isMonospaced -> R.id.checklist_text_right_monospace gravity == GRAVITY_RIGHT -> R.id.checklist_text_right isMonospaced -> R.id.checklist_text_left_monospace else -> R.id.checklist_text_left } } override fun onCreate() {} override fun getLoadingView() = null override fun getItemId(position: Int) = position.toLong() override fun onDataSetChanged() { widgetTextColor = intent.getIntExtra(WIDGET_TEXT_COLOR, DEFAULT_WIDGET_TEXT_COLOR) val noteId = intent.getLongExtra(NOTE_ID, 0L) note = context.notesDB.getNoteWithId(noteId) if (note?.type == NoteType.TYPE_CHECKLIST.value) { val checklistItemType = object : TypeToken<List<ChecklistItem>>() {}.type checklistItems = Gson().fromJson<ArrayList<ChecklistItem>>(note!!.getNoteStoredValue(context), checklistItemType) ?: ArrayList(1) // checklist title can be null only because of the glitch in upgrade to 6.6.0, remove this check in the future checklistItems = checklistItems.filter { it.title != null }.toMutableList() as ArrayList<ChecklistItem> } } override fun hasStableIds() = true override fun getCount(): Int { return if (note?.type == NoteType.TYPE_CHECKLIST.value) { checklistItems.size } else { 1 } } override fun getViewTypeCount() = 2 override fun onDestroy() {} }
gpl-3.0
d045540c81f0da75b621e2db928b9c71
42.587838
142
0.661603
4.601284
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/tree/StartEditingAction.kt
5
2176
// 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.ide.actions.tree import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.SwingActionDelegate import com.intellij.util.ui.tree.EditableNode import com.intellij.util.ui.tree.EditableTree import com.intellij.util.ui.tree.TreeUtil import javax.swing.JTree internal class StartEditingAction : DumbAwareAction() { private val AnActionEvent.contextTree get() = getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) as? JTree private fun getEditableNode(node: Any?) = node as? EditableNode ?: TreeUtil.getUserObject(EditableNode::class.java, node) private fun getEditableTree(tree: JTree) = tree.model as? EditableTree ?: tree as? EditableTree ?: tree.getClientProperty(EditableTree.KEY) as? EditableTree override fun update(event: AnActionEvent) { event.presentation.isEnabledAndVisible = false val tree = event.contextTree ?: return event.presentation.isVisible = true // enable editing if the selected path is editable val path = tree.leadSelectionPath ?: return event.presentation.isEnabled = tree.run { isPathEditable(path) && cellEditor?.isCellEditable(null) == true } // update action presentation according to the selected node getEditableNode(path.lastPathComponent)?.updateAction(event.presentation) ?: getEditableTree(tree)?.updateAction(event.presentation, path) } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun actionPerformed(event: AnActionEvent) { // javax.swing.plaf.basic.BasicTreeUI.Actions.START_EDITING SwingActionDelegate.performAction("startEditing", event.contextTree) } init { isEnabledInModalContext = true } }
apache-2.0
26e08e88449c05ba934442d10c065f62
43.408163
158
0.738051
4.803532
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/base/analysis/LibraryDependenciesCache.kt
1
14033
// 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.analysis import com.intellij.ProjectTopics import com.intellij.openapi.Disposable import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.service import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressManager.checkCanceled import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.libraries.LibraryEx import com.intellij.openapi.roots.libraries.Library import com.intellij.openapi.util.Condition import com.intellij.openapi.util.Disposer import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.util.containers.MultiMap import com.intellij.workspaceModel.ide.WorkspaceModelTopics import com.intellij.workspaceModel.ide.impl.legacyBridge.module.findModule import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity import org.jetbrains.kotlin.idea.base.analysis.libraries.LibraryDependencyCandidate import org.jetbrains.kotlin.idea.base.facet.isHMPPEnabled import org.jetbrains.kotlin.idea.base.projectStructure.* import org.jetbrains.kotlin.idea.base.projectStructure.LibraryDependenciesCache.LibraryDependencies import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.allSdks import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.checkValidity import org.jetbrains.kotlin.idea.base.util.caching.SynchronizedFineGrainedEntityCache import org.jetbrains.kotlin.idea.base.util.caching.WorkspaceEntityChangeListener import org.jetbrains.kotlin.idea.caches.project.* import org.jetbrains.kotlin.idea.caches.trackers.ModuleModificationTracker import org.jetbrains.kotlin.idea.configuration.isMavenized import org.jetbrains.kotlin.utils.addToStdlib.safeAs typealias LibraryDependencyCandidatesAndSdkInfos = Pair<Set<LibraryDependencyCandidate>, Set<SdkInfo>> class LibraryDependenciesCacheImpl(private val project: Project) : LibraryDependenciesCache, Disposable { companion object { fun getInstance(project: Project): LibraryDependenciesCache = project.service() } private val cache = LibraryDependenciesInnerCache() private val moduleDependenciesCache = ModuleDependenciesCache() init { Disposer.register(this, cache) Disposer.register(this, moduleDependenciesCache) } override fun getLibraryDependencies(library: LibraryInfo): LibraryDependencies = cache[library] override fun dispose() = Unit private fun computeLibrariesAndSdksUsedWith(libraryInfo: LibraryInfo): LibraryDependencies { val (dependencyCandidates, sdks) = computeLibrariesAndSdksUsedWithNoFilter(libraryInfo) // Maven is Gradle Metadata unaware, and therefore needs stricter filter. See KTIJ-15758 val libraryDependenciesFilter = if (project.isMavenized) StrictEqualityForPlatformSpecificCandidatesFilter else DefaultLibraryDependenciesFilter union SharedNativeLibraryToNativeInteropFallbackDependenciesFilter val libraries = libraryDependenciesFilter(libraryInfo.platform, dependencyCandidates).flatMap { it.libraries } return LibraryDependencies(libraryInfo, libraries, sdks.toList()) } //NOTE: used LibraryRuntimeClasspathScope as reference private fun computeLibrariesAndSdksUsedWithNoFilter(libraryInfo: LibraryInfo): LibraryDependencyCandidatesAndSdkInfos { val libraries = LinkedHashSet<LibraryDependencyCandidate>() val sdks = LinkedHashSet<SdkInfo>() val modulesLibraryIsUsedIn = getLibraryUsageIndex().getModulesLibraryIsUsedIn(libraryInfo) for (module in modulesLibraryIsUsedIn) { checkCanceled() val (moduleLibraries, moduleSdks) = moduleDependenciesCache[module] libraries.addAll(moduleLibraries) sdks.addAll(moduleSdks) } val filteredLibraries = filterForBuiltins(libraryInfo, libraries) return filteredLibraries to sdks } private fun computeLibrariesAndSdksUsedIn(module: Module): LibraryDependencyCandidatesAndSdkInfos { val libraries = LinkedHashSet<LibraryDependencyCandidate>() val sdks = LinkedHashSet<SdkInfo>() val processedModules = HashSet<Module>() val condition = Condition<OrderEntry> { orderEntry -> checkCanceled() orderEntry.safeAs<ModuleOrderEntry>()?.let { it.module?.run { this !in processedModules } ?: false } ?: true } val infoCache = LibraryInfoCache.getInstance(project) ModuleRootManager.getInstance(module).orderEntries() // TODO: it results into O(n^2) .recursively() .satisfying(condition).process(object : RootPolicy<Unit>() { override fun visitModuleSourceOrderEntry(moduleSourceOrderEntry: ModuleSourceOrderEntry, value: Unit) { processedModules.add(moduleSourceOrderEntry.ownerModule) } override fun visitLibraryOrderEntry(libraryOrderEntry: LibraryOrderEntry, value: Unit) { checkCanceled() val libraryEx = libraryOrderEntry.library.safeAs<LibraryEx>()?.takeUnless { it.isDisposed } ?: return val candidate = LibraryDependencyCandidate.fromLibraryOrNull(infoCache[libraryEx]) ?: return libraries += candidate } override fun visitJdkOrderEntry(jdkOrderEntry: JdkOrderEntry, value: Unit) { checkCanceled() jdkOrderEntry.jdk?.let { jdk -> sdks += SdkInfo(project, jdk) } } }, Unit) return libraries to sdks } /* * When built-ins are created from module dependencies (as opposed to loading them from classloader) * we must resolve Kotlin standard library containing some built-ins declarations in the same * resolver for project as JDK. This comes from the following requirements: * - JvmBuiltins need JDK and standard library descriptors -> resolver for project should be able to * resolve them * - Builtins are created in BuiltinsCache -> module descriptors should be resolved under lock of the * SDK resolver to prevent deadlocks * This means we have to maintain dependencies of the standard library manually or effectively drop * resolver for SDK otherwise. Libraries depend on superset of their actual dependencies because of * the inability to get real dependencies from IDEA model. So moving stdlib with all dependencies * down is a questionable option. */ private fun filterForBuiltins( libraryInfo: LibraryInfo, dependencyLibraries: Set<LibraryDependencyCandidate> ): Set<LibraryDependencyCandidate> { return if (!IdeBuiltInsLoadingState.isFromClassLoader && libraryInfo.isCoreKotlinLibrary(project)) { dependencyLibraries.filterTo(mutableSetOf()) { dep -> dep.libraries.any { it.isCoreKotlinLibrary(project) } } } else { dependencyLibraries } } private fun getLibraryUsageIndex(): LibraryUsageIndex = CachedValuesManager.getManager(project).getCachedValue(project) { CachedValueProvider.Result( LibraryUsageIndex(), ModuleModificationTracker.getInstance(project), LibraryModificationTracker.getInstance(project) ) }!! private inner class LibraryDependenciesInnerCache : SynchronizedFineGrainedEntityCache<LibraryInfo, LibraryDependencies>(project, cleanOnLowMemory = true), LibraryInfoListener, ModuleRootListener, ProjectJdkTable.Listener { override fun subscribe() { val connection = project.messageBus.connect(this) connection.subscribe(LibraryInfoListener.TOPIC, this) connection.subscribe(ProjectTopics.PROJECT_ROOTS, this) connection.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, this) } override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) { invalidateEntries({ k, v -> k in libraryInfos || v.libraries.any { it in libraryInfos } }) } override fun jdkRemoved(jdk: Sdk) { invalidateEntries({ _, v -> v.sdk.any { it.sdk == jdk } }) } override fun jdkNameChanged(jdk: Sdk, previousName: String) { jdkRemoved(jdk) } override fun calculate(key: LibraryInfo): LibraryDependencies = computeLibrariesAndSdksUsedWith(key) override fun checkKeyValidity(key: LibraryInfo) { key.checkValidity() } override fun checkValueValidity(value: LibraryDependencies) { value.libraries.forEach { it.checkValidity() } } override fun rootsChanged(event: ModuleRootEvent) { if (event.isCausedByWorkspaceModelChangesOnly) return // SDK could be changed (esp in tests) out of message bus subscription val sdks = project.allSdks() invalidateEntries( { _, value -> value.sdk.any { it.sdk !in sdks } }, // unable to check entities properly: an event could be not the last validityCondition = null ) } } private inner class ModuleDependenciesCache : SynchronizedFineGrainedEntityCache<Module, LibraryDependencyCandidatesAndSdkInfos>(project), ProjectJdkTable.Listener, LibraryInfoListener, ModuleRootListener { override fun subscribe() { val connection = project.messageBus.connect(this) connection.subscribe(WorkspaceModelTopics.CHANGED, ModelChangeListener()) connection.subscribe(LibraryInfoListener.TOPIC, this) connection.subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, this) connection.subscribe(ProjectTopics.PROJECT_ROOTS, this) } override fun calculate(key: Module): LibraryDependencyCandidatesAndSdkInfos = computeLibrariesAndSdksUsedIn(key) override fun checkKeyValidity(key: Module) { key.checkValidity() } override fun checkValueValidity(value: LibraryDependencyCandidatesAndSdkInfos) { value.first.forEach { it.libraries.forEach { libraryInfo -> libraryInfo.checkValidity() } } } override fun jdkRemoved(jdk: Sdk) { invalidateEntries({ _, candidates -> candidates.second.any { it.sdk == jdk } }) } override fun jdkNameChanged(jdk: Sdk, previousName: String) { jdkRemoved(jdk) } override fun rootsChanged(event: ModuleRootEvent) { if (event.isCausedByWorkspaceModelChangesOnly) return // SDK could be changed (esp in tests) out of message bus subscription val sdks = project.allSdks() invalidateEntries( { _, (_, sdkInfos) -> sdkInfos.any { it.sdk !in sdks } }, // unable to check entities properly: an event could be not the last validityCondition = null ) } inner class ModelChangeListener : WorkspaceEntityChangeListener<ModuleEntity, Module>(project) { override val entityClass: Class<ModuleEntity> get() = ModuleEntity::class.java override fun map(storage: EntityStorage, entity: ModuleEntity): Module? = entity.findModule(storage) override fun entitiesChanged(outdated: List<Module>) { // TODO: incorrect in case of transitive module dependency invalidateKeys(outdated) { _, _ -> false } } } override fun libraryInfosRemoved(libraryInfos: Collection<LibraryInfo>) { val infos = libraryInfos.toHashSet() invalidateEntries( { _, v -> v.first.any { candidate -> candidate.libraries.any { it in infos } } }, // unable to check entities properly: an event could be not the last validityCondition = null ) } } private inner class LibraryUsageIndex { private val modulesLibraryIsUsedIn: MultiMap<Library, Module> = runReadAction { val map: MultiMap<Library, Module> = MultiMap.createSet() val libraryCache = LibraryInfoCache.getInstance(project) for (module in ModuleManager.getInstance(project).modules) { checkCanceled() for (entry in ModuleRootManager.getInstance(module).orderEntries) { if (entry !is LibraryOrderEntry) continue val library = entry.library ?: continue val keyLibrary = libraryCache.deduplicatedLibrary(library) map.putValue(keyLibrary, module) } } map } fun getModulesLibraryIsUsedIn(libraryInfo: LibraryInfo) = sequence<Module> { val ideaModelInfosCache = getIdeaModelInfosCache(project) for (module in modulesLibraryIsUsedIn[libraryInfo.library]) { val mappedModuleInfos = ideaModelInfosCache.getModuleInfosForModule(module) if (mappedModuleInfos.any { it.platform.canDependOn(libraryInfo, module.isHMPPEnabled) }) { yield(module) } } } } }
apache-2.0
5bbe6b452818c1a7c637ed4597777fa2
43.549206
123
0.688306
5.581941
false
false
false
false
jwren/intellij-community
platform/credential-store/src/keePass/KeePassFileManager.kt
1
7682
// 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.credentialStore.keePass import com.intellij.credentialStore.* import com.intellij.credentialStore.kdbx.IncorrectMasterPasswordException import com.intellij.credentialStore.kdbx.KdbxPassword import com.intellij.credentialStore.kdbx.KeePassDatabase import com.intellij.credentialStore.kdbx.loadKdbx import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.openapi.util.NlsContexts.DialogTitle import com.intellij.util.io.delete import com.intellij.util.io.exists import java.awt.Component import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.security.SecureRandom open class KeePassFileManager(private val file: Path, masterKeyFile: Path, private val masterKeyEncryptionSpec: EncryptionSpec, private val secureRandom: Lazy<SecureRandom>) { private val masterKeyFileStorage = MasterKeyFileStorage(masterKeyFile) fun clear() { if (!file.exists()) { return } try { // don't create with preloaded empty db because "clear" action should remove only IntelliJ group from database, // but don't remove other groups val masterPassword = masterKeyFileStorage.load() if (masterPassword != null) { val db = loadKdbx(file, KdbxPassword.createAndClear(masterPassword)) val store = KeePassCredentialStore(file, masterKeyFileStorage, db) store.clear() store.save(masterKeyEncryptionSpec) return } } catch (e: Exception) { // ok, just remove file if (e !is IncorrectMasterPasswordException && ApplicationManager.getApplication()?.isUnitTestMode == false) { LOG.error(e) } } file.delete() } fun import(fromFile: Path, event: AnActionEvent?) { if (file == fromFile) { return } try { doImportOrUseExisting(fromFile, event) } catch (e: IncorrectMasterPasswordException) { throw e } catch (e: Exception) { LOG.warn(e) CredentialStoreUiService.getInstance().showErrorMessage( event?.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT), CredentialStoreBundle.message("kee.pass.dialog.title.cannot.import"), CredentialStoreBundle.message("kee.pass.dialog.message")) } } // throws IncorrectMasterPasswordException if user cancelled ask master password dialog @Throws(IncorrectMasterPasswordException::class) fun useExisting() { if (file.exists()) { if (!doImportOrUseExisting(file, event = null)) { throw IncorrectMasterPasswordException() } } else { saveDatabase(file, KeePassDatabase(), generateRandomMasterKey(masterKeyEncryptionSpec, secureRandom.value), masterKeyFileStorage, secureRandom.value) } } private fun doImportOrUseExisting(file: Path, event: AnActionEvent?): Boolean { val contextComponent = event?.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) // check master key file in parent dir of imported file val possibleMasterKeyFile = file.parent.resolve(MASTER_KEY_FILE_NAME) var masterPassword = MasterKeyFileStorage(possibleMasterKeyFile).load() if (masterPassword != null) { try { loadKdbx(file, KdbxPassword(masterPassword)) } catch (e: IncorrectMasterPasswordException) { LOG.warn("On import \"$file\" found existing master key file \"$possibleMasterKeyFile\" but key is not correct") masterPassword = null } } if (masterPassword == null && !requestMasterPassword(CredentialStoreBundle.message("kee.pass.dialog.request.master.title"), contextComponent = contextComponent) { try { loadKdbx(file, KdbxPassword(it)) masterPassword = it null } catch (e: IncorrectMasterPasswordException) { CredentialStoreBundle.message("dialog.message.master.password.not.correct") } }) { return false } if (file !== this.file) { Files.copy(file, this.file, StandardCopyOption.REPLACE_EXISTING) } masterKeyFileStorage.save(createMasterKey(masterPassword!!)) return true } fun askAndSetMasterKey(event: AnActionEvent?, @DialogMessage topNote: String? = null): Boolean { val contextComponent = event?.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT) // to open old database, key can be required, so, to avoid showing 2 dialogs, check it before val db = try { if (file.exists()) loadKdbx(file, KdbxPassword( this.masterKeyFileStorage.load() ?: throw IncorrectMasterPasswordException(isFileMissed = true))) else KeePassDatabase() } catch (e: IncorrectMasterPasswordException) { // ok, old key is required return requestCurrentAndNewKeys(contextComponent) } return requestMasterPassword(CredentialStoreBundle.message("kee.pass.dialog.title.set.master.password"), topNote = topNote, contextComponent = contextComponent) { saveDatabase(file, db, createMasterKey(it), masterKeyFileStorage, secureRandom.value) null } } protected open fun requestCurrentAndNewKeys(contextComponent: Component?): Boolean { return CredentialStoreUiService.getInstance().showChangeMasterPasswordDialog(contextComponent, ::doSetNewMasterPassword) } @Suppress("MemberVisibilityCanBePrivate") protected fun doSetNewMasterPassword(current: CharArray, new: CharArray): Boolean { val db = loadKdbx(file, KdbxPassword.createAndClear(current.toByteArrayAndClear())) saveDatabase(file, db, createMasterKey(new.toByteArrayAndClear()), masterKeyFileStorage, secureRandom.value) return false } private fun createMasterKey(value: ByteArray, isAutoGenerated: Boolean = false) = MasterKey(value, isAutoGenerated, masterKeyEncryptionSpec) protected open fun requestMasterPassword(@DialogTitle title: String, @DialogMessage topNote: String? = null, contextComponent: Component? = null, @DialogMessage ok: (value: ByteArray) -> String?): Boolean { return CredentialStoreUiService.getInstance().showRequestMasterPasswordDialog(title, topNote, contextComponent, ok) } fun saveMasterKeyToApplyNewEncryptionSpec() { // if null, master key file doesn't exist now, it will be saved later somehow, no need to re-save with a new encryption spec val existing = masterKeyFileStorage.load() ?: return // no need to re-save db file because master password is not changed, only master key encryption spec changed masterKeyFileStorage.save(createMasterKey(existing, isAutoGenerated = masterKeyFileStorage.isAutoGenerated())) } fun setCustomMasterPasswordIfNeeded(defaultDbFile: Path) { // https://youtrack.jetbrains.com/issue/IDEA-174581#focus=streamItem-27-3081868-0-0 // for custom location require to set custom master password to make sure that user will be able to reuse file on another machine if (file == defaultDbFile) { return } if (!masterKeyFileStorage.isAutoGenerated()) { return } askAndSetMasterKey(null, topNote = CredentialStoreBundle.message("kee.pass.top.note")) } }
apache-2.0
f1a974c247ec1e575db1f88e972077f4
39.861702
135
0.703723
5.111111
false
false
false
false
AleksanderBrzozowski/ticket-booking
src/main/kotlin/com/maly/domain/order/OrderService.kt
1
4549
package com.maly.domain.order import com.google.i18n.phonenumbers.NumberParseException import com.google.i18n.phonenumbers.PhoneNumberUtil import com.maly.domain.event.EventService import com.maly.domain.order.dto.TicketDto import com.maly.domain.room.Seat import com.maly.domain.room.SeatRepository import com.maly.extension.getDefaultMessage import com.maly.presentation.error.BusinessException import com.maly.presentation.order.BuyModel import com.maly.presentation.order.ReservationModel import org.springframework.context.MessageSource import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.LocalDateTime /** * @author Aleksander Brzozowski */ @Service class OrderService(private val discountRepository: DiscountRepository, private val saleFormRepository: SaleFormRepository, private val reservationRepository: ReservationRepository, private val seatRepository: SeatRepository, private val eventService: EventService, private val ticketRepository: TicketRepository, private val messageSource: MessageSource, private val saleRepository: SaleRepository) { companion object { const val SALE_FORM_NAME = "Internetowa" const val EXPIRE_TIME_MINUTES = 30L } fun getDiscounts(): List<Discount> = discountRepository.findAll() @Transactional fun reserveEvent(model: ReservationModel): TicketDto { validatePhoneNumber(model.telephone) val saleForm = getSaleForm() val now = LocalDateTime.now() val event = eventService.getEvent(model.eventId) val reservation = Reservation(saleForm = saleForm, expiryDate = event.date.minusMinutes(EXPIRE_TIME_MINUTES), date = now, firstName = model.firstName, lastName = model.lastName, telephone = model.telephone) .let { reservationRepository.save(it) } return model.tickets.map { it.discountId?.let { getDiscountById(it) } to getSeatById(it.seatId) } .map { (discount, seat) -> Ticket(reservation = reservation, seat = seat, discount = discount, event = event) } .map { saveTicket(it) } .let { TicketDto.of(it) } } fun buyEvent(model: BuyModel): TicketDto { val saleForm = getSaleForm() val sale = Sale(saleForm = saleForm).let { saleRepository.save(it) } val event = eventService.getEvent(model.eventId) return model.tickets.map { it.discountId?.let { getDiscountById(it) } to getSeatById(it.seatId) } .map { (discount, seat) -> Ticket(sale = sale, seat = seat, discount = discount, event = event) } .map { saveTicket(it) } .let { TicketDto.of(it) } } private fun getSaleForm() = (saleFormRepository.findByName(SALE_FORM_NAME) ?: throw RuntimeException("SaleForm [$SALE_FORM_NAME] not found")) private fun getDiscountById(id: Long): Discount { return discountRepository.findOne(id) ?: throw RuntimeException("discount with id: [$id] not found") } private fun getSeatById(id: Long): Seat { return seatRepository.findOne(id) ?: throw RuntimeException("seat with id: [$id] not found") } private fun saveTicket(ticket: Ticket): Ticket { ticketRepository.findBySeatAndEvent(seat = ticket.seat, event = ticket.event) ?.let { ticket.seat.let { arrayOf(it.row.toString(), it.number.toString()) } } ?.let { messageSource.getDefaultMessage("seat", it) } ?.apply { throw BusinessException( messageCode = "seat.notFree.error", params = arrayOf(this), systemMessage = "Seat with id: ${ticket.seat.id} not free for event id: ${ticket.event.id}" ) } return ticketRepository.save(ticket) } private fun validatePhoneNumber(phoneNumber: String) { val instance = PhoneNumberUtil.getInstance() val wrongPhoneNumber = { throw BusinessException("phoneNumber.error", arrayOf(phoneNumber)) } try { instance.parse(phoneNumber, "PL") .let { instance.isValidNumber(it) } .apply { if (!this) wrongPhoneNumber.invoke() } } catch (exc: NumberParseException) { wrongPhoneNumber.invoke() } } }
mit
15535905dff46320d846b4363c6d9fa4
41.523364
127
0.649373
4.499505
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExternalExtensionFix.kt
5
12540
// 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.quickfix.migration import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention import org.jetbrains.kotlin.idea.intentions.declarations.ConvertMemberToExtensionIntention import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.quickfix.CleanupFix import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory import org.jetbrains.kotlin.idea.util.addAnnotation import org.jetbrains.kotlin.js.PredefinedAnnotation import org.jetbrains.kotlin.js.resolve.diagnostics.ErrorsJs import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class MigrateExternalExtensionFix(declaration: KtNamedDeclaration) : KotlinQuickFixAction<KtNamedDeclaration>(declaration), CleanupFix { override fun getText() = KotlinBundle.message("fix.with.asdynamic") override fun getFamilyName() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val declaration = element ?: return when { isMemberExtensionDeclaration(declaration) -> fixExtensionMemberDeclaration(declaration, editor) isMemberDeclaration(declaration) -> { val containingClass = declaration.containingClassOrObject if (containingClass != null) { fixNativeClass(containingClass) } } declaration is KtClassOrObject -> fixNativeClass(declaration) } } private fun fixNativeClass(containingClass: KtClassOrObject) { val membersToFix = containingClass.declarations.asSequence().filterIsInstance<KtCallableDeclaration>() .filter { isMemberDeclaration(it) && !isMemberExtensionDeclaration(it) }.map { it to fetchJsNativeAnnotations(it) }.filter { it.second.annotations.isNotEmpty() }.toList() membersToFix.asReversed().forEach { (memberDeclaration, annotations) -> if (annotations.nativeAnnotation != null && !annotations.isGetter && !annotations.isSetter && !annotations.isInvoke) { convertNativeAnnotationToJsName(memberDeclaration, annotations) annotations.nativeAnnotation.delete() } else { val externalDeclaration = ConvertMemberToExtensionIntention.convert(memberDeclaration) fixExtensionMemberDeclaration(externalDeclaration, null) // editor is null as we are not going to open any live templates } } // make class external val classAnnotations = fetchJsNativeAnnotations(containingClass) fixAnnotations(containingClass, classAnnotations, null) } private data class JsNativeAnnotations( val annotations: List<KtAnnotationEntry>, val nativeAnnotation: KtAnnotationEntry?, val isGetter: Boolean, val isSetter: Boolean, val isInvoke: Boolean ) private fun fetchJsNativeAnnotations(declaration: KtNamedDeclaration): JsNativeAnnotations { var isGetter = false var isSetter = false var isInvoke = false var nativeAnnotation: KtAnnotationEntry? = null val nativeAnnotations = ArrayList<KtAnnotationEntry>() declaration.modifierList?.annotationEntries?.forEach { when { it.isJsAnnotation(PredefinedAnnotation.NATIVE_GETTER) -> { isGetter = true nativeAnnotations.add(it) } it.isJsAnnotation(PredefinedAnnotation.NATIVE_SETTER) -> { isSetter = true nativeAnnotations.add(it) } it.isJsAnnotation(PredefinedAnnotation.NATIVE_INVOKE) -> { isInvoke = true nativeAnnotations.add(it) } it.isJsAnnotation(PredefinedAnnotation.NATIVE) -> { nativeAnnotations.add(it) nativeAnnotation = it } } } return JsNativeAnnotations(nativeAnnotations, nativeAnnotation, isGetter, isSetter, isInvoke) } private fun fixExtensionMemberDeclaration(declaration: KtNamedDeclaration, editor: Editor?) { val name = declaration.nameAsSafeName val annotations = fetchJsNativeAnnotations(declaration) fixAnnotations(declaration, annotations, editor) val ktPsiFactory = KtPsiFactory(declaration) val body = ktPsiFactory.buildExpression { appendName(Name.identifier("asDynamic")) when { annotations.isGetter -> { appendFixedText("()") if (declaration is KtNamedFunction) { appendParameters(declaration, "[", "]") } } annotations.isSetter -> { appendFixedText("()") if (declaration is KtNamedFunction) { appendParameters(declaration, "[", "]", skipLast = true) declaration.valueParameters.last().nameAsName?.let { appendFixedText(" = ") appendName(it) } } } annotations.isInvoke -> { appendFixedText("()") if (declaration is KtNamedFunction) { appendParameters(declaration, "(", ")") } } else -> { appendFixedText("().") appendName(name) if (declaration is KtNamedFunction) { appendParameters(declaration, "(", ")") } } } } if (declaration is KtNamedFunction) { declaration.bodyExpression?.delete() declaration.equalsToken?.delete() if (annotations.isSetter || annotations.isInvoke) { val blockBody = ktPsiFactory.createSingleStatementBlock(body) declaration.add(blockBody) } else { declaration.add(ktPsiFactory.createEQ()) declaration.add(body) } } else if (declaration is KtProperty) { declaration.setter?.delete() declaration.getter?.delete() val getter = ktPsiFactory.createPropertyGetter(body) declaration.add(getter) if (declaration.isVar) { val setterBody = ktPsiFactory.buildExpression { appendName(Name.identifier("asDynamic")) appendFixedText("().") appendName(name) appendFixedText(" = ") appendName(Name.identifier("value")) } val setterStubProperty = ktPsiFactory.createProperty("val x: Unit set(value) { Unit }") val block = setterStubProperty.setter!!.bodyBlockExpression!! block.statements.single().replace(setterBody) declaration.add(setterStubProperty.setter!!) } } } private fun fixAnnotations(declaration: KtNamedDeclaration, annotations: JsNativeAnnotations, editor: Editor?) { annotations.annotations.forEach { it.delete() } if (declaration is KtClassOrObject) { declaration.addModifier(KtTokens.EXTERNAL_KEYWORD) } else { declaration.addModifier(KtTokens.INLINE_KEYWORD) declaration.removeModifier(KtTokens.EXTERNAL_KEYWORD) } if (declaration is KtFunction) { declaration.addAnnotation(StandardNames.FqNames.suppress, "\"NOTHING_TO_INLINE\"") } convertNativeAnnotationToJsName(declaration, annotations) if (declaration is KtFunction && !declaration.hasDeclaredReturnType() && !annotations.isSetter && !annotations.isInvoke && editor != null) { SpecifyTypeExplicitlyIntention.addTypeAnnotation(editor, declaration, declaration.builtIns.unitType) } } private fun convertNativeAnnotationToJsName(declaration: KtNamedDeclaration, annotations: JsNativeAnnotations) { val nativeAnnotation = annotations.nativeAnnotation if (nativeAnnotation != null && nativeAnnotation.valueArguments.isNotEmpty()) { declaration.addAnnotation(FqName("JsName"), nativeAnnotation.valueArguments.joinToString { it.asElement().text }) } } private fun BuilderByPattern<KtExpression>.appendParameters( declaration: KtNamedFunction, lParenth: String, rParenth: String, skipLast: Boolean = false ) { appendFixedText(lParenth) for ((index, param) in declaration.valueParameters.let { if (skipLast) it.take(it.size - 1) else it }.withIndex()) { param.nameAsName?.let { paramName -> if (index > 0) { appendFixedText(",") } appendName(paramName) } } appendFixedText(rParenth) } companion object : KotlinSingleIntentionActionFactory() { private fun KtAnnotationEntry.isJsAnnotation(vararg predefinedAnnotations: PredefinedAnnotation): Boolean { val bindingContext = analyze(BodyResolveMode.PARTIAL) val annotationDescriptor = bindingContext[BindingContext.ANNOTATION, this] return annotationDescriptor != null && predefinedAnnotations.any { annotationDescriptor.fqName == it.fqName } } private fun KtAnnotationEntry.isJsNativeAnnotation(): Boolean = isJsAnnotation( PredefinedAnnotation.NATIVE, PredefinedAnnotation.NATIVE_GETTER, PredefinedAnnotation.NATIVE_SETTER, PredefinedAnnotation.NATIVE_INVOKE ) private fun isMemberExtensionDeclaration(psiElement: PsiElement): Boolean { return (psiElement is KtNamedFunction && psiElement.receiverTypeReference != null) || (psiElement is KtProperty && psiElement.receiverTypeReference != null) } private fun isMemberDeclaration(psiElement: PsiElement): Boolean = (psiElement is KtNamedFunction && psiElement.receiverTypeReference == null) || (psiElement is KtProperty && psiElement.receiverTypeReference == null) override fun createAction(diagnostic: Diagnostic): IntentionAction? { val e = diagnostic.psiElement when (diagnostic.factory) { ErrorsJs.WRONG_EXTERNAL_DECLARATION -> { if (isMemberExtensionDeclaration(e) && e.getParentOfType<KtClassOrObject>(true) == null) { return MigrateExternalExtensionFix(e as KtNamedDeclaration) } } Errors.DEPRECATION_ERROR, Errors.DEPRECATION -> { if (e.getParentOfType<KtAnnotationEntry>(false)?.isJsNativeAnnotation() == true) { e.getParentOfType<KtNamedDeclaration>(false)?.let { return MigrateExternalExtensionFix(it) } } if ((e as? KtNamedDeclaration)?.modifierList?.annotationEntries?.any { it.isJsNativeAnnotation() } == true) { return MigrateExternalExtensionFix(e) } } } return null } } }
apache-2.0
0d666d82fd6ec753daf8e4b7e21a6c43
43.785714
161
0.625598
6.011505
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/wordSelection/Statements/8.kt
13
455
fun main(args : Array<String>) { for (i in 1..100) { when { i%3 == 0 -> {print("Fizz"); continue;} i%5 == 0 -> {print("Buzz"); continue;} (i%3 != 0 && i%5 != 0) -> {print(i); continue;} else -> println() } } } fun foo() : Unit { <selection> println() { println() pr<caret>intln() println() } </selection> println(array(1, 2, 3)) println() }
apache-2.0
ea34830b8c7939b11ed6e38eacda177b
18
59
0.417582
3.345588
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SafeCastWithReturnInspection.kt
4
3346
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class SafeCastWithReturnInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = binaryWithTypeRHSExpressionVisitor(fun(expression) { if (expression.right == null) return if (expression.operationReference.getReferencedName() != "as?") return val parent = expression.getStrictParentOfType<KtBinaryExpression>() ?: return if (KtPsiUtil.deparenthesize(parent.left) != expression) return if (parent.operationReference.getReferencedName() != "?:") return if (KtPsiUtil.deparenthesize(parent.right) !is KtReturnExpression) return val context = expression.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) if (parent.isUsedAsExpression(context)) { val lambda = expression.getStrictParentOfType<KtLambdaExpression>() ?: return if (lambda.functionLiteral.bodyExpression?.statements?.lastOrNull() != parent) return val call = lambda.getStrictParentOfType<KtCallExpression>() ?: return if (call.isUsedAsExpression(context)) return } if (context.diagnostics.forElement(expression.operationReference).any { it.factory == Errors.CAST_NEVER_SUCCEEDS }) return holder.registerProblem( parent, KotlinBundle.message("should.be.replaced.with.if.type.check"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceWithIfFix() ) }) } private class ReplaceWithIfFix : LocalQuickFix { override fun getName() = KotlinBundle.message("replace.with.if.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val elvisExpression = descriptor.psiElement as? KtBinaryExpression ?: return val returnExpression = KtPsiUtil.deparenthesize(elvisExpression.right) ?: return val safeCastExpression = KtPsiUtil.deparenthesize(elvisExpression.left) as? KtBinaryExpressionWithTypeRHS ?: return val typeReference = safeCastExpression.right ?: return elvisExpression.replace( KtPsiFactory(elvisExpression).createExpressionByPattern( "if ($0 !is $1) $2", safeCastExpression.left, typeReference, returnExpression ) ) } }
apache-2.0
c615d78ce6063d4d1da3ec5ea99f4a60
48.955224
158
0.715481
5.396774
false
false
false
false
Cognifide/gradle-aem-plugin
src/main/kotlin/com/cognifide/gradle/aem/common/instance/service/repository/QueryCriteria.kt
1
3407
package com.cognifide.gradle.aem.common.instance.service.repository @Suppress("TooManyFunctions") class QueryCriteria : QueryParams(false) { // Grouped params (logic statements) fun or(paramsDefiner: QueryParams.() -> Unit) = group(true, paramsDefiner) fun and(paramsDefiner: QueryParams.() -> Unit) = group(false, paramsDefiner) private fun group(or: Boolean, paramsDefiner: QueryParams.() -> Unit) { val params = QueryParams(true).apply(paramsDefiner).params val index = groupIndex this.params["${index}_group.p.or"] = or.toString() this.params.putAll(params.mapKeys { "${index}_group.${it.key}" }) } private val groupIndex: Int get() = (params.keys .filter { it.matches(Regex("^\\d+_group\\..*")) } .map { it.split("_")[0].toInt() } .maxOrNull() ?: 0) + 1 // Multi-value shorthands fun paths(vararg values: String) = paths(values.asIterable()) fun paths(values: Iterable<String>) = or { values.forEach { path(it) } } fun types(vararg values: String) = types(values.asIterable()) fun types(values: Iterable<String>) = or { values.forEach { type(it) } } fun names(vararg values: String) = names(values.asIterable()) fun names(values: Iterable<String>) = or { values.forEach { name(it) } } fun fullTexts(vararg values: String, all: Boolean = false) = fullTexts(values.asIterable(), all) fun fullTexts(values: Iterable<String>, all: Boolean = false) = group(all) { values.forEach { fullText(it) } } fun tags(vararg values: String, all: Boolean = true) = tags(values.asIterable(), all) fun tags(values: Iterable<String>, all: Boolean = true) = group(!all) { values.forEach { tag(it) } } // Ordering params fun orderBy(value: String, desc: Boolean = false) { params["orderby"] = value if (desc) { params["orderby.sort"] = "desc" } } fun orderByPath(desc: Boolean = false) = orderBy("path", desc) fun orderByName(desc: Boolean = false) = orderBy("nodename", desc) fun orderByProperty(name: String, desc: Boolean = false) = orderBy("@$name", desc) fun orderByScore(desc: Boolean = true) = orderByProperty("jcr:score", desc) fun orderByLastModified(desc: Boolean = true) = orderByProperty("cq:lastModified", desc) fun orderByContentLastModified(desc: Boolean = true) = orderByProperty("jcr:content/cq:lastModified", desc) // Paginating params fun offset(value: Int) { params["p.offset"] = value.toString() } val offset: Int get() = params["p.offset"]?.toInt() ?: 0 fun limit(value: Int) { params["p.limit"] = value.toString() } val limit: Int get() = params["p.limit"]?.toInt() ?: 10 // Rest val queryString get() = (params + FORCED_PARAMS).entries .joinToString("&") { (k, v) -> "$k=$v" } fun copy() = QueryCriteria().apply { params.putAll([email protected]) } fun forMore() = copy().apply { offset(offset + limit) } override fun toString(): String = "QueryCriteria($queryString)" init { limit(LIMIT_DEFAULT) // performance improvement (default is 10) } companion object { const val LIMIT_DEFAULT = 100 private val FORCED_PARAMS = mapOf( "p.guessTotal" to "true", "p.hits" to "full" ) } }
apache-2.0
ea843e80f9c80efd8a3eb6d1eecc99f9
30.841121
114
0.620194
3.920598
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/customUsageCollectors/ui/FontSizeInfoUsageCollector.kt
6
2458
/* * 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 com.intellij.internal.statistic.customUsageCollectors.ui import com.intellij.ide.ui.UISettings import com.intellij.internal.statistic.CollectUsagesException import com.intellij.internal.statistic.UsagesCollector import com.intellij.internal.statistic.beans.GroupDescriptor import com.intellij.internal.statistic.beans.UsageDescriptor import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.editor.colors.impl.AppEditorFontOptions /** * @author Konstantin Bulenkov */ class FontSizeInfoUsageCollector : UsagesCollector() { @Throws(CollectUsagesException::class) override fun getUsages(): Set<UsageDescriptor> { val scheme = EditorColorsManager.getInstance().globalScheme val ui = UISettings.shadowInstance var usages = setOf( UsageDescriptor("UI font size: ${ui.fontSize}"), UsageDescriptor("UI font name: ${ui.fontFace}"), UsageDescriptor("Presentation mode font size: ${ui.presentationModeFontSize}") ) if (!scheme.isUseAppFontPreferencesInEditor) { usages += setOf( UsageDescriptor("Editor font size: ${scheme.editorFontSize}"), UsageDescriptor("Editor font name: ${scheme.editorFontName}") ) } else { val appPrefs = AppEditorFontOptions.getInstance().fontPreferences usages += setOf( UsageDescriptor("IDE editor font size: ${appPrefs.getSize(appPrefs.fontFamily)}"), UsageDescriptor("IDE editor font name: ${appPrefs.fontFamily}") ) } if (!scheme.isUseEditorFontPreferencesInConsole) { usages += setOf( UsageDescriptor("Console font size: ${scheme.consoleFontSize}"), UsageDescriptor("Console font name: ${scheme.consoleFontName}") ) } return usages } override fun getGroupId(): GroupDescriptor { return GroupDescriptor.create("Fonts") } }
apache-2.0
bf6a6574218f4ceacedf738249cd4bbd
37.40625
90
0.73393
4.69084
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventurecreation/impl/TCOCAdventureCreation.kt
1
3343
package pt.joaomneto.titancompanion.adventurecreation.impl import android.view.View import java.io.BufferedWriter import java.io.IOException import java.util.ArrayList import java.util.HashMap import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventurecreation.AdventureCreation import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.VitalStatisticsFragment import pt.joaomneto.titancompanion.adventurecreation.impl.fragments.tcoc.TCOCAdventureCreationSpellsFragment import pt.joaomneto.titancompanion.util.AdventureFragmentRunner import pt.joaomneto.titancompanion.util.DiceRoller class TCOCAdventureCreation : AdventureCreation( arrayOf( AdventureFragmentRunner( R.string.title_adventure_creation_vitalstats, VitalStatisticsFragment::class ), AdventureFragmentRunner( R.string.spells, TCOCAdventureCreationSpellsFragment::class ) ) ) { var spells: MutableMap<String, Int> = HashMap() private var internalSpellList: MutableList<String> = ArrayList() var spellList: MutableList<String> = ArrayList() get() { spells.keys .filterNot { this.internalSpellList.contains(it) } .forEach { this.internalSpellList.add(it) } this.internalSpellList.sort() return this.internalSpellList } var spellValue = -1 private val tcocSpellsFragment: TCOCAdventureCreationSpellsFragment? get() = getFragment() val spellListSize: Int get() { var size = 0 spellList .asSequence() .map { spells[it] } .forEach { size += it ?: 1 } return size } @Throws(IOException::class) override fun storeAdventureSpecificValuesInFile(bw: BufferedWriter) { var spellsS = "" if (spells.isNotEmpty()) { for (spell in spellList) { spellsS += spell + "§" + spells[spell] + "#" } spellsS = spellsS.substring(0, spellsS.length - 1) } bw.write("spellValue=$spellValue\n") bw.write("spells=$spellsS\n") bw.write("gold=0\n") } override fun validateCreationSpecificParameters(): String? { val sb = StringBuilder() var error = false if (this.spellValue < 0) { sb.append(getString(R.string.spellCount)) error = true } sb.append(if (error) "; " else "") if (this.spells.isEmpty()) { sb.append(getString(R.string.chosenSpells)) } return sb.toString() } override fun rollGamebookSpecificStats(view: View) { spellValue = DiceRoller.roll2D6().sum + 6 tcocSpellsFragment?.spellScoreValue?.text = "" + spellValue } fun addSpell(spell: String) { if (!spells.containsKey(spell)) { spells[spell] = 0 } spells[spell] = spells[spell]!! + 1 } fun removeSpell(position: Int) { val spell = spellList[position] val value = spells[spell]!! - 1 if (value == 0) { spells.remove(spell) spellList.removeAt(position) } else { spells[spell] = value } } }
lgpl-3.0
1d56a5d7fb71323d51fb8c62b1daa000
29.381818
108
0.608618
4.654596
false
false
false
false
sksamuel/ktest
kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/internal/tags/Parser.kt
1
1360
package io.kotest.core.internal.tags import io.kotest.core.Tags fun Tags.parse(): Expression? { val expr = this.expression return if (expr == null) null else Parser.from(expr).expression() } class Parser(private val tokens: List<Token>) { companion object { fun from(input: String) = Parser(Lexer(input).lex()) } private var cursor = 0 /** * Returns true if we have reached the end of the token stream */ private fun isEof(): Boolean = cursor == tokens.size fun skip() { consume() } fun skip(type: TokenType) { consume(type) } /** * Consumes and returns the next [Token]. */ fun consume(): Token { val token = tokens[cursor] cursor++ return token } /** * Consumes the next token, throwing an error if the token * is not of the given type. */ fun consume(type: TokenType): Token { val next = consume() if (next.type != type) { error("Expected $type but was $next") } return next } /** * Returns the next [Token] without consuming it, or null if the next token is eof */ fun peek(): Token? = if (isEof()) null else tokens[cursor] fun skipIf(type: TokenType): Boolean { return if (peek()?.type == type) { skip() true } else { false } } }
mit
c2c35d13da2f0495bd425b3d815ffc9e
19.923077
85
0.577941
3.919308
false
false
false
false
piotrwalkusz1/LEBRB
lanlearn/src/main/kotlin/com/piotrwalkusz/lebrb/lanlearn/TranslationDictionary.kt
1
2757
package com.piotrwalkusz.lebrb.lanlearn import java.io.Reader /* Basic terms: - lemma form - the lowercase lemma of word consisting of only letters, a user doesn't see this form, only this form can be translated (e.g. hund; eat) - representation form - the form of a foreign language word that user sees (eg. der Hund; essen / aß / gegessen) - translated form - possible translation of words (e.g. dog; to eat, to dine) A Translation Dictionary file consists of the header line describing source and destination language: <source language>;<destination language> followed by lines in format: <lemma form>;<representation form>;<translated form> for example: german;polish hund;der Hund;dog essen;essen / aß / gegessen;to eat, to dine */ class TranslationDictionary(val sourceLanguage: Language, val destinationLanguage: Language, private val translations: Map<String, Pair<String, String>>) { companion object { fun createFromReader(reader: Reader): TranslationDictionary { val lines = reader.readLines() if (lines.isEmpty()) throw IllegalArgumentException("Translation Dictionary file is empty") val headerLine = lines[0].split(';') if (headerLine.size != 2) throw IllegalArgumentException("Translation Dictionary has to have the header line in format " + "'<source language>;<destination language>'") val languages = headerLine.map { it to Language.valueOfIgnoreCase(it) } val nonExistingLanguage = languages.find { it.second == null } if (nonExistingLanguage != null) throw IllegalArgumentException("Language ${nonExistingLanguage.first} in Translation Dictionary file " + "does not exist") val translations = lines.drop(1).map { val forms = it.split(';') if (forms.size != 3) { throw IllegalArgumentException("Lines in Translation Dictionary has to be in format " + "<lemma form>;<representation form>;<translated form>. Invalid line '$it' was founded.") } Pair(forms[0], Pair(forms[1], forms[2])) }.toMap() return TranslationDictionary(languages[0].second!!, languages[1].second!!, translations) } } fun getTranslatableWords(): Set<String> { return translations.keys } fun getRepresentation(word: String): String? { return translations[word]?.first } fun translate(word: String): String? { return translations[word]?.second } }
mit
28e6706e01de3b1778ee73f944b66667
37.816901
120
0.619601
4.876106
false
false
false
false
getsentry/raven-java
sentry-android-core/src/test/java/io/sentry/android/core/SentryPerformanceProviderTest.kt
1
1292
package io.sentry.android.core import android.content.pm.ProviderInfo import androidx.test.ext.junit.runners.AndroidJUnit4 import java.util.Date import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SentryPerformanceProviderTest { @BeforeTest fun `set up`() { AppStartState.getInstance().resetInstance() } @Test fun `provider sets app start`() { val providerInfo = ProviderInfo() val mockContext = ContextUtilsTest.createMockContext() providerInfo.authority = AUTHORITY val providerAppStartMillis = 10L val providerAppStartTime = Date(0) SentryPerformanceProvider.setAppStartTime(providerAppStartMillis, providerAppStartTime) val provider = SentryPerformanceProvider() provider.attachInfo(mockContext, providerInfo) // done by ActivityLifecycleIntegration so forcing it here val lifecycleAppEndMillis = 20L AppStartState.getInstance().setAppStartEnd(lifecycleAppEndMillis) assertEquals(10L, AppStartState.getInstance().appStartInterval) } companion object { private const val AUTHORITY = "io.sentry.sample.SentryPerformanceProvider" } }
bsd-3-clause
a3e1089a656887949a198dd62f48b489
29.046512
95
0.737616
4.802974
false
true
false
false
batagliao/onebible.android
app/src/main/java/com/claraboia/bibleandroid/services/DownloadTranslationService.kt
1
5907
package com.claraboia.bibleandroid.services import android.app.IntentService import android.app.NotificationManager import android.content.Context import android.content.Intent import android.support.v4.content.LocalBroadcastManager import android.support.v7.app.NotificationCompat import android.util.Log import com.claraboia.bibleandroid.R import com.claraboia.bibleandroid.bibleApplication import com.claraboia.bibleandroid.helpers.* import com.claraboia.bibleandroid.models.BibleTranslation import java.io.BufferedInputStream import java.io.DataInputStream import java.io.FileOutputStream import java.io.IOException import java.net.HttpURLConnection import java.net.URL import java.net.URLConnection /** * Created by lucas.batagliao on 01-Nov-16. */ const val EXTRA_TRANSLATION = "com.claraboia.bibleandroid.BibleTranslation.extra" const val DOWNLOAD_TRANSLATION_PROGRESS_ACTION = "com.claraboia.bibleandroid.DownloadTranslation.ActionProgress" const val DOWNLOAD_TRANSLATION_PROGRESS_VALUE = "com.claraboia.bibleandroid.DownloadTranslation.ProgressValue" const val DOWNLOAD_TRANSLATION_NAME_VALUE = "com.claraboia.bibleandroid.DownloadTranslation.NameValue" class DownloadTranslationService : IntentService("DownloadTranslationService") { var notificationId = 0 override fun onHandleIntent(intent: Intent?) { val translation = intent?.getParcelableExtra<BibleTranslation>(EXTRA_TRANSLATION) val destfilepath = getBibleDir() + "/${translation?.getFileName()}" translation?.localFile = destfilepath notify(translation!!) try { downloadFile(translation.file, destfilepath, translation) translation.addToLocalTranslations() //TODO: increase download count on Firebase postProgress(100, translation.abbreviation.toString()) }finally { endNotification() } //TODO: notify on status bar when download finishes? } private fun downloadFile(source: String, target: String, translation: BibleTranslation?) { var count = 0 try { val url = URL(source) val connection = url.openConnection() connection.connect() // this will be useful so that you can show a tipical 0-100% // progress bar // --------- // unfortunatelly we are getting -1 because size is unknow var lenghtOfFile = connection.contentLength if(lenghtOfFile <= 0){ lenghtOfFile = tryGetFileSize(url) } // download the file val input = BufferedInputStream(url.openStream(), 8192) // Output stream val output = FileOutputStream(target) val data = ByteArray(1024) var total: Long = 0 do { count = input.read(data) total += count // publishing the progress.... // After this onProgressUpdate will be called val progress = (total * 100 / lenghtOfFile).toInt() postProgress(progress, translation?.abbreviation.toString()) if(count > 0) { // writing data to file output.write(data, 0, count) } } while (count > 0) // flushing output output.flush() // closing streams output.close() input.close() } finally { } } private fun tryGetFileSize(url: URL): Int { var conn: HttpURLConnection? = null try { conn = url.openConnection() as HttpURLConnection conn.requestMethod = "HEAD" conn.inputStream return conn.contentLength } catch (e: IOException) { return -1 } finally { conn!!.disconnect() } } fun postProgress(progress: Int, target: String) { val intent = Intent(DOWNLOAD_TRANSLATION_PROGRESS_ACTION) .putExtra(DOWNLOAD_TRANSLATION_PROGRESS_VALUE, progress) .putExtra(DOWNLOAD_TRANSLATION_NAME_VALUE, target) LocalBroadcastManager.getInstance(this).sendBroadcast(intent) } private fun notify(translation : BibleTranslation){ val text = resources.getText(R.string.notification_downloading).toString() + " ${translation.name}" val builder = NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_bible_notify) .setContentTitle(translation.abbreviation) .setContentText(text) .setProgress(0, 0, true) // // Creates an explicit intent for an Activity in your app // val resultIntent = Intent(this, ResultActivity::class.java) // //// The stack builder object will contain an artificial back stack for the //// started Activity. //// This ensures that navigating backward from the Activity leads out of //// your application to the Home screen. // val stackBuilder = TaskStackBuilder.create(this) //// Adds the back stack for the Intent (but not the Intent itself) // stackBuilder.addParentStack(ResultActivity::class.java) //// Adds the Intent that starts the Activity to the top of the stack // stackBuilder.addNextIntent(resultIntent) // val resultPendingIntent = stackBuilder.getPendingIntent( // 0, // PendingIntent.FLAG_UPDATE_CURRENT) // mBuilder.setContentIntent(resultPendingIntent) notificationId = translation.hashCode() val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager manager.notify(notificationId, builder.build()) } private fun endNotification(){ val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager manager.cancel(notificationId) } }
apache-2.0
a1bae72d47548a897e5ec7e8e276509f
34.166667
112
0.654478
5.087855
false
false
false
false
AdamMc331/CashCaretaker
app/src/main/java/com/androidessence/cashcaretaker/ui/transfer/AddTransferDialog.kt
1
4552
package com.androidessence.cashcaretaker.ui.transfer import android.app.DatePickerDialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.DatePicker import androidx.fragment.app.DialogFragment import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import com.androidessence.cashcaretaker.R import com.androidessence.cashcaretaker.core.models.Account import com.androidessence.cashcaretaker.databinding.DialogAddTransferBinding import com.androidessence.cashcaretaker.ui.addtransaction.AddTransactionDialog import com.androidessence.cashcaretaker.ui.views.DatePickerFragment import com.androidessence.cashcaretaker.ui.views.SpinnerInputEditText import com.androidessence.cashcaretaker.util.DecimalDigitsInputFilter import com.androidessence.cashcaretaker.util.asUIString import java.util.Calendar import java.util.Date import kotlinx.android.synthetic.main.dialog_add_transfer.transferAmount import kotlinx.coroutines.launch import org.koin.android.viewmodel.ext.android.viewModel /** * Dialog that allows a user to transfer money from one account to another. */ class AddTransferDialog : DialogFragment(), DatePickerDialog.OnDateSetListener { private lateinit var binding: DialogAddTransferBinding private lateinit var fromAccount: SpinnerInputEditText<Account> private lateinit var toAccount: SpinnerInputEditText<Account> private val viewModel: AddTransferViewModel by viewModel() private var selectedDate: Date = Date() set(value) { binding.transferDate.setText(value.asUIString()) field = value } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DialogAddTransferBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fromAccount = view.findViewById(R.id.transferFromAccount) toAccount = view.findViewById(R.id.transferToAccount) binding.transferAmount.filters = arrayOf(DecimalDigitsInputFilter()) selectedDate = Date() binding.transferDate.setOnClickListener { showDatePicker() } binding.submitButton.setOnClickListener { addTransfer( fromAccount.selectedItem, toAccount.selectedItem, binding.transferAmount.text.toString(), selectedDate ) } subscribeToViewModel() } override fun onResume() { super.onResume() dialog?.window?.setLayout( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) } private fun subscribeToViewModel() { viewModel.viewState.observe(viewLifecycleOwner, Observer(this::processViewState)) lifecycleScope.launch { val shouldDismiss = viewModel.dismissEventChannel.receive() if (shouldDismiss) dismiss() } } private fun processViewState(viewState: AddTransferViewState) { viewState.accounts?.let { accounts -> fromAccount.items = accounts toAccount.items = accounts } viewState.fromAccountErrorRes ?.let(::getString) .let(fromAccount::setError) viewState.toAccountErrorRes ?.let(::getString) .let(toAccount::setError) viewState.amountErrorRes ?.let(::getString) .let(binding.transferAmount::setError) } private fun addTransfer( fromAccount: Account?, toAccount: Account?, amount: String, date: Date ) { viewModel.addTransfer(fromAccount, toAccount, amount, date) } private fun showDatePicker() { val datePickerFragment = DatePickerFragment.newInstance(selectedDate) datePickerFragment.setTargetFragment(this, REQUEST_DATE) datePickerFragment.show( childFragmentManager, AddTransactionDialog::class.java.simpleName ) } override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) { val calendar = Calendar.getInstance() calendar.set(year, month, dayOfMonth) selectedDate = calendar.time } companion object { private const val REQUEST_DATE = 0 } }
mit
5bdaf415b163f7cb77734eec5a86e6f1
31.985507
89
0.700791
5.190422
false
false
false
false
dmitryustimov/weather-kotlin
app/src/main/java/ru/ustimov/weather/content/impl/glide/TabIconTarget.kt
1
2261
package ru.ustimov.weather.content.impl.glide import android.graphics.drawable.Animatable import android.graphics.drawable.Drawable import android.support.design.widget.TabLayout import android.view.View import com.bumptech.glide.request.target.BaseTarget import com.bumptech.glide.request.target.SizeReadyCallback import com.bumptech.glide.request.transition.Transition class TabIconTarget( private val tab: TabLayout.Tab, private val width: Int, private val height: Int ) : BaseTarget<Drawable>(), Transition.ViewAdapter { private var animatable: Animatable? = null override fun getView(): View? = tab.customView override fun getCurrentDrawable(): Drawable? = tab.icon override fun setDrawable(drawable: Drawable?) { tab.icon = drawable } override fun getSize(cb: SizeReadyCallback?) { cb?.onSizeReady(width, height) } override fun removeCallback(cb: SizeReadyCallback?) { } override fun onLoadStarted(placeholder: Drawable?) { super.onLoadStarted(placeholder) setResourceInternal(null) setDrawable(placeholder) } override fun onLoadFailed(errorDrawable: Drawable?) { super.onLoadFailed(errorDrawable) setResourceInternal(null) setDrawable(errorDrawable) } override fun onLoadCleared(placeholder: Drawable?) { super.onLoadCleared(placeholder) setResourceInternal(null) setDrawable(placeholder) } override fun onResourceReady(resource: Drawable?, transition: Transition<in Drawable>?) { if (transition == null || !transition.transition(resource, this)) { setResourceInternal(resource) } else { maybeUpdateAnimatable(resource) } } override fun onStart() { animatable?.start() } override fun onStop() { animatable?.stop() } private fun setResourceInternal(resource: Drawable?) { maybeUpdateAnimatable(resource) setDrawable(resource) } private fun maybeUpdateAnimatable(resource: Drawable?) { if (resource is Animatable) { animatable = resource resource.start() } else { animatable = null } } }
apache-2.0
0d1bf4d36d0acad2d0de9149e44a3774
26.585366
93
0.673596
4.883369
false
false
false
false
davinkevin/Podcast-Server
backend/src/test/kotlin/com/github/davinkevin/podcastserver/messaging/MessageHandlerTest.kt
1
12632
package com.github.davinkevin.podcastserver.messaging import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.github.davinkevin.podcastserver.entity.Status import com.github.davinkevin.podcastserver.extension.json.assertThatJson import com.github.davinkevin.podcastserver.manager.downloader.DownloadingItem import org.mockito.kotlin.whenever import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.ImportAutoConfiguration import org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.context.annotation.Import import org.springframework.http.MediaType import org.springframework.http.codec.ServerSentEvent import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.returnResult import reactor.core.publisher.Sinks import reactor.test.StepVerifier import java.net.URI import java.util.* /** * Created by kevin on 02/05/2020 */ @WebFluxTest(controllers = [MessageHandler::class]) @Import(MessagingRoutingConfig::class) @AutoConfigureWebTestClient(timeout = "PT15S") @ImportAutoConfiguration(ErrorWebFluxAutoConfiguration::class) class MessageHandlerTest( @Autowired val rest: WebTestClient, @Autowired val mapper: ObjectMapper ) { @MockBean private lateinit var messageTemplate: MessagingTemplate @Nested @DisplayName("on streaming to client") inner class OnStreamingToClient { private val item1 = DownloadingItem( id = UUID.randomUUID(), title = "Title 1", status = Status.NOT_DOWNLOADED, url = URI("https://foo.bar.com/podcast/title-1"), numberOfFail = 0, progression = 0, podcast = DownloadingItem.Podcast(UUID.randomUUID(), "podcast"), cover = DownloadingItem.Cover(UUID.randomUUID(), URI("https://foo.bar.com/podcast/title-1.jpg")) ) private val item2 = DownloadingItem( id = UUID.randomUUID(), title = "Title 2", status = Status.STARTED, url = URI("https://foo.bar.com/podcast/title-2"), numberOfFail = 0, progression = 50, podcast = DownloadingItem.Podcast(UUID.randomUUID(), "podcast"), cover = DownloadingItem.Cover(UUID.randomUUID(), URI("https://foo.bar.com/podcast/title-2.jpg")) ) private val item3 = DownloadingItem( id = UUID.randomUUID(), title = "Title 3", status = Status.STARTED, url = URI("https://foo.bar.com/podcast/title-3"), numberOfFail = 3, progression = 75, podcast = DownloadingItem.Podcast(UUID.randomUUID(), "podcast"), cover = DownloadingItem.Cover(UUID.randomUUID(), URI("https://foo.bar.com/podcast/title-3.jpg")) ) private val item4 = DownloadingItem( id = UUID.randomUUID(), title = "Title 4", status = Status.FINISH, url = URI("https://foo.bar.com/podcast/title-4"), numberOfFail = 0, progression = 100, podcast = DownloadingItem.Podcast(UUID.randomUUID(), "podcast"), cover = DownloadingItem.Cover(UUID.randomUUID(), URI("https://foo.bar.com/podcast/title-4.jpg")) ) @Nested @DisplayName("on downloading item") inner class OnDownloadingItem { @Test fun `should receive items`() { /* Given */ val messages = Sinks.many().multicast().directBestEffort<Message<out Any>>() whenever(messageTemplate.messages).thenReturn(messages) /* When */ StepVerifier.create(rest .get() .uri("/api/v1/sse") .accept(MediaType.TEXT_EVENT_STREAM) .exchange() .expectStatus() .isOk .returnResult<ServerSentEvent<String>>() .responseBody .filter { it.event() != "heartbeat" } .map { it.event() to mapper.readValue<DownloadingItemHAL>(it.data()!!) } .take(2) ) /* Then */ .expectSubscription() .then { messages.tryEmitNext(DownloadingItemMessage(item1)) messages.tryEmitNext(DownloadingItemMessage(item4)) } .assertNext { (event, body) -> assertThat(event).isEqualTo("downloading") assertThat(body.id).isEqualTo(item1.id) assertThat(body.title).isEqualTo(item1.title) assertThat(body.status).isEqualTo(item1.status) assertThat(body.url).isEqualTo(item1.url) assertThat(body.progression).isEqualTo(item1.progression) assertThat(body.podcast.id).isEqualTo(item1.podcast.id) assertThat(body.podcast.title).isEqualTo(item1.podcast.title) assertThat(body.cover.id).isEqualTo(item1.cover.id) assertThat(body.cover.url).isEqualTo(item1.cover.url) assertThat(body.isDownloaded).isEqualTo(false) } .assertNext { (event, body) -> assertThat(event).isEqualTo("downloading") assertThat(body.id).isEqualTo(item4.id) assertThat(body.title).isEqualTo(item4.title) assertThat(body.status).isEqualTo(item4.status) assertThat(body.url).isEqualTo(item4.url) assertThat(body.progression).isEqualTo(item4.progression) assertThat(body.podcast.id).isEqualTo(item4.podcast.id) assertThat(body.podcast.title).isEqualTo(item4.podcast.title) assertThat(body.cover.id).isEqualTo(item4.cover.id) assertThat(body.cover.url).isEqualTo(item4.cover.url) assertThat(body.isDownloaded).isEqualTo(true) } .verifyComplete() } } @Nested @DisplayName("on update") inner class OnUpdate { @Test fun `should receive updates`() { /* Given */ val messages = Sinks.many().multicast().directBestEffort<Message<out Any>>() whenever(messageTemplate.messages).thenReturn(messages) /* When */ StepVerifier.create(rest .get() .uri("/api/v1/sse") .accept(MediaType.TEXT_EVENT_STREAM) .exchange() .expectStatus() .isOk .returnResult<ServerSentEvent<String>>() .responseBody .filter { it.event() != "heartbeat" } .take(2) ) /* Then */ .expectSubscription() .then { messages.tryEmitNext(UpdateMessage(true)) messages.tryEmitNext(UpdateMessage(false)) } .assertNext { assertThat(it.event()).isEqualTo("updating") assertThat(it.data()).isEqualTo("true") } .assertNext { assertThat(it.event()).isEqualTo("updating") assertThat(it.data()).isEqualTo("false") } .verifyComplete() } } @Nested @DisplayName("on waiting list change") inner class OnWaitingListChange { @Test fun `should receive new waiting list`() { /* Given */ val messages = Sinks.many().multicast().directBestEffort<Message<out Any>>() whenever(messageTemplate.messages).thenReturn(messages) /* When */ StepVerifier.create(rest .get() .uri("/api/v1/sse") .accept(MediaType.TEXT_EVENT_STREAM) .exchange() .expectStatus() .isOk .returnResult<ServerSentEvent<String>>() .responseBody .filter { it.event() != "heartbeat" } .map { it.event() to mapper.readValue<List<DownloadingItemHAL>>(it.data()!!) } .take(4) ) /* Then */ .expectSubscription() .then { messages.tryEmitNext(WaitingQueueMessage(listOf(item1, item2, item3))) messages.tryEmitNext(WaitingQueueMessage(listOf(item2, item3))) messages.tryEmitNext(WaitingQueueMessage(listOf(item3))) messages.tryEmitNext(WaitingQueueMessage(emptyList())) } .assertNext { (event, body) -> assertThat(event).isEqualTo("waiting") assertThat(body).hasSize(3) assertThat(body[0].id).isEqualTo(item1.id) assertThat(body[1].id).isEqualTo(item2.id) assertThat(body[2].id).isEqualTo(item3.id) } .assertNext { (event, body) -> assertThat(event).isEqualTo("waiting") assertThat(body).hasSize(2) assertThat(body[0].id).isEqualTo(item2.id) assertThat(body[1].id).isEqualTo(item3.id) } .assertNext { (event, body) -> assertThat(event).isEqualTo("waiting") assertThat(body).hasSize(1) assertThat(body[0].id).isEqualTo(item3.id) } .assertNext { (event, body) -> assertThat(event).isEqualTo("waiting") assertThat(body).hasSize(0) } .verifyComplete() } } @Test fun `should receive heartbeat`() { /* Given */ whenever(messageTemplate.messages) .thenReturn(Sinks.many().multicast().directBestEffort()) /* When */ StepVerifier.create(rest .get() .uri("/api/v1/sse") .accept(MediaType.TEXT_EVENT_STREAM) .exchange() .expectStatus() .isOk .returnResult<ServerSentEvent<Int>>() .responseBody .take(2) ) /* Then */ .expectSubscription() .assertNext { assertThat(it.event()).isEqualTo("heartbeat") } .assertNext { assertThat(it.event()).isEqualTo("heartbeat") } .verifyComplete() } } }
apache-2.0
3d576148dfb1ea0e808da771355be052
43.794326
112
0.501742
5.530648
false
true
false
false
duftler/orca
orca-dry-run/src/main/kotlin/com/netflix/spinnaker/orca/dryrun/stub/TitusRunJobOutputStub.kt
1
1877
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.dryrun.stub import com.netflix.spinnaker.orca.pipeline.model.Stage import org.springframework.stereotype.Component import java.util.UUID @Component class TitusRunJobOutputStub : OutputStub { override fun supports(stage: Stage) = stage.type == "runJob" && stage.context["cloudProvider"] == "titus" override fun outputs(stage: Stage): Map<String, Any> { val app = stage.execution.application val account = stage.context["credentials"] val cluster = stage.context["cluster"] as Map<String, Any> val region = cluster["region"] val jobId = UUID.randomUUID().toString() val taskId = UUID.randomUUID().toString() val instanceId = UUID.randomUUID().toString() return mapOf( "jobStatus" to mapOf( "id" to jobId, "name" to "$app-v000", "type" to "titus", "createdTime" to 0, "provider" to "titus", "account" to account, "application" to app, "region" to "$region", "completionDetails" to mapOf( "taskId" to taskId, "instanceId" to instanceId ), "jobState" to "Succeeded" ), "completionDetails" to mapOf( "taskId" to taskId, "instanceId" to instanceId ) ) } }
apache-2.0
3c0a8866b5137efdc2b9012669578009
30.813559
75
0.663292
4.036559
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/authentication/util/AccountRestrictions.kt
1
6672
package com.arcao.geocaching4locus.authentication.util import android.content.Context import androidx.core.content.edit import androidx.preference.PreferenceManager import com.arcao.geocaching4locus.base.constants.AppConstants import com.arcao.geocaching4locus.base.constants.PrefConstants import com.arcao.geocaching4locus.data.api.model.User import com.arcao.geocaching4locus.data.api.model.enums.MembershipType import java.time.Duration import java.time.Instant class AccountRestrictions internal constructor(context: Context) { private val context: Context = context.applicationContext private val preferences = this.context.getSharedPreferences(PrefConstants.RESTRICTION_STORAGE_NAME, Context.MODE_PRIVATE) var maxFullGeocacheLimit: Int = 0 private set var maxLiteGeocacheLimit: Int = 0 private set var currentFullGeocacheLimit: Int = 0 private set var currentLiteGeocacheLimit: Int = 0 private set var renewFullGeocacheLimit: Instant = Instant.now() get() { val now = Instant.now() if (field.isBefore(now)) { field = now } return field } private set var renewLiteGeocacheLimit: Instant = Instant.now() get() { val now = Instant.now() if (field.isBefore(now)) { field = now } return field } private set init { init() } fun remove() { preferences.edit { clear() putInt(PrefConstants.PREF_VERSION, PrefConstants.CURRENT_PREF_VERSION) } init() } private fun init() { val version = preferences.getInt(PrefConstants.PREF_VERSION, 0) if (version != PrefConstants.CURRENT_PREF_VERSION) { preferences.edit { clear() putInt(PrefConstants.PREF_VERSION, PrefConstants.CURRENT_PREF_VERSION) } } maxFullGeocacheLimit = preferences.getInt(PrefConstants.RESTRICTION__MAX_FULL_GEOCACHE_LIMIT, 0) currentFullGeocacheLimit = preferences.getInt(PrefConstants.RESTRICTION__CURRENT_FULL_GEOCACHE_LIMIT, 0) renewFullGeocacheLimit = Instant.ofEpochSecond(preferences.getLong(PrefConstants.RESTRICTION__RENEW_FULL_GEOCACHE_LIMIT, 0)) maxLiteGeocacheLimit = preferences.getInt(PrefConstants.RESTRICTION__MAX_LITE_GEOCACHE_LIMIT, 0) currentLiteGeocacheLimit = preferences.getInt(PrefConstants.RESTRICTION__CURRENT_LITE_GEOCACHE_LIMIT, 0) renewLiteGeocacheLimit = Instant.ofEpochSecond(preferences.getLong(PrefConstants.RESTRICTION__RENEW_LITE_GEOCACHE_LIMIT, 0)) } internal fun applyRestrictions(user: User) { if (user.isPremium()) { presetPremiumMembershipConfiguration() } else { presetBasicMembershipConfiguration() } } private fun presetBasicMembershipConfiguration() { PreferenceManager.getDefaultSharedPreferences(context).edit { // DOWNLOADING putBoolean(PrefConstants.DOWNLOADING_SIMPLE_CACHE_DATA, true) putString( PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW, PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW__UPDATE_NEVER ) putInt(PrefConstants.DOWNLOADING_COUNT_OF_LOGS, 0) // LIVE MAP putBoolean(PrefConstants.LIVE_MAP_DOWNLOAD_HINTS, false) // FILTERS putString(PrefConstants.FILTER_DIFFICULTY_MIN, "1") putString(PrefConstants.FILTER_DIFFICULTY_MAX, "5") putString(PrefConstants.FILTER_TERRAIN_MIN, "1") putString(PrefConstants.FILTER_TERRAIN_MAX, "5") // multi-select filters (select all) for (i in AppConstants.GEOCACHE_TYPES.indices) putBoolean(PrefConstants.FILTER_CACHE_TYPE_PREFIX + i, true) for (i in AppConstants.GEOCACHE_SIZES.indices) putBoolean(PrefConstants.FILTER_CONTAINER_TYPE_PREFIX + i, true) } } private fun presetPremiumMembershipConfiguration() { val defaultPreferences = PreferenceManager.getDefaultSharedPreferences(context) defaultPreferences.edit { // DOWNLOADING putBoolean(PrefConstants.DOWNLOADING_SIMPLE_CACHE_DATA, false) putString( PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW, PrefConstants.DOWNLOADING_FULL_CACHE_DATE_ON_SHOW__UPDATE_ONCE ) putInt(PrefConstants.DOWNLOADING_COUNT_OF_LOGS, 5) } } fun updateLimits(user: User) { maxFullGeocacheLimit = if (user.isPremium()) { FULL_GEOCACHE_LIMIT_PREMIUM } else { FULL_GEOCACHE_LIMIT_BASIC } maxLiteGeocacheLimit = if (user.isPremium()) { LITE_GEOCACHE_LIMIT_PREMIUM } else { LITE_GEOCACHE_LIMIT_BASIC } val limits = user.geocacheLimits ?: return preferences.edit { currentFullGeocacheLimit = limits.fullCallsRemaining renewFullGeocacheLimit = Instant.now().plus(limits.fullCallsSecondsToLive ?: DEFAULT_RENEW_DURATION) currentLiteGeocacheLimit = limits.liteCallsRemaining renewLiteGeocacheLimit = Instant.now().plus(limits.liteCallsSecondsToLive ?: DEFAULT_RENEW_DURATION) // store it to preferences putInt(PrefConstants.RESTRICTION__MAX_FULL_GEOCACHE_LIMIT, maxFullGeocacheLimit) putInt(PrefConstants.RESTRICTION__CURRENT_FULL_GEOCACHE_LIMIT, currentFullGeocacheLimit) putLong(PrefConstants.RESTRICTION__RENEW_FULL_GEOCACHE_LIMIT, renewFullGeocacheLimit.epochSecond) putInt(PrefConstants.RESTRICTION__MAX_LITE_GEOCACHE_LIMIT, maxLiteGeocacheLimit) putInt(PrefConstants.RESTRICTION__CURRENT_LITE_GEOCACHE_LIMIT, currentLiteGeocacheLimit) putLong(PrefConstants.RESTRICTION__RENEW_LITE_GEOCACHE_LIMIT, renewLiteGeocacheLimit.epochSecond) } } companion object { private const val FULL_GEOCACHE_LIMIT_PREMIUM = 16000 private const val FULL_GEOCACHE_LIMIT_BASIC = 3 private const val LITE_GEOCACHE_LIMIT_PREMIUM = 10000 private const val LITE_GEOCACHE_LIMIT_BASIC = 10000 val DEFAULT_RENEW_DURATION: Duration = Duration.ofDays(1) } private fun User.isPremium() = when (membership) { MembershipType.UNKNOWN -> false MembershipType.BASIC -> false MembershipType.CHARTER -> true MembershipType.PREMIUM -> true } }
gpl-3.0
2bf9aab433744b8bb9fc42a1b05832b9
36.909091
132
0.661421
4.956909
false
false
false
false
Doist/TodoistModels
src/main/java/com/todoist/pojo/LiveNotification.kt
1
2724
package com.todoist.pojo open class LiveNotification<C : Collaborator>( id: Long, var notificationType: String, open var created: Long, open var isUnread: Boolean, // Optional fields, not set in all types. open var fromUid: Long?, open var projectId: Long?, open var projectName: String?, open var invitationId: Long?, open var invitationSecret: String?, open var state: String?, open var itemId: Long?, open var itemContent: String?, open var responsibleUid: Long?, open var noteId: Long?, open var noteContent: String?, open var removedUid: Long?, open var fromUser: C?, open var accountName: String?, // Optional fields used in Karma notifications (which are set depends on the karma level). open var karmaLevel: Int?, open var completedTasks: Int?, open var completedInDays: Int?, open var completedLastMonth: Int?, open var topProcent: Double?, open var dateReached: Long?, open var promoImg: String?, isDeleted: Boolean ) : Model(id, isDeleted) { open val isInvitation get() = notificationType == TYPE_SHARE_INVITATION_SENT || notificationType == TYPE_BIZ_INVITATION_CREATED open val isStatePending get() = state != STATE_ACCEPTED && state != STATE_REJECTED companion object { const val TYPE_SHARE_INVITATION_SENT = "share_invitation_sent" const val TYPE_SHARE_INVITATION_ACCEPTED = "share_invitation_accepted" const val TYPE_SHARE_INVITATION_REJECTED = "share_invitation_rejected" const val TYPE_USER_LEFT_PROJECT = "user_left_project" const val TYPE_USER_REMOVED_FROM_PROJECT = "user_removed_from_project" const val TYPE_NOTE_ADDED = "note_added" const val TYPE_ITEM_ASSIGNED = "item_assigned" const val TYPE_ITEM_COMPLETED = "item_completed" const val TYPE_ITEM_UNCOMPLETED = "item_uncompleted" const val TYPE_KARMA_LEVEL = "karma_level" const val TYPE_BIZ_POLICY_DISALLOWED_INVITATION = "biz_policy_disallowed_invitation" const val TYPE_BIZ_POLICY_REJECTED_INVITATION = "biz_policy_rejected_invitation" const val TYPE_BIZ_TRIAL_WILL_END = "biz_trial_will_end" const val TYPE_BIZ_PAYMENT_FAILED = "biz_payment_failed" const val TYPE_BIZ_ACCOUNT_DISABLED = "biz_account_disabled" const val TYPE_BIZ_INVITATION_CREATED = "biz_invitation_created" const val TYPE_BIZ_INVITATION_ACCEPTED = "biz_invitation_accepted" const val TYPE_BIZ_INVITATION_REJECTED = "biz_invitation_rejected" const val STATE_INVITED = "invited" const val STATE_ACCEPTED = "accepted" const val STATE_REJECTED = "rejected" } }
mit
5477a69431d81b6b7cb591b83ef684a3
41.5625
94
0.682452
4.127273
false
false
false
false
konrad-jamrozik/droidmate
dev/droidmate/projects/reporter/src/main/kotlin/org/droidmate/report/AggregateStatsTable.kt
1
2889
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2016 Konrad Jamrozik // // 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/>. // // email: [email protected] // web: www.droidmate.org package org.droidmate.report import com.google.common.collect.Table import org.droidmate.exploration.data_aggregators.IApkExplorationOutput2 class AggregateStatsTable private constructor(val table: Table<Int, String, String>) : Table<Int, String, String> by table { constructor(data: List<IApkExplorationOutput2>) : this(AggregateStatsTable.build(data)) companion object { val headerApkName = "file_name" val headerPackageName = "package_name" val headerExplorationTimeInSeconds = "exploration_seconds" val headerActionsCount = "actions" val headerResetActionsCount = "in_this_reset_actions" val headerViewsSeenCount = "actionable_unique_views_seen_at_least_once" val headerViewsClickedCount = "actionable_unique_views_clicked_or_long_clicked_at_least_once" val headerApisSeenCount = "unique_apis" val headerEventApiPairsSeenCount = "unique_event_api_pairs" val headerException = "exception" fun build(data: List<IApkExplorationOutput2>): Table<Int, String, String> { return buildTable( headers = listOf( headerApkName, headerPackageName, headerExplorationTimeInSeconds, headerActionsCount, headerResetActionsCount, headerViewsSeenCount, headerViewsClickedCount, headerApisSeenCount, headerEventApiPairsSeenCount, headerException ), rowCount = data.size, computeRow = { rowIndex -> val apkData = data[rowIndex] listOf( apkData.apk.fileName, apkData.packageName, apkData.explorationDuration.seconds.toString(), apkData.actions.size.toString(), apkData.resetActionsCount.toString(), apkData.uniqueActionableWidgets.size.toString(), apkData.uniqueClickedWidgets.size.toString(), apkData.uniqueApis.size.toString(), apkData.uniqueEventApiPairs.size.toString(), apkData.exception.toString() ) } ) } } }
gpl-3.0
3a89214fca611470c690b9efa2c4b8af
37.533333
124
0.696781
4.556782
false
false
false
false
dfernandez79/swtlin
builder/src/test/kotlin/swtlin/CompositeTest.kt
1
4435
package swtlin import org.eclipse.swt.SWT import org.eclipse.swt.layout.FillLayout import org.eclipse.swt.layout.FormData import org.eclipse.swt.layout.FormLayout import org.eclipse.swt.widgets.Composite import org.eclipse.swt.widgets.Control import org.eclipse.swt.widgets.Label import org.eclipse.swt.widgets.Shell import org.junit.After import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class CompositeTest { var shell: Shell? = null @Before fun createShell() { shell = Shell() } @After fun disposeShell() { if (shell != null && !shell!!.isDisposed) { shell?.dispose() } } @Test fun `Create empty Composite`() { val result = composite().createControl(shell!!) assertNotNull(result) assertEquals(0, result.children.size) } @Test fun `Create Composite with a Label`() { val result = composite { label { text = "Hello World!" } }.createControl(shell!!) assertEquals(1, result.children.size.toLong()) assertTrue(result.children[0] is Label) assertEquals("Hello World!", (result.children[0] as Label).text) } @Test fun `Create Composite with style`() { val result = composite { style = SWT.NO_FOCUS }.createControl(shell!!) assertTrue(result.style and SWT.NO_FOCUS == SWT.NO_FOCUS) } @Test fun `Create Label with id`() { val refs = mutableMapOf<String, Control>() composite { label("id") { text = "Hello" } }.createControl(shell!!, refs) assertTrue(refs["id"] is Label) assertEquals((refs["id"] as Label).text, "Hello") } @Test fun `Uses FormLayout by default`() { val result = composite().createControl(shell!!) assertTrue(result.layout is FormLayout) } @Test fun `Apply layout to children`() { val refs = mutableMapOf<String, Control>() composite { label("test") { left = 5 top = 5 } }.createControl(shell!!, refs) val testLabel = refs["test"] as Label assertTrue(testLabel.layoutData is FormData) val formData = testLabel.layoutData as FormData assertEquals(5, formData.left.offset) assertEquals(5, formData.top.offset) } @Test fun `Nested composite`() { val refs = mutableMapOf<String, Control>() composite { label("test1") { text = "first" } composite { label("test2") { text = "second" } } }.createControl(shell!!, refs) assertTrue(refs["test1"] is Label) assertEquals("first", (refs["test1"] as Label).text) assertTrue(refs["test2"] is Label) assertEquals("second", (refs["test2"] as Label).text) } @Test fun `Nested composite with id`() { val refs = mutableMapOf<String, Control>() composite { label("test1") { text = "first" } composite("comp") { label("test2") { text = "second" } } }.createControl(shell!!, refs) assertTrue(refs["test1"] is Label) assertEquals("first", (refs["test1"] as Label).text) assertTrue(refs["test2"] is Label) assertEquals("second", (refs["test2"] as Label).text) assertTrue(refs["comp"] is Composite) assertEquals((refs["test2"] as Control).parent, refs["comp"]) } @Test fun `setUp block is executed after creation`() { var ref: Composite? = null val result = composite().also { it.setUp { c -> ref = c } }.createControl(shell!!) assertEquals(result, ref) } @Test fun `Use fillLayout`() { val result = composite { layout = fillLayout() }.createControl(shell!!) assertTrue(result.layout is FillLayout) } // // @Test // fun `Dispose disposable resources on dispose`() { // val result = composite { // background = rgba(128, 128, 128, 1) // }.createControl(shell!!) // // val createdColor = result.background // shell?.dispose() // assertTrue(createdColor.isDisposed) // } }
apache-2.0
a0fc178a7132cf08b4f5d11c12bb2bb3
25.39881
72
0.570011
4.285024
false
true
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/voice/LorittaAudioProvider.kt
1
1895
package net.perfectdreams.loritta.cinnamon.discord.voice import dev.kord.common.annotation.KordVoice import dev.kord.voice.AudioFrame import dev.kord.voice.AudioProvider import kotlinx.coroutines.channels.Channel @OptIn(KordVoice::class) class LorittaAudioProvider(private val audioClipProviderNotificationChannel: Channel<Unit>) : AudioProvider { companion object { val SILENCE = AudioFrame(byteArrayOf()) // While Kord does have a "SILENCE", it shows the "Speaking" indicator } var audioFramesInOpusFormatQueue = Channel<ByteArray>(Channel.UNLIMITED) var requestedNewAudioTracks = false override suspend fun provide(): AudioFrame { val audioDataInOpusFormatTryReceive = audioFramesInOpusFormatQueue.tryReceive() if (audioDataInOpusFormatTryReceive.isFailure) { if (requestedNewAudioTracks) // We already tried requesting it, so now we will wait... return SILENCE // isFailure == empty, then we need to request moar framez!! :3 audioClipProviderNotificationChannel.send(Unit) // Send a moar framez!! request... requestedNewAudioTracks = true // And then return SILENCE for now return SILENCE } // If it is closed... then why are we here? if (audioDataInOpusFormatTryReceive.isClosed) return SILENCE requestedNewAudioTracks = false return AudioFrame(audioDataInOpusFormatTryReceive.getOrNull()!!) } /** * Appends the [audioFramesInOpusFormat] in the current audio provider to the end of the [audioFramesInOpusFormat] queue * * @param audioFramesInOpusFormat the Opus audio frames */ suspend fun queue(audioFramesInOpusFormat: List<ByteArray>) { for (frame in audioFramesInOpusFormat) { this.audioFramesInOpusFormatQueue.send(frame) } } }
agpl-3.0
97caf0161ec43badc985d39e551a8bce
36.92
124
0.702375
4.871465
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/utils/EncodeCommand.kt
1
3277
package net.perfectdreams.loritta.morenitta.commands.vanilla.utils import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.common.locale.LocaleStringData import net.perfectdreams.loritta.morenitta.utils.stripCodeMarks import net.perfectdreams.loritta.common.commands.ArgumentType import net.perfectdreams.loritta.common.commands.arguments import net.perfectdreams.loritta.morenitta.messages.LorittaReply import org.apache.commons.codec.digest.DigestUtils import java.util.* import net.perfectdreams.loritta.morenitta.LorittaBot class EncodeCommand(loritta: LorittaBot) : AbstractCommand(loritta, "encode", listOf("codificar", "encrypt", "criptografar", "hash"), net.perfectdreams.loritta.common.commands.CommandCategory.UTILS) { override fun getDescriptionKey() = LocaleKeyData( "commands.command.encode.description", listOf( LocaleStringData( listOf("md2", "md5", "sha1", "sha256", "sha384", "sha512", "rot13", "uuid", "base64").joinToString(", ", transform = { "`$it`" }) ) ) ) override fun getExamplesKey() = LocaleKeyData("commands.command.encode.examples") // TODO: Fix Detailed Usage override fun getUsage() = arguments { argument(ArgumentType.TEXT) {} argument(ArgumentType.TEXT) {} } override suspend fun run(context: CommandContext, locale: BaseLocale) { val args = context.rawArgs.toMutableList() val encodeMode = context.rawArgs.getOrNull(0)?.toLowerCase() if (encodeMode == null) { context.explain() return } args.removeAt(0) val text = args.joinToString(" ") if (text.isEmpty()) { context.explain() return } val encodedText = when (encodeMode) { "md2" -> DigestUtils.md2Hex(text) "md5" -> DigestUtils.md5Hex(text) "sha1" -> DigestUtils.sha1Hex(text) "sha256" -> DigestUtils.sha256Hex(text) "sha384" -> DigestUtils.sha384Hex(text) "sha512" -> DigestUtils.sha512Hex(text) "rot13" -> rot13(text) "uuid" -> UUID.nameUUIDFromBytes(text.toByteArray(Charsets.UTF_8)).toString() "base64" -> { val b64 = Base64.getEncoder().encode(text.toByteArray(Charsets.UTF_8)) String(b64) } else -> null } if (encodedText == null) { context.reply( locale["commands.command.encode.invalidMethod", encodeMode.stripCodeMarks()], Constants.ERROR ) return } context.reply( true, LorittaReply( "**${locale["commands.command.encode.originalText"]}:** `${text.stripCodeMarks()}`", "\uD83D\uDCC4", mentionUser = false ), LorittaReply( "**${locale["commands.command.encode.encodedText"]}:** `${encodedText.stripCodeMarks()}`", "<:blobspy:465979979876794368>", mentionUser = false ) ) } fun rot13(input: String): String { val sb = StringBuilder() for (i in 0 until input.length) { var c = input[i] if (c in 'a'..'m') c += 13 else if (c in 'A'..'M') c += 13 else if (c in 'n'..'z') c -= 13 else if (c in 'N'..'Z') c -= 13 sb.append(c) } return sb.toString() } }
agpl-3.0
b5cbc195ebf690c3ee2ebb6e869453f7
29.924528
200
0.69942
3.424242
false
false
false
false
signed/intellij-community
java/java-impl/src/com/intellij/codeInsight/hints/JavaInlayParameterHintsProvider.kt
1
3962
/* * 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 com.intellij.codeInsight.hints import com.intellij.codeInsight.hints.HintInfo.MethodInfo import com.intellij.lang.java.JavaLanguage import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiCallExpression import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod class JavaInlayParameterHintsProvider : InlayParameterHintsProvider { companion object { fun getInstance() = InlayParameterHintsExtension.forLanguage(JavaLanguage.INSTANCE) as JavaInlayParameterHintsProvider } override fun getHintInfo(element: PsiElement): MethodInfo? { if (element is PsiCallExpression) { val resolvedElement = element.resolveMethodGenerics().element if (resolvedElement is PsiMethod) { return getMethodInfo(resolvedElement) } } return null } override fun getParameterHints(element: PsiElement): List<InlayInfo> { if (element is PsiCallExpression) { return JavaInlayHintsProvider.createHints(element).toList() } return emptyList() } fun getMethodInfo(method: PsiMethod): MethodInfo? { val containingClass = method.containingClass ?: return null val fullMethodName = StringUtil.getQualifiedName(containingClass.qualifiedName, method.name) val paramNames: List<String> = method.parameterList.parameters.map { it.name ?: "" } return MethodInfo(fullMethodName, paramNames) } override fun getDefaultBlackList() = defaultBlackList private val defaultBlackList = setOf( "(begin*, end*)", "(start*, end*)", "(first*, last*)", "(first*, second*)", "(from*, to*)", "(min*, max*)", "(key, value)", "(format, arg*)", "(message)", "(message, error)", "*Exception", "*.set*(*)", "*.add(*)", "*.set(*,*)", "*.get(*)", "*.create(*)", "*.getProperty(*)", "*.setProperty(*,*)", "*.print(*)", "*.println(*)", "*.append(*)", "*.charAt(*)", "*.indexOf(*)", "*.contains(*)", "*.startsWith(*)", "*.endsWith(*)", "*.equals(*)", "*.equal(*)", "java.lang.Math.*", "org.slf4j.Logger.*", "*.singleton(*)", "*.singletonList(*)", "*.Set.of", "*.ImmutableList.of", "*.ImmutableMultiset.of", "*.ImmutableSortedMultiset.of", "*.ImmutableSortedSet.of" ) val isDoNotShowIfMethodNameContainsParameterName = Option("java.method.name.contains.parameter.name", "Do not show if method name contains parameter name", true) val isShowForParamsWithSameType = Option("java.multiple.params.same.type", "Show for non-literals in case of multiple params with the same type", false) val isDoNotShowForBuilderLikeMethods = Option("java.build.like.method", "Do not show for builder-like methods", true) override fun getSupportedOptions(): List<Option> { return listOf( isDoNotShowIfMethodNameContainsParameterName, isShowForParamsWithSameType, isDoNotShowForBuilderLikeMethods ) } }
apache-2.0
512b5b609f18be000d7849e1bdd79066
31.483607
122
0.613579
5.021546
false
false
false
false
LorittaBot/Loritta
common/src/commonMain/kotlin/net/perfectdreams/loritta/common/utils/GACampaigns.kt
1
3498
package net.perfectdreams.loritta.common.utils import io.ktor.http.* import net.perfectdreams.i18nhelper.core.keydata.StringI18nData import net.perfectdreams.loritta.i18n.I18nKeysData /** * Google Analytics' campaigns to track where users are coming from */ object GACampaigns { fun sonhosBundlesUpsellDiscordMessage( lorittaWebsiteUrl: String, medium: String, campaignContent: String ): StringI18nData { return I18nKeysData.Commands.WantingMoreSonhosBundlesUpsell(sonhosBundlesUpsellDiscordMessageUrl(lorittaWebsiteUrl, medium, campaignContent)) } fun sonhosBundlesUpsellDiscordMessageUrl( lorittaWebsiteUrl: String, medium: String, campaignContent: String ): String { return "<${sonhosBundlesUpsellUrl(lorittaWebsiteUrl, "discord", medium, "sonhos-bundles-upsell", campaignContent)}>" } fun sonhosBundlesUpsellUrl( lorittaWebsiteUrl: String, source: String, medium: String, campaignName: String, campaignContent: String ): String { return "${lorittaWebsiteUrl}user/@me/dashboard/bundles?utm_source=$source&utm_medium=$medium&utm_campaign=$campaignName&utm_content=$campaignContent" } fun premiumUpsellDiscordMessageUrl( lorittaWebsiteUrl: String, medium: String, campaignContent: String ): String { return "<${premiumUpsellDiscordCampaignUrl(lorittaWebsiteUrl, medium, campaignContent)}>" } fun premiumUpsellDiscordCampaignUrl( lorittaWebsiteUrl: String, medium: String, campaignContent: String ): String { return premiumUrl(lorittaWebsiteUrl, "discord", medium, "premium-upsell", campaignContent) } fun premiumUrl( lorittaWebsiteUrl: String, source: String, medium: String, campaignName: String, campaignContent: String ): String { return "${lorittaWebsiteUrl}donate?utm_source=$source&utm_medium=$medium&utm_campaign=$campaignName&utm_content=$campaignContent" } fun dailyWebRewardDiscordCampaignUrl( lorittaWebsiteUrl: String, medium: String, campaignContent: String ): String { return dailyUrl(lorittaWebsiteUrl, "discord", medium, "daily-web-reward", campaignContent) } fun dailyUrl( lorittaWebsiteUrl: String, source: String, medium: String, campaignName: String, campaignContent: String ): String { return "${lorittaWebsiteUrl}daily?utm_source=$source&utm_medium=$medium&utm_campaign=$campaignName&utm_content=$campaignContent" } fun patchNotesUrl( lorittaWebsiteUrl: String, websiteLocaleId: String, path: String, source: String, medium: String, campaignName: String, campaignContent: String ): String { return "${lorittaWebsiteUrl}$websiteLocaleId$path?utm_source=$source&utm_medium=$medium&utm_campaign=$campaignName&utm_content=$campaignContent" } fun createUrlWithCampaign( url: String, source: String, medium: String, campaignName: String, campaignContent: String ) = URLBuilder(url) .apply { parameters.append("utm_source", source) parameters.append("utm_medium", medium) parameters.append("utm_campaign", campaignName) parameters.append("utm_content", campaignContent) }.build() }
agpl-3.0
5dd587498cdb29af4543ccca9bf1c785
32.009434
157
0.671812
4.940678
false
false
false
false
Jachu5/Koans
src/i_introduction/_7_Data_Classes/DataClasses.kt
1
1566
package i_introduction._7_Data_Classes import util.TODO class Person1(val name: String, val age: Int) //no 'new' keyword fun create() = Person1("James Gosling", 58) fun useFromJava() { // property 'val name' = backing field + getter // => from Java you access it through 'getName()' JavaCode7().useKotlinClass(Person1("Martin Odersky", 55)) // property 'var mutable' = backing field + getter + setter } // It's the same as the following (getters are generated by default): class Person2(_name: String, _age: Int) { //_name, _age are constructor parameters val name: String = _name //property initialization is the part of constructor get(): String { return $name // you can access the backing field of property with '$' + property name } val age: Int = _age get(): Int { return $age } } // If you add annotation 'data' for your class, some additional methods will be generated for you // like 'equals', 'hashCode', 'toString'. data class Person3(val name: String, val age: Int) // This class is as good as Person4 (written in Java), 42 lines shorter. =) fun todoTask7() = TODO( """ There is no task for you here. Just make sure you're not forgetting to read carefully all code examples and comments and ask questions if you have any. =) Then return 'true' from 'task7'. More information about classes in kotlin can be found in syntax/classesObjectsInterfaces.kt """, references = { JavaCode7.Person4("???", -1) } ) fun task7(): Boolean = true
mit
f089d209d677c341cd12663a701cb56d
31.645833
99
0.662835
3.934673
false
false
false
false
cketti/okhttp
okhttp/src/main/kotlin/okhttp3/internal/cache/DiskLruCache.kt
1
35073
/* * Copyright (C) 2011 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 okhttp3.internal.cache import java.io.Closeable import java.io.EOFException import java.io.File import java.io.FileNotFoundException import java.io.Flushable import java.io.IOException import java.util.ArrayList import java.util.LinkedHashMap import java.util.NoSuchElementException import okhttp3.internal.assertThreadHoldsLock import okhttp3.internal.cache.DiskLruCache.Editor import okhttp3.internal.closeQuietly import okhttp3.internal.concurrent.Task import okhttp3.internal.concurrent.TaskRunner import okhttp3.internal.io.FileSystem import okhttp3.internal.isCivilized import okhttp3.internal.okHttpName import okhttp3.internal.platform.Platform import okhttp3.internal.platform.Platform.Companion.WARN import okio.BufferedSink import okio.ForwardingSource import okio.Sink import okio.Source import okio.blackholeSink import okio.buffer /** * A cache that uses a bounded amount of space on a filesystem. Each cache entry has a string key * and a fixed number of values. Each key must match the regex `[a-z0-9_-]{1,64}`. Values are byte * sequences, accessible as streams or files. Each value must be between `0` and `Int.MAX_VALUE` * bytes in length. * * The cache stores its data in a directory on the filesystem. This directory must be exclusive to * the cache; the cache may delete or overwrite files from its directory. It is an error for * multiple processes to use the same cache directory at the same time. * * This cache limits the number of bytes that it will store on the filesystem. When the number of * stored bytes exceeds the limit, the cache will remove entries in the background until the limit * is satisfied. The limit is not strict: the cache may temporarily exceed it while waiting for * files to be deleted. The limit does not include filesystem overhead or the cache journal so * space-sensitive applications should set a conservative limit. * * Clients call [edit] to create or update the values of an entry. An entry may have only one editor * at one time; if a value is not available to be edited then [edit] will return null. * * * When an entry is being **created** it is necessary to supply a full set of values; the empty * value should be used as a placeholder if necessary. * * * When an entry is being **edited**, it is not necessary to supply data for every value; values * default to their previous value. * * Every [edit] call must be matched by a call to [Editor.commit] or [Editor.abort]. Committing is * atomic: a read observes the full set of values as they were before or after the commit, but never * a mix of values. * * Clients call [get] to read a snapshot of an entry. The read will observe the value at the time * that [get] was called. Updates and removals after the call do not impact ongoing reads. * * This class is tolerant of some I/O errors. If files are missing from the filesystem, the * corresponding entries will be dropped from the cache. If an error occurs while writing a cache * value, the edit will fail silently. Callers should handle other problems by catching * `IOException` and responding appropriately. * * @constructor Create a cache which will reside in [directory]. This cache is lazily initialized on * first access and will be created if it does not exist. * @param directory a writable directory. * @param valueCount the number of values per cache entry. Must be positive. * @param maxSize the maximum number of bytes this cache should use to store. */ class DiskLruCache internal constructor( internal val fileSystem: FileSystem, /** Returns the directory where this cache stores its data. */ val directory: File, private val appVersion: Int, internal val valueCount: Int, /** Returns the maximum number of bytes that this cache should use to store its data. */ maxSize: Long, /** Used for asynchronous journal rebuilds. */ taskRunner: TaskRunner ) : Closeable, Flushable { /** The maximum number of bytes that this cache should use to store its data. */ @get:Synchronized @set:Synchronized var maxSize: Long = maxSize set(value) { field = value if (initialized) { cleanupQueue.schedule(cleanupTask) // Trim the existing store if necessary. } } /* * This cache uses a journal file named "journal". A typical journal file looks like this: * * libcore.io.DiskLruCache * 1 * 100 * 2 * * CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054 * DIRTY 335c4c6028171cfddfbaae1a9c313c52 * CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342 * REMOVE 335c4c6028171cfddfbaae1a9c313c52 * DIRTY 1ab96a171faeeee38496d8b330771a7a * CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234 * READ 335c4c6028171cfddfbaae1a9c313c52 * READ 3400330d1dfc7f3f7f4b8d4d803dfcf6 * * The first five lines of the journal form its header. They are the constant string * "libcore.io.DiskLruCache", the disk cache's version, the application's version, the value * count, and a blank line. * * Each of the subsequent lines in the file is a record of the state of a cache entry. Each line * contains space-separated values: a state, a key, and optional state-specific values. * * o DIRTY lines track that an entry is actively being created or updated. Every successful * DIRTY action should be followed by a CLEAN or REMOVE action. DIRTY lines without a matching * CLEAN or REMOVE indicate that temporary files may need to be deleted. * * o CLEAN lines track a cache entry that has been successfully published and may be read. A * publish line is followed by the lengths of each of its values. * * o READ lines track accesses for LRU. * * o REMOVE lines track entries that have been deleted. * * The journal file is appended to as cache operations occur. The journal may occasionally be * compacted by dropping redundant lines. A temporary file named "journal.tmp" will be used during * compaction; that file should be deleted if it exists when the cache is opened. */ private val journalFile: File private val journalFileTmp: File private val journalFileBackup: File private var size: Long = 0L private var journalWriter: BufferedSink? = null internal val lruEntries = LinkedHashMap<String, Entry>(0, 0.75f, true) private var redundantOpCount: Int = 0 private var hasJournalErrors: Boolean = false private var civilizedFileSystem: Boolean = false // Must be read and written when synchronized on 'this'. private var initialized: Boolean = false internal var closed: Boolean = false private var mostRecentTrimFailed: Boolean = false private var mostRecentRebuildFailed: Boolean = false /** * To differentiate between old and current snapshots, each entry is given a sequence number each * time an edit is committed. A snapshot is stale if its sequence number is not equal to its * entry's sequence number. */ private var nextSequenceNumber: Long = 0 private val cleanupQueue = taskRunner.newQueue() private val cleanupTask = object : Task("$okHttpName Cache") { override fun runOnce(): Long { synchronized(this@DiskLruCache) { if (!initialized || closed) { return -1L // Nothing to do. } try { trimToSize() } catch (_: IOException) { mostRecentTrimFailed = true } try { if (journalRebuildRequired()) { rebuildJournal() redundantOpCount = 0 } } catch (_: IOException) { mostRecentRebuildFailed = true journalWriter = blackholeSink().buffer() } return -1L } } } init { require(maxSize > 0L) { "maxSize <= 0" } require(valueCount > 0) { "valueCount <= 0" } this.journalFile = File(directory, JOURNAL_FILE) this.journalFileTmp = File(directory, JOURNAL_FILE_TEMP) this.journalFileBackup = File(directory, JOURNAL_FILE_BACKUP) } @Synchronized @Throws(IOException::class) fun initialize() { this.assertThreadHoldsLock() if (initialized) { return // Already initialized. } // If a bkp file exists, use it instead. if (fileSystem.exists(journalFileBackup)) { // If journal file also exists just delete backup file. if (fileSystem.exists(journalFile)) { fileSystem.delete(journalFileBackup) } else { fileSystem.rename(journalFileBackup, journalFile) } } civilizedFileSystem = fileSystem.isCivilized(journalFileBackup) // Prefer to pick up where we left off. if (fileSystem.exists(journalFile)) { try { readJournal() processJournal() initialized = true return } catch (journalIsCorrupt: IOException) { Platform.get().log( "DiskLruCache $directory is corrupt: ${journalIsCorrupt.message}, removing", WARN, journalIsCorrupt) } // The cache is corrupted, attempt to delete the contents of the directory. This can throw and // we'll let that propagate out as it likely means there is a severe filesystem problem. try { delete() } finally { closed = false } } rebuildJournal() initialized = true } @Throws(IOException::class) private fun readJournal() { fileSystem.source(journalFile).buffer().use { source -> val magic = source.readUtf8LineStrict() val version = source.readUtf8LineStrict() val appVersionString = source.readUtf8LineStrict() val valueCountString = source.readUtf8LineStrict() val blank = source.readUtf8LineStrict() if (MAGIC != magic || VERSION_1 != version || appVersion.toString() != appVersionString || valueCount.toString() != valueCountString || blank.isNotEmpty()) { throw IOException( "unexpected journal header: [$magic, $version, $valueCountString, $blank]") } var lineCount = 0 while (true) { try { readJournalLine(source.readUtf8LineStrict()) lineCount++ } catch (_: EOFException) { break // End of journal. } } redundantOpCount = lineCount - lruEntries.size // If we ended on a truncated line, rebuild the journal before appending to it. if (!source.exhausted()) { rebuildJournal() } else { journalWriter = newJournalWriter() } } } @Throws(FileNotFoundException::class) private fun newJournalWriter(): BufferedSink { val fileSink = fileSystem.appendingSink(journalFile) val faultHidingSink = FaultHidingSink(fileSink) { [email protected]() hasJournalErrors = true } return faultHidingSink.buffer() } @Throws(IOException::class) private fun readJournalLine(line: String) { val firstSpace = line.indexOf(' ') if (firstSpace == -1) throw IOException("unexpected journal line: $line") val keyBegin = firstSpace + 1 val secondSpace = line.indexOf(' ', keyBegin) val key: String if (secondSpace == -1) { key = line.substring(keyBegin) if (firstSpace == REMOVE.length && line.startsWith(REMOVE)) { lruEntries.remove(key) return } } else { key = line.substring(keyBegin, secondSpace) } var entry: Entry? = lruEntries[key] if (entry == null) { entry = Entry(key) lruEntries[key] = entry } when { secondSpace != -1 && firstSpace == CLEAN.length && line.startsWith(CLEAN) -> { val parts = line.substring(secondSpace + 1) .split(' ') entry.readable = true entry.currentEditor = null entry.setLengths(parts) } secondSpace == -1 && firstSpace == DIRTY.length && line.startsWith(DIRTY) -> { entry.currentEditor = Editor(entry) } secondSpace == -1 && firstSpace == READ.length && line.startsWith(READ) -> { // This work was already done by calling lruEntries.get(). } else -> throw IOException("unexpected journal line: $line") } } /** * Computes the initial size and collects garbage as a part of opening the cache. Dirty entries * are assumed to be inconsistent and will be deleted. */ @Throws(IOException::class) private fun processJournal() { fileSystem.delete(journalFileTmp) val i = lruEntries.values.iterator() while (i.hasNext()) { val entry = i.next() if (entry.currentEditor == null) { for (t in 0 until valueCount) { size += entry.lengths[t] } } else { entry.currentEditor = null for (t in 0 until valueCount) { fileSystem.delete(entry.cleanFiles[t]) fileSystem.delete(entry.dirtyFiles[t]) } i.remove() } } } /** * Creates a new journal that omits redundant information. This replaces the current journal if it * exists. */ @Synchronized @Throws(IOException::class) internal fun rebuildJournal() { journalWriter?.close() fileSystem.sink(journalFileTmp).buffer().use { sink -> sink.writeUtf8(MAGIC).writeByte('\n'.toInt()) sink.writeUtf8(VERSION_1).writeByte('\n'.toInt()) sink.writeDecimalLong(appVersion.toLong()).writeByte('\n'.toInt()) sink.writeDecimalLong(valueCount.toLong()).writeByte('\n'.toInt()) sink.writeByte('\n'.toInt()) for (entry in lruEntries.values) { if (entry.currentEditor != null) { sink.writeUtf8(DIRTY).writeByte(' '.toInt()) sink.writeUtf8(entry.key) sink.writeByte('\n'.toInt()) } else { sink.writeUtf8(CLEAN).writeByte(' '.toInt()) sink.writeUtf8(entry.key) entry.writeLengths(sink) sink.writeByte('\n'.toInt()) } } } if (fileSystem.exists(journalFile)) { fileSystem.rename(journalFile, journalFileBackup) } fileSystem.rename(journalFileTmp, journalFile) fileSystem.delete(journalFileBackup) journalWriter = newJournalWriter() hasJournalErrors = false mostRecentRebuildFailed = false } /** * Returns a snapshot of the entry named [key], or null if it doesn't exist is not currently * readable. If a value is returned, it is moved to the head of the LRU queue. */ @Synchronized @Throws(IOException::class) operator fun get(key: String): Snapshot? { initialize() checkNotClosed() validateKey(key) val entry = lruEntries[key] ?: return null val snapshot = entry.snapshot() ?: return null redundantOpCount++ journalWriter!!.writeUtf8(READ) .writeByte(' '.toInt()) .writeUtf8(key) .writeByte('\n'.toInt()) if (journalRebuildRequired()) { cleanupQueue.schedule(cleanupTask) } return snapshot } /** Returns an editor for the entry named [key], or null if another edit is in progress. */ @Synchronized @Throws(IOException::class) @JvmOverloads fun edit(key: String, expectedSequenceNumber: Long = ANY_SEQUENCE_NUMBER): Editor? { initialize() checkNotClosed() validateKey(key) var entry: Entry? = lruEntries[key] if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER && (entry == null || entry.sequenceNumber != expectedSequenceNumber)) { return null // Snapshot is stale. } if (entry?.currentEditor != null) { return null // Another edit is in progress. } if (entry != null && entry.lockingSourceCount != 0) { return null // We can't write this file because a reader is still reading it. } if (mostRecentTrimFailed || mostRecentRebuildFailed) { // The OS has become our enemy! If the trim job failed, it means we are storing more data than // requested by the user. Do not allow edits so we do not go over that limit any further. If // the journal rebuild failed, the journal writer will not be active, meaning we will not be // able to record the edit, causing file leaks. In both cases, we want to retry the clean up // so we can get out of this state! cleanupQueue.schedule(cleanupTask) return null } // Flush the journal before creating files to prevent file leaks. val journalWriter = this.journalWriter!! journalWriter.writeUtf8(DIRTY) .writeByte(' '.toInt()) .writeUtf8(key) .writeByte('\n'.toInt()) journalWriter.flush() if (hasJournalErrors) { return null // Don't edit; the journal can't be written. } if (entry == null) { entry = Entry(key) lruEntries[key] = entry } val editor = Editor(entry) entry.currentEditor = editor return editor } /** * Returns the number of bytes currently being used to store the values in this cache. This may be * greater than the max size if a background deletion is pending. */ @Synchronized @Throws(IOException::class) fun size(): Long { initialize() return size } @Synchronized @Throws(IOException::class) internal fun completeEdit(editor: Editor, success: Boolean) { val entry = editor.entry check(entry.currentEditor == editor) // If this edit is creating the entry for the first time, every index must have a value. if (success && !entry.readable) { for (i in 0 until valueCount) { if (!editor.written!![i]) { editor.abort() throw IllegalStateException("Newly created entry didn't create value for index $i") } if (!fileSystem.exists(entry.dirtyFiles[i])) { editor.abort() return } } } for (i in 0 until valueCount) { val dirty = entry.dirtyFiles[i] if (success && !entry.zombie) { if (fileSystem.exists(dirty)) { val clean = entry.cleanFiles[i] fileSystem.rename(dirty, clean) val oldLength = entry.lengths[i] val newLength = fileSystem.size(clean) entry.lengths[i] = newLength size = size - oldLength + newLength } } else { fileSystem.delete(dirty) } } entry.currentEditor = null if (entry.zombie) { removeEntry(entry) return } redundantOpCount++ journalWriter!!.apply { if (entry.readable || success) { entry.readable = true writeUtf8(CLEAN).writeByte(' '.toInt()) writeUtf8(entry.key) entry.writeLengths(this) writeByte('\n'.toInt()) if (success) { entry.sequenceNumber = nextSequenceNumber++ } } else { lruEntries.remove(entry.key) writeUtf8(REMOVE).writeByte(' '.toInt()) writeUtf8(entry.key) writeByte('\n'.toInt()) } flush() } if (size > maxSize || journalRebuildRequired()) { cleanupQueue.schedule(cleanupTask) } } /** * We only rebuild the journal when it will halve the size of the journal and eliminate at least * 2000 ops. */ private fun journalRebuildRequired(): Boolean { val redundantOpCompactThreshold = 2000 return redundantOpCount >= redundantOpCompactThreshold && redundantOpCount >= lruEntries.size } /** * Drops the entry for [key] if it exists and can be removed. If the entry for [key] is currently * being edited, that edit will complete normally but its value will not be stored. * * @return true if an entry was removed. */ @Synchronized @Throws(IOException::class) fun remove(key: String): Boolean { initialize() checkNotClosed() validateKey(key) val entry = lruEntries[key] ?: return false val removed = removeEntry(entry) if (removed && size <= maxSize) mostRecentTrimFailed = false return removed } @Throws(IOException::class) internal fun removeEntry(entry: Entry): Boolean { // If we can't delete files that are still open, mark this entry as a zombie so its files will // be deleted when those files are closed. if (!civilizedFileSystem) { if (entry.lockingSourceCount > 0) { // Mark this entry as 'DIRTY' so that if the process crashes this entry won't be used. journalWriter?.let { it.writeUtf8(DIRTY) it.writeByte(' '.toInt()) it.writeUtf8(entry.key) it.writeByte('\n'.toInt()) it.flush() } } if (entry.lockingSourceCount > 0 || entry.currentEditor != null) { entry.zombie = true return true } } entry.currentEditor?.detach() // Prevent the edit from completing normally. for (i in 0 until valueCount) { fileSystem.delete(entry.cleanFiles[i]) size -= entry.lengths[i] entry.lengths[i] = 0 } redundantOpCount++ journalWriter?.let { it.writeUtf8(REMOVE) it.writeByte(' '.toInt()) it.writeUtf8(entry.key) it.writeByte('\n'.toInt()) } lruEntries.remove(entry.key) if (journalRebuildRequired()) { cleanupQueue.schedule(cleanupTask) } return true } @Synchronized private fun checkNotClosed() { check(!closed) { "cache is closed" } } /** Force buffered operations to the filesystem. */ @Synchronized @Throws(IOException::class) override fun flush() { if (!initialized) return checkNotClosed() trimToSize() journalWriter!!.flush() } @Synchronized fun isClosed(): Boolean = closed /** Closes this cache. Stored values will remain on the filesystem. */ @Synchronized @Throws(IOException::class) override fun close() { if (!initialized || closed) { closed = true return } // Copying for concurrent iteration. for (entry in lruEntries.values.toTypedArray()) { if (entry.currentEditor != null) { entry.currentEditor?.detach() // Prevent the edit from completing normally. } } trimToSize() journalWriter!!.close() journalWriter = null closed = true } @Throws(IOException::class) fun trimToSize() { while (size > maxSize) { if (!removeOldestEntry()) return } mostRecentTrimFailed = false } /** Returns true if an entry was removed. This will return false if all entries are zombies. */ private fun removeOldestEntry(): Boolean { for (toEvict in lruEntries.values) { if (!toEvict.zombie) { removeEntry(toEvict) return true } } return false } /** * Closes the cache and deletes all of its stored values. This will delete all files in the cache * directory including files that weren't created by the cache. */ @Throws(IOException::class) fun delete() { close() fileSystem.deleteContents(directory) } /** * Deletes all stored values from the cache. In-flight edits will complete normally but their * values will not be stored. */ @Synchronized @Throws(IOException::class) fun evictAll() { initialize() // Copying for concurrent iteration. for (entry in lruEntries.values.toTypedArray()) { removeEntry(entry) } mostRecentTrimFailed = false } private fun validateKey(key: String) { require(LEGAL_KEY_PATTERN.matches(key)) { "keys must match regex [a-z0-9_-]{1,120}: \"$key\"" } } /** * Returns an iterator over the cache's current entries. This iterator doesn't throw * `ConcurrentModificationException`, but if new entries are added while iterating, those new * entries will not be returned by the iterator. If existing entries are removed during iteration, * they will be absent (unless they were already returned). * * If there are I/O problems during iteration, this iterator fails silently. For example, if the * hosting filesystem becomes unreachable, the iterator will omit elements rather than throwing * exceptions. * * **The caller must [close][Snapshot.close]** each snapshot returned by [Iterator.next]. Failing * to do so leaks open files! */ @Synchronized @Throws(IOException::class) fun snapshots(): MutableIterator<Snapshot> { initialize() return object : MutableIterator<Snapshot> { /** Iterate a copy of the entries to defend against concurrent modification errors. */ private val delegate = ArrayList(lruEntries.values).iterator() /** The snapshot to return from [next]. Null if we haven't computed that yet. */ private var nextSnapshot: Snapshot? = null /** The snapshot to remove with [remove]. Null if removal is illegal. */ private var removeSnapshot: Snapshot? = null override fun hasNext(): Boolean { if (nextSnapshot != null) return true synchronized(this@DiskLruCache) { // If the cache is closed, truncate the iterator. if (closed) return false while (delegate.hasNext()) { nextSnapshot = delegate.next()?.snapshot() ?: continue return true } } return false } override fun next(): Snapshot { if (!hasNext()) throw NoSuchElementException() removeSnapshot = nextSnapshot nextSnapshot = null return removeSnapshot!! } override fun remove() { val removeSnapshot = this.removeSnapshot checkNotNull(removeSnapshot) { "remove() before next()" } try { [email protected](removeSnapshot.key()) } catch (_: IOException) { // Nothing useful to do here. We failed to remove from the cache. Most likely that's // because we couldn't update the journal, but the cached entry will still be gone. } finally { this.removeSnapshot = null } } } } /** A snapshot of the values for an entry. */ inner class Snapshot internal constructor( private val key: String, private val sequenceNumber: Long, private val sources: List<Source>, private val lengths: LongArray ) : Closeable { fun key(): String = key /** * Returns an editor for this snapshot's entry, or null if either the entry has changed since * this snapshot was created or if another edit is in progress. */ @Throws(IOException::class) fun edit(): Editor? = [email protected](key, sequenceNumber) /** Returns the unbuffered stream with the value for [index]. */ fun getSource(index: Int): Source = sources[index] /** Returns the byte length of the value for [index]. */ fun getLength(index: Int): Long = lengths[index] override fun close() { for (source in sources) { source.closeQuietly() } } } /** Edits the values for an entry. */ inner class Editor internal constructor(internal val entry: Entry) { internal val written: BooleanArray? = if (entry.readable) null else BooleanArray(valueCount) private var done: Boolean = false /** * Prevents this editor from completing normally. This is necessary either when the edit causes * an I/O error, or if the target entry is evicted while this editor is active. In either case * we delete the editor's created files and prevent new files from being created. Note that once * an editor has been detached it is possible for another editor to edit the entry. */ internal fun detach() { if (entry.currentEditor == this) { if (civilizedFileSystem) { completeEdit(this, false) // Delete it now. } else { entry.zombie = true // We can't delete it until the current edit completes. } } } /** * Returns an unbuffered input stream to read the last committed value, or null if no value has * been committed. */ fun newSource(index: Int): Source? { synchronized(this@DiskLruCache) { check(!done) if (!entry.readable || entry.currentEditor != this || entry.zombie) { return null } return try { fileSystem.source(entry.cleanFiles[index]) } catch (_: FileNotFoundException) { null } } } /** * Returns a new unbuffered output stream to write the value at [index]. If the underlying * output stream encounters errors when writing to the filesystem, this edit will be aborted * when [commit] is called. The returned output stream does not throw IOExceptions. */ fun newSink(index: Int): Sink { synchronized(this@DiskLruCache) { check(!done) if (entry.currentEditor != this) { return blackholeSink() } if (!entry.readable) { written!![index] = true } val dirtyFile = entry.dirtyFiles[index] val sink: Sink try { sink = fileSystem.sink(dirtyFile) } catch (_: FileNotFoundException) { return blackholeSink() } return FaultHidingSink(sink) { synchronized(this@DiskLruCache) { detach() } } } } /** * Commits this edit so it is visible to readers. This releases the edit lock so another edit * may be started on the same key. */ @Throws(IOException::class) fun commit() { synchronized(this@DiskLruCache) { check(!done) if (entry.currentEditor == this) { completeEdit(this, true) } done = true } } /** * Aborts this edit. This releases the edit lock so another edit may be started on the same * key. */ @Throws(IOException::class) fun abort() { synchronized(this@DiskLruCache) { check(!done) if (entry.currentEditor == this) { completeEdit(this, false) } done = true } } } internal inner class Entry internal constructor( internal val key: String ) { /** Lengths of this entry's files. */ internal val lengths: LongArray = LongArray(valueCount) internal val cleanFiles = mutableListOf<File>() internal val dirtyFiles = mutableListOf<File>() /** True if this entry has ever been published. */ internal var readable: Boolean = false /** True if this entry must be deleted when the current edit or read completes. */ internal var zombie: Boolean = false /** * The ongoing edit or null if this entry is not being edited. When setting this to null the * entry must be removed if it is a zombie. */ internal var currentEditor: Editor? = null /** * Sources currently reading this entry before a write or delete can proceed. When decrementing * this to zero, the entry must be removed if it is a zombie. */ internal var lockingSourceCount = 0 /** The sequence number of the most recently committed edit to this entry. */ internal var sequenceNumber: Long = 0 init { // The names are repetitive so re-use the same builder to avoid allocations. val fileBuilder = StringBuilder(key).append('.') val truncateTo = fileBuilder.length for (i in 0 until valueCount) { fileBuilder.append(i) cleanFiles += File(directory, fileBuilder.toString()) fileBuilder.append(".tmp") dirtyFiles += File(directory, fileBuilder.toString()) fileBuilder.setLength(truncateTo) } } /** Set lengths using decimal numbers like "10123". */ @Throws(IOException::class) internal fun setLengths(strings: List<String>) { if (strings.size != valueCount) { throw invalidLengths(strings) } try { for (i in strings.indices) { lengths[i] = strings[i].toLong() } } catch (_: NumberFormatException) { throw invalidLengths(strings) } } /** Append space-prefixed lengths to [writer]. */ @Throws(IOException::class) internal fun writeLengths(writer: BufferedSink) { for (length in lengths) { writer.writeByte(' '.toInt()).writeDecimalLong(length) } } @Throws(IOException::class) private fun invalidLengths(strings: List<String>): Nothing { throw IOException("unexpected journal line: $strings") } /** * Returns a snapshot of this entry. This opens all streams eagerly to guarantee that we see a * single published snapshot. If we opened streams lazily then the streams could come from * different edits. */ internal fun snapshot(): Snapshot? { [email protected]() if (!readable) return null if (!civilizedFileSystem && (currentEditor != null || zombie)) return null val sources = mutableListOf<Source>() val lengths = this.lengths.clone() // Defensive copy since these can be zeroed out. try { for (i in 0 until valueCount) { sources += newSource(i) } return Snapshot(key, sequenceNumber, sources, lengths) } catch (_: FileNotFoundException) { // A file must have been deleted manually! for (source in sources) { source.closeQuietly() } // Since the entry is no longer valid, remove it so the metadata is accurate (i.e. the cache // size.) try { removeEntry(this) } catch (_: IOException) { } return null } } private fun newSource(index: Int): Source { val fileSource = fileSystem.source(cleanFiles[index]) if (civilizedFileSystem) return fileSource lockingSourceCount++ return object : ForwardingSource(fileSource) { private var closed = false override fun close() { super.close() if (!closed) { closed = true synchronized(this@DiskLruCache) { lockingSourceCount-- if (lockingSourceCount == 0 && zombie) { removeEntry(this@Entry) } } } } } } } companion object { @JvmField val JOURNAL_FILE = "journal" @JvmField val JOURNAL_FILE_TEMP = "journal.tmp" @JvmField val JOURNAL_FILE_BACKUP = "journal.bkp" @JvmField val MAGIC = "libcore.io.DiskLruCache" @JvmField val VERSION_1 = "1" @JvmField val ANY_SEQUENCE_NUMBER: Long = -1 @JvmField val LEGAL_KEY_PATTERN = "[a-z0-9_-]{1,120}".toRegex() @JvmField val CLEAN = "CLEAN" @JvmField val DIRTY = "DIRTY" @JvmField val REMOVE = "REMOVE" @JvmField val READ = "READ" } }
apache-2.0
77d5703ca5489c222aaea8c715749a5f
31.963346
100
0.649816
4.593112
false
false
false
false
nt-ca-aqe/library-app
library-enrichment/src/test/kotlin/library/enrichment/FunctionalAcceptanceTest.kt
1
2867
package library.enrichment import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.ObjectMapper import com.nhaarman.mockitokotlin2.given import com.nhaarman.mockitokotlin2.timeout import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.willReturn import library.enrichment.core.BookAddedEvent import library.enrichment.gateways.library.LibraryClient import library.enrichment.gateways.library.UpdateAuthors import library.enrichment.gateways.library.UpdateNumberOfPages import library.enrichment.gateways.openlibrary.OpenLibraryClient import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.amqp.core.TopicExchange import org.springframework.amqp.rabbit.core.RabbitTemplate import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.context.ActiveProfiles import org.springframework.test.context.junit.jupiter.SpringExtension import utils.classification.AcceptanceTest import utils.extensions.RabbitMqExtension import utils.readFile @AcceptanceTest @ExtendWith(RabbitMqExtension::class, SpringExtension::class) @SpringBootTest( webEnvironment = NONE, properties = ["spring.rabbitmq.port=\${RABBITMQ_PORT}"] ) @ActiveProfiles("test", "unsecured") internal class FunctionalAcceptanceTest { companion object { const val TIMEOUT = 5000L const val routingKey = "book-added" const val id = "dda05852-f6fe-4ba6-9ce2-6f3a73c664a9" const val bookId = "175c5a7e-dd91-4d42-8c0d-6a97d8755231" } @Autowired lateinit var exchange: TopicExchange @Autowired lateinit var objectMapper: ObjectMapper @Autowired lateinit var rabbitTemplate: RabbitTemplate @MockBean lateinit var openLibraryClient: OpenLibraryClient @MockBean lateinit var libraryClient: LibraryClient @Test fun `book added events are processed correctly`() { given { openLibraryClient.searchBooks("9780261102354") } willReturn { readFile("openlibrary/responses/200_isbn_9780261102354.json").toJson() } send(BookAddedEvent( id = id, bookId = bookId, isbn = "9780261102354" )) verify(libraryClient, timeout(TIMEOUT)) .updateAuthors(bookId, UpdateAuthors(listOf("J. R. R. Tolkien"))) verify(libraryClient, timeout(TIMEOUT)) .updateNumberOfPages(bookId, UpdateNumberOfPages(576)) } fun String.toJson(): JsonNode = objectMapper.readTree(this) fun send(event: BookAddedEvent) = rabbitTemplate.convertAndSend(exchange.name, routingKey, event) }
apache-2.0
a5f572fc8196f1eedd170ae55c43614e
38.833333
101
0.769445
4.343939
false
true
false
false
eugeis/ee
ee-lang_fx/src/main/kotlin/ee/lang/fx/view/TasksController.kt
1
1285
package ee.lang.fx.view import ee.lang.ItemI import ee.task.Result import ee.task.TaskFactory import ee.task.TaskRepository import ee.task.print import tornadofx.Controller class TasksController : Controller() { val tasksView: TasksView by inject() val outputContainerView: OutputContainerView by inject() val repo: TaskRepository by di() var selectedElements: List<ItemI<*>> = emptyList() fun onStructureUnitsSelected(elements: List<ItemI<*>>) { selectedElements = elements runAsync { repo.find(elements) } ui { tasksView.refresh(it) } } fun execute(taskFactory: TaskFactory<*>) { runAsync { val console = outputContainerView.takeConsole(this, taskFactory.name) val results = arrayListOf<Result>() val ret = Result(action = taskFactory.name, results = results) taskFactory.create(selectedElements).forEach { task -> console.title = task.name val result = task.execute({ console.println(it) }) console.title = result.toString() results.add(result) } ret.print({ console.println(it) }) outputContainerView.release(console) } } }
apache-2.0
61a9df638e89e831b2b7de78ef375207
30.341463
81
0.62179
4.605735
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/types/tarfileset.kt
1
11286
/* * Copyright 2016 Karl Tauber * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.devcharly.kotlin.ant import org.apache.tools.ant.types.ResourceCollection import org.apache.tools.ant.types.TarFileSet import org.apache.tools.ant.types.selectors.AndSelector import org.apache.tools.ant.types.selectors.ContainsRegexpSelector import org.apache.tools.ant.types.selectors.ContainsSelector import org.apache.tools.ant.types.selectors.DateSelector import org.apache.tools.ant.types.selectors.DependSelector import org.apache.tools.ant.types.selectors.DepthSelector import org.apache.tools.ant.types.selectors.DifferentSelector import org.apache.tools.ant.types.selectors.ExecutableSelector import org.apache.tools.ant.types.selectors.ExtendSelector import org.apache.tools.ant.types.selectors.FileSelector import org.apache.tools.ant.types.selectors.FilenameSelector import org.apache.tools.ant.types.selectors.MajoritySelector import org.apache.tools.ant.types.selectors.NoneSelector import org.apache.tools.ant.types.selectors.NotSelector import org.apache.tools.ant.types.selectors.OrSelector import org.apache.tools.ant.types.selectors.OwnedBySelector import org.apache.tools.ant.types.selectors.PresentSelector import org.apache.tools.ant.types.selectors.ReadableSelector import org.apache.tools.ant.types.selectors.SelectSelector import org.apache.tools.ant.types.selectors.SizeSelector import org.apache.tools.ant.types.selectors.SymlinkSelector import org.apache.tools.ant.types.selectors.TypeSelector import org.apache.tools.ant.types.selectors.WritableSelector import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ interface ITarFileSetNested : INestedComponent { fun tarfileset( dir: String? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, src: String? = null, erroronmissingarchive: Boolean? = null, prefix: String? = null, fullpath: String? = null, encoding: String? = null, filemode: String? = null, dirmode: String? = null, username: String? = null, uid: Int? = null, group: String? = null, gid: Int? = null, nested: (KTarFileSet.() -> Unit)? = null) { _addTarFileSet(TarFileSet().apply { component.project.setProjectReference(this); _init(dir, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, src, erroronmissingarchive, prefix, fullpath, encoding, filemode, dirmode, username, uid, group, gid, nested) }) } fun _addTarFileSet(value: TarFileSet) } fun IFileSetNested.tarfileset( dir: String? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, src: String? = null, erroronmissingarchive: Boolean? = null, prefix: String? = null, fullpath: String? = null, encoding: String? = null, filemode: String? = null, dirmode: String? = null, username: String? = null, uid: Int? = null, group: String? = null, gid: Int? = null, nested: (KTarFileSet.() -> Unit)? = null) { _addFileSet(TarFileSet().apply { component.project.setProjectReference(this); _init(dir, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, src, erroronmissingarchive, prefix, fullpath, encoding, filemode, dirmode, username, uid, group, gid, nested) }) } fun IResourceCollectionNested.tarfileset( dir: String? = null, file: String? = null, includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, defaultexcludes: Boolean? = null, casesensitive: Boolean? = null, followsymlinks: Boolean? = null, maxlevelsofsymlinks: Int? = null, erroronmissingdir: Boolean? = null, src: String? = null, erroronmissingarchive: Boolean? = null, prefix: String? = null, fullpath: String? = null, encoding: String? = null, filemode: String? = null, dirmode: String? = null, username: String? = null, uid: Int? = null, group: String? = null, gid: Int? = null, nested: (KTarFileSet.() -> Unit)? = null) { _addResourceCollection(TarFileSet().apply { component.project.setProjectReference(this); _init(dir, file, includes, excludes, includesfile, excludesfile, defaultexcludes, casesensitive, followsymlinks, maxlevelsofsymlinks, erroronmissingdir, src, erroronmissingarchive, prefix, fullpath, encoding, filemode, dirmode, username, uid, group, gid, nested) }) } fun TarFileSet._init( dir: String?, file: String?, includes: String?, excludes: String?, includesfile: String?, excludesfile: String?, defaultexcludes: Boolean?, casesensitive: Boolean?, followsymlinks: Boolean?, maxlevelsofsymlinks: Int?, erroronmissingdir: Boolean?, src: String?, erroronmissingarchive: Boolean?, prefix: String?, fullpath: String?, encoding: String?, filemode: String?, dirmode: String?, username: String?, uid: Int?, group: String?, gid: Int?, nested: (KTarFileSet.() -> Unit)?) { if (dir != null) setDir(project.resolveFile(dir)) if (file != null) setFile(project.resolveFile(file)) if (includes != null) setIncludes(includes) if (excludes != null) setExcludes(excludes) if (includesfile != null) setIncludesfile(project.resolveFile(includesfile)) if (excludesfile != null) setExcludesfile(project.resolveFile(excludesfile)) if (defaultexcludes != null) setDefaultexcludes(defaultexcludes) if (casesensitive != null) setCaseSensitive(casesensitive) if (followsymlinks != null) setFollowSymlinks(followsymlinks) if (maxlevelsofsymlinks != null) setMaxLevelsOfSymlinks(maxlevelsofsymlinks) if (erroronmissingdir != null) setErrorOnMissingDir(erroronmissingdir) if (src != null) setSrc(project.resolveFile(src)) if (erroronmissingarchive != null) setErrorOnMissingArchive(erroronmissingarchive) if (prefix != null) setPrefix(prefix) if (fullpath != null) setFullpath(fullpath) if (encoding != null) setEncoding(encoding) if (filemode != null) setFileMode(filemode) if (dirmode != null) setDirMode(dirmode) if (username != null) setUserName(username) if (uid != null) setUid(uid) if (group != null) setGroup(group) if (gid != null) setGid(gid) if (nested != null) nested(KTarFileSet(this)) } class KTarFileSet(override val component: TarFileSet) : IFileSelectorNested, IResourceCollectionNested, ISelectSelectorNested, IAndSelectorNested, IOrSelectorNested, INotSelectorNested, INoneSelectorNested, IMajoritySelectorNested, IDateSelectorNested, ISizeSelectorNested, IDifferentSelectorNested, IFilenameSelectorNested, ITypeSelectorNested, IExtendSelectorNested, IContainsSelectorNested, IPresentSelectorNested, IDepthSelectorNested, IDependSelectorNested, IContainsRegexpSelectorNested, IModifiedSelectorNested, IReadableSelectorNested, IWritableSelectorNested, IExecutableSelectorNested, ISymlinkSelectorNested, IOwnedBySelectorNested { fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) { component.createPatternSet().apply { component.project.setProjectReference(this) _init(includes, excludes, includesfile, excludesfile, nested) } } fun include(name: String? = null, If: String? = null, unless: String? = null) { component.createInclude().apply { _init(name, If, unless) } } fun includesfile(name: String? = null, If: String? = null, unless: String? = null) { component.createIncludesFile().apply { _init(name, If, unless) } } fun exclude(name: String? = null, If: String? = null, unless: String? = null) { component.createExclude().apply { _init(name, If, unless) } } fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) { component.createExcludesFile().apply { _init(name, If, unless) } } override fun _addFileSelector(value: FileSelector) = component.add(value) override fun _addResourceCollection(value: ResourceCollection) = component.addConfigured(value) override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value) override fun _addAndSelector(value: AndSelector) = component.addAnd(value) override fun _addOrSelector(value: OrSelector) = component.addOr(value) override fun _addNotSelector(value: NotSelector) = component.addNot(value) override fun _addNoneSelector(value: NoneSelector) = component.addNone(value) override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value) override fun _addDateSelector(value: DateSelector) = component.addDate(value) override fun _addSizeSelector(value: SizeSelector) = component.addSize(value) override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value) override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value) override fun _addTypeSelector(value: TypeSelector) = component.addType(value) override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value) override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value) override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value) override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value) override fun _addDependSelector(value: DependSelector) = component.addDepend(value) override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value) override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value) override fun _addReadableSelector(value: ReadableSelector) = component.addReadable(value) override fun _addWritableSelector(value: WritableSelector) = component.addWritable(value) override fun _addExecutableSelector(value: ExecutableSelector) = component.addExecutable(value) override fun _addSymlinkSelector(value: SymlinkSelector) = component.addSymlink(value) override fun _addOwnedBySelector(value: OwnedBySelector) = component.addOwnedBy(value) }
apache-2.0
6ec12fdad3b72a7740851a7b415e87fa
35.057508
171
0.751728
3.70884
false
false
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/DelegatedGradlePropertiesIntegrationTest.kt
1
7811
package org.gradle.kotlin.dsl.integration import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest import org.hamcrest.CoreMatchers.containsString import org.junit.Assert.assertThat import org.junit.Test /** * See https://docs.gradle.org/current/userguide/build_environment.html */ class DelegatedGradlePropertiesIntegrationTest : AbstractKotlinIntegrationTest() { @Test fun `non-nullable delegated property access of non-existing gradle property throws`() { withSettings(""" val nonExisting: String by settings println(nonExisting) """) assertThat( buildAndFail("help").error, containsString("Cannot get non-null property 'nonExisting' on settings '${projectRoot.name}' as it does not exist")) withSettings("") withBuildScript(""" val nonExisting: String by project println(nonExisting) """) assertThat( buildAndFail("help").error, containsString("Cannot get non-null property 'nonExisting' on root project '${projectRoot.name}' as it does not exist")) } @Test fun `delegated properties follow Gradle mechanics and allow to model optional properties via nullable kotlin types`() { // given: build root gradle.properties file withFile("gradle.properties", """ setBuildProperty=build value emptyBuildProperty= userHomeOverriddenBuildProperty=build value cliOverriddenBuildProperty=build value projectMutatedBuildProperty=build value """.trimIndent()) // and: gradle user home gradle.properties file withFile("gradle-user-home/gradle.properties", """ setUserHomeProperty=user home value emptyUserHomeProperty= userHomeOverriddenBuildProperty=user home value cliOverriddenUserHomeProperty=user home value projectMutatedUserHomeProperty=user home value """.trimIndent()) // and: isolated gradle user home executer.withGradleUserHomeDir(existing("gradle-user-home")) executer.requireIsolatedDaemons() // and: gradle command line with properties val buildArguments = arrayOf( "-PsetCliProperty=cli value", "-PemptyCliProperty=", "-PcliOverriddenBuildProperty=cli value", "-PcliOverriddenUserHomeProperty=cli value", "-Dorg.gradle.project.setOrgGradleProjectSystemProperty=system property value", "-Dorg.gradle.project.emptyOrgGradleProjectSystemProperty=", "help") // when: both settings and project scripts asserting on delegated properties withSettings(requirePropertiesFromSettings()) withBuildScript(requirePropertiesFromProject()) // then: build(*buildArguments) // when: project script buildscript block asserting on delegated properties withSettings("") withBuildScript(""" buildscript { ${requirePropertiesFromProject()} } """) // then: build(*buildArguments) } private fun requirePropertiesFromSettings() = """ ${requireNotOverriddenPropertiesFrom("settings")} ${requireOverriddenPropertiesFrom("settings")} ${requireEnvironmentPropertiesFrom("settings")} ${requireProjectMutatedPropertiesOriginalValuesFrom("settings")} """.trimIndent() private fun requirePropertiesFromProject() = """ ${requireNotOverriddenPropertiesFrom("project")} ${requireOverriddenPropertiesFrom("project")} ${requireEnvironmentPropertiesFrom("project")} ${requireProjectExtraProperties()} ${requireProjectMutatedPropertiesOriginalValuesFrom("project")} ${requireProjectPropertiesMutation()} """.trimIndent() private fun requireNotOverriddenPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "setUserHomeProperty", """"user home value"""")} ${requireProperty<String>(source, "emptyUserHomeProperty", """""""")} ${requireProperty<String>(source, "setBuildProperty", """"build value"""")} ${requireProperty<String>(source, "emptyBuildProperty", """""""")} ${requireProperty<String>(source, "setCliProperty", """"cli value"""")} ${requireProperty<String>(source, "emptyCliProperty", """""""")} ${requireNullableProperty<String>(source, "unsetProperty", "null")} """.trimIndent() private fun requireOverriddenPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "userHomeOverriddenBuildProperty", """"user home value"""")} ${requireProperty<String>(source, "cliOverriddenBuildProperty", """"cli value"""")} ${requireProperty<String>(source, "cliOverriddenUserHomeProperty", """"cli value"""")} """.trimIndent() private fun requireEnvironmentPropertiesFrom(source: String) = """ ${requireProperty<String>(source, "setOrgGradleProjectSystemProperty", """"system property value"""")} ${requireProperty<String>(source, "emptyOrgGradleProjectSystemProperty", """""""")} """.trimIndent() private fun requireProjectExtraProperties() = """ run { extra["setExtraProperty"] = "extra value" extra["emptyExtraProperty"] = "" extra["unsetExtraProperty"] = null val setExtraProperty: String by project require(setExtraProperty == "extra value") val emptyExtraProperty: String by project require(emptyExtraProperty == "") val unsetExtraProperty: String? by project require(unsetExtraProperty == null) setProperty("setExtraProperty", "mutated") require(setExtraProperty == "mutated") } """.trimIndent() private fun requireProjectMutatedPropertiesOriginalValuesFrom(source: String) = """ ${requireProperty<String>(source, "projectMutatedBuildProperty", """"build value"""")} ${requireProperty<String>(source, "projectMutatedUserHomeProperty", """"user home value"""")} """.trimIndent() private fun requireProjectPropertiesMutation() = """ run { val projectMutatedBuildProperty: String by project require(projectMutatedBuildProperty == "build value") setProperty("projectMutatedBuildProperty", "mutated") require(projectMutatedBuildProperty == "mutated") val projectMutatedUserHomeProperty: String by project require(projectMutatedUserHomeProperty == "user home value") setProperty("projectMutatedUserHomeProperty", "mutated") require(projectMutatedUserHomeProperty == "mutated") } """.trimIndent() private inline fun <reified T : Any> requireProperty(source: String, name: String, valueRepresentation: String) = requireProperty(source, name, T::class.qualifiedName!!, valueRepresentation) private inline fun <reified T : Any> requireNullableProperty(source: String, name: String, valueRepresentation: String) = requireProperty(source, name, "${T::class.qualifiedName!!}?", valueRepresentation) private fun requireProperty(source: String, name: String, type: String, valueRepresentation: String) = """ run { val $name: $type by $source require($name == $valueRepresentation) { ${"\"".repeat(3)}expected $name to be '$valueRepresentation' but was '${'$'}$name'${"\"".repeat(3)} } } """.trimIndent() }
apache-2.0
f215a61a37608047580aaf7132317667
36.373206
132
0.642683
6.04099
false
false
false
false
FrancYescO/PokemonGoBot
src/main/kotlin/ink/abb/pogo/scraper/tasks/ProcessPokestops.kt
1
2703
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package ink.abb.pogo.scraper.tasks import com.pokegoapi.api.map.fort.Pokestop import ink.abb.pogo.scraper.Bot import ink.abb.pogo.scraper.Context import ink.abb.pogo.scraper.Settings import ink.abb.pogo.scraper.Task import ink.abb.pogo.scraper.util.Log import java.util.* import java.util.concurrent.TimeUnit /** * Task that handles catching pokemon, activating stops, and walking to a new target. */ class ProcessPokestops(var pokestops: MutableCollection<Pokestop>) : Task { val refetchTime = TimeUnit.SECONDS.toMillis(30) var lastFetch: Long = 0 private val lootTimeouts = HashMap<String, Long>() var startPokestop: Pokestop? = null override fun run(bot: Bot, ctx: Context, settings: Settings) { var writeCampStatus = false if (lastFetch + refetchTime < bot.api.currentTimeMillis()) { writeCampStatus = true lastFetch = bot.api.currentTimeMillis() if (settings.allowLeaveStartArea) { try { val newStops = ctx.api.map.mapObjects.pokestops if (newStops.size > 0) { pokestops = newStops } } catch (e: Exception) { // ignored failed request } } } val sortedPokestops = pokestops.sortedWith(Comparator { a, b -> a.distance.compareTo(b.distance) }) if (startPokestop == null) startPokestop = sortedPokestops.first() if (settings.lootPokestop) { val loot = LootOneNearbyPokestop(sortedPokestops, lootTimeouts) try { bot.task(loot) } catch (e: Exception) { ctx.pauseWalking.set(false) } } if (settings.campLurePokestop > 0 && !ctx.pokemonInventoryFullStatus.get() && settings.catchPokemon) { val luresInRange = sortedPokestops.filter { it.inRangeForLuredPokemon() && it.fortData.hasLureInfo() }.size if (luresInRange >= settings.campLurePokestop) { if (writeCampStatus) { Log.green("$luresInRange lure(s) in range, pausing") } return } } val walk = Walk(sortedPokestops, lootTimeouts) bot.task(walk) } }
gpl-3.0
f0f7b5e6e7bfc823d99d3e6fec4648dc
34.565789
110
0.605623
4.520067
false
false
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/collection/ModularCollectionKComponent.kt
1
1924
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.litho.kotlin.collection import com.facebook.litho.Component import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.State import com.facebook.litho.Style import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.useState import com.facebook.litho.view.onClick import com.facebook.litho.widget.collection.LazyList import com.facebook.litho.widget.collection.LazyListScope class ModularCollectionKComponent : KComponent() { override fun ComponentScope.render(): Component { val nestedContentVisible = useState { true } return LazyList { addHeader() addBody(nestedContentVisible) addFooter() } } private fun LazyListScope.addHeader() { child(isSticky = true, component = Text("Header")) } private fun LazyListScope.addBody(nestedContentVisible: State<Boolean>) { child( Text( "${if (nestedContentVisible.value) "-" else "+"} Body", style = Style.onClick { nestedContentVisible.update(!nestedContentVisible.value) })) if (nestedContentVisible.value) { children(items = listOf(0, 1, 2, 3), id = { it }) { Text(" Nested Body Item $it") } } } private fun LazyListScope.addFooter() { child(Text("Footer")) } }
apache-2.0
7af3b8d2c3942c2113aa6442dfa4584a
31.610169
96
0.722973
4.219298
false
false
false
false
greggigon/Home-Temperature-Controller
temperature-sensor-and-rest/src/main/kotlin/io/dev/temperature/TemperatureApp.kt
1
2120
package io.dev.temperature import io.dev.temperature.model.Temperature import io.dev.temperature.model.TemperatureCodec import io.dev.temperature.verticles.* import io.vertx.core.AbstractVerticle import io.vertx.core.DeploymentOptions import io.vertx.core.Vertx import io.vertx.core.json.JsonObject import org.slf4j.Logger import org.slf4j.LoggerFactory import kotlin.system.exitProcess class TemperatureApp : AbstractVerticle() { override fun start() { val serialPortConfig = config().getJsonObject("serialPort", JsonObject().put("path", "/tmp/foo")) val serialPortPath = serialPortConfig.getString("path", "/tmp/foo") vertx.eventBus().registerDefaultCodec(Temperature::class.java, TemperatureCodec()) vertx.deployVerticle(MessageParsingVerticle()) vertx.deployVerticle(ScheduleVerticle()) vertx.deployVerticle(InMemoryTemperatureRepository()) vertx.deployVerticle(SerialPortTemperatureVerticle(serialPortPath), { when (it.succeeded()) { true -> { vertx.deployVerticle(RESTVerticle(), { if (it.failed()) { log.error("Failed to start REST Verticle", it.cause()) exitProcess(-3) } }) } false -> { log.error("Unable to start Serial Port Verticle :(", it.cause()) exitProcess(-2) } } }) val deploymentOptionsoptions = DeploymentOptions().setWorker(true) vertx.deployVerticle(SQLTemperatureRepository(), deploymentOptionsoptions) } } val log: Logger = LoggerFactory.getLogger(TemperatureApp::class.java) fun main(args: Array<String>) { val vertx = Vertx.vertx() vertx.deployVerticle(TemperatureApp(), { if (it.succeeded()) { log.info("!!! Started the Top Level Verticle !!! ") } else { log.error("!!! Couldn't start the Top Level Verticle", it.cause()) exitProcess(-1) } }) }
mit
8817cf78b56ccbaf6702d461f91f7065
30.641791
105
0.611792
4.896074
false
false
false
false
vase4kin/TeamCityApp
app/src/androidTest/java/com/github/vase4kin/teamcityapp/filter_builds/view/FilterBuildsActivityTest.kt
1
14814
/* * Copyright 2019 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.filter_builds.view import android.view.View import androidx.test.espresso.Espresso.onData import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.closeSoftKeyboard import androidx.test.espresso.action.ViewActions.typeText import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.RootMatchers import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.github.vase4kin.teamcityapp.R import com.github.vase4kin.teamcityapp.TeamCityApplication import com.github.vase4kin.teamcityapp.api.TeamCityService import com.github.vase4kin.teamcityapp.buildlist.api.Builds import com.github.vase4kin.teamcityapp.dagger.components.AppComponent import com.github.vase4kin.teamcityapp.dagger.components.RestApiComponent import com.github.vase4kin.teamcityapp.dagger.modules.AppModule import com.github.vase4kin.teamcityapp.dagger.modules.FakeTeamCityServiceImpl import com.github.vase4kin.teamcityapp.dagger.modules.Mocks import com.github.vase4kin.teamcityapp.dagger.modules.RestApiModule import com.github.vase4kin.teamcityapp.helper.CustomIntentsTestRule import com.github.vase4kin.teamcityapp.helper.TestUtils import com.github.vase4kin.teamcityapp.helper.eq import com.github.vase4kin.teamcityapp.home.view.HomeActivity import com.github.vase4kin.teamcityapp.runbuild.api.Branch import com.github.vase4kin.teamcityapp.runbuild.api.Branches import io.reactivex.Single import it.cosenonjaviste.daggermock.DaggerMockRule import org.hamcrest.Matchers.`is` import org.hamcrest.Matchers.instanceOf import org.hamcrest.Matchers.not import org.hamcrest.core.AllOf.allOf import org.junit.Before import org.junit.BeforeClass import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Matchers.anyString import org.mockito.Mockito.`when` import org.mockito.Mockito.verify import org.mockito.Spy import java.util.ArrayList /** * Tests for [FilterBuildsActivity] */ @RunWith(AndroidJUnit4::class) class FilterBuildsActivityTest { @JvmField @Rule val daggerRule: DaggerMockRule<RestApiComponent> = DaggerMockRule(RestApiComponent::class.java, RestApiModule(Mocks.URL)) .addComponentDependency( AppComponent::class.java, AppModule(InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication) ) .set { restApiComponent -> val app = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication app.setRestApiInjector(restApiComponent) } @JvmField @Rule val activityRule: CustomIntentsTestRule<HomeActivity> = CustomIntentsTestRule(HomeActivity::class.java) @Spy private val teamCityService: TeamCityService = FakeTeamCityServiceImpl() companion object { @JvmStatic @BeforeClass fun disableOnboarding() { TestUtils.disableOnboarding() } } @Before fun setUp() { val app = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as TeamCityApplication app.restApiInjector.sharedUserStorage().clearAll() app.restApiInjector.sharedUserStorage() .saveGuestUserAccountAndSetItAsActive(Mocks.URL, false) `when`( teamCityService.listBuilds( anyString(), anyString() ) ).thenReturn(Single.just(Builds(0, emptyList()))) } @Test fun testUserCanFilterBuildsWithDefaultFilter() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("state:any,canceled:any,failedToStart:any,branch:default:any,personal:false,pinned:false,count:10") ) } @Test fun testUserCanFilterBuildsByPinned() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on pin switcher onView(withId(R.id.switcher_is_pinned)).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("state:any,canceled:any,failedToStart:any,branch:default:any,personal:false,pinned:true,count:10") ) } @Test fun testUserCanFilterBuildsByPersonal() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on pin switcher onView(withId(R.id.switcher_is_personal)).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify<TeamCityService>(teamCityService).listBuilds( anyString(), eq("state:any,canceled:any,failedToStart:any,branch:default:any,personal:true,pinned:false,count:10") ) } @Test fun testUserCanFilterBuildsByBranch() { // Prepare mocks val branches = ArrayList<Branch>() branches.add(Branch("dev1")) branches.add(Branch("dev2")) `when`(teamCityService.listBranches(anyString())).thenReturn(Single.just(Branches(branches))) // Starting the activity activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Choose branch from autocomplete and verify it is appeared onView(withId(R.id.autocomplete_branches)) .perform(typeText("dev")) onData(allOf(`is`(instanceOf<Any>(String::class.java)), `is`<String>("dev1"))) .inRoot(RootMatchers.withDecorView(not(`is`<View>(activityRule.activity.window.decorView)))) .perform(click()) onView(withText("dev1")).perform(click(), closeSoftKeyboard()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("state:any,canceled:any,failedToStart:any,branch:name:dev1,personal:false,pinned:false,count:10") ) } @Test fun testPinnedSwitchIsGoneWhenQueuedFilterIsChosen() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Check switchers are shown onView(withId(R.id.switcher_is_pinned)).check(matches(isDisplayed())) onView(withId(R.id.switcher_is_personal)).check(matches(isDisplayed())) // Click on filter chooser onView(withId(R.id.chooser_filter)).perform(click()) // Filter by queued onView(withText("Queued")).perform(click()) // Check switchers onView(withId(R.id.switcher_is_pinned)).check(matches(not(isDisplayed()))) onView(withId(R.id.divider_switcher_is_pinned)).check(matches(not(isDisplayed()))) onView(withId(R.id.switcher_is_personal)).check(matches(isDisplayed())) } @Test fun testUserCanFilterBuildsWithSuccessFilter() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on filter chooser onView(withId(R.id.chooser_filter)).perform(click()) // Filter by success onView(withText("Success")).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("status:SUCCESS,branch:default:any,personal:false,pinned:false,count:10") ) } @Test fun testUserCanFilterBuildsWithFailedFilter() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on filter chooser onView(withId(R.id.chooser_filter)).perform(click()) // Filter by success onView(withText("Failed")).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("status:FAILURE,branch:default:any,personal:false,pinned:false,count:10") ) } @Test fun testUserCanFilterBuildsWithFailedServerErrorFilter() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on filter chooser onView(withId(R.id.chooser_filter)).perform(click()) // Filter by success onView(withText("Failed due server error")).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("status:ERROR,branch:default:any,personal:false,pinned:false,count:10") ) } @Test fun testUserCanFilterBuildsWithCancelledFilter() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on filter chooser onView(withId(R.id.chooser_filter)).perform(click()) // Filter by success onView(withText("Cancelled")).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("canceled:true,branch:default:any,personal:false,pinned:false,count:10") ) } @Test fun testUserCanFilterBuildsWithFailedToStartFilter() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on filter chooser onView(withId(R.id.chooser_filter)).perform(click()) // Filter by success onView(withText("Failed to start")).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("failedToStart:true,branch:default:any,personal:false,pinned:false,count:10") ) } @Test fun testUserCanFilterBuildsWithRunningFilter() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on filter chooser onView(withId(R.id.chooser_filter)).perform(click()) // Filter by success onView(withText("Running")).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("running:true,branch:default:any,personal:false,pinned:false") ) } @Test fun testUserCanFilterBuildsWithQueuedFilter() { activityRule.launchActivity(null) // Open build type onView(withText("build type")) .perform(click()) // Pressing filter builds toolbar item onView(withId(R.id.filter_builds)) .perform(click()) // Click on filter chooser onView(withId(R.id.chooser_filter)).perform(click()) // Filter by success onView(withText("Queued")).perform(click()) // Click on filter fab onView(withId(R.id.fab_filter)).perform(click()) // Check data was loaded with new filter verify(teamCityService).listBuilds( anyString(), eq("state:queued,branch:default:any,personal:false,pinned:any") ) } }
apache-2.0
7b67a27a09b8f50ce6092534fd42d090
32.066964
127
0.656271
4.640977
false
true
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/psi/element/MdInlineGitLabMathImpl.kt
1
5273
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.ElementManipulators import com.intellij.psi.LiteralTextEscaper import com.intellij.psi.PsiElement import com.vladsch.flexmark.util.sequence.BasedSequence import com.vladsch.md.nav.actions.handlers.util.PsiEditAdjustment import com.vladsch.md.nav.parser.MdFactoryContext import com.vladsch.md.nav.psi.util.MdElementFactory import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.psi.util.MdTypes import com.vladsch.plugin.util.ifElse import com.vladsch.plugin.util.toRich open class MdInlineGitLabMathImpl(node: ASTNode) : MdInlineStyleCompositeImpl(node), MdInlineGitLabMath { override fun getContent(): String { return contentElement?.text ?: "" } override fun getContentElement(): ASTNode? { return node.findChildByType(MdTypes.GITLAB_MATH_TEXT) } override fun setContent(content: String): PsiElement { // REFACTOR: factor out common part. This is almost identical to MdInlineCodeImpl val containingFile = containingFile val editContext = PsiEditAdjustment(containingFile) val paragraph = MdPsiImplUtil.getParagraphParent(this) ?: this val indentPrefix = MdPsiImplUtil.getBlockPrefixes(paragraph, null, editContext).finalizePrefixes(editContext).childContPrefix var convertedContent = content val newElementText = getElementText(MdFactoryContext(this), convertedContent).toRich() if (indentPrefix.isNotEmpty) { // re-indent if there is an indent ahead of our content on the line if (indentPrefix.isNotEmpty) { val contentLines = newElementText.split("\n", 0, BasedSequence.SPLIT_INCLUDE_DELIMS) val sb = StringBuilder() val firstIndentPrefix = BasedSequence.EMPTY var useIndentPrefix = firstIndentPrefix for (line in contentLines) { sb.append(useIndentPrefix) useIndentPrefix = indentPrefix sb.append(line) } convertedContent = sb.toString() } // we have no choice but to replace the element textually, because with all possible prefix combinations // it will not parse, so we have to create a file with contents of the top parent element that contains us // the easiest way is to just take the whole PsiFile and replace our content in it val file = containingFile.originalFile val fileText: String = file.text val changedText = fileText.substring(0, this.node.startOffset) + convertedContent + fileText.substring(this.node.startOffset + this.textLength, fileText.length) val factoryContext = MdFactoryContext(this) val newFile = MdElementFactory.createFile(factoryContext, changedText) val psiElement = newFile.findElementAt(node.startOffset)?.parent if (psiElement is MdInlineGitLabMath) { // NOTE: replacing the content node leaves the element unchanged and preserves the injection all the time // if the element is changed, injection may be lost and will have to be initiated again by the user. node.replaceAllChildrenToChildrenOf(psiElement.getNode()) } } else { MdPsiImplUtil.setContent(this, convertedContent) } return this } override fun getContentRange(inDocument: Boolean): TextRange { val contentElement = contentElement return if (contentElement != null) inDocument.ifElse(contentElement.textRange, TextRange(0, contentElement.textLength)).shiftRight(2) else TextRange.EMPTY_RANGE } override fun isValidHost(): Boolean { return isValid } override fun updateText(text: String): MdPsiLanguageInjectionHost? { return ElementManipulators.handleContentChange(this, text) } override fun createLiteralTextEscaper(): LiteralTextEscaper<out MdPsiLanguageInjectionHost?> { return object : LiteralTextEscaper<MdPsiLanguageInjectionHost?>(this) { override fun decode(rangeInsideHost: TextRange, outChars: StringBuilder): Boolean { outChars.append(rangeInsideHost.shiftLeft(2).substring((myHost as MdInlineGitLabMathImpl).contentElement!!.text)) return true } override fun getOffsetInHost(offsetInDecoded: Int, rangeInsideHost: TextRange): Int { return rangeInsideHost.startOffset + offsetInDecoded } override fun getRelevantTextRange(): TextRange { return contentRange } override fun isOneLine(): Boolean { return true } } } companion object { fun getElementText(factoryContext: MdFactoryContext, content: String): String { return "\$`$content`\$" } } }
apache-2.0
d623aa6ed81147c9c3759d57457a7cca
44.068376
177
0.678172
5.220792
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/MdPlugin.kt
1
21553
/* * Copyright (c) 2015-2019 Vladimir Schneider <[email protected]>, all rights reserved. * * This code is private property of the copyright holder and cannot be used without * having obtained a license or prior written permission of the copyright holder. * * 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.vladsch.md.nav import com.intellij.ide.BrowserUtil import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.ide.plugins.PluginManagerCore import com.intellij.notification.Notification import com.intellij.notification.NotificationListener import com.intellij.notification.NotificationType import com.intellij.notification.impl.NotificationsManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.Anchor import com.intellij.openapi.actionSystem.Constraints import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.components.BaseComponent import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.colors.EditorColorsListener import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.util.Ref import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.wm.IdeFrame import com.intellij.openapi.wm.WindowManager import com.intellij.ui.BalloonLayoutData import com.intellij.ui.awt.RelativePoint import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.vladsch.md.nav.actions.ide.CopyFileBareNameProvider import com.vladsch.md.nav.actions.ide.CopyFileNameProvider import com.vladsch.md.nav.actions.ide.CopyFilePathWithLineNumbersProvider import com.vladsch.md.nav.actions.ide.CopyUpsourceFilePathWithLineNumbersProvider import com.vladsch.md.nav.highlighter.MdSyntaxHighlighter import com.vladsch.md.nav.settings.MdApplicationSettings import com.vladsch.md.nav.settings.MdDocumentSettings import com.vladsch.md.nav.settings.SettingsChangedListener import com.vladsch.md.nav.settings.api.MdExtensionInfoProvider import com.vladsch.md.nav.util.DynamicNotificationText import com.vladsch.md.nav.util.MdCancelableJobScheduler import com.vladsch.plugin.util.* import org.jetbrains.jps.service.SharedThreadPool import java.awt.Color import java.awt.Point import java.util.function.Consumer import javax.swing.UIManager class MdPlugin : BaseComponent, Disposable { private var projectLoaded = false private val myNotificationRunnable: DelayedConsumerRunner<Project> = DelayedConsumerRunner() var startupDocumentSettings: MdDocumentSettings = MdDocumentSettings() private set // var startupDebugSettings: MdDebugSettings = MdDebugSettings() // private set private val restartRequiredChecker = object : AppRestartRequiredCheckerBase<MdApplicationSettings>(MdBundle.message("settings.restart-required.title")) { override fun getRestartNeededReasons(settings: MdApplicationSettings): Long { val fullHighlightChanged = startupDocumentSettings.fullHighlightCombinations != settings.documentSettings.fullHighlightCombinations return fullHighlightChanged.ifElse(1L, 0L) } } override fun initComponent() { val appSettings = MdApplicationSettings.instance ApplicationManager.getApplication().invokeLater { SharedThreadPool.getInstance().submit { try { val actionManager = ActionManager.getInstance() // document options for copy path to turn visibility of these on, all are off by default val action0 = CopyUpsourceFilePathWithLineNumbersProvider() actionManager.registerAction("CopyUpsourceFilePathWithLineNumbersProvider", action0) val action1 = CopyFilePathWithLineNumbersProvider() actionManager.registerAction("MdCopyPathWithSelectionLineNumbers", action1) val action2 = CopyFileNameProvider() actionManager.registerAction("MdCopyPathFileName", action2) val action3 = CopyFileBareNameProvider() actionManager.registerAction("MdCopyCopyPathBareName", action3) val referenceAction = actionManager.getAction("CopyFileReference") if (referenceAction is DefaultActionGroup) { referenceAction.add(action0, Constraints(Anchor.AFTER, "CopyPathWithLineNumber")) referenceAction.add(action1, Constraints(Anchor.AFTER, "CopyPathWithLineNumber")) referenceAction.add(action2, Constraints(Anchor.AFTER, "CopyPathWithLineNumber")) referenceAction.add(action3, Constraints(Anchor.AFTER, "CopyPathWithLineNumber")) } } catch (e: Throwable) { } } } // make a copy so we can inform when it changes val documentSettings = appSettings.documentSettings startupDocumentSettings = MdDocumentSettings(documentSettings) // startupDebugSettings = MdDebugSettings(appSettings.debugSettings) LOG.info("Initializing Component: fullHighlights = ${documentSettings.fullHighlightCombinations}") // QUERY: do we still need to init default project settings just in case they don't exist? // MdProjectSettings.getInstance(ProjectManager.getInstance().defaultProject) val settingsChangedListener = SettingsChangedListener { applicationSettings -> ApplicationManager.getApplication().invokeLater { informRestartIfNeeded(applicationSettings) } } val settingsConnection = ApplicationManager.getApplication().messageBus.connect(this as Disposable) settingsConnection.subscribe(SettingsChangedListener.TOPIC, settingsChangedListener) @Suppress("DEPRECATION") EditorColorsManager.getInstance().addEditorColorsListener(EditorColorsListener { MdSyntaxHighlighter.computeMergedAttributes(true) }, this) // do initialization after first project is loaded myNotificationRunnable.addRunnable { AwtRunnable.schedule(MdCancelableJobScheduler.getInstance(), "New Features Notification", 1000) { // To Show if enhanced plugin is not installed val showAvailable = MdExtensionInfoProvider.EP_NAME.extensions.all { if (it is MdEnhancedExtensionInfoProvider) it.showEnhancedPluginAvailable() else true } if (showAvailable) { notifyLicensedAvailableUpdate(fullProductVersion, MdResourceResolverImpl.instance.getResourceFileContent("/com/vladsch/md/nav/FEATURES.html")) } } } } private fun informRestartIfNeeded(applicationSettings: MdApplicationSettings) { restartRequiredChecker.informRestartIfNeeded(applicationSettings) } override fun dispose() { } fun projectLoaded(project: Project) { if (!projectLoaded) { projectLoaded = true fullProductVersion // load version myNotificationRunnable.runAll(project) // allow extensions to perform when first project is loaded MdExtensionInfoProvider.EP_NAME.extensions.forEach { if (it is MdEnhancedExtensionInfoProvider) it.projectLoaded(project) } } } private fun addHtmlColors(dynamicText: DynamicNotificationText): DynamicNotificationText { val isDarkUITheme = UIUtil.isUnderDarcula() val enhColor = if (isDarkUITheme) "#B0A8E6" else "#6106A5" val buyColor = if (isDarkUITheme) "#F0A8D4" else "#C02080" val specialsColor = if (isDarkUITheme) "#A4EBC5" else "#04964F" val linkColor = (UIManager.getColor("link.foreground") ?: Color(0x589df6)).toHtmlString() return dynamicText.addText("[[ENHANCED]]") { enhColor } .addText("[[BUY]]") { buyColor } .addText("[[SPECIALS]]") { specialsColor } .addText("[[LINK]]") { linkColor } } private fun addCommonLinks(dynamicText: DynamicNotificationText): DynamicNotificationText { val settings = MdApplicationSettings.instance.getLocalState() return dynamicText .addLink(":DISABLE_ENHANCED") { settings.wasShownSettings.licensedAvailable = true it.expire() } .addLink(":BUY") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator/buy") } .addLink(":TRY") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator/try") } .addLink(":NAME_CHANGE") { BrowserUtil.browse("https://github.com/vsch/idea-multimarkdown/wiki/Settings-Affected-by-Plugin-Name-Change") } .addLink(":SPECIALS") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator/specials") } .addLink(":FEATURES") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator") } .addLink(":REFERRALS") { BrowserUtil.browse("https://vladsch.com/product/markdown-navigator/referrals") } .addLink(":VERSION") { BrowserUtil.browse("https://github.com/vsch/idea-multimarkdown/blob/master/VERSION.md") } } private fun showFullNotification(project: Project?, notification: Notification) { val runnable = Consumer<IdeFrame> { frame -> val bounds = frame.component.bounds val target = RelativePoint(Point(bounds.x + bounds.width, 0)) var handled = false try { val balloon = NotificationsManagerImpl.createBalloon(frame, notification, true, true, BalloonLayoutData.fullContent(), { }) balloon.show(target, Balloon.Position.atRight) handled = true } catch (e: NoSuchMethodError) { } catch (e: NoClassDefFoundError) { } catch (e: NoSuchFieldError) { } if (!handled) { try { val layoutData = BalloonLayoutData() try { layoutData.groupId = "" layoutData.showSettingButton = false } catch (e: NoSuchFieldError) { } layoutData.showFullContent = true val layoutDataRef = Ref(layoutData) val balloon = NotificationsManagerImpl.createBalloon(frame, notification, true, true, layoutDataRef, { }) balloon.show(target, Balloon.Position.atRight) } catch (e: NoSuchMethodError) { // use normal balloons notification.notify(project) } catch (e: NoSuchFieldError) { // use normal balloons notification.notify(project) } catch (e: NoClassDefFoundError) { // use normal balloons notification.notify(project) } } } if (project != null) { if (project.isDisposed) return val frame = WindowManager.getInstance().getIdeFrame(project) if (frame != null) { runnable.accept(frame) return } } var delayedRun: (project: Project) -> Unit = {} delayedRun = { if (!it.isDisposed) { val frame = WindowManager.getInstance().getIdeFrame(it) if (frame != null) { runnable.accept(frame) } else { // reschedule for a bit later AwtRunnable.schedule(MdCancelableJobScheduler.getInstance(), "New Features Notification", 1000) { delayedRun.invoke(it) } } } } myNotificationRunnable.addRunnable(delayedRun) } private fun notifyLicensedAvailableUpdate(currentVersion: String, html: String) { val settings = MdApplicationSettings.instance.getLocalState() if (settings.wasShownSettings.lastLicensedAvailableVersion != currentVersion) { val notificationType = NotificationType.INFORMATION settings.wasShownSettings.licensedAvailable = true settings.wasShownSettings.lastLicensedAvailableVersion = currentVersion val issueNotificationGroup = PluginNotifications.NOTIFICATION_GROUP_UPDATE val title = MdBundle.message("plugin.licensed-available.notification.title", productDisplayName, currentVersion) val content = html.replace("<ul", String.format("<ul style=\"margin-left: %dpx\"", JBUI.scale(10))) val dynamicText = DynamicNotificationText() addHtmlColors(dynamicText) addCommonLinks(dynamicText) val listener = NotificationListener { notification, hyperlinkEvent -> if (hyperlinkEvent.url == null) { val link = hyperlinkEvent.description dynamicText.linkAction(notification, link) } else { BrowserUtil.browse(hyperlinkEvent.url.toString()) } } val messageText = dynamicText.replaceText(content) val notification = issueNotificationGroup.createNotification(title, messageText, notificationType, listener) //.notify(null) showFullNotification(null, notification) } } override fun disposeComponent() { // empty } override fun getComponentName(): String { return this.javaClass.name } fun getLogger(): Logger { return LOG } interface MdEnhancedExtensionInfoProvider : MdExtensionInfoProvider { fun showEnhancedPluginAvailable(): Boolean fun projectLoaded(project: Project) } companion object { private const val PLUGIN_ID = "com.vladsch.idea.multimarkdown" val LOG: Logger by lazy { Logger.getInstance(PLUGIN_ID) } const val siteURL: String = "https://vladsch.com" const val productPrefixURL: String = "/product/markdown-navigator" const val altProductPrefixURL: String = "/product/multimarkdown" const val patchRelease: String = "$siteURL$productPrefixURL/patch-release" const val eapRelease: String = "$siteURL$productPrefixURL/eap-release" const val altPatchRelease: String = "$siteURL$altProductPrefixURL/patch-release" const val altEapRelease: String = "$siteURL$altProductPrefixURL/eap-release" const val jbLegacyRelease: String = "https://plugins.jetbrains.com/plugins/LEGACY/7896" const val jbLegacyEapRelease: String = "https://plugins.jetbrains.com/plugins/LEGACY-EAP/7896" const val jbEapRelease: String = "https://plugins.jetbrains.com/plugins/EAP/7896" const val PREVIEW_STYLESHEET_LAYOUT: String = "/com/vladsch/md/nav/layout.css" const val PREVIEW_STYLESHEET_LIGHT: String = "/com/vladsch/md/nav/default.css" const val PREVIEW_STYLESHEET_DARK: String = "/com/vladsch/md/nav/darcula.css" const val PREVIEW_FX_STYLESHEET_LAYOUT: String = "/com/vladsch/md/nav/layout-fx.css" const val PREVIEW_FX_STYLESHEET_LIGHT: String = "/com/vladsch/md/nav/default-fx.css" const val PREVIEW_FX_STYLESHEET_DARK: String = "/com/vladsch/md/nav/darcula-fx.css" const val PREVIEW_FX_JS: String = "/com/vladsch/md/nav/markdown-navigator.js" const val PREVIEW_FX_HLJS_STYLESHEET_LIGHT: String = "/com/vladsch/md/nav/hljs-default.css" const val PREVIEW_FX_HLJS_STYLESHEET_DARK: String = "/com/vladsch/md/nav/hljs-darcula.css" const val PREVIEW_FX_PRISM_JS_STYLESHEET_LIGHT: String = "/com/vladsch/md/nav/prism-default.css" const val PREVIEW_FX_PRISM_JS_STYLESHEET_DARK: String = "/com/vladsch/md/nav/prism-darcula.css" const val PREVIEW_FX_HIGHLIGHT_JS: String = "/com/vladsch/md/nav/highlight.pack.js" const val PREVIEW_FX_PRISM_JS: String = "/com/vladsch/md/nav/prism.pack.js" const val PREVIEW_TASKITEMS_FONT: String = "/com/vladsch/md/nav/taskitems.ttf" const val PREVIEW_NOTOMONO_REGULAR_FONT: String = "/com/vladsch/md/nav/noto/NotoMono-Regular.ttf" const val PREVIEW_NOTOSANS_BOLD_FONT: String = "/com/vladsch/md/nav/noto/NotoSans-Bold.ttf" const val PREVIEW_NOTOSANS_BOLDITALIC_FONT: String = "/com/vladsch/md/nav/noto/NotoSans-BoldItalic.ttf" const val PREVIEW_NOTOSANS_ITALIC_FONT: String = "/com/vladsch/md/nav/noto/NotoSans-Italic.ttf" const val PREVIEW_NOTOSANS_REGULAR_FONT: String = "/com/vladsch/md/nav/noto/NotoSans-Regular.ttf" const val PREVIEW_NOTOSERIF_BOLD_FONT: String = "/com/vladsch/md/nav/noto/NotoSerif-Bold.ttf" const val PREVIEW_NOTOSERIF_BOLDITALIC_FONT: String = "/com/vladsch/md/nav/noto/NotoSerif-BoldItalic.ttf" const val PREVIEW_NOTOSERIF_ITALIC_FONT: String = "/com/vladsch/md/nav/noto/NotoSerif-Italic.ttf" const val PREVIEW_NOTOSERIF_REGULAR_FONT: String = "/com/vladsch/md/nav/noto/NotoSerif-Regular.ttf" const val PREVIEW_GITHUB_COLLAPSE_MARKDOWN_JS: String = "/com/vladsch/md/nav/github-collapse-markdown.js" const val PREVIEW_GITHUB_COLLAPSE_IN_COMMENT_JS: String = "/com/vladsch/md/nav/github-collapse-in-comment.user.original.js" const val PREVIEW_GITHUB_COLLAPSE_LIGHT: String = "/com/vladsch/md/nav/github-collapse.css" const val PREVIEW_GITHUB_COLLAPSE_DARK: String = "/com/vladsch/md/nav/github-collapse.css" const val TASK_ITEM: String = "/icons/svg/application-undone-task-list-item.svg" const val TASK_ITEM_DARK: String = "/icons/svg/application-undone-task-list-item_dark.svg" const val TASK_ITEM_DONE: String = "/icons/svg/application-done-task-list-item.svg" const val TASK_ITEM_DONE_DARK: String = "/icons/svg/application-done-task-list-item_dark.svg" const val productId: String = "idea-multimarkdown" const val productDisplayName: String = "Markdown Navigator" @JvmStatic val pluginDescriptor: IdeaPluginDescriptor by lazy { val plugins = PluginManagerCore.getPlugins() var descriptor: IdeaPluginDescriptor? = null for (plugin in plugins) { if (PLUGIN_ID == plugin.pluginId.idString) { descriptor = plugin } } descriptor ?: throw IllegalStateException("Unexpected, plugin cannot find its own plugin descriptor") // val pluginId = PluginId.findId(PLUGIN_ID) // val pluginDescriptor = PluginManagerCore.getPlugin(pluginId) // pluginDescriptor } @JvmStatic fun getPluginDescriptor(pluginId: String): IdeaPluginDescriptor? { val plugins = PluginManagerCore.getPlugins() for (plugin in plugins) { if (pluginId == plugin.pluginId.idString) { return plugin } } return null } @JvmStatic val productVersion: String by lazy { val pluginDescriptor = pluginDescriptor val version = pluginDescriptor.version // truncate version to 3 digits and if had more than 3 append .x, that way // no separate product versions need to be created val parts = version.split(delimiters = *charArrayOf('.'), limit = 4) if (parts.size <= 3) { version } else { val newVersion = parts.subList(0, 3).reduce { total, next -> "$total.$next" } "$newVersion.x" } } @JvmStatic val fullProductVersion: String by lazy { val pluginDescriptor = pluginDescriptor pluginDescriptor.version } @JvmStatic fun getPluginCustomPath(): String? { val variants = arrayOf(PathManager.getHomePath(), PathManager.getPluginsPath()) for (variant in variants) { val path = "$variant/$productId" if (LocalFileSystem.getInstance().findFileByPath(path) != null) { return path } } return null } @JvmStatic fun getPluginPath(): String? { val variants = arrayOf(PathManager.getPluginsPath()) for (variant in variants) { val path = "$variant/$productId" if (LocalFileSystem.getInstance().findFileByPath(path) != null) { return path } } return null } @JvmStatic val instance: MdPlugin get() = ApplicationManager.getApplication().getComponent(MdPlugin::class.java) ?: throw IllegalStateException() } }
apache-2.0
2d4258ab8b6225fe192082559703b401
46.473568
162
0.659305
4.899523
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/test/java/jp/toastkid/yobidashi/browser/floating/WebViewInitializerTest.kt
2
2106
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.browser.floating import android.webkit.WebView import androidx.fragment.app.FragmentActivity import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.mockk import io.mockk.mockkObject import io.mockk.unmockkAll import io.mockk.verify import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.browser.block.AdRemover import org.junit.After import org.junit.Before import org.junit.Test class WebViewInitializerTest { @InjectMockKs private lateinit var webViewInitializer: WebViewInitializer @MockK private lateinit var preferenceApplier: PreferenceApplier @MockK private lateinit var viewModel: FloatingPreviewViewModel @MockK private lateinit var webView: WebView @MockK private lateinit var fragmentActivity: FragmentActivity @Before fun setUp() { MockKAnnotations.init(this) every { fragmentActivity.getAssets() }.returns(mockk()) every { webView.getContext() }.returns(fragmentActivity) mockkObject(AdRemover) every { AdRemover.make(any()) }.returns(mockk()) every { webView.setWebViewClient(any()) }.answers { Unit } every { webView.setWebChromeClient(any()) }.answers { Unit } } @After fun tearDown() { unmockkAll() } @Test fun invoke() { webViewInitializer.invoke(webView) verify(exactly = 1) { fragmentActivity.getAssets() } verify(exactly = 1) { webView.getContext() } verify(exactly = 1) { AdRemover.make(any()) } verify(exactly = 1) { webView.setWebViewClient(any()) } verify(exactly = 1) { webView.setWebChromeClient(any()) } } }
epl-1.0
22033ad5758522bd4db1f631a84e8151
27.093333
88
0.716524
4.490405
false
false
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/screen/dialog/LoadGameDialog.kt
1
11380
/* * 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.screen.dialog import com.badlogic.gdx.Input import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.ui.* import com.badlogic.gdx.scenes.scene2d.utils.ClickListener import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable import com.badlogic.gdx.utils.Align import com.jupiter.europa.EuropaGame import com.jupiter.europa.scene2d.ui.EuropaButton import com.jupiter.europa.scene2d.ui.EuropaButton.ClickEvent import com.jupiter.europa.scene2d.ui.ObservableDialog import com.jupiter.europa.screen.MainMenuScreen import com.badlogic.gdx.scenes.scene2d.ui.List as GuiList import com.badlogic.gdx.utils.Array as GdxArray /** * @author Nathan Templon */ public class LoadGameDialog : ObservableDialog(LoadGameDialog.DIALOG_NAME, LoadGameDialog.getDefaultSkin()) { // Enumerations public enum class LoadGameExitStates { LOAD, CANCEL } // Fields private val skinInternal = getDefaultSkin() private var mainTable: Table? = null private var loadGameLabel: Label? = null private var listTable: Table? = null private var gameList: GuiList<String>? = null private var gameListPane: ScrollPane? = null private var buttonTableInternal: Table? = null private var okButton: EuropaButton? = null private var cancelButton: EuropaButton? = null private var deleteButton: EuropaButton? = null private var widthInternal: Float = 0.toFloat() private var heightInternal: Float = 0.toFloat() public var gameToLoad: String = "" private set public var exitState: LoadGameExitStates? = null private set private var confirmDeleteDialog: ConfirmDeleteSaveDialog? = null init { this.initComponents() } // Public Methods override fun setSize(width: Float, height: Float) { super.setSize(width, height) if (this.confirmDeleteDialog != null) { this.confirmDeleteDialog!!.setSize(width, this.heightInternal) } this.widthInternal = width this.heightInternal = height } // Private Methods private fun initComponents() { this.mainTable = Table() this.listTable = Table() this.loadGameLabel = Label("Save Games", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<Label.LabelStyle>())) this.gameList = GuiList(skinInternal.get<GuiList.ListStyle>(MainMenuScreen.DEFAULT_KEY, javaClass<GuiList.ListStyle>())) this.gameList?.setItems(GdxArray(EuropaGame.game.getSaveNames())) this.gameListPane = ScrollPane(this.gameList, skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<ScrollPane.ScrollPaneStyle>())) this.listTable!!.add<ScrollPane>(this.gameListPane).pad(MainMenuScreen.LIST_WRAPPER_PADDING.toFloat()).expand().fill() this.listTable!!.background(skinInternal.get(MainMenuScreen.LIST_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.okButton = EuropaButton("Accept", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>())) this.okButton!!.addClickListener { args -> this.onLoadClick(args) } this.cancelButton = EuropaButton("Cancel", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>())) this.cancelButton!!.addClickListener { args -> this.onCancelClick(args) } this.deleteButton = EuropaButton("Delete", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>())) this.deleteButton!!.addClickListener { args -> this.onDeleteClick(args) } this.buttonTableInternal = Table() this.buttonTableInternal!!.add<EuropaButton>(this.cancelButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right().expandX() this.buttonTableInternal!!.add<EuropaButton>(this.deleteButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right() this.buttonTableInternal!!.add<EuropaButton>(this.okButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right() this.mainTable!!.pad(MainMenuScreen.TABLE_PADDING.toFloat()) this.mainTable!!.add<Label>(this.loadGameLabel).center().left() this.mainTable!!.row() this.mainTable!!.add<Table>(this.listTable).expandY().fill() this.mainTable!!.row() this.mainTable!!.add<Table>(this.buttonTableInternal).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).right().expandX().fillX() this.mainTable!!.row() this.mainTable!!.background(this.skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.getContentTable().add<Table>(this.mainTable).center().expandY().fillY().width(MainMenuScreen.DIALOG_WIDTH.toFloat()) } private fun onLoadClick(event: ClickEvent) { this.gameToLoad = this.gameList!!.getSelected().toString() this.exitState = LoadGameExitStates.LOAD this.hide() } private fun onCancelClick(event: ClickEvent) { this.gameToLoad = "" this.exitState = LoadGameExitStates.CANCEL this.hide() } private fun onDeleteClick(event: ClickEvent) { this.confirmDeleteDialog = ConfirmDeleteSaveDialog(this.gameList!!.getSelected().toString(), this.skinInternal) this.confirmDeleteDialog!!.addDialogListener({ args -> this.onConfirmDeleteSaveDialogClose(args) }, ObservableDialog.DialogEvents.HIDDEN) this.confirmDeleteDialog!!.show(this.getStage()) this.confirmDeleteDialog!!.setSize(this.widthInternal, this.heightInternal) } private fun onConfirmDeleteSaveDialogClose(args: ObservableDialog.DialogEventArgs) { if (this.confirmDeleteDialog!!.exitState === ConfirmDeleteSaveDialog.ConfirmDeleteExitStates.DELETE) { EuropaGame.game.deleteSave(this.gameList!!.getSelected().toString()) this.gameList!!.setItems(GdxArray(EuropaGame.game.getSaveNames())) this.okButton!!.setDisabled(EuropaGame.game.getSaveNames().size() == 0) } } // Nested Classes private class ConfirmDeleteSaveDialog(public val saveToDelete: String, private val skinInternal: Skin) : ObservableDialog(LoadGameDialog.ConfirmDeleteSaveDialog.DIALOG_NAME, skinInternal.get(MainMenuScreen.POPUP_DIALOG_STYLE_KEY, javaClass<Window.WindowStyle>())) { // Enumerations public enum class ConfirmDeleteExitStates { DELETE, CANCEL } private var titleLabelInternal: Label? = null private var mainTable: Table? = null private var yesButton: TextButton? = null private var noButton: TextButton? = null public var exitState: ConfirmDeleteExitStates? = null private set init { this.initComponents() } // Public Methods override fun setSize(width: Float, height: Float) { super.setSize(width, height) } // Private Methods private fun initComponents() { this.titleLabelInternal = Label("Are you sure you want to delete the save game \"" + this.saveToDelete + "\"?", skinInternal.get(MainMenuScreen.INFO_STYLE_KEY, javaClass<Label.LabelStyle>())) this.titleLabelInternal!!.setWrap(true) this.titleLabelInternal!!.setAlignment(Align.center) this.yesButton = TextButton("Yes", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>())) this.yesButton!!.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { if (event!!.getButton() == Input.Buttons.LEFT && [email protected]!!.isDisabled()) { [email protected]() } [email protected]!!.setChecked(false) } }) this.noButton = TextButton("No", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>())) this.noButton!!.addListener(object : ClickListener() { override fun clicked(event: InputEvent?, x: Float, y: Float) { if (event!!.getButton() == Input.Buttons.LEFT && [email protected]!!.isDisabled()) { [email protected]() } [email protected]!!.setChecked(false) } }) this.mainTable = Table() this.mainTable!!.add<Label>(this.titleLabelInternal).colspan(2).width(MainMenuScreen.DIALOG_WIDTH.toFloat()).expandX().fillX() this.mainTable!!.row() this.mainTable!!.add<TextButton>(this.noButton).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).right() this.mainTable!!.add<TextButton>(this.yesButton).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).left() this.mainTable!!.padLeft(MainMenuScreen.TABLE_PADDING.toFloat()) this.mainTable!!.padRight(MainMenuScreen.TABLE_PADDING.toFloat()) this.mainTable!!.background(this.skinInternal.get(MainMenuScreen.POPUP_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.getContentTable().add<Table>(this.mainTable).row() } private fun onYesButtonClick() { this.exitState = ConfirmDeleteExitStates.DELETE this.hide() } private fun onNoButtonClick() { this.exitState = ConfirmDeleteExitStates.CANCEL this.hide() } companion object { // Constants private val DIALOG_NAME = "" } }// Properties companion object { // Constants private val DIALOG_NAME = "" // Static Methods private fun getDefaultSkin(): Skin { return MainMenuScreen.createMainMenuSkin() } } }
mit
06d94f90b2abeb5a9afca300afffc74e
41.462687
269
0.690685
4.92854
false
false
false
false
square/curtains
curtains/src/main/java/curtains/internal/CurrentFrameMetricsListener.kt
1
1248
package curtains.internal import android.os.Handler import android.os.Looper import android.view.FrameMetrics import android.view.FrameMetrics.VSYNC_TIMESTAMP import android.view.Window import android.view.Window.OnFrameMetricsAvailableListener import androidx.annotation.RequiresApi import kotlin.LazyThreadSafetyMode.NONE @RequiresApi(26) internal class CurrentFrameMetricsListener( private val frameTimeNanos: Long, private val callback: (FrameMetrics) -> Unit ) : OnFrameMetricsAvailableListener { private var removed = false override fun onFrameMetricsAvailable( window: Window, frameMetrics: FrameMetrics, dropCountSinceLastInvocation: Int ) { if (!removed) { removed = true // We're on the frame metrics threads, the listener is stored in a non thread // safe list so we need to jump back to the main thread to remove. mainThreadHandler.post { window.removeOnFrameMetricsAvailableListener(this) } } val vsyncTimestamp = frameMetrics.getMetric(VSYNC_TIMESTAMP) if (vsyncTimestamp == frameTimeNanos) { callback(frameMetrics) } } companion object { private val mainThreadHandler by lazy(NONE) { Handler(Looper.getMainLooper()) } } }
apache-2.0
eed68428c2a51a0983352e73a42b9728
26.755556
83
0.745994
4.674157
false
false
false
false
Raniz85/ffbe-grinder
src/main/kotlin/se/raneland/ffbe/ui/GraphSelector.kt
1
6309
/* * Copyright (c) 2017, Daniel Raniz Raneland */ package se.raneland.ffbe.ui import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.dataformat.yaml.YAMLFactory import com.fasterxml.jackson.module.kotlin.readValue import net.miginfocom.swing.MigLayout import se.raneland.ffbe.state.MachineState import se.raneland.ffbe.state.action.GameAction import se.raneland.ffbe.state.transition.StateTransition import se.raneland.ffbe.state.transition.TransitionTest import java.awt.Dimension import java.io.IOException import java.io.InputStream import java.time.Duration import javax.swing.JButton import javax.swing.JDialog import javax.swing.JFrame import javax.swing.JList import javax.swing.JOptionPane import javax.swing.JTextArea val DESCRIPTIONS = listOf( GraphDescription("Stage Grinding (Lapis Refresh)", """ Runs the second quest of any stage over and over again, refreshing NRG with lapis. Navigate to any vortex or world stage and the script will repeatedly run the second stage. """.trimIndent(), "/machines/stage.yml"), GraphDescription("Stage Grinding (No Lapis Refresh)", """ Runs the second quest of any stage over and over again, waiting for NRG to recover. Navigate to any vortex or world stage and the script will repeatedly run the second stage. """.trimIndent(), "/machines/stage-no-lapis.yml"), GraphDescription("Raid Summon", """ Performs Multi-Summon for raid coins over and over again """.trimIndent(), "/machines/raid-summon.yml") ) data class StateGraph(val name: String, val description: String, val initialState: MachineState) /** * @author Raniz * @since 2017-04-19. */ class GraphSelector(owner: JFrame) : JDialog(owner, "Select", true) { val descriptions: JList<GraphDescription> val descriptionField: JTextArea val cancelButton: JButton val okButton: JButton var selectedGraph: StateGraph? = null init { layout = MigLayout( "fill", "[align left][align right]", "[fill][grow 0, shrink 0]" ) descriptions = JList(DESCRIPTIONS.toTypedArray()) descriptionField = JTextArea() cancelButton = JButton("Cancel") okButton = JButton("OK") add(descriptions, "cell 0 0, growy") add(descriptionField, "cell 1 0, grow") add(cancelButton, "cell 0 1") add(okButton, "cell 1 1") descriptions.addListSelectionListener { val selectedDescription = descriptions.selectedValue if (selectedDescription == null) { descriptionField.text = "" okButton.isEnabled = false } else { descriptionField.text = selectedDescription.description okButton.isEnabled = true } } descriptions.selectedIndex = 0 descriptionField.lineWrap = true descriptionField.isEditable = false cancelButton.addActionListener { selectedGraph = null isVisible = false } okButton.addActionListener { val selectedDescription = descriptions.selectedValue if (selectedDescription == null) { JOptionPane.showMessageDialog(this, "No graph selected", "Error", JOptionPane.ERROR_MESSAGE) } selectedGraph = getResource(selectedDescription.path).use { if (it == null) { JOptionPane.showMessageDialog(this, "Graph not found", "Error", JOptionPane.ERROR_MESSAGE) return@use null } try { return@use readStateGraph(it) } catch(e: IOException) { JOptionPane.showMessageDialog(this, "Could not read graph: ${e.message}", "Error", JOptionPane.ERROR_MESSAGE) return@use null } } if (selectedGraph != null) { isVisible = false } } pack() minimumSize = Dimension(600, 600) preferredSize = minimumSize setLocationRelativeTo(owner) } fun select(): StateGraph? { isVisible = true return selectedGraph } } data class GraphDescription(val name: String, val description: String, val path: String) { override fun toString() = name } class DurationDeserialiser: JsonDeserializer<Duration>() { override fun deserialize(p: JsonParser, ctxt: DeserializationContext): Duration = Duration.parse(p.valueAsString) } private val yamlMapper = ObjectMapper(YAMLFactory()).apply { findAndRegisterModules() registerModule(object: SimpleModule() { init { addDeserializer(Duration::class.java, DurationDeserialiser()) } }) enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) } private fun getResource(path: String) = StringStateGraph::class.java.getResourceAsStream(path) /** * @author Raniz * @since 2017-04-10. */ fun readStateGraph(yml: InputStream): StateGraph { val graph = yamlMapper.readValue<StringStateGraph>(yml) val states = graph.states.mapValues { (name, gState) -> MachineState(name, actions = gState.actions) } graph.states.forEach { (name, gState) -> val state = states[name]!! gState.transitions .map { (nextState, test) -> StateTransition(test, states[nextState] ?: error("State ${nextState} not found")) } .forEach { state.transitions.add(it) } } return StateGraph(graph.name, graph.description, states[graph.initialState]!!) } data class StringStateGraph(val name: String, val description: String, val initialState: String, val states: Map<String, StringState>) data class StringState(val transitions: Map<String, TransitionTest> = mapOf(), val actions: List<GameAction> = listOf())
mit
5fb9f8f664f781933c1babc912ffd3ac
35.680233
134
0.652877
4.750753
false
false
false
false
VisualDig/visualdig-kotlin
dig/src/main/io/visualdig/exceptions/DigSpacialException.kt
1
8464
package io.visualdig.exceptions import io.visualdig.actions.SpacialSearchAction import io.visualdig.results.CloseResult import io.visualdig.results.Result import io.visualdig.results.SpacialSearchResult import io.visualdig.spacial.Direction import io.visualdig.spacial.SearchPriority import java.lang.Math.abs import java.util.* class DigSpacialException(action: SpacialSearchAction, result: SpacialSearchResult) : Exception(getDetailedMessage(action, result)) { companion object { private fun getDetailedMessage(action: SpacialSearchAction, result: SpacialSearchResult): String { val direction = action.direction.description.toLowerCase(Locale.ENGLISH) val elementType = action.elementType.description.toLowerCase(Locale.ENGLISH) val queryText = action.prevQueries.first().queryDescription() val errorText: String when (result.result) { Result.Failure_NoMatch -> { if (result.closeResults.isEmpty()) { errorText = noCloseMatchesMessage(direction, elementType, queryText) } else { val htmlId = result.closeResults.first().htmlId val spacialDescription = getSpacialDescription(action.direction, result.closeResults.first()) errorText = closeMatchMessage(direction, elementType, htmlId, queryText, spacialDescription) } } Result.Failure_AmbiguousMatch -> { if(action.priority == SearchPriority.DISTANCE) { errorText = ambiguousDistanceMatchMessage(direction, elementType, result.closeResults, queryText) } else if(action.priority == SearchPriority.ALIGNMENT) { errorText = ambiguousAlignmentMatchMessage(direction, elementType, result.closeResults, queryText) } else { throw DigFatalException("Result should not be ambiguous if alignment and distance based") } } Result.Failure_QueryExpired -> { errorText = "Query expired TODO"} Result.Success -> { throw DigFatalException("Result from spacial search should not be successful inside of an exception method") } } return errorText } private fun ambiguousDistanceMatchMessage(direction: String, elementType: String, closeResults: List<CloseResult>, queryText: String): String { val foundString = "$elementType B and $elementType C which both are the same distance from element A." val capitalizeFoundString = foundString.capitalize() val bElementInfoText : String if (closeResults[0].htmlId == null) { bElementInfoText = "First ambiguous element (no HTML id)" } else { val htmlId = closeResults[0].htmlId bElementInfoText = "First ambiguous element with HTML id: $htmlId" } val cElementInfoText : String if (closeResults[1].htmlId == null) { cElementInfoText = "Second ambiguous element (no HTML id)" } else { val htmlId = closeResults[1].htmlId cElementInfoText = "Second ambiguous element with HTML id: $htmlId" } return """ Could not find an unambiguous $elementType element $direction of element A. Expected: ___ ___ | | | | | A | | B | |___| |___| Found: $capitalizeFoundString Suggestions: - Are these elements overlapping on the web page? - Try setting the priority to DistanceThenAlignment or AlignmentThenDistance to resolve which factor matters more in this test: distance or alignment. Additional Info: A = $queryText B = $bElementInfoText C = $cElementInfoText """ } private fun ambiguousAlignmentMatchMessage(direction: String, elementType: String, closeResults: List<CloseResult>, queryText: String): String { val foundString = "$elementType B and $elementType C which both have the same alignment relative to element A." val capitalizeFoundString = foundString.capitalize() val bElementInfoText : String if (closeResults[0].htmlId == null) { bElementInfoText = "First ambiguous element (no HTML id)" } else { val htmlId = closeResults[0].htmlId bElementInfoText = "First ambiguous element with HTML id: $htmlId" } val cElementInfoText : String if (closeResults[1].htmlId == null) { cElementInfoText = "Second ambiguous element (no HTML id)" } else { val htmlId = closeResults[1].htmlId cElementInfoText = "Second ambiguous element with HTML id: $htmlId" } return """ Could not find an unambiguous $elementType element $direction of element A. Expected: ___ ___ | | | | | A | | B | |___| |___| Found: $capitalizeFoundString Suggestions: - Are these elements overlapping on the web page? - Try setting the priority to DistanceThenAlignment or AlignmentThenDistance to resolve which factor matters more in this test: distance or alignment. Additional Info: A = $queryText B = $bElementInfoText C = $cElementInfoText """ } private fun closeMatchMessage(direction: String, elementType: String, htmlId: String?, queryText: String, spacialDescription: String): String { val closestMatchIdText : String if(htmlId == null) { closestMatchIdText = "There was a close match, but it has no HTML id." } else { closestMatchIdText = "The closest match was an element with id: $htmlId." } return """ Unable to find $elementType $direction of $queryText. $closestMatchIdText $spacialDescription """ } private fun noCloseMatchesMessage(direction: String, elementType: String, queryText: String): String { return """ Unable to find $elementType $direction of $queryText. There are no close matches. This is likely because the element isn't visible or it is actually east of $queryText. """ } private fun getSpacialDescription(direction: Direction, result: CloseResult): String { val directionText = direction.description.toLowerCase(Locale.ENGLISH) var offDirection = "" var offAmount = 0 var isAlignmentMessage = true when (direction) { Direction.EAST -> { offAmount = (abs(result.y) - result.tolerance) if (result.y < 0) { offDirection = "south" } else { offDirection = "north" } isAlignmentMessage = result.x > 0 } Direction.WEST -> { offAmount = (abs(result.y) - result.tolerance) if (result.y < 0) { offDirection = "south" } else { offDirection = "north" } isAlignmentMessage = result.x < 0 } Direction.NORTH -> { offAmount = (abs(result.x) - result.tolerance) if (result.x < 0) { offDirection = "west" } else { offDirection = "east" } isAlignmentMessage = result.y > 0 } Direction.SOUTH -> { offAmount = (abs(result.x) - result.tolerance) if (result.x < 0) { offDirection = "west" } else { offDirection = "east" } isAlignmentMessage = result.y < 0 } } if (isAlignmentMessage) { return "The element was $offAmount pixels too far $offDirection to be considered aligned $directionText." } return "TODO WOOPS" } } }
mit
6c0251ecdc214ab7211bd3bba6a3e09a
36.622222
152
0.569589
5.404853
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/test/java/com/ichi2/anki/dialogs/tags/TagsDialogTest.kt
1
31199
/* Copyright (c) 2021 Tarek Mohamed <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.dialogs.tags import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.RadioGroup import androidx.fragment.app.testing.FragmentScenario import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry import androidx.recyclerview.widget.RecyclerView import androidx.test.ext.junit.runners.AndroidJUnit4 import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.WhichButton import com.afollestad.materialdialogs.actions.getActionButton import com.afollestad.materialdialogs.customview.getCustomView import com.ichi2.anki.R import com.ichi2.testutils.ParametersUtils import com.ichi2.testutils.RecyclerViewUtils import com.ichi2.ui.CheckBoxTriStates import com.ichi2.utils.ListUtil import org.hamcrest.MatcherAssert import org.hamcrest.core.IsNull import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.kotlin.whenever import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference @RunWith(AndroidJUnit4::class) class TagsDialogTest { @Test fun testTagsDialogCustomStudyOptionInterface() { val type = TagsDialog.DialogType.CUSTOM_STUDY_TAGS val allTags = listOf("1", "2", "3", "4") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, ArrayList(), allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val optionsGroup = body.findViewById<RadioGroup>(R.id.tags_dialog_options_radiogroup) Assert.assertEquals(optionsGroup.visibility.toLong(), View.VISIBLE.toLong()) val expectedOption = 1 optionsGroup.getChildAt(expectedOption).performClick() dialog.getActionButton(WhichButton.POSITIVE).callOnClick() Mockito.verify(mockListener, Mockito.times(1)).onSelectedTags(ArrayList(), ArrayList(), expectedOption) } } @Test fun testTagsDialogCustomStudyOptionFragmentAPI() { val type = TagsDialog.DialogType.CUSTOM_STUDY_TAGS val allTags = listOf("1", "2", "3", "4") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, ArrayList(), allTags) .arguments val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val returnedList = AtomicReference<List<String>?>() val returnedOption = AtomicInteger() f.parentFragmentManager.setFragmentResultListener( TagsDialogListener.ON_SELECTED_TAGS_KEY, mockLifecycleOwner(), { _: String?, bundle: Bundle -> returnedList.set(bundle.getStringArrayList(TagsDialogListener.ON_SELECTED_TAGS__SELECTED_TAGS)) returnedOption.set(bundle.getInt(TagsDialogListener.ON_SELECTED_TAGS__OPTION)) } ) val body = dialog!!.getCustomView() val optionsGroup = body.findViewById<RadioGroup>(R.id.tags_dialog_options_radiogroup) Assert.assertEquals(optionsGroup.visibility.toLong(), View.VISIBLE.toLong()) val expectedOption = 2 optionsGroup.getChildAt(expectedOption).performClick() dialog.getActionButton(WhichButton.POSITIVE).callOnClick() ListUtil.assertListEquals(ArrayList(), returnedList.get()) Assert.assertEquals(expectedOption.toLong(), returnedOption.get().toLong()) } } // regression test #8762 // test for #8763 @Test fun test_AddNewTag_shouldBeVisibleInRecyclerView_andSortedCorrectly() { val type = TagsDialog.DialogType.EDIT_TAGS val allTags = listOf("a", "b", "d", "e") val checkedTags = listOf("a", "b") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val tag = "zzzz" f.addTag(tag) // workaround robolectric recyclerView issue // update recycler recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) val lastItem = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 4) val newTagItemItem = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) Assert.assertEquals(5, recycler.adapter!!.itemCount.toLong()) Assert.assertEquals(tag, newTagItemItem.text) Assert.assertTrue(newTagItemItem.isChecked) Assert.assertNotEquals(tag, lastItem.text) Assert.assertFalse(lastItem.isChecked) } } // test for #8763 @Test fun test_AddNewTag_existingTag_shouldBeSelectedAndSorted() { val type = TagsDialog.DialogType.EDIT_TAGS val allTags = listOf("a", "b", "d", "e") val checkedTags = listOf("a", "b") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val tag = "e" f.addTag(tag) // workaround robolectric recyclerView issue // update recycler recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) val lastItem = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 3) val newTagItemItem = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) Assert.assertEquals(4, recycler.adapter!!.itemCount.toLong()) Assert.assertEquals(tag, newTagItemItem.text) Assert.assertTrue(newTagItemItem.isChecked) Assert.assertNotEquals(tag, lastItem.text) Assert.assertFalse(lastItem.isChecked) } } @Test fun test_checked_unchecked_indeterminate() { val type = TagsDialog.DialogType.EDIT_TAGS val expectedAllTags = listOf("a", "b", "d", "e") val checkedTags = listOf("a", "b") val uncheckedTags = listOf("b", "d") val expectedCheckedTags = listOf("a") val expectedUncheckedTags = listOf("d", "e") val expectedIndeterminate = listOf("b") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, uncheckedTags, expectedAllTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) // workaround robolectric recyclerView issue // update recycler recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) val itemCount = recycler.adapter!!.itemCount val foundAllTags: MutableList<String> = ArrayList() val foundCheckedTags: MutableList<String> = ArrayList() val foundUncheckedTags: MutableList<String> = ArrayList() val foundIndeterminate: MutableList<String> = ArrayList() for (i in 0 until itemCount) { val vh = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, i) val tag = vh.text foundAllTags.add(tag) when (vh.checkboxState) { CheckBoxTriStates.State.INDETERMINATE -> foundIndeterminate.add(tag) CheckBoxTriStates.State.UNCHECKED -> foundUncheckedTags.add(tag) CheckBoxTriStates.State.CHECKED -> foundCheckedTags.add(tag) else -> Assert.fail("Unknown CheckBoxTriStates.State? " + vh.checkboxState) } } ListUtil.assertListEquals(expectedAllTags, foundAllTags) ListUtil.assertListEquals(expectedCheckedTags, foundCheckedTags) ListUtil.assertListEquals(expectedUncheckedTags, foundUncheckedTags) ListUtil.assertListEquals(expectedIndeterminate, foundIndeterminate) } } @Test fun test_TagsDialog_expandPathToCheckedTagsUponOpening() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf( "fruit::apple", "fruit::pear", "fruit::pear::big", "sport::football", "sport::tennis", "book" ) val checkedTags = listOf( "fruit::pear::big", "sport::tennis" ) val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) fun getItem(index: Int): TagsArrayAdapter.ViewHolder { return RecyclerViewUtils.viewHolderAt(recycler, index) } fun updateLayout() { recycler.measure(0, 0) recycler.layout(0, 0, 100, 2000) } updateLayout() // v fruit [-] // - apple [ ] // v pear [-] // - big [x] // v sport [-] // - football [ ] // - tennis [x] // - book [ ] Assert.assertEquals(8, recycler.adapter!!.itemCount.toLong()) Assert.assertEquals("fruit", getItem(0).text) Assert.assertEquals("fruit::apple", getItem(1).text) Assert.assertEquals("fruit::pear", getItem(2).text) Assert.assertEquals("fruit::pear::big", getItem(3).text) Assert.assertEquals("sport", getItem(4).text) Assert.assertEquals("sport::football", getItem(5).text) Assert.assertEquals("sport::tennis", getItem(6).text) Assert.assertEquals("book", getItem(7).text) } } @Test fun test_AddNewTag_newHierarchicalTag_pathToItShouldBeExpanded() { val type = TagsDialog.DialogType.EDIT_TAGS val allTags = listOf("common::speak", "common::speak::daily", "common::sport::tennis", "common::sport::football") val checkedTags = listOf("common::speak::daily", "common::sport::tennis") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val tag = "common::sport::football::small" f.addTag(tag) // v common [-] // v speak [-] // - daily [x] // v sport [-] // v football [-] // > small [x] // - tennis [x] recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) Assert.assertEquals(7, recycler.adapter!!.itemCount.toLong()) val item0 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 0) val item1 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 1) val item2 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) val item3 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 3) val item4 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 4) val item5 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 5) val item6 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 6) Assert.assertEquals("common", item0.text) Assert.assertEquals("common::speak", item1.text) Assert.assertEquals("common::speak::daily", item2.text) Assert.assertEquals("common::sport", item3.text) Assert.assertEquals("common::sport::football", item4.text) Assert.assertEquals("common::sport::football::small", item5.text) Assert.assertEquals("common::sport::tennis", item6.text) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, item0.mCheckBoxView.state) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, item1.mCheckBoxView.state) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, item2.mCheckBoxView.state) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, item3.mCheckBoxView.state) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, item4.mCheckBoxView.state) Assert.assertTrue(item5.mCheckBoxView.isChecked) Assert.assertTrue(item6.mCheckBoxView.isChecked) } } @Test fun test_AddNewTag_newHierarchicalTag_willUniformHierarchicalTag() { val type = TagsDialog.DialogType.EDIT_TAGS val allTags = listOf("common") val checkedTags = listOf("common") val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val tag = "common::::careless" f.addTag(tag) // v common [x] // > blank [-] // - careless [x] recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) Assert.assertEquals(3, recycler.adapter!!.itemCount.toLong()) val item0 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 0) val item1 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 1) val item2 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) Assert.assertEquals("common", item0.text) Assert.assertEquals("common::blank", item1.text) Assert.assertEquals("common::blank::careless", item2.text) Assert.assertTrue(item0.mCheckBoxView.isChecked) Assert.assertTrue(item1.mCheckBoxView.state == CheckBoxTriStates.State.INDETERMINATE) Assert.assertTrue(item2.mCheckBoxView.isChecked) } } @Test fun test_SearchTag_showAllRelevantTags() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf( "common::speak", "common::speak::tennis", "common::sport::tennis", "common::sport::football", "common::sport::football::small" ) val checkedTags = listOf( "common::speak::tennis", "common::sport::tennis", "common::sport::football::small" ) val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) val adapter = recycler.adapter!! as TagsArrayAdapter adapter.filter.filter("tennis") // v common [-] // v speak [-] // - tennis [x] // v sport [-] // - tennis [x] recycler.measure(0, 0) recycler.layout(0, 0, 100, 1000) Assert.assertEquals(5, recycler.adapter!!.itemCount.toLong()) val item0 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 0) val item1 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 1) val item2 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 2) val item3 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 3) val item4 = RecyclerViewUtils.viewHolderAt<TagsArrayAdapter.ViewHolder>(recycler, 4) Assert.assertEquals("common", item0.text) Assert.assertEquals("common::speak", item1.text) Assert.assertEquals("common::speak::tennis", item2.text) Assert.assertEquals("common::sport", item3.text) Assert.assertEquals("common::sport::tennis", item4.text) } } @Test fun test_SearchTag_willInheritExpandState() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf("common::speak", "common::sport::tennis") val checkedTags = emptyList<String>() val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) fun updateLayout() { recycler.measure(0, 0) recycler.layout(0, 0, 100, 2000) } val adapter = recycler.adapter!! as TagsArrayAdapter adapter.filter.filter("sport") updateLayout() // v common [ ] // v sport [ ] // - tennis [ ] Assert.assertEquals(3, recycler.adapter!!.itemCount.toLong()) adapter.filter.filter("") updateLayout() // v common [ ] // - speak [ ] // v sport [ ] // - tennis [ ] Assert.assertEquals(4, recycler.adapter!!.itemCount.toLong()) } } @Test fun test_CheckTags_intermediateTagsShouldToggleDynamically() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf( "common::speak", "common::speak::tennis", "common::sport::tennis", "common::sport::football", "common::sport::football::small" ) val checkedTags = emptyList<String>() val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val body = dialog!!.getCustomView() val recycler: RecyclerView = body.findViewById(R.id.tags_dialog_tags_list) fun getItem(index: Int): TagsArrayAdapter.ViewHolder { return RecyclerViewUtils.viewHolderAt(recycler, index) } fun updateLayout() { recycler.measure(0, 0) recycler.layout(0, 0, 100, 2000) } updateLayout() getItem(0).itemView.performClick() updateLayout() getItem(1).itemView.performClick() updateLayout() getItem(3).itemView.performClick() updateLayout() getItem(4).itemView.performClick() updateLayout() // v common [ ] // v speak [ ] // - tennis [ ] // v sport [ ] // v football [ ] // - small [ ] // - tennis [ ] Assert.assertEquals(7, recycler.adapter!!.itemCount.toLong()) getItem(2).mCheckBoxView.performClick() updateLayout() getItem(5).mCheckBoxView.performClick() updateLayout() // v common [-] // v speak [-] // - tennis [x] // v sport [-] // v football [-] // - small [x] // - tennis [ ] Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(0).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(1).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, getItem(2).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(3).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(4).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, getItem(5).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(6).checkboxState) getItem(2).mCheckBoxView.performClick() updateLayout() getItem(5).mCheckBoxView.performClick() updateLayout() // v common [ ] // v speak [ ] // - tennis [ ] // v sport [ ] // v football [ ] // - small [ ] // - tennis [ ] Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(0).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(1).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(2).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(3).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(4).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(5).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(6).checkboxState) getItem(5).mCheckBoxView.performClick() updateLayout() // v common [-] // v speak [ ] // - tennis [ ] // v sport [-] // v football [-] // - small [x] // - tennis [ ] Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(0).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(1).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(2).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(3).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(4).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, getItem(5).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(6).checkboxState) getItem(3).mCheckBoxView.performClick() updateLayout() getItem(5).mCheckBoxView.performClick() updateLayout() // v common [-] // v speak [ ] // - tennis [ ] // v sport [x] // v football [ ] // - small [ ] // - tennis [ ] Assert.assertEquals(CheckBoxTriStates.State.INDETERMINATE, getItem(0).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(1).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(2).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.CHECKED, getItem(3).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(4).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(5).checkboxState) Assert.assertEquals(CheckBoxTriStates.State.UNCHECKED, getItem(6).checkboxState) } } @Test // #11089 fun test_SearchTag_spaceWillBeFilteredCorrectly() { val type = TagsDialog.DialogType.FILTER_BY_TAG val allTags = listOf("hello::world") val checkedTags = emptyList<String>() val args = TagsDialog(ParametersUtils.whatever()) .withArguments(type, checkedTags, allTags) .arguments val mockListener = Mockito.mock(TagsDialogListener::class.java) val factory = TagsDialogFactory(mockListener) val scenario = FragmentScenario.launch(TagsDialog::class.java, args, R.style.Theme_AppCompat, factory) scenario.moveToState(Lifecycle.State.STARTED) scenario.onFragment { f: TagsDialog -> val dialog = f.dialog as MaterialDialog? MatcherAssert.assertThat(dialog, IsNull.notNullValue()) val editText = f.getSearchView()!!.findViewById<EditText>(R.id.search_src_text)!! editText.setText("hello ") Assert.assertEquals( "The space should be replaced by '::' without mistakenly clear everything.", "hello::", editText.text.toString() ) editText.setText("hello") editText.text.insert(5, " ") Assert.assertEquals("Should complete 2 colons.", "hello::", editText.text.toString()) editText.setText("hello:") editText.text.insert(6, " ") Assert.assertEquals("Should complete 1 colon.", "hello::", editText.text.toString()) editText.setText("hello::") editText.text.insert(7, " ") Assert.assertEquals("Should do nothing.", "hello::", editText.text.toString()) editText.setText("") editText.text.insert(0, " ") Assert.assertEquals("Should not crash.", "::", editText.text.toString()) } } companion object { private fun mockLifecycleOwner(): LifecycleOwner { val owner = Mockito.mock(LifecycleOwner::class.java) val lifecycle = LifecycleRegistry(owner) lifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) whenever(owner.lifecycle).thenReturn(lifecycle) return owner } } }
gpl-3.0
f1685e646b93e1445dc8a1c4444ecb46
48.600954
121
0.628802
4.991041
false
true
false
false
Samourai-Wallet/samourai-wallet-android
app/src/main/java/com/samourai/wallet/tor/TorManager.kt
1
7437
package com.samourai.wallet.tor import android.app.Application import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Process import android.widget.Toast import androidx.core.app.NotificationCompat import androidx.core.app.TaskStackBuilder import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.samourai.wallet.BuildConfig import com.samourai.wallet.MainActivity2 import com.samourai.wallet.R import com.samourai.wallet.SamouraiApplication import com.samourai.wallet.util.PrefsUtil import io.matthewnelson.topl_core_base.TorConfigFiles import io.matthewnelson.topl_service.TorServiceController import io.matthewnelson.topl_service.TorServiceController.* import io.matthewnelson.topl_service.lifecycle.BackgroundManager import io.matthewnelson.topl_service.notification.ServiceNotification import org.json.JSONException import org.json.JSONObject import java.io.File import java.net.InetSocketAddress import java.net.Proxy /** * samourai-wallet-android * */ object TorManager { lateinit var stopTorDelaySettingAtAppStartup: String private set private var proxy: Proxy? = null enum class TorState { WAITING, ON, OFF } var appContext: SamouraiApplication? = null private val torStateLiveData: MutableLiveData<TorState> = MutableLiveData() private val torProgress: MutableLiveData<Int> = MutableLiveData() var torState: TorState = TorState.OFF set(value) { field = value torStateLiveData.postValue(value) } fun startTor() { TorServiceController.startTor() } private fun generateTorServiceNotificationBuilder( ): ServiceNotification.Builder { var contentIntent: PendingIntent? = null appContext?.packageManager?.getLaunchIntentForPackage(appContext!!.packageName)?.let { intent -> contentIntent = PendingIntent.getActivity( appContext, 0, intent, 0 ) } return ServiceNotification.Builder( channelName = "Tor service", channelDescription = "Tor foreground service notification", channelID = SamouraiApplication.TOR_CHANNEL_ID, notificationID = 12 ) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setImageTorNetworkingEnabled(R.drawable.ic_samourai_tor_enabled) .setImageTorDataTransfer(R.drawable.ic_samourai_tor_data_transfer) .setImageTorNetworkingDisabled(R.drawable.ic_samourai_tor_idle) .setCustomColor(R.color.green_ui_2) .enableTorRestartButton(true) .enableTorStopButton(false) .showNotification(true) .also { builder -> contentIntent?.let { builder.setContentIntent(it) } } } /** * for a cleaner * */ private fun generateBackgroundManagerPolicy( ): BackgroundManager.Builder.Policy { val builder = BackgroundManager.Builder() return builder.runServiceInForeground(true) } private fun setupTorServices( application: Application, serviceNotificationBuilder: ServiceNotification.Builder, ): Builder { val installDir = File(application.applicationInfo.nativeLibraryDir) val configDir = application.getDir("torservice", Context.MODE_PRIVATE) val builder = TorConfigFiles.Builder(installDir, configDir) builder.torExecutable(File(installDir, "libTor.so")) return Builder( application = application, torServiceNotificationBuilder = serviceNotificationBuilder, backgroundManagerPolicy = generateBackgroundManagerPolicy(), buildConfigVersionCode = BuildConfig.VERSION_CODE, defaultTorSettings = TorSettings(), geoipAssetPath = "common/geoip", geoip6AssetPath = "common/geoip6", ) .useCustomTorConfigFiles(builder.build()) .setBuildConfigDebug(BuildConfig.DEBUG) .setEventBroadcaster(eventBroadcaster = TorEventBroadcaster()) } fun isRequired(): Boolean { return PrefsUtil.getInstance(appContext).getValue(PrefsUtil.ENABLE_TOR, false); } fun isConnected(): Boolean { return getTorStateLiveData().value == TorState.ON } fun getTorStateLiveData(): LiveData<TorState> { return torStateLiveData } fun getTorBootstrapProgress(): LiveData<Int> { return torProgress } fun getProxy(): Proxy? { return proxy; } fun setUp(context: SamouraiApplication) { appContext = context val builder = setupTorServices( context, generateTorServiceNotificationBuilder(), ) try { builder.build() } catch (e: Exception) { e.message?.let { } } TorServiceController.appEventBroadcaster?.let { (it as TorEventBroadcaster).liveTorState.observeForever { torEventState -> when (torEventState.state) { "Tor: Off" -> { torState = TorState.OFF } "Tor: Starting" -> { torState = TorState.WAITING } "Tor: Stopping" -> { torState = TorState.WAITING } } } it.torLogs.observeForever { log -> if (log.contains("Bootstrapped 100%")) { torState = TorState.ON } if (log.contains("NEWNYM")) { val message = log.substring(log.lastIndexOf("|"), log.length) Toast.makeText(appContext, message.replace("|", ""), Toast.LENGTH_SHORT).show() } } it.torBootStrapProgress.observeForever { log -> torProgress.postValue(log) } it.torPortInfo.observeForever { torInfo -> torInfo.socksPort?.let { port -> createProxy(port) } } } } private fun createProxy(proxyUrl: String) { val host = proxyUrl.split(":")[0].trim() val port = proxyUrl.split(":")[1] proxy = Proxy(Proxy.Type.SOCKS, InetSocketAddress( host, port.trim().toInt())) } fun toJSON(): JSONObject { val jsonPayload = JSONObject(); try { jsonPayload.put("active", PrefsUtil.getInstance(appContext).getValue(PrefsUtil.ENABLE_TOR,false)); } catch (ex: JSONException) { // throw RuntimeException(ex); } catch (ex: ClassCastException) { // throw RuntimeException(ex); } return jsonPayload } fun fromJSON(jsonPayload: JSONObject) { try { if (jsonPayload.has("active")) { PrefsUtil.getInstance(appContext).setValue(PrefsUtil.ENABLE_TOR, jsonPayload.getBoolean("active")); } } catch (ex: JSONException) { } } }
unlicense
cb265e58e268ef149d69bf026d6fcb77
31.334783
115
0.599973
5.143154
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/validator/DeprecateFIXME.kt
1
1407
package de.westnordost.streetcomplete.quests.validator import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment class DeprecateFIXME() : OsmFilterQuestType<Boolean>() { override val elementFilter = "nodes, ways, relations with FIXME and !fixme" override val commitMessage = "convert FIXME to fixme" override val icon = R.drawable.ic_quest_power override fun getTitle(tags: Map<String, String>) = R.string.quest_convert_FIXME_to_fixme override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> { val name = tags["FIXME"] return if (name != null) arrayOf(name) else arrayOf() } override fun createForm() = YesNoQuestAnswerFragment() override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) { if (answer){ val fixme = changes.getPreviousValue("FIXME")!! changes.delete("FIXME") changes.add("fixme", fixme) } } override val wikiLink = "Key:fixme" override val questTypeAchievements: List<QuestTypeAchievement> get() = listOf() }
gpl-3.0
8aa6d33abc34bb2a38edd9c369ec6d76
38.083333
101
0.731343
4.69
false
false
false
false
tokenbrowser/token-android-client
app/src/main/java/com/toshi/manager/chat/SofaMessageManager.kt
1
10763
/* * Copyright (c) 2017. Toshi Inc * * 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 com.toshi.manager.chat import com.toshi.BuildConfig import com.toshi.R import com.toshi.crypto.HDWallet import com.toshi.crypto.signal.ChatService import com.toshi.crypto.signal.store.ProtocolStore import com.toshi.crypto.signal.store.SignalTrustStore import com.toshi.manager.UserManager import com.toshi.manager.model.SofaMessageTask import com.toshi.manager.store.ConversationStore import com.toshi.model.local.Conversation import com.toshi.model.local.Group import com.toshi.model.local.IncomingMessage import com.toshi.model.local.Recipient import com.toshi.model.local.User import com.toshi.model.sofa.Init import com.toshi.model.sofa.SofaAdapters import com.toshi.model.sofa.SofaMessage import com.toshi.util.LocaleUtil import com.toshi.util.logging.LogUtil import com.toshi.util.sharedPrefs.SignalPrefs import com.toshi.view.BaseApplication import org.whispersystems.signalservice.internal.configuration.SignalServiceUrl import rx.Completable import rx.Observable import rx.Scheduler import rx.Single import rx.Subscription import rx.schedulers.Schedulers class SofaMessageManager( private val conversationStore: ConversationStore, private val userManager: UserManager, private val baseApplication: BaseApplication = BaseApplication.get(), private val protocolStore: ProtocolStore = ProtocolStore().init(), private val trustStore: SignalTrustStore = SignalTrustStore(), private val signalServiceUrl: SignalServiceUrl = SignalServiceUrl(baseApplication.getString(R.string.chat_url), trustStore), private val signalServiceUrls: Array<SignalServiceUrl> = Array(1, { signalServiceUrl }), private val signalPrefs: SignalPrefs = SignalPrefs, private val walletObservable: Observable<HDWallet>, private val userAgent: String = "Android " + BuildConfig.APPLICATION_ID + " - " + BuildConfig.VERSION_NAME + ":" + BuildConfig.VERSION_CODE, private val scheduler: Scheduler = Schedulers.io() ) { private var chatService: ChatService? = null private var messageRegister: SofaMessageRegistration? = null private var messageReceiver: SofaMessageReceiver? = null private var messageSender: SofaMessageSender? = null private var groupManager: SofaGroupManager? = null private var connectivitySub: Subscription? = null fun initEverything(wallet: HDWallet): Completable { initChatService(wallet) initSenderAndReceiver(wallet) return initRegistrationTask() .doOnCompleted { attachConnectivityObserver() } } private fun initChatService(wallet: HDWallet) { chatService = ChatService(signalServiceUrls, wallet.ownerAddress, protocolStore, userAgent) } private fun initSenderAndReceiver(wallet: HDWallet) { val messageSender = initMessageSender(wallet, protocolStore, conversationStore, signalServiceUrls) this.messageReceiver = initMessageReceiver(wallet, protocolStore, conversationStore, signalServiceUrls, messageSender) this.groupManager = SofaGroupManager(messageSender, conversationStore, userManager) this.messageSender = messageSender } private fun initMessageSender(wallet: HDWallet, protocolStore: ProtocolStore, conversationStore: ConversationStore, signalServiceUrls: Array<SignalServiceUrl>): SofaMessageSender { return messageSender ?: SofaMessageSender( wallet.ownerAddress, protocolStore, conversationStore, signalServiceUrls ) } private fun initMessageReceiver(wallet: HDWallet, protocolStore: ProtocolStore, conversationStore: ConversationStore, signalServiceUrls: Array<SignalServiceUrl>, messageSender: SofaMessageSender): SofaMessageReceiver { return messageReceiver ?: SofaMessageReceiver( wallet.ownerAddress, walletObservable, protocolStore, conversationStore, signalServiceUrls, messageSender ) } private fun attachConnectivityObserver() { clearConnectivitySubscription() connectivitySub = baseApplication .isConnectedSubject .subscribeOn(scheduler) .filter { isConnected -> isConnected } .subscribe( { handleConnectivity() }, { LogUtil.exception("Error checking connection state", it) } ) } private fun handleConnectivity() { redoRegistrationTask() .subscribeOn(scheduler) .subscribe( { }, { LogUtil.exception("Error during registration task", it) } ) } private fun initRegistrationTask(): Completable { return if (messageRegister != null) return Completable.complete() else initSofaMessageRegistration() } private fun initSofaMessageRegistration(): Completable { val messageRegister = SofaMessageRegistration(chatService, protocolStore) this.messageRegister = messageRegister return messageRegister .registerIfNeeded() .doOnCompleted { messageReceiver?.receiveMessagesAsync() } } private fun redoRegistrationTask(): Completable { val messageRegister = messageRegister ?: SofaMessageRegistration(chatService, protocolStore) this.messageRegister = messageRegister return messageRegister .registerIfNeededWithOnboarding() .doOnCompleted { messageReceiver?.receiveMessagesAsync() } } // Will send the message to a remote peer // and store the message in the local database fun sendAndSaveMessage(receiver: Recipient, message: SofaMessage) { val messageTask = SofaMessageTask(receiver, message, SofaMessageTask.SEND_AND_SAVE) messageSender?.addNewTask(messageTask) } // Will send the message to a remote peer // but not store the message in the local database fun sendMessage(recipient: Recipient, message: SofaMessage) { val messageTask = SofaMessageTask(recipient, message, SofaMessageTask.SEND_ONLY) messageSender?.addNewTask(messageTask) } // Will send an init message to remote peer fun sendInitMessage(sender: User, recipient: Recipient) { val initMessage = Init() .setPaymentAddress(sender.paymentAddress) .setLanguage(LocaleUtil.getLocale().language) val messageBody = SofaAdapters.get().toJson(initMessage) val sofaMessage = SofaMessage().makeNew(sender, messageBody) val messageTask = SofaMessageTask(recipient, sofaMessage, SofaMessageTask.SEND_ONLY) messageSender?.addNewTask(messageTask) } // Will store a transaction in the local database // but not send the message to a remote peer. It will also save the state as "SENDING". fun saveTransaction(user: User, message: SofaMessage) { val recipient = Recipient(user) val messageTask = SofaMessageTask(recipient, message, SofaMessageTask.SAVE_TRANSACTION) messageSender?.addNewTask(messageTask) } // Updates a pre-existing message. fun updateMessage(recipient: Recipient, message: SofaMessage) { val messageTask = SofaMessageTask(recipient, message, SofaMessageTask.UPDATE_MESSAGE) messageSender?.addNewTask(messageTask) } fun resendPendingMessage(sofaMessage: SofaMessage) = messageSender?.sendPendingMessage(sofaMessage) fun createConversationFromGroup(group: Group): Single<Conversation> { return groupManager ?.createConversationFromGroup(group) ?.subscribeOn(scheduler) ?: Single.error(IllegalStateException("SofaGroupManager is null while createConversationFromGroup")) } fun updateConversationFromGroup(group: Group): Completable { return groupManager ?.updateConversationFromGroup(group) ?.subscribeOn(scheduler) ?: Completable.error(IllegalStateException("SofaGroupManager is null while updateConversationFromGroup")) } fun leaveGroup(group: Group): Completable { return groupManager ?.leaveGroup(group) ?.subscribeOn(scheduler) ?: Completable.error(IllegalStateException("SofaGroupManager is null while leaveGroup")) } fun resumeMessageReceiving() { val registeredWithServer = signalPrefs.getRegisteredWithServer() if (registeredWithServer) messageReceiver?.receiveMessagesAsync() } fun tryUnregisterGcm(): Completable { return messageRegister ?.tryUnregisterGcm() ?: Completable.error(IllegalStateException("Unable to register as class hasn't been initialised yet.")) } fun forceRegisterChatGcm(): Completable { return messageRegister ?.registerChatGcm() ?: Completable.error(IllegalStateException("Unable to register as class hasn't been initialised yet.")) } fun fetchLatestMessage(): Single<IncomingMessage> { return messageReceiver ?.fetchLatestMessage() ?: Single.error(IllegalStateException("SofaMessageReceiver is null while fetchLatestMessage")) } fun clear() { clearMessageReceiver() clearMessageSender() clearConnectivitySubscription() } private fun clearMessageReceiver() { messageReceiver?.shutdown() messageReceiver = null } private fun clearMessageSender() { messageSender?.clear() messageSender = null } private fun clearConnectivitySubscription() = connectivitySub?.unsubscribe() fun deleteSession() = protocolStore.deleteAllSessions() fun disconnect() = messageReceiver?.shutdown() }
gpl-3.0
7f89c3038285110551dc9b84aa533a39
40.559846
148
0.690978
5.533676
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/store/WCInboxStore.kt
2
5527
package org.wordpress.android.fluxc.store import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.UNKNOWN import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.GENERIC_ERROR import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult import org.wordpress.android.fluxc.network.rest.wpcom.wc.inbox.InboxNoteDto import org.wordpress.android.fluxc.network.rest.wpcom.wc.inbox.InboxRestClient import org.wordpress.android.fluxc.persistence.dao.InboxNotesDao import org.wordpress.android.fluxc.persistence.entity.InboxNoteWithActions import org.wordpress.android.fluxc.tools.CoroutineEngine import org.wordpress.android.util.AppLog.T.API import javax.inject.Inject import javax.inject.Singleton @Singleton class WCInboxStore @Inject constructor( private val restClient: InboxRestClient, private val coroutineEngine: CoroutineEngine, private val inboxNotesDao: InboxNotesDao ) { companion object { // API has a restriction were no more than 25 notes can be deleted at once so when deleting all notes // for site we have to calculate the number of "pages" to be deleted. This only applies for deletion. const val MAX_PAGE_SIZE_FOR_DELETING_NOTES = 25 const val DEFAULT_PAGE_SIZE = 100 const val DEFAULT_PAGE = 1 val INBOX_NOTE_TYPES_FOR_APPS = arrayOf( "info", "survey", "marketing", "warning" ) } suspend fun fetchInboxNotes( site: SiteModel, page: Int = DEFAULT_PAGE, pageSize: Int = DEFAULT_PAGE_SIZE, inboxNoteTypes: Array<String> = INBOX_NOTE_TYPES_FOR_APPS ): WooResult<Unit> = coroutineEngine.withDefaultContext(API, this, "fetchInboxNotes") { val response = restClient.fetchInboxNotes(site, page, pageSize, inboxNoteTypes) when { response.isError -> WooResult(response.error) response.result != null -> { saveInboxNotes(response.result, site.siteId) WooResult(Unit) } else -> WooResult(WooError(GENERIC_ERROR, UNKNOWN)) } } fun observeInboxNotes(siteId: Long): Flow<List<InboxNoteWithActions>> = inboxNotesDao.observeInboxNotes(siteId) .distinctUntilChanged() suspend fun markInboxNoteAsActioned( site: SiteModel, noteId: Long, actionId: Long ): WooResult<Unit> = coroutineEngine.withDefaultContext(API, this, "fetchInboxNotes") { val response = restClient.markInboxNoteAsActioned(site, noteId, actionId) when { response.isError -> WooResult(response.error) response.result != null -> { markNoteAsActionedLocally(site.siteId, response.result) WooResult(Unit) } else -> WooResult(WooError(GENERIC_ERROR, UNKNOWN)) } } suspend fun deleteNote( site: SiteModel, noteId: Long ): WooResult<Unit> = coroutineEngine.withDefaultContext(API, this, "fetchInboxNotes") { val response = restClient.deleteNote(site, noteId) when { response.isError -> WooResult(response.error) response.result != null -> { inboxNotesDao.deleteInboxNote(noteId, site.siteId) WooResult(Unit) } else -> WooResult(WooError(GENERIC_ERROR, UNKNOWN)) } } suspend fun deleteNotesForSite( site: SiteModel, pageSize: Int = MAX_PAGE_SIZE_FOR_DELETING_NOTES, inboxNoteTypes: Array<String> = INBOX_NOTE_TYPES_FOR_APPS ): WooResult<Unit> = coroutineEngine.withDefaultContext(API, this, "fetchInboxNotes") { var latestResult = WooResult(Unit) for (page in 1..getNumberOfPagesToDelete(site)) { latestResult = restClient .deleteAllNotesForSite(site, page, pageSize, inboxNoteTypes) .asWooResult() if (latestResult.isError) break } if (!latestResult.isError) { inboxNotesDao.deleteInboxNotesForSite(site.siteId) } latestResult } private fun getNumberOfPagesToDelete(site: SiteModel): Int { val sizeOfCachedNotesForSite = inboxNotesDao.getInboxNotesForSite(site.siteId).size var numberOfPagesToDelete = sizeOfCachedNotesForSite / MAX_PAGE_SIZE_FOR_DELETING_NOTES if (sizeOfCachedNotesForSite % MAX_PAGE_SIZE_FOR_DELETING_NOTES > 0) { numberOfPagesToDelete++ } return numberOfPagesToDelete } @Suppress("SpreadOperator") private suspend fun saveInboxNotes(result: Array<InboxNoteDto>, siteId: Long) { val notesWithActions = result.map { it.toInboxNoteWithActionsEntity(siteId) } inboxNotesDao.deleteAllAndInsertInboxNotes(siteId, *notesWithActions.toTypedArray()) } private suspend fun markNoteAsActionedLocally(siteId: Long, updatedNote: InboxNoteDto) { val noteWithActionsEntity = updatedNote.toInboxNoteWithActionsEntity(siteId) inboxNotesDao.updateNote(siteId, noteWithActionsEntity) } }
gpl-2.0
cd7b27831b0ecc8023e04b9948daeebf
40.871212
109
0.65768
4.822862
false
false
false
false
raatiniemi/worker
core-test/src/main/java/me/raatiniemi/worker/domain/repository/TimesheetInMemoryRepository.kt
1
2589
/* * Copyright (C) 2018 Tobias Raatiniemi * * 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, version 2 of the License. * * 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.raatiniemi.worker.domain.repository import me.raatiniemi.worker.domain.comparator.TimesheetDateComparator import me.raatiniemi.worker.domain.comparator.TimesheetItemComparator import me.raatiniemi.worker.domain.model.TimeInterval import me.raatiniemi.worker.domain.model.TimesheetItem import java.util.* class TimesheetInMemoryRepository(private val timeIntervals: List<TimeInterval>) : TimesheetRepository { private fun resetToStartOfDay(timeInMilliseconds: Long): Date { val calendar = Calendar.getInstance() calendar.timeInMillis = timeInMilliseconds calendar.set(Calendar.HOUR_OF_DAY, 0) calendar.set(Calendar.MINUTE, 0) calendar.set(Calendar.SECOND, 0) calendar.set(Calendar.MILLISECOND, 0) return calendar.time } // TODO: Implement proper support for pagination. private fun filterAndBuildResult(predicate: (TimeInterval) -> Boolean) : TreeMap<Date, Set<TimesheetItem>> { val matchingTimeIntervals = timeIntervals.filter { predicate(it) } .groupBy { resetToStartOfDay(it.startInMilliseconds) } val timeIntervals = TreeMap<Date, Set<TimesheetItem>>(TimesheetDateComparator()) matchingTimeIntervals.forEach { timeIntervals[it.key] = it.value .map { timeInterval -> TimesheetItem(timeInterval) } .toSortedSet(TimesheetItemComparator()) } return timeIntervals } override fun getTimesheet( projectId: Long, pageRequest: PageRequest ): Map<Date, Set<TimesheetItem>> { return filterAndBuildResult { it.projectId == projectId } } override fun getTimesheetWithoutRegisteredEntries( projectId: Long, pageRequest: PageRequest ): Map<Date, Set<TimesheetItem>> { return filterAndBuildResult { it.projectId == projectId && !it.isRegistered } } }
gpl-2.0
f3560b1d0578eecffbbc60783e26c8e2
38.227273
104
0.704905
4.794444
false
false
false
false
Kotlin/kotlinx.serialization
core/commonMain/src/kotlinx/serialization/descriptors/SerialDescriptors.kt
1
13873
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.descriptors import kotlinx.serialization.* import kotlinx.serialization.encoding.* import kotlinx.serialization.internal.* import kotlin.reflect.* /** * Builder for [SerialDescriptor]. * The resulting descriptor will be uniquely identified by the given [serialName], [typeParameters] and * elements structure described in [builderAction] function. * * Example: * ``` * // Class with custom serializer and custom serial descriptor * class Data( * val intField: Int, // This field is ignored by custom serializer * val longField: Long, // This field is written as long, but in serialized form is named as "_longField" * val stringList: List<String> // This field is written as regular list of strings * val nullableInt: Int? * ) * // Descriptor for such class: * SerialDescriptor("my.package.Data") { * // intField is deliberately ignored by serializer -- not present in the descriptor as well * element<Long>("_longField") // longField is named as _longField * element("stringField", listSerialDescriptor<String>()) * element("nullableInt", serialDescriptor<Int>().nullable) * } * ``` * * Example for generic classes: * ``` * @Serializable(CustomSerializer::class) * class BoxedList<T>(val list: List<T>) * * class CustomSerializer<T>(tSerializer: KSerializer<T>): KSerializer<BoxedList<T>> { * // here we use tSerializer.descriptor because it represents T * override val descriptor = SerialDescriptor("pkg.BoxedList", CLASS, tSerializer.descriptor) { * // here we have to wrap it with List first, because property has type List<T> * element("list", ListSerializer(tSerializer).descriptor) // or listSerialDescriptor(tSerializer.descriptor) * } * } * ``` */ @Suppress("FunctionName") @OptIn(ExperimentalSerializationApi::class) public fun buildClassSerialDescriptor( serialName: String, vararg typeParameters: SerialDescriptor, builderAction: ClassSerialDescriptorBuilder.() -> Unit = {} ): SerialDescriptor { require(serialName.isNotBlank()) { "Blank serial names are prohibited" } val sdBuilder = ClassSerialDescriptorBuilder(serialName) sdBuilder.builderAction() return SerialDescriptorImpl( serialName, StructureKind.CLASS, sdBuilder.elementNames.size, typeParameters.toList(), sdBuilder ) } /** * Factory to create a trivial primitive descriptors. * Primitive descriptors should be used when the serialized form of the data has a primitive form, for example: * ``` * object LongAsStringSerializer : KSerializer<Long> { * override val descriptor: SerialDescriptor = * PrimitiveDescriptor("kotlinx.serialization.LongAsStringSerializer", PrimitiveKind.STRING) * * override fun serialize(encoder: Encoder, value: Long) { * encoder.encodeString(value.toString()) * } * * override fun deserialize(decoder: Decoder): Long { * return decoder.decodeString().toLong() * } * } * ``` */ public fun PrimitiveSerialDescriptor(serialName: String, kind: PrimitiveKind): SerialDescriptor { require(serialName.isNotBlank()) { "Blank serial names are prohibited" } return PrimitiveDescriptorSafe(serialName, kind) } /** * Factory to create a new descriptor that is identical to [original] except that the name is equal to [serialName]. * Should be used when you want to serialize a type as another non-primitive type. * Don't use this if you want to serialize a type as a primitive value, use [PrimitiveSerialDescriptor] instead. * * Example: * ``` * @Serializable(CustomSerializer::class) * class CustomType(val a: Int, val b: Int, val c: Int) * * class CustomSerializer: KSerializer<CustomType> { * override val descriptor = SerialDescriptor("CustomType", IntArraySerializer().descriptor) * * override fun serialize(encoder: Encoder, value: CustomType) { * encoder.encodeSerializableValue(IntArraySerializer(), intArrayOf(value.a, value.b, value.c)) * } * * override fun deserialize(decoder: Decoder): CustomType { * val array = decoder.decodeSerializableValue(IntArraySerializer()) * return CustomType(array[0], array[1], array[2]) * } * } * ``` */ @ExperimentalSerializationApi public fun SerialDescriptor(serialName: String, original: SerialDescriptor): SerialDescriptor { require(serialName.isNotBlank()) { "Blank serial names are prohibited" } require(original.kind !is PrimitiveKind) { "For primitive descriptors please use 'PrimitiveSerialDescriptor' instead" } require(serialName != original.serialName) { "The name of the wrapped descriptor ($serialName) cannot be the same as the name of the original descriptor (${original.serialName})" } return WrappedSerialDescriptor(serialName, original) } @OptIn(ExperimentalSerializationApi::class) internal class WrappedSerialDescriptor(override val serialName: String, original: SerialDescriptor) : SerialDescriptor by original /** * An unsafe alternative to [buildClassSerialDescriptor] that supports an arbitrary [SerialKind]. * This function is left public only for migration of pre-release users and is not intended to be used * as generally-safe and stable mechanism. Beware that it can produce inconsistent or non spec-compliant instances. * * If you end up using this builder, please file an issue with your use-case in kotlinx.serialization */ @InternalSerializationApi @OptIn(ExperimentalSerializationApi::class) public fun buildSerialDescriptor( serialName: String, kind: SerialKind, vararg typeParameters: SerialDescriptor, builder: ClassSerialDescriptorBuilder.() -> Unit = {} ): SerialDescriptor { require(serialName.isNotBlank()) { "Blank serial names are prohibited" } require(kind != StructureKind.CLASS) { "For StructureKind.CLASS please use 'buildClassSerialDescriptor' instead" } val sdBuilder = ClassSerialDescriptorBuilder(serialName) sdBuilder.builder() return SerialDescriptorImpl(serialName, kind, sdBuilder.elementNames.size, typeParameters.toList(), sdBuilder) } /** * Retrieves descriptor of type [T] using reified [serializer] function. */ public inline fun <reified T> serialDescriptor(): SerialDescriptor = serializer<T>().descriptor /** * Retrieves descriptor of type associated with the given [KType][type] */ public fun serialDescriptor(type: KType): SerialDescriptor = serializer(type).descriptor /** * Creates a descriptor for the type `List<T>` where `T` is the type associated with [elementDescriptor]. */ @ExperimentalSerializationApi public fun listSerialDescriptor(elementDescriptor: SerialDescriptor): SerialDescriptor { return ArrayListClassDesc(elementDescriptor) } /** * Creates a descriptor for the type `List<T>`. */ @ExperimentalSerializationApi public inline fun <reified T> listSerialDescriptor(): SerialDescriptor { return listSerialDescriptor(serializer<T>().descriptor) } /** * Creates a descriptor for the type `Map<K, V>` where `K` and `V` are types * associated with [keyDescriptor] and [valueDescriptor] respectively. */ @ExperimentalSerializationApi public fun mapSerialDescriptor( keyDescriptor: SerialDescriptor, valueDescriptor: SerialDescriptor ): SerialDescriptor { return HashMapClassDesc(keyDescriptor, valueDescriptor) } /** * Creates a descriptor for the type `Map<K, V>`. */ @ExperimentalSerializationApi public inline fun <reified K, reified V> mapSerialDescriptor(): SerialDescriptor { return mapSerialDescriptor(serializer<K>().descriptor, serializer<V>().descriptor) } /** * Creates a descriptor for the type `Set<T>` where `T` is the type associated with [elementDescriptor]. */ @ExperimentalSerializationApi public fun setSerialDescriptor(elementDescriptor: SerialDescriptor): SerialDescriptor { return HashSetClassDesc(elementDescriptor) } /** * Creates a descriptor for the type `Set<T>`. */ @ExperimentalSerializationApi public inline fun <reified T> setSerialDescriptor(): SerialDescriptor { return setSerialDescriptor(serializer<T>().descriptor) } /** * Returns new serial descriptor for the same type with [isNullable][SerialDescriptor.isNullable] * property set to `true`. */ @OptIn(ExperimentalSerializationApi::class) public val SerialDescriptor.nullable: SerialDescriptor get() { if (this.isNullable) return this return SerialDescriptorForNullable(this) } /** * Builder for [SerialDescriptor] for user-defined serializers. * * Both explicit builder functions and implicit (using reified type-parameters) are present and are equivalent. * For example, `element<Int?>("nullableIntField")` is indistinguishable from * `element("nullableIntField", IntSerializer.descriptor.nullable)` and * from `element("nullableIntField", descriptor<Int?>)`. * * Please refer to [SerialDescriptor] builder function for a complete example. */ public class ClassSerialDescriptorBuilder internal constructor( public val serialName: String ) { /** * Indicates that serializer associated with the current serial descriptor * support nullable types, meaning that it should declare nullable type * in its [KSerializer] type parameter and handle nulls during encoding and decoding. */ @ExperimentalSerializationApi @Deprecated("isNullable inside buildSerialDescriptor is deprecated. Please use SerialDescriptor.nullable extension on a builder result.", level = DeprecationLevel.ERROR) public var isNullable: Boolean = false /** * [Serial][SerialInfo] annotations on a target type. */ @ExperimentalSerializationApi public var annotations: List<Annotation> = emptyList() internal val elementNames: MutableList<String> = ArrayList() private val uniqueNames: MutableSet<String> = HashSet() internal val elementDescriptors: MutableList<SerialDescriptor> = ArrayList() internal val elementAnnotations: MutableList<List<Annotation>> = ArrayList() internal val elementOptionality: MutableList<Boolean> = ArrayList() /** * Add an element with a given [name][elementName], [descriptor], * type annotations and optionality the resulting descriptor. * * Example of usage: * ``` * class Data( * val intField: Int? = null, // Optional, has default value * @ProtoNumber(1) val longField: Long * ) * * // Corresponding descriptor * SerialDescriptor("package.Data") { * element<Int?>("intField", isOptional = true) * element<Long>("longField", annotations = listOf(protoIdAnnotationInstance)) * } * ``` */ public fun element( elementName: String, descriptor: SerialDescriptor, annotations: List<Annotation> = emptyList(), isOptional: Boolean = false ) { require(uniqueNames.add(elementName)) { "Element with name '$elementName' is already registered" } elementNames += elementName elementDescriptors += descriptor elementAnnotations += annotations elementOptionality += isOptional } } /** * A reified version of [element] function that * extract descriptor using `serializer<T>().descriptor` call with all the restrictions of `serializer<T>().descriptor`. */ public inline fun <reified T> ClassSerialDescriptorBuilder.element( elementName: String, annotations: List<Annotation> = emptyList(), isOptional: Boolean = false ) { val descriptor = serializer<T>().descriptor element(elementName, descriptor, annotations, isOptional) } @OptIn(ExperimentalSerializationApi::class) internal class SerialDescriptorImpl( override val serialName: String, override val kind: SerialKind, override val elementsCount: Int, typeParameters: List<SerialDescriptor>, builder: ClassSerialDescriptorBuilder ) : SerialDescriptor, CachedNames { override val annotations: List<Annotation> = builder.annotations override val serialNames: Set<String> = builder.elementNames.toHashSet() private val elementNames: Array<String> = builder.elementNames.toTypedArray() private val elementDescriptors: Array<SerialDescriptor> = builder.elementDescriptors.compactArray() private val elementAnnotations: Array<List<Annotation>> = builder.elementAnnotations.toTypedArray() private val elementOptionality: BooleanArray = builder.elementOptionality.toBooleanArray() private val name2Index: Map<String, Int> = elementNames.withIndex().map { it.value to it.index }.toMap() private val typeParametersDescriptors: Array<SerialDescriptor> = typeParameters.compactArray() private val _hashCode: Int by lazy { hashCodeImpl(typeParametersDescriptors) } override fun getElementName(index: Int): String = elementNames.getChecked(index) override fun getElementIndex(name: String): Int = name2Index[name] ?: CompositeDecoder.UNKNOWN_NAME override fun getElementAnnotations(index: Int): List<Annotation> = elementAnnotations.getChecked(index) override fun getElementDescriptor(index: Int): SerialDescriptor = elementDescriptors.getChecked(index) override fun isElementOptional(index: Int): Boolean = elementOptionality.getChecked(index) override fun equals(other: Any?): Boolean = equalsImpl(other) { otherDescriptor: SerialDescriptorImpl -> typeParametersDescriptors.contentEquals( otherDescriptor.typeParametersDescriptors ) } override fun hashCode(): Int = _hashCode override fun toString(): String { return (0 until elementsCount).joinToString(", ", prefix = "$serialName(", postfix = ")") { getElementName(it) + ": " + getElementDescriptor(it).serialName } } }
apache-2.0
2994db9e46cb08e3c67a136c11cd3e89
39.328488
184
0.731204
4.832114
false
false
false
false
sabi0/intellij-community
platform/platform-impl/src/com/intellij/openapi/actionSystem/ex/QuickListsManager.kt
1
4017
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.actionSystem.ex import com.intellij.configurationStore.LazySchemeProcessor import com.intellij.configurationStore.SchemeDataHolder import com.intellij.ide.IdeBundle import com.intellij.ide.actions.QuickSwitchSchemeAction import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.actionSystem.impl.BundledQuickListsProvider import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ApplicationComponent import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.Project import gnu.trove.THashSet import java.util.function.Function class QuickListsManager(private val myActionManager: ActionManager, schemeManagerFactory: SchemeManagerFactory) : ApplicationComponent { private val mySchemeManager: SchemeManager<QuickList> init { mySchemeManager = schemeManagerFactory.create("quicklists", object : LazySchemeProcessor<QuickList, QuickList>(QuickList.DISPLAY_NAME_TAG) { override fun createScheme(dataHolder: SchemeDataHolder<QuickList>, name: String, attributeProvider: Function<String, String?>, isBundled: Boolean): QuickList { val item = QuickList() item.readExternal(dataHolder.read()) dataHolder.updateDigest(item) return item } }, presentableName = IdeBundle.message("quick.lists.presentable.name")) } companion object { @JvmStatic val instance: QuickListsManager get() = ApplicationManager.getApplication().getComponent(QuickListsManager::class.java) } override fun initComponent() { for (provider in BundledQuickListsProvider.EP_NAME.extensionList) { for (path in provider.bundledListsRelativePaths) { mySchemeManager.loadBundledScheme(path, provider) } } mySchemeManager.loadSchemes() registerActions() } val schemeManager: SchemeManager<QuickList> get() = mySchemeManager val allQuickLists: Array<QuickList> get() { return mySchemeManager.allSchemes.toTypedArray() } private fun registerActions() { // to prevent exception if 2 or more targets have the same name val registeredIds = THashSet<String>() for (scheme in mySchemeManager.allSchemes) { val actionId = scheme.actionId if (registeredIds.add(actionId)) { myActionManager.registerAction(actionId, InvokeQuickListAction(scheme)) } } } private fun unregisterActions() { for (oldId in myActionManager.getActionIds(QuickList.QUICK_LIST_PREFIX)) { myActionManager.unregisterAction(oldId) } } // used by external plugin fun setQuickLists(quickLists: List<QuickList>) { unregisterActions() mySchemeManager.setSchemes(quickLists) registerActions() } } private class InvokeQuickListAction(private val myQuickList: QuickList) : QuickSwitchSchemeAction() { init { myActionPlace = ActionPlaces.ACTION_PLACE_QUICK_LIST_POPUP_ACTION templatePresentation.description = myQuickList.description templatePresentation.setText(myQuickList.name, false) } override fun fillActions(project: Project, group: DefaultActionGroup, dataContext: DataContext) { val actionManager = ActionManager.getInstance() for (actionId in myQuickList.actionIds) { if (QuickList.SEPARATOR_ID == actionId) { group.addSeparator() } else { val action = actionManager.getAction(actionId) if (action != null) { group.add(action) } } } } }
apache-2.0
19e22331b1b15e46a4919259ba505a28
35.853211
140
0.728902
5.136829
false
false
false
false
sabi0/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryFilterer.kt
1
11674
/* * 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 com.intellij.vcs.log.history import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Pair import com.intellij.openapi.vcs.AbstractVcs import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.history.VcsCachingHistory import com.intellij.openapi.vcs.history.VcsFileRevision import com.intellij.openapi.vcs.history.VcsFileRevisionEx import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.ContainerUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.data.* import com.intellij.vcs.log.data.index.VcsLogModifiableIndex import com.intellij.vcs.log.graph.GraphCommit import com.intellij.vcs.log.graph.GraphCommitImpl import com.intellij.vcs.log.graph.PermanentGraph import com.intellij.vcs.log.graph.VisibleGraph import com.intellij.vcs.log.graph.api.LiteLinearGraph import com.intellij.vcs.log.graph.impl.facade.PermanentGraphImpl import com.intellij.vcs.log.graph.impl.facade.VisibleGraphImpl import com.intellij.vcs.log.graph.utils.LinearGraphUtils import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcs.log.impl.VcsLogFilterCollectionImpl import com.intellij.vcs.log.impl.VcsLogRevisionFilterImpl import com.intellij.vcs.log.util.StopWatch import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcs.log.visible.CommitCountStage import com.intellij.vcs.log.visible.VcsLogFilterer import com.intellij.vcs.log.visible.VcsLogFiltererImpl import com.intellij.vcs.log.visible.VcsLogFiltererImpl.matchesNothing import com.intellij.vcs.log.visible.VisiblePack import com.intellij.vcsUtil.VcsUtil internal class FileHistoryFilterer(logData: VcsLogData) : VcsLogFilterer { private val project = logData.project private val logProviders = logData.logProviders private val storage = logData.storage private val index = logData.index private val indexDataGetter = index.dataGetter!! private val vcsLogFilterer = VcsLogFiltererImpl(logProviders, storage, logData.topCommitsCache, logData.commitDetailsGetter, index) override fun filter(dataPack: DataPack, sortType: PermanentGraph.SortType, filters: VcsLogFilterCollection, commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> { val filePath = getFilePath(filters) ?: return vcsLogFilterer.filter(dataPack, sortType, filters, commitCount) val root = VcsUtil.getVcsRootFor(project, filePath)!! return MyWorker(root, filePath, getHash(filters)).filter(dataPack, sortType, filters, commitCount) } override fun canFilterEmptyPack(filters: VcsLogFilterCollection): Boolean { return getFilePath(filters)?.run { !isDirectory } ?: false } private inner class MyWorker constructor(private val root: VirtualFile, private val filePath: FilePath, private val hash: Hash?) { fun filter(dataPack: DataPack, sortType: PermanentGraph.SortType, filters: VcsLogFilterCollection, commitCount: CommitCountStage): Pair<VisiblePack, CommitCountStage> { val start = System.currentTimeMillis() if (index.isIndexed(root) && (dataPack.isFull || filePath.isDirectory)) { val visiblePack = filterWithIndex(dataPack, sortType, filters) LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with index") checkNotEmpty(dataPack, visiblePack, true) return Pair.create(visiblePack, commitCount) } if (filePath.isDirectory) { return vcsLogFilterer.filter(dataPack, sortType, filters, commitCount) } ProjectLevelVcsManager.getInstance(project).getVcsFor(root)?.let { vcs -> if (vcs.vcsHistoryProvider != null) { return@filter try { val visiblePack = filterWithProvider(vcs, dataPack, sortType, filters) LOG.debug(StopWatch.formatTime(System.currentTimeMillis() - start) + " for computing history for $filePath with history provider") checkNotEmpty(dataPack, visiblePack, false) Pair.create(visiblePack, commitCount) } catch (e: VcsException) { LOG.error(e) vcsLogFilterer.filter(dataPack, sortType, filters, commitCount) } } } LOG.warn("Could not find vcs or history provider for file $filePath") return vcsLogFilterer.filter(dataPack, sortType, filters, commitCount) } private fun checkNotEmpty(dataPack: DataPack, visiblePack: VisiblePack, withIndex: Boolean) { if (!dataPack.isFull) { LOG.debug("Data pack is not full while computing file history for $filePath\n" + "Found ${visiblePack.visibleGraph.visibleCommitCount} commits") } else if (visiblePack.visibleGraph.visibleCommitCount == 0) { LOG.warn("Empty file history from ${if (withIndex) "index" else "provider"} for $filePath") } } @Throws(VcsException::class) private fun filterWithProvider(vcs: AbstractVcs<*>, dataPack: DataPack, sortType: PermanentGraph.SortType, filters: VcsLogFilterCollection): VisiblePack { val revisionNumber = if (hash != null) VcsLogUtil.convertToRevisionNumber(hash) else null val revisions = VcsCachingHistory.collect(vcs, filePath, revisionNumber) if (revisions.isEmpty()) return VisiblePack.EMPTY if (dataPack.isFull) { val pathsMap = ContainerUtil.newHashMap<Int, FilePath>() for (revision in revisions) { pathsMap[getIndex(revision)] = (revision as VcsFileRevisionEx).path } val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, null, pathsMap.keys) return FileHistoryVisiblePack(dataPack, visibleGraph, false, filters, pathsMap) } val commits = ContainerUtil.newArrayListWithCapacity<GraphCommit<Int>>(revisions.size) val pathsMap = ContainerUtil.newHashMap<Int, FilePath>() for (revision in revisions) { val index = getIndex(revision) pathsMap[index] = (revision as VcsFileRevisionEx).path commits.add(GraphCommitImpl.createCommit(index, emptyList(), revision.getRevisionDate().time)) } val refs = getFilteredRefs(dataPack) val providers = ContainerUtil.newHashMap(Pair.create<VirtualFile, VcsLogProvider>(root, logProviders[root])) val fakeDataPack = DataPack.build(commits, refs, providers, storage, false) val visibleGraph = vcsLogFilterer.createVisibleGraph(fakeDataPack, sortType, null, null/*no need to filter here, since we do not have any extra commits in this pack*/) return FileHistoryVisiblePack(fakeDataPack, visibleGraph, false, filters, pathsMap) } private fun getFilteredRefs(dataPack: DataPack): Map<VirtualFile, CompressedRefs> { val compressedRefs = dataPack.refsModel.allRefsByRoot[root] ?: CompressedRefs(emptySet(), storage) return mapOf(kotlin.Pair(root, compressedRefs)) } private fun getIndex(revision: VcsFileRevision): Int { return storage.getCommitIndex(HashImpl.build(revision.revisionNumber.asString()), root) } private fun filterWithIndex(dataPack: DataPack, sortType: PermanentGraph.SortType, filters: VcsLogFilterCollection): VisiblePack { val matchingHeads = vcsLogFilterer.getMatchingHeads(dataPack.refsModel, setOf(root), filters) val data = indexDataGetter.buildFileNamesData(filePath) val permanentGraph = dataPack.permanentGraph if (permanentGraph !is PermanentGraphImpl) { val visibleGraph = vcsLogFilterer.createVisibleGraph(dataPack, sortType, matchingHeads, data.commits) return FileHistoryVisiblePack(dataPack, visibleGraph, false, filters, data.buildPathsMap()) } if (matchesNothing(matchingHeads) || data.isEmpty) { return VisiblePack.EMPTY } val commit = (hash ?: getHead(dataPack))?.let { storage.getCommitIndex(it, root) } val historyBuilder = FileHistoryBuilder(commit, filePath, data) val visibleGraph = permanentGraph.createVisibleGraph(sortType, matchingHeads, data.commits, historyBuilder) if (!filePath.isDirectory) reindexFirstCommitsIfNeeded(visibleGraph) return FileHistoryVisiblePack(dataPack, visibleGraph, false, filters, historyBuilder.pathsMap) } private fun reindexFirstCommitsIfNeeded(graph: VisibleGraph<Int>) { // we may not have renames big commits, may need to reindex them if (graph is VisibleGraphImpl<*>) { val liteLinearGraph = LinearGraphUtils.asLiteLinearGraph((graph as VisibleGraphImpl<*>).linearGraph) for (row in 0 until liteLinearGraph.nodesCount()) { // checking if commit is a root commit (which means file was added or renamed there) if (liteLinearGraph.getNodes(row, LiteLinearGraph.NodeFilter.DOWN).isEmpty() && index is VcsLogModifiableIndex) { index.reindexWithRenames(graph.getRowInfo(row).commit, root) } } } } private fun getHead(pack: DataPack): Hash? { val refs = pack.refsModel.allRefsByRoot[root] val headOptional = refs!!.streamBranches().filter { br -> br.name == "HEAD" }.findFirst() if (headOptional.isPresent) { val head = headOptional.get() assert(head.root == root) return head.commitHash } return null } } private fun getFilePath(filters: VcsLogFilterCollection): FilePath? { val filter = filters.detailsFilters.singleOrNull() as? VcsLogStructureFilter ?: return null return filter.files.singleOrNull() } private fun getHash(filters: VcsLogFilterCollection): Hash? { val revisionFilter = filters.get(VcsLogFilterCollection.REVISION_FILTER) ?: return null return revisionFilter.heads.singleOrNull()?.hash } companion object { private val LOG = Logger.getInstance(FileHistoryFilterer::class.java) @JvmStatic fun createFilters(path: FilePath, revision: Hash?, root: VirtualFile, showAllBranches: Boolean): VcsLogFilterCollection { val fileFilter = VcsLogStructureFilterImpl(setOf(path)) if (revision != null) { val revisionFilter = VcsLogRevisionFilterImpl.fromCommit(CommitId(revision, root)) return VcsLogFilterCollectionImpl.VcsLogFilterCollectionBuilder(fileFilter, revisionFilter).build() } val branchFilter = if (showAllBranches) null else VcsLogBranchFilterImpl.fromBranch("HEAD") return VcsLogFilterCollectionImpl.VcsLogFilterCollectionBuilder(fileFilter, branchFilter).build() } } }
apache-2.0
b98bf255dc785dac4855b0dee5833861
45.696
143
0.706442
5.07786
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/arch/viewmodel/DismissViewModel.kt
1
1612
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * 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 net.sarangnamu.common.arch.viewmodel import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.ViewModel /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2018. 5. 11.. <p/> */ open class DismissViewModel: ViewModel() { protected lateinit var dismiss: MutableLiveData<Boolean> open fun init() { dismiss = MutableLiveData() } open fun positiveClose() { dismiss.value = true } open fun negativeClose() { dismiss.value = false } } open class DismissAndroidViewModel(app: Application) : AndroidViewModel(app) { protected lateinit var dismiss: MutableLiveData<Boolean> open fun init() { dismiss = MutableLiveData() } open fun positiveClose() { dismiss.value = true } open fun negativeClose() { dismiss.value = false } }
apache-2.0
1aed211f23069a5363dc98351593f74d
25.883333
84
0.69603
4.253298
false
false
false
false
lettuce-io/lettuce-core
src/main/kotlin/io/lettuce/core/api/coroutines/RedisTransactionalCoroutinesCommandsImpl.kt
1
1653
/* * Copyright 2020-2022 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 * * 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 io.lettuce.core.api.coroutines import io.lettuce.core.ExperimentalLettuceCoroutinesApi import io.lettuce.core.TransactionResult import io.lettuce.core.api.reactive.RedisTransactionalReactiveCommands import kotlinx.coroutines.reactive.awaitLast /** * Coroutine executed commands (based on reactive commands) for Transactions. * * @param <K> Key type. * @param <V> Value type. * @author Mikhael Sokolov * @since 6.0 */ @ExperimentalLettuceCoroutinesApi internal class RedisTransactionalCoroutinesCommandsImpl<K : Any, V : Any>(internal val ops: RedisTransactionalReactiveCommands<K, V>) : RedisTransactionalCoroutinesCommands<K, V> { override suspend fun discard(): String = ops.discard().awaitLast() override suspend fun exec(): TransactionResult = ops.exec().awaitLast() override suspend fun multi(): String = ops.multi().awaitLast() override suspend fun watch(vararg keys: K): String = ops.watch(*keys).awaitLast() override suspend fun unwatch(): String = ops.unwatch().awaitLast() }
apache-2.0
8d84ac8f413f582076b6a912e45486c4
34.170213
180
0.753176
4.396277
false
false
false
false
clappr/clappr-android
clappr/src/main/kotlin/io/clappr/player/components/Core.kt
1
5436
package io.clappr.player.components import android.os.Bundle import android.view.View import android.widget.FrameLayout import io.clappr.player.base.InternalEvent import io.clappr.player.base.Options import io.clappr.player.base.UIObject import io.clappr.player.log.Logger import io.clappr.player.plugin.Loader import io.clappr.player.plugin.Plugin import io.clappr.player.plugin.core.UICorePlugin import io.clappr.player.shared.SharedData import io.clappr.player.utils.Environment class Core(options: Options) : UIObject() { enum class FullscreenState { EMBEDDED, FULLSCREEN } var fullscreenState: FullscreenState = FullscreenState.EMBEDDED set(value) { if (value != fullscreenState) { val beforeEvent: InternalEvent val afterEvent: InternalEvent if (value == FullscreenState.FULLSCREEN) { beforeEvent = InternalEvent.WILL_ENTER_FULLSCREEN afterEvent = InternalEvent.DID_ENTER_FULLSCREEN } else { beforeEvent = InternalEvent.WILL_EXIT_FULLSCREEN afterEvent = InternalEvent.DID_EXIT_FULLSCREEN } trigger(beforeEvent.value) field = value trigger(afterEvent.value) } } val plugins: List<Plugin> get() = internalPlugins private val internalPlugins: MutableList<Plugin> val containers: MutableList<Container> = mutableListOf() var activeContainer: Container? = null set(value) { if (activeContainer != value) { activeContainer?.stopListening() trigger(InternalEvent.WILL_CHANGE_ACTIVE_CONTAINER.value) field = value activeContainer?.on(InternalEvent.WILL_CHANGE_PLAYBACK.value ) { bundle: Bundle? -> trigger( InternalEvent.WILL_CHANGE_ACTIVE_PLAYBACK.value, bundle) } activeContainer?.on(InternalEvent.DID_CHANGE_PLAYBACK.value ) { bundle: Bundle? -> trigger( InternalEvent.DID_CHANGE_ACTIVE_PLAYBACK.value, bundle) } trigger(InternalEvent.DID_CHANGE_ACTIVE_CONTAINER.value) } } val activePlayback: Playback? get() = activeContainer?.playback private val frameLayout: FrameLayout get() = view as FrameLayout var options: Options = options set(options) { field = options trigger(InternalEvent.DID_UPDATE_OPTIONS.value) updateContainerOptions(options) } val environment = Environment() val sharedData = SharedData() private fun updateContainerOptions(options: Options) { containers.forEach { it.options = options } } override val viewClass: Class<*> get() = FrameLayout::class.java private val layoutChangeListener = View.OnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> val horizontalChange = (right - left) != (oldRight - oldLeft) val verticalChange = (bottom - top) != (oldBottom - oldTop) if (horizontalChange || verticalChange) { trigger(InternalEvent.DID_RESIZE.value) } } private val orientationChangeListener = OrientationChangeListener(this) init { internalPlugins = Loader.loadPlugins(this).toMutableList() val container = Container(options) containers.add(container) } fun load() { activeContainer = containers.first() trigger(InternalEvent.WILL_LOAD_SOURCE.value) options.source?.let { activeContainer?.load(it, options.mimeType) } trigger(InternalEvent.DID_LOAD_SOURCE.value) } fun destroy() { trigger(InternalEvent.WILL_DESTROY.value) containers.forEach { it.destroy() } containers.clear() internalPlugins.forEach { handlePluginAction( { it.destroy() }, "Plugin ${it.javaClass.simpleName} crashed during destroy") } internalPlugins.clear() stopListening() frameLayout.removeOnLayoutChangeListener(layoutChangeListener) orientationChangeListener.disable() trigger(InternalEvent.DID_DESTROY.value) } override fun render(): Core { frameLayout.removeAllViews() containers.forEach { frameLayout.addView(it.view) it.render() } internalPlugins.filterIsInstance(UICorePlugin::class.java).forEach { frameLayout.addView(it.view) handlePluginAction( { it.render() }, "Plugin ${it.javaClass.simpleName} crashed during render") } frameLayout.removeOnLayoutChangeListener(layoutChangeListener) frameLayout.addOnLayoutChangeListener(layoutChangeListener) orientationChangeListener.enable() return this } private fun handlePluginAction(action: () -> Unit, errorMessage: String) { try { action.invoke() } catch (error: Exception) { Logger.error(Core::class.java.simpleName, errorMessage, error) } } }
bsd-3-clause
03099988b355d9a8b7763f3abbdbd541
32.975
108
0.609088
5.201914
false
false
false
false
ahmedeltaher/MVP-Sample
app/src/main/java/com/task/ui/component/news/HomeActivity.kt
1
3020
package com.task.ui.component.news import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import androidx.annotation.VisibleForTesting import androidx.recyclerview.widget.LinearLayoutManager import androidx.test.espresso.IdlingResource import butterknife.OnClick import com.task.App import com.task.R import com.task.data.remote.dto.NewsItem import com.task.ui.base.BaseActivity import com.task.ui.component.details.DetailsActivity import com.task.utils.Constants import com.task.utils.EspressoIdlingResource import kotlinx.android.synthetic.main.home_activity.* import org.jetbrains.anko.design.snackbar import org.jetbrains.anko.intentFor import javax.inject.Inject /** * Created by AhmedEltaher on 5/12/2016 */ class HomeActivity : BaseActivity(), HomeContract.View { @Inject lateinit var homePresenter: HomePresenter override val layoutId: Int get() = R.layout.home_activity val countingIdlingResource: IdlingResource @VisibleForTesting get() = EspressoIdlingResource.idlingResource override fun initializeDagger() { val app = applicationContext as App app.mainComponent?.inject(this@HomeActivity) } override fun initializePresenter() { homePresenter.setView(this) super.presenter = homePresenter } override fun initializeNewsList(news: List<NewsItem>) { val newsAdapter = NewsAdapter(homePresenter.getRecyclerItemListener(), news) val layoutManager = LinearLayoutManager(this) rv_news_list.layoutManager = layoutManager rv_news_list.setHasFixedSize(true) rv_news_list.adapter = newsAdapter } override fun setLoaderVisibility(isVisible: Boolean) { pb_loading.visibility = if (isVisible) VISIBLE else GONE } override fun navigateToDetailsScreen(news: NewsItem) { startActivity(intentFor<DetailsActivity>(Constants.NEWS_ITEM_KEY to news)) } override fun setNoDataVisibility(isVisible: Boolean) { tv_no_data.visibility = if (isVisible) VISIBLE else GONE } override fun setListVisibility(isVisible: Boolean) { rl_news_list.visibility = if (isVisible) VISIBLE else GONE } override fun showSearchError() { rl_news_list.snackbar(R.string.search_error) } override fun showNoNewsError() { rl_news_list.snackbar(R.string.news_error) } override fun incrementCountingIdlingResource() { EspressoIdlingResource.increment() } override fun decrementCountingIdlingResource() { EspressoIdlingResource.decrement() } @OnClick(R.id.ic_toolbar_setting, R.id.ic_toolbar_refresh, R.id.btn_search) fun onClick(view: View) { when (view.id) { R.id.ic_toolbar_refresh -> homePresenter.getNews() R.id.btn_search -> homePresenter.onSearchClick(et_search.text.toString()) } } override fun onDestroy() { super.onDestroy() homePresenter.unSubscribe() } }
apache-2.0
dae1b76299b6ba451c579f770b026a6a
29.2
85
0.716556
4.434655
false
false
false
false
didi/DoraemonKit
Android/dokit-test/src/main/java/com/didichuxing/doraemonkit/kit/test/widget/FlashImageView.kt
1
1793
package com.didichuxing.doraemonkit.kit.test.widget import android.content.Context import android.util.AttributeSet import android.view.View import kotlinx.coroutines.* import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn /** * didi Create on 2022/4/14 . * * Copyright (c) 2022/4/14 by didiglobal.com. * * @author <a href="[email protected]">zhangjun</a> * @version 1.0 * @Date 2022/4/14 4:24 下午 * @Description 用一句话说明文件功能 */ class FlashImageView : androidx.appcompat.widget.AppCompatImageView { private val flashViewScope = MainScope() + CoroutineName(this.toString()) private var flashFlow = flow { while (true) { emit(0) delay(500) emit(1) delay(500) } } private var flashEnable: Boolean = false constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) fun isFlashEnable(): Boolean { return flashEnable } fun cancelFlash() { flashViewScope.cancel() flashEnable = false } fun startFlash() { if (!flashEnable) { flashEnable = true flashViewScope.launch { flashFlow.flowOn(Dispatchers.IO) .collect { when (it) { 0 -> visibility = View.VISIBLE 1 -> visibility = View.INVISIBLE else -> { } } } } } } }
apache-2.0
8d30145a7443c052e46a065b9829e551
24.637681
113
0.570944
4.547558
false
false
false
false
free5ty1e/primestationone-control-android
app/src/main/java/com/chrisprime/primestationonecontrol/PrimeStationOneControlApplication.kt
1
2610
package com.chrisprime.primestationonecontrol import android.app.Application import android.content.Context import android.util.Log import com.chrisprime.primestationonecontrol.dagger.Injector import com.chrisprime.primestationonecontrol.model.PrimeStationOne import com.chrisprime.primestationonecontrol.utilities.FileUtilities import com.squareup.leakcanary.LeakCanary import com.squareup.otto.Bus import timber.log.Timber class PrimeStationOneControlApplication : Application() { var currentPrimeStationOne: PrimeStationOne? = null companion object { val ID_EVENT_BUS_MAIN = "main" lateinit var instance: PrimeStationOneControlApplication lateinit var eventBus: Bus val appResourcesContext: Context get() = instance.applicationContext } init { instance = this eventBus = Bus(ID_EVENT_BUS_MAIN) } override fun onCreate() { super.onCreate() if (LeakCanary.isInAnalyzerProcess(this)) { // This process is dedicated to LeakCanary for heap analysis. // You should not init your app in this process. return } LeakCanary.install(this) Injector.initializeApplicationComponent(this) // if (BuildConfig.DEBUG) { Timber.plant(Timber.DebugTree()) /* } else { Timber.plant(CrashReportingTree()) } */ val buildType = if (BuildConfig.DEBUG) "debug" else "production" Timber.d("Launching " + buildType + " build version " + BuildConfig.VERSION_NAME + ", which is version code " + BuildConfig.VERSION_CODE) updateCurrentPrimeStationFromJson() } fun updateCurrentPrimeStationFromJson() { currentPrimeStationOne = FileUtilities.readJsonCurrentPrimestation(this) } /** * A tree which logs important information for crash reporting. */ private class CrashReportingTree : Timber.Tree() { override fun log(priority: Int, tag: String, message: String, t: Throwable) { if (priority == Log.VERBOSE || priority == Log.DEBUG) { return } // FakeCrashLibrary.log(priority, tag, message); // // if (t != null) { // if (priority == Log.ERROR) { // FakeCrashLibrary.logError(t); // } else if (priority == Log.WARN) { // FakeCrashLibrary.logWarning(t); // } // } } } }
mit
d4344e29fc9c52d7b6d6119bf1f138b9
29.705882
145
0.60728
4.99044
false
false
false
false
adrianfaciu/flowdock-teamcity-plugin
flowdock-teamcity-plugin-server/src/main/kotlin/com/adrianfaciu/teamcity/flowdockPlugin/notifications/NotificationThread.kt
1
547
package com.adrianfaciu.teamcity.flowdockPlugin.notifications /** * Threads represent entities in external services */ class NotificationThread { var body: String? = null var title: String? = null var status: NotificationStatus? = null var external_url: String? = null var fields: Array<NotificationFields>? = null var source: NotificationSource? = null override fun toString(): String { return "[body = $body, title = $title, status = $status, external_url = $external_url, fields = $fields]" } }
mit
a2288eb1b706ec8bf838a3ec70d77fc4
23.863636
113
0.681901
4.307087
false
false
false
false
wiltonlazary/kotlin-native
tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/konan/KonanPlugin.kt
1
18978
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.gradle.plugin.konan import org.gradle.api.* import org.gradle.api.component.ComponentWithVariants import org.gradle.api.component.SoftwareComponent import org.gradle.api.file.FileCollection import org.gradle.api.internal.FeaturePreviews import org.gradle.api.internal.component.SoftwareComponentInternal import org.gradle.api.internal.component.UsageContext import org.gradle.api.internal.project.ProjectInternal import org.gradle.api.plugins.BasePlugin import org.gradle.api.publish.PublishingExtension import org.gradle.api.publish.maven.MavenPublication import org.gradle.api.publish.maven.internal.publication.MavenPublicationInternal import org.gradle.language.cpp.internal.NativeVariantIdentity import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry import org.gradle.util.GradleVersion import org.jetbrains.kotlin.gradle.plugin.konan.KonanPlugin.Companion.COMPILE_ALL_TASK_NAME import org.jetbrains.kotlin.gradle.plugin.model.KonanToolingModelBuilder import org.jetbrains.kotlin.gradle.plugin.tasks.* import org.jetbrains.kotlin.konan.CURRENT import org.jetbrains.kotlin.konan.CompilerVersion import org.jetbrains.kotlin.konan.parseCompilerVersion import org.jetbrains.kotlin.konan.target.HostManager import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.konan.target.buildDistribution import org.jetbrains.kotlin.konan.target.customerDistribution import org.jetbrains.kotlin.konan.util.DependencyProcessor import java.io.File import javax.inject.Inject /** * We use the following properties: * org.jetbrains.kotlin.native.home - directory where compiler is located (aka dist in konan project output). * org.jetbrains.kotlin.native.version - a konan compiler version for downloading. * konan.build.targets - list of targets to build (by default all the declared targets are built). * konan.jvmArgs - additional args to be passed to a JVM executing the compiler/cinterop tool. */ internal fun Project.warnAboutDeprecatedProperty(property: KonanPlugin.ProjectProperty) = property.deprecatedPropertyName?.let { deprecated -> if (project.hasProperty(deprecated)) { logger.warn("Project property '$deprecated' is deprecated. Use '${property.propertyName}' instead.") } } internal fun Project.hasProperty(property: KonanPlugin.ProjectProperty) = with(property) { when { hasProperty(propertyName) -> true deprecatedPropertyName != null && hasProperty(deprecatedPropertyName) -> true else -> false } } internal fun Project.findProperty(property: KonanPlugin.ProjectProperty): Any? = with(property) { return findProperty(propertyName) ?: deprecatedPropertyName?.let { findProperty(it) } } internal fun Project.getProperty(property: KonanPlugin.ProjectProperty) = findProperty(property) ?: throw IllegalArgumentException("No such property in the project: ${property.propertyName}") internal fun Project.getProperty(property: KonanPlugin.ProjectProperty, defaultValue: Any) = findProperty(property) ?: defaultValue internal fun Project.setProperty(property: KonanPlugin.ProjectProperty, value: Any) { extensions.extraProperties.set(property.propertyName, value) } // konanHome extension is set by downloadKonanCompiler task. internal val Project.konanHome: String get() { assert(hasProperty(KonanPlugin.ProjectProperty.KONAN_HOME)) return project.file(getProperty(KonanPlugin.ProjectProperty.KONAN_HOME)).canonicalPath } internal val Project.konanVersion: CompilerVersion get() = project.findProperty(KonanPlugin.ProjectProperty.KONAN_VERSION) ?.toString()?.let { CompilerVersion.fromString(it) } ?: CompilerVersion.CURRENT internal val Project.konanBuildRoot get() = buildDir.resolve("konan") internal val Project.konanBinBaseDir get() = konanBuildRoot.resolve("bin") internal val Project.konanLibsBaseDir get() = konanBuildRoot.resolve("libs") internal val Project.konanBitcodeBaseDir get() = konanBuildRoot.resolve("bitcode") internal fun File.targetSubdir(target: KonanTarget) = resolve(target.visibleName) internal val Project.konanDefaultSrcFiles get() = fileTree("${projectDir.canonicalPath}/src/main/kotlin") internal fun Project.konanDefaultDefFile(libName: String) = file("${projectDir.canonicalPath}/src/main/c_interop/$libName.def") @Suppress("UNCHECKED_CAST") internal val Project.konanArtifactsContainer: KonanArtifactContainer get() = extensions.getByName(KonanPlugin.ARTIFACTS_CONTAINER_NAME) as KonanArtifactContainer // TODO: The Kotlin/Native compiler is downloaded manually by a special task so the compilation tasks // are configured without the compile distribution. After target management refactoring // we need .properties files from the distribution to configure targets. This is worked around here // by using HostManager instead of PlatformManager. But we need to download the compiler at the configuration // stage (e.g. by getting it from maven as a plugin dependency) and bring back the PlatformManager here. internal val Project.hostManager: HostManager get() = findProperty("hostManager") as HostManager? ?: if (hasProperty("org.jetbrains.kotlin.native.experimentalTargets")) HostManager(buildDistribution(rootProject.rootDir.absolutePath), true) else HostManager(customerDistribution(konanHome)) internal val Project.konanTargets: List<KonanTarget> get() = hostManager.toKonanTargets(konanExtension.targets) .filter{ hostManager.isEnabled(it) } .distinct() @Suppress("UNCHECKED_CAST") internal val Project.konanExtension: KonanExtension get() = extensions.getByName(KonanPlugin.KONAN_EXTENSION_NAME) as KonanExtension internal val Project.konanCompilerDownloadTask get() = tasks.getByName(KonanPlugin.KONAN_DOWNLOAD_TASK_NAME) internal val Project.requestedTargets get() = findProperty(KonanPlugin.ProjectProperty.KONAN_BUILD_TARGETS)?.let { it.toString().trim().split("\\s+".toRegex()) }.orEmpty() internal val Project.jvmArgs get() = (findProperty(KonanPlugin.ProjectProperty.KONAN_JVM_ARGS) as String?)?.split("\\s+".toRegex()).orEmpty() internal val Project.compileAllTask get() = getOrCreateTask(COMPILE_ALL_TASK_NAME) internal fun Project.targetIsRequested(target: KonanTarget): Boolean { val targets = requestedTargets return (targets.isEmpty() || targets.contains(target.visibleName) || targets.contains("all")) } /** Looks for task with given name in the given project. Throws [UnknownTaskException] if there's not such task. */ private fun Project.getTask(name: String): Task = tasks.getByPath(name) /** * Looks for task with given name in the given project. * If such task isn't found, will create it. Returns created/found task. */ private fun Project.getOrCreateTask(name: String): Task = with(tasks) { findByPath(name) ?: create(name, DefaultTask::class.java) } internal fun Project.konanCompilerName(): String = "kotlin-native-${project.simpleOsName}-${project.konanVersion}" internal fun Project.konanCompilerDownloadDir(): String = DependencyProcessor.localKonanDir.resolve(project.konanCompilerName()).absolutePath // region Useful extensions and functions --------------------------------------- internal fun MutableList<String>.addArg(parameter: String, value: String) { add(parameter) add(value) } internal fun MutableList<String>.addArgs(parameter: String, values: Iterable<String>) { values.forEach { addArg(parameter, it) } } internal fun MutableList<String>.addArgIfNotNull(parameter: String, value: String?) { if (value != null) { addArg(parameter, value) } } internal fun MutableList<String>.addKey(key: String, enabled: Boolean) { if (enabled) { add(key) } } internal fun MutableList<String>.addFileArgs(parameter: String, values: FileCollection) { values.files.forEach { addArg(parameter, it.canonicalPath) } } internal fun MutableList<String>.addFileArgs(parameter: String, values: Collection<FileCollection>) { values.forEach { addFileArgs(parameter, it) } } // endregion internal fun dumpProperties(task: Task) { fun Iterable<String>.dump() = joinToString(prefix = "[", separator = ",\n${" ".repeat(22)}", postfix = "]") fun Collection<FileCollection>.dump() = flatMap { it.files }.map { it.canonicalPath }.dump() when (task) { is KonanCompileTask -> with(task) { println() println("Compilation task: $name") println("destinationDir : $destinationDir") println("artifact : ${artifact.canonicalPath}") println("srcFiles : ${srcFiles.dump()}") println("produce : $produce") println("libraries : ${libraries.files.dump()}") println(" : ${libraries.artifacts.map { it.artifact.canonicalPath }.dump()}") println(" : ${libraries.namedKlibs.dump()}") println("nativeLibraries : ${nativeLibraries.dump()}") println("linkerOpts : $linkerOpts") println("enableDebug : $enableDebug") println("noStdLib : $noStdLib") println("noMain : $noMain") println("enableOptimization : $enableOptimizations") println("enableAssertions : $enableAssertions") println("noDefaultLibs : $noDefaultLibs") println("noEndorsedLibs : $noEndorsedLibs") println("target : $target") println("languageVersion : $languageVersion") println("apiVersion : $apiVersion") println("konanVersion : ${CompilerVersion.CURRENT}") println("konanHome : $konanHome") println() } is KonanInteropTask -> with(task) { println() println("Stub generation task: $name") println("destinationDir : $destinationDir") println("artifact : $artifact") println("libraries : ${libraries.files.dump()}") println(" : ${libraries.artifacts.map { it.artifact.canonicalPath }.dump()}") println(" : ${libraries.namedKlibs.dump()}") println("defFile : $defFile") println("target : $target") println("packageName : $packageName") println("compilerOpts : $compilerOpts") println("linkerOpts : $linkerOpts") println("headers : ${headers.dump()}") println("linkFiles : ${linkFiles.dump()}") println("konanVersion : ${CompilerVersion.CURRENT}") println("konanHome : $konanHome") println() } else -> { println("Unsupported task.") } } } open class KonanExtension { var targets = mutableListOf("host") var languageVersion: String? = null var apiVersion: String? = null var jvmArgs = mutableListOf<String>() } open class KonanSoftwareComponent(val project: ProjectInternal?): SoftwareComponentInternal, ComponentWithVariants { private val usages = mutableSetOf<UsageContext>() override fun getUsages(): MutableSet<out UsageContext> = usages private val variants = mutableSetOf<SoftwareComponent>() override fun getName() = "main" override fun getVariants(): Set<SoftwareComponent> = variants fun addVariant(component: SoftwareComponent) = variants.add(component) } class KonanPlugin @Inject constructor(private val registry: ToolingModelBuilderRegistry) : Plugin<ProjectInternal> { enum class ProjectProperty(val propertyName: String, val deprecatedPropertyName: String? = null) { KONAN_HOME ("org.jetbrains.kotlin.native.home", "konan.home"), KONAN_VERSION ("org.jetbrains.kotlin.native.version"), KONAN_BUILD_TARGETS ("konan.build.targets"), KONAN_JVM_ARGS ("konan.jvmArgs"), KONAN_USE_ENVIRONMENT_VARIABLES("konan.useEnvironmentVariables"), DOWNLOAD_COMPILER ("download.compiler"), // Properties used instead of env vars until https://github.com/gradle/gradle/issues/3468 is fixed. // TODO: Remove them when an API for env vars is provided. KONAN_CONFIGURATION_BUILD_DIR ("konan.configuration.build.dir"), KONAN_DEBUGGING_SYMBOLS ("konan.debugging.symbols"), KONAN_OPTIMIZATIONS_ENABLE ("konan.optimizations.enable"), } companion object { internal const val ARTIFACTS_CONTAINER_NAME = "konanArtifacts" internal const val KONAN_DOWNLOAD_TASK_NAME = "checkKonanCompiler" internal const val KONAN_GENERATE_CMAKE_TASK_NAME = "generateCMake" internal const val COMPILE_ALL_TASK_NAME = "compileKonan" internal const val KONAN_EXTENSION_NAME = "konan" internal val REQUIRED_GRADLE_VERSION = GradleVersion.version("4.7") } private fun Project.cleanKonan() = project.tasks.withType(KonanBuildingTask::class.java).forEach { project.delete(it.artifact) } private fun checkGradleVersion() = GradleVersion.current().let { current -> check(current >= REQUIRED_GRADLE_VERSION) { "Kotlin/Native Gradle plugin is incompatible with this version of Gradle.\n" + "The minimal required version is $REQUIRED_GRADLE_VERSION\n" + "Current version is ${current}" } } override fun apply(project: ProjectInternal?) { if (project == null) { return } checkGradleVersion() registry.register(KonanToolingModelBuilder) project.plugins.apply("base") // Create necessary tasks and extensions. project.tasks.create(KONAN_DOWNLOAD_TASK_NAME, KonanCompilerDownloadTask::class.java) project.tasks.create(KONAN_GENERATE_CMAKE_TASK_NAME, KonanGenerateCMakeTask::class.java) project.extensions.create(KONAN_EXTENSION_NAME, KonanExtension::class.java) val container = project.extensions.create( KonanArtifactContainer::class.java, ARTIFACTS_CONTAINER_NAME, KonanArtifactContainer::class.java, project ) project.warnAboutDeprecatedProperty(ProjectProperty.KONAN_HOME) // Set additional project properties like org.jetbrains.kotlin.native.home, konan.build.targets etc. if (!project.hasProperty(ProjectProperty.KONAN_HOME)) { project.setProperty(ProjectProperty.KONAN_HOME, project.konanCompilerDownloadDir()) project.setProperty(ProjectProperty.DOWNLOAD_COMPILER, true) } // Create and set up aggregate building tasks. val compileKonanTask = project.getOrCreateTask(COMPILE_ALL_TASK_NAME).apply { group = BasePlugin.BUILD_GROUP description = "Compiles all the Kotlin/Native artifacts" } project.getTask("build").apply { dependsOn(compileKonanTask) } project.getTask("clean").apply { doLast { project.cleanKonan() } } val runTask = project.getOrCreateTask("run") project.afterEvaluate { project.konanArtifactsContainer .filterIsInstance(KonanProgram::class.java) .forEach { program -> program.forEach { compile -> compile.runTask?.let { runTask.dependsOn(it) } } } } // Enable multiplatform support project.pluginManager.apply(KotlinNativePlatformPlugin::class.java) project.afterEvaluate { project.pluginManager.withPlugin("maven-publish") { container.all { buildingConfig -> val konanSoftwareComponent = buildingConfig.mainVariant project.extensions.configure(PublishingExtension::class.java) { val builtArtifact = buildingConfig.name val mavenPublication = it.publications.maybeCreate(builtArtifact, MavenPublication::class.java) mavenPublication.apply { artifactId = builtArtifact groupId = project.group.toString() from(konanSoftwareComponent) } (mavenPublication as MavenPublicationInternal).publishWithOriginalFileName() buildingConfig.pomActions.forEach { mavenPublication.pom(it) } } project.extensions.configure(PublishingExtension::class.java) { val publishing = it for (v in konanSoftwareComponent.variants) { publishing.publications.create(v.name, MavenPublication::class.java) { mavenPublication -> val coordinates = (v as NativeVariantIdentity).coordinates project.logger.info("variant with coordinates($coordinates) and module: ${coordinates.module}") mavenPublication.artifactId = coordinates.module.name mavenPublication.groupId = coordinates.group mavenPublication.version = coordinates.version mavenPublication.from(v) (mavenPublication as MavenPublicationInternal).publishWithOriginalFileName() buildingConfig.pomActions.forEach { mavenPublication.pom(it) } } } } } } } } }
apache-2.0
02a8a52a786df5750965dde6825c6060
44.401914
127
0.656813
5.043317
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/designer/editor/tset/TsetEditorComponent.kt
1
6169
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham 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.thomas.needham.neurophidea.designer.editor.tset import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.EditorMarkupModel import com.intellij.openapi.editor.highlighter.EditorHighlighter import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.impl.EditorHistoryManager import com.intellij.openapi.fileEditor.impl.text.FileDropHandler import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.ex.StatusBarEx import com.intellij.ui.components.JBLoadingPanel import com.intellij.util.messages.MessageBusConnection import org.jetbrains.annotations.NotNull import java.awt.BorderLayout /** * Created by thoma on 09/10/2016. */ class TsetEditorComponent : JBLoadingPanel, DataProvider { val project: Project? @NotNull val file: VirtualFile? val tsetEditor: TsetEditorImpl? val editor: Editor? val document: Document? val documentListener: TsetDocumentListener? var isComponentModified: Boolean var isComponentValid: Boolean val fileListener: TsetVirtualFileListener? val busConnection: MessageBusConnection? companion object Log { @JvmStatic val LOG: Logger = Logger.getInstance("#com.thomas.needham.neurophidea.designer.editor.tset.TsetEditorComponent") @JvmStatic val assertThread: () -> Unit = { ApplicationManager.getApplication().assertIsDispatchThread() } } constructor(@NotNull project: Project?, @NotNull file: VirtualFile?, @NotNull editor: TsetEditorImpl?) : super(BorderLayout(), editor as Disposable) { this.project = project this.file = file this.tsetEditor = editor this.document = TsetDocumentManager.getInstance().getDocument(file!!) LOG.assertTrue(this.document != null) documentListener = TsetDocumentListener(this) document?.addDocumentListener(documentListener) this.editor = createEditor() this.add(this, BorderLayout.CENTER) isComponentModified = isModifiedImpl() isComponentValid = isEditorValidImpl() LOG.assertTrue(isComponentValid) fileListener = TsetVirtualFileListener(this) this.file?.fileSystem?.addVirtualFileListener(fileListener) busConnection = project?.messageBus?.connect() busConnection?.subscribe(FileTypeManager.TOPIC, TsetFileTypeListener(this)) busConnection?.subscribe(DumbService.DUMB_MODE, TsetDumbModeListener(this)) } @NotNull private fun createEditor(): Editor? { val e: Editor? = EditorFactory.getInstance().createEditor(document!!, project) (e?.markupModel as EditorMarkupModel).isErrorStripeVisible = true (e as EditorEx).gutterComponentEx.setForceShowRightFreePaintersArea(true) e.setFile(file) e.contextMenuGroupId = IdeActions.GROUP_EDITOR_POPUP (e as EditorImpl).setDropHandler(FileDropHandler(e)) TsetFileEditorProvider.putTsetEditor(e, tsetEditor) return e } private fun isEditorValidImpl(): Boolean { return TsetDocumentManager.getInstance().getDocument(file!!) != null } override fun getData(p0: String): Any? { throw UnsupportedOperationException() } fun updateModifiedProperty() { val oldModified = isComponentModified isComponentModified = isModifiedImpl() tsetEditor?.firePropertyChange(FileEditor.PROP_MODIFIED, oldModified, isComponentModified) } private fun isModifiedImpl(): Boolean { return TsetDocumentManager.getInstance().isFileModified(file!!); } fun updateValidProperty() { val oldValid = isComponentValid isComponentValid = isEditorValidImpl() tsetEditor?.firePropertyChange(FileEditor.PROP_VALID, oldValid, isComponentValid) } fun updateHighlighters() { if (!project?.isDisposed!! && !editor?.isDisposed!!) { val highlighter: EditorHighlighter = EditorHighlighterFactory.getInstance().createEditorHighlighter(project, file!!) (editor as EditorEx).highlighter = highlighter } } fun dispose() { document?.removeDocumentListener(documentListener!!) if (!project?.isDefault!!) { EditorHistoryManager.getInstance(project!!).updateHistoryEntry(file, false) } disposeEditor() busConnection?.disconnect() file?.fileSystem?.removeVirtualFileListener(fileListener!!) } private fun disposeEditor() { EditorFactory.getInstance().releaseEditor(editor!!) } fun selectNotify() { updateStatusBar() } private fun updateStatusBar() { val statusBar: StatusBarEx? = WindowManager.getInstance().getStatusBar(project) as StatusBarEx statusBar?.updateWidgets() } }
mit
fbda03086b5fb3b680068fc87c753f71
36.621951
119
0.798671
4.289986
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/project/NeurophSDKComboBoxActionListener.kt
1
1913
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham 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.thomas.needham.neurophidea.project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.ui.ProjectJdksEditor import java.awt.event.ActionEvent import java.awt.event.ActionListener /** * Created by Thomas Needham on 06/06/2016. */ class NeurophSDKComboBoxActionListener : ActionListener { var instance: NeurophSDKComboBox? = null companion object Data { val project = ProjectManager.getInstance().defaultProject } override fun actionPerformed(e: ActionEvent?) { var sdk: Sdk? = instance?.getSelectedSdk() var editor = ProjectJdksEditor(sdk, NeurophSDKComboBoxActionListener.project, instance?.rootPane) editor.show() if (editor.isOK) { sdk = editor.selectedJdk instance?.updateSDKList(sdk, false) } } }
mit
4409a44948cb0e865fb584dc139de32e
36.529412
99
0.79195
4.298876
false
false
false
false
nemerosa/ontrack
ontrack-extension-git/src/main/java/net/nemerosa/ontrack/extension/git/graphql/GitChangeLogGQLType.kt
1
4855
package net.nemerosa.ontrack.extension.git.graphql import graphql.Scalars.GraphQLString import graphql.schema.DataFetchingEnvironment import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.api.model.IssueChangeLogExportRequest import net.nemerosa.ontrack.extension.git.model.GitChangeLog import net.nemerosa.ontrack.extension.git.model.GitProjectNotConfiguredException import net.nemerosa.ontrack.extension.git.service.GitService import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.support.listType import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.stereotype.Component /** * GraphQL type for a change log * @see net.nemerosa.ontrack.extension.git.model.GitChangeLog */ @Component class GitChangeLogGQLType( private val gitUICommitGQLType: GitUICommitGQLType, private val gitChangeLogIssuesGQLType: GitChangeLogIssuesGQLType, private val issueChangeLogExportRequestGQLInputType: IssueChangeLogExportRequestGQLInputType, private val gitService: GitService, ) : GQLType { override fun getTypeName(): String = GIT_CHANGE_LOG override fun createType(cache: GQLTypeCache): GraphQLObjectType { return GraphQLObjectType.newObject() .name(GIT_CHANGE_LOG) // Commits .field { f -> f.name("commits") .description("List of commits in the change log") .type(listType(gitUICommitGQLType.typeRef)) .dataFetcher { env -> val gitChangeLog: GitChangeLog = env.getSource() gitService.getChangeLogCommits(gitChangeLog).commits } } // Issues .field { f -> f.name("issues") .description("List of issues in the change log") .type(gitChangeLogIssuesGQLType.typeRef) .dataFetcher { env -> val gitChangeLog: GitChangeLog = env.getSource() gitService.getChangeLogIssues(gitChangeLog) } } // Export of change log .field { f -> f.name("export") .description("Export of the change log according to some specifications") .type(GraphQLString) .argument { it.name("request") .description("Export specifications") .type(issueChangeLogExportRequestGQLInputType.typeRef) } .dataFetcher { env -> val gitChangeLog: GitChangeLog = env.getSource() // Parses the request val request = parseExportRequest(env) // Build boundaries request.from = gitChangeLog.from.build.id request.to = gitChangeLog.to.build.id // Gets the associated project val project = gitChangeLog.project // Gets the configuration for the project val gitConfiguration = gitService.getProjectConfiguration(project) ?: return@dataFetcher null // Gets the issue service val configuredIssueService = gitConfiguration.configuredIssueService ?: return@dataFetcher null // Gets the issue change log val changeLogIssues = gitService.getChangeLogIssues(gitChangeLog) // List of issues val issues = changeLogIssues.list.map { it.issue } // Exports the change log using the given format val exportedChangeLogIssues = configuredIssueService.issueServiceExtension .exportIssues( configuredIssueService.issueServiceConfiguration, issues, request ) // Returns the content exportedChangeLogIssues.content } } // OK .build() } private fun parseExportRequest(env: DataFetchingEnvironment): IssueChangeLogExportRequest { val requestArg: Any? = env.getArgument<Any>("request") return issueChangeLogExportRequestGQLInputType.convert(requestArg) ?: IssueChangeLogExportRequest() } companion object { const val GIT_CHANGE_LOG = "GitChangeLog" } }
mit
ad5709706b04aa2e05e3c92f20748181
44.811321
107
0.579815
6.1378
false
true
false
false
genobis/tornadofx
src/main/java/tornadofx/Slideshow.kt
1
3965
package tornadofx import javafx.beans.property.ObjectProperty import javafx.beans.property.ReadOnlyIntegerProperty import javafx.beans.property.SimpleIntegerProperty import javafx.beans.property.SimpleObjectProperty import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.scene.input.KeyCombination import javafx.scene.input.KeyEvent import javafx.scene.layout.BorderPane import tornadofx.ViewTransition.Direction.RIGHT import kotlin.reflect.KClass class Slideshow(val scope: Scope = DefaultScope) : BorderPane() { val slides: ObservableList<Slide> = FXCollections.observableArrayList<Slide>() val defaultTransitionProperty: ObjectProperty<ViewTransition> = SimpleObjectProperty(ViewTransition.Swap(.3.seconds)) var defaultTransition: ViewTransition? by defaultTransitionProperty val defaultBackTransitionProperty: ObjectProperty<ViewTransition> = SimpleObjectProperty(ViewTransition.Swap(.3.seconds, RIGHT)) var defaultBackTransition: ViewTransition? by defaultBackTransitionProperty val currentSlideProperty: ObjectProperty<Slide?> = SimpleObjectProperty() var currentSlide: Slide? by currentSlideProperty val nextKeyProperty: ObjectProperty<KeyCombination> = SimpleObjectProperty(KeyCombination.valueOf("Alt+Right")) var nextKey: KeyCombination by nextKeyProperty val previousKeyProperty: ObjectProperty<KeyCombination> = SimpleObjectProperty(KeyCombination.valueOf("Alt+Left")) var previousKey: KeyCombination by previousKeyProperty private val realIndexProperty = SimpleIntegerProperty(-1) val indexProperty: ReadOnlyIntegerProperty = ReadOnlyIntegerProperty.readOnlyIntegerProperty(realIndexProperty) val index by indexProperty inline fun <reified T:UIComponent> slide(transition: ViewTransition? = null) = slide(T::class,transition) fun slide(view: KClass<out UIComponent>, transition: ViewTransition? = null) = slides.addAll(Slide(view, transition)) fun next(): Boolean { if (index + 1 >= slides.size) return false goto(slides[index + 1], true) return true } fun previous(): Boolean { if (index <= 0) return false goto(slides[index - 1], false) return true } init { showFirstSlideWhenAvailable() hookNavigationShortcuts() } private fun hookNavigationShortcuts() { sceneProperty().onChange { scene?.addEventHandler(KeyEvent.KEY_PRESSED) { if (!it.isConsumed) { if (nextKey.match(it)) next() else if (previousKey.match(it)) previous() } } } } private fun showFirstSlideWhenAvailable() { slides.addListener { change: ListChangeListener.Change<out Slide> -> while (change.next()) { if (change.wasAdded() && currentSlide == null) next() } } } private fun goto(slide: Slide, forward: Boolean) { val nextUI = slide.getUI(scope) // Avoid race conditions if last transition is still in progress val centerRightNow = center if (centerRightNow == null) { center = nextUI.root } else { val transition = if (forward) slide.transition ?: defaultTransition else defaultBackTransition nextUI.root.removeFromParent() centerRightNow.replaceWith(nextUI.root, transition) } val delta = if (forward) 1 else -1 val newIndex = index + delta currentSlide = slides[newIndex] realIndexProperty.value = newIndex } class Slide(val view: KClass<out UIComponent>, val transition: ViewTransition? = null) { private var ui: UIComponent? = null fun getUI(scope: Scope): UIComponent { if (ui == null) ui = find(view, scope) return ui!! } } }
apache-2.0
03a262d73452e54118b7aa09b4c31e43
37.134615
132
0.692055
5.076825
false
false
false
false
gameofbombs/kt-postgresql-async
postgresql-async/src/test/kotlin/com/github/mauricio/async/db/postgresql/column/IntervalSpec.kt
2
2019
/* * Copyright 2013 Maurício Linhares * Copyright 2013 Dylan Simon * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.postgresql.column import org.specs2.mutable.Specification class IntervalSpec extends Specification { "interval encoder/decoder" should { fun decode(s : String) : Any = PostgreSQLIntervalEncoderDecoder.decode(s) fun encode(i : Any) : String = PostgreSQLIntervalEncoderDecoder.encode(i) fun both(s : String) : String = encode(decode(s)) "parse and encode example intervals" in { Seq("1-2", "1 year 2 mons", "@ 1 year 2 mons", "@ 1 year 2 mons", "P1Y2M") forall { both(_) === "P1Y2M" } Seq("3 4:05:06", "3 days 04:05:06", "@ 3 days 4 hours 5 mins 6 secs", "P3DT4H5M6S") forall { both(_) === "P3DT4H5M6S" } Seq("1-2 +3 4:05:06", "1 year 2 mons +3 days 04:05:06", "@ 1 year 2 mons 3 days 4 hours 5 mins 6 secs", "P1Y2M3DT4H5M6S") forall { both(_) === "P1Y2M3DT4H5M6S" } Seq("@ 1 year 2 mons -3 days 4 hours 5 mins 6 secs ago", "P-1Y-2M3DT-4H-5M-6S") forall { both(_) === "P-1Y-2M3DT-4H-5M-6S" } both("-1.234") === "PT-1.234S" both("-4:05:06") === "PT-4H-5M-6S" } "parse and encode example intervals" in { Seq("-1-2 +3 -4:05:06", "-1 year -2 mons +3 days -04:05:06") forall { both(_) === "P-1Y-2M3DT-4H-5M-6S" } }.pendingUntilFixed("with mixed/grouped negations") } }
apache-2.0
3b42aed459c63383b8ae706965dfdb64
35.672727
136
0.639068
3.127132
false
false
false
false
JimSeker/drawing
DrawDemo1_kt/app/src/main/java/edu/cs4730/drawdemo1_kt/MainFragment.kt
1
6535
package edu.cs4730.drawdemo1_kt import android.graphics.* import android.view.LayoutInflater import android.view.ViewGroup import android.os.Bundle import android.util.Log import android.view.View.OnTouchListener import android.view.MotionEvent import android.view.View import android.widget.* import androidx.fragment.app.Fragment /** * This is a simple example to show how each of the canvas drawing works. * */ class MainFragment : Fragment() { lateinit var theboardfield: ImageView lateinit var theboard: Bitmap lateinit var theboardc: Canvas lateinit var btnClear: Button lateinit var btnNColor: Button lateinit var mySpinner: Spinner var which = 1 val boardsize = 480 //for drawing var firstx = 0f var firsty = 0f var first = true var myRecF = RectF() var myColor: Paint? = null var myColorList = ColorList() lateinit var alien: Bitmap override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val myView = inflater.inflate(R.layout.fragment_main, container, false) //Simple clear button, reset the image to white. btnClear = myView.findViewById<View>(R.id.button2) as Button btnClear.setOnClickListener { theboardc.drawColor(Color.WHITE) //background color for the board. refreshBmp() } //changes to the next color in the list btnNColor = myView.findViewById<View>(R.id.button3) as Button btnNColor.setOnClickListener { myColorList.next() myColor!!.color = myColorList.getNum() } //setup the spinner val list = arrayOf("Point", "Line", "Rect", "Circle", "Arc", "Oval", "Pic", "Text") //first we will work on the spinner1 (which controls the seekbar) mySpinner = myView.findViewById<View>(R.id.spinner) as Spinner //create the ArrayAdapter of strings from my List. val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, list) //set the dropdown layout adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) //finally set the adapter to the spinner mySpinner.adapter = adapter //set the selected listener as well mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parent: AdapterView<*>?, view: View, position: Int, id: Long ) { which = position first = true } override fun onNothingSelected(parent: AdapterView<*>?) { which = 1 //point first = true } } //get the imageview and create a bitmap to put in the imageview. //also create the canvas to draw on. theboardfield = myView.findViewById<View>(R.id.boardfield) as ImageView theboard = Bitmap.createBitmap(boardsize, boardsize, Bitmap.Config.ARGB_8888) theboardc = Canvas(theboard) theboardc.drawColor(Color.WHITE) //background color for the board. theboardfield.setImageBitmap(theboard) theboardfield.invalidate() theboardfield.setOnTouchListener(myTouchListener()) //For drawing myColor = Paint() //default black myColor!!.color = myColorList.getNum() myColor!!.style = Paint.Style.FILL myColor!!.strokeWidth = 10f myColor!!.textSize = myColor!!.textSize * 4 //load a picture and draw it onto the screen. alien = BitmapFactory.decodeResource(resources, R.drawable.alien) //draw it on the screen. //theboardc.drawBitmap(alien, null, new Rect(0, 0, 300, 300), myColor); return myView } /* * TouchListener will draw a square on the image where "touched". * If doing an animated clear, it will return without doing anything. */ internal inner class myTouchListener : OnTouchListener { override fun onTouch(v: View, event: MotionEvent): Boolean { //We just need the x and y position, to draw on the canvas //so, retrieve the new x and y touch positions if (event.action == MotionEvent.ACTION_UP) { //fake it for tap. drawBmp(event.x, event.y) v.performClick() return true } return false } } fun drawBmp(x: Float, y: Float) { //"Point", "Line", "Rect", "Circle", "Arc", "Oval", "Pic", "Text" when (which) { 0 -> theboardc.drawPoint(x, y, myColor!!) 1 -> if (first) { //store the point for later firstx = x firsty = y first = false } else { theboardc.drawLine(firstx, firsty, x, y, myColor!!) first = true } 2 -> if (first) { //store the point for later myRecF.top = y myRecF.left = x first = false } else { myRecF.bottom = y myRecF.right = x theboardc.drawRect(myRecF, myColor!!) first = true } 3 -> theboardc.drawCircle(x, y, 20.0f, myColor!!) 4 -> if (first) { //store the point for later myRecF.top = y myRecF.left = x first = false } else { myRecF.bottom = y myRecF.right = x theboardc.drawArc(myRecF, 0.0f, 45.0f, true, myColor!!) first = true } 5 -> if (first) { //store the point for later myRecF.top = y myRecF.left = x first = false } else { myRecF.bottom = y myRecF.right = x theboardc.drawOval(myRecF, myColor!!) first = true } 6 -> theboardc.drawBitmap(alien, x, y, myColor) 7 -> theboardc.drawText("Hi there", x, y, myColor!!) else -> Log.v("hi", "NOT working? $which") } theboardfield.setImageBitmap(theboard) theboardfield.invalidate() } fun refreshBmp() { theboardfield.setImageBitmap(theboard) theboardfield.invalidate() } }
apache-2.0
292105e1bf95e5ad4aa4e5f296a41a82
34.32973
96
0.574445
4.840741
false
false
false
false
apixandru/intellij-community
platform/lang-impl/src/com/intellij/psi/stubs/PrebuiltStubs.kt
1
6706
/* * 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 com.intellij.psi.stubs import com.google.common.hash.HashCode import com.google.common.hash.Hashing import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.PathManager import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileTypes.FileTypeExtension import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.io.FileUtil import com.intellij.util.indexing.FileContent import com.intellij.util.indexing.IndexInfrastructure import com.intellij.util.io.DataExternalizer import com.intellij.util.io.DataInputOutputUtil import com.intellij.util.io.KeyDescriptor import com.intellij.util.io.PersistentHashMap import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.TestOnly import java.io.DataInput import java.io.DataOutput import java.io.File import java.io.IOException /** * @author traff */ val EP_NAME = "com.intellij.filetype.prebuiltStubsProvider" object PrebuiltStubsProviders : FileTypeExtension<PrebuiltStubsProvider>(EP_NAME) @ApiStatus.Experimental interface PrebuiltStubsProvider { fun findStub(fileContent: FileContent): Stub? } class FileContentHashing { private val hashing = Hashing.sha256() fun hashString(fileContent: FileContent) = hashing.hashBytes(fileContent.content) } class HashCodeDescriptor : HashCodeExternalizers(), KeyDescriptor<HashCode> { override fun getHashCode(value: HashCode): Int = value.hashCode() override fun isEqual(val1: HashCode, val2: HashCode): Boolean = val1 == val2 companion object { val instance = HashCodeDescriptor() } } open class HashCodeExternalizers : DataExternalizer<HashCode> { override fun save(out: DataOutput, value: HashCode) { val bytes = value.asBytes() DataInputOutputUtil.writeINT(out, bytes.size) out.write(bytes, 0, bytes.size) } override fun read(`in`: DataInput): HashCode { val len = DataInputOutputUtil.readINT(`in`) val bytes = ByteArray(len) `in`.readFully(bytes) return HashCode.fromBytes(bytes) } } class StubTreeExternalizer : DataExternalizer<SerializedStubTree> { override fun save(out: DataOutput, value: SerializedStubTree) { value.write(out) } override fun read(`in`: DataInput) = SerializedStubTree(`in`) } abstract class PrebuiltStubsProviderBase : PrebuiltStubsProvider, Disposable { private val myFileContentHashing = FileContentHashing() private var myPrebuiltStubsStorage: PersistentHashMap<HashCode, SerializedStubTree>? = null private var mySerializationManager: SerializationManagerImpl? = null protected abstract val stubVersion: Int protected abstract val name: String init { init() } companion object { val PREBUILT_INDICES_PATH_PROPERTY = "prebuilt_indices_path" val SDK_STUBS_STORAGE_NAME = "sdk-stubs" private val LOG = Logger.getInstance("#com.intellij.psi.stubs.PrebuiltStubsProviderBase") } internal fun init() { var indexesRoot = findPrebuiltIndicesRoot() try { if (indexesRoot != null) { // we should copy prebuilt indexes to a writable folder indexesRoot = copyPrebuiltIndicesToIndexRoot(indexesRoot) // otherwise we can get access denied error, because persistent hash map opens file for read and write val versionInFile = FileUtil.loadFile(File(indexesRoot, SDK_STUBS_STORAGE_NAME + ".version")) if (Integer.parseInt(versionInFile) == stubVersion) { myPrebuiltStubsStorage = object : PersistentHashMap<HashCode, SerializedStubTree>( File(indexesRoot, SDK_STUBS_STORAGE_NAME + ".input"), HashCodeDescriptor.instance, StubTreeExternalizer()) { override fun isReadOnly(): Boolean { return true } } mySerializationManager = SerializationManagerImpl(File(indexesRoot, SDK_STUBS_STORAGE_NAME + ".names")) Disposer.register(ApplicationManager.getApplication(), mySerializationManager!!) LOG.info("Using prebuilt stubs from " + myPrebuiltStubsStorage!!.baseFile.absolutePath) } else { LOG.error("Prebuilt stubs version mismatch: $versionInFile, current version is $stubVersion") } } } catch (e: Exception) { myPrebuiltStubsStorage = null LOG.warn("Prebuilt stubs can't be loaded at " + indexesRoot!!, e) } } override fun findStub(fileContent: FileContent): Stub? { if (myPrebuiltStubsStorage != null) { val hashCode = myFileContentHashing.hashString(fileContent) var stub: Stub? = null try { val stubTree = myPrebuiltStubsStorage!!.get(hashCode) if (stubTree != null) { stub = stubTree.getStub(false, mySerializationManager!!) } } catch (e: SerializerNotFoundException) { LOG.error("Can't deserialize stub tree", e) } catch (e: Exception) { LOG.error("Error reading prebuilt stubs from " + myPrebuiltStubsStorage!!.baseFile.path, e) myPrebuiltStubsStorage = null stub = null } if (stub != null) { return stub } } return null } override fun dispose() { if (myPrebuiltStubsStorage != null) { try { myPrebuiltStubsStorage!!.close() } catch (e: IOException) { LOG.error(e) } } } @Throws(IOException::class) private fun copyPrebuiltIndicesToIndexRoot(prebuiltIndicesRoot: File): File { val indexRoot = File(IndexInfrastructure.getPersistentIndexRoot(), "prebuilt/" + name) FileUtil.copyDir(prebuiltIndicesRoot, indexRoot) return indexRoot } private fun findPrebuiltIndicesRoot(): File? { val path: String? = System.getProperty(PREBUILT_INDICES_PATH_PROPERTY) if (path != null && File(path).exists()) { return File(path) } val f = indexRoot() return if (f.exists()) f else null } open fun indexRoot():File = File(PathManager.getHomePath(), "index/$name") // compiled binary } @TestOnly fun PrebuiltStubsProviderBase.reset() { this.init() }
apache-2.0
f5d8cbb0d0282814be15ff938a728c2b
30.938095
113
0.713838
4.497653
false
false
false
false
gmariotti/intro-big-data
03_sensors-analysis/src/main/kotlin/SensorsMapperType1.kt
1
934
import common.hadoop.extensions.split import org.apache.hadoop.io.Text import org.apache.hadoop.mapreduce.Mapper import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs /* Input format is of type: <s#id>\t<date>,<temp> */ class SensorsMapperType1: Mapper<Text, Text, Text, SensorData>() { lateinit var multipleOutputs: MultipleOutputs<Text, SensorData> override fun setup(context: Context) { multipleOutputs = MultipleOutputs(context) } override fun map(key: Text, value: Text, context: Context) { val values = value.split(",") val date = values[0] val temp = values[1].toFloat() val sensorData = SensorData(date, temp) val threshold = context.configuration.get(THRESHOLD).toFloat() if (temp >= threshold) { multipleOutputs.write(HIGH_TEMP, key, sensorData) } else { multipleOutputs.write(LOW_TEMP, key, sensorData) } } override fun cleanup(context: Context?) { multipleOutputs.close() } }
mit
2aa53fdfdbddba65af9151d6d0d0a600
26.5
66
0.734475
3.34767
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/persistence/game/GameSettingsBE.kt
2
3830
package de.sudoq.persistence.game import de.sudoq.model.game.Assistances import de.sudoq.model.sudoku.sudokuTypes.SudokuTypes import de.sudoq.persistence.sudoku.sudokuTypes.SudokuTypesListBE import de.sudoq.persistence.XmlAttribute import de.sudoq.persistence.XmlTree import de.sudoq.persistence.Xmlable import java.util.* import kotlin.math.pow class GameSettingsBE(val assistances: BitSet = BitSet(), var isLefthandModeSet: Boolean = false, var isHelperSet: Boolean = false, var isGesturesSet: Boolean = false, val wantedTypesList: SudokuTypesListBE = SudokuTypesListBE(listOf(*SudokuTypes.values())) ) : Xmlable { /** * Sets an assistance to true * * @param assistance The assistance to set */ fun setAssistance(assistance: Assistances) { assistances.set( 2.0.pow((assistance.ordinal + 1).toDouble()).toInt() ) //TODO that looks wrong... } /* to and from string */ override fun toXmlTree(): XmlTree { val representation = XmlTree("gameSettings") representation.addAttribute( XmlAttribute( "assistances", convertAssistancesToString() ) ) //TODO scrap that, representation as 0,1 is ugly -> save all with name, then make all of the boolean assistances enums representation.addAttribute(XmlAttribute("gestures", isGesturesSet)) representation.addAttribute(XmlAttribute("left", isLefthandModeSet)) representation.addAttribute(XmlAttribute("helper", isHelperSet)) representation.addChild(wantedTypesList.toXmlTree()) return representation } @Throws(IllegalArgumentException::class) override fun fillFromXml(xmlTreeRepresentation: XmlTree) { assistancesfromString(xmlTreeRepresentation.getAttributeValue("assistances")!!) isGesturesSet = java.lang.Boolean.parseBoolean(xmlTreeRepresentation.getAttributeValue("gestures")) isLefthandModeSet = java.lang.Boolean.parseBoolean(xmlTreeRepresentation.getAttributeValue("left")) isHelperSet = java.lang.Boolean.parseBoolean(xmlTreeRepresentation.getAttributeValue("helper")) for (xt in xmlTreeRepresentation) if (xt.name == SudokuTypesListBE.ROOT_NAME) wantedTypesList.fillFromXml( xt ) } /** * Generates a String of "0" and "1" from the AssistanceSet. * The String car be parsed again with [assistancesfromString]. * * @return String representation of the AssistanceSet */ private fun convertAssistancesToString(): String { val bitstring = StringBuilder() for (assist in Assistances.values()) bitstring.append(if (getAssistance(assist)) "1" else "0") return bitstring.toString() } /** * Checks if an assistance is set * * @param assistance [Assistances] to check * @return true, if assistance is set, false otherwise */ open fun getAssistance(assistance: Assistances): Boolean { return assistances[2.0.pow((assistance.ordinal + 1).toDouble()).toInt()] } /** * Reads the Assistance set from a String of "0" and "1"s * * @param representation String representation of the assistances * * @throws IllegalArgumentException on parse error */ @Throws(IllegalArgumentException::class) private fun assistancesfromString(representation: String) { for ((i, assist) in Assistances.values().withIndex()) { try { if (representation[i] == '1') { setAssistance(assist) } } catch (exc: Exception) { throw IllegalArgumentException() } } } }
gpl-3.0
82ebeae41ce66a68bd8d9e9f612891c7
36.194175
128
0.651436
4.891443
false
false
false
false
AndroidX/androidx
navigation/navigation-runtime/src/main/java/androidx/navigation/Navigation.kt
3
5688
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation import android.app.Activity import android.os.Bundle import android.view.View import androidx.annotation.IdRes import androidx.core.app.ActivityCompat import java.lang.ref.WeakReference /** * Entry point for navigation operations. * * This class provides utilities for finding a relevant [NavController] instance from * various common places in your application, or for performing navigation in response to * UI events. */ public object Navigation { /** * Find a [NavController] given the id of a View and its containing * [Activity]. This is a convenience wrapper around [findNavController]. * * This method will locate the [NavController] associated with this view. * This is automatically populated for the id of a [NavHost] and its children. * * @param activity The Activity hosting the view * @param viewId The id of the view to search from * @return the [NavController] associated with the view referenced by id * @throws IllegalStateException if the given viewId does not correspond with a * [NavHost] or is not within a NavHost. */ @JvmStatic public fun findNavController(activity: Activity, @IdRes viewId: Int): NavController { val view = ActivityCompat.requireViewById<View>(activity, viewId) return findViewNavController(view) ?: throw IllegalStateException( "Activity $activity does not have a NavController set on $viewId" ) } /** * Find a [NavController] given a local [View]. * * This method will locate the [NavController] associated with this view. * This is automatically populated for views that are managed by a [NavHost] * and is intended for use by various [listener][android.view.View.OnClickListener] * interfaces. * * @param view the view to search from * @return the locally scoped [NavController] to the given view * @throws IllegalStateException if the given view does not correspond with a * [NavHost] or is not within a NavHost. */ @JvmStatic public fun findNavController(view: View): NavController { return findViewNavController(view) ?: throw IllegalStateException("View $view does not have a NavController set") } /** * Create an [android.view.View.OnClickListener] for navigating * to a destination. This supports both navigating via an * [action][NavDestination.getAction] and directly navigating to a destination. * * @param resId an [action][NavDestination.getAction] id or a destination id to * navigate to when the view is clicked * @param args arguments to pass to the final destination * @return a new click listener for setting on an arbitrary view */ @JvmStatic @JvmOverloads public fun createNavigateOnClickListener( @IdRes resId: Int, args: Bundle? = null ): View.OnClickListener { return View.OnClickListener { view -> findNavController(view).navigate(resId, args) } } /** * Create an [android.view.View.OnClickListener] for navigating * to a destination via a generated [NavDirections]. * * @param directions directions that describe this navigation operation * @return a new click listener for setting on an arbitrary view */ @JvmStatic public fun createNavigateOnClickListener(directions: NavDirections): View.OnClickListener { return View.OnClickListener { view -> findNavController(view).navigate(directions) } } /** * Associates a NavController with the given View, allowing developers to use * [findNavController] and [findNavController] with that * View or any of its children to retrieve the NavController. * * This is generally called for you by the hosting [NavHost]. * @param view View that should be associated with the given NavController * @param controller The controller you wish to later retrieve via * [findNavController] */ @JvmStatic public fun setViewNavController(view: View, controller: NavController?) { view.setTag(R.id.nav_controller_view_tag, controller) } /** * Recurse up the view hierarchy, looking for the NavController * @param view the view to search from * @return the locally scoped [NavController] to the given view, if found */ private fun findViewNavController(view: View): NavController? = generateSequence(view) { it.parent as? View? }.mapNotNull { getViewNavController(it) }.firstOrNull() @Suppress("UNCHECKED_CAST") private fun getViewNavController(view: View): NavController? { val tag = view.getTag(R.id.nav_controller_view_tag) var controller: NavController? = null if (tag is WeakReference<*>) { controller = (tag as WeakReference<NavController>).get() } else if (tag is NavController) { controller = tag } return controller } }
apache-2.0
f2728044ebf24b790303b32b9ae55ac8
38.776224
95
0.690049
4.836735
false
false
false
false
Xenoage/Zong
core/src/com/xenoage/zong/core/position/Time.kt
1
944
package com.xenoage.zong.core.position import com.xenoage.utils.math.Fraction import com.xenoage.utils.math._0 /** * Time in a score. * Like a [MP], but consists only of measure and beat. */ data class Time( /** The measure index */ val measure: Int, /** The beat within the measure */ val beat: Fraction ) : Comparable<Time> { /** Compares this [Time] with the given one */ override fun compareTo(time: Time) = when { measure < time.measure -> -1 measure > time.measure -> 1 else -> beat.compareTo(time.beat) } override fun toString() = "[Measure = " + measure + ", Beat = " + beat.numerator + "/" + beat.denominator + "]" fun toStringCompact() = "m" + measure + ",b" + beat.numerator + "/" + beat.denominator } /** Creates a new [Time] at the given measure and beat. */ fun time(measure: Int, beat: Fraction) = Time(measure, beat) /** Musical position with all values set to 0. */ val time0 = Time(0, _0)
agpl-3.0
99769a60f601781f65b3b8c2d868caa2
24.540541
88
0.648305
3.277778
false
false
false
false
Dr-Horv/Advent-of-Code-2017
src/main/kotlin/solutions/Main.kt
1
2497
package solutions import solutions.day01.Day1 import solutions.day02.Day2 import solutions.day03.Day3 import solutions.day04.Day4 import solutions.day05.Day5 import solutions.day06.Day6 import solutions.day07.Day7 import solutions.day08.Day8 import solutions.day09.Day9 import solutions.day10.Day10 import solutions.day11.Day11 import solutions.day12.Day12 import solutions.day13.Day13 import solutions.day14.Day14 import solutions.day15.Day15 import solutions.day16.Day16 import solutions.day18.Day18 import solutions.day20.Day20 import solutions.day21.Day21 import solutions.day22.Day22 import solutions.day23.Day23 import solutions.day24.Day24 import solutions.day25.Day25 import utils.readFile import kotlin.system.measureNanoTime enum class Days { Day01, Day02, Day03, Day04, Day05, Day06, Day07, Day08, Day09, Day10, Day11, Day12, Day13, Day14, Day15, Day16, Day18, Day20, Day22, Day21, Day23, Day24, Day25 } fun Long.toSeconds(): Double = this / (10e8) fun Long.toMilliseconds(): Double = this / (10e5) fun main(args: Array<String>) { val time = measureNanoTime { val partTwo = false val day = Days.Day16 val input = getInput(day) val solver = when (day) { Days.Day01 -> Day1() Days.Day02 -> Day2() Days.Day03 -> Day3() Days.Day04 -> Day4() Days.Day05 -> Day5() Days.Day06 -> Day6() Days.Day07 -> Day7() Days.Day08 -> Day8() Days.Day09 -> Day9() Days.Day10 -> Day10() Days.Day11 -> Day11() Days.Day12 -> Day12() Days.Day13 -> Day13() Days.Day14 -> Day14() Days.Day15 -> Day15() Days.Day16 -> Day16() Days.Day18 -> Day18() Days.Day20 -> Day20() Days.Day21 -> Day21() Days.Day22 -> Day22() Days.Day23 -> Day23() Days.Day24 -> Day24() Days.Day25 -> Day25() } printAnswer(day.name, solver.solve(input, partTwo)) } println("Took ${time.toSeconds()} seconds") println("Took ${time.toMilliseconds()} milliseconds") } fun getInput(day: Days): List<String> { val solutions = "src/main/kotlin/solutions" return readFile("$solutions/${day.name.toLowerCase()}/input") } fun printAnswer(msg: String, answer: String) { println("$msg: $answer") }
mit
fc48f8b9841368388e94298c2d272636
21.908257
65
0.609131
3.448895
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/container/builtin/ContainerLock.kt
1
3016
package com.teamwizardry.librarianlib.facade.container.builtin import java.util.function.Supplier public fun interface ContainerLock { public fun isLocked(): Boolean public class ManualLock(private var isLocked: Boolean) : ContainerLock { public fun setLocked(value: Boolean) { this.isLocked = value } public fun lock() { this.isLocked = true } public fun unlock() { this.isLocked = false } override fun isLocked(): Boolean { return isLocked } } public class StaticLock(private val isLocked: Boolean) : ContainerLock { override fun isLocked(): Boolean { return isLocked } } /** * A slot intended to prevent certain kinds of item duplication glitches. To do this, it records the value returned * from the [verificationCallback] and before every operation it verifies that the callback returns the same object. * * The specific dupe this prevents is (using a backpack as an example): * * - the player opens a backpack item * - you open a container and add the held backpack's inventory to it * - the player puts items in the backpack inventory * - the player uses a "player interface" of some sort to take the backpack out of their inventory and put it in a * chest, which copies the itemstack and discards the existing instance * - your screen is now accessing an "orphaned" backpack, so the player can pull items out without affecting the * instance in the chest * - congratulations, you've just introduced a new dupe! * * ***!NOTE!*** * It seems the default inventory code in 1.16+ does *not* actually *replace* the ItemStack in the inventory, it * just *modifies* it. This means you can *not* use the actual stack, you'll have to use something like a capability * instead. (e.g. `player.getItemInHand(...).getCapability(...)`) * * The code is designed to be more general though, so you can use any object as the verification. * * * @param verificationCallback A callback that, if its value changes, will lock the slot. * @param isClient Whether this slot is in the client container. ItemStack object identity in particular is not * preserved on the client, so the check has to be disabled there. */ public class ConsistencyLock( private val isClient: Boolean, private val verificationCallback: Supplier<Any> ) : ContainerLock { private val verificationReference: Any = verificationCallback.get() override fun isLocked(): Boolean { if (isClient) return false return verificationCallback.get() !== verificationReference } } public companion object { @JvmField public val LOCKED: ContainerLock = StaticLock(true) @JvmField public val UNLOCKED: ContainerLock = StaticLock(false) } }
lgpl-3.0
70840c30b00a1e5458eec858704d8ae9
37.679487
120
0.657493
4.920065
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/pastry/layers/PastryTabPane.kt
1
1401
package com.teamwizardry.librarianlib.facade.pastry.layers import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.layers.SpriteLayer import com.teamwizardry.librarianlib.facade.pastry.ExperimentalPastryAPI import com.teamwizardry.librarianlib.facade.pastry.PastryTexture import com.teamwizardry.librarianlib.core.util.vec @ExperimentalPastryAPI public class PastryTabPane: GuiLayer { private val background = SpriteLayer(PastryTexture.tabsBody) public val pages: List<PastryTabPage> get() = children.filterIsInstance<PastryTabPage>().filter { it.isVisible } public constructor(posX: Int, posY: Int, width: Int, height: Int): super(posX, posY, width, height) public constructor(posX: Int, posY: Int): super(posX, posY) public constructor(): super() init { this.add(background) } override fun layoutChildren() { pages.forEach { it.frame = this.bounds } children.forEach { it.runLayout() } var x = 1.0 val maxTabHeight = pages.map { it.tab.height }.maxOrNull() ?: 0.0 pages.forEach { it.tab.pos = vec(x, maxTabHeight - it.tab.height) x += it.tab.width + 1 it.contents.frame = it.bounds.offset(0, maxTabHeight, 0, 0) } background.frame = this.bounds.offset(0, maxTabHeight - 1, 0, 0) } }
lgpl-3.0
0859d391e4cd63c5fae536b543e3af8c
35.894737
103
0.685939
3.946479
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/timeTracker/IssueWorkItemsStoreUpdaterService.kt
1
3525
package com.github.jk1.ytplugin.timeTracker import com.github.jk1.ytplugin.ComponentAware import com.github.jk1.ytplugin.logger import com.github.jk1.ytplugin.rest.TimeTrackerRestClient import com.github.jk1.ytplugin.tasks.NoYouTrackRepositoryException import com.github.jk1.ytplugin.tasks.YouTrackServer import com.intellij.concurrency.JobScheduler import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.project.Project import com.intellij.serviceContainer.AlreadyDisposedException import java.util.* import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import javax.swing.SwingUtilities /** * Manages timed issueWorkItems store updates for active projects * todo: the service is initialized lazily, so it's only behave as expected because of a #subscribe call * todo: convert into a post startup activity */ @Service class IssueWorkItemsStoreUpdaterService(override val project: Project) : Disposable, ComponentAware { // todo: customizable update interval private val timedRefreshTask: ScheduledFuture<*> = JobScheduler.getScheduler().scheduleWithFixedDelay({ SwingUtilities.invokeLater { if (!project.isDisposed) { taskManagerComponent.getAllConfiguredYouTrackRepositories().forEach { issueWorkItemsStoreComponent[it].update(it) } } } }, 5, 5, TimeUnit.MINUTES) private val listeners: MutableSet<() -> Unit> = mutableSetOf() override fun dispose() { try { val repo = taskManagerComponent.getActiveYouTrackRepository() val timer = timeTrackerComponent if (timer.isWhenProjectClosedEnabled) { logger.debug("state PROJECT_CLOSE with posting enabled") postOnProjectClose(timer, repo) } } catch (e: NoYouTrackRepositoryException) { logger.warn("NoYouTrackRepository: ${e.message}") } catch (e: AlreadyDisposedException) { logger.debug("Container is already disposed") logger.debug(e) } timedRefreshTask.cancel(true) } private fun postOnProjectClose(timer: TimeTracker, repo: YouTrackServer) { try { timer.stop() repo.let { it1 -> val connector = TimeTrackerConnector(it1, project) connector.postWorkItemToServer(timer.issueId, timer.recordedTime, timer.type, timer.comment, (Date().time).toString(), mapOf()) // post not only last recorded item, but all saved items as well connector.postSavedWorkItemsToServer(spentTimePerTaskStorage.getAllStoredItems()) } val propertiesStore: PropertiesComponent = PropertiesComponent.getInstance(project) propertiesStore.setValue("spentTimePerTaskStorage.store", timer.spentTimePerTaskStorage.getAllStoredItems().toString()) logger.debug("time tracker stopped on PROJECT_CLOSE with time ${timer.recordedTime}") } catch (e: IllegalStateException) { logger.debug("Could not stop time tracking: timer is not started: ${e.message}") } } fun subscribe(listener: () -> Unit) { listeners.add(listener) } fun onAfterUpdate() { listeners.forEach { it.invoke() } } }
apache-2.0
3d5e1b6a78decf80f85ca83bbbe69f52
40
131
0.674326
4.93007
false
false
false
false
ryan652/EasyCrypt
easycrypt/src/main/java/com/pvryan/easycrypt/asymmetric/performVerify.kt
1
2760
/* * Copyright 2018 Priyank Vasa * 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.pvryan.easycrypt.asymmetric import com.pvryan.easycrypt.Constants import com.pvryan.easycrypt.extensions.asString import com.pvryan.easycrypt.extensions.fromBase64 import org.jetbrains.anko.AnkoLogger import java.io.File import java.io.FileInputStream import java.io.IOException import java.io.InputStream import java.security.InvalidParameterException import java.security.Signature import java.security.SignatureException import java.security.interfaces.RSAPublicKey @Suppress("ClassName") internal object performVerify : AnkoLogger { private val signature = Signature.getInstance(Constants.SIGNATURE_ALGORITHM) @JvmSynthetic internal fun <T> invoke(input: T, publicKey: RSAPublicKey, sigFile: File, evl: ECVerifiedListener) { signature.initVerify(publicKey) when (input) { is InputStream -> { val buffer = ByteArray(8192) var bytesCopied: Long = 0 try { val size = if (input is FileInputStream) input.channel.size() else -1 var read = input.read(buffer) while (read > -1) { signature.update(buffer, 0, read) bytesCopied += read evl.onProgress(read, bytesCopied, size) read = input.read(buffer) } try { evl.onSuccess(signature.verify( sigFile.readBytes().asString().fromBase64())) } catch (e: IllegalArgumentException) { evl.onFailure(Constants.ERR_BAD_BASE64, e) } catch (e: SignatureException) { evl.onFailure(Constants.ERR_VERIFY_EXCEPTION, e) } } catch (e: IOException) { evl.onFailure(Constants.ERR_CANNOT_WRITE, e) } } else -> evl.onFailure(Constants.ERR_INPUT_TYPE_NOT_SUPPORTED, InvalidParameterException()) } } }
apache-2.0
d2e3e28d7cffda8cd49e74a3f66621a5
33.5
102
0.601087
4.919786
false
false
false
false
androidx/androidx
datastore/datastore-core/src/commonMain/kotlin/androidx/datastore/core/DataMigrationInitializer.kt
3
2488
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.datastore.core /** * Returns an initializer function created from a list of DataMigrations. */ internal class DataMigrationInitializer<T>() { companion object { /** * Creates an initializer from DataMigrations for use with DataStore. * * @param migrations A list of migrations that will be included in the initializer. * @return The initializer which includes the data migrations returned from the factory * functions. */ fun <T> getInitializer(migrations: List<DataMigration<T>>): suspend (api: InitializerApi<T>) -> Unit = { api -> runMigrations(migrations, api) } private suspend fun <T> runMigrations( migrations: List<DataMigration<T>>, api: InitializerApi<T> ) { val cleanUps = mutableListOf<suspend () -> Unit>() api.updateData { startingData -> migrations.fold(startingData) { data, migration -> if (migration.shouldMigrate(data)) { cleanUps.add { migration.cleanUp() } migration.migrate(data) } else { data } } } var cleanUpFailure: Throwable? = null cleanUps.forEach { cleanUp -> try { cleanUp() } catch (exception: Throwable) { if (cleanUpFailure == null) { cleanUpFailure = exception } else { cleanUpFailure!!.addSuppressed(exception) } } } // If we encountered a failure on cleanup, throw it. cleanUpFailure?.let { throw it } } } }
apache-2.0
2f378c7ac6cd7232de57e78a05d75317
34.056338
95
0.560691
5.237895
false
false
false
false
mickele/DBFlow
dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/definition/InternalAdapterHelper.kt
1
5479
package com.raizlabs.android.dbflow.processor.definition import com.raizlabs.android.dbflow.processor.ClassNames import com.raizlabs.android.dbflow.processor.definition.column.ColumnDefinition import com.raizlabs.android.dbflow.processor.definition.column.DefinitionUtils import com.raizlabs.android.dbflow.processor.utils.ModelUtils import com.raizlabs.android.dbflow.sql.QueryBuilder import com.squareup.javapoet.* import javax.lang.model.element.Modifier /** * Description: Assists in writing methods for adapters */ object InternalAdapterHelper { fun writeGetModelClass(typeBuilder: TypeSpec.Builder, modelClassName: ClassName?) { typeBuilder.addMethod(MethodSpec.methodBuilder("getModelClass") .addAnnotation(Override::class.java) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addStatement("return \$T.class", modelClassName) .returns(ParameterizedTypeName.get(ClassName.get(Class::class.java), modelClassName)) .build()) } fun writeGetTableName(typeBuilder: TypeSpec.Builder, tableName: String?) { typeBuilder.addMethod(MethodSpec.methodBuilder("getTableName") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addStatement("return \$S", QueryBuilder.quote(tableName)) .returns(ClassName.get(String::class.java)) .build()) } fun writeUpdateAutoIncrement(typeBuilder: TypeSpec.Builder, modelClassName: TypeName?, autoIncrementDefinition: ColumnDefinition) { typeBuilder.addMethod(MethodSpec.methodBuilder("updateAutoIncrement") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(modelClassName, ModelUtils.variable) .addParameter(ClassName.get(Number::class.java), "id") .addCode(autoIncrementDefinition.updateAutoIncrementMethod) .build()) } fun writeGetCachingId(typeBuilder: TypeSpec.Builder, modelClassName: TypeName?, primaryColumns: List<ColumnDefinition>) { if (primaryColumns.size > 1) { var methodBuilder: MethodSpec.Builder = MethodSpec.methodBuilder("getCachingColumnValuesFromModel") .addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ArrayTypeName.of(Any::class.java), "inValues") .addParameter(modelClassName, ModelUtils.variable) for (i in primaryColumns.indices) { val column = primaryColumns[i] methodBuilder.addCode(column.getColumnAccessString(i)) } methodBuilder.addStatement("return \$L", "inValues").returns(ArrayTypeName.of(Any::class.java)) typeBuilder.addMethod(methodBuilder.build()) methodBuilder = MethodSpec.methodBuilder("getCachingColumnValuesFromCursor") .addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ArrayTypeName.of(Any::class.java), "inValues") .addParameter(ClassNames.CURSOR, "cursor") for (i in primaryColumns.indices) { val column = primaryColumns[i] val method = DefinitionUtils.getLoadFromCursorMethodString(column.elementTypeName, column.wrapperTypeName) methodBuilder.addStatement("inValues[\$L] = \$L.\$L(\$L.getColumnIndex(\$S))", i, LoadFromCursorMethod.PARAM_CURSOR, method, LoadFromCursorMethod.PARAM_CURSOR, column.columnName) } methodBuilder.addStatement("return \$L", "inValues").returns(ArrayTypeName.of(Any::class.java)) typeBuilder.addMethod(methodBuilder.build()) } else { // single primary key var methodBuilder: MethodSpec.Builder = MethodSpec.methodBuilder("getCachingColumnValueFromModel") .addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(modelClassName, ModelUtils.variable) methodBuilder.addCode(primaryColumns[0].getSimpleAccessString()) .returns(Any::class.java) typeBuilder.addMethod(methodBuilder.build()) methodBuilder = MethodSpec.methodBuilder("getCachingColumnValueFromCursor") .addAnnotation(Override::class.java).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(ClassNames.CURSOR, "cursor") val column = primaryColumns[0] val method = DefinitionUtils.getLoadFromCursorMethodString(column.elementTypeName, column.wrapperTypeName) methodBuilder.addStatement("return \$L.\$L(\$L.getColumnIndex(\$S))", LoadFromCursorMethod.PARAM_CURSOR, method, LoadFromCursorMethod.PARAM_CURSOR, column.columnName).returns(Any::class.java) typeBuilder.addMethod(methodBuilder.build()) methodBuilder = MethodSpec.methodBuilder("getCachingId") .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addParameter(modelClassName, ModelUtils.variable) .addStatement("return getCachingColumnValueFromModel(\$L)", ModelUtils.variable).returns(TypeName.OBJECT) typeBuilder.addMethod(methodBuilder.build()) } } }
mit
1a1fab8e7aa40bf22a550d52b6c5b68f
56.072917
132
0.664537
5.350586
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/Draggable.kt
3
18393
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.gestures import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.MutatorMutex import androidx.compose.foundation.gestures.DragEvent.DragCancelled import androidx.compose.foundation.gestures.DragEvent.DragDelta import androidx.compose.foundation.gestures.DragEvent.DragStarted import androidx.compose.foundation.gestures.DragEvent.DragStopped import androidx.compose.foundation.interaction.DragInteraction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.internal.JvmDefaultWithCompatibility import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.AwaitPointerEventScope import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.PointerInputChange import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChange import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.input.pointer.util.addPointerInputChange import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.unit.Velocity import kotlin.coroutines.cancellation.CancellationException import kotlin.math.sign import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.isActive /** * State of [draggable]. Allows for a granular control of how deltas are consumed by the user as * well as to write custom drag methods using [drag] suspend function. */ @JvmDefaultWithCompatibility interface DraggableState { /** * Call this function to take control of drag logic. * * All actions that change the logical drag position must be performed within a [drag] * block (even if they don't call any other methods on this object) in order to guarantee * that mutual exclusion is enforced. * * If [drag] is called from elsewhere with the [dragPriority] higher or equal to ongoing * drag, ongoing drag will be canceled. * * @param dragPriority of the drag operation * @param block to perform drag in */ suspend fun drag( dragPriority: MutatePriority = MutatePriority.Default, block: suspend DragScope.() -> Unit ) /** * Dispatch drag delta in pixels avoiding all drag related priority mechanisms. * * **NOTE:** unlike [drag], dispatching any delta with this method will bypass scrolling of * any priority. This method will also ignore `reverseDirection` and other parameters set in * [draggable]. * * This method is used internally for low level operations, allowing implementers of * [DraggableState] influence the consumption as suits them, e.g. introduce nested scrolling. * Manually dispatching delta via this method will likely result in a bad user experience, * you must prefer [drag] method over this one. * * @param delta amount of scroll dispatched in the nested drag process */ fun dispatchRawDelta(delta: Float) } /** * Scope used for suspending drag blocks */ interface DragScope { /** * Attempts to drag by [pixels] px. */ fun dragBy(pixels: Float) } /** * Default implementation of [DraggableState] interface that allows to pass a simple action that * will be invoked when the drag occurs. * * This is the simplest way to set up a [draggable] modifier. When constructing this * [DraggableState], you must provide a [onDelta] lambda, which will be invoked whenever * drag happens (by gesture input or a custom [DraggableState.drag] call) with the delta in * pixels. * * If you are creating [DraggableState] in composition, consider using [rememberDraggableState]. * * @param onDelta callback invoked when drag occurs. The callback receives the delta in pixels. */ fun DraggableState(onDelta: (Float) -> Unit): DraggableState = DefaultDraggableState(onDelta) /** * Create and remember default implementation of [DraggableState] interface that allows to pass a * simple action that will be invoked when the drag occurs. * * This is the simplest way to set up a [draggable] modifier. When constructing this * [DraggableState], you must provide a [onDelta] lambda, which will be invoked whenever * drag happens (by gesture input or a custom [DraggableState.drag] call) with the delta in * pixels. * * @param onDelta callback invoked when drag occurs. The callback receives the delta in pixels. */ @Composable fun rememberDraggableState(onDelta: (Float) -> Unit): DraggableState { val onDeltaState = rememberUpdatedState(onDelta) return remember { DraggableState { onDeltaState.value.invoke(it) } } } /** * Configure touch dragging for the UI element in a single [Orientation]. The drag distance * reported to [DraggableState], allowing users to react on the drag delta and update their state. * * The common usecase for this component is when you need to be able to drag something * inside the component on the screen and represent this state via one float value * * If you need to control the whole dragging flow, consider using [pointerInput] instead with the * helper functions like [detectDragGestures]. * * If you are implementing scroll/fling behavior, consider using [scrollable]. * * @sample androidx.compose.foundation.samples.DraggableSample * * @param state [DraggableState] state of the draggable. Defines how drag events will be * interpreted by the user land logic. * @param orientation orientation of the drag * @param enabled whether or not drag is enabled * @param interactionSource [MutableInteractionSource] that will be used to emit * [DragInteraction.Start] when this draggable is being dragged. * @param startDragImmediately when set to true, draggable will start dragging immediately and * prevent other gesture detectors from reacting to "down" events (in order to block composed * press-based gestures). This is intended to allow end users to "catch" an animating widget by * pressing on it. It's useful to set it when value you're dragging is settling / animating. * @param onDragStarted callback that will be invoked when drag is about to start at the starting * position, allowing user to suspend and perform preparation for drag, if desired. This suspend * function is invoked with the draggable scope, allowing for async processing, if desired * @param onDragStopped callback that will be invoked when drag is finished, allowing the * user to react on velocity and process it. This suspend function is invoked with the draggable * scope, allowing for async processing, if desired * @param reverseDirection reverse the direction of the scroll, so top to bottom scroll will * behave like bottom to top and left to right will behave like right to left. */ fun Modifier.draggable( state: DraggableState, orientation: Orientation, enabled: Boolean = true, interactionSource: MutableInteractionSource? = null, startDragImmediately: Boolean = false, onDragStarted: suspend CoroutineScope.(startedPosition: Offset) -> Unit = {}, onDragStopped: suspend CoroutineScope.(velocity: Float) -> Unit = {}, reverseDirection: Boolean = false ): Modifier = draggable( state = state, orientation = orientation, enabled = enabled, interactionSource = interactionSource, startDragImmediately = { startDragImmediately }, onDragStarted = onDragStarted, onDragStopped = { velocity -> onDragStopped(velocity.toFloat(orientation)) }, reverseDirection = reverseDirection, canDrag = { true } ) internal fun Modifier.draggable( state: DraggableState, canDrag: (PointerInputChange) -> Boolean, orientation: Orientation, enabled: Boolean = true, interactionSource: MutableInteractionSource? = null, startDragImmediately: () -> Boolean, onDragStarted: suspend CoroutineScope.(startedPosition: Offset) -> Unit = {}, onDragStopped: suspend CoroutineScope.(velocity: Velocity) -> Unit = {}, reverseDirection: Boolean = false ): Modifier = composed( inspectorInfo = debugInspectorInfo { name = "draggable" properties["canDrag"] = canDrag properties["orientation"] = orientation properties["enabled"] = enabled properties["reverseDirection"] = reverseDirection properties["interactionSource"] = interactionSource properties["startDragImmediately"] = startDragImmediately properties["onDragStarted"] = onDragStarted properties["onDragStopped"] = onDragStopped properties["state"] = state } ) { val draggedInteraction = remember { mutableStateOf<DragInteraction.Start?>(null) } DisposableEffect(interactionSource) { onDispose { draggedInteraction.value?.let { interaction -> interactionSource?.tryEmit(DragInteraction.Cancel(interaction)) draggedInteraction.value = null } } } val channel = remember { Channel<DragEvent>(capacity = Channel.UNLIMITED) } val startImmediatelyState = rememberUpdatedState(startDragImmediately) val canDragState = rememberUpdatedState(canDrag) val dragLogic by rememberUpdatedState( DragLogic(onDragStarted, onDragStopped, draggedInteraction, interactionSource) ) LaunchedEffect(state) { while (isActive) { var event = channel.receive() if (event !is DragStarted) continue with(dragLogic) { processDragStart(event as DragStarted) } try { state.drag(MutatePriority.UserInput) { while (event !is DragStopped && event !is DragCancelled) { (event as? DragDelta)?.let { dragBy(it.delta.toFloat(orientation)) } event = channel.receive() } } with(dragLogic) { if (event is DragStopped) { processDragStop(event as DragStopped) } else if (event is DragCancelled) { processDragCancel() } } } catch (c: CancellationException) { with(dragLogic) { processDragCancel() } } } } Modifier.pointerInput(orientation, enabled, reverseDirection) { if (!enabled) return@pointerInput coroutineScope { try { awaitPointerEventScope { while (isActive) { val velocityTracker = VelocityTracker() awaitDownAndSlop( canDragState, startImmediatelyState, velocityTracker, orientation )?.let { var isDragSuccessful = false try { isDragSuccessful = awaitDrag( it.first, it.second, velocityTracker, channel, reverseDirection, orientation ) } catch (cancellation: CancellationException) { isDragSuccessful = false if (!isActive) throw cancellation } finally { val event = if (isDragSuccessful) { val velocity = velocityTracker.calculateVelocity() DragStopped(velocity * if (reverseDirection) -1f else 1f) } else { DragCancelled } channel.trySend(event) } } } } } catch (exception: CancellationException) { if (!isActive) { throw exception } } } } } private suspend fun AwaitPointerEventScope.awaitDownAndSlop( canDrag: State<(PointerInputChange) -> Boolean>, startDragImmediately: State<() -> Boolean>, velocityTracker: VelocityTracker, orientation: Orientation ): Pair<PointerInputChange, Offset>? { val initialDown = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) return if (!canDrag.value.invoke(initialDown)) { null } else if (startDragImmediately.value.invoke()) { initialDown.consume() velocityTracker.addPointerInputChange(initialDown) // since we start immediately we don't wait for slop and the initial delta is 0 initialDown to Offset.Zero } else { val down = awaitFirstDown(requireUnconsumed = false) velocityTracker.addPointerInputChange(down) var initialDelta = Offset.Zero val postPointerSlop = { event: PointerInputChange, offset: Offset -> velocityTracker.addPointerInputChange(event) event.consume() initialDelta = offset } val afterSlopResult = awaitPointerSlopOrCancellation( down.id, down.type, pointerDirectionConfig = orientation.toPointerDirectionConfig(), onPointerSlopReached = postPointerSlop ) if (afterSlopResult != null) afterSlopResult to initialDelta else null } } private suspend fun AwaitPointerEventScope.awaitDrag( startEvent: PointerInputChange, initialDelta: Offset, velocityTracker: VelocityTracker, channel: SendChannel<DragEvent>, reverseDirection: Boolean, orientation: Orientation ): Boolean { val overSlopOffset = initialDelta val xSign = sign(startEvent.position.x) val ySign = sign(startEvent.position.y) val adjustedStart = startEvent.position - Offset(overSlopOffset.x * xSign, overSlopOffset.y * ySign) channel.trySend(DragStarted(adjustedStart)) channel.trySend(DragDelta(if (reverseDirection) initialDelta * -1f else initialDelta)) val dragTick: (PointerInputChange) -> Unit = { event -> velocityTracker.addPointerInputChange(event) val delta = event.positionChange() event.consume() channel.trySend(DragDelta(if (reverseDirection) delta * -1f else delta)) } return if (orientation == Orientation.Vertical) { verticalDrag(startEvent.id, dragTick) } else { horizontalDrag(startEvent.id, dragTick) } } private class DragLogic( val onDragStarted: suspend CoroutineScope.(startedPosition: Offset) -> Unit, val onDragStopped: suspend CoroutineScope.(velocity: Velocity) -> Unit, val dragStartInteraction: MutableState<DragInteraction.Start?>, val interactionSource: MutableInteractionSource? ) { suspend fun CoroutineScope.processDragStart(event: DragStarted) { dragStartInteraction.value?.let { oldInteraction -> interactionSource?.emit(DragInteraction.Cancel(oldInteraction)) } val interaction = DragInteraction.Start() interactionSource?.emit(interaction) dragStartInteraction.value = interaction onDragStarted.invoke(this, event.startPoint) } suspend fun CoroutineScope.processDragStop(event: DragStopped) { dragStartInteraction.value?.let { interaction -> interactionSource?.emit(DragInteraction.Stop(interaction)) dragStartInteraction.value = null } onDragStopped.invoke(this, event.velocity) } suspend fun CoroutineScope.processDragCancel() { dragStartInteraction.value?.let { interaction -> interactionSource?.emit(DragInteraction.Cancel(interaction)) dragStartInteraction.value = null } onDragStopped.invoke(this, Velocity.Zero) } } private class DefaultDraggableState(val onDelta: (Float) -> Unit) : DraggableState { private val dragScope: DragScope = object : DragScope { override fun dragBy(pixels: Float): Unit = onDelta(pixels) } private val scrollMutex = MutatorMutex() override suspend fun drag( dragPriority: MutatePriority, block: suspend DragScope.() -> Unit ): Unit = coroutineScope { scrollMutex.mutateWith(dragScope, dragPriority, block) } override fun dispatchRawDelta(delta: Float) { return onDelta(delta) } } private sealed class DragEvent { class DragStarted(val startPoint: Offset) : DragEvent() class DragStopped(val velocity: Velocity) : DragEvent() object DragCancelled : DragEvent() class DragDelta(val delta: Offset) : DragEvent() } private fun Offset.toFloat(orientation: Orientation) = if (orientation == Orientation.Vertical) this.y else this.x private fun Velocity.toFloat(orientation: Orientation) = if (orientation == Orientation.Vertical) this.y else this.x
apache-2.0
93716bfc8990a25b4994cc1ca2c6de70
40.897494
98
0.678682
5.268691
false
false
false
false
arkon/LISTEN.moe-Unofficial-Android-App
app/src/main/java/me/echeung/moemoekyun/client/stream/player/LocalStreamPlayer.kt
1
3784
package me.echeung.moemoekyun.client.stream.player import android.content.Context import android.media.AudioManager import android.net.Uri import com.google.android.exoplayer2.C import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.audio.AudioAttributes import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import me.echeung.moemoekyun.client.RadioClient import me.echeung.moemoekyun.util.PreferenceUtil import me.echeung.moemoekyun.util.ext.isCarUiMode import me.echeung.moemoekyun.util.system.AudioManagerUtil import me.echeung.moemoekyun.util.system.NetworkUtil import org.koin.core.KoinComponent import org.koin.core.inject class LocalStreamPlayer(private val context: Context) : StreamPlayer<SimpleExoPlayer>(), KoinComponent { private val preferenceUtil: PreferenceUtil by inject() private var audioManagerUtil: AudioManagerUtil private var audioFocusChangeListener: AudioManager.OnAudioFocusChangeListener private var wasPlayingBeforeLoss: Boolean = false private val focusLock = Any() init { audioFocusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange -> when (focusChange) { AudioManager.AUDIOFOCUS_GAIN -> { unduck() if (wasPlayingBeforeLoss) { play() } } AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> { wasPlayingBeforeLoss = isPlaying if (wasPlayingBeforeLoss && (preferenceUtil.shouldPauseAudioOnLoss() || context.isCarUiMode())) { pause() } } AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> { wasPlayingBeforeLoss = isPlaying if (preferenceUtil.shouldDuckAudio()) { duck() } } } } audioManagerUtil = AudioManagerUtil(context, audioFocusChangeListener) } override fun initPlayer() { if (player == null) { player = SimpleExoPlayer.Builder(context).build() player!!.setWakeMode(C.WAKE_MODE_NETWORK) player!!.addListener(eventListener) player!!.volume = 1f val audioAttributes = AudioAttributes.Builder() .setContentType(C.CONTENT_TYPE_MUSIC) .setUsage(C.USAGE_MEDIA) .build() player!!.audioAttributes = audioAttributes } // Set stream val streamUrl = RadioClient.library.streamUrl if (streamUrl != currentStreamUrl) { val dataSourceFactory = DefaultDataSourceFactory(context, NetworkUtil.userAgent) val streamSource = ProgressiveMediaSource.Factory(dataSourceFactory, DefaultExtractorsFactory()) .createMediaSource(Uri.parse(streamUrl)) player!!.prepare(streamSource) currentStreamUrl = streamUrl } } override fun play() { // Request audio focus for playback val result = audioManagerUtil.requestAudioFocus() synchronized(focusLock) { if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { super.play() } } } override fun stop() { audioManagerUtil.abandonAudioFocus() super.stop() } private fun duck() { player?.audioComponent?.volume = 0.5f } private fun unduck() { player?.audioComponent?.volume = 1f } }
mit
59e15c1a8c48e19cef77882162eddfd6
33.09009
117
0.639006
5.337094
false
false
false
false
pbauerochse/youtrack-worklog-viewer
common-api/src/main/java/de/pbauerochse/worklogviewer/timereport/IssueWithWorkItems.kt
1
1020
package de.pbauerochse.worklogviewer.timereport import java.time.LocalDate /** * Groups an [Issue] with its [WorkItem]s */ class IssueWithWorkItems( val issue: Issue, val workItems: List<WorkItem> ): Comparable<IssueWithWorkItems> { /** * Returns `true` if any of the [WorkItem]s * were created by the current user. */ val hasWorkItemsBelongingToCurrentUser: Boolean get() = workItems.any { it.belongsToCurrentUser } /** * Returns all [WorkItem]s that are for the given LocalDate */ fun getWorkItemsForDate(date: LocalDate): List<WorkItem> { return workItems.filter { it.workDateAtLocalZone.toLocalDate() == date } } /** * Returns the total time in minutes spent on this [Issue], * by summing up the `durationInMinutes` of each [WorkItem] */ val totalTimeInMinutes: Long get() = workItems.sumOf { it.durationInMinutes } override fun compareTo(other: IssueWithWorkItems): Int = issue.compareTo(other.issue) }
mit
5583eb63bd39eee2c1093636fa311144
27.361111
89
0.677451
4.180328
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/model/response/mine_page/FeedbackContent.kt
1
2772
package com.intfocus.template.model.response.mine_page import com.google.gson.annotations.SerializedName import com.intfocus.template.model.response.BaseResult /** * @author liuruilin * @data 2017/12/6 * @describe */ class FeedbackContent: BaseResult() { /** * code : 200 * message : 获取数据列表成功 * current_page : 0 * page_size : 15 * total_page : 15 * data : [{"id":210,"title":"生意人问题反馈","content":"测试","images":["/images/feedback-210-48cb2c983ce84020baf0b8f7893642df.png"],"replies":[{"id":1,"content":"测试","images":["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"],"created_at":"2017-11-17 17:30:30"}],"user_num":"13564379606","app_version":"0.0.2","platform":"ios","platform_version":"iphoneos","progress_state":0,"progress_content":null,"publicly":false,"created_at":"2017-08-15 10:55:49"}] */ var current_page: Int = 0 var page_size: Int = 0 var total_page: Int = 0 @SerializedName("data") var data: Data? = null class Data { /** * id : 210 * title : 生意人问题反馈 * content : 测试 * images : ["/images/feedback-210-48cb2c983ce84020baf0b8f7893642df.png"] * replies : [{"id":1,"content":"测试","images":["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"],"created_at":"2017-11-17 17:30:30"}] * user_num : 13564379606 * app_version : 0.0.2 * platform : ios * platform_version : iphoneos * progress_state : 0 * progress_content : null * publicly : false * created_at : 2017-08-15 10:55:49 */ var id: Int = 0 var title: String? = null var content: String? = null var user_num: String? = null var app_version: String? = null var platform: String? = null var platform_version: String? = null var progress_state: Int = 0 var progress_content: Any? = null var publicly: Boolean = false var created_at: String? = null var images: List<String>? = null var replies: List<Replies>? = null class Replies { /** * id : 1 * content : 测试 * images : ["/images/feedback-reply-d0d653c4ba9e4f01bb4b76d9a1bb389f.png","/images/feedback-reply-65a01382393f4114ae99092370e1191e.png"] * created_at : 2017-11-17 17:30:30 */ var id: Int = 0 var content: String? = null var created_at: String? = null var images: List<String>? = null } } }
gpl-3.0
a6239ca14aaa057cb24632aca3072403
37.140845
525
0.595643
3.254808
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/one/ModeImpl.kt
1
11498
package com.intfocus.template.subject.one import android.util.Log import com.alibaba.fastjson.JSON import com.alibaba.fastjson.JSONReader import com.intfocus.template.SYPApplication.globalContext import com.intfocus.template.model.DaoUtil import com.intfocus.template.model.entity.Report import com.intfocus.template.model.entity.ReportModule import com.intfocus.template.model.gen.ReportDao import com.intfocus.template.subject.model.ReportModelImpl import com.intfocus.template.subject.one.entity.Filter import com.intfocus.template.util.* import com.intfocus.template.util.ApiHelper.clearResponseHeader import rx.Observable import rx.Subscriber import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import java.io.File import java.io.StringReader /** * **************************************************** * @author jameswong * created on: 17/10/25 下午5:11 * e-mail: [email protected] * name: * desc: 模板一 Model 层 * **************************************************** */ class ModeImpl : ReportModelImpl() { private val sqlDistinctPageTitle = "SELECT DISTINCT " + ReportDao.Properties.Page_title.columnName + " FROM " + ReportDao.TABLENAME private var pageTitleList: MutableList<String> = arrayListOf() private var reportDao: ReportDao = DaoUtil.getReportDao() lateinit private var filterObject: Filter private var urlString: String = "" private var jsonFileName: String = "" private var groupId: String = "" private var templateId: String = "" private var reportId: String = "" private var count = 0 companion object { private val TAG = "ModeImpl" private var INSTANCE: ModeImpl? = null private var observable: Subscription? = null private var uuid: String = "" /** * Returns the single instance of this class, creating it if necessary. */ @JvmStatic fun getInstance(): ModeImpl { return INSTANCE ?: ModeImpl() .apply { INSTANCE = this } } /** * Used to force [getInstance] to create a new instance * next time it's called. */ @JvmStatic fun destroyInstance() { unSubscribe() observable?.let { Log.d(TAG, "取消订阅 ::: " + it.isUnsubscribed) } INSTANCE = null } /** * 取消订阅 */ private fun unSubscribe() { observable?.unsubscribe() ?: return } } fun getData(reportId: String, templateId: String, groupId: String, callback: ModeModel.LoadDataCallback) { this.reportId = reportId this.templateId = templateId this.groupId = groupId uuid = reportId + templateId + groupId jsonFileName = String.format("group_%s_template_%s_report_%s.json", groupId, templateId, reportId) urlString = String.format(K.API_REPORT_JSON_ZIP, TempHost.getHost(), groupId, templateId, reportId) LogUtil.d(this@ModeImpl, "报表 url ::: " + urlString) checkReportData(callback) } private fun checkReportData(callback: ModeModel.LoadDataCallback) { observable = Observable.just(uuid) .subscribeOn(Schedulers.io()) .map { when { check(urlString) -> { LogUtil.d(this@ModeImpl, "网络数据") analysisData() } available(uuid) -> { LogUtil.d(this@ModeImpl, "本地数据") queryFilter(uuid) generatePageList() } else -> { LogUtil.d(this@ModeImpl, "报表数据有缓存,数据库无数据") analysisData() } } } .observeOn(AndroidSchedulers.mainThread()) .subscribe(object : Subscriber<List<String>>() { override fun onCompleted() { } override fun onNext(t: List<String>?) { t?.let { callback.onDataLoaded(it, filterObject) } } override fun onError(e: Throwable?) { delete(uuid) clearResponseHeader(urlString) callback.onDataNotAvailable(e!!) } }) } private fun analysisData(): List<String> { LogUtil.d(TAG, "ModeImpl 报表数据开始转为对象") delete(uuid) val response: String? val jsonFilePath = FileUtil.dirPath(globalContext, K.K_CACHED_DIR_NAME, jsonFileName) val dataState = ApiHelper.reportJsonData(globalContext, groupId, templateId, reportId) if (dataState || File(jsonFilePath).exists()) { response = FileUtil.readFile(jsonFilePath) } else { throw Throwable("获取数据失败") } // response = LoadAssetsJsonUtil.getAssetsJsonData("group_165_template_1_report_31.json") val stringReader = StringReader(response) val reader = JSONReader(stringReader) reader.startObject() var report: Report val reportDataList = mutableListOf<Report>() while (reader.hasNext()) { val configKey = reader.readString() when (configKey) { "filter" -> { filterObject = JSON.parseObject(reader.readObject().toString(), Filter::class.java) report = Report() report.id = null report.uuid = uuid report.name = filterObject.display report.index = 0 report.type = "filter" report.page_title = "filter" report.config = JSON.toJSONString(filterObject) reportDataList.add(report) // reportDao.insert(report) } "parts" -> { reader.startArray() var i = 0 while (reader.hasNext()) { val partsItem = JSON.parseObject(reader.readObject().toString(), ReportModule::class.java) report = Report() report.id = null report.uuid = uuid report.name = partsItem.name ?: "name" report.page_title = partsItem.page_title ?: "page_title" report.index = partsItem.control_index ?: i report.type = partsItem.type ?: "unknown_type" report.config = partsItem.config ?: "null_config" // reportDao.insert(report) reportDataList.add(report) i++ } reader.endArray() } } } reader.endObject() reportDao.insertInTx(reportDataList) LogUtil.d(TAG, "ModeImpl 报表数据解析完成") return generatePageList() } /** * 查询筛选条件 * @uuid 报表唯一标识 * @return 筛选实体类 */ private fun queryFilter(uuid: String) { val reportDao = DaoUtil.getReportDao() val filter = reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Type.eq("filter"))).unique() filterObject = JSON.parseObject(filter.config, Filter::class.java) } /** * 查询单个页面的所有报表组件 * @pageId 页面id * @return pageId 对应页面的所有报表组件 */ fun queryPageData(uuid: String, pageId: Int): List<Report> { val reportDao = DaoUtil.getReportDao() return if (null == filterObject.data) { reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Page_title.eq(pageTitleList[pageId]))) .list() } else { reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Page_title.eq(pageTitleList[pageId]), ReportDao.Properties.Name.eq(filterObject!!.display))) .list() } } /** * 查询单个组件的 Config * @index 组件 index 标识 * @pageId 组件所在页面的 id * @return 组件 config */ fun queryModuleConfig(index: Int, pageId: Int): String { val reportDao = DaoUtil.getReportDao() return if (null == filterObject.data) { reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Page_title.eq(pageTitleList[pageId]), ReportDao.Properties.Index.eq(index))) .unique().config } else { reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Page_title.eq(pageTitleList[pageId]), ReportDao.Properties.Name.eq(filterObject.display), ReportDao.Properties.Index.eq(index))) .unique().config } } /** * 更新筛选条件 * @display 当前已选的筛选项 * @callback 数据加载回调 */ fun updateFilter(display: String, callback: ModeModel.LoadDataCallback) { filterObject.display = display val reportDao = DaoUtil.getReportDao() val filter = reportDao.queryBuilder() .where(reportDao.queryBuilder() .and(ReportDao.Properties.Uuid.eq(uuid), ReportDao.Properties.Type.eq("filter"))).unique() filter?.name = display filter?.config = JSON.toJSONString(filterObject) filter?.let { reportDao.update(it) checkReportData(callback) } } /** * 根页签去重 * @reports 当前报表所有数据 * @return 去重后的根页签 */ private fun generatePageList(): List<String> { pageTitleList.clear() var distinctPageTitle = sqlDistinctPageTitle if (null != filterObject.data) { distinctPageTitle = sqlDistinctPageTitle + " WHERE " + ReportDao.Properties.Name.columnName + " = \'" + filterObject.display + "\' AND " + ReportDao.Properties.Uuid.columnName + " = \'" + uuid + "\'" } val cursor = DaoUtil.getDaoSession()!!.database.rawQuery(distinctPageTitle, null) cursor.use { if (it.moveToFirst()) { do { val pageTitle = it.getString(0) if (pageTitle != null && "" != pageTitle && "filter" != pageTitle) { pageTitleList.add(pageTitle) } } while (it.moveToNext()) } } if (pageTitleList.size == 0) { pageTitleList.add("") } return pageTitleList } }
gpl-3.0
ebf9a5f192314d0dcbfe5f6d201a90b6
36.10299
218
0.545308
4.921992
false
false
false
false
sybila/ode-generator
src/test/kotlin/com/github/sybila/ode/generator/zero/OneDimNoParamGeneratorTest.kt
1
18846
package com.github.sybila.ode.generator.zero import com.github.sybila.checker.Transition import com.github.sybila.checker.decreaseProp import com.github.sybila.checker.increaseProp import com.github.sybila.huctl.DirectionFormula import com.github.sybila.ode.generator.ExplicitEvaluable import com.github.sybila.ode.generator.bool.BoolOdeModel import com.github.sybila.ode.model.OdeModel import com.github.sybila.ode.model.Summand import org.junit.Test import kotlin.test.assertEquals /** * This test suit should provide a really basic way to test how * s.s.g behaves in trivial cases of one dimensional models. * * All test cases rely on a one dimensional model with three states and predefined result. **/ class OneDimNoParamGeneratorTest { private val variable = OdeModel.Variable( name = "v1", range = Pair(0.0, 3.0), varPoints = null, thresholds = listOf(0.0, 1.0, 2.0, 3.0), summands = Summand(evaluables = ExplicitEvaluable( 0, mapOf(0.0 to 0.0, 1.0 to 0.0, 2.0 to 0.0, 3.0 to 0.0) )) ) private fun createFragment(vararg values: Double): BoolOdeModel { return BoolOdeModel(OdeModel(variable.copy(equation = listOf(Summand( evaluables = ExplicitEvaluable(0, listOf(0.0, 1.0, 2.0, 3.0).zip(values.toList()).toMap() ) ))))) } private infix fun Int.s(s: Int) = Transition(s, if (this == s) DirectionFormula.Atom.Loop else if (this > s) "v1".decreaseProp() else "v1".increaseProp() , true) private infix fun Int.p(s: Int) = Transition(s, if (this == s) DirectionFormula.Atom.Loop else if (this < s) "v1".decreaseProp() else "v1".increaseProp() , true) private fun BoolOdeModel.checkSuccessors(from: Int, to: List<Int>) { this.run { val s = from.successors(true).asSequence().toSet() assertEquals(to.map { from s it }.toSet(), s) } } private fun BoolOdeModel.checkPredecessors(from: Int, to: List<Int>) { this.run { val s = from.predecessors(true).asSequence().toSet() assertEquals(to.map { from p it }.toSet(), s) } } //ignore symmetric cases, otherwise try as many combinations as possible //No +/- //0..0..0..0 @Test fun case0() { createFragment(0.0, 0.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //One + //+..0..0..0 @Test fun case1() { createFragment(1.0, 0.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //0..+..0..0 @Test fun case2() { createFragment(0.0, 1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //One - //-..0..0..0 @Test fun case3() { createFragment(-1.0, 0.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //0..-..0..0 @Test fun case4() { createFragment(0.0, -1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //Two + //+..+..0..0 @Test fun case5() { createFragment(1.0, 1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf()) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //+..0..+..0 @Test fun case6() { createFragment(1.0, 0.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //+..0..0..+ @Test fun case7() { createFragment(1.0, 0.0, 0.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //0..+..+..0 @Test fun case8() { createFragment(0.0, 1.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //Two - //-..-..0..0 @Test fun case9() { createFragment(-1.0, -1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //-..0..-..0 @Test fun case10() { createFragment(-1.0, 0.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1,2)) checkPredecessors(2, listOf(2)) } } //-..0..0..- @Test fun case11() { createFragment(-1.0, 0.0, 0.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //0..-..-..0 @Test fun case12() { createFragment(0.0, -1.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf(2)) } } //Three + //0..+..+..+ @Test fun case13() { createFragment(0.0, 1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //+..0..+..+ @Test fun case14() { createFragment(1.0, 0.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //Three - //0..-..-..- @Test fun case15() { createFragment(0.0, -1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf()) } } //-..0..-..- @Test fun case16() { createFragment(-1.0, 0.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1,2)) checkPredecessors(2, listOf()) } } //Four + //+..+..+..+ @Test fun case17() { createFragment(1.0, 1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf()) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //Four - //-..-..-..- @Test fun case18() { createFragment(-1.0, -1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf()) } } //One + / One - //+..-..0..0 @Test fun case19() { createFragment(1.0, -1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //+..0..-..0 @Test fun case20() { createFragment(1.0, 0.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1,2)) checkPredecessors(2, listOf(2)) } } //+..0..0..- @Test fun case21() { createFragment(1.0, 0.0, 0.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //-..+..0..0 @Test fun case22() { createFragment(-1.0, 1.0, 0.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //-..0..+..0 @Test fun case23() { createFragment(-1.0, 0.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //0..+..-..0 @Test fun case24() { createFragment(0.0, 1.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf(2)) } } //0..-..+..0 @Test fun case25() { createFragment(0.0, -1.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //One + / Two - //+..0..-..- @Test fun case26() { createFragment(1.0, 0.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1,2)) checkPredecessors(2, listOf()) } } //+..-..0..- @Test fun case27() { createFragment(1.0, -1.0, 0.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //+..-..-..0 @Test fun case28() { createFragment(1.0, -1.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf(2)) } } //0..+..-..- @Test fun case29() { createFragment(0.0, 1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf()) } } //-..+..0..- @Test fun case30() { createFragment(-1.0, 1.0, 0.0, -1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //-..+..-..0 @Test fun case31() { createFragment(-1.0, 1.0, -1.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1,2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf(2)) } } //Two + / One - //-..0..+..+ @Test fun case32() { createFragment(-1.0, 0.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //-..+..0..+ @Test fun case33() { createFragment(-1.0, 1.0, 0.0, 1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1)) checkPredecessors(2, listOf(2)) } } //-..+..+..0 @Test fun case34() { createFragment(-1.0, 1.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //0..-..+..+ @Test fun case35() { createFragment(0.0, -1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //+..-..0..+ @Test fun case36() { createFragment(1.0, -1.0, 0.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(2)) } } //+..-..+..0 @Test fun case37() { createFragment(1.0, -1.0, 1.0, 0.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //Two + / Two - //+..+..-..- @Test fun case38() { createFragment(1.0, 1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf()) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf()) } } //+..-..+..- @Test fun case39() { createFragment(1.0, -1.0, 1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //Three + / One - //-..+..+..+ @Test fun case40() { createFragment(-1.0, 1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0)) checkPredecessors(2, listOf(1,2)) } } //+..-..+..+ @Test fun case41() { createFragment(1.0, -1.0, 1.0, 1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0,1,2)) checkSuccessors(2, listOf(2)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(1)) checkPredecessors(2, listOf(1,2)) } } //Three - / One + //+..-..-..- @Test fun case42() { createFragment(1.0, -1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0)) checkSuccessors(1, listOf(0)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0,1)) checkPredecessors(1, listOf(2)) checkPredecessors(2, listOf()) } } //-..+..-..- @Test fun case43() { createFragment(-1.0, 1.0, -1.0, -1.0).run { checkSuccessors(0, listOf(0,1)) checkSuccessors(1, listOf(1)) checkSuccessors(2, listOf(1)) checkPredecessors(0, listOf(0)) checkPredecessors(1, listOf(0,1,2)) checkPredecessors(2, listOf()) } } }
gpl-3.0
cfefe9359b8a1fb96da33105e7060de4
30.516722
90
0.514645
3.788902
false
true
false
false
Shockah/Godwit
core/src/pl/shockah/godwit/node/SpriteNode.kt
1
2177
package pl.shockah.godwit.node import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.SpriteBatch.* import com.badlogic.gdx.graphics.g2d.TextureRegion import pl.shockah.godwit.GDelegates import pl.shockah.godwit.color.GAlphaColor import pl.shockah.godwit.color.RGBColor import pl.shockah.godwit.geom.MutableVec2 import pl.shockah.godwit.geom.ObservableVec2 import pl.shockah.godwit.geom.Rectangle open class SpriteNode( val region: TextureRegion ) : Node() { constructor(texture: Texture) : this(TextureRegion(texture)) companion object { const val VERTEX_SIZE = 2 + 1 + 2 const val SPRITE_SIZE = 4 * VERTEX_SIZE } val texture: Texture get() = region.texture protected val observableSize = ObservableVec2 { setupPoints() } var size: MutableVec2 by observableSize.asMutableProperty() var color: GAlphaColor by GDelegates.observable(RGBColor.white.alpha()) { -> setupColor() } var usesRectangleTouchShape: Boolean by GDelegates.observable(true) { -> setupRectangleTouchShape() } private val vertices = FloatArray(SPRITE_SIZE) init { size.x = region.regionWidth.toFloat() size.y = region.regionHeight.toFloat() origin.x = size.x * 0.5f origin.y = size.y * 0.5f setupPoints() setupUV() setupColor() } private fun setupUV() { vertices[U1] = region.u vertices[V1] = region.v2 vertices[U2] = region.u vertices[V2] = region.v vertices[U3] = region.u2 vertices[V3] = region.v vertices[U4] = region.u2 vertices[V4] = region.v2 } private fun setupRectangleTouchShape() { if (usesRectangleTouchShape) touchShape = Rectangle(position - origin, size) } private fun setupPoints() { vertices[X1] = 0f vertices[Y1] = 0f vertices[X2] = 0f vertices[Y2] = size.y vertices[X3] = size.x vertices[Y3] = size.y vertices[X4] = size.x vertices[Y4] = 0f setupRectangleTouchShape() } private fun setupColor() { val colorBits = color.gdx.toFloatBits() vertices[C1] = colorBits vertices[C2] = colorBits vertices[C3] = colorBits vertices[C4] = colorBits } override fun drawSelf(renderers: NodeRenderers) { renderers.sprites { draw(texture, vertices, 0, SPRITE_SIZE) } } }
apache-2.0
4279c19ba2d2ac9d5fa7998c0e7164f0
24.034483
102
0.727147
3.105563
false
false
false
false
rhdunn/xquery-intellij-plugin
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/lang/SaxonSyntaxValidator.kt
1
6587
/* * Copyright (C) 2020-2022 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.saxon.lang import com.intellij.psi.PsiElement import com.intellij.psi.util.elementType import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginContextItemFunctionExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginLambdaFunctionExpr import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginParamRef import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginTypeAlias import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.* import uk.co.reecedunn.intellij.plugin.xpath.lexer.XPathTokenType import uk.co.reecedunn.intellij.plugin.xpath.resources.XPathBundle import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxErrorReporter import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidator import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.requires.XpmRequiresAny import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.requires.XpmRequiresProductVersion import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryItemTypeDecl import xqt.platform.intellij.saxon.SaxonXPathTokenProvider import xqt.platform.intellij.xpath.XPathTokenProvider object SaxonSyntaxValidator : XpmSyntaxValidator { override fun validate( element: XpmSyntaxValidationElement, reporter: XpmSyntaxErrorReporter ): Unit = when (element) { is PluginContextItemFunctionExpr -> when (element.conformanceElement.elementType) { XPathTokenProvider.ContextItem, SaxonXPathTokenProvider.ContextFunctionOpen -> reporter.requires(element, SAXON_PE_10) else -> reporter.requires(element, SAXON_PE_9_9_ONLY) } is PluginLambdaFunctionExpr -> reporter.requires(element, SAXON_PE_10) is XPathOtherwiseExpr -> reporter.requires(element, SAXON_PE_10) is PluginParamRef -> reporter.requires(element, SAXON_PE_10) is XPathAnyMapTest -> reporter.requires(element, SAXON_PE_9_4) is XPathSimpleForClause -> when (element.conformanceElement.elementType) { XPathTokenProvider.KMember -> reporter.requires(element, SAXON_PE_10) else -> { } } is XPathFieldDeclaration -> { val recordTest = (element as PsiElement).parent as XpmSyntaxValidationElement when (recordTest.conformanceElement.elementType) { XPathTokenProvider.KRecord -> { } else -> when (element.conformanceElement.elementType) { XPathTokenProvider.QuestionMark, XPathTokenType.ELVIS -> reporter.requires(element, SAXON_PE_9_9) XPathTokenProvider.KAs -> reporter.requires(element, SAXON_PE_10) else -> { } } } } is XPathRecordTest -> when (element.conformanceElement.elementType) { XPathTokenProvider.KRecord -> { } else -> when (element.isExtensible) { true -> reporter.requires(element, SAXON_PE_9_9) else -> reporter.requires(element, SAXON_PE_9_8) } } is PluginTypeAlias -> when (element.conformanceElement.elementType) { SaxonXPathTokenProvider.TypeAlias -> reporter.requires(element, SAXON_PE_9_8_TO_9_9) // ~T else -> reporter.requires(element, SAXON_PE_10) // type(T) } is XQueryItemTypeDecl -> when (element.conformanceElement.elementType) { XPathTokenProvider.KType -> reporter.requires(element, SAXON_PE_9_8) else -> { } } is XPathLocalUnionType -> reporter.requires(element, SAXON_PE_9_8) is XPathAndExpr -> when (element.conformanceElement.elementType) { SaxonXPathTokenProvider.KAndAlso -> reporter.requires(element, SAXON_PE_9_9) else -> { } } is XPathAttributeTest -> when (element.conformanceElement) { is XPathWildcard -> { val name = XPathBundle.message("construct.wildcard-attribute-test") reporter.requires(element, SAXON_PE_10, name) } else -> { } } is XPathElementTest -> when (element.conformanceElement) { is XPathWildcard -> { val name = XPathBundle.message("construct.wildcard-element-test") reporter.requires(element, SAXON_PE_10, name) } else -> { } } is XPathOrExpr -> when (element.conformanceElement.elementType) { SaxonXPathTokenProvider.KOrElse -> reporter.requires(element, SAXON_PE_9_9) else -> { } } else -> { } } private val SAXON_PE_9_4 = XpmRequiresAny( XpmRequiresProductVersion.since(SaxonPE.VERSION_9_4), XpmRequiresProductVersion.since(SaxonEE.VERSION_9_4) ) private val SAXON_PE_9_8 = XpmRequiresAny( XpmRequiresProductVersion.since(SaxonPE.VERSION_9_8), XpmRequiresProductVersion.since(SaxonEE.VERSION_9_8) ) private val SAXON_PE_9_8_TO_9_9 = XpmRequiresAny( XpmRequiresProductVersion.between(SaxonPE.VERSION_9_8, SaxonPE.VERSION_9_9), XpmRequiresProductVersion.between(SaxonEE.VERSION_9_8, SaxonEE.VERSION_9_9) ) private val SAXON_PE_9_9 = XpmRequiresAny( XpmRequiresProductVersion.since(SaxonPE.VERSION_9_9), XpmRequiresProductVersion.since(SaxonEE.VERSION_9_9) ) private val SAXON_PE_9_9_ONLY = XpmRequiresAny( XpmRequiresProductVersion.between(SaxonPE.VERSION_9_9, SaxonPE.VERSION_9_9), XpmRequiresProductVersion.between(SaxonEE.VERSION_9_9, SaxonEE.VERSION_9_9) ) private val SAXON_PE_10 = XpmRequiresAny( XpmRequiresProductVersion.since(SaxonPE.VERSION_10_0), XpmRequiresProductVersion.since(SaxonEE.VERSION_10_0) ) }
apache-2.0
221b0bfa418ecdfa76dc6ec33698bad8
44.743056
130
0.676332
4.441672
false
true
false
false
sn3d/nomic
nomic-core/src/test/kotlin/nomic/core/TopologySortTest.kt
1
2567
/* * Copyright 2017 [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 nomic.core import org.assertj.core.api.Assertions.assertThat import org.junit.Test /** * @author [email protected] */ class TopologySortTest { @Test fun `test of simple topology sort`() { val graph = listOf<Node<String>>( Node("A"), Node("B", mutableListOf("A")), Node("C", mutableListOf("A")), Node("E", mutableListOf("D")), Node("D", mutableListOf("B", "C")) ) val sortedGraph = graph.topologySort() val sortedGraphStr = sortedGraph.toString() assertThat(sortedGraphStr) .isEqualTo("[A, B, C, D, E]") } /** * test of graph: https://en.wikipedia.org/wiki/File:Directed_acyclic_graph_2.svg */ @Test fun `test of topology sort over advanced graph`() { val graph = listOf<Node<String>>( Node("5"), Node("7"), Node("3"), Node("11", mutableListOf("5", "7")), Node("8", mutableListOf("7", "3")), Node("2", mutableListOf("11")), Node("9", mutableListOf("11", "8")), Node("10", mutableListOf("11", "3")) ) val sortedGraph = graph.topologySort() val sortedGraphStr = sortedGraph.toString() assertThat(sortedGraphStr) .isEqualTo("[5, 7, 3, 11, 8, 2, 10, 9]") } /** * test of more complicated graph with multiple starts (https://www.youtube.com/watch?v=tFpvX8T0-Pw) */ @Test fun `test of topology sort over advanced graph with two starts`() { val graph = listOf<Node<String>>( Node("A", mutableListOf("B")), Node("B", mutableListOf("E")), Node("C", mutableListOf("B")), Node("D", mutableListOf("A", "F")), Node("E", mutableListOf()), Node("F", mutableListOf("E")), Node("G", mutableListOf("C", "D", "J")), Node("H", mutableListOf("F", "I", "K")), Node("I", mutableListOf()), Node("J", mutableListOf("H")), Node("K", mutableListOf("I")) ) val sortedGraph = graph.topologySort() val sortedGraphStr = sortedGraph.toString() assertThat(sortedGraphStr) .isEqualTo("[E, I, B, F, K, A, C, H, D, J, G]") } }
apache-2.0
f1e5190293573820670038a5a43edcbd
24.929293
101
0.643553
3.320828
false
true
false
false
google/filament
android/samples/sample-lit-cube/src/main/java/com/google/android/filament/litcube/MainActivity.kt
1
17180
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.filament.litcube import android.animation.ValueAnimator import android.app.Activity import android.opengl.Matrix import android.os.Bundle import android.view.Choreographer import android.view.Surface import android.view.SurfaceView import android.view.animation.LinearInterpolator import com.google.android.filament.* import com.google.android.filament.RenderableManager.* import com.google.android.filament.VertexBuffer.* import com.google.android.filament.android.DisplayHelper import com.google.android.filament.android.UiHelper import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.channels.Channels class MainActivity : Activity() { // Make sure to initialize Filament first // This loads the JNI library needed by most API calls companion object { init { Filament.init() } } // The View we want to render into private lateinit var surfaceView: SurfaceView // UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture private lateinit var uiHelper: UiHelper // DisplayHelper is provided by Filament to manage the display private lateinit var displayHelper: DisplayHelper // Choreographer is used to schedule new frames private lateinit var choreographer: Choreographer // Engine creates and destroys Filament resources // Each engine must be accessed from a single thread of your choosing // Resources cannot be shared across engines private lateinit var engine: Engine // A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.) private lateinit var renderer: Renderer // A scene holds all the renderable, lights, etc. to be drawn private lateinit var scene: Scene // A view defines a viewport, a scene and a camera for rendering private lateinit var view: View // Should be pretty obvious :) private lateinit var camera: Camera private lateinit var material: Material private lateinit var materialInstance: MaterialInstance private lateinit var vertexBuffer: VertexBuffer private lateinit var indexBuffer: IndexBuffer // Filament entity representing a renderable object @Entity private var renderable = 0 @Entity private var light = 0 // A swap chain is Filament's representation of a surface private var swapChain: SwapChain? = null // Performs the rendering and schedules new frames private val frameScheduler = FrameCallback() private val animator = ValueAnimator.ofFloat(0.0f, 360.0f) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) surfaceView = SurfaceView(this) setContentView(surfaceView) choreographer = Choreographer.getInstance() displayHelper = DisplayHelper(this) setupSurfaceView() setupFilament() setupView() setupScene() } private fun setupSurfaceView() { uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK) uiHelper.renderCallback = SurfaceCallback() // NOTE: To choose a specific rendering resolution, add the following line: // uiHelper.setDesiredSize(1280, 720) uiHelper.attachTo(surfaceView) } private fun setupFilament() { engine = Engine.create() renderer = engine.createRenderer() scene = engine.createScene() view = engine.createView() camera = engine.createCamera(engine.entityManager.create()) } private fun setupView() { scene.skybox = Skybox.Builder().color(0.035f, 0.035f, 0.035f, 1.0f).build(engine) // NOTE: Try to disable post-processing (tone-mapping, etc.) to see the difference // view.isPostProcessingEnabled = false // Tell the view which camera we want to use view.camera = camera // Tell the view which scene we want to render view.scene = scene } private fun setupScene() { loadMaterial() setupMaterial() createMesh() // To create a renderable we first create a generic entity renderable = EntityManager.get().create() // We then create a renderable component on that entity // A renderable is made of several primitives; in this case we declare only 1 // If we wanted each face of the cube to have a different material, we could // declare 6 primitives (1 per face) and give each of them a different material // instance, setup with different parameters RenderableManager.Builder(1) // Overall bounding box of the renderable .boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f)) // Sets the mesh data of the first primitive, 6 faces of 6 indices each .geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 6 * 6) // Sets the material of the first primitive .material(0, materialInstance) .build(engine, renderable) // Add the entity to the scene to render it scene.addEntity(renderable) // We now need a light, let's create a directional light light = EntityManager.get().create() // Create a color from a temperature (5,500K) val (r, g, b) = Colors.cct(5_500.0f) LightManager.Builder(LightManager.Type.DIRECTIONAL) .color(r, g, b) // Intensity of the sun in lux on a clear day .intensity(110_000.0f) // The direction is normalized on our behalf .direction(0.0f, -0.5f, -1.0f) .castShadows(true) .build(engine, light) // Add the entity to the scene to light it scene.addEntity(light) // Set the exposure on the camera, this exposure follows the sunny f/16 rule // Since we've defined a light that has the same intensity as the sun, it // guarantees a proper exposure camera.setExposure(16.0f, 1.0f / 125.0f, 100.0f) // Move the camera back to see the object camera.lookAt(0.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0) startAnimation() } private fun loadMaterial() { readUncompressedAsset("materials/lit.filamat").let { material = Material.Builder().payload(it, it.remaining()).build(engine) } } private fun setupMaterial() { // Create an instance of the material to set different parameters on it materialInstance = material.createInstance() // Specify that our color is in sRGB so the conversion to linear // is done automatically for us. If you already have a linear color // you can pass it directly, or use Colors.RgbType.LINEAR materialInstance.setParameter("baseColor", Colors.RgbType.SRGB, 1.0f, 0.85f, 0.57f) // The default value is always 0, but it doesn't hurt to be clear about our intentions // Here we are defining a dielectric material materialInstance.setParameter("metallic", 0.0f) // We increase the roughness to spread the specular highlights materialInstance.setParameter("roughness", 0.3f) } private fun createMesh() { val floatSize = 4 val shortSize = 2 // A vertex is a position + a tangent frame: // 3 floats for XYZ position, 4 floats for normal+tangents (quaternion) val vertexSize = 3 * floatSize + 4 * floatSize // Define a vertex and a function to put a vertex in a ByteBuffer @Suppress("ArrayInDataClass") data class Vertex(val x: Float, val y: Float, val z: Float, val tangents: FloatArray) fun ByteBuffer.put(v: Vertex): ByteBuffer { putFloat(v.x) putFloat(v.y) putFloat(v.z) v.tangents.forEach { putFloat(it) } return this } // 6 faces, 4 vertices per face val vertexCount = 6 * 4 // Create tangent frames, one per face val tfPX = FloatArray(4) val tfNX = FloatArray(4) val tfPY = FloatArray(4) val tfNY = FloatArray(4) val tfPZ = FloatArray(4) val tfNZ = FloatArray(4) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.0f, tfPX) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -1.0f, -1.0f, 0.0f, 0.0f, tfNX) MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, tfPY) MathUtils.packTangentFrame(-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 0.0f, tfNY) MathUtils.packTangentFrame( 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, tfPZ) MathUtils.packTangentFrame( 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, tfNZ) val vertexData = ByteBuffer.allocate(vertexCount * vertexSize) // It is important to respect the native byte order .order(ByteOrder.nativeOrder()) // Face -Z .put(Vertex(-1.0f, -1.0f, -1.0f, tfNZ)) .put(Vertex(-1.0f, 1.0f, -1.0f, tfNZ)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfNZ)) .put(Vertex( 1.0f, -1.0f, -1.0f, tfNZ)) // Face +X .put(Vertex( 1.0f, -1.0f, -1.0f, tfPX)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfPX)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPX)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfPX)) // Face +Z .put(Vertex(-1.0f, -1.0f, 1.0f, tfPZ)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfPZ)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPZ)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfPZ)) // Face -X .put(Vertex(-1.0f, -1.0f, 1.0f, tfNX)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfNX)) .put(Vertex(-1.0f, 1.0f, -1.0f, tfNX)) .put(Vertex(-1.0f, -1.0f, -1.0f, tfNX)) // Face -Y .put(Vertex(-1.0f, -1.0f, 1.0f, tfNY)) .put(Vertex(-1.0f, -1.0f, -1.0f, tfNY)) .put(Vertex( 1.0f, -1.0f, -1.0f, tfNY)) .put(Vertex( 1.0f, -1.0f, 1.0f, tfNY)) // Face +Y .put(Vertex(-1.0f, 1.0f, -1.0f, tfPY)) .put(Vertex(-1.0f, 1.0f, 1.0f, tfPY)) .put(Vertex( 1.0f, 1.0f, 1.0f, tfPY)) .put(Vertex( 1.0f, 1.0f, -1.0f, tfPY)) // Make sure the cursor is pointing in the right place in the byte buffer .flip() // Declare the layout of our mesh vertexBuffer = VertexBuffer.Builder() .bufferCount(1) .vertexCount(vertexCount) // Because we interleave position and color data we must specify offset and stride // We could use de-interleaved data by declaring two buffers and giving each // attribute a different buffer index .attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize) .attribute(VertexAttribute.TANGENTS, 0, AttributeType.FLOAT4, 3 * floatSize, vertexSize) .build(engine) // Feed the vertex data to the mesh // We only set 1 buffer because the data is interleaved vertexBuffer.setBufferAt(engine, 0, vertexData) // Create the indices val indexData = ByteBuffer.allocate(6 * 2 * 3 * shortSize) .order(ByteOrder.nativeOrder()) repeat(6) { val i = (it * 4).toShort() indexData .putShort(i).putShort((i + 1).toShort()).putShort((i + 2).toShort()) .putShort(i).putShort((i + 2).toShort()).putShort((i + 3).toShort()) } indexData.flip() // 6 faces, 2 triangles per face, indexBuffer = IndexBuffer.Builder() .indexCount(vertexCount * 2) .bufferType(IndexBuffer.Builder.IndexType.USHORT) .build(engine) indexBuffer.setBuffer(engine, indexData) } private fun startAnimation() { // Animate the triangle animator.interpolator = LinearInterpolator() animator.duration = 6000 animator.repeatMode = ValueAnimator.RESTART animator.repeatCount = ValueAnimator.INFINITE animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { val transformMatrix = FloatArray(16) override fun onAnimationUpdate(a: ValueAnimator) { Matrix.setRotateM(transformMatrix, 0, a.animatedValue as Float, 0.0f, 1.0f, 0.0f) val tcm = engine.transformManager tcm.setTransform(tcm.getInstance(renderable), transformMatrix) } }) animator.start() } override fun onResume() { super.onResume() choreographer.postFrameCallback(frameScheduler) animator.start() } override fun onPause() { super.onPause() choreographer.removeFrameCallback(frameScheduler) animator.cancel() } override fun onDestroy() { super.onDestroy() // Stop the animation and any pending frame choreographer.removeFrameCallback(frameScheduler) animator.cancel(); // Always detach the surface before destroying the engine uiHelper.detach() // Cleanup all resources engine.destroyEntity(light) engine.destroyEntity(renderable) engine.destroyRenderer(renderer) engine.destroyVertexBuffer(vertexBuffer) engine.destroyIndexBuffer(indexBuffer) engine.destroyMaterialInstance(materialInstance) engine.destroyMaterial(material) engine.destroyView(view) engine.destroyScene(scene) engine.destroyCameraComponent(camera.entity) // Engine.destroyEntity() destroys Filament related resources only // (components), not the entity itself val entityManager = EntityManager.get() entityManager.destroy(light) entityManager.destroy(renderable) entityManager.destroy(camera.entity) // Destroying the engine will free up any resource you may have forgotten // to destroy, but it's recommended to do the cleanup properly engine.destroy() } inner class FrameCallback : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { // Schedule the next frame choreographer.postFrameCallback(this) // This check guarantees that we have a swap chain if (uiHelper.isReadyToRender) { // If beginFrame() returns false you should skip the frame // This means you are sending frames too quickly to the GPU if (renderer.beginFrame(swapChain!!, frameTimeNanos)) { renderer.render(view) renderer.endFrame() } } } } inner class SurfaceCallback : UiHelper.RendererCallback { override fun onNativeWindowChanged(surface: Surface) { swapChain?.let { engine.destroySwapChain(it) } swapChain = engine.createSwapChain(surface) displayHelper.attach(renderer, surfaceView.display) } override fun onDetachedFromSurface() { displayHelper.detach() swapChain?.let { engine.destroySwapChain(it) // Required to ensure we don't return before Filament is done executing the // destroySwapChain command, otherwise Android might destroy the Surface // too early engine.flushAndWait() swapChain = null } } override fun onResized(width: Int, height: Int) { val aspect = width.toDouble() / height.toDouble() camera.setProjection(45.0, aspect, 0.1, 20.0, Camera.Fov.VERTICAL) view.viewport = Viewport(0, 0, width, height) } } private fun readUncompressedAsset(assetName: String): ByteBuffer { assets.openFd(assetName).use { fd -> val input = fd.createInputStream() val dst = ByteBuffer.allocate(fd.length.toInt()) val src = Channels.newChannel(input) src.read(dst) src.close() return dst.apply { rewind() } } } }
apache-2.0
73e0253d8aec24786f9c6494e1c1ec9b
38.860789
104
0.613446
4.228403
false
false
false
false
exponentjs/exponent
packages/expo-dev-menu/android/src/main/java/expo/modules/devmenu/react/DevMenuPackagerCommandHandlersSwapper.kt
2
4484
package expo.modules.devmenu.react import android.util.Log import com.facebook.react.ReactInstanceManager import com.facebook.react.devsupport.DevServerHelper import com.facebook.react.devsupport.DevSupportManagerBase import com.facebook.react.devsupport.interfaces.DevSupportManager import com.facebook.react.packagerconnection.JSPackagerClient import com.facebook.react.packagerconnection.RequestHandler import expo.modules.devmenu.DevMenuManager import expo.modules.devmenu.helpers.getPrivateDeclaredFieldValue import expo.modules.devmenu.helpers.setPrivateDeclaredFieldValue import kotlinx.coroutines.delay import kotlinx.coroutines.launch class DevMenuPackagerCommandHandlersSwapper { fun swapPackagerCommandHandlers( reactInstanceManager: ReactInstanceManager, handlers: Map<String, RequestHandler> ) { try { val devSupportManager: DevSupportManager = ReactInstanceManager::class.java.getPrivateDeclaredFieldValue( "mDevSupportManager", reactInstanceManager ) // We don't want to add handlers into `DisabledDevSupportManager` or other custom classes if (devSupportManager !is DevSupportManagerBase) { return } val currentCommandHandlers: Map<String, RequestHandler>? = DevSupportManagerBase::class.java.getPrivateDeclaredFieldValue( "mCustomPackagerCommandHandlers", devSupportManager ) val newCommandHandlers = currentCommandHandlers?.toMutableMap() ?: mutableMapOf() newCommandHandlers.putAll(handlers) DevSupportManagerBase::class.java.setPrivateDeclaredFieldValue( "mCustomPackagerCommandHandlers", devSupportManager, newCommandHandlers ) swapCurrentCommandHandlers(reactInstanceManager, handlers) } catch (e: Exception) { Log.w("DevMenu", "Couldn't add packager command handlers to current client: ${e.message}", e) } } /** * No matter where we swap the command handlers there always will be an instance of [JSPackagerClient] * that was created before swapping. The only place where you can add custom handlers, * is in the [com.facebook.react.ReactInstanceManagerBuilder.setCustomPackagerCommandHandlers]. * Unfortunately, we don't have access to this function. What's worst, we can't even add a new installation step. * The builder is hidden from the user. * * So we need to swap command handlers in the current [JSPackagerClient] instance. * However, we can't just use the reflection API to access handlers variable inside that object, * cause we don't know if it is available. [JSPackagerClient] is created on background thread (see [DevServerHelper.openPackagerConnection]). * The final solution is to spin a background task that monitors if the client is present. */ private fun swapCurrentCommandHandlers( reactInstanceManager: ReactInstanceManager, handlers: Map<String, RequestHandler> ) { DevMenuManager.coroutineScope.launch { try { while (true) { val devSupportManager: DevSupportManagerBase = ReactInstanceManager::class.java.getPrivateDeclaredFieldValue( "mDevSupportManager", reactInstanceManager ) val devServerHelper: DevServerHelper = DevSupportManagerBase::class.java.getPrivateDeclaredFieldValue( "mDevServerHelper", devSupportManager ) val jsPackagerClient: JSPackagerClient? = DevServerHelper::class.java.getPrivateDeclaredFieldValue( "mPackagerClient", devServerHelper ) if (jsPackagerClient != null) { val currentCommandHandlers: Map<String, RequestHandler>? = JSPackagerClient::class.java.getPrivateDeclaredFieldValue( "mRequestHandlers", jsPackagerClient ) val newCommandHandlers = currentCommandHandlers?.toMutableMap() ?: mutableMapOf() newCommandHandlers.putAll(handlers) JSPackagerClient::class.java.setPrivateDeclaredFieldValue( "mRequestHandlers", jsPackagerClient, newCommandHandlers ) return@launch } delay(50) } } catch (e: Exception) { Log.w("DevMenu", "Couldn't add packager command handlers to current client: ${e.message}", e) } } } }
bsd-3-clause
f3b912cf43b0391d0c08e15f33055b04
37.655172
143
0.701383
5.675949
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/command/insulin/program/BasalInsulinProgramElement.kt
1
1570
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.insulin.program.util.ProgramBasalUtil import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.Encodable import java.io.Serializable import java.nio.ByteBuffer open class BasalInsulinProgramElement( val startSlotIndex: Byte, val numberOfSlots: Byte, val totalTenthPulses: Short ) : Encodable, Serializable { override val encoded: ByteArray get() = ByteBuffer.allocate(6) .putShort(totalTenthPulses) .putInt(if (totalTenthPulses.toInt() == 0) Int.MIN_VALUE or delayBetweenTenthPulsesInUsec else delayBetweenTenthPulsesInUsec) .array() val durationInSeconds: Short get() = (numberOfSlots * 1800).toShort() val delayBetweenTenthPulsesInUsec: Int get() = if (totalTenthPulses.toInt() == 0) { ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT } else (ProgramBasalUtil.MAX_DELAY_BETWEEN_TENTH_PULSES_IN_USEC_AND_USECS_IN_BASAL_SLOT.toLong() * numberOfSlots / totalTenthPulses.toDouble()).toInt() override fun toString(): String { return "LongInsulinProgramElement{" + "startSlotIndex=" + startSlotIndex + ", numberOfSlots=" + numberOfSlots + ", totalTenthPulses=" + totalTenthPulses + ", delayBetweenTenthPulsesInUsec=" + delayBetweenTenthPulsesInUsec + '}' } }
agpl-3.0
b61a8dc1acdf92dbb426bca8b30f0409
45.176471
159
0.710828
4.325069
false
false
false
false