repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jovr/imgui
core/src/main/kotlin/imgui/api/widgetsInputWithKeyboard.kt
2
12721
package imgui.api import gli_.hasnt import glm_.func.common.max import glm_.vec2.Vec2 import glm_.vec2.Vec2i import glm_.vec3.Vec3 import glm_.vec3.Vec3i import glm_.vec4.Vec4 import glm_.vec4.Vec4i import imgui.* import imgui.ImGui.beginGroup import imgui.ImGui.buttonEx import imgui.ImGui.calcItemWidth import imgui.ImGui.currentWindow import imgui.ImGui.dataTypeApplyOp import imgui.ImGui.dataTypeApplyOpFromText import imgui.ImGui.endGroup import imgui.ImGui.findRenderedTextEnd import imgui.ImGui.format import imgui.ImGui.frameHeight import imgui.ImGui.inputTextEx import imgui.ImGui.io import imgui.ImGui.markItemEdited import imgui.ImGui.popID import imgui.ImGui.popItemWidth import imgui.ImGui.pushID import imgui.ImGui.pushMultiItemsWidths import imgui.ImGui.sameLine import imgui.ImGui.setNextItemWidth import imgui.ImGui.style import imgui.ImGui.textEx import imgui.internal.sections.or import kool.getValue import kool.setValue import kotlin.reflect.KMutableProperty0 import imgui.InputTextFlag as Itf import imgui.internal.sections.ButtonFlag as Bf @Suppress("UNCHECKED_CAST") /** Widgets: Input with Keyboard * - If you want to use InputText() with std::string or any custom dynamic string type, see cpp/imgui_stdlib.h and comments in imgui_demo.cpp. * - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc. */ interface widgetsInputWithKeyboard { /** String overload */ fun inputText(label: String, buf: String, flags: InputTextFlags = Itf.None.i, callback: InputTextCallback? = null, userData: Any? = null): Boolean = inputText(label, buf.toByteArray(), flags, callback, userData) fun inputText(label: String, buf: ByteArray, flags: InputTextFlags = Itf.None.i, callback: InputTextCallback? = null, userData: Any? = null): Boolean { assert(flags hasnt Itf._Multiline) { "call InputTextMultiline()" } return inputTextEx(label, null, buf, Vec2(), flags, callback, userData) } /** String overload */ fun inputTextMultiline(label: String, buf: String, size: Vec2 = Vec2(), flags: InputTextFlags = Itf.None.i, callback: InputTextCallback? = null, userData: Any? = null): Boolean = inputTextEx(label, null, buf.toByteArray(), size, flags or Itf._Multiline, callback, userData) fun inputTextMultiline(label: String, buf: ByteArray, size: Vec2 = Vec2(), flags: InputTextFlags = Itf.None.i, callback: InputTextCallback? = null, userData: Any? = null): Boolean = inputTextEx(label, null, buf, size, flags or Itf._Multiline, callback, userData) /** String overload */ fun inputTextWithHint(label: String, hint: String, buf: String, flags: InputTextFlags = Itf.None.i, callback: InputTextCallback? = null, userData: Any? = null): Boolean = inputTextWithHint(label, hint, buf.toByteArray(), flags) fun inputTextWithHint(label: String, hint: String, buf: ByteArray, flags: InputTextFlags = 0, callback: InputTextCallback? = null, userData: Any? = null): Boolean { assert(flags hasnt Itf._Multiline) { "call InputTextMultiline()" } return inputTextEx(label, hint, buf, Vec2(), flags, callback, userData) } fun inputFloat(label: String, v: FloatArray, step: Float = 0f, stepFast: Float = 0f, format: String = "%.3f", flags: InputTextFlags = Itf.None.i): Boolean = inputFloat(label, v, 0, step, stepFast, format, flags) fun inputFloat(label: String, v: FloatArray, ptr: Int = 0, step: Float = 0f, stepFast: Float = 0f, format: String = "%.3f", flags: InputTextFlags = Itf.None.i): Boolean = withFloat(v, ptr) { inputFloat(label, it, step, stepFast, format, flags) } fun inputFloat(label: String, v: KMutableProperty0<Float>, step: Float = 0f, stepFast: Float = 0f, format: String = "%.3f", flags_: InputTextFlags = Itf.None.i): Boolean { val flags = flags_ or Itf.CharsScientific return inputScalar(label, DataType.Float, v, step.takeIf { it > 0f }, stepFast.takeIf { it > 0f }, format, flags) } fun inputFloat2(label: String, v: FloatArray, format: String = "%.3f", flags: InputTextFlags = Itf.None.i): Boolean = inputScalarN<Float>(label, DataType.Float, v, 2, null, null, format, flags) fun inputVec2(label: String, v: Vec2, format: String = "%.3f", flags: InputTextFlags = Itf.None.i): Boolean = inputScalarN<Float>(label, DataType.Float, v to _fa, Vec2.length, null, null, format, flags) .also { v put _fa } fun inputFloat3(label: String, v: FloatArray, format: String = "%.3f", flags: InputTextFlags = Itf.None.i): Boolean = inputScalarN<Float>(label, DataType.Float, v, 3, null, null, format, flags) fun inputVec3(label: String, v: Vec3, format: String = "%.3f", flags: InputTextFlags = Itf.None.i): Boolean = inputScalarN<Float>(label, DataType.Float, v to _fa, Vec3.length, null, null, format, flags) .also { v put _fa } fun inputFloat4(label: String, v: FloatArray, format: String = "%.3f", flags: InputTextFlags = Itf.None.i): Boolean = inputScalarN<Float>(label, DataType.Float, v, 4, null, null, format, flags) fun inputVec4(label: String, v: Vec4, format: String = "%.3f", flags: InputTextFlags = Itf.None.i): Boolean = inputScalarN<Float>(label, DataType.Float, v to _fa, Vec4.length, null, null, format, flags) .also { v put _fa } fun inputInt(label: String, v: KMutableProperty0<Int>, step: Int = 1, stepFast: Int = 100, flags: InputTextFlags = 0): Boolean { /* Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use inputText() to parse your own data, if you want to handle prefixes. */ val format = if (flags has Itf.CharsHexadecimal) "%08X" else "%d" return inputScalar(label, DataType.Int, v, step.takeIf { it > 0f }, stepFast.takeIf { it > 0f }, format, flags) } fun inputInt2(label: String, v: IntArray, flags: InputTextFlags = 0): Boolean = inputScalarN<Int>(label, DataType.Int, v, 2, null, null, "%d", flags) fun inputVec2i(label: String, v: Vec2i, flags: InputTextFlags = 0): Boolean = inputScalarN<Int>(label, DataType.Int, v to _ia, Vec2i.length, null, null, "%d", flags) .also { v put _ia } fun inputInt3(label: String, v: IntArray, flags: InputTextFlags = 0): Boolean = inputScalarN<Int>(label, DataType.Int, v, 3, null, null, "%d", flags) fun inputVec3i(label: String, v: Vec3i, flags: InputTextFlags = 0): Boolean = inputScalarN<Int>(label, DataType.Int, v to _ia, Vec3i.length, null, null, "%d", flags) .also { v put _ia } fun inputInt4(label: String, v: IntArray, flags: InputTextFlags = 0): Boolean = inputScalarN<Int>(label, DataType.Int, v, 4, null, null, "%d", flags) fun inputVec4i(label: String, v: Vec4i, flags: InputTextFlags = 0): Boolean = inputScalarN<Int>(label, DataType.Int, v to _ia, Vec4i.length, null, null, "%d", flags) .also { v put _ia } fun inputDouble(label: String, v: KMutableProperty0<Double>, step: Double = 0.0, stepFast: Double = 0.0, format: String? = "%.6f", flags_: InputTextFlags = Itf.None.i): Boolean { val flags = flags_ or Itf.CharsScientific /* Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1 */ return inputScalar(label, DataType.Double, v, step.takeIf { it > 0.0 }, stepFast.takeIf { it > 0.0 }, format, flags) } fun <N> inputScalar(label: String, dataType: DataType, pData: IntArray, step: Int?, stepFast: Int?, format: String? = null, flags: InputTextFlags = Itf.None.i) : Boolean where N : Number, N : Comparable<N> = withInt(pData) { inputScalar(label, dataType, it, step, stepFast, format, flags) } fun <N> inputScalar(label: String, dataType: DataType, pData: KMutableProperty0<N>, step: N? = null, stepFast: N? = null, format_: String? = null, flags_: InputTextFlags = Itf.None.i) : Boolean where N : Number, N : Comparable<N> { var data by pData val window = currentWindow if (window.skipItems) return false val format = when (format_) { null -> when (dataType) { DataType.Float, DataType.Double -> "%f" else -> "%d" } else -> format_ } val buf = pData.format(dataType, format/*, 64*/).toByteArray(64) var valueChanged = false var flags = flags_ if (flags hasnt (Itf.CharsHexadecimal or Itf.CharsScientific)) flags = flags or Itf.CharsDecimal flags = flags or Itf.AutoSelectAll flags = flags or Itf._NoMarkEdited // We call MarkItemEdited() ourselves by comparing the actual data rather than the string. if (step != null) { val buttonSize = frameHeight beginGroup() // The only purpose of the group here is to allow the caller to query item data e.g. IsItemActive() pushID(label) setNextItemWidth(1f max (calcItemWidth() - (buttonSize + style.itemInnerSpacing.x) * 2)) if (inputText("", buf, flags)) // PushId(label) + "" gives us the expected ID from outside point of view valueChanged = dataTypeApplyOpFromText(buf.cStr, g.inputTextState.initialTextA, dataType, pData, format) // Step buttons val backupFramePadding = Vec2(style.framePadding) style.framePadding.x = style.framePadding.y var buttonFlags = Bf.Repeat or Bf.DontClosePopups if (flags has Itf.ReadOnly) buttonFlags = buttonFlags or Bf.Disabled sameLine(0f, style.itemInnerSpacing.x) if (buttonEx("-", Vec2(buttonSize), buttonFlags)) { data = dataTypeApplyOp(dataType, '-', data, stepFast?.takeIf { io.keyCtrl } ?: step) valueChanged = true } sameLine(0f, style.itemInnerSpacing.x) if (buttonEx("+", Vec2(buttonSize), buttonFlags)) { data = dataTypeApplyOp(dataType, '+', data, stepFast?.takeIf { io.keyCtrl } ?: step) valueChanged = true } val labelEnd = findRenderedTextEnd(label) if (0 != labelEnd) { sameLine(0f, style.itemInnerSpacing.x) textEx(label, labelEnd) } style.framePadding put backupFramePadding popID() endGroup() } else if (inputText(label, buf, flags)) valueChanged = dataTypeApplyOpFromText(buf.cStr, g.inputTextState.initialTextA, dataType, pData, format) if (valueChanged) markItemEdited(window.dc.lastItemId) return valueChanged } fun <N> inputScalarN(label: String, dataType: DataType, v: Any, components: Int, step: N? = null, stepFast: N? = null, format: String? = null, flags: InputTextFlags = 0): Boolean where N : Number, N : Comparable<N> { val window = currentWindow if (window.skipItems) return false var valueChanged = false beginGroup() pushID(label) pushMultiItemsWidths(components, calcItemWidth()) for (i in 0 until components) { pushID(i) if (i > 0) sameLine(0f, style.itemInnerSpacing.x) valueChanged = when (dataType) { DataType.Float -> withFloat(v as FloatArray, i) { inputScalar("", dataType, it as KMutableProperty0<N>, step, stepFast, format, flags) } DataType.Int -> withInt(v as IntArray, i) { inputScalar("", dataType, it as KMutableProperty0<N>, step, stepFast, format, flags) } else -> error("invalid") } || valueChanged sameLine(0f, style.itemInnerSpacing.x) popID() popItemWidth() } popID() val labelEnd = findRenderedTextEnd(label) if (0 != labelEnd) { sameLine(0f, style.itemInnerSpacing.x) textEx(label, labelEnd) } endGroup() return valueChanged } }
mit
0b2554ff7b6fbc9b06f5d87c2779c48e
47.553435
152
0.626838
3.951848
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ConvertNaNEqualityInspection.kt
1
2564
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe class ConvertNaNEqualityInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return binaryExpressionVisitor { expression -> if (expression.left.isNaNExpression() || expression.right.isNaNExpression()) { val inverted = when (expression.operationToken) { KtTokens.EXCLEQ -> true KtTokens.EQEQ -> false else -> return@binaryExpressionVisitor } holder.registerProblem( expression, KotlinBundle.message("equality.check.with.nan.should.be.replaced.with.isnan"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ConvertNaNEqualityQuickFix(inverted) ) } } } } private class ConvertNaNEqualityQuickFix(val inverted: Boolean) : LocalQuickFix { override fun getName() = KotlinBundle.message("convert.na.n.equality.quick.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement as? KtBinaryExpression ?: return val other = when { element.left.isNaNExpression() -> element.right ?: return element.right.isNaNExpression() -> element.left ?: return else -> return } val pattern = if (inverted) "!$0.isNaN()" else "$0.isNaN()" element.replace(KtPsiFactory(element).createExpressionByPattern(pattern, other)) } } private val NaNSet = setOf("kotlin.Double.Companion.NaN", "java.lang.Double.NaN", "kotlin.Float.Companion.NaN", "java.lang.Float.NaN") private fun KtExpression?.isNaNExpression(): Boolean { if (this?.text?.endsWith("NaN") != true) return false val fqName = this.resolveToCall()?.resultingDescriptor?.fqNameUnsafe?.asString() return NaNSet.contains(fqName) }
apache-2.0
df821df5092e18232d634b037257975b
43.206897
134
0.686037
4.865275
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/SimplifyAssertNotNullInspection.kt
5
5194
// 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.codeInsight.CodeInsightUtilCore import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.intentions.branchedTransformations.expressionComparedToNull import org.jetbrains.kotlin.idea.util.CommentSaver import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.siblings import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.resolve.calls.model.isReallySuccess import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull class SimplifyAssertNotNullInspection : AbstractApplicabilityBasedInspection<KtCallExpression>(KtCallExpression::class.java) { override fun isApplicable(element: KtCallExpression): Boolean { if ((element.calleeExpression as? KtNameReferenceExpression)?.getReferencedName() != "assert") return false val arguments = element.valueArguments if (arguments.size != 1 && arguments.size != 2) return false val condition = arguments.first().getArgumentExpression() as? KtBinaryExpression ?: return false if (condition.operationToken != KtTokens.EXCLEQ) return false val value = condition.expressionComparedToNull() as? KtNameReferenceExpression ?: return false val prevDeclaration = findVariableDeclaration(element) ?: return false if (value.getReferencedNameAsName() != prevDeclaration.nameAsName) return false if (prevDeclaration.initializer == null) return false val resolvedCall = element.resolveToCall() ?: return false if (!resolvedCall.isReallySuccess()) return false val function = resolvedCall.resultingDescriptor as? FunctionDescriptor ?: return false if (function.importableFqName?.asString() != "kotlin.assert") return false if (arguments.size != 1) { if (extractMessage(element) == null) return false } return true } override fun inspectionText(element: KtCallExpression) = KotlinBundle.message("assert.should.be.replaced.with.operator") override val defaultFixText: String get() = KotlinBundle.message("replace.assert.with.operator") override fun fixText(element: KtCallExpression): String = if (element.valueArguments.size == 1) { KotlinBundle.message("replace.with.0.operator", "!!") } else { KotlinBundle.message("replace.with.error") } override fun applyTo(element: KtCallExpression, project: Project, editor: Editor?) { val declaration = findVariableDeclaration(element) ?: return val initializer = declaration.initializer ?: return val message = extractMessage(element) val commentSaver = CommentSaver(element) if (message == null) { val newInitializer = KtPsiFactory(element).createExpressionByPattern("$0!!", initializer) initializer.replace(newInitializer) } else { val newInitializer = KtPsiFactory(element).createExpressionByPattern("$0 ?: kotlin.error($1)", initializer, message) val result = initializer.replace(newInitializer) val qualifiedExpression = (result as KtBinaryExpression).right as KtDotQualifiedExpression ShortenReferences.DEFAULT.process( element.containingKtFile, qualifiedExpression.startOffset, (qualifiedExpression.selectorExpression as KtCallExpression).calleeExpression!!.endOffset ) } element.delete() commentSaver.restore(declaration) if (editor != null) { val newInitializer = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(declaration)?.initializer ?: return val offset = if (message == null) newInitializer.endOffset else (newInitializer as KtBinaryExpression).operationReference.startOffset editor.moveCaret(offset) } } private fun findVariableDeclaration(element: KtCallExpression): KtVariableDeclaration? { if (element.parent !is KtBlockExpression) return null return element.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtExpression>() as? KtVariableDeclaration } private fun extractMessage(element: KtCallExpression): KtExpression? { val arguments = element.valueArguments if (arguments.size != 2) return null return (arguments[1].getArgumentExpression() as? KtLambdaExpression) ?.bodyExpression ?.statements ?.singleOrNull() } }
apache-2.0
5d17d868eeefb49c96803c78b36c0ce3
46.218182
158
0.72603
5.393562
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/SelectContentStep.kt
12
1473
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl.content import com.intellij.openapi.ui.popup.PopupStep import com.intellij.openapi.ui.popup.util.BaseListPopupStep import com.intellij.ui.content.Content import com.intellij.ui.content.TabbedContent import java.awt.Color import javax.swing.Icon open class SelectContentStep : BaseListPopupStep<Content> { constructor(contents: Array<Content>) : super(null, *contents) constructor(contents: List<Content>) : super(null, contents) override fun isSpeedSearchEnabled(): Boolean = true override fun getIconFor(value: Content): Icon? = value.icon override fun getTextFor(value: Content): String { return value.asMultiTabbed()?.titlePrefix ?: value.displayName ?: super.getTextFor(value) } override fun getBackgroundFor(value: Content): Color? = value.tabColor override fun hasSubstep(value: Content): Boolean = value.asMultiTabbed() != null override fun onChosen(value: Content, finalChoice: Boolean): PopupStep<*>? { val tabbed = value.asMultiTabbed() if (tabbed == null) { value.manager?.setSelectedContentCB(value, true, true) return PopupStep.FINAL_CHOICE } else { return SelectContentTabStep(tabbed) } } private fun Content.asMultiTabbed(): TabbedContent? = if (this is TabbedContent && hasMultipleTabs()) this else null }
apache-2.0
5ff0623adbd41779c93454601b3cded9
36.769231
140
0.75017
4.114525
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/base/fragment/TimerFragmentBase.kt
1
5659
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.shared.base.fragment import android.app.Activity import android.content.Context import android.media.MediaPlayer import android.os.Bundle import android.os.CountDownTimer import android.os.Vibrator import android.view.View import android.view.WindowManager import androidx.core.content.getSystemService import androidx.fragment.app.Fragment import de.dreier.mytargets.shared.R import de.dreier.mytargets.shared.base.fragment.ETimerState.* import de.dreier.mytargets.shared.models.TimerSettings import de.dreier.mytargets.shared.utils.VibratorCompat abstract class TimerFragmentBase : Fragment(), View.OnClickListener { private var currentStatus = WAIT_FOR_START private var countdown: CountDownTimer? = null private lateinit var horn: MediaPlayer lateinit var settings: TimerSettings private var exitAfterStop = true override fun onAttach(context: Context) { super.onAttach(context) horn = MediaPlayer.create(context, R.raw.horn) } @Suppress("OverridingDeprecatedMember", "DEPRECATION") override fun onAttach(activity: Activity?) { super.onAttach(activity) horn = MediaPlayer.create(activity, R.raw.horn) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) settings = arguments!!.getParcelable(ARG_TIMER_SETTINGS)!! exitAfterStop = arguments!!.getBoolean(ARG_EXIT_AFTER_STOP) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) activity!!.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.setOnClickListener(this) changeStatus(currentStatus) } override fun onDetach() { countdown?.cancel() if (horn.isPlaying) { horn.stop() } horn.release() super.onDetach() } override fun onClick(v: View) { changeStatus(currentStatus.next) } private fun changeStatus(status: ETimerState) { countdown?.cancel() if (status === ETimerState.EXIT) { if (exitAfterStop) { activity?.finish() } else { changeStatus(WAIT_FOR_START) } return } currentStatus = status applyStatus(status) playSignal(status.signalCount) if (status === FINISHED) { applyTime(getString(R.string.stop)) countdown = object : CountDownTimer(6000, 100) { override fun onTick(millisUntilFinished: Long) {} override fun onFinish() { changeStatus(status.next) } }.start() } else { if (status !== PREPARATION && status !== SHOOTING && status !== COUNTDOWN) { applyTime("") } else { val offset = getOffset(status) countdown = object : CountDownTimer((getDuration(status) * 1000).toLong(), 1000) { override fun onTick(millisUntilFinished: Long) { val countdown = offset + Math.ceil(millisUntilFinished / 1000.0).toInt() applyTime(countdown.toString()) } override fun onFinish() { changeStatus(status.next) } }.start() } } } protected fun getDuration(status: ETimerState): Int { return when (status) { PREPARATION -> settings.waitTime SHOOTING -> settings.shootTime - settings.warnTime COUNTDOWN -> settings.warnTime else -> throw IllegalArgumentException() } } private fun getOffset(status: ETimerState): Int { return if (status === SHOOTING) { settings.warnTime } else { 0 } } private fun playSignal(n: Int) { if (n > 0) { if (settings.sound) { playHorn(n) } if (settings.vibrate) { val pattern = LongArray(1 + n * 2) val v = activity!!.getSystemService<Vibrator>()!! pattern[0] = 150 for (i in 0 until n) { pattern[i * 2 + 1] = 400 pattern[i * 2 + 2] = 750 } VibratorCompat.vibrate(v, pattern, -1) } } } private fun playHorn(n: Int) { if (!horn.isPlaying && !isDetached) { horn.start() horn.setOnCompletionListener { if (n > 1) { playHorn(n - 1) } } } } abstract fun applyTime(text: String) protected abstract fun applyStatus(status: ETimerState) companion object { const val ARG_TIMER_SETTINGS = "timer_settings" const val ARG_EXIT_AFTER_STOP = "exit_after_stop" } }
gpl-2.0
cddf8f8464bd744d03788a9f19beca17
30.614525
98
0.593214
4.707987
false
false
false
false
EddieRingle/statesman
runtime/src/main/kotlin/io/ringle/statesman/Helpers.kt
1
1292
package io.ringle.statesman import android.os.Bundle import android.util.SparseArray import kotlin.properties.ReadWriteProperty fun <T> bundle(bundle: Bundle, default: (thisRef: Any?, desc: String) -> T = defaultValueProvider): ReadWriteProperty<Any?, T> { return FixedBundleVar(bundle, defaultKeyProvider, default) } fun <T> Stateful.store(default: (thisRef: Any?, desc: String) -> T = defaultValueProvider): ReadWriteProperty<Any?, T> { return bundle(state, default) } fun <T> Stateful.store(default: T): ReadWriteProperty<Any?, T> { return bundle(state, { r, d -> default }) } fun Bundle.isNewState(): Boolean = getBoolean(Statesman.sKeyNewState) class SparseEntry<E>(val k: Int, val v: E) : Map.Entry<Int, E> { override val key: Int = k override val value: E = v } operator fun <E> SparseArray<E>.iterator(): MutableIterator<SparseEntry<E>> { return object : MutableIterator<SparseEntry<E>> { var index = 0 override fun hasNext(): Boolean { return index < size() } override fun next(): SparseEntry<E> { val i = index++ return SparseEntry(keyAt(i), valueAt(i)) } override fun remove() { index -= 1 removeAt(index) } } }
mit
849eb02707bf6f298792e8e807c944a0
27.711111
120
0.634675
3.868263
false
false
false
false
FireZenk/Kartographer
animations/src/main/java/org/firezenk/kartographer/animations/ContextMonitor.kt
1
1371
package org.firezenk.kartographer.animations import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import org.firezenk.kartographer.annotations.Monitor /** * Project: Kartographer * * Created by Jorge Garrido Oval, aka firezenk on 08/01/17. * Copyright © Jorge Garrido Oval 2017 */ class ContextMonitor : Monitor(), Application.ActivityLifecycleCallbacks { private lateinit var observer: (Any) -> Unit override fun onContextChanged(block: (Any) -> Unit) { observer = block } override fun onContextCaptured(context: Any) { observer(context) } override fun onActivityPaused(activity: Activity?) {} override fun onActivityResumed(activity: Activity?) = onActivityCaptured(activity) override fun onActivityStarted(activity: Activity?) = onActivityCaptured(activity) override fun onActivityDestroyed(activity: Activity?) {} override fun onActivitySaveInstanceState(activity: Activity?, p1: Bundle?) {} override fun onActivityStopped(activity: Activity?) {} override fun onActivityCreated(activity: Activity?, p1: Bundle?) = onActivityCaptured(activity) private fun onActivityCaptured(activity: Activity?) { if (activity?.callingActivity == null) { onContextCaptured(activity as Context) } } }
mit
fe1193558e3046fd7d3c117a7a6e355a
28.804348
99
0.729197
4.756944
false
false
false
false
kmagiera/react-native-gesture-handler
android/src/main/java/com/swmansion/gesturehandler/react/RNGestureHandlerButtonViewManager.kt
1
12568
package com.swmansion.gesturehandler.react import android.annotation.SuppressLint import android.annotation.TargetApi import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.drawable.Drawable import android.graphics.drawable.LayerDrawable import android.graphics.drawable.PaintDrawable import android.graphics.drawable.RippleDrawable import android.os.Build import android.util.TypedValue import android.view.MotionEvent import android.view.View import android.view.View.OnClickListener import android.view.ViewGroup import androidx.core.view.children import com.facebook.react.bridge.SoftAssertions import com.facebook.react.uimanager.PixelUtil import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.ViewGroupManager import com.facebook.react.uimanager.ViewProps import com.facebook.react.uimanager.annotations.ReactProp import com.swmansion.gesturehandler.NativeViewGestureHandler import com.swmansion.gesturehandler.react.RNGestureHandlerButtonViewManager.ButtonViewGroup class RNGestureHandlerButtonViewManager : ViewGroupManager<ButtonViewGroup>() { override fun getName() = "RNGestureHandlerButton" public override fun createViewInstance(context: ThemedReactContext) = ButtonViewGroup(context) @TargetApi(Build.VERSION_CODES.M) @ReactProp(name = "foreground") fun setForeground(view: ButtonViewGroup, useDrawableOnForeground: Boolean) { view.useDrawableOnForeground = useDrawableOnForeground } @ReactProp(name = "borderless") fun setBorderless(view: ButtonViewGroup, useBorderlessDrawable: Boolean) { view.useBorderlessDrawable = useBorderlessDrawable } @ReactProp(name = "enabled") fun setEnabled(view: ButtonViewGroup, enabled: Boolean) { view.isEnabled = enabled } @ReactProp(name = ViewProps.BORDER_RADIUS) override fun setBorderRadius(view: ButtonViewGroup, borderRadius: Float) { view.borderRadius = borderRadius } @ReactProp(name = "rippleColor") fun setRippleColor(view: ButtonViewGroup, rippleColor: Int?) { view.rippleColor = rippleColor } @ReactProp(name = "rippleRadius") fun setRippleRadius(view: ButtonViewGroup, rippleRadius: Int?) { view.rippleRadius = rippleRadius } @ReactProp(name = "exclusive") fun setExclusive(view: ButtonViewGroup, exclusive: Boolean = true) { view.exclusive = exclusive } override fun onAfterUpdateTransaction(view: ButtonViewGroup) { view.updateBackground() } class ButtonViewGroup(context: Context?) : ViewGroup(context), NativeViewGestureHandler.StateChangeHook { // Using object because of handling null representing no value set. var rippleColor: Int? = null set(color) = withBackgroundUpdate { field = color } var rippleRadius: Int? = null set(radius) = withBackgroundUpdate { field = radius } var useDrawableOnForeground = false set(useForeground) = withBackgroundUpdate { field = useForeground } var useBorderlessDrawable = false var borderRadius = 0f set(radius) = withBackgroundUpdate { field = radius * resources.displayMetrics.density } var exclusive = true private var _backgroundColor = Color.TRANSPARENT private var needBackgroundUpdate = false private var lastEventTime = -1L private var lastAction = -1 var isTouched = false init { // we attach empty click listener to trigger tap sounds (see View#performClick()) setOnClickListener(dummyClickListener) isClickable = true isFocusable = true needBackgroundUpdate = true } private inline fun withBackgroundUpdate(block: () -> Unit) { block() needBackgroundUpdate = true } override fun setBackgroundColor(color: Int) = withBackgroundUpdate { _backgroundColor = color } private fun applyRippleEffectWhenNeeded(selectable: Drawable): Drawable { val rippleColor = rippleColor if (rippleColor != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && selectable is RippleDrawable) { val states = arrayOf(intArrayOf(android.R.attr.state_enabled)) val colors = intArrayOf(rippleColor) val colorStateList = ColorStateList(states, colors) selectable.setColor(colorStateList) } val rippleRadius = rippleRadius if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && rippleRadius != null && selectable is RippleDrawable) { selectable.radius = PixelUtil.toPixelFromDIP(rippleRadius.toFloat()).toInt() } return selectable } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { if (super.onInterceptTouchEvent(ev)) { return true } // We call `onTouchEvent` and wait until button changes state to `pressed`, if it's pressed // we return true so that the gesture handler can activate. onTouchEvent(ev) return isPressed } /** * Buttons in RN are wrapped in NativeViewGestureHandler which manages * calling onTouchEvent after activation of the handler. Problem is, in order to verify that * underlying button implementation is interested in receiving touches we have to call onTouchEvent * and check if button is pressed. * * This leads to invoking onTouchEvent twice which isn't idempotent in View - it calls OnClickListener * and plays sound effect if OnClickListener was set. * * To mitigate this behavior we use lastEventTime and lastAction variables to check that we already handled * the event in [onInterceptTouchEvent]. We assume here that different events * will have different event times or actions. * Events with same event time can occur on some devices for different actions. * (e.g. move and up in one gesture; move and cancel) * * Reference: * [com.swmansion.gesturehandler.NativeViewGestureHandler.onHandle] */ @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { val eventTime = event.eventTime val action = event.action // always true when lastEventTime or lastAction have default value (-1) if (lastEventTime != eventTime || lastAction != action) { lastEventTime = eventTime lastAction = action return super.onTouchEvent(event) } return false } fun updateBackground() { if (!needBackgroundUpdate) { return } needBackgroundUpdate = false if (_backgroundColor == Color.TRANSPARENT) { // reset background background = null } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // reset foreground foreground = null } if (useDrawableOnForeground && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { foreground = applyRippleEffectWhenNeeded(createSelectableDrawable()) if (_backgroundColor != Color.TRANSPARENT) { setBackgroundColor(_backgroundColor) } } else if (_backgroundColor == Color.TRANSPARENT && rippleColor == null) { background = createSelectableDrawable() } else { val colorDrawable = PaintDrawable(_backgroundColor) val selectable = createSelectableDrawable() if (borderRadius != 0f) { // Radius-connected lines below ought to be considered // as a temporary solution. It do not allow to set // different radius on each corner. However, I suppose it's fairly // fine for button-related use cases. // Therefore it might be used as long as: // 1. ReactViewManager is not a generic class with a possibility to handle another ViewGroup // 2. There's no way to force native behavior of ReactViewGroup's superclass's onTouchEvent colorDrawable.setCornerRadius(borderRadius) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && selectable is RippleDrawable) { val mask = PaintDrawable(Color.WHITE) mask.setCornerRadius(borderRadius) selectable.setDrawableByLayerId(android.R.id.mask, mask) } } applyRippleEffectWhenNeeded(selectable) val layerDrawable = LayerDrawable(arrayOf(colorDrawable, selectable)) background = layerDrawable } } private fun createSelectableDrawable(): Drawable { val version = Build.VERSION.SDK_INT val identifier = if (useBorderlessDrawable && version >= 21) SELECTABLE_ITEM_BACKGROUND_BORDERLESS else SELECTABLE_ITEM_BACKGROUND val attrID = getAttrId(context, identifier) context.theme.resolveAttribute(attrID, resolveOutValue, true) return if (version >= 21) { resources.getDrawable(resolveOutValue.resourceId, context.theme) } else { @Suppress("Deprecation") resources.getDrawable(resolveOutValue.resourceId) } } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { // No-op } override fun drawableHotspotChanged(x: Float, y: Float) { if (responder == null || responder === this) { super.drawableHotspotChanged(x, y) } } override fun canStart(): Boolean { val isResponder = tryGrabbingResponder() if (isResponder) { isTouched = true } return isResponder } override fun afterGestureEnd() { tryFreeingResponder() isTouched = false } private fun tryGrabbingResponder(): Boolean { if (isChildTouched()) { return false } if (responder == null) { responder = this return true } return if (exclusive) { responder === this } else { !(responder?.exclusive ?: false) } } private fun tryFreeingResponder() { if (responder === this) { responder = null } } private fun isChildTouched(children: Sequence<View> = this.children): Boolean { for (child in children) { if (child is ButtonViewGroup && (child.isTouched || child.isPressed)) { return true } else if (child is ViewGroup) { return isChildTouched(child.children) } } return false } override fun setPressed(pressed: Boolean) { // there is a possibility of this method being called before NativeViewGestureHandler has // opportunity to call canStart, in that case we need to grab responder in case the gesture // will activate // when canStart is called eventually, tryGrabbingResponder will return true if the button // already is a responder if (pressed) { tryGrabbingResponder() } // button can be pressed alongside other button if both are non-exclusive and it doesn't have // any pressed children (to prevent pressing the parent when children is pressed). val canBePressedAlongsideOther = !exclusive && responder?.exclusive != true && !isChildTouched() if (!pressed || responder === this || canBePressedAlongsideOther) { // we set pressed state only for current responder or any non-exclusive button when responder // is null or non-exclusive, assuming it doesn't have pressed children super.setPressed(pressed) isTouched = pressed } if (!pressed && responder === this) { // if the responder is no longer pressed we release button responder responder = null } } override fun dispatchDrawableHotspotChanged(x: Float, y: Float) { // No-op // by default Viewgroup would pass hotspot change events } companion object { const val SELECTABLE_ITEM_BACKGROUND = "selectableItemBackground" const val SELECTABLE_ITEM_BACKGROUND_BORDERLESS = "selectableItemBackgroundBorderless" var resolveOutValue = TypedValue() var responder: ButtonViewGroup? = null var dummyClickListener = OnClickListener { } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private fun getAttrId(context: Context, attr: String): Int { SoftAssertions.assertNotNull(attr) return when (attr) { SELECTABLE_ITEM_BACKGROUND -> { R.attr.selectableItemBackground } SELECTABLE_ITEM_BACKGROUND_BORDERLESS -> { R.attr.selectableItemBackgroundBorderless } else -> { context.resources.getIdentifier(attr, "attr", "android") } } } } } }
mit
d10e75f502059bc648f1e24079030ffd
35.114943
136
0.68563
4.830131
false
false
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/sdk/pipenv/pipenv.kt
4
18665
// 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.jetbrains.python.sdk.pipenv import com.google.gson.Gson import com.google.gson.JsonSyntaxException import com.google.gson.annotations.SerializedName import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.execution.ExecutionException import com.intellij.execution.RunCanceledByUserException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.configurations.PathEnvironmentVariableUtil import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessOutput import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationDisplayType import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationType import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.ProjectComponent import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.EditorFactory import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.event.DocumentListener import com.intellij.openapi.editor.event.EditorFactoryEvent import com.intellij.openapi.editor.event.EditorFactoryListener import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Key import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtil import com.jetbrains.python.inspections.PyPackageRequirementsInspection import com.jetbrains.python.packaging.* import com.jetbrains.python.sdk.* import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import icons.PythonIcons import org.jetbrains.annotations.SystemDependent import org.jetbrains.annotations.TestOnly import java.io.File import javax.swing.Icon /** * @author vlan */ const val PIP_FILE: String = "Pipfile" const val PIP_FILE_LOCK: String = "Pipfile.lock" const val PIPENV_DEFAULT_SOURCE_URL: String = "https://pypi.org/simple" const val PIPENV_PATH_SETTING: String = "PyCharm.Pipenv.Path" // TODO: Provide a special icon for pipenv val PIPENV_ICON: Icon = PythonIcons.Python.PythonClosed /** * The Pipfile found in the main content root of the module. */ val Module.pipFile: VirtualFile? get() = baseDir?.findChild(PIP_FILE) /** * Tells if the SDK was added as a pipenv. */ var Sdk.isPipEnv: Boolean get() = sdkAdditionalData is PyPipEnvSdkAdditionalData set(value) { val oldData = sdkAdditionalData val newData = if (value) { when (oldData) { is PythonSdkAdditionalData -> PyPipEnvSdkAdditionalData(oldData) else -> PyPipEnvSdkAdditionalData() } } else { when (oldData) { is PyPipEnvSdkAdditionalData -> PythonSdkAdditionalData(PythonSdkFlavor.getFlavor(this)) else -> oldData } } val modificator = sdkModificator modificator.sdkAdditionalData = newData ApplicationManager.getApplication().runWriteAction { modificator.commitChanges() } } /** * The user-set persisted path to the pipenv executable. */ var PropertiesComponent.pipEnvPath: @SystemDependent String? get() = getValue(PIPENV_PATH_SETTING) set(value) { setValue(PIPENV_PATH_SETTING, value) } /** * Detects the pipenv executable in `$PATH`. */ fun detectPipEnvExecutable(): File? { val name = when { SystemInfo.isWindows -> "pipenv.exe" else -> "pipenv" } return PathEnvironmentVariableUtil.findInPath(name) } /** * Returns the configured pipenv executable or detects it automatically. */ fun getPipEnvExecutable(): File? = PropertiesComponent.getInstance().pipEnvPath?.let { File(it) } ?: detectPipEnvExecutable() /** * Sets up the pipenv environment under the modal progress window. * * The pipenv is associated with the first valid object from this list: * * 1. New project specified by [newProjectPath] * 2. Existing module specified by [module] * 3. Existing project specified by [project] * * @return the SDK for pipenv, not stored in the SDK table yet. */ fun setupPipEnvSdkUnderProgress(project: Project?, module: Module?, existingSdks: List<Sdk>, newProjectPath: String?, python: String?, installPackages: Boolean): Sdk? { val projectPath = newProjectPath ?: module?.basePath ?: project?.basePath ?: return null val task = object : Task.WithResult<String, ExecutionException>(project, "Setting Up Pipenv Environment", true) { override fun compute(indicator: ProgressIndicator): String { indicator.isIndeterminate = true val pipEnv = setupPipEnv(FileUtil.toSystemDependentName(projectPath), python, installPackages) return PythonSdkType.getPythonExecutable(pipEnv) ?: FileUtil.join(pipEnv, "bin", "python") } } val suggestedName = "Pipenv (${PathUtil.getFileName(projectPath)})" return createSdkByGenerateTask(task, existingSdks, null, projectPath, suggestedName)?.apply { isPipEnv = true associateWithModule(module, newProjectPath) } } /** * Sets up the pipenv environment for the specified project path. * * @return the path to the pipenv environment. */ fun setupPipEnv(projectPath: @SystemDependent String, python: String?, installPackages: Boolean): @SystemDependent String { when { installPackages -> { val pythonArgs = if (python != null) listOf("--python", python) else emptyList() val command = pythonArgs + listOf("install", "--dev") runPipEnv(projectPath, *command.toTypedArray()) } python != null -> runPipEnv(projectPath, "--python", python) else -> runPipEnv(projectPath, "run", "python", "-V") } return runPipEnv(projectPath, "--venv").trim() } /** * Runs the configured pipenv for the specified Pipenv SDK with the associated project path. */ fun runPipEnv(sdk: Sdk, vararg args: String): String { val projectPath = sdk.associatedModulePath ?: throw PyExecutionException("Cannot find the project associated with this Pipenv environment", "Pipenv", emptyList(), ProcessOutput()) return runPipEnv(projectPath, *args) } /** * Runs the configured pipenv for the specified project path. */ fun runPipEnv(projectPath: @SystemDependent String, vararg args: String): String { val executable = getPipEnvExecutable()?.path ?: throw PyExecutionException("Cannot find Pipenv", "pipenv", emptyList(), ProcessOutput()) val command = listOf(executable) + args val commandLine = GeneralCommandLine(command).withWorkDirectory(projectPath) val handler = CapturingProcessHandler(commandLine) val indicator = ProgressManager.getInstance().progressIndicator val result = with(handler) { when { indicator != null -> { addProcessListener(PyPackageManagerImpl.IndicatedProcessOutputListener(indicator)) runProcessWithProgressIndicator(indicator) } else -> runProcess() } } return with(result) { when { isCancelled -> throw RunCanceledByUserException() exitCode != 0 -> throw PyExecutionException("Error Running Pipenv", executable, args.asList(), stdout, stderr, exitCode, emptyList()) else -> stdout } } } /** * Detects and sets up pipenv SDK for a module with Pipfile. */ fun detectAndSetupPipEnv(project: Project?, module: Module?, existingSdks: List<Sdk>): Sdk? { if (module?.pipFile == null || getPipEnvExecutable() == null) { return null } return setupPipEnvSdkUnderProgress(project, module, existingSdks, null, null, false) } /** * The URLs of package sources configured in the Pipfile.lock of the module associated with this SDK. */ val Sdk.pipFileLockSources: List<String> get() = parsePipFileLock()?.meta?.sources?.mapNotNull { it.url } ?: listOf(PIPENV_DEFAULT_SOURCE_URL) /** * The list of requirements defined in the Pipfile.lock of the module associated with this SDK. */ val Sdk.pipFileLockRequirements: List<PyRequirement>? get() { return pipFileLock?.let { getPipFileLockRequirements(it, packageManager) } } /** * A quick-fix for setting up the pipenv for the module of the current PSI element. */ class UsePipEnvQuickFix(sdk: Sdk?, module: Module) : LocalQuickFix { private val quickFixName = when { sdk != null && sdk.associatedModule != module -> "Fix Pipenv interpreter" else -> "Use Pipenv interpreter" } companion object { fun isApplicable(module: Module): Boolean = module.pipFile != null fun setUpPipEnv(project: Project, module: Module) { val sdksModel = ProjectSdksModel().apply { reset(project) } val existingSdks = sdksModel.sdks.filter { it.sdkType is PythonSdkType } // XXX: Should we show an error message on exceptions and on null? val newSdk = setupPipEnvSdkUnderProgress(project, module, existingSdks, null, null, false) ?: return val existingSdk = existingSdks.find { it.isPipEnv && it.homePath == newSdk.homePath } val sdk = existingSdk ?: newSdk if (sdk == newSdk) { SdkConfigurationUtil.addSdk(newSdk) } else { sdk.associateWithModule(module, null) } project.pythonSdk = sdk module.pythonSdk = sdk } } override fun getFamilyName() = quickFixName override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement ?: return val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return // Invoke the setup later to escape the write action of the quick fix in order to show the modal progress dialog ApplicationManager.getApplication().invokeLater { if (project.isDisposed || module.isDisposed) return@invokeLater setUpPipEnv(project, module) } } } /** * A quick-fix for installing packages specified in Pipfile.lock. */ class PipEnvInstallQuickFix : LocalQuickFix { companion object { fun pipEnvInstall(project: Project, module: Module) { val sdk = module.pythonSdk ?: return if (!sdk.isPipEnv) return val listener = PyPackageRequirementsInspection.RunningPackagingTasksListener(module) val ui = PyPackageManagerUI(project, sdk, listener) ui.install(null, listOf("--dev")) } } override fun getFamilyName() = "Install requirements from Pipfile.lock" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement ?: return val module = ModuleUtilCore.findModuleForPsiElement(element) ?: return pipEnvInstall(project, module) } } /** * Watches for edits in Pipfiles inside modules with a pipenv SDK set. */ class PipEnvPipFileWatcherComponent(val project: Project) : ProjectComponent { override fun projectOpened() { val editorFactoryListener = object : EditorFactoryListener { private val changeListenerKey = Key.create<DocumentListener>("Pipfile.change.listener") private val notificationActive = Key.create<Boolean>("Pipfile.notification.active") override fun editorCreated(event: EditorFactoryEvent) { if (!isPipFileEditor(event.editor)) return val listener = object : DocumentListener { override fun documentChanged(event: DocumentEvent) { val document = event?.document ?: return val module = document.virtualFile?.getModule(project) ?: return if (FileDocumentManager.getInstance().isDocumentUnsaved(document)) { notifyPipFileChanged(module) } } } with(event.editor.document) { addDocumentListener(listener) putUserData(changeListenerKey, listener) } } override fun editorReleased(event: EditorFactoryEvent) { val listener = event.editor.getUserData(changeListenerKey) ?: return event.editor.document.removeDocumentListener(listener) } private fun notifyPipFileChanged(module: Module) { if (module.getUserData(notificationActive) == true) return val what = when { module.pipFileLock == null -> "not found" else -> "out of date" } val title = "$PIP_FILE_LOCK is $what" val content = "Run <a href='#lock'>pipenv lock</a> or <a href='#update'>pipenv update</a>" val notification = LOCK_NOTIFICATION_GROUP.createNotification(title, null, content, NotificationType.INFORMATION) { notification, event -> notification.expire() module.putUserData(notificationActive, null) FileDocumentManager.getInstance().saveAllDocuments() when (event.description) { "#lock" -> runPipEnvInBackground(module, listOf("lock"), "Locking $PIP_FILE") "#update" -> runPipEnvInBackground(module, listOf("update", "--dev"), "Updating Pipenv environment") } } module.putUserData(notificationActive, true) notification.whenExpired { module.putUserData(notificationActive, null) } notification.notify(project) } private fun runPipEnvInBackground(module: Module, args: List<String>, description: String) { val task = object : Task.Backgroundable(module.project, StringUtil.toTitleCase(description), true) { override fun run(indicator: ProgressIndicator) { val sdk = module.pythonSdk ?: return indicator.text = "$description..." try { runPipEnv(sdk, *args.toTypedArray()) } catch (e: RunCanceledByUserException) {} catch (e: ExecutionException) { runInEdt { Messages.showErrorDialog(project, e.toString(), "Error Running Pipenv") } } finally { sdk.associatedModule?.baseDir?.refresh(true, false) } } } ProgressManager.getInstance().run(task) } private fun isPipFileEditor(editor: Editor): Boolean { if (editor.project != project) return false val file = editor.document.virtualFile ?: return false if (file.name != PIP_FILE) return false val module = file.getModule(project) ?: return false if (module.pipFile != file) return false return module.pythonSdk?.isPipEnv == true } } EditorFactory.getInstance().addEditorFactoryListener(editorFactoryListener, project) } } private val Document.virtualFile: VirtualFile? get() = FileDocumentManager.getInstance().getFile(this) private fun VirtualFile.getModule(project: Project): Module? = ModuleUtil.findModuleForFile(this, project) private val LOCK_NOTIFICATION_GROUP = NotificationGroup("$PIP_FILE Watcher", NotificationDisplayType.STICKY_BALLOON, false) private val Sdk.packageManager: PyPackageManager get() = PyPackageManagers.getInstance().forSdk(this) @TestOnly fun getPipFileLockRequirements(virtualFile: VirtualFile, packageManager: PyPackageManager): List<PyRequirement>? { fun toRequirements(packages: Map<String, PipFileLockPackage>): List<PyRequirement> = packages .asSequence() .filterNot { (_, pkg) -> pkg.editable ?: false } // TODO: Support requirements markers (PEP 496), currently any packages with markers are ignored due to PY-30803 .filter { (_, pkg) -> pkg.markers == null } .flatMap { (name, pkg) -> packageManager.parseRequirements("$name${pkg.version ?: ""}").asSequence() } .toList() val pipFileLock = parsePipFileLock(virtualFile) ?: return null val packages = pipFileLock.packages?.let { toRequirements(it) } ?: emptyList() val devPackages = pipFileLock.devPackages?.let { toRequirements(it) } ?: emptyList() return packages + devPackages } private fun Sdk.parsePipFileLock(): PipFileLock? { // TODO: Log errors if Pipfile.lock is not found val file = pipFileLock ?: return null return parsePipFileLock(file) } private fun parsePipFileLock(virtualFile: VirtualFile): PipFileLock? { val text = ReadAction.compute<String, Throwable> { FileDocumentManager.getInstance().getDocument(virtualFile)?.text } return try { Gson().fromJson(text, PipFileLock::class.java) } catch (e: JsonSyntaxException) { // TODO: Log errors return null } } private val Sdk.pipFileLock: VirtualFile? get() = associatedModulePath?.let { StandardFileSystems.local().findFileByPath(it)?.findChild(PIP_FILE_LOCK) } private val Module.pipFileLock: VirtualFile? get() = baseDir?.findChild(PIP_FILE_LOCK) private data class PipFileLock(@SerializedName("_meta") var meta: PipFileLockMeta?, @SerializedName("default") var packages: Map<String, PipFileLockPackage>?, @SerializedName("develop") var devPackages: Map<String, PipFileLockPackage>?) private data class PipFileLockMeta(@SerializedName("sources") var sources: List<PipFileLockSource>?) private data class PipFileLockSource(@SerializedName("url") var url: String?) private data class PipFileLockPackage(@SerializedName("version") var version: String?, @SerializedName("editable") var editable: Boolean?, @SerializedName("hashes") var hashes: List<String>?, @SerializedName("markers") var markers: String?)
apache-2.0
5c39ac5795eda3cb9a156ac82f19aeb0
38.212185
140
0.700348
4.575876
false
false
false
false
paplorinc/intellij-community
platform/projectModel-api/src/com/intellij/openapi/application/actions.kt
2
2435
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.application import com.intellij.openapi.command.CommandProcessor import com.intellij.openapi.util.Computable import java.lang.reflect.InvocationTargetException import javax.swing.SwingUtilities inline fun <T> runWriteAction(crossinline runnable: () -> T): T { return ApplicationManager.getApplication().runWriteAction(Computable { runnable() }) } inline fun <T> runUndoTransparentWriteAction(crossinline runnable: () -> T): T { return computeDelegated { CommandProcessor.getInstance().runUndoTransparentAction { ApplicationManager.getApplication().runWriteAction(Runnable { it(runnable()) }) } } } inline fun <T> runReadAction(crossinline runnable: () -> T): T { return ApplicationManager.getApplication().runReadAction(Computable { runnable() }) } /** * @suppress Internal use only */ fun <T> invokeAndWaitIfNeeded(modalityState: ModalityState? = null, runnable: () -> T): T { val app = ApplicationManager.getApplication() if (app == null) { if (SwingUtilities.isEventDispatchThread()) { return runnable() } else { @Suppress("UNCHECKED_CAST") try { return computeDelegated { SwingUtilities.invokeAndWait { it(runnable()) } } } catch (e: InvocationTargetException) { throw e.cause ?: e } } } else if (app.isDispatchThread) { return runnable() } else { return computeDelegated { app.invokeAndWait({ it (runnable()) }, modalityState ?: ModalityState.defaultModalityState()) } } } @Deprecated(replaceWith = ReplaceWith("invokeAndWaitIfNeeded()"), message = "Use invokeAndWaitIfNeeded()") fun <T> invokeAndWaitIfNeed(modalityState: ModalityState? = null, runnable: () -> T): T { return invokeAndWaitIfNeeded(modalityState, runnable) } @PublishedApi internal inline fun <T> computeDelegated(executor: (setter: (T) -> Unit) -> Unit): T { var resultRef: T? = null executor { resultRef = it } @Suppress("UNCHECKED_CAST") return resultRef as T } inline fun runInEdt(modalityState: ModalityState? = null, crossinline runnable: () -> Unit) { val app = ApplicationManager.getApplication() if (app.isDispatchThread) { runnable() } else { app.invokeLater({ runnable() }, modalityState ?: ModalityState.defaultModalityState()) } }
apache-2.0
9c23aa1b4d6c3082156a440bd9ef8e3c
32.369863
140
0.711294
4.559925
false
false
false
false
PaulWoitaschek/MaterialAudiobookPlayer
covercolorextractor/src/main/java/de/ph1b/audiobook/covercolorextractor/CoverColorExtractor.kt
1
2157
package de.ph1b.audiobook.covercolorextractor import android.graphics.Bitmap import androidx.palette.graphics.Palette import com.squareup.picasso.MemoryPolicy import com.squareup.picasso.Picasso import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.withContext import timber.log.Timber import java.io.File import java.io.IOException import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine class CoverColorExtractor { private val tasks = HashMap<Long, Deferred<Int?>>() private val extractedColors = HashMap<Long, Int?>() suspend fun extract(file: File): Int? = withContext(Dispatchers.IO) { if (!file.canRead()) { return@withContext null } val fileHash = fileHash(file) val extracted = extractedColors.getOrElse(fileHash) { 0 } if (extracted == 0) { val task = tasks.getOrPut(fileHash) { extractionTask(file) } task.await() } else extracted } private suspend fun CoroutineScope.extractionTask(file: File): Deferred<Int?> = async { val bitmap = bitmapByFile(file) if (bitmap != null) { val extracted = extractColor(bitmap) bitmap.recycle() val hash = fileHash(file) extractedColors[hash] = extracted extracted } else null } private suspend fun bitmapByFile(file: File): Bitmap? = withContext(Dispatchers.IO) { Timber.i("load cover for $file") try { Picasso.get() .load(file) .memoryPolicy(MemoryPolicy.NO_STORE) .resize(500, 500) .get() } catch (e: IOException) { Timber.e(e, "Error loading coverFile $file") null } } private suspend fun extractColor(bitmap: Bitmap): Int? = suspendCoroutine { cont -> Palette.from(bitmap) .generate { palette -> val invalidColor = -1 val color = palette?.getVibrantColor(invalidColor) cont.resume(color.takeUnless { it == invalidColor }) } } private fun fileHash(file: File) = file.absolutePath.hashCode() + file.lastModified() + file.length() }
lgpl-3.0
2e83f0e097ed757ed2515440dbff2caa
28.958333
89
0.689847
4.140115
false
false
false
false
apache/isis
incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/snapshots/demo2_0_0/ACTIONS_WHEREINTHEWORLD_INVOKE.kt
2
13063
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.snapshots.demo2_0_0 import org.apache.causeway.client.kroviz.snapshots.Response object ACTIONS_WHEREINTHEWORLD_INVOKE : Response() { override val url = "http://localhost:8080/restful/objects/demo.WhereInTheWorldMenu/1/actions/whereInTheWorld/invoke?address=Malvern,%20UK&zoom=14" override val str = """ { "links" : [ { "rel" : "self", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object\"", "title" : "Malvern, UK" }, { "rel" : "describedby", "href" : "http://localhost:8080/restful/domain-types/demo.CustomUiVm", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\"" }, { "rel" : "urn:org.apache.causeway.restfulobjects:rels/object-layout", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/object-layout", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-layout-bs3\"" }, { "rel" : "urn:org.apache.causeway.restfulobjects:rels/object-icon", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/image", "method" : "GET", "type" : "image/png" }, { "rel" : "urn:org.restfulobjects:rels/update", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm:PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K", "method" : "PUT", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object\"", "arguments" : { } } ], "extensions" : { "oid" : "demo.CustomUiVm:PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K", "isService" : false, "isPersistent" : true }, "title" : "Malvern, UK", "domainType" : "demo.CustomUiVm", "instanceId" : "PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K", "members" : { "address" : { "id" : "address", "memberType" : "property", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;property=\"address\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/properties/address", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\"" } ], "value" : "Malvern, UK", "extensions" : { "x-causeway-format" : "string" }, "disabledReason" : "Disabled" }, "latitude" : { "id" : "latitude", "memberType" : "property", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;property=\"latitude\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/properties/latitude", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\"" } ], "value" : "52.198944", "extensions" : { "x-causeway-format" : "string" }, "disabledReason" : "Disabled" }, "longitude" : { "id" : "longitude", "memberType" : "property", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;property=\"longitude\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/properties/longitude", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\"" } ], "value" : "-2.2426571079130886", "extensions" : { "x-causeway-format" : "string" }, "disabledReason" : "Disabled" }, "zoom" : { "id" : "zoom", "memberType" : "property", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;property=\"zoom\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/properties/zoom", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-property\"" } ], "value" : 14, "format" : "int", "extensions" : { "x-causeway-format" : "int" }, "disabledReason" : "Disabled" }, "clearHints" : { "id" : "clearHints", "memberType" : "action", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;action=\"clearHints\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/actions/clearHints", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "inspectMetamodel" : { "id" : "inspectMetamodel", "memberType" : "action", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;action=\"inspectMetamodel\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/actions/inspectMetamodel", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "downloadLayoutXml" : { "id" : "downloadLayoutXml", "memberType" : "action", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;action=\"downloadLayoutXml\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/actions/downloadLayoutXml", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "recentCommands" : { "id" : "recentCommands", "memberType" : "action", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;action=\"recentCommands\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/actions/recentCommands", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "rebuildMetamodel" : { "id" : "rebuildMetamodel", "memberType" : "action", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;action=\"rebuildMetamodel\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/actions/rebuildMetamodel", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "downloadMetamodelXml" : { "id" : "downloadMetamodelXml", "memberType" : "action", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;action=\"downloadMetamodelXml\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/actions/downloadMetamodelXml", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] }, "openRestApi" : { "id" : "openRestApi", "memberType" : "action", "links" : [ { "rel" : "urn:org.restfulobjects:rels/details;action=\"openRestApi\"", "href" : "http://localhost:8080/restful/objects/demo.CustomUiVm/PADw_eG1sIHZlcnNpb249IjEuMCIgZW5jb2Rpbmc9IlVURi04IiBzdGFuZGFsb25lPSJ5ZXMiPz4KPGRlbW8uQ3VzdG9tVWlWbT4KICAgIDxhZGRyZXNzPk1hbHZlcm4sIFVLPC9hZGRyZXNzPgogICAgPGxhdGl0dWRlPjUyLjE5ODk0NDwvbGF0aXR1ZGU-CiAgICA8bG9uZ2l0dWRlPi0yLjI0MjY1NzEwNzkxMzA4ODY8L2xvbmdpdHVkZT4KICAgIDx6b29tPjE0PC96b29tPgo8L2RlbW8uQ3VzdG9tVWlWbT4K/actions/openRestApi", "method" : "GET", "type" : "application/json;profile=\"urn:org.restfulobjects:repr-types/object-action\"" } ] } } } """ }
apache-2.0
ba49e37a08ab3d2ac6ba4a6530205bdb
64.974747
412
0.763071
2.285739
false
false
false
false
dzharkov/intellij-markdown
src/org/intellij/markdown/parser/TreeBuilder.kt
1
4147
package org.intellij.markdown.parser import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.ASTNodeBuilder import org.intellij.markdown.parser.sequentialparsers.SequentialParser import java.util.ArrayList import java.util.Collections import java.util.Stack public abstract class TreeBuilder(protected val nodeBuilder: ASTNodeBuilder) { public fun buildTree(production: List<SequentialParser.Node>): ASTNode { val events = constructEvents(production) val markersStack = Stack<Pair<MyEvent, MutableList<MyASTNodeWrapper>>>() assert(!events.isEmpty()) { "nonsense" } assert(events.first().info == events.last().info, { -> "more than one root?\nfirst: ${events.first().info}\nlast: ${events.last().info}" }) for (i in events.indices) { val event = events.get(i) flushEverythingBeforeEvent(event, if (markersStack.isEmpty()) null else markersStack.peek().second); if (event.isStart()) { markersStack.push(Pair(event, ArrayList())) } else { val currentNodeChildren = if (event.isEmpty()) { ArrayList() } else { val eventAndChildren = markersStack.pop() assert(eventAndChildren.first.info == event.info) eventAndChildren.second } val isTopmostNode = markersStack.isEmpty() val newNode = createASTNodeOnClosingEvent(event, currentNodeChildren, isTopmostNode) if (isTopmostNode) { assert(i + 1 == events.size()) return newNode.astNode } else { markersStack.peek().second.add(newNode) } } } throw AssertionError("markers stack should close some time thus would not be here!") } protected abstract fun createASTNodeOnClosingEvent(event: MyEvent, currentNodeChildren: List<MyASTNodeWrapper>, isTopmostNode: Boolean): MyASTNodeWrapper protected abstract fun flushEverythingBeforeEvent(event: MyEvent, currentNodeChildren: MutableList<MyASTNodeWrapper>?) private fun constructEvents(production: List<SequentialParser.Node>): List<MyEvent> { val events = ArrayList<MyEvent>() for (index in production.indices) { val result = production.get(index) val startTokenId = result.range.start val endTokenId = result.range.end events.add(MyEvent(startTokenId, index, result)) if (endTokenId != startTokenId) { events.add(MyEvent(endTokenId, index, result)) } } Collections.sort(events) return events } protected class MyEvent(val position: Int, val timeClosed: Int, val info: SequentialParser.Node) : Comparable<MyEvent> { public fun isStart(): Boolean { return info.range.end != position } public fun isEmpty(): Boolean { return info.range.start == info.range.end } override fun compareTo(other: MyEvent): Int { if (position != other.position) { return position - other.position } if (isStart() == other.isStart()) { val positionDiff = info.range.start + info.range.end - (other.info.range.start + other.info.range.end) if (positionDiff != 0) { return -positionDiff } val timeDiff = timeClosed - other.timeClosed if (isStart()) { return -timeDiff } else { return timeDiff } } return if (isStart()) 1 else -1 } override fun toString(): String { return "${if (isStart()) "Open" else "Close"}: ${position} (${info})" } } protected class MyASTNodeWrapper(public val astNode: ASTNode, public val startTokenIndex: Int, public val endTokenIndex: Int) }
apache-2.0
87d94728a39ad6387bcba5815e09dd3a
36.026786
157
0.583072
4.907692
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/collect/StringTokenizer.kt
1
416
package com.nibado.projects.advent.collect class StringTokenizer(val value: String) { private var index = 0 val read: Int get() = index constructor(seq: CharSequence) : this(seq.toString()) fun take(amount: Int) : String { val s = value.substring(index, index + amount) index += amount return s } override fun toString(): String = value.substring(index) }
mit
59f5e23940e6460df7c923f35458e1c2
22.166667
60
0.634615
4.118812
false
false
false
false
vhromada/Catalog
core/src/main/kotlin/com/github/vhromada/catalog/domain/filter/MovieFilter.kt
1
803
package com.github.vhromada.catalog.domain.filter import com.github.vhromada.catalog.common.filter.FieldOperation import com.github.vhromada.catalog.domain.QMovie /** * A class represents filter for movies. * * @author Vladimir Hromada */ data class MovieFilter( /** * Czech name */ val czechName: String? = null, /** * Original name */ val originalName: String? = null ) : JpaFilter() { override fun isEmpty(): Boolean { return czechName.isNullOrBlank() && originalName.isNullOrBlank() } override fun process() { val movie = QMovie.movie add(field = czechName, path = movie.czechName, operation = FieldOperation.LIKE) add(field = originalName, path = movie.originalName, operation = FieldOperation.LIKE) } }
mit
294ffb00bc64abfd8a6fa6aa3a333822
23.333333
93
0.666252
4.204188
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/moduleInfo/SdkInfo.kt
1
3922
// 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.projectStructure.moduleInfo import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.JdkOrderEntry import com.intellij.openapi.roots.ModuleRootManager import com.intellij.openapi.roots.OrderRootType import com.intellij.psi.search.GlobalSearchScope import org.jetbrains.kotlin.analyzer.* import org.jetbrains.kotlin.descriptors.ModuleCapability import org.jetbrains.kotlin.idea.base.projectStructure.KotlinBaseProjectStructureBundle import org.jetbrains.kotlin.idea.base.projectStructure.scope.PoweredLibraryScopeBase import org.jetbrains.kotlin.idea.framework.KotlinSdkType import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.platform.* import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.resolve.PlatformDependentAnalyzerServices import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices import org.jetbrains.kotlin.utils.addToStdlib.safeAs //TODO: (module refactoring) there should be separate SdkSourceInfo but there are no kotlin source in existing sdks for now :) data class SdkInfo(override val project: Project, val sdk: Sdk) : IdeaModuleInfo, SdkInfoBase { override val moduleOrigin: ModuleOrigin get() = ModuleOrigin.LIBRARY override val name: Name = Name.special("<sdk ${sdk.name}>") override val displayedName: String get() = KotlinBaseProjectStructureBundle.message("sdk.0", sdk.name) override val contentScope: GlobalSearchScope get() = SdkScope(project, sdk) override fun dependencies(): List<IdeaModuleInfo> = listOf(this) override fun dependenciesWithoutSelf(): Sequence<IdeaModuleInfo> = emptySequence() override val platform: TargetPlatform // TODO(dsavvinov): provide proper target version get() = when (sdk.sdkType) { is KotlinSdkType -> CommonPlatforms.defaultCommonPlatform else -> JvmPlatforms.unspecifiedJvmPlatform } override val analyzerServices: PlatformDependentAnalyzerServices get() = JvmPlatformAnalyzerServices override val capabilities: Map<ModuleCapability<*>, Any?> get() = when (this.sdk.sdkType) { is JavaSdk -> super<IdeaModuleInfo>.capabilities + mapOf(JDK_CAPABILITY to true) else -> super<IdeaModuleInfo>.capabilities } } fun Project.allSdks(modules: Array<out Module>? = null): Set<Sdk> = runReadAction { if (isDisposed) return@runReadAction emptySet() val sdks = ProjectJdkTable.getInstance().allJdks.toHashSet() val modulesArray = modules ?: ideaModules() ProgressManager.checkCanceled() modulesArray.flatMapTo(sdks, ::moduleSdks) sdks } fun moduleSdks(module: Module): List<Sdk> = if (module.isDisposed) { emptyList() } else { ModuleRootManager.getInstance(module).orderEntries.mapNotNull { orderEntry -> ProgressManager.checkCanceled() orderEntry.safeAs<JdkOrderEntry>()?.jdk } } //TODO: (module refactoring) android sdk has modified scope @Suppress("EqualsOrHashCode") // DelegatingGlobalSearchScope requires to provide 'calcHashCode()' private class SdkScope( project: Project, val sdk: Sdk ) : PoweredLibraryScopeBase(project, sdk.rootProvider.getFiles(OrderRootType.CLASSES), arrayOf()) { override fun equals(other: Any?) = other is SdkScope && sdk == other.sdk override fun calcHashCode(): Int = sdk.hashCode() override fun toString() = "SdkScope($sdk)" }
apache-2.0
dca0da6fe5f49fd493a3f7e76faccaac
43.579545
126
0.760071
4.742443
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/screen/GitUpdateScreen.kt
2
11127
package io.github.chrislo27.rhre3.screen import com.badlogic.gdx.Gdx import com.badlogic.gdx.Input import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.utils.Align import io.github.chrislo27.rhre3.PreferenceKeys import io.github.chrislo27.rhre3.RHRE3 import io.github.chrislo27.rhre3.RHRE3Application import io.github.chrislo27.rhre3.git.GitHelper import io.github.chrislo27.rhre3.git.SfxDbInfoObject import io.github.chrislo27.rhre3.stage.GenericStage import io.github.chrislo27.rhre3.stage.LoadingIcon import io.github.chrislo27.rhre3.util.JsonHandler import io.github.chrislo27.toolboks.Toolboks import io.github.chrislo27.toolboks.ToolboksScreen import io.github.chrislo27.toolboks.i18n.Localization import io.github.chrislo27.toolboks.registry.AssetRegistry import io.github.chrislo27.toolboks.registry.ScreenRegistry import io.github.chrislo27.toolboks.ui.Button import io.github.chrislo27.toolboks.ui.ImageLabel import io.github.chrislo27.toolboks.ui.Stage import io.github.chrislo27.toolboks.ui.TextLabel import io.github.chrislo27.toolboks.version.Version import kotlinx.coroutines.* import org.eclipse.jgit.api.errors.TransportException import org.eclipse.jgit.lib.ProgressMonitor class GitUpdateScreen(main: RHRE3Application) : ToolboksScreen<RHRE3Application, GitUpdateScreen>(main) { override val stage: Stage<GitUpdateScreen> = GenericStage(main.uiPalette, null, main.defaultCamera) private val label: TextLabel<GitUpdateScreen> @Volatile private var repoStatus: RepoStatus = RepoStatus.UNKNOWN @Volatile private var coroutine: Job? = null private val spinner: LoadingIcon<GitUpdateScreen> init { stage as GenericStage val palette = main.uiPalette stage.titleLabel.setText("screen.database.title") label = TextLabel(palette, stage.centreStage, stage.centreStage) label.setText("", Align.center, wrapping = true, isLocalization = false) stage.centreStage.elements += label spinner = LoadingIcon(palette, stage.centreStage).apply { this.renderType = ImageLabel.ImageRendering.ASPECT_RATIO this.location.set(screenHeight = 0.125f, screenY = 0.125f / 2f) } stage.centreStage.elements += spinner stage.bottomStage.elements += object : Button<GitUpdateScreen>(palette, stage.bottomStage, stage.bottomStage) { override fun onLeftClick(xPercent: Float, yPercent: Float) { super.onLeftClick(xPercent, yPercent) Gdx.net.openURI(if (repoStatus == RepoStatus.NO_INTERNET_CANNOT_CONTINUE) RHRE3.GITHUB_RELEASES else RHRE3.DATABASE_RELEASES) } private var setToReleases = false override fun frameUpdate(screen: GitUpdateScreen) { if (repoStatus == RepoStatus.NO_INTERNET_CANNOT_CONTINUE && !setToReleases) { (labels.first() as TextLabel).text = "screen.version.viewChangelog" setToReleases = true } super.frameUpdate(screen) } }.apply { this.addLabel(TextLabel(palette, this, this.stage).apply { this.isLocalizationKey = true this.textWrapping = false this.text = "screen.info.database" // this.fontScaleMultiplier = 0.9f }) this.location.set(screenX = 0.15f, screenWidth = 0.7f) } stage.updatePositions() } fun fetch() { if (repoStatus == RepoStatus.DOING) return val nano = System.nanoTime() repoStatus = RepoStatus.UNKNOWN coroutine = GlobalScope.launch { repoStatus = RepoStatus.DOING val lastVersion = main.preferences.getInteger(PreferenceKeys.DATABASE_VERSION_BRANCH, -1) main.preferences.putInteger(PreferenceKeys.DATABASE_VERSION_BRANCH, -1).flush() fun restoreDatabaseVersion() { main.preferences.putInteger(PreferenceKeys.DATABASE_VERSION_BRANCH, lastVersion).flush() } try { if ((!RHRE3.forceGitFetch && RHRE3.DATABASE_BRANCH != RHRE3.DEV_DATABASE_BRANCH) || RHRE3.forceGitCheck) { label.text = Localization["screen.database.checkingGithub"] try { val current = JsonHandler.fromJson<SfxDbInfoObject>(RHRE3Application.httpClient.prepareGet(RHRE3.DATABASE_CURRENT_VERSION).execute().get().responseBody) val ver: Version = Version.fromString(current.requiresVersion) Toolboks.LOGGER.info("Pulled SFXDB version from GitHub in ${(System.nanoTime() - nano) / 1_000_000f} ms, got ${current.version} vs real $lastVersion") if (ver > RHRE3.VERSION) { label.text = Localization["screen.database.incompatibleVersion${if (lastVersion >= 0) ".canContinue" else ""}", current.requiresVersion] repoStatus = if (lastVersion < 0) RepoStatus.NO_INTERNET_CANNOT_CONTINUE else RepoStatus.NO_INTERNET_CAN_CONTINUE Toolboks.LOGGER.info("Incompatible SFXDB versions: requires ${current.requiresVersion}, have ${RHRE3.VERSION}") restoreDatabaseVersion() return@launch } } catch (e: Exception) { e.printStackTrace() restoreDatabaseVersion() repoStatus = RepoStatus.ERROR label.text = Localization["screen.database.error"] return@launch } } GitHelper.ensureRemoteExists() GitHelper.fetchOrClone(GitScreenProgressMonitor(this@GitUpdateScreen, !GitHelper.doesGitFolderExist())) repoStatus = RepoStatus.DONE run { val str = GitHelper.SOUNDS_DIR.child("current.json").readString("UTF-8") val obj = JsonHandler.fromJson<SfxDbInfoObject>(str) if (obj.version < 0) error("Current database version json object has a negative version of ${obj.version}") main.preferences.putInteger(PreferenceKeys.DATABASE_VERSION_BRANCH, obj.version).flush() } val time = (System.nanoTime() - nano) / 1_000_000.0 Toolboks.LOGGER.info("Finished fetch/clone in $time ms") } catch (te: TransportException) { te.printStackTrace() try { GitHelper.ensureRemoteExists() GitHelper.reset() } catch (e: Exception) { e.printStackTrace() } repoStatus = if (lastVersion < 0) RepoStatus.NO_INTERNET_CANNOT_CONTINUE else RepoStatus.NO_INTERNET_CAN_CONTINUE label.text = Localization["screen.database.transportException." + if (lastVersion < 0) "failed" else "safe"] restoreDatabaseVersion() } catch (e: Exception) { e.printStackTrace() try { GitHelper.ensureRemoteExists() GitHelper.reset() } catch (e2: Exception) { e2.printStackTrace() GitHelper.SOUNDS_DIR.deleteDirectory() } repoStatus = RepoStatus.ERROR label.text = Localization["screen.database.error"] main.preferences.putInteger(PreferenceKeys.DATABASE_VERSION_BRANCH, -1).flush() } } } private enum class RepoStatus { UNKNOWN, DOING, DONE, ERROR, NO_INTERNET_CAN_CONTINUE, NO_INTERNET_CANNOT_CONTINUE, INCOMPAT_VERSION } class GitScreenProgressMonitor(val screen: GitUpdateScreen, val clone: Boolean) : ProgressMonitor { enum class SpecialState(val localization: String?) { NONE(null), CLONING("screen.database.state.cloning"), FETCHING("screen.database.state.fetching"), RESETTING("screen.database.state.resetting") } var currentSpecialState: SpecialState = SpecialState.NONE set(value) { field = value Gdx.app.postRunnable { updateLabel() } } var currentTask: Int = 0 var completedTaskWork: Int = 0 var taskTotalWork: Int = ProgressMonitor.UNKNOWN var task: String? = "" set(value) { field = (if (clone) "Performing first-time SFX Database setup...\nThis will take a while.\n\n" else "") + if (value == "Updating references") { "Updating references (please be patient)" } else { value } } init { updateLabel() } private fun updateLabel() { screen.label.text = "${currentSpecialState.localization?.let { Localization[it] } ?: ""}\n\n${task ?: Localization["screen.database.pending"]}\n" + "$completedTaskWork / $taskTotalWork\n" + Localization["screen.database.tasksCompleted", currentTask] } override fun update(completed: Int) { completedTaskWork += completed updateLabel() } override fun start(totalTasks: Int) { updateLabel() } override fun beginTask(title: String?, totalWork: Int) { currentTask++ task = title completedTaskWork = 0 taskTotalWork = totalWork updateLabel() } override fun endTask() { updateLabel() } override fun isCancelled(): Boolean { return false } } private fun toNextScreen() { main.screen = ScreenRegistry["sfxdbLoad"] } override fun renderUpdate() { super.renderUpdate() spinner.visible = repoStatus == RepoStatus.DOING if ((Gdx.input.isKeyJustPressed(Input.Keys.ENTER) && (repoStatus == RepoStatus.NO_INTERNET_CAN_CONTINUE)) || repoStatus == RepoStatus.DONE || (RHRE3.DATABASE_BRANCH == RHRE3.DEV_DATABASE_BRANCH && Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE))) { coroutine?.cancel() coroutine = null toNextScreen() } } override fun show() { super.show() stage as GenericStage if (stage.titleIcon.image == null) { stage.titleIcon.image = TextureRegion(AssetRegistry.get<Texture>("ui_icon_updatesfx")) } fetch() } override fun hide() { super.hide() repoStatus = RepoStatus.UNKNOWN } override fun tickUpdate() { } override fun dispose() { } }
gpl-3.0
51210d3e3b57c91a1221f4f640fb580b
38.742857
176
0.596926
4.738927
false
false
false
false
StepicOrg/stepik-android
app/src/main/java/org/stepik/android/domain/base/analytic/AnalyticEventExtensions.kt
1
1153
package org.stepik.android.domain.base.analytic import android.os.Bundle import androidx.core.os.bundleOf const val BUNDLEABLE_ANALYTIC_EVENT = "bundleable_analytic_event" private const val BUNDLEABLE_EVENT_NAME = "bundleable_event_name" private const val BUNDLEABLE_EVENT_PARAMS = "bundleable_event_params" fun AnalyticEvent.toBundle(): Bundle = bundleOf( BUNDLEABLE_EVENT_NAME to name, BUNDLEABLE_EVENT_PARAMS to bundleOf(*params.map { (a, b) -> a to b }.toTypedArray()) ) fun Bundle.toAnalyticEvent(): AnalyticEvent? { val eventName = getString(BUNDLEABLE_EVENT_NAME) val eventParams = getBundle(BUNDLEABLE_EVENT_PARAMS) return if (eventName == null) { null } else { object : AnalyticEvent { override val name: String = eventName override val params: Map<String, Any> = eventParams?.let { bundle -> bundle .keySet() .mapNotNull { key -> bundle[key]?.let { value -> key to value } } .toMap() } ?: emptyMap() } } }
apache-2.0
a4393d67f521f67acf6297a17a7b416d
31.055556
92
0.596704
4.350943
false
false
false
false
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/rhre3/sfxdb/Game.kt
2
5375
package io.github.chrislo27.rhre3.sfxdb import com.badlogic.gdx.files.FileHandle import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.utils.Disposable import io.github.chrislo27.rhre3.sfxdb.datamodel.Datamodel import io.github.chrislo27.rhre3.sfxdb.datamodel.DatamodelComparator import io.github.chrislo27.rhre3.sfxdb.datamodel.ResponseModel import io.github.chrislo27.toolboks.registry.AssetRegistry import java.util.* data class Game(val id: String, val rawName: String, val series: Series, val objects: List<Datamodel>, val iconFh: FileHandle, val language: Language?, val group: String, val groupDefault: Boolean, val priority: Int, val isCustom: Boolean, val noDisplay: Boolean, val searchHints: List<String>, val jsonless: Boolean, val isSpecial: Boolean) : Disposable, Comparable<Game> { val name: String = if (language != null) "$rawName (${language.langName})" else rawName val lowerCaseName: String = name.toLowerCase(Locale.ROOT) val searchHintsAsSet: Set<String> = searchHints.map { it.toLowerCase(Locale.ROOT) }.toMutableSet().also { set -> if (series == Series.FEVER) { set += "wii" } else if (series == Series.MEGAMIX) { set += "3ds" } } val placeableObjects: List<Datamodel> by lazy { objects.filter { !it.hidden }.sortedWith(DatamodelComparator) } val hasCallAndResponse: Boolean by lazy { placeableObjects.any { it is ResponseModel && it.responseIDs.isNotEmpty() } } val objectsMap: Map<String, Datamodel> by lazy { objects.associateBy { it.id } + objects.filter { it.deprecatedIDs.isNotEmpty() }.flatMap { it.deprecatedIDs.map { dep -> dep to it } } } val placeableObjectsMap: Map<String, Datamodel> by lazy { placeableObjects.associateBy { it.id } + objects.filter { it.deprecatedIDs.isNotEmpty() }.flatMap { it.deprecatedIDs.map { dep -> dep to it } } } val gameGroup: GameGroup get() = SFXDatabase.data.gameGroupsMap[group] ?: error("No valid game group for $id with group $group") val isFavourited: Boolean get() = GameMetadata.isGameFavourited(this) val recency: Int get() = GameMetadata.recents.indexOf(this) val isRecent: Boolean get() = recency != -1 val icon: Texture = if (language != null && !(id.startsWith("countIn") && id.length == 9 /* Count-In games don't get a language code baked in */)) { // Add on language code val pixmap = Pixmap(if (iconFh.exists()) iconFh else FileHandle(AssetRegistry.assetMap.getValue("sfxdb_missing_icon"))) // Draw language code val langPixmap: Pixmap = AssetRegistry["sfxdb_langicon_${language.code}_pixmap"] pixmap.drawPixmap(langPixmap, 0, 0, langPixmap.width, langPixmap.height, 0, 0, pixmap.width, pixmap.height) val newTex = Texture(pixmap) pixmap.dispose() newTex } else if (!iconFh.exists()) { AssetRegistry["sfxdb_missing_icon"] } else { Texture(iconFh) } override fun compareTo(other: Game): Int { return GameGroupListComparator.compare(this, other) } override fun dispose() { objects.forEach(Disposable::dispose) if (!icon.isManaged) { icon.dispose() } } } object GameByNameComparator : Comparator<Game> { override fun compare(o1: Game?, o2: Game?): Int { if (o1 == null && o2 == null) { return 0 } else if (o1 == null) { return -1 } else if (o2 == null) { return 1 } // higher priorities are first if (o1.priority > o2.priority) { return -1 } else if (o2.priority > o1.priority) { return 1 } return o1.name.compareTo(o2.name) } } object GameGroupListComparatorIgnorePriority : Comparator<Game> { override fun compare(o1: Game?, o2: Game?): Int { if (o1 == null && o2 == null) { return 0 } else if (o1 == null) { return -1 } else if (o2 == null) { return 1 } if (o1.group == o2.group) { return when { o1.groupDefault -> -1 o2.groupDefault -> 1 else -> o1.id.compareTo(o2.id) } } return o1.id.compareTo(o2.id) } } object GameGroupListComparator : Comparator<Game> { override fun compare(o1: Game?, o2: Game?): Int { if (o1 == null && o2 == null) { return 0 } else if (o1 == null) { return -1 } else if (o2 == null) { return 1 } // higher priorities are first if (o1.priority > o2.priority) { return -1 } else if (o2.priority > o1.priority) { return 1 } if (o1.group == o2.group) { return when { o1.groupDefault -> -1 o2.groupDefault -> 1 else -> o1.id.compareTo(o2.id) } } return o1.id.compareTo(o2.id) } } fun MutableList<Game>.sortByName() { this.sortWith(GameByNameComparator) } fun List<Game>.sortedByName(): List<Game> { return this.sortedWith(GameByNameComparator) }
gpl-3.0
e456af8525a6c6850d82ce652d04b56f
31.575758
152
0.596465
3.858579
false
false
false
false
android/wear-os-samples
DataLayer/Application/src/main/java/com/example/android/wearable/datalayer/ClientDataViewModel.kt
1
3124
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.wearable.datalayer import android.graphics.Bitmap import androidx.annotation.StringRes import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import com.google.android.gms.wearable.CapabilityClient import com.google.android.gms.wearable.CapabilityInfo import com.google.android.gms.wearable.DataClient import com.google.android.gms.wearable.DataEvent import com.google.android.gms.wearable.DataEventBuffer import com.google.android.gms.wearable.MessageClient import com.google.android.gms.wearable.MessageEvent /** * A state holder for the client data. */ class ClientDataViewModel : ViewModel(), DataClient.OnDataChangedListener, MessageClient.OnMessageReceivedListener, CapabilityClient.OnCapabilityChangedListener { private val _events = mutableStateListOf<Event>() /** * The list of events from the clients. */ val events: List<Event> = _events /** * The currently captured image (if any), available to send to the wearable devices. */ var image by mutableStateOf<Bitmap?>(null) private set override fun onDataChanged(dataEvents: DataEventBuffer) { _events.addAll( dataEvents.map { dataEvent -> val title = when (dataEvent.type) { DataEvent.TYPE_CHANGED -> R.string.data_item_changed DataEvent.TYPE_DELETED -> R.string.data_item_deleted else -> R.string.data_item_unknown } Event( title = title, text = dataEvent.dataItem.toString() ) } ) } override fun onMessageReceived(messageEvent: MessageEvent) { _events.add( Event( title = R.string.message_from_watch, text = messageEvent.toString() ) ) } override fun onCapabilityChanged(capabilityInfo: CapabilityInfo) { _events.add( Event( title = R.string.capability_changed, text = capabilityInfo.toString() ) ) } fun onPictureTaken(bitmap: Bitmap?) { image = bitmap ?: return } } /** * A data holder describing a client event. */ data class Event( @StringRes val title: Int, val text: String )
apache-2.0
2e510d75b5e6ecdb14f8cc80d062df05
29.930693
88
0.664853
4.520984
false
false
false
false
glodanif/BluetoothChat
app/src/main/kotlin/com/glodanif/bluetoothchat/ui/activity/SettingsActivity.kt
1
4766
package com.glodanif.bluetoothchat.ui.activity import android.app.AlertDialog import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.view.View import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import androidx.annotation.ColorInt import androidx.appcompat.app.AppCompatDelegate.* import com.glodanif.bluetoothchat.R import com.glodanif.bluetoothchat.ui.presenter.SettingsPresenter import com.glodanif.bluetoothchat.ui.util.ThemeHolder import com.glodanif.bluetoothchat.ui.view.SettingsView import com.glodanif.bluetoothchat.ui.widget.SwitchPreference import com.glodanif.bluetoothchat.utils.bind import me.priyesh.chroma.ChromaDialog import me.priyesh.chroma.ColorMode import me.priyesh.chroma.ColorSelectListener import org.koin.android.ext.android.inject import org.koin.core.parameter.parametersOf class SettingsActivity : SkeletonActivity(), SettingsView { private val presenter: SettingsPresenter by inject { parametersOf(this, application as ThemeHolder) } private val colorPreview: View by bind(R.id.v_color) private val notificationsHeader: TextView by bind(R.id.tv_notifications_header) private val nightModeSubtitle: TextView by bind(R.id.tv_night_mode) private val soundPreference: SwitchPreference by bind(R.id.sp_sound) private val classificationPreference: SwitchPreference by bind(R.id.sp_class_filter) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings, ActivityType.CHILD_ACTIVITY) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationsHeader.visibility = View.GONE soundPreference.visibility = View.GONE } else { soundPreference.listener = { presenter.onNewSoundPreference(it) } } classificationPreference.listener = { presenter.onNewClassificationPreference(it) } findViewById<RelativeLayout>(R.id.rl_chat_bg_color_button).setOnClickListener { presenter.prepareColorPicker() } findViewById<LinearLayout>(R.id.ll_night_mode_button).setOnClickListener { presenter.prepareNightModePicker() } presenter.loadPreferences() } override fun displayNotificationSetting(sound: Boolean) { soundPreference.setChecked(sound) } override fun displayBgColorSettings(@ColorInt color: Int) { colorPreview.setBackgroundColor(color) } override fun displayNightModeSettings(@NightMode nightMode: Int) { val modeLabelText = when (nightMode) { MODE_NIGHT_YES -> R.string.settings__night_mode_on MODE_NIGHT_NO -> R.string.settings__night_mode_off MODE_NIGHT_FOLLOW_SYSTEM -> R.string.settings__night_mode_system else -> R.string.settings__night_mode_off } nightModeSubtitle.setText(modeLabelText) } override fun displayDiscoverySetting(classification: Boolean) { classificationPreference.setChecked(classification) } override fun displayColorPicker(@ColorInt color: Int) { ChromaDialog.Builder() .initialColor(color) .colorMode(ColorMode.RGB) .onColorSelected(colorSelectListener) .create() .show(supportFragmentManager, "ChromaDialog") } override fun displayNightModePicker(nightMode: Int) { val items = arrayOf<CharSequence>( getString(R.string.settings__night_mode_on), getString(R.string.settings__night_mode_off), getString(R.string.settings__night_mode_system) ) val modes = arrayOf(MODE_NIGHT_YES, MODE_NIGHT_NO, MODE_NIGHT_FOLLOW_SYSTEM) AlertDialog.Builder(this).apply { setSingleChoiceItems(items, modes.indexOf(nightMode)) { dialog, which -> presenter.onNewNightModePreference(modes[which]) dialog.dismiss() } setNegativeButton(R.string.general__cancel, null) setTitle(R.string.settings__night_mode) }.show() } private val colorSelectListener = object : ColorSelectListener { override fun onColorSelected(color: Int) { presenter.onNewColorPicked(color) } } override fun onBackPressed() { if (presenter.isNightModeChanged()) { ConversationsActivity.start(this, clearTop = true) } else { super.onBackPressed() } } companion object { fun start(context: Context) { context.startActivity(Intent(context, SettingsActivity::class.java)) } } }
apache-2.0
b8cae203e6806eb94aa9df5335b9fa7b
35.106061
154
0.69786
4.587103
false
false
false
false
CORDEA/MackerelClient
app/src/main/java/jp/cordea/mackerelclient/McApplication.kt
1
2216
package jp.cordea.mackerelclient import android.app.Activity import android.app.Application import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import io.realm.Realm import io.realm.RealmConfiguration import jp.cordea.mackerelclient.model.DisplayHostState import javax.inject.Inject class McApplication : Application(), HasActivityInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity> override fun onCreate() { super.onCreate() Realm.init(this) Realm.setDefaultConfiguration( RealmConfiguration.Builder() .schemaVersion(SCHEMA_VERSION) .migration { dynamicRealm, old, _ -> val scheme = dynamicRealm.schema var oldVersion = old if (oldVersion == 0L) { scheme[DisplayHostState::class.java.simpleName]!! .addField("new_name", String::class.java) .transform { it.setString("new_name", it.getString("name")) } .removeField("name") .addPrimaryKey("new_name") .renameField("new_name", "name") ++oldVersion } if (oldVersion == 1L) { scheme[DisplayHostState::class.java.simpleName]!! .removePrimaryKey() .setRequired(DisplayHostState::name.name, true) .addIndex(DisplayHostState::name.name) .addPrimaryKey(DisplayHostState::name.name) ++oldVersion } }.build() ) DaggerAppComponent .builder() .application(this) .build() .inject(this) } override fun activityInjector(): AndroidInjector<Activity> = dispatchingAndroidInjector companion object { private const val SCHEMA_VERSION = 2L } }
apache-2.0
2b01b8c1746aa26753fcab74eefd8e6c
34.741935
91
0.540614
5.862434
false
false
false
false
pzhangleo/android-base
base/src/main/java/hope/base/extensions/LogExtensions.kt
1
708
@file:JvmName("LogExtensions") package hope.base.extensions import hope.base.log.ZLog fun String.logd(tag: String? = null) { if (tag.isNullOrEmpty()) { ZLog.d(this) } else { ZLog.tag(tag).d(this) } } fun String.logv(tag: String? = null) { if (tag.isNullOrEmpty()) { ZLog.v(this) } else { ZLog.tag(tag).v(this) } } fun String.logi(tag: String? = null) { if (tag.isNullOrEmpty()) { ZLog.i(this) } else { ZLog.tag(tag).i(this) } } fun String.loge(tag: String? = null, throwable: Throwable? = null) { if (tag.isNullOrEmpty()) { ZLog.e(this, throwable) } else { ZLog.tag(tag).e(this, throwable) } }
lgpl-3.0
c71629b06f73bdd1fd2557a1bf140186
18.666667
68
0.562147
3.051724
false
false
false
false
leafclick/intellij-community
plugins/git4idea/src/git4idea/history/GitDetailsCollector.kt
1
6345
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.history import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ArrayUtil import com.intellij.util.Consumer import com.intellij.vcs.log.VcsCommitMetadata import com.intellij.vcs.log.VcsLogObjectsFactory import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcs.log.util.StopWatch import git4idea.GitCommit import git4idea.GitVcs import git4idea.commands.Git import git4idea.commands.GitLineHandler internal abstract class GitDetailsCollector<R : GitLogRecord, C : VcsCommitMetadata>(protected val project: Project, protected val root: VirtualFile, private val recordBuilder: GitLogRecordBuilder<R>) { private val LOG = Logger.getInstance(GitDetailsCollector::class.java) private val vcs = GitVcs.getInstance(project) @Throws(VcsException::class) fun readFullDetails(commitConsumer: Consumer<in C>, requirements: GitCommitRequirements, lowPriorityProcess: Boolean, vararg parameters: String) { val configParameters = requirements.configParameters() val handler = GitLogUtil.createGitHandler(project, root, configParameters, lowPriorityProcess) readFullDetailsFromHandler(commitConsumer, handler, requirements, *parameters) } @Throws(VcsException::class) fun readFullDetailsForHashes(hashes: List<String>, requirements: GitCommitRequirements, lowPriorityProcess: Boolean, commitConsumer: Consumer<in C>) { if (hashes.isEmpty()) return val handler = GitLogUtil.createGitHandler(project, root, requirements.configParameters(), lowPriorityProcess) GitLogUtil.sendHashesToStdin(vcs, hashes, handler) readFullDetailsFromHandler(commitConsumer, handler, requirements, GitLogUtil.getNoWalkParameter(vcs), GitLogUtil.STDIN) } @Throws(VcsException::class) private fun readFullDetailsFromHandler(commitConsumer: Consumer<in C>, handler: GitLineHandler, requirements: GitCommitRequirements, vararg parameters: String) { val factory = GitLogUtil.getObjectsFactoryWithDisposeCheck(project) ?: return val commandParameters = ArrayUtil.mergeArrays(ArrayUtil.toStringArray(requirements.commandParameters()), *parameters) if (requirements.diffInMergeCommits == GitCommitRequirements.DiffInMergeCommits.DIFF_TO_PARENTS) { val consumer = { records: List<R> -> val firstRecord = records.first() val parents = firstRecord.parentsHashes if (parents.isEmpty() || parents.size == records.size) { commitConsumer.consume(createCommit(records, factory, requirements.diffRenameLimit)) } else { LOG.warn("Not enough records for commit ${firstRecord.hash} " + "expected ${parents.size} records, but got ${records.size}") } } val recordCollector = createRecordsCollector(consumer) readRecordsFromHandler(handler, recordCollector, *commandParameters) recordCollector.finish() } else { val consumer = Consumer<R> { record -> commitConsumer.consume(createCommit(mutableListOf(record), factory, requirements.diffRenameLimit)) } readRecordsFromHandler(handler, consumer, *commandParameters) } } @Throws(VcsException::class) private fun readRecordsFromHandler(handler: GitLineHandler, converter: Consumer<R>, vararg parameters: String) { val parser = GitLogParser(project, recordBuilder, GitLogParser.NameStatus.STATUS, *GitLogUtil.COMMIT_METADATA_OPTIONS) handler.setStdoutSuppressed(true) handler.addParameters(*parameters) handler.addParameters(parser.pretty, "--encoding=UTF-8") handler.addParameters("--name-status") handler.endOptions() val sw = StopWatch.start("loading details in [" + root.name + "]") val handlerListener = GitLogOutputSplitter<R>(handler, parser, converter) Git.getInstance().runCommandWithoutCollectingOutput(handler).throwOnError() handlerListener.reportErrors() sw.report() } protected abstract fun createRecordsCollector(consumer: (List<R>) -> Unit): GitLogRecordCollector<R> protected abstract fun createCommit(records: List<R>, factory: VcsLogObjectsFactory, renameLimit: GitCommitRequirements.DiffRenameLimit): C } internal class GitFullDetailsCollector(project: Project, root: VirtualFile, recordBuilder: GitLogRecordBuilder<GitLogFullRecord>) : GitDetailsCollector<GitLogFullRecord, GitCommit>(project, root, recordBuilder) { internal constructor(project: Project, root: VirtualFile) : this(project, root, DefaultGitLogFullRecordBuilder()) override fun createCommit(records: List<GitLogFullRecord>, factory: VcsLogObjectsFactory, renameLimit: GitCommitRequirements.DiffRenameLimit): GitCommit { val record = records.last() val parents = record.parentsHashes.map { factory.createHash(it) } return GitCommit(project, HashImpl.build(record.hash), parents, record.commitTime, root, record.subject, factory.createUser(record.authorName, record.authorEmail), record.fullMessage, factory.createUser(record.committerName, record.committerEmail), record.authorTimeStamp, records.map { it.statusInfos } ) } override fun createRecordsCollector(consumer: (List<GitLogFullRecord>) -> Unit): GitLogRecordCollector<GitLogFullRecord> { return object : GitLogRecordCollector<GitLogFullRecord>(project, root, consumer) { override fun createEmptyCopy(r: GitLogFullRecord): GitLogFullRecord = GitLogFullRecord(r.options, listOf(), r.isSupportsRawBody) } } }
apache-2.0
989c5e2f9a885e9a0d6085cfcb37b7a5
47.815385
140
0.692987
4.964789
false
false
false
false
RobWin/javaslang-circuitbreaker
resilience4j-kotlin/src/main/kotlin/io/github/resilience4j/kotlin/circuitbreaker/CircuitBreaker.kt
2
2150
/* * * Copyright 2019: Guido Pio Mariotti, Brad Newman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package io.github.resilience4j.kotlin.circuitbreaker import io.github.resilience4j.circuitbreaker.CircuitBreaker import io.github.resilience4j.kotlin.isCancellation import java.util.* import java.util.concurrent.TimeUnit import kotlin.coroutines.coroutineContext /** * Decorates and executes the given suspend function [block]. */ suspend fun <T> CircuitBreaker.executeSuspendFunction(block: suspend () -> T): T { acquirePermission() val start = System.nanoTime() try { val result = block() val durationInNanos = System.nanoTime() - start onResult(durationInNanos, TimeUnit.NANOSECONDS, result) return result } catch (exception: Throwable) { if (isCancellation(coroutineContext, exception)) { releasePermission() } else { val durationInNanos = System.nanoTime() - start onError(durationInNanos, TimeUnit.NANOSECONDS, exception) } throw exception } } /** * Decorates the given *suspend* function [block] and returns it. */ fun <T> CircuitBreaker.decorateSuspendFunction(block: suspend () -> T): suspend () -> T = { executeSuspendFunction(block) } /** * Decorates and executes the given function [block]. */ fun <T> CircuitBreaker.executeFunction(block: () -> T): T { return this.decorateCallable(block).call() } /** * Decorates the given function [block] and returns it. */ fun <T> CircuitBreaker.decorateFunction(block: () -> T): () -> T = { executeFunction(block) }
apache-2.0
e59f0d5fa196e2e912e58e299078246e
30.617647
91
0.693488
4.134615
false
false
false
false
AndroidX/androidx
compose/animation/animation-core/src/test/java/androidx/compose/animation/core/AnimationTestUtils.kt
3
4225
/* * 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.animation.core internal fun VectorizedAnimationSpec<AnimationVector1D>.at(time: Long): Float = getValueFromMillis( time, AnimationVector1D(0f), AnimationVector1D(1f), AnimationVector1D(0f) ).value internal fun VectorizedAnimationSpec<AnimationVector1D>.at(time: Int): Float = at(time.toLong()) internal fun VectorizedAnimationSpec<AnimationVector1D>.getValue( playTime: Long, start: Number, end: Number, startVelocity: Number ) = getValueFromMillis( playTime, AnimationVector1D(start.toFloat()), AnimationVector1D(end.toFloat()), AnimationVector1D(startVelocity.toFloat()) ).value internal fun VectorizedAnimationSpec<AnimationVector1D>.getVelocity( playTime: Long, start: Number, end: Number, startVelocity: Number ) = getVelocityFromNanos( playTime * MillisToNanos, AnimationVector1D(start.toFloat()), AnimationVector1D(end.toFloat()), AnimationVector1D(startVelocity.toFloat()) ).value /** * Returns the value of the animation at the given play time. * * @param playTimeMillis the play time that is used to determine the value of the animation. */ internal fun <T> Animation<T, *>.getValueFromMillis(playTimeMillis: Long): T = getValueFromNanos(playTimeMillis * MillisToNanos) /** * Returns the velocity (in [AnimationVector] form) of the animation at the given play time. * * @param playTimeMillis the play time that is used to calculate the velocity of the animation. */ internal fun <V : AnimationVector> Animation<*, V>.getVelocityVectorFromMillis( playTimeMillis: Long ): V = getVelocityVectorFromNanos(playTimeMillis * MillisToNanos) /** * Returns whether the animation is finished at the given play time. * * @param playTimeMillis the play time used to determine whether the animation is finished. */ internal fun Animation<*, *>.isFinishedFromMillis(playTimeMillis: Long): Boolean { return playTimeMillis >= durationMillis } internal fun <T, V : AnimationVector> Animation<T, V>.getVelocityFromMillis( playTimeMillis: Long ): T = typeConverter.convertFromVector(getVelocityVectorFromMillis(playTimeMillis)) internal fun FloatAnimationSpec.getDurationMillis( start: Float, end: Float, startVelocity: Float ): Long = getDurationNanos(start, end, startVelocity) / MillisToNanos /** * Calculates the value of the animation at given the playtime, with the provided start/end * values, and start velocity. * * @param playTimeMillis time since the start of the animation * @param start start value of the animation * @param end end value of the animation * @param startVelocity start velocity of the animation */ // TODO: bring all tests on to `getValueFromNanos` internal fun FloatAnimationSpec.getValueFromMillis( playTimeMillis: Long, start: Float, end: Float, startVelocity: Float ): Float = getValueFromNanos(playTimeMillis * MillisToNanos, start, end, startVelocity) /** * Calculates the velocity of the animation at given the playtime, with the provided start/end * values, and start velocity. * * @param playTimeMillis time since the start of the animation * @param start start value of the animation * @param end end value of the animation * @param startVelocity start velocity of the animation */ // TODO: bring all tests on to `getVelocityFromNanos` internal fun FloatAnimationSpec.getVelocityFromMillis( playTimeMillis: Long, start: Float, end: Float, startVelocity: Float ): Float = getVelocityFromNanos(playTimeMillis * MillisToNanos, start, end, startVelocity)
apache-2.0
1fc920ac3730c5dfb2e2c02f0fefdf19
33.917355
96
0.748166
4.38278
false
false
false
false
codeka/wwmmo
server/src/main/kotlin/au/com/codeka/warworlds/server/html/account/ConnectToPatreonHandler.kt
1
1828
package au.com.codeka.warworlds.server.html.account import au.com.codeka.warworlds.common.proto.PatreonBeginRequest import au.com.codeka.warworlds.server.Configuration import au.com.codeka.warworlds.server.Configuration.PatreonConfig import au.com.codeka.warworlds.server.handlers.ProtobufRequestHandler import au.com.codeka.warworlds.server.handlers.RequestException import au.com.codeka.warworlds.server.proto.PatreonInfo import au.com.codeka.warworlds.server.store.DataStore import au.com.codeka.warworlds.server.world.EmpireManager import com.google.common.io.BaseEncoding import com.patreon.PatreonOAuth class ConnectToPatreonHandler : ProtobufRequestHandler() { /** * Handler for where the client gets redirected to after successfully doing the oauth handshake. */ public override fun get() { val code = request.getParameter("code") val state = request.getParameter("state") val patreonConfig: PatreonConfig = Configuration.i.patreon ?: throw RequestException(500, "Patreon not configured.") val oauthClient = PatreonOAuth(patreonConfig.clientId, patreonConfig.clientSecret, patreonConfig.redirectUri) val tokens = oauthClient.getTokens(code) val req = PatreonBeginRequest.ADAPTER.decode(BaseEncoding.base64().decode(state)) // Set up an empty PatreonInfo, that we'll then populate. val patreonInfo = PatreonInfo( empire_id = req.empire_id, access_token = tokens.accessToken, refresh_token = tokens.refreshToken, token_expiry_time = tokens.expiresIn.toLong(), token_type = tokens.tokenType, token_scope = tokens.scope) DataStore.i.empires().savePatreonInfo(req.empire_id, patreonInfo) val empire = EmpireManager.i.getEmpire(req.empire_id) EmpireManager.i.refreshPatreonInfo(empire, patreonInfo) } }
mit
3c243fef726837c17bdd3b9201cc23ef
44.7
99
0.766411
4.026432
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownProcessor.kt
1
9030
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.pushDown import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewDescriptor import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.pullUp.* import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.types.substitutions.getTypeSubstitutor import org.jetbrains.kotlin.utils.keysToMap class KotlinPushDownContext( val sourceClass: KtClass, val membersToMove: List<KotlinMemberInfo> ) { val resolutionFacade = sourceClass.getResolutionFacade() val sourceClassContext = resolutionFacade.analyzeWithAllCompilerChecks(sourceClass).bindingContext val sourceClassDescriptor = sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, sourceClass] as ClassDescriptor val memberDescriptors = membersToMove.map { it.member }.keysToMap { when (it) { is KtPsiClassWrapper -> it.psiClass.getJavaClassDescriptor(resolutionFacade)!! else -> sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]!! } } } class KotlinPushDownProcessor( project: Project, sourceClass: KtClass, membersToMove: List<KotlinMemberInfo> ) : BaseRefactoringProcessor(project) { private val context = KotlinPushDownContext(sourceClass, membersToMove) inner class UsageViewDescriptorImpl : UsageViewDescriptor { override fun getProcessedElementsHeader() = RefactoringBundle.message("push.down.members.elements.header") override fun getElements() = arrayOf(context.sourceClass) override fun getCodeReferencesText(usagesCount: Int, filesCount: Int) = RefactoringBundle.message("classes.to.push.down.members.to", UsageViewBundle.getReferencesString(usagesCount, filesCount)) override fun getCommentReferencesText(usagesCount: Int, filesCount: Int) = null } class SubclassUsage(element: PsiElement) : UsageInfo(element) override fun getCommandName() = PUSH_MEMBERS_DOWN override fun createUsageViewDescriptor(usages: Array<out UsageInfo>) = UsageViewDescriptorImpl() override fun getBeforeData() = RefactoringEventData().apply { addElement(context.sourceClass) addElements(context.membersToMove.map { it.member }.toTypedArray()) } override fun getAfterData(usages: Array<out UsageInfo>) = RefactoringEventData().apply { addElements(usages.mapNotNull { it.element as? KtClassOrObject }) } override fun findUsages(): Array<out UsageInfo> { return HierarchySearchRequest(context.sourceClass, context.sourceClass.useScope, false).searchInheritors() .mapNotNull { it.unwrapped } .map(::SubclassUsage) .toTypedArray() } override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean { val usages = refUsages.get() ?: UsageInfo.EMPTY_ARRAY if (usages.isEmpty()) { val message = KotlinBundle.message("text.0.have.no.inheritors.warning", context.sourceClassDescriptor.renderForConflicts()) val answer = Messages.showYesNoDialog(message.capitalize(), PUSH_MEMBERS_DOWN, Messages.getWarningIcon()) if (answer == Messages.NO) return false } val conflicts = myProject.runSynchronouslyWithProgress(RefactoringBundle.message("detecting.possible.conflicts"), true) { runReadAction { analyzePushDownConflicts(context, usages) } } ?: return false return showConflicts(conflicts, usages) } private fun pushDownToClass(targetClass: KtClassOrObject) { val targetClassDescriptor = context.resolutionFacade.resolveToDescriptor(targetClass) as ClassDescriptor val substitutor = getTypeSubstitutor(context.sourceClassDescriptor.defaultType, targetClassDescriptor.defaultType) ?: TypeSubstitutor.EMPTY members@ for (memberInfo in context.membersToMove) { val member = memberInfo.member val memberDescriptor = context.memberDescriptors[member] ?: continue val movedMember = when (member) { is KtProperty, is KtNamedFunction -> { memberDescriptor as CallableMemberDescriptor moveCallableMemberToClass( member as KtCallableDeclaration, memberDescriptor, targetClass, targetClassDescriptor, substitutor, memberInfo.isToAbstract ) } is KtClassOrObject, is KtPsiClassWrapper -> { if (memberInfo.overrides != null) { context.sourceClass.getSuperTypeEntryByDescriptor( memberDescriptor as ClassDescriptor, context.sourceClassContext )?.let { addSuperTypeEntry(it, targetClass, targetClassDescriptor, context.sourceClassContext, substitutor) } continue@members } else { addMemberToTarget(member, targetClass) } } else -> continue@members } applyMarking(movedMember, substitutor, targetClassDescriptor) } } private fun removeOriginalMembers() { for (memberInfo in context.membersToMove) { val member = memberInfo.member val memberDescriptor = context.memberDescriptors[member] ?: continue when (member) { is KtProperty, is KtNamedFunction -> { member as KtCallableDeclaration memberDescriptor as CallableMemberDescriptor if (memberDescriptor.modality != Modality.ABSTRACT && memberInfo.isToAbstract) { if (member.hasModifier(KtTokens.PRIVATE_KEYWORD)) { member.addModifier(KtTokens.PROTECTED_KEYWORD) } makeAbstract(member, memberDescriptor, TypeSubstitutor.EMPTY, context.sourceClass) member.typeReference?.addToShorteningWaitSet() } else { member.delete() } } is KtClassOrObject, is KtPsiClassWrapper -> { if (memberInfo.overrides != null) { context.sourceClass.getSuperTypeEntryByDescriptor( memberDescriptor as ClassDescriptor, context.sourceClassContext )?.let { context.sourceClass.removeSuperTypeListEntry(it) } } else { member.delete() } } } } } override fun performRefactoring(usages: Array<out UsageInfo>) { val markedElements = ArrayList<KtElement>() try { context.membersToMove.forEach { markedElements += markElements(it.member, context.sourceClassContext, context.sourceClassDescriptor, null) } usages.forEach { (it.element as? KtClassOrObject)?.let { pushDownToClass(it) } } removeOriginalMembers() } finally { clearMarking(markedElements) } } }
apache-2.0
de55ce389ecd2119ce88c22d0e34d0df
44.38191
158
0.669103
5.733333
false
false
false
false
zielu/GitToolBox
src/main/kotlin/zielu/gittoolbox/ResIcons.kt
1
1663
package zielu.gittoolbox import com.intellij.openapi.util.IconLoader import javax.swing.Icon internal object ResIcons { @JvmStatic val BranchOrange: Icon get() = getIcon("/zielu/gittoolbox/git-icon-orange.png") @JvmStatic val BranchViolet: Icon get() = getIcon("/zielu/gittoolbox/git-icon-violet.png") @JvmStatic val Warning: Icon get() = getIcon("/zielu/gittoolbox/exclamation-circle-frame.png") @JvmStatic val Error: Icon get() = getIcon("/zielu/gittoolbox/exclamation-red-frame.png") @JvmStatic val Ok: Icon get() = getIcon("/zielu/gittoolbox/tick-circle-frame.png") @JvmStatic val Edit: Icon get() = getIcon("/zielu/gittoolbox/edit.png") @JvmStatic val RegExp: Icon get() = getIcon("/zielu/gittoolbox/regular-expression-search.png") @JvmStatic val Commit: Icon get() = getIcon("/zielu/gittoolbox/commit.png") @JvmStatic val Blame: Icon get() = getIcon("/zielu/gittoolbox/git-icon-black.png") @JvmStatic val ChangesPresent: Icon get() = getIcon("/zielu/gittoolbox/changes-present.svg") @JvmStatic val NoChanges: Icon get() = getIcon("/zielu/gittoolbox/changes-none.svg") @JvmStatic val Logo: Icon get() = getIcon("/META-INF/pluginIcon.svg") @JvmStatic val Plus: Icon get() = getIcon("/zielu/gittoolbox/plus-button.png") @JvmStatic val Minus: Icon get() = getIcon("/zielu/gittoolbox/minus-button.png") val ArrowMerge: Icon get() = getIcon("/zielu/gittoolbox/arrow-merge-090.png") val ArrowSplit: Icon get() = getIcon("/zielu/gittoolbox/arrow-split-090.png") private fun getIcon(path: String) = IconLoader.getIcon(path, javaClass) }
apache-2.0
47823f5360881781eb642a6582faf9e5
29.236364
73
0.698136
3.545842
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DgmIteratorCallTypeCalculator.kt
12
1592
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.typing import com.intellij.openapi.util.NlsSafe import com.intellij.psi.CommonClassNames.JAVA_UTIL_ITERATOR import com.intellij.psi.CommonClassNames.JAVA_UTIL_MAP import com.intellij.psi.PsiClassType import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import com.intellij.psi.util.InheritanceUtil.isInheritor import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.createGenericType import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.ClosureParameterEnhancer.getEntryForMap import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.DEFAULT_GROOVY_METHODS import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments class DgmIteratorCallTypeCalculator : GrCallTypeCalculator { companion object { @NlsSafe private const val ITERATOR = "iterator" } override fun getType(receiver: PsiType?, method: PsiMethod, arguments: Arguments?, context: PsiElement): PsiType? { if (method.name != ITERATOR || method.containingClass?.qualifiedName != DEFAULT_GROOVY_METHODS) return null val receiverType = arguments?.singleOrNull()?.type as? PsiClassType ?: return null if (!isInheritor(receiverType, JAVA_UTIL_MAP)) return null val entryType = getEntryForMap(receiverType, context.project, context.resolveScope) return createGenericType(JAVA_UTIL_ITERATOR, context, entryType) } }
apache-2.0
6e9b30feeaa66a1be98c4ec364d74d73
47.242424
140
0.807161
4.21164
false
false
false
false
kenyee/teamcity-graphite-stats
src/main/kotlin/org/jetbrains/teamcity/rest/rest.kt
1
4128
package org.jetbrains.teamcity.rest import retrofit.client.Response import retrofit.http.* import retrofit.mime.TypedString import java.util.* internal interface TeamCityService { @Headers("Accept: application/json") @GET("/app/rest/builds") fun builds(@Query("locator") buildLocator: String?): BuildListBean @Headers("Accept: application/json") @GET("/app/rest/builds/id:{id}") fun build(@Path("id") id: String): BuildBean @Headers("Accept: application/json") @GET("/app/rest/changes") fun changes(@Query("locator") locator: String, @Query("fields") fields: String): ChangesBean @POST("/app/rest/builds/id:{id}/tags/") fun addTag(@Path("id") buildId: String, @Body tag: TypedString): Response @PUT("/app/rest/builds/id:{id}/pin/") fun pin(@Path("id") buildId: String, @Body comment: TypedString): Response @Streaming @GET("/app/rest/builds/id:{id}/artifacts/content/{path}") fun artifactContent(@Path("id") buildId: String, @Path("path") artifactPath: String): Response @Headers("Accept: application/json") @GET("/app/rest/builds/id:{id}/artifacts/children/{path}") fun artifactChildren(@Path("id") buildId: String, @Path("path") artifactPath: String): ArtifactFileListBean @Headers("Accept: application/json") @GET("/app/rest/projects/id:{id}") fun project(@Path("id") id: String): ProjectBean @Headers("Accept: application/json") @GET("/app/rest/buildTypes/id:{id}/buildTags") fun buildTypeTags(@Path("id") buildTypeId: String): TagsBean @Headers("Accept: application/json") @GET("/app/rest/buildQueue") fun queuedBuilds(@Query("locator") buildLocator: String?): QueuedBuildListBean } internal class ProjectsBean { var project: List<ProjectBean> = ArrayList() } internal class ArtifactFileListBean { var file: List<ArtifactFileBean> = ArrayList() } internal class ArtifactFileBean { var name: String? = null var size: Long? = null var modificationTime: String? = null } internal class BuildListBean { var build: List<BuildBean> = ArrayList() } internal open class BuildBean { var id: String? = null var number: String? = null var status: BuildStatus? = null var buildTypeId: String? = null var branchName : String? = null var isDefaultBranch : Boolean? = null var queuedDate: String? = null var startDate: String? = null var finishDate: String? = null var properties: ParametersBean? = ParametersBean() } internal class QueuedBuildListBean { var build: List<QueuedBuildBean> = ArrayList() } internal open class QueuedBuildBean { var id: String? = null var buildTypeId: String? = null var state: QueuedBuildStatus? = null var branchName : String? = null var isDefaultBranch : Boolean? = null var href: String? = null var webUrl: String? = null } internal class BuildTypeBean { var id: String? = null var name: String? = null var projectId: String? = null } internal class BuildTypesBean { var buildType: List<BuildTypeBean> = ArrayList() } internal class TagBean { var name: String? = null } internal class TagsBean { var tag: List<TagBean>? = ArrayList() } internal class ProjectBean { var id: String? = null var name: String? = null var parentProjectId: String? = null var archived: Boolean = false var projects: ProjectsBean? = ProjectsBean() var parameters: ParametersBean? = ParametersBean() var buildTypes: BuildTypesBean? = BuildTypesBean() } internal class ChangesBean { var change: List<ChangeBean>? = ArrayList() } internal class ChangeBean { var id: String? = null var version: String? = null var user: UserBean? = null var date: String? = null var comment: String? = null } internal class UserBean { var id: String? = null var username: String? = null var name: String? = null } internal class ParametersBean { var property: List<ParameterBean>? = ArrayList() } internal class ParameterBean { var name: String? = null var value: String? = null var own: Boolean = false }
mit
79913ffab658853da14f748c1a98d1f2
26.344371
111
0.681928
3.847158
false
false
false
false
GlobalTechnology/android-gto-support
gto-support-api-base/src/main/kotlin/org/ccci/gto/android/common/api/TheKeySession.kt
2
1294
package org.ccci.gto.android.common.api import android.content.SharedPreferences import java.util.Locale class TheKeySession private constructor( prefs: SharedPreferences?, id: String?, guid: String?, baseAttrName: String ) : Session(prefs = prefs, id = id, baseAttrName = guid.sanitizeGuid(".") + baseAttrName) { private val guid = guid?.sanitizeGuid() @JvmOverloads constructor( id: String?, guid: String?, baseAttrName: String = PREF_SESSION_BASE_NAME ) : this(prefs = null, id = id, guid = guid, baseAttrName = baseAttrName) @JvmOverloads constructor( prefs: SharedPreferences, guid: String?, baseAttrName: String = PREF_SESSION_BASE_NAME ) : this(prefs = prefs, id = null, guid = guid, baseAttrName = baseAttrName) override val isValid get() = super.isValid && guid != null override fun equals(other: Any?) = when { this === other -> true !(other is TheKeySession && javaClass == other.javaClass) -> false else -> super.equals(other) && guid == other.guid } override fun hashCode() = super.hashCode() * 31 + (guid?.hashCode() ?: 0) } private fun String?.sanitizeGuid(suffix: String = "") = if (this != null) "${uppercase(Locale.US)}$suffix" else ""
mit
f4a72fc2e48f430f5f221c3d8ea6dbd5
32.179487
114
0.644513
3.969325
false
false
false
false
google/intellij-community
plugins/eclipse/src/org/jetbrains/idea/eclipse/config/relativeModulePathSupport.kt
5
2895
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.idea.eclipse.config import com.intellij.openapi.module.impl.getModuleNameByFilePath import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsFileContentReader import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsModuleListSerializer import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.bridgeEntities.api.ContentRootEntity import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager import org.jetbrains.jps.model.serialization.JpsProjectLoader import org.jetbrains.jps.util.JpsPathUtil class ModuleRelativePathResolver(private val moduleListSerializer: JpsModuleListSerializer?, private val reader: JpsFileContentReader, private val virtualFileManager: VirtualFileUrlManager) { private val moduleFileUrls by lazy { (moduleListSerializer?.loadFileList(reader, virtualFileManager) ?: emptyList()).associateBy( { getModuleNameByFilePath(JpsPathUtil.urlToPath(it.first.url)) }, { it.first } ) } fun resolve(moduleName: String, relativePath: String?): String? { val moduleFile = moduleFileUrls[moduleName] ?: return null val component = reader.loadComponent(moduleFile.url, "DeprecatedModuleOptionManager", null) val baseDir = component?.getChildren("option") ?.firstOrNull { it.getAttributeValue("key") == JpsProjectLoader.CLASSPATH_DIR_ATTRIBUTE } ?.getAttributeValue("value") val storageRoot = getStorageRoot(moduleFile, baseDir, virtualFileManager) if (relativePath.isNullOrEmpty()) return storageRoot.url val url = "${storageRoot.url}/${relativePath.removePrefix("/")}" val file = VirtualFileManager.getInstance().findFileByUrl(url) ?: return null return JarFileSystem.getInstance().getJarRootForLocalFile(file)?.url ?: file.url } } class ModulePathShortener(private val storage: EntityStorage) { private val contentRootsToModule by lazy { storage.entities(ContentRootEntity::class.java).associateBy({ it.url.url }, { it.module.name }) } fun shortenPath(file: VirtualFile): String? { var current: VirtualFile? = file val map = contentRootsToModule while (current != null) { val moduleName = map[current.url] if (moduleName != null) { return "/$moduleName${file.url.substring(current.url.length)}" } current = current.parent } return null } fun isUnderContentRoots(file: VirtualFile): Boolean { val map = contentRootsToModule return generateSequence(file, {it.parent}).any { it.url in map } } }
apache-2.0
ca1c84af9660a021f443a23955395acd
45.693548
140
0.749914
4.816972
false
false
false
false
siosio/intellij-community
plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/script/KotlinScriptDependenciesClassFinder.kt
1
6343
// 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.core.script import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.roots.ProjectRootModificationTracker import com.intellij.openapi.util.Condition import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.* import com.intellij.psi.impl.java.stubs.index.JavaFullClassNameIndex import com.intellij.psi.search.EverythingGlobalScope import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.StubIndex import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.util.Processor import com.intellij.util.containers.ConcurrentFactoryMap import org.jetbrains.kotlin.idea.core.script.dependencies.KotlinScriptMarkerFileSystem import org.jetbrains.kotlin.resolve.jvm.KotlinSafeClassFinder class KotlinScriptDependenciesClassFinder(private val project: Project) : NonClasspathClassFinder(project), KotlinSafeClassFinder { private val useOnlyForScripts = Registry.`is`("kotlin.resolve.scripting.limit.dependency.element.finder") /* 'PsiElementFinder's are global and can be called for any context. As 'KotlinScriptDependenciesClassFinder' is meant to provide additional dependencies only for scripts, we need to know if the caller came from a script resolution context. We are doing so by checking if the given scope contains a synthetic 'KotlinScriptMarkerFileSystem.rootFile'. Normally, only global scopes and 'KotlinScriptScope' contains such a file. */ private fun isApplicable(scope: GlobalSearchScope): Boolean { return true || !useOnlyForScripts || scope.contains(KotlinScriptMarkerFileSystem.rootFile) } override fun getClassRoots(scope: GlobalSearchScope?): List<VirtualFile> { var result = super.getClassRoots(scope) if (scope is EverythingGlobalScope) { result = result + KotlinScriptMarkerFileSystem.rootFile } return result } override fun calcClassRoots(): List<VirtualFile> { return ScriptConfigurationManager.getInstance(project) .getAllScriptsDependenciesClassFiles() .filter { it.isValid } } private val everywhereCache = CachedValuesManager.getManager(project).createCachedValue { CachedValueProvider.Result.create( ConcurrentFactoryMap.createMap { qualifiedName: String -> findClassNotCached(qualifiedName, GlobalSearchScope.everythingScope(project)) }, ScriptDependenciesModificationTracker.getInstance(project), PsiModificationTracker.MODIFICATION_COUNT, ProjectRootModificationTracker.getInstance(project), VirtualFileManager.getInstance() ) } override fun findClass(qualifiedName: String, scope: GlobalSearchScope): PsiClass? { return if (isApplicable(scope)) everywhereCache.value[qualifiedName]?.takeIf { isInScope(it, scope) } else null } private fun findClassNotCached(qualifiedName: String, scope: GlobalSearchScope): PsiClass? { val topLevelClass = super.findClass(qualifiedName, scope) if (topLevelClass != null && isInScope(topLevelClass, scope)) { return topLevelClass } // The following code is needed because NonClasspathClassFinder cannot find inner classes // JavaFullClassNameIndex cannot be used directly, because it filter only classes in source roots val classes = StubIndex.getElements( JavaFullClassNameIndex.getInstance().key, qualifiedName.hashCode(), project, scope.takeUnless { it is EverythingGlobalScope }, PsiClass::class.java ).filter { it.qualifiedName == qualifiedName } return when (classes.size) { 0 -> null 1 -> classes.single() else -> classes.first() // todo: check when this happens }?.takeIf { isInScope(it, scope) } } private fun isInScope(clazz: PsiClass, scope: GlobalSearchScope): Boolean { if (scope is EverythingGlobalScope) { return true } val file = clazz.containingFile?.virtualFile ?: return false val index = ProjectFileIndex.SERVICE.getInstance(myProject) return !index.isInContent(file) && !index.isInLibrary(file) && scope.contains(file) } override fun findClasses(qualifiedName: String, scope: GlobalSearchScope): Array<PsiClass> { return if (isApplicable(scope)) super.findClasses(qualifiedName, scope) else emptyArray() } override fun getSubPackages(psiPackage: PsiPackage, scope: GlobalSearchScope): Array<PsiPackage> { return if (isApplicable(scope)) super.getSubPackages(psiPackage, scope) else emptyArray() } override fun getClasses(psiPackage: PsiPackage, scope: GlobalSearchScope): Array<PsiClass> { return if (isApplicable(scope)) super.getClasses(psiPackage, scope) else emptyArray() } override fun getPackageFiles(psiPackage: PsiPackage, scope: GlobalSearchScope): Array<PsiFile> { return if (isApplicable(scope)) super.getPackageFiles(psiPackage, scope) else emptyArray() } override fun getPackageFilesFilter(psiPackage: PsiPackage, scope: GlobalSearchScope): Condition<PsiFile>? { return if (isApplicable(scope)) super.getPackageFilesFilter(psiPackage, scope) else null } override fun getClassNames(psiPackage: PsiPackage, scope: GlobalSearchScope): Set<String> { return if (isApplicable(scope)) super.getClassNames(psiPackage, scope) else emptySet() } override fun processPackageDirectories( psiPackage: PsiPackage, scope: GlobalSearchScope, consumer: Processor<in PsiDirectory>, includeLibrarySources: Boolean ): Boolean { return if (isApplicable(scope)) super.processPackageDirectories(psiPackage, scope, consumer, includeLibrarySources) else true } }
apache-2.0
10be3e9f0265733a8ed1c5e6ddab210b
45.647059
158
0.730569
5.161107
false
false
false
false
siosio/intellij-community
plugins/markdown/src/org/intellij/plugins/markdown/editor/lists/MarkdownListIndentProvider.kt
1
2938
package org.intellij.plugins.markdown.editor.lists import com.intellij.codeInsight.editorActions.AutoHardWrapHandler import com.intellij.lang.Language import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.impl.source.codeStyle.lineIndent.FormatterBasedLineIndentProvider import com.intellij.psi.util.PsiEditorUtil import com.intellij.psi.util.parentOfTypes import com.intellij.refactoring.suggested.startOffset import org.intellij.plugins.markdown.editor.lists.ListUtils.getLineIndentRange import org.intellij.plugins.markdown.editor.lists.ListUtils.getListItemAtLineSafely import com.intellij.util.text.CharArrayUtil import org.intellij.plugins.markdown.lang.MarkdownLanguage import org.intellij.plugins.markdown.lang.psi.impl.MarkdownBlockQuoteImpl import org.intellij.plugins.markdown.lang.psi.impl.MarkdownCodeFenceImpl import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile /** * This is a helper class for the [MarkdownListEnterHandlerDelegate] to provide correct indentation for new lines, created on Enter. * * [FormatterBasedLineIndentProvider] is extended to be able to fallback to the default behaviour */ internal class MarkdownListIndentProvider : FormatterBasedLineIndentProvider() { override fun getLineIndent(project: Project, editor: Editor, language: Language?, offset: Int): String? { val file = PsiEditorUtil.getPsiFile(editor) as? MarkdownFile ?: return null return doGetLineIndent(editor, file, offset) ?: super.getLineIndent(project, editor, language, offset) } private fun doGetLineIndent(editor: Editor, file: MarkdownFile, offset: Int): String? { if (isInBlockQuoteOrCodeFence(editor, file)) return null if (editor.getUserData(AutoHardWrapHandler.AUTO_WRAP_LINE_IN_PROGRESS_KEY) == true) return null val document = editor.document val prevLine = document.getLineNumber(offset) - 1 val listItem = file.getListItemAtLineSafely(prevLine, document) ?: file.getListItemAtLineSafely(prevLine - 1, document) ?: return null val firstLine = document.getLineNumber(listItem.startOffset) val indentRange = document.getLineIndentRange(firstLine) return document.getText(indentRange) } private fun isInBlockQuoteOrCodeFence(editor: Editor, file: MarkdownFile): Boolean { val document = editor.document val prevLine = document.getLineNumber(editor.caretModel.offset) - 1 if (prevLine == -1) return false val prevLineEnd = document.getLineEndOffset(prevLine) val beforeWhitespaceOffset = CharArrayUtil.shiftBackward(document.text, prevLineEnd - 1, " \t") if (beforeWhitespaceOffset == -1) return false return file.findElementAt(beforeWhitespaceOffset) ?.parentOfTypes(MarkdownBlockQuoteImpl::class, MarkdownCodeFenceImpl::class) != null } override fun isSuitableFor(language: Language?) = language is MarkdownLanguage }
apache-2.0
5e5ee769032e262235b8bce6021792f1
46.387097
132
0.789653
4.471842
false
false
false
false
Zhouzhouzhou/AndroidDemo
app/src/main/java/com/zhou/android/kotlin/WindowCallbackInvocation.kt
1
741
package com.zhou.android.kotlin import android.util.Log import android.view.MotionEvent import java.lang.reflect.InvocationHandler import java.lang.reflect.Method /** * Created by mxz on 2019/6/5. */ class WindowCallbackInvocation(val callback: Any) : InvocationHandler { override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any? { if ("dispatchTouchEvent" == method?.name) { Log.i("zhou", "WindowCallbackInvocation") val event: MotionEvent = args?.get(0) as MotionEvent if (MotionEvent.ACTION_UP == event.action) { ActivityMonitor.get().update() } } return method?.invoke(callback, *(args ?: arrayOfNulls<Any>(0))) } }
mit
f043e12daccec0f1f104b28b8517e48d
31.26087
84
0.646424
4.139665
false
false
false
false
lsmaira/gradle
buildSrc/subprojects/plugins/src/main/kotlin/org/gradle/plugins/buildtypes/BuildType.kt
2
899
package org.gradle.plugins.buildtypes typealias ProjectProperties = Map<String, Any> class BuildType(val name: String) { init { require(name.isNotEmpty()) } val abbreviation = abbreviationOf(name) var tasks: List<String> = emptyList() var active = false var onProjectProperties: (ProjectProperties) -> Unit = {} fun tasks(vararg tasks: String) { this.tasks = tasks.asList() } fun projectProperties(vararg pairs: Pair<String, Any>) { // this is so that when we configure the active buildType, // the project properties set for that buildType immediately // become active in the build if (active) onProjectProperties(pairs.toMap()) } } private fun abbreviationOf(name: String) = name[0] + name.substring(1).replace(lowercaseAlphaRegex, "") private val lowercaseAlphaRegex = Regex("\\p{Lower}")
apache-2.0
4d518a2c62bb9ac55f71860358691bd2
21.475
68
0.669633
4.280952
false
false
false
false
allotria/intellij-community
plugins/github/src/org/jetbrains/plugins/github/util/CachingGHUserAvatarLoader.kt
2
2594
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.util import com.google.common.cache.CacheBuilder import com.intellij.openapi.Disposable import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.LowMemoryWatcher import com.intellij.util.ImageLoader import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubApiRequests import java.awt.Image import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit class CachingGHUserAvatarLoader : Disposable { private val LOG = logger<CachingGHUserAvatarLoader>() private val indicatorProvider = ProgressIndicatorsProvider().also { Disposer.register(this, it) } private val avatarCache = CacheBuilder.newBuilder() .expireAfterAccess(5, TimeUnit.MINUTES) .build<String, CompletableFuture<Image?>>() init { LowMemoryWatcher.register(Runnable { avatarCache.invalidateAll() }, this) } fun requestAvatar(requestExecutor: GithubApiRequestExecutor, url: String): CompletableFuture<Image?> = avatarCache.get(url) { ProgressManager.getInstance().submitIOTask(indicatorProvider) { loadAndDownscale(requestExecutor, it, url, STORED_IMAGE_SIZE) } } private fun loadAndDownscale(requestExecutor: GithubApiRequestExecutor, indicator: ProgressIndicator, url: String, maximumSize: Int): Image? { try { val image = requestExecutor.execute(indicator, GithubApiRequests.CurrentUser.getAvatar(url)) return if (image.getWidth(null) <= maximumSize && image.getHeight(null) <= maximumSize) image else ImageLoader.scaleImage(image, maximumSize) } catch (e: ProcessCanceledException) { return null } catch (e: Exception) { LOG.debug("Error loading image from $url", e) return null } } override fun dispose() {} companion object { @JvmStatic fun getInstance(): CachingGHUserAvatarLoader = service() private const val MAXIMUM_ICON_SIZE = 40 // store images at maximum used size with maximum reasonable scale to avoid upscaling (3 for system scale, 2 for user scale) private const val STORED_IMAGE_SIZE = MAXIMUM_ICON_SIZE * 6 } }
apache-2.0
72cc7619d3a5089e729c5cb237082ada
38.30303
140
0.7633
4.599291
false
false
false
false
apollographql/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/OperationVariablesAdapterBuilder.kt
1
1552
package com.apollographql.apollo3.compiler.codegen.kotlin.file import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext import com.apollographql.apollo3.compiler.codegen.kotlin.CgFile import com.apollographql.apollo3.compiler.codegen.kotlin.CgFileBuilder import com.apollographql.apollo3.compiler.codegen.kotlin.CgOutputFileBuilder import com.apollographql.apollo3.compiler.codegen.kotlin.adapter.inputAdapterTypeSpec import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.toNamedType import com.apollographql.apollo3.compiler.ir.IrOperation import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.TypeSpec class OperationVariablesAdapterBuilder( val context: KotlinContext, val operation: IrOperation ): CgOutputFileBuilder { val packageName = context.layout.operationAdapterPackageName(operation.filePath) val simpleName = context.layout.operationVariablesAdapterName(operation) override fun prepare() { context.resolver.registerOperationVariablesAdapter( operation.name, ClassName(packageName, simpleName) ) } override fun build(): CgFile { return CgFile( packageName = packageName, fileName = simpleName, typeSpecs = listOf(typeSpec()) ) } private fun typeSpec(): TypeSpec { return operation.variables.map { it.toNamedType() } .inputAdapterTypeSpec( context = context, adapterName = simpleName, adaptedTypeName = context.resolver.resolveOperation(operation.name) ) } }
mit
ded32769ca27ec80b94771d489e7cfc2
35.97619
85
0.769974
4.564706
false
false
false
false
androidx/androidx
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/RejectTextChangeDemo.kt
3
2248
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.demos.text import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp @Preview @Composable fun RejectTextChangeDemo() { LazyColumn { item { TagLine(tag = "don't set if non number is added") RejectNonDigits() } item { TagLine(tag = "always clear composition") RejectComposition() } } } @Composable private fun RejectNonDigits() { val state = rememberSaveable { mutableStateOf("") } BasicTextField( modifier = demoTextFieldModifiers, value = state.value, textStyle = TextStyle(fontSize = 32.sp), onValueChange = { if (it.all { text -> text.isDigit() }) { state.value = it } }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) ) } @Composable private fun RejectComposition() { val state = rememberSaveable { mutableStateOf(({ "" })()) } BasicTextField( modifier = demoTextFieldModifiers, value = state.value, textStyle = TextStyle(fontSize = 32.sp), onValueChange = { state.value = it } ) }
apache-2.0
8311b7806bb095537380f438abd69b5a
29.808219
77
0.685498
4.523139
false
false
false
false
GunoH/intellij-community
plugins/package-search/test-src/com/jetbrains/packagesearch/intellij/plugin/Assertion.kt
7
2456
/******************************************************************************* * Copyright 2000-2022 JetBrains s.r.o. and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.jetbrains.packagesearch.intellij.plugin import kotlin.reflect.KProperty0 internal sealed class Assertion<out T>(val message: String?) { fun <V> failure(throwable: Throwable, message: String? = this.message): Assertion<V> = WithFailure(throwable, message) fun ifHasValue(assertion: (T) -> Unit) { if (this !is WithValue) return assertion(value) } fun <V> map(message: String? = this.message, transform: (T) -> V): Assertion<V> = when (this) { is WithFailure -> failure(throwable, message) is WithValue -> try { assertThat(transform(value), message) } catch (t: Throwable) { failure(t, message) } } abstract fun <A> assertThat(actual: A, message: String? = null): Assertion<A> class WithValue<T>(val value: T, message: String?) : Assertion<T>(message) { override fun <A> assertThat(actual: A, message: String?): Assertion<A> = WithValue(actual, message) } class WithFailure<T>(val throwable: Throwable, message: String?) : Assertion<T>(message) { override fun <A> assertThat(actual: A, message: String?): Assertion<A> = WithFailure(throwable, message) } } internal fun <T> assertThat(actual: T, message: String? = null): Assertion<T> = Assertion.WithValue(value = actual, message = message) internal fun <T> assertThat(getter: KProperty0<T>, message: String? = null): Assertion<T> = assertThat(getter.get(), message ?: getter.name) internal fun <T> assertThat(action: () -> T, message: String? = null): Assertion<Result<T>> = assertThat(runCatching { action() }, message)
apache-2.0
2709059e586834b6949660a813875c8c
38.612903
112
0.625814
4.198291
false
false
false
false
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/savedPatches/ShelfProvider.kt
7
8424
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.savedPatches import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.BackgroundTaskUtil import com.intellij.openapi.project.Project import com.intellij.openapi.util.Computable import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.shelf.* import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNodeRenderer import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder import com.intellij.ui.SimpleTextAttributes import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.text.DateFormatUtil import one.util.streamex.StreamEx import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit import java.util.stream.Stream import javax.swing.event.ChangeListener class ShelfProvider(private val project: Project, parent: Disposable) : SavedPatchesProvider<ShelvedChangeList>, Disposable { private val executor = AppExecutorUtil.createBoundedApplicationPoolExecutor("Shelved Changes Loader", 1) private val shelveManager: ShelveChangesManager get() = ShelveChangesManager.getInstance(project) override val dataClass: Class<ShelvedChangeList> get() = ShelvedChangeList::class.java override val applyAction: AnAction get() = ActionManager.getInstance().getAction("Vcs.Shelf.Apply") override val popAction: AnAction get() = ActionManager.getInstance().getAction("Vcs.Shelf.Pop") init { Disposer.register(parent, this) project.messageBus.connect(this).subscribe(ShelveChangesManager.SHELF_TOPIC, ChangeListener { preloadChanges() }) preloadChanges() } private fun preloadChanges() { BackgroundTaskUtil.submitTask(executor, this) { for (list in shelveManager.allLists) { ProgressManager.checkCanceled() list.loadChangesIfNeeded(project) } } } override fun subscribeToPatchesListChanges(disposable: Disposable, listener: () -> Unit) { val disposableFlag = Disposer.newCheckedDisposable() Disposer.register(disposable, disposableFlag) project.messageBus.connect(disposable).subscribe(ShelveChangesManager.SHELF_TOPIC, ChangeListener { if (ApplicationManager.getApplication().isDispatchThread) { listener() } else { ApplicationManager.getApplication().invokeLater(listener) { disposableFlag.isDisposed } } }) } private fun mainLists(): List<ShelvedChangeList> { return shelveManager.allLists.filter { l -> !l.isDeleted && !l.isRecycled } } private fun deletedLists() = shelveManager.allLists.filter { l -> l.isDeleted } override fun isEmpty() = mainLists().isEmpty() && deletedLists().isEmpty() override fun buildPatchesTree(modelBuilder: TreeModelBuilder) { val shelvesList = mainLists().sortedByDescending { it.DATE } val shelvesRoot = SavedPatchesTree.TagWithCounterChangesBrowserNode(VcsBundle.message("shelf.root.node.title")) modelBuilder.insertSubtreeRoot(shelvesRoot) modelBuilder.insertShelves(shelvesRoot, shelvesList) val deletedShelvesList = deletedLists().sortedByDescending { it.DATE } if (deletedShelvesList.isNotEmpty()) { val deletedShelvesRoot = SavedPatchesTree.TagWithCounterChangesBrowserNode(VcsBundle.message("shelve.recently.deleted.node"), expandByDefault = false, sortWeight = 20) modelBuilder.insertSubtreeRoot(deletedShelvesRoot, shelvesRoot) modelBuilder.insertShelves(deletedShelvesRoot, deletedShelvesList) } } private fun TreeModelBuilder.insertShelves(root: SavedPatchesTree.TagWithCounterChangesBrowserNode, shelvesList: List<ShelvedChangeList>) { for (shelve in shelvesList) { insertSubtreeRoot(ShelvedChangeListChangesBrowserNode(ShelfObject(shelve)), root) } } override fun getData(dataId: String, selectedObjects: Stream<SavedPatchesProvider.PatchObject<*>>): Any? { if (ShelvedChangesViewManager.SHELVED_CHANGELIST_KEY.`is`(dataId)) { return filterLists(selectedObjects) { l -> !l.isRecycled && !l.isDeleted } } else if (ShelvedChangesViewManager.SHELVED_RECYCLED_CHANGELIST_KEY.`is`(dataId)) { return filterLists(selectedObjects) { l -> l.isRecycled && !l.isDeleted } } else if (ShelvedChangesViewManager.SHELVED_DELETED_CHANGELIST_KEY.`is`(dataId)) { return filterLists(selectedObjects) { l -> l.isDeleted } } return null } private fun filterLists(selectedObjects: Stream<SavedPatchesProvider.PatchObject<*>>, predicate: (ShelvedChangeList) -> Boolean): List<ShelvedChangeList> { return StreamEx.of(selectedObjects.map(SavedPatchesProvider.PatchObject<*>::data)).filterIsInstance(dataClass).filter(predicate).toList() } override fun dispose() { executor.shutdown() try { executor.awaitTermination(10, TimeUnit.MILLISECONDS) } finally { } } class ShelvedChangeListChangesBrowserNode(private val shelf: ShelfObject) : ChangesBrowserNode<ShelfObject>(shelf) { override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) { val listName = shelf.data.DESCRIPTION.ifBlank { VcsBundle.message("changes.nodetitle.empty.changelist.name") } val attributes = if (shelf.data.isRecycled || shelf.data.isDeleted) { SimpleTextAttributes.GRAYED_BOLD_ATTRIBUTES } else { SimpleTextAttributes.REGULAR_ATTRIBUTES } renderer.appendTextWithIssueLinks(listName, attributes) renderer.toolTipText = VcsBundle.message("saved.patch.created.on.date.at.time.tooltip", VcsBundle.message("shelf.tooltip.title"), DateFormatUtil.formatDate(shelf.data.DATE), DateFormatUtil.formatTime(shelf.data.DATE)) } override fun getTextPresentation(): String = shelf.data.toString() } inner class ShelfObject(override val data: ShelvedChangeList) : SavedPatchesProvider.PatchObject<ShelvedChangeList> { override fun cachedChanges(): Collection<SavedPatchesProvider.ChangeObject>? = data.getChangeObjects() override fun loadChanges(): CompletableFuture<SavedPatchesProvider.LoadingResult>? { val cachedChangeObjects = data.getChangeObjects() if (cachedChangeObjects != null) { return CompletableFuture.completedFuture(SavedPatchesProvider.LoadingResult.Changes(cachedChangeObjects)) } return BackgroundTaskUtil.submitTask(executor, this@ShelfProvider, Computable { try { data.loadChangesIfNeededOrThrow(project) return@Computable SavedPatchesProvider.LoadingResult.Changes(data.getChangeObjects()!!) } catch (throwable: Throwable) { return@Computable when (throwable) { is VcsException -> SavedPatchesProvider.LoadingResult.Error(throwable) else -> SavedPatchesProvider.LoadingResult.Error(VcsException(throwable)) } } }).future } private fun ShelvedChangeList.getChangeObjects(): Set<SavedPatchesProvider.ChangeObject>? { val cachedChanges = changes ?: return null return cachedChanges.map { MyShelvedWrapper(it, null, this) } .union(binaryFiles.map { MyShelvedWrapper(null, it, this) }) } override fun getDiffPreviewTitle(changeName: String?): String { return changeName?.let { name -> VcsBundle.message("shelve.editor.diff.preview.title", name) } ?: VcsBundle.message("shelved.version.name") } } private class MyShelvedWrapper(shelvedChange: ShelvedChange?, binaryFile: ShelvedBinaryFile?, changeList: ShelvedChangeList) : ShelvedWrapper(shelvedChange, binaryFile, changeList) { override fun getTag(): ChangesBrowserNode.Tag? = null } }
apache-2.0
39aebb02773dda3de78305ed668c6411
45.038251
141
0.730176
4.740574
false
false
false
false
hellenxu/TipsProject
DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/material/FullScreenDialog.kt
1
1046
package six.ca.droiddailyproject.material import android.os.Bundle import android.view.* import androidx.fragment.app.DialogFragment import six.ca.droiddailyproject.R /** * @author hellenxu * @date 2021-04-27 * Copyright 2021 Six. All rights reserved. */ class FullScreenDialog: DialogFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NO_TITLE, R.style.FullScreenDialog) } override fun onStart() { super.onStart() val window = dialog?.window if (window != null) { val attributes = window.attributes attributes.gravity = Gravity.BOTTOM attributes.windowAnimations = R.style.BottomToTopAnim window.attributes = attributes } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.dialog_full_screen, container, false) } }
apache-2.0
86a160fc381fdd841236e4b44f392f95
25.175
78
0.666348
4.648889
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/KotlinPackageEntryTableAccessor.kt
4
2150
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.formatter import com.intellij.application.options.codeStyle.properties.CodeStylePropertiesUtil import com.intellij.application.options.codeStyle.properties.ValueListPropertyAccessor import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings import org.jetbrains.kotlin.idea.core.formatter.KotlinPackageEntry import org.jetbrains.kotlin.idea.core.formatter.KotlinPackageEntryTable import java.lang.reflect.Field class KotlinPackageEntryTableAccessor(kotlinCodeStyle: KotlinCodeStyleSettings, field: Field) : ValueListPropertyAccessor<KotlinPackageEntryTable>(kotlinCodeStyle, field) { override fun valueToString(value: List<String>): String = CodeStylePropertiesUtil.toCommaSeparatedString(value) override fun fromExternal(extVal: List<String>): KotlinPackageEntryTable = KotlinPackageEntryTable( extVal.asSequence().map(String::trim).map(::readPackageEntry).toMutableList() ) override fun isEmptyListAllowed(): Boolean = false override fun toExternal(value: KotlinPackageEntryTable): List<String> = value.getEntries().map(::writePackageEntry) companion object { private const val ALIAS_CHAR = "^" private const val OTHER_CHAR = "*" private fun readPackageEntry(string: String): KotlinPackageEntry = when { string == ALIAS_CHAR -> KotlinPackageEntry.ALL_OTHER_ALIAS_IMPORTS_ENTRY string == OTHER_CHAR -> KotlinPackageEntry.ALL_OTHER_IMPORTS_ENTRY string.endsWith("**") -> KotlinPackageEntry(string.substring(0, string.length - 1), true) else -> KotlinPackageEntry(string, false) } private fun writePackageEntry(entry: KotlinPackageEntry): String = when (entry) { KotlinPackageEntry.ALL_OTHER_ALIAS_IMPORTS_ENTRY -> ALIAS_CHAR KotlinPackageEntry.ALL_OTHER_IMPORTS_ENTRY -> OTHER_CHAR else -> "${entry.packageName}.*" + if (entry.withSubpackages) "*" else "" } } }
apache-2.0
d3939f68292ccf10dd8157e680b15719
50.190476
158
0.744186
4.423868
false
false
false
false
siosio/intellij-community
plugins/kotlin/gradle/gradle-idea/src/org/jetbrains/kotlin/idea/scripting/gradle/roots/GradleBuildRoot.kt
1
5377
// 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.scripting.gradle.roots import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.core.script.scriptingDebugLog import org.jetbrains.kotlin.idea.core.script.ucache.ScriptClassRootsBuilder import org.jetbrains.kotlin.idea.scripting.gradle.GradleScriptDefinitionsContributor import org.jetbrains.kotlin.idea.scripting.gradle.LastModifiedFiles import org.jetbrains.kotlin.idea.scripting.gradle.importing.KotlinDslScriptModel import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.scripting.resolve.VirtualFileScriptSource import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import java.io.File import java.util.concurrent.atomic.AtomicReference /** * [GradleBuildRoot] is a linked gradle build (don't confuse with gradle project and included build). * Each [GradleBuildRoot] may have it's own Gradle version, Java home and other settings. * * Typically, IntelliJ project have no more than one [GradleBuildRoot]. * * See [GradleBuildRootsManager] for more details. */ sealed class GradleBuildRoot( private val lastModifiedFiles: LastModifiedFiles ) { enum class ImportingStatus { importing, updatingCaches, updated } val importing = AtomicReference(ImportingStatus.updated) abstract val pathPrefix: String abstract val projectRoots: Collection<String> val dir: VirtualFile? get() = LocalFileSystem.getInstance().findFileByPath(pathPrefix) fun saveLastModifiedFiles() { scriptingDebugLog { "LasModifiedFiles saved: $lastModifiedFiles" } LastModifiedFiles.write(dir ?: return, lastModifiedFiles) } fun areRelatedFilesChangedBefore(file: VirtualFile, lastModified: Long): Boolean = lastModifiedFiles.lastModifiedTimeStampExcept(file.path) < lastModified fun fileChanged(filePath: String, ts: Long) { lastModifiedFiles.fileChanged(ts, filePath) } fun isImportingInProgress(): Boolean { return importing.get() != ImportingStatus.updated } } sealed class WithoutScriptModels( settings: GradleProjectSettings, lastModifiedFiles: LastModifiedFiles ) : GradleBuildRoot(lastModifiedFiles) { final override val pathPrefix = settings.externalProjectPath!! final override val projectRoots = settings.modules.takeIf { it.isNotEmpty() } ?: listOf(pathPrefix) } /** * Gradle build with old Gradle version (<6.0) */ class Legacy( settings: GradleProjectSettings, lastModifiedFiles: LastModifiedFiles = settings.loadLastModifiedFiles() ?: LastModifiedFiles() ) : WithoutScriptModels(settings, lastModifiedFiles) /** * Linked but not yet imported Gradle build. */ class New( settings: GradleProjectSettings, lastModifiedFiles: LastModifiedFiles = settings.loadLastModifiedFiles() ?: LastModifiedFiles() ) : WithoutScriptModels(settings, lastModifiedFiles) /** * Imported Gradle build. * Each imported build have info about all of it's Kotlin Build Scripts. */ class Imported( override val pathPrefix: String, val data: GradleBuildRootData, lastModifiedFiles: LastModifiedFiles ) : GradleBuildRoot(lastModifiedFiles) { override val projectRoots: Collection<String> get() = data.projectRoots val javaHome = data.javaHome?.takeIf { it.isNotBlank() }?.let { File(it) } fun collectConfigurations(builder: ScriptClassRootsBuilder) { if (javaHome != null) { builder.sdks.addSdk(javaHome) } val definitions = GradleScriptDefinitionsContributor.getDefinitions(builder.project, pathPrefix, data.gradleHome, data.javaHome) if (definitions == null) { // needed to recreate classRoots if correct script definitions weren't loaded at this moment // in this case classRoots will be recreated after script definitions update builder.useCustomScriptDefinition() } builder.addTemplateClassesRoots(GradleScriptDefinitionsContributor.getDefinitionsTemplateClasspath(data.gradleHome)) data.models.forEach { script -> val definition = definitions?.let { selectScriptDefinition(script, it) } builder.addCustom( script.file, script.classPath, script.sourcePath, GradleScriptInfo(this, definition, script) ) } } private fun selectScriptDefinition( script: KotlinDslScriptModel, definitions: List<ScriptDefinition> ): ScriptDefinition? { val file = LocalFileSystem.getInstance().findFileByPath(script.file) ?: return null val scriptSource = VirtualFileScriptSource(file) return definitions.firstOrNull { it.isScript(scriptSource) } } } fun GradleProjectSettings.loadLastModifiedFiles(): LastModifiedFiles? { val externalProjectPath = externalProjectPath ?: return null return loadLastModifiedFiles(externalProjectPath) } fun loadLastModifiedFiles(rootDirPath: String): LastModifiedFiles? { val vFile = LocalFileSystem.getInstance().findFileByPath(rootDirPath) ?: return null return LastModifiedFiles.read(vFile) }
apache-2.0
dfa0e8a9f29c17bf543ad0dfafeec422
37.134752
158
0.744281
4.87931
false
false
false
false
siosio/intellij-community
java/java-tests/testSrc/com/intellij/compiler/backwardRefs/CompilerReferencesMultiModuleTest.kt
1
4276
// 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.compiler.backwardRefs import com.intellij.compiler.CompilerReferenceService import com.intellij.java.compiler.CompilerReferencesTestBase import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.module.JavaModuleType import com.intellij.openapi.module.Module import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.psi.PsiClassOwner import com.intellij.psi.PsiManager import com.intellij.psi.search.searches.ClassInheritorsSearch import com.intellij.testFramework.PsiTestUtil import org.intellij.lang.annotations.Language class CompilerReferencesMultiModuleTest : CompilerReferencesTestBase() { private var moduleA: Module? = null private var moduleB: Module? = null override fun setUp() { super.setUp() addTwoModules() installCompiler() } override fun tearDown() { moduleA = null moduleB = null super.tearDown() } fun testNoChanges() { addClass("BaseClass.java", "public interface BaseClass{}") addClass("A/ClassA.java", "public class ClassA implements BaseClass{}") addClass("B/ClassB.java", "public class ClassB implements BaseClass{}") rebuildProject() assertEmpty(dirtyModules()) } @Throws(Exception::class) fun testDirtyScopeCachedResults() { val file1 = addClass("A/Foo.java", """public class Foo { static class Bar extends Foo {} }""") addClass("B/Unrelated.java", "public class Unrelated {}") rebuildProject() val foo = (file1 as PsiClassOwner).classes[0] assertOneElement(ClassInheritorsSearch.search(foo, foo.useScope, false).findAll()) try { assertTrue(CompilerReferenceService.IS_ENABLED_KEY.asBoolean()) CompilerReferenceService.IS_ENABLED_KEY.setValue(false) assertOneElement(ClassInheritorsSearch.search(foo, foo.useScope, false).findAll()) } finally { CompilerReferenceService.IS_ENABLED_KEY.setValue(true) } } fun testLeafModuleTyping() { addClass("BaseClass.java", "public interface BaseClass{}") val classA = addClass("A/ClassA.java", "public class ClassA implements BaseClass{}") addClass("B/ClassB.java", "public class ClassB implements BaseClass{}") rebuildProject() myFixture.openFileInEditor(classA.virtualFile) myFixture.type("/*typing in module A*/") assertEquals("A", assertOneElement(dirtyModules())) FileDocumentManager.getInstance().saveAllDocuments() assertEquals("A", assertOneElement(dirtyModules())) } private fun addClass(relativePath: String, @Language("JAVA") text: String) = myFixture.addFileToProject(relativePath, text) fun testModulePathRename() { addClass("A/Foo.java", "class Foo { void m() {System.out.println(123);} }") rebuildProject() val moduleARoot = PsiManager.getInstance(myFixture.project).findDirectory(myFixture.findFileInTempDir("A"))!! myFixture.renameElement(moduleARoot, "XXX") assertTrue(dirtyModules().contains("A")) addClass("XXX/Bar.java", "class Bar { void m() {System.out.println(123);} }") rebuildProject() assertEmpty(dirtyModules()) val javaLangSystem = myFixture.javaFacade.findClass("java.lang.System")!! val referentFiles = (CompilerReferenceService.getInstance(myFixture.project) as CompilerReferenceServiceImpl).getReferentFilesForTests(javaLangSystem)!! assertEquals(setOf("Foo.java", "Bar.java"), referentFiles.map { it.name }.toSet()) } private fun addTwoModules() { moduleA = PsiTestUtil.addModule(project, JavaModuleType.getModuleType(), "A", myFixture.tempDirFixture.findOrCreateDir("A")) moduleB = PsiTestUtil.addModule(project, JavaModuleType.getModuleType(), "B", myFixture.tempDirFixture.findOrCreateDir("B")) ModuleRootModificationUtil.addDependency(moduleA!!, module) ModuleRootModificationUtil.addDependency(moduleB!!, module) } private fun dirtyModules(): Collection<String> = (CompilerReferenceService.getInstance(project) as CompilerReferenceServiceImpl).dirtyScopeHolder.allDirtyModules.map { module -> module.name } }
apache-2.0
00e3b3ce660b20f979994749f5f87a35
43.092784
158
0.738307
4.637744
false
true
false
false
nonylene/PhotoLinkViewer-Core
photolinkviewer-core/src/main/java/net/nonylene/photolinkviewer/core/dialog/SaveDialogFragment.kt
1
4665
package net.nonylene.photolinkviewer.core.dialog import android.app.Activity import android.app.Dialog import android.content.Intent import android.os.Bundle import android.os.Parcel import android.os.Parcelable import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import net.nonylene.photolinkviewer.core.R import net.nonylene.photolinkviewer.core.view.SaveDialogItemView import java.util.* //todo: move to recyclerview class SaveDialogFragment : DialogFragment() { companion object { val DIR_KEY = "dir" val INFO_KEY = "info" val QUALITY_KEY = "quality" fun createArguments(dirName: String, quality: String?, infoList: ArrayList<Info>): Bundle { return Bundle().apply { putString(DIR_KEY, dirName) putString(QUALITY_KEY, quality) putParcelableArrayList(INFO_KEY, infoList) } } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val infoList = arguments.getParcelableArrayList<Info>(INFO_KEY) // set custom view val view = View.inflate(activity, R.layout.plv_core_save_path, null) val dirname = arguments.getString(DIR_KEY) (view.findViewById(R.id.path_text_view) as TextView).text = dirname val linearLayout = view.findViewById(R.id.path_linear_layout) as LinearLayout for (info in infoList) { linearLayout.addView( (LayoutInflater.from(context).inflate(R.layout.plv_core_save_path_item, linearLayout, false) as SaveDialogItemView).apply { setThumbnailUrl(info.thumbnailUrl) setFileName(info.fileName) checkedChangeListener = { (dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = (0..linearLayout.childCount - 1).fold(false) { result, i -> result || (linearLayout.getChildAt(i) as SaveDialogItemView).isChecked } } } ) } return AlertDialog.Builder(activity).setView(view) .setTitle(arguments.getString(QUALITY_KEY)?.let { getString(R.string.plv_core_save_dialog_title).format(it) } ?: getString(R.string.plv_core_save_dialog_title_null)) .setPositiveButton(getString(R.string.plv_core_save_dialog_positive), { _, _ -> // get filename val newInfoList = (0..linearLayout.childCount - 1).map { linearLayout.getChildAt(it) as SaveDialogItemView to infoList[it] }.filter { it.first.isChecked }.map { Info(it.first.getFileName(), it.second.downloadUrl, it.second.thumbnailUrl) }.toCollection(ArrayList()) targetFragment.onActivityResult(targetRequestCode, Activity.RESULT_OK, Intent().putParcelableArrayListExtra(INFO_KEY, newInfoList) .putExtra(DIR_KEY, dirname) ) } ) .setNegativeButton(getString(android.R.string.cancel), null) .create() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) dialog.window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } class Info(val fileName: String, val downloadUrl: String, val thumbnailUrl: String) : Parcelable { override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(fileName) dest.writeString(downloadUrl) dest.writeString(thumbnailUrl) } constructor(source: Parcel) : this( source.readString(), source.readString(), source.readString() ) companion object CREATOR: Parcelable.Creator<Info> { override fun createFromParcel(source: Parcel): Info { return Info(source) } override fun newArray(size: Int): Array<Info?> { return arrayOfNulls(size) } } } }
gpl-2.0
e8b1118f27aaa29ab9d01cae740d7ed1
39.215517
143
0.592926
5.043243
false
false
false
false
jwren/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/AllClassesCompletion.kt
1
5040
// 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.completion import com.intellij.codeInsight.completion.AllClassesGetter import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.PrefixMatcher import com.intellij.psi.PsiClass import com.intellij.psi.search.PsiShortNamesCache import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.ClassifierDescriptorWithTypeParameters import org.jetbrains.kotlin.idea.base.utils.fqname.getKotlinFqName import org.jetbrains.kotlin.idea.base.utils.fqname.isJavaClassNotToBeUsedInKotlin import org.jetbrains.kotlin.idea.caches.KotlinShortNamesCache import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper import org.jetbrains.kotlin.idea.project.TargetPlatformDetector import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.util.isSyntheticKotlinClass import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered class AllClassesCompletion( private val parameters: CompletionParameters, private val kotlinIndicesHelper: KotlinIndicesHelper, private val prefixMatcher: PrefixMatcher, private val resolutionFacade: ResolutionFacade, private val kindFilter: (ClassKind) -> Boolean, private val includeTypeAliases: Boolean, private val includeJavaClassesNotToBeUsed: Boolean ) { fun collect(classifierDescriptorCollector: (ClassifierDescriptorWithTypeParameters) -> Unit, javaClassCollector: (PsiClass) -> Unit) { //TODO: this is a temporary solution until we have built-ins in indices // we need only nested classes because top-level built-ins are all added through default imports for (builtInPackage in resolutionFacade.moduleDescriptor.builtIns.builtInPackagesImportedByDefault) { collectClassesFromScope(builtInPackage.memberScope) { if (it.containingDeclaration is ClassDescriptor) { classifierDescriptorCollector(it) } } } kotlinIndicesHelper.processKotlinClasses( { prefixMatcher.prefixMatches(it) }, kindFilter = kindFilter, processor = classifierDescriptorCollector ) if (includeTypeAliases) { kotlinIndicesHelper.processTopLevelTypeAliases(prefixMatcher.asStringNameFilter(), classifierDescriptorCollector) } if (TargetPlatformDetector.getPlatform(parameters.originalFile as KtFile).isJvm()) { addAdaptedJavaCompletion(javaClassCollector) } } private fun collectClassesFromScope(scope: MemberScope, collector: (ClassDescriptor) -> Unit) { for (descriptor in scope.getDescriptorsFiltered(DescriptorKindFilter.CLASSIFIERS)) { if (descriptor is ClassDescriptor) { if (kindFilter(descriptor.kind) && prefixMatcher.prefixMatches(descriptor.name.asString())) { collector(descriptor) } collectClassesFromScope(descriptor.unsubstitutedInnerClassesScope, collector) } } } private fun addAdaptedJavaCompletion(collector: (PsiClass) -> Unit) { val shortNamesCache = PsiShortNamesCache.EP_NAME.getExtensions(parameters.editor.project).firstOrNull { it is KotlinShortNamesCache } as KotlinShortNamesCache? shortNamesCache?.disableSearch?.set(true) try { AllClassesGetter.processJavaClasses(parameters, prefixMatcher, true) { psiClass -> if (psiClass!! !is KtLightClass) { // Kotlin class should have already been added as kotlin element before if (psiClass.isSyntheticKotlinClass()) return@processJavaClasses // filter out synthetic classes produced by Kotlin compiler val kind = when { psiClass.isAnnotationType -> ClassKind.ANNOTATION_CLASS psiClass.isInterface -> ClassKind.INTERFACE psiClass.isEnum -> ClassKind.ENUM_CLASS else -> ClassKind.CLASS } if (kindFilter(kind) && !isNotToBeUsed(psiClass)) { collector(psiClass) } } } } finally { shortNamesCache?.disableSearch?.set(false) } } private fun isNotToBeUsed(javaClass: PsiClass): Boolean { if (includeJavaClassesNotToBeUsed) return false val fqName = javaClass.getKotlinFqName() return fqName?.isJavaClassNotToBeUsedInKotlin() == true } }
apache-2.0
e732fe9a3dd2cc8a6ac0c06f7f1b34ab
46.54717
144
0.711706
5.502183
false
false
false
false
smmribeiro/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/annotate/AnnotationsPreloader.kt
1
4023
// 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.openapi.vcs.annotate import com.intellij.codeInsight.hints.isCodeAuthorInlayHintsEnabled import com.intellij.codeInsight.hints.refreshCodeAuthorInlayHints import com.intellij.ide.PowerSaveMode import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.Service import com.intellij.openapi.components.Service.Level import com.intellij.openapi.components.service import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.FileEditorManagerEvent import com.intellij.openapi.fileEditor.FileEditorManagerListener import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vcs.ProjectLevelVcsManager.VCS_CONFIGURATION_CHANGED import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsListener import com.intellij.openapi.vcs.changes.ChangeListManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.ui.update.DisposableUpdate import com.intellij.util.ui.update.MergingUpdateQueue import com.intellij.vcs.CacheableAnnotationProvider @Service(Level.PROJECT) internal class AnnotationsPreloader(private val project: Project) { private val updateQueue = MergingUpdateQueue("Annotations preloader queue", 1000, true, null, project, null, false) init { project.messageBus.connect().subscribe(VCS_CONFIGURATION_CHANGED, VcsListener { refreshSelectedFiles() }) } fun schedulePreloading(file: VirtualFile) { if (project.isDisposed || file.fileType.isBinary) return updateQueue.queue(object : DisposableUpdate(project, file) { override fun doRun() { try { val start = if (LOG.isDebugEnabled) System.currentTimeMillis() else 0 if (!FileEditorManager.getInstance(project).isFileOpen(file)) return val annotationProvider = getAnnotationProvider(project, file) ?: return annotationProvider.populateCache(file) LOG.debug { "Preloaded VCS annotations for ${file.name} in ${System.currentTimeMillis() - start} ms" } runInEdt { refreshCodeAuthorInlayHints(project, file) } } catch (e: VcsException) { LOG.info(e) } } }) } private fun refreshSelectedFiles() { if (!isEnabled()) return val selectedFiles = FileEditorManager.getInstance(project).selectedFiles for (file in selectedFiles) schedulePreloading(file) } internal class AnnotationsPreloaderFileEditorManagerListener(private val project: Project) : FileEditorManagerListener { override fun selectionChanged(event: FileEditorManagerEvent) { if (!isEnabled()) return val file = event.newFile ?: return project.service<AnnotationsPreloader>().schedulePreloading(file) } } companion object { private val LOG = logger<AnnotationsPreloader>() // TODO: check cores number? internal fun isEnabled(): Boolean = (isCodeAuthorInlayHintsEnabled() || AdvancedSettings.getBoolean("vcs.annotations.preload")) && !PowerSaveMode.isEnabled() internal fun canPreload(project: Project, file: VirtualFile): Boolean = getAnnotationProvider(project, file) != null private fun getAnnotationProvider(project: Project, file: VirtualFile): CacheableAnnotationProvider? { val status = ChangeListManager.getInstance(project).getStatus(file) if (status == FileStatus.UNKNOWN || status == FileStatus.ADDED || status == FileStatus.IGNORED) return null val vcs = ProjectLevelVcsManager.getInstance(project).getVcsFor(file) ?: return null return vcs.annotationProvider as? CacheableAnnotationProvider } } }
apache-2.0
a4d1a00d1888d5246eae098edd0194b2
41.808511
158
0.770569
4.766588
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/actions/row/InsertRowAction.kt
4
2265
// 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.intellij.plugins.markdown.editor.tables.actions.row import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.intellij.plugins.markdown.editor.tables.TableUtils.isHeaderRow import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElementFactory import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableRow import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableSeparatorRow internal abstract class InsertRowAction(private val insertAbove: Boolean): RowBasedTableAction(considerSeparatorRow = true) { override fun performAction(editor: Editor, table: MarkdownTable, rowElement: PsiElement) { runWriteAction { val widths = obtainCellsWidths(rowElement) val newRow = MarkdownPsiElementFactory.createTableEmptyRow(table.project, widths) require(rowElement.parent == table) executeCommand(rowElement.project) { when { insertAbove -> table.addRangeBefore(newRow, newRow.nextSibling, rowElement) else -> table.addRangeAfter(newRow.prevSibling, newRow, rowElement) } } } } private fun obtainCellsWidths(element: PsiElement): Collection<Int> { return when (element) { is MarkdownTableRow -> element.cells.map { it.textLength } is MarkdownTableSeparatorRow -> element.cellsRanges.map { it.length } else -> error("element should be either MarkdownTableRow or MarkdownTableSeparatorRow") } } override fun findRowOrSeparator(file: PsiFile, editor: Editor): PsiElement? { val element = super.findRowOrSeparator(file, editor) ?: return null return when { (element as? MarkdownTableRow)?.isHeaderRow == true -> null insertAbove && element is MarkdownTableSeparatorRow -> null else -> element } } class InsertAbove: InsertRowAction(insertAbove = true) class InsertBelow: InsertRowAction(insertAbove = false) }
apache-2.0
755c561eafdb22ada33a1342734faa75
44.3
158
0.763797
4.458661
false
false
false
false
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/action/GHPRSelectPullRequestForFileAction.kt
7
1964
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.action import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.components.service import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.DumbAwareAction import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.pullrequest.GHPRToolWindowController import org.jetbrains.plugins.github.pullrequest.GHPRVirtualFile import java.util.function.Supplier class GHPRSelectPullRequestForFileAction : DumbAwareAction(GithubBundle.messagePointer("pull.request.select.action"), Supplier<String?> { null }, AllIcons.General.Locate) { override fun update(e: AnActionEvent) { val project = e.project if (project == null) { e.presentation.isEnabledAndVisible = false return } val componentController = project.service<GHPRToolWindowController>().getTabController()?.componentController if (componentController == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true val files = FileEditorManager.getInstance(project).selectedFiles.filterIsInstance<GHPRVirtualFile>() e.presentation.isEnabled = files.isNotEmpty() } override fun actionPerformed(e: AnActionEvent) { val project = e.getRequiredData(PlatformDataKeys.PROJECT) val file = FileEditorManager.getInstance(project).selectedFiles.filterIsInstance<GHPRVirtualFile>().first() project.service<GHPRToolWindowController>().activate { it.componentController?.viewPullRequest(file.pullRequest) } } }
apache-2.0
6b2b6367fedd3833807af46082661fba
43.659091
140
0.744908
5.035897
false
false
false
false
appmattus/layercache
samples/androidApp/src/main/kotlin/com/appmattus/layercache/samples/data/network/PersonalDetailsNetworkEntity.kt
1
1102
/* * Copyright 2021 Appmattus Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.appmattus.layercache.samples.data.network import com.appmattus.layercache.samples.domain.PersonalDetails import kotlinx.serialization.Serializable @Serializable internal data class PersonalDetailsNetworkEntity( val name: String, val tagline: String, val location: String, val avatarUrl: String ) { fun toDomainEntity(): PersonalDetails = PersonalDetails( name = name, tagline = tagline, location = location, avatarUrl = avatarUrl ) }
apache-2.0
97a5b07df1bec6ec12c3d81240e184c8
30.485714
75
0.735027
4.425703
false
false
false
false
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/highlighting/EditorConfigSyntaxHighlighter.kt
13
3599
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.highlighting import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.HighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.editor.colors.TextAttributesKey.createTextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.TokenType import com.intellij.psi.tree.IElementType import org.editorconfig.configmanagement.lexer.EditorConfigLexerFactory import org.editorconfig.language.psi.EditorConfigElementTypes object EditorConfigSyntaxHighlighter : SyntaxHighlighterBase() { const val VALID_ESCAPES = " \r\n\t\\#;!?*[]{}" val SEPARATOR = createTextAttributesKey("EDITORCONFIG_SEPARATOR", DefaultLanguageHighlighterColors.OPERATION_SIGN) val BRACE = createTextAttributesKey("EDITORCONFIG_BRACE", DefaultLanguageHighlighterColors.BRACES) val BRACKET = createTextAttributesKey("EDITORCONFIG_BRACKET", DefaultLanguageHighlighterColors.BRACKETS) val COMMA = createTextAttributesKey("EDITORCONFIG_COMMA", DefaultLanguageHighlighterColors.COMMA) val IDENTIFIER = createTextAttributesKey("EDITORCONFIG_IDENTIFIER", DefaultLanguageHighlighterColors.IDENTIFIER) val COMMENT = createTextAttributesKey("EDITORCONFIG_LINE_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT) private val BAD_CHARACTER = createTextAttributesKey("EDITORCONFIG_BAD_CHARACTER", HighlighterColors.BAD_CHARACTER) // Added by annotators val VALID_CHAR_ESCAPE = createTextAttributesKey("EDITORCONFIG_VALID_CHAR_ESCAPE", DefaultLanguageHighlighterColors.VALID_STRING_ESCAPE) val INVALID_CHAR_ESCAPE = createTextAttributesKey("EDITORCONFIG_INVALID_CHAR_ESCAPE", DefaultLanguageHighlighterColors.INVALID_STRING_ESCAPE) val PROPERTY_KEY = createTextAttributesKey("EDITORCONFIG_PROPERTY_KEY", DefaultLanguageHighlighterColors.INSTANCE_FIELD) val PROPERTY_VALUE = createTextAttributesKey("EDITORCONFIG_PROPERTY_VALUE", DefaultLanguageHighlighterColors.STRING) val KEY_DESCRIPTION = createTextAttributesKey("EDITORCONFIG_VARIABLE", DefaultLanguageHighlighterColors.CLASS_REFERENCE) val PATTERN = createTextAttributesKey("EDITORCONFIG_PATTERN", DefaultLanguageHighlighterColors.KEYWORD) val SPECIAL_SYMBOL = createTextAttributesKey("EDITORCONFIG_SPECIAL_SYMBOL", DefaultLanguageHighlighterColors.OPERATION_SIGN) private val BAD_CHAR_KEYS = arrayOf(BAD_CHARACTER) private val SEPARATOR_KEYS = arrayOf(SEPARATOR) private val BRACE_KEYS = arrayOf(BRACE) private val BRACKET_KEYS = arrayOf(BRACKET) private val COMMA_KEYS = arrayOf(COMMA) private val IDENTIFIER_KEYS = arrayOf(IDENTIFIER) private val COMMENT_KEYS = arrayOf(COMMENT) override fun getHighlightingLexer() = EditorConfigLexerFactory.getAdapter() override fun getTokenHighlights(tokenType: IElementType) = when (tokenType) { EditorConfigElementTypes.SEPARATOR, EditorConfigElementTypes.COLON -> SEPARATOR_KEYS EditorConfigElementTypes.L_BRACKET, EditorConfigElementTypes.R_BRACKET -> BRACKET_KEYS EditorConfigElementTypes.L_CURLY, EditorConfigElementTypes.R_CURLY -> BRACE_KEYS EditorConfigElementTypes.COMMA -> COMMA_KEYS EditorConfigElementTypes.IDENTIFIER -> IDENTIFIER_KEYS EditorConfigElementTypes.LINE_COMMENT -> COMMENT_KEYS TokenType.BAD_CHARACTER -> BAD_CHAR_KEYS else -> TextAttributesKey.EMPTY_ARRAY } }
apache-2.0
dbc51e84e2d7ddfcd19adab5ddbaa61c
61.051724
140
0.814949
5.3161
false
true
false
false
blan4/MangaReader
app/src/main/java/org/seniorsigan/mangareader/usecases/readmanga/ReadmangaUrls.kt
1
842
package org.seniorsigan.mangareader.usecases.readmanga interface Urls { val name: String val base: String val mangaList: String val search: String } object ReadmangaUrls: Urls { override val name = "readmanga" override val base = "http://readmanga.me" override val mangaList = "http://readmanga.me/list?sortType=rate" override val search = "$base/search" } object MintmangaUrls: Urls { override val name = "mintmanga" override val base = "http://mintmanga.com" override val mangaList = "http://mintmanga.com/list?sortType=rate" override val search = "$base/search" } object SelfmangaUrls: Urls { override val name = "selfmanga" override val base = "http://selfmanga.ru" override val mangaList = "http://selfmanga.ru/list?sortType=rate" override val search = "$base/search" }
mit
712ea5b214f8607287c102a56fcf4719
28.068966
70
0.698337
3.676856
false
false
false
false
joaomneto/TitanCompanion
src/main/java/pt/joaomneto/titancompanion/adventure/impl/fragments/sl/SLWeaponCombatFragment.kt
1
4926
package pt.joaomneto.titancompanion.adventure.impl.fragments.sl import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_33sl_adventure_weaponcombat.* import pt.joaomneto.titancompanion.R import pt.joaomneto.titancompanion.adventure.AdventureFragment import pt.joaomneto.titancompanion.adventure.impl.SLAdventure import pt.joaomneto.titancompanion.util.DiceRoller class SLWeaponCombatFragment : AdventureFragment() { private var enemyLasers = 0 private var enemyShields = 0 private var enemyRating = 0 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreate(savedInstanceState) return inflater.inflate( R.layout.fragment_33sl_adventure_weaponcombat, container, false ) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val adv = context as SLAdventure plusEnemylasersButton.setOnClickListener({ enemyLasers += 1 refreshScreensFromResume() }) plusEnemyshieldsButton.setOnClickListener({ enemyShields += 1 refreshScreensFromResume() }) plusEnemyratingButton.setOnClickListener({ enemyRating += 1 refreshScreensFromResume() }) minusEnemylasersButton.setOnClickListener({ enemyLasers = maxOf(0, enemyLasers - 1) refreshScreensFromResume() }) minusEnemyshieldsButton.setOnClickListener({ enemyShields = maxOf(0, enemyShields - 1) refreshScreensFromResume() }) minusEnemyratingButton.setOnClickListener({ enemyRating = maxOf(0, enemyRating - 1) refreshScreensFromResume() }) pluslasersButton.setOnClickListener({ adv.currentLasers += 1 refreshScreensFromResume() }) plusshieldsButton.setOnClickListener({ adv.currentShields += 1 refreshScreensFromResume() }) plusratingButton.setOnClickListener({ adv.rating += 1 refreshScreensFromResume() }) minuslasersButton.setOnClickListener({ adv.currentLasers = maxOf(0, adv.currentLasers - 1) refreshScreensFromResume() }) minusshieldsButton.setOnClickListener({ adv.currentShields = maxOf(0, adv.currentShields - 1) refreshScreensFromResume() }) minusratingButton.setOnClickListener({ adv.rating = maxOf(0, adv.rating - 1) refreshScreensFromResume() }) buttonAttack.setOnClickListener({ combatTurn() refreshScreensFromResume() }) } fun combatTurn() { val adv = activity as SLAdventure var combatText: String if (adv.rating > enemyRating) { combatText = playerTurn() combatText += if (enemyShields > 0) "\n${enemyTurn()}" else "\n${getString(R.string.slPlayerVictory)}" combatText += if (adv.currentShields == 0) "\n${getString(R.string.slEnemyVictory)}" else "" } else { combatText = enemyTurn() combatText += if (adv.currentShields > 0) "\n${playerTurn()}" else "\n${getString(R.string.slEnemyVictory)}" combatText += if (enemyShields == 0) "\n${getString(R.string.slPlayerVictory)}" else "" } combatResult?.text = combatText } private fun enemyTurn(): String { val adv = activity as SLAdventure if (DiceRoller.rollD6() <= enemyLasers) { adv.currentShields = maxOf(0, adv.currentShields - 2) return getString(R.string.slEnemyHitPlayer, 2) } return getString(R.string.enemyMissed) } private fun playerTurn(): String { val adv = activity as SLAdventure if (DiceRoller.rollD6() <= adv.currentLasers) { enemyShields = maxOf(0, enemyShields - 2) return getString(R.string.slDirectHit, 2) } return getString(R.string.missedTheEnemy) } override fun refreshScreensFromResume() { val adv = activity as SLAdventure enemyshieldsValue?.text = enemyShields.toString() enemylasersValue?.text = enemyLasers.toString() enemyratingValue?.text = enemyRating.toString() playerratingValue?.text = adv.rating.toString() playershieldsValue?.text = adv.currentShields.toString() playerlasersValue?.text = adv.currentLasers.toString() buttonAttack.isEnabled = adv.currentShields > 0 } }
lgpl-3.0
211e7d66f87e0df24b7f5d7c1da57d45
31.622517
104
0.623427
4.709369
false
false
false
false
TachiWeb/TachiWeb-Server
Tachiyomi-App/src/compat/java/eu/kanade/tachiyomi/network/CloudflareInterceptor.kt
1
3722
package eu.kanade.tachiyomi.network import com.gargoylesoftware.htmlunit.BrowserVersion import com.gargoylesoftware.htmlunit.WebClient import com.gargoylesoftware.htmlunit.html.HtmlPage import okhttp3.* import uy.kohesive.injekt.injectLazy import java.io.IOException class CloudflareInterceptor : Interceptor { private val network: NetworkHelper by injectLazy() private val serverCheck = arrayOf("cloudflare-nginx", "cloudflare") @Synchronized override fun intercept(chain: Interceptor.Chain): Response { val response = chain.proceed(chain.request()) // Check if Cloudflare anti-bot is on if (response.code() == 503 && response.header("Server") in serverCheck) { return try { chain.proceed(resolveChallenge(response)) } catch (e: Exception) { // Because OkHttp's enqueue only handles IOExceptions, wrap the exception so that // we don't crash the entire app throw IOException(e) } } return response } private fun resolveChallenge(response: Response): Request { val browserVersion = BrowserVersion.BrowserVersionBuilder(BrowserVersion.BEST_SUPPORTED) .setUserAgent(response.request().header("User-Agent") ?: BrowserVersion.BEST_SUPPORTED.userAgent) .build() val convertedCookies = WebClient(browserVersion).use { webClient -> webClient.options.isThrowExceptionOnFailingStatusCode = false webClient.options.isThrowExceptionOnScriptError = false webClient.getPage<HtmlPage>(response.request().url().toString()) webClient.waitForBackgroundJavaScript(10000) // Challenge solved, process cookies webClient.cookieManager.cookies.filter { // Only include Cloudflare cookies it.name.startsWith("__cf") || it.name.startsWith("cf_") }.map { // Convert cookies -> OkHttp format Cookie.Builder() .domain(it.domain.removePrefix(".")) .expiresAt(it.expires.time) .name(it.name) .path(it.path) .value(it.value).apply { if (it.isHttpOnly) httpOnly() if (it.isSecure) secure() }.build() } } // Copy cookies to cookie store convertedCookies.forEach { network.cookies.addAll( HttpUrl.Builder() .scheme("http") .host(it.domain()) .build(), listOf(it) ) } // Merge new and existing cookies for this request // Find the cookies that we need to merge into this request val convertedForThisRequest = convertedCookies.filter { it.matches(response.request().url()) } // Extract cookies from current request val existingCookies = Cookie.parseAll( response.request().url(), response.request().headers() ) // Filter out existing values of cookies that we are about to merge in val filteredExisting = existingCookies.filter { existing -> convertedForThisRequest.none { converted -> converted.name() == existing.name() } } val newCookies = filteredExisting + convertedForThisRequest return response.request().newBuilder() .header("Cookie", newCookies.map { it.toString() }.joinToString("; ")) .build() } }
apache-2.0
a852f9fb87a42ef92a2332a57ee69740
40.820225
113
0.580602
5.279433
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/WakeOnLanActionType.kt
1
936
package ch.rmy.android.http_shortcuts.scripting.actions.types import ch.rmy.android.framework.extensions.takeUnlessEmpty import ch.rmy.android.http_shortcuts.scripting.ActionAlias import ch.rmy.android.http_shortcuts.scripting.actions.ActionDTO class WakeOnLanActionType : BaseActionType() { override val type = TYPE override fun fromDTO(actionDTO: ActionDTO) = WakeOnLanAction( macAddress = actionDTO.getString(0) ?: "", ipAddress = actionDTO.getString(1)?.takeUnlessEmpty() ?: "255.255.255.255", port = actionDTO.getInt(2) ?: 9, ) override fun getAlias() = ActionAlias( functionName = FUNCTION_NAME, functionNameAliases = setOf(FUNCTION_NAME_ALIAS), parameters = 3, ) companion object { private const val TYPE = "wake_on_lan" private const val FUNCTION_NAME = "wakeOnLan" private const val FUNCTION_NAME_ALIAS = "wakeOnLAN" } }
mit
162fc25cf9e4796e0f22b488243f44eb
32.428571
83
0.695513
3.949367
false
false
false
false
sg26565/hott-transmitter-config
HoTT-Model/src/main/kotlin/de/treichels/hott/model/enums/ESCType.kt
1
1528
package de.treichels.hott.model.enums import de.treichels.hott.util.get import java.util.* enum class ESCType(override val productCode: Int, override val orderNo: String = "", override val category: String = ESCType.category, override val baudRate: Int = 19200) : Registered<ESCType> { bl_control_18(15, "33718"), bl_control_35(12, "33735"), bl_control_45(12, "33745"), bl_control_50(16, "S3046"), bl_control_60(12, "33760"), bl_control_70(12, "33770"), bl_control_100(12, "S3030"), bl_control_80_hv(13, "S3041"), bl_control_100_hv(13, "S3036"), bl_control_120_hv(13, "S3038"), bl_control_160_hv(13, "S3039"), bl_control_160_hv_cool(13, "S3064"), bl_control_60_opto(14, "S3031"), bl_control_80_opto(14, "S3042"), bl_control_100_opto(14, "S3037"), bl_control_120_opto(14, "S3032"), bl_control_160_opto(14, "S3033"), genius_60(24, "S3084"), genius_120(24, "S3051"), genius_160(24, "S3078"), genius_180(24, "S3085"), gm_genius_90(5, "97171"), gm_genius_120(5, "97170"), programmer_box(13017000, "S8272"), wlan_module(13020400, "S8505"); override fun toString(): String = ResourceBundle.getBundle(javaClass.name)[name] + " ($orderNo)" companion object { fun forProductCode(productCode: Int) = ESCType.values().firstOrNull { s -> s.productCode == productCode } fun forOrderNo(orderNo: String) = ESCType.values().firstOrNull { s -> s.orderNo == orderNo } val category = "Speed_Controller" } }
lgpl-3.0
dd9fbdab52ada81d2efb0ee712202738
36.268293
194
0.637435
2.793419
false
false
false
false
android/midi-samples
MidiTools/src/main/java/com/example/android/miditools/MusicKeyboardView.kt
1
14400
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.miditools import android.annotation.TargetApi import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Rect import android.os.Build import android.util.AttributeSet import android.view.MotionEvent import android.view.View import java.util.ArrayList import java.util.HashMap import kotlin.math.abs import kotlin.math.max import kotlin.math.roundToInt /** * View that displays a traditional piano style keyboard. Finger presses are reported to a * MusicKeyListener. Keys that pressed are highlighted. Running a finger along the top of the * keyboard will only hit black keys. Running a finger along the bottom of the keyboard will only * hit white keys. */ class MusicKeyboardView(context: Context?, attrs: AttributeSet?) : View(context, attrs) { // Preferences private var mNumKeys = 0 private var mNumPortraitKeys = NOTES_PER_OCTAVE + 1 private var mNumLandscapeKeys = 2 * NOTES_PER_OCTAVE + 1 private var mNumWhiteKeys = 15 // Geometry. private var mWidth = 0f private var mHeight = 0f private var mWhiteKeyWidth = 0f private var mBlackKeyWidth = 0f // Y position of bottom of black keys. private var mBlackBottom = 0f private lateinit var mBlackKeyRectangles: Array<Rect> // Keyboard state private val mNotesOnByPitch = BooleanArray(128) // Appearance private var mShadowPaint: Paint? = null private var mBlackOnKeyPaint: Paint? = null private var mBlackOffKeyPaint: Paint? = null private var mWhiteOnKeyPaint: Paint? = null private var mWhiteOffKeyPaint: Paint? = null private val mLegato = true // Maps each finger to a pair of notes and y location private val mFingerMap = HashMap<Int, Pair<Int, Float>>() // Note number for the left most key. private var mLowestPitch = PITCH_MIDDLE_C - NOTES_PER_OCTAVE private val mListeners = ArrayList<MusicKeyListener>() /** Implement this to receive keyboard events. */ interface MusicKeyListener { /** This will be called when a key is pressed. */ fun onKeyDown(keyIndex: Int) /** This will be called when a key is pressed. */ fun onKeyUp(keyIndex: Int) /** This will called when the pitch bend changes. * pitch bend will be a float between 0 and 1 */ fun onPitchBend(keyIndex: Int, bend: Float) } private fun init() { mShadowPaint = Paint(Paint.ANTI_ALIAS_FLAG) mShadowPaint!!.style = Paint.Style.FILL mShadowPaint!!.color = -0x8f8f90 mBlackOnKeyPaint = Paint(Paint.ANTI_ALIAS_FLAG) mBlackOnKeyPaint!!.style = Paint.Style.FILL mBlackOnKeyPaint!!.color = -0xdfdf20 mBlackOffKeyPaint = Paint(Paint.ANTI_ALIAS_FLAG) mBlackOffKeyPaint!!.style = Paint.Style.FILL mBlackOffKeyPaint!!.color = -0xdfdfe0 mWhiteOnKeyPaint = Paint(Paint.ANTI_ALIAS_FLAG) mWhiteOnKeyPaint!!.style = Paint.Style.FILL mWhiteOnKeyPaint!!.color = -0x9f9f10 mWhiteOffKeyPaint = Paint(Paint.ANTI_ALIAS_FLAG) mWhiteOffKeyPaint!!.style = Paint.Style.FILL mWhiteOffKeyPaint!!.color = -0xf0f10 } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { mWidth = w.toFloat() mHeight = h.toFloat() mNumKeys = if (mHeight > mWidth) mNumPortraitKeys else mNumLandscapeKeys mNumWhiteKeys = 0 // Count white keys. for (i in 0 until mNumKeys) { val pitch = mLowestPitch + i if (!isPitchBlack(pitch)) { mNumWhiteKeys++ } } mWhiteKeyWidth = mWidth / mNumWhiteKeys mBlackKeyWidth = mWhiteKeyWidth * BLACK_KEY_WIDTH_FACTOR mBlackBottom = mHeight * BLACK_KEY_HEIGHT_FACTOR makeBlackRectangles() } private fun makeBlackRectangles() { val top = 0 val rectangles = ArrayList<Rect>() var whiteKeyIndex = 0 var blackKeyIndex = 0 for (i in 0 until mNumKeys) { val x = mWhiteKeyWidth * whiteKeyIndex val pitch = mLowestPitch + i val note = pitch % NOTES_PER_OCTAVE if (NOTE_IN_OCTAVE_IS_BLACK[note]) { val leftComplement = BLACK_KEY_LEFT_COMPLEMENTS[mLowestPitch % 12] val offset = (BLACK_KEY_OFFSET_FACTOR * BLACK_KEY_HORIZONTAL_OFFSETS[(blackKeyIndex + leftComplement) % 5]) var left = x - mBlackKeyWidth * (0.55f - offset) left += WHITE_KEY_GAP / 2f val right = left + mBlackKeyWidth val rect = Rect(left.roundToInt(), top, right.roundToInt(), mBlackBottom.roundToInt()) rectangles.add(rect) blackKeyIndex++ } else { whiteKeyIndex++ } } mBlackKeyRectangles = rectangles.toTypedArray() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) var whiteKeyIndex = 0 canvas.drawRect(0f, 0f, mWidth, mHeight, mShadowPaint!!) // Draw white keys first. for (i in 0 until mNumKeys) { val pitch = mLowestPitch + i val note = pitch % NOTES_PER_OCTAVE if (!NOTE_IN_OCTAVE_IS_BLACK[note]) { val x = mWhiteKeyWidth * whiteKeyIndex + WHITE_KEY_GAP / 2 val paint = if (mNotesOnByPitch[pitch]) mWhiteOnKeyPaint else mWhiteOffKeyPaint canvas.drawRect( x, 0f, x + mWhiteKeyWidth - WHITE_KEY_GAP, mHeight, paint!! ) whiteKeyIndex++ } } // Then draw black keys over the white keys. var blackKeyIndex = 0 for (i in 0 until mNumKeys) { val pitch = mLowestPitch + i val note = pitch % NOTES_PER_OCTAVE if (NOTE_IN_OCTAVE_IS_BLACK[note]) { val r = mBlackKeyRectangles[blackKeyIndex] val paint = if (mNotesOnByPitch[pitch]) mBlackOnKeyPaint else mBlackOffKeyPaint canvas.drawRect(r, paint!!) blackKeyIndex++ } } } @TargetApi(Build.VERSION_CODES.FROYO) override fun onTouchEvent(event: MotionEvent): Boolean { super.onTouchEvent(event) val action = event.actionMasked // Track individual fingers. val pointerIndex = event.actionIndex var id = event.getPointerId(pointerIndex) // Get the pointer's current position var x = event.getX(pointerIndex) var y = event.getY(pointerIndex) // Some devices can return negative x or y, which can cause an array exception. x = max(x, 0.0f) y = max(y, 0.0f) when (action) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> { onFingerDown(id, x, y) } MotionEvent.ACTION_MOVE -> { val pointerCount = event.pointerCount var i = 0 while (i < pointerCount) { id = event.getPointerId(i) x = event.getX(i) y = event.getY(i) x = max(x, 0.0f) y = max(y, 0.0f) onFingerMove(id, x, y) i++ } } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> { onFingerUp(id, x, y) } MotionEvent.ACTION_CANCEL -> { onAllFingersUp() } else -> { } } performClick() // Must return true or we do not get the ACTION_MOVE and // ACTION_UP events. return true } @TargetApi(Build.VERSION_CODES.FROYO) override fun performClick(): Boolean { return super.performClick() } private fun onFingerDown(id: Int, x: Float, y: Float) { val pitch = xyToPitch(x, y) fireKeyDown(pitch) mFingerMap[id] = Pair(pitch, y) } private fun onFingerMove(id: Int, x: Float, y: Float) { val previousPitch = mFingerMap[id]?.first if (previousPitch != null) { val pitch = if (y < mBlackBottom) { // Only hit black keys if above line. xyToBlackPitch(x, y) } else { xToWhitePitch(x) } // Did we change to a new key. if (pitch >= 0 && pitch != previousPitch) { if (mLegato) { fireKeyDown(pitch) fireKeyUp(previousPitch) } else { fireKeyUp(previousPitch) fireKeyDown(pitch) } mFingerMap[id] = Pair(pitch, y) } if (pitch >= 0) { val previousY = mFingerMap[id]?.second if ((pitch != previousPitch) || (previousY == null) || (PITCH_BEND_HEIGHT_CHANGE_FACTOR * mHeight < abs(y - previousY))) { if (y < mBlackBottom) { firePitchBend(pitch, y / mBlackBottom) } else { firePitchBend(pitch, (y - mBlackBottom) / (mHeight - mBlackBottom)) } mFingerMap[id] = Pair(pitch, y) } } } } private fun onFingerUp(id: Int, x: Float, y: Float) { val previousPitch = mFingerMap[id]?.first if (previousPitch != null) { fireKeyUp(previousPitch) mFingerMap.remove(id) } else { val pitch = xyToPitch(x, y) fireKeyUp(pitch) } } private fun onAllFingersUp() { // Turn off all notes. for (notes in mFingerMap.values) { fireKeyUp(notes.first) } mFingerMap.clear() } private fun fireKeyDown(pitch: Int) { for (listener in mListeners) { listener.onKeyDown(pitch) } mNotesOnByPitch[pitch] = true invalidate() } private fun fireKeyUp(pitch: Int) { for (listener in mListeners) { listener.onKeyUp(pitch) } mNotesOnByPitch[pitch] = false invalidate() } private fun firePitchBend(pitch: Int, bend: Float) { for (listener in mListeners) { listener.onPitchBend(pitch, bend) } } private fun xyToPitch(x: Float, y: Float): Int { var pitch = -1 if (y < mBlackBottom) { pitch = xyToBlackPitch(x, y) } if (pitch < 0) { pitch = xToWhitePitch(x) } return pitch } private fun isPitchBlack(pitch: Int): Boolean { val note = pitch % NOTES_PER_OCTAVE return NOTE_IN_OCTAVE_IS_BLACK[note] } // Convert x to MIDI pitch. Ignores black keys. private fun xToWhitePitch(x: Float): Int { val leftComplement = WHITE_KEY_LEFT_COMPLEMENTS[mLowestPitch % 12] val octave2 = mLowestPitch / 12 - 1 val whiteKeyIndex = (x / mWhiteKeyWidth).toInt() + leftComplement val octave = whiteKeyIndex / WHITE_KEY_OFFSETS.size val indexInOctave = whiteKeyIndex - octave * WHITE_KEY_OFFSETS.size return 12 * (octave2 + octave + 1) + WHITE_KEY_OFFSETS[indexInOctave] } // Convert x to MIDI pitch. Ignores white keys. private fun xyToBlackPitch(x: Float, y: Float): Int { var result = -1 var blackKeyIndex = 0 for (i in 0 until mNumKeys) { val pitch = mLowestPitch + i if (isPitchBlack(pitch)) { val rect = mBlackKeyRectangles[blackKeyIndex] if (rect.contains(x.toInt(), y.toInt())) { result = pitch break } blackKeyIndex++ } } return result } fun addMusicKeyListener(musicKeyListener: MusicKeyListener) { mListeners.add(musicKeyListener) } companion object { // Adjust proportions of the keys. private const val WHITE_KEY_GAP = 10 private const val PITCH_MIDDLE_C = 60 private const val NOTES_PER_OCTAVE = 12 private val WHITE_KEY_OFFSETS = intArrayOf( 0, 2, 4, 5, 7, 9, 11 ) private const val BLACK_KEY_HEIGHT_FACTOR = 0.60f private const val BLACK_KEY_WIDTH_FACTOR = 0.6f private const val BLACK_KEY_OFFSET_FACTOR = 0.18f private const val PITCH_BEND_HEIGHT_CHANGE_FACTOR = 0.05f private val BLACK_KEY_HORIZONTAL_OFFSETS = intArrayOf( -1, 1, -1, 0, 1 ) private val NOTE_IN_OCTAVE_IS_BLACK = booleanArrayOf( false, true, false, true, false, false, true, false, true, false, true, false ) // These COMPLEMENTS are used to fix a problem with the alignment of the keys. // If mLowestPitch starts from the beginning of some octave then there is no problem. // But if it's not, then the BLACK_KEY_HORIZONTAL_OFFSETS[blackKeyIndex % 5] would give // us the wrong result. So, the "left complement" in this case is the number of black keys we // should add to the blackKeyIndex to fill the left space down to the beginning of the octave. private val WHITE_KEY_LEFT_COMPLEMENTS = intArrayOf( 0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6 ) private val BLACK_KEY_LEFT_COMPLEMENTS = intArrayOf( 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 ) } init { init() } }
apache-2.0
d9e42eb88c7ab4e11a87e34dcbde71bd
34.64604
138
0.575556
4.090909
false
false
false
false
JakeWharton/dex-method-list
diffuse/src/main/kotlin/com/jakewharton/diffuse/Aab.kt
1
2728
package com.jakewharton.diffuse import com.android.aapt.Resources.XmlNode import com.jakewharton.diffuse.Aab.Module.Companion.toModule import com.jakewharton.diffuse.ApiMapping.Companion.toApiMapping import com.jakewharton.diffuse.ArchiveFile.Type.Companion.toAabFileType import com.jakewharton.diffuse.ArchiveFiles.Companion.toArchiveFiles import com.jakewharton.diffuse.Dex.Companion.toDex import com.jakewharton.diffuse.Manifest.Companion.toManifest import com.jakewharton.diffuse.io.Input import com.jakewharton.diffuse.io.Zip class Aab private constructor( override val filename: String?, val apiMapping: ApiMapping, val baseModule: Module, val featureModules: Map<String, Module> ) : Binary { // TODO remove toTypedArray call https://youtrack.jetbrains.com/issue/KT-12663 val modules get() = listOf(baseModule, *featureModules.values.toTypedArray()) class Module private constructor( val files: ArchiveFiles, val manifest: Manifest, val dexes: List<Dex> ) { companion object { internal const val manifestFilePath = "manifest/${Apk.manifestFileName}" fun Zip.toModule(): Module { val files = toArchiveFiles { it.toAabFileType() } val manifest = this[manifestFilePath].asInput().source().use { XmlNode.parseFrom(it.inputStream()).toManifest() } val dexes = entries.filter { it.path.startsWith("dex/") }.map { it.asInput().toDex() } return Module(files, manifest, dexes) } } } companion object { private const val bundleMetadataDirectoryName = "BUNDLE-METADATA" private const val metadataObfuscationDirectoryName = "$bundleMetadataDirectoryName/com.android.tools.build.obfuscation/proguard.map" private const val baseDirectoryName = "base" @JvmStatic @JvmName("parse") fun Input.toAab(): Aab { toZip().use { zip -> val apiMapping = zip.find(metadataObfuscationDirectoryName)?.asInput()?.toApiMapping() ?: ApiMapping.EMPTY val baseModule = zip.directoryView(baseDirectoryName).toModule() val featureModules = zip.directories // TODO there's probably a better way to discover feature module names. .filter { it != baseDirectoryName && it != bundleMetadataDirectoryName && it != "META-INF" } .associateWith { zip.directoryView(it).toModule() } return Aab(name, apiMapping, baseModule, featureModules) } } private val Zip.directories: List<String> get() { return entries.mapNotNullTo(LinkedHashSet()) { val slash = it.path.indexOf('/') if (slash == -1) { null } else { it.path.substring(0, slash) } }.sorted() } } }
apache-2.0
898801a10c0f8a397a7ccd187f44dc01
36.369863
104
0.693915
4.184049
false
false
false
false
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/abp/AbpFragment.kt
1
6464
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.adblock.ui.abp import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.* import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton import dagger.hilt.android.AndroidEntryPoint import jp.hazuki.yuzubrowser.adblock.R import jp.hazuki.yuzubrowser.adblock.filter.abp.getAbpBlackListFile import jp.hazuki.yuzubrowser.adblock.filter.abp.getAbpWhiteListFile import jp.hazuki.yuzubrowser.adblock.filter.abp.getAbpWhitePageListFile import jp.hazuki.yuzubrowser.adblock.filter.abp.isNeedUpdate import jp.hazuki.yuzubrowser.adblock.filter.unified.getFilterDir import jp.hazuki.yuzubrowser.adblock.repository.abp.AbpDatabase import jp.hazuki.yuzubrowser.adblock.repository.abp.AbpEntity import jp.hazuki.yuzubrowser.adblock.service.AbpUpdateService import jp.hazuki.yuzubrowser.core.utility.utils.ui import jp.hazuki.yuzubrowser.ui.extensions.applyIconColor import jp.hazuki.yuzubrowser.ui.widget.recycler.OnRecyclerListener import javax.inject.Inject @AndroidEntryPoint class AbpFragment : Fragment(), OnRecyclerListener, AddAbpDialog.OnAddItemListener, AbpMenuDialog.OnAbpMenuListener, AbpItemDeleteDialog.OnAbpItemDeleteListener { @Inject internal lateinit var abpDatabase: AbpDatabase private lateinit var adapter: AbpEntityAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_abp_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val activity = activity ?: throw IllegalStateException() val recyclerView: RecyclerView = view.findViewById(R.id.recyclerView) val fab: FloatingActionButton = view.findViewById(R.id.fab) adapter = AbpEntityAdapter(activity, mutableListOf(), this@AbpFragment) ui { adapter.items.addAll(abpDatabase.abpDao().getAll()) adapter.notifyDataSetChanged() } recyclerView.run { layoutManager = LinearLayoutManager(activity) adapter = [email protected] } fab.setOnClickListener { AddAbpDialog.create(null) .show(childFragmentManager, "edit") } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.abp_fragment, menu) applyIconColor(menu) } override fun onRecyclerItemClicked(v: View, position: Int) { val entity = adapter.items[position] entity.enabled = !entity.enabled ui { abpDatabase.abpDao().update(entity) } adapter.notifyItemChanged(position) if (entity.enabled && entity.isNeedUpdate()) { AbpUpdateService.update(requireContext(), entity, result) } } override fun onRecyclerItemLongClicked(v: View, position: Int): Boolean { AbpMenuDialog(position, adapter.items[position]) .show(childFragmentManager, "menu") return true } override fun onAddEntity(entity: AbpEntity) { ui { if (entity.entityId > 0) { abpDatabase.abpDao().update(entity) } else { entity.entityId = abpDatabase.abpDao().inset(entity).toInt() } AbpUpdateService.update(requireContext(), entity, result) } } override fun onAskDelete(index: Int, entity: AbpEntity) { AbpItemDeleteDialog(index, entity).show(childFragmentManager, "delete") } override fun onEdit(index: Int, entity: AbpEntity) { AddAbpDialog.create(entity).show(childFragmentManager, "edit") } override fun onRefresh(index: Int, entity: AbpEntity) { AbpUpdateService.update(requireContext(), entity, result) } override fun onDelete(index: Int, entity: AbpEntity) { ui { abpDatabase.abpDao().delete(entity) val dir = requireContext().getFilterDir() dir.getAbpBlackListFile(entity).delete() dir.getAbpWhiteListFile(entity).delete() dir.getAbpWhitePageListFile(entity).delete() val i = adapter.items.indexOf(entity) adapter.items.removeAt(i) adapter.notifyItemRemoved(i) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.update -> { AbpUpdateService.updateAll(requireContext(), true, result) return true } } return super.onOptionsItemSelected(item) } private val result = object : AbpUpdateService.UpdateResult(Handler(Looper.getMainLooper())) { override fun onUpdated(entity: AbpEntity) { updateInternal(entity) } override fun onFailedUpdate(entity: AbpEntity) { updateInternal(entity) } private fun updateInternal(entity: AbpEntity) { val index = adapter.items.indexOf(entity) if (index < 0) { adapter.items.add(entity) adapter.notifyItemChanged(adapter.itemCount - 1) } else { adapter.items[index] = entity adapter.notifyItemChanged(index) } } override fun onUpdateAll() { ui { adapter.items.clear() adapter.items.addAll(abpDatabase.abpDao().getAll()) adapter.notifyDataSetChanged() } } } }
apache-2.0
a5ccf7ab9c75e1ebdcc71dd585cd8460
36.364162
162
0.678527
4.548909
false
false
false
false
hazuki0x0/YuzuBrowser
legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/utils/view/pie/PieMenu.kt
1
12682
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.legacy.utils.view.pie import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.MotionEvent import android.view.SoundEffectConstants import android.view.ViewGroup import android.widget.FrameLayout import jp.hazuki.yuzubrowser.core.utility.extensions.dimension import jp.hazuki.yuzubrowser.core.utility.extensions.getResColor import jp.hazuki.yuzubrowser.legacy.R import java.util.* import kotlin.math.asin import kotlin.math.cos import kotlin.math.sin import kotlin.math.sqrt class PieMenu @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { private val center = Point(0, 0) private var radius: Int = 0 private var radiusInc: Int = 0 private var slop: Int = 0 private var touchOffset: Int = 0 private var position: Int = 0 var isOpen: Boolean = false private set private var controller: PieController? = null private val items = ArrayList<PieItem>() private var levels: Int = 0 private val counts = IntArray(MAX_LEVELS) private var pieView: PieView? = null private val normalPaint = Paint() private val selectedPaint = Paint() // touch handling internal var currentItem: PieItem? = null interface PieController { /** * called before menu opens to customize menu * returns if pie state has been changed */ fun onOpen(): Boolean } /** * A view like object that lives off of the pie menu */ interface PieView { interface OnLayoutListener { fun onLayout(ax: Int, ay: Int, left: Boolean) } fun setLayoutListener(l: OnLayoutListener) fun layout(anchorX: Int, anchorY: Int, onleft: Boolean, angle: Float) fun draw(c: Canvas) fun onTouchEvent(evt: MotionEvent): Boolean } init { radius = context.dimension(R.dimen.qc_radius_start) radiusInc = context.dimension(R.dimen.qc_radius_increment) slop = context.dimension(R.dimen.qc_slop) touchOffset = context.dimension(R.dimen.qc_touch_offset) setWillNotDraw(false) isDrawingCacheEnabled = false normalPaint.color = context.getResColor(R.color.qc_normal) normalPaint.isAntiAlias = true selectedPaint.color = context.getResColor(R.color.qc_selected) selectedPaint.isAntiAlias = true } fun setController(ctl: PieController) { controller = ctl } fun addItem(item: PieItem) { // add the item to the pie itself items.add(item) val l = item.level levels = levels.coerceAtLeast(l) counts[l]++ } fun removeItem(item: PieItem) { items.remove(item) counts[item.level]-- } fun clearItems() { items.clear() levels = 0 for (i in 0 until MAX_LEVELS) { counts[i] = 0 } } private fun onTheLeft(): Boolean { return center.x < slop } /** * guaranteed has center set * * @param show */ private fun show(show: Boolean) { isOpen = show if (isOpen) { if (controller != null) { controller!!.onOpen() } layoutPie() } if (!show) { currentItem = null pieView = null } invalidate() } private fun setCenter(x: Int, y: Int) { if (x < slop) { center.x = 0 } else { center.x = width } center.y = y } private fun layoutPie() { val emptyangle = Math.PI.toFloat() / 16 val rgap = 2 var inner = radius + rgap var outer = radius + radiusInc - rgap val gap = 1 for (i in 0 until levels) { val level = i + 1 val sweep = (Math.PI - 2 * emptyangle).toFloat() / counts[level] var angle = emptyangle + sweep / 2 for (item in items) { if (item.level == level) { val view = item.view val w = view.layoutParams.width val h = view.layoutParams.height val r = inner + (outer - inner) * 55 / 100 var x = (r * sin(angle.toDouble())).toInt() val y = center.y - (r * cos(angle.toDouble())).toInt() - h / 2 x = if (onTheLeft()) { center.x + x - w / 2 } else { center.x - x - w / 2 } view.layout(x, y, x + w, y + h) val itemstart = angle - sweep / 2 val slice = makeSlice(getDegrees(itemstart.toDouble()) - gap, getDegrees((itemstart + sweep).toDouble()) + gap, outer, inner, center) item.setGeometry(itemstart, sweep, inner, outer, slice) angle += sweep } } inner += radiusInc outer += radiusInc } } /** * converts a * * @param angle from 0..PI to Android degrees (clockwise starting at 3 * o'clock) * @return skia angle */ private fun getDegrees(angle: Double): Float { return (270 - 180 * angle / Math.PI).toFloat() } override fun onDraw(canvas: Canvas) { if (isOpen) { var state: Int for (item in items) { val p = if (item.isSelected) selectedPaint else normalPaint state = canvas.save() if (onTheLeft()) { canvas.scale(-1f, 1f) } drawPath(canvas, item.path, p) canvas.restoreToCount(state) drawItem(canvas, item) } if (pieView != null) { pieView!!.draw(canvas) } } } private fun drawItem(canvas: Canvas, item: PieItem) { // draw the item view val view = item.view val state = canvas.save() canvas.translate(view.x, view.y) view.draw(canvas) canvas.restoreToCount(state) } private fun drawPath(canvas: Canvas, path: Path?, paint: Paint?) { canvas.drawPath(path!!, paint!!) } private fun makeSlice(start: Float, end: Float, outer: Int, inner: Int, center: Point?): Path { val bb = RectF((center!!.x - outer).toFloat(), (center.y - outer).toFloat(), (center.x + outer).toFloat(), (center.y + outer).toFloat()) val bbi = RectF((center.x - inner).toFloat(), (center.y - inner).toFloat(), (center.x + inner).toFloat(), (center.y + inner).toFloat()) val path = Path() path.arcTo(bb, start, end - start, true) path.arcTo(bbi, end, start - end) path.close() return path } // touch handling for pie @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(evt: MotionEvent): Boolean { val x = evt.x val y = evt.y val action = evt.actionMasked if (MotionEvent.ACTION_DOWN == action) { if (position != 1 && x > width - slop || position != 2 && x < slop) { setCenter(x.toInt(), y.toInt()) show(true) return true } } else if (MotionEvent.ACTION_UP == action) { if (isOpen) { val handled = pieView?.onTouchEvent(evt) ?: false val item = currentItem deselect() show(false) if (!handled && item != null) { item.view.performClick() } return true } } else if (MotionEvent.ACTION_CANCEL == action) { if (isOpen) { show(false) } deselect() return false } else if (MotionEvent.ACTION_MOVE == action) { val handled = pieView?.onTouchEvent(evt) ?: false val polar = getPolar(x, y) val maxr = radius + levels * radiusInc + 50 if (handled) { invalidate() return false } if (polar.y > maxr) { deselect() show(false) evt.action = MotionEvent.ACTION_DOWN if (parent != null) { (parent as ViewGroup).dispatchTouchEvent(evt) } return false } val item = findItem(polar) if (currentItem != item) { onEnter(item) if (item != null && item.isPieView) { val cx = item.view.left + if (onTheLeft()) item.view.width else 0 val cy = item.view.top pieView = item.pieView layoutPieView(pieView!!, cx, cy, (item.startAngle + item.sweep) / 2) } invalidate() } } // always re-dispatch event return false } private fun layoutPieView(pv: PieView, x: Int, y: Int, angle: Float) { pv.layout(x, y, onTheLeft(), angle) } /** * enter a slice for a view * updates model only * * @param item */ private fun onEnter(item: PieItem?) { // deselect currentItem?.isSelected = false if (item != null) { // clear up stack playSoundEffect(SoundEffectConstants.CLICK) item.isSelected = true pieView = null } currentItem = item } private fun deselect() { currentItem?.isSelected = false currentItem = null pieView = null } private fun getPolar(tx: Float, ty: Float): PointF { var x = tx var y = ty val res = PointF() // get angle and radius from x/y res.x = Math.PI.toFloat() / 2 x = center.x - x if (center.x < slop) { x = -x } y = center.y - y res.y = sqrt((x * x + y * y).toDouble()).toFloat() if (y > 0) { res.x = asin((x / res.y).toDouble()).toFloat() } else if (y < 0) { res.x = (Math.PI - asin((x / res.y).toDouble())).toFloat() } return res } /** * @param polar x: angle, y: dist * @return the item at angle/dist or null */ private fun findItem(polar: PointF): PieItem? { // find the matching item: return items.firstOrNull { it.innerRadius - touchOffset < polar.y && it.outerRadius - touchOffset > polar.y && it.startAngle < polar.x && it.startAngle + it.sweep > polar.x } } fun notifyChangeState() { for (item in items) { item.notifyChangeState() } } fun setRadiusStart(radius: Int) { this.radius = radius } fun setRadiusIncrement(radiusInc: Int) { this.radiusInc = radiusInc } fun setSlop(slop: Int) { this.slop = slop } fun setPosition(position: Int) { this.position = position } fun setTouchOffset(touchOffset: Int) { this.touchOffset = touchOffset } fun setNormalColor(color: Int) { normalPaint.color = color } fun setSelectedColor(color: Int) { selectedPaint.color = color } fun setColorFilterToItems(color: Int) { val cf = if (color != 0) PorterDuffColorFilter(color, PorterDuff.Mode.MULTIPLY) else null for (item in items) { item.view.colorFilter = cf } } companion object { private const val MAX_LEVELS = 5 } }
apache-2.0
f5ee6ef6eb661494cbec9f6a10acb215
28.561772
114
0.527362
4.355082
false
false
false
false
AdamMc331/CashCaretaker
app/src/main/java/com/androidessence/cashcaretaker/core/BaseViewModel.kt
1
1692
package com.androidessence.cashcaretaker.core import androidx.databinding.Bindable import androidx.databinding.Observable import androidx.databinding.PropertyChangeRegistry import androidx.lifecycle.ViewModel open class BaseViewModel : ViewModel(), Observable { @Transient private var mCallbacks: PropertyChangeRegistry? = null override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback) { synchronized(this) { if (mCallbacks == null) { mCallbacks = PropertyChangeRegistry() } } mCallbacks!!.add(callback) } override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback) { synchronized(this) { if (mCallbacks == null) { return } } mCallbacks!!.remove(callback) } /** * Notifies listeners that all properties of this instance have changed. */ fun notifyChange() { synchronized(this) { if (mCallbacks == null) { return } } mCallbacks!!.notifyCallbacks(this, 0, null) } /** * Notifies listeners that a specific property has changed. The getter for the property * that changes should be marked with [Bindable] to generate a field in * `BR` to be used as `fieldId`. * * @param fieldId The generated BR id for the Bindable field. */ fun notifyPropertyChanged(fieldId: Int) { synchronized(this) { if (mCallbacks == null) { return } } mCallbacks!!.notifyCallbacks(this, fieldId, null) } }
mit
e22112177882f655bde1251128bed538
28.172414
98
0.619385
5.304075
false
false
false
false
zhanhb/spring-boot
spring-boot-project/spring-boot-test/src/test/kotlin/org/springframework/boot/test/web/client/TestRestTemplateExtensionsTests.kt
9
9139
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.test.web.client import com.nhaarman.mockito_kotlin.mock import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.mockito.Answers import org.mockito.Mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.junit.MockitoJUnitRunner import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpEntity import org.springframework.http.HttpMethod import org.springframework.http.RequestEntity import org.springframework.util.ReflectionUtils import org.springframework.web.client.RestOperations import java.net.URI import kotlin.reflect.full.createType import kotlin.reflect.jvm.kotlinFunction /** * Mock object based tests for [TestRestTemplate] Kotlin extensions * * @author Sebastien Deleuze */ @RunWith(MockitoJUnitRunner::class) class TestRestTemplateExtensionsTests { @Mock(answer = Answers.RETURNS_MOCKS) lateinit var template: TestRestTemplate @Test fun `getForObject with reified type parameters, String and varargs`() { val url = "https://spring.io" val var1 = "var1" val var2 = "var2" template.getForObject<Foo>(url, var1, var2) template.restTemplate verify(template, times(1)).getForObject(url, Foo::class.java, var1, var2) } @Test fun `getForObject with reified type parameters, String and Map`() { val url = "https://spring.io" val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2")) template.getForObject<Foo>(url, vars) verify(template, times(1)).getForObject(url, Foo::class.java, vars) } @Test fun `getForObject with reified type parameters and URI`() { val url = URI("https://spring.io") template.getForObject<Foo>(url) verify(template, times(1)).getForObject(url, Foo::class.java) } @Test fun `getForEntity with reified type parameters and URI`() { val url = URI("https://spring.io") template.getForEntity<Foo>(url) verify(template, times(1)).getForEntity(url, Foo::class.java) } @Test fun `getForEntity with reified type parameters, String and varargs`() { val url = "https://spring.io" val var1 = "var1" val var2 = "var2" template.getForEntity<Foo>(url, var1, var2) verify(template, times(1)).getForEntity(url, Foo::class.java, var1, var2) } @Test fun `getForEntity with reified type parameters, String and Map`() { val url = "https://spring.io" val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2")) template.getForEntity<Foo>(url, vars) verify(template, times(1)).getForEntity(url, Foo::class.java, vars) } @Test fun `patchForObject with reified type parameters, String, Any and varargs`() { val url = "https://spring.io" val body: Any = "body" val var1 = "var1" val var2 = "var2" template.patchForObject<Foo>(url, body, var1, var2) verify(template, times(1)).patchForObject(url, body, Foo::class.java, var1, var2) } @Test fun `patchForObject with reified type parameters, String, Any and Map`() { val url = "https://spring.io" val body: Any = "body" val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2")) template.patchForObject<Foo>(url, body, vars) verify(template, times(1)).patchForObject(url, body, Foo::class.java, vars) } @Test fun `patchForObject with reified type parameters, String and Any`() { val url = "https://spring.io" val body: Any = "body" template.patchForObject<Foo>(url, body) verify(template, times(1)).patchForObject(url, body, Foo::class.java) } @Test fun `patchForObject with reified type parameters`() { val url = "https://spring.io" template.patchForObject<Foo>(url) verify(template, times(1)).patchForObject(url, null, Foo::class.java) } @Test fun `postForObject with reified type parameters, String, Any and varargs`() { val url = "https://spring.io" val body: Any = "body" val var1 = "var1" val var2 = "var2" template.postForObject<Foo>(url, body, var1, var2) verify(template, times(1)).postForObject(url, body, Foo::class.java, var1, var2) } @Test fun `postForObject with reified type parameters, String, Any and Map`() { val url = "https://spring.io" val body: Any = "body" val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2")) template.postForObject<Foo>(url, body, vars) verify(template, times(1)).postForObject(url, body, Foo::class.java, vars) } @Test fun `postForObject with reified type parameters, String and Any`() { val url = "https://spring.io" val body: Any = "body" template.postForObject<Foo>(url, body) verify(template, times(1)).postForObject(url, body, Foo::class.java) } @Test fun `postForObject with reified type parameters`() { val url = "https://spring.io" template.postForObject<Foo>(url) verify(template, times(1)).postForObject(url, null, Foo::class.java) } @Test fun `postForEntity with reified type parameters, String, Any and varargs`() { val url = "https://spring.io" val body: Any = "body" val var1 = "var1" val var2 = "var2" template.postForEntity<Foo>(url, body, var1, var2) verify(template, times(1)).postForEntity(url, body, Foo::class.java, var1, var2) } @Test fun `postForEntity with reified type parameters, String, Any and Map`() { val url = "https://spring.io" val body: Any = "body" val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2")) template.postForEntity<Foo>(url, body, vars) verify(template, times(1)).postForEntity(url, body, Foo::class.java, vars) } @Test fun `postForEntity with reified type parameters, String and Any`() { val url = "https://spring.io" val body: Any = "body" template.postForEntity<Foo>(url, body) verify(template, times(1)).postForEntity(url, body, Foo::class.java) } @Test fun `postForEntity with reified type parameters`() { val url = "https://spring.io" template.postForEntity<Foo>(url) verify(template, times(1)).postForEntity(url, null, Foo::class.java) } @Test fun `exchange with reified type parameters, String, HttpMethod, HttpEntity and varargs`() { val url = "https://spring.io" val method = HttpMethod.GET val entity = mock<HttpEntity<Foo>>() val var1 = "var1" val var2 = "var2" template.exchange<List<Foo>>(url, method, entity, var1, var2) verify(template, times(1)).exchange(url, method, entity, object : ParameterizedTypeReference<List<Foo>>() {}, var1, var2) } @Test fun `exchange with reified type parameters, String, HttpMethod, HttpEntity and Map`() { val url = "https://spring.io" val method = HttpMethod.GET val entity = mock<HttpEntity<Foo>>() val vars = mapOf(Pair("key1", "value1"), Pair("key2", "value2")) template.exchange<List<Foo>>(url, method, entity, vars) verify(template, times(1)).exchange(url, method, entity, object : ParameterizedTypeReference<List<Foo>>() {}, vars) } @Test fun `exchange with reified type parameters, String, HttpMethod, HttpEntity`() { val url = "https://spring.io" val method = HttpMethod.GET val entity = mock<HttpEntity<Foo>>() template.exchange<List<Foo>>(url, method, entity) verify(template, times(1)).exchange(url, method, entity, object : ParameterizedTypeReference<List<Foo>>() {}) } @Test fun `exchange with reified type parameters and HttpEntity`() { val entity = mock<RequestEntity<Foo>>() template.exchange<List<Foo>>(entity) verify(template, times(1)).exchange(entity, object : ParameterizedTypeReference<List<Foo>>() {}) } @Test fun `exchange with reified type parameters, String and HttpMethod`() { val url = "https://spring.io" val method = HttpMethod.GET template.exchange<List<Foo>>(url, method) verify(template, times(1)).exchange(url, method, null, object : ParameterizedTypeReference<List<Foo>>() {}) } @Test fun `RestOperations are available`() { val extensions = Class.forName( "org.springframework.boot.test.web.client.TestRestTemplateExtensionsKt") ReflectionUtils.doWithMethods(RestOperations::class.java) { method -> arrayOf(ParameterizedTypeReference::class, Class::class).forEach { kClass -> if (method.parameterTypes.contains(kClass.java)) { val parameters = mutableListOf<Class<*>>(TestRestTemplate::class.java) .apply { addAll(method.parameterTypes.filter { it != kClass.java }) } val f = extensions.getDeclaredMethod(method.name, *parameters.toTypedArray()).kotlinFunction!! Assert.assertEquals(1, f.typeParameters.size) Assert.assertEquals(listOf(Any::class.createType()), f.typeParameters[0].upperBounds) } } } } class Foo }
apache-2.0
a3c7aff311d3322c5f4e94b166a650f0
32.723247
92
0.710472
3.381058
false
true
false
false
evant/silent-support
silent-support-lint/src/main/java/me/tatarka/silentsupport/lint/SilentSupportApiDetector.kt
1
8747
package me.tatarka.silentsupport.lint import com.android.builder.model.AndroidLibrary import com.android.tools.lint.checks.ApiDetector import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.* import com.android.tools.lint.detector.api.LintUtils.getInternalMethodName import com.intellij.psi.PsiAnonymousClass import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiSuperExpression import com.intellij.psi.util.PsiTreeUtil import me.tatarka.silentsupport.SupportCompat import me.tatarka.silentsupport.SupportMetadataProcessor import me.tatarka.silentsupport.lint.context.IssueRewriter import me.tatarka.silentsupport.lint.context.RewriteIssueJavaContext import me.tatarka.silentsupport.lint.context.RewriteIssueXmlContext import org.jetbrains.uast.* import org.jetbrains.uast.util.isMethodCall import org.w3c.dom.Attr import org.w3c.dom.Element class SilentSupportApiDetector : ApiDetector() { private val xmlIssueRewriter = SilentSupportIssueRewriter() private val javaIssueRewriter = JavaIssueRewriter() private var supportApiDatabase: ApiLookup? = null override fun beforeCheckProject(context: Context) { super.beforeCheckProject(context) supportApiDatabase = loadSupportApiDatabase(context) } private fun loadSupportApiDatabase(context: Context): ApiLookup? { val variant = context.mainProject.currentVariant ?: return null val deps = variant.mainArtifact.dependencies.libraries val supportCompat = findSupportCompat(deps) ?: return null val dir = context.client.getCacheDir(true) val processor = SupportMetadataProcessor(supportCompat, dir) val file = processor.metadataFile if (!file.exists()) { processor.process() } return ApiLookup.create(context.client, file, true) } private fun findSupportCompat(deps: Collection<AndroidLibrary>): SupportCompat? { for (dep in deps) { val rc = dep.resolvedCoordinates if ("com.android.support" == rc.groupId && "support-compat" == rc.artifactId) { return SupportCompat(dep.jarFile, rc.version) } val result = findSupportCompat(dep.libraryDependencies) if (result != null) { return result } } return null } private fun checkSupport(owner: String, name: String, desc: String): Boolean { return supportApiDatabase?.let { supportApiDatabase -> val compatClassName = owner.replaceFirst("android/".toRegex(), "android/support/v4/") + "Compat" val newDesc = desc.replace("(", "(L$owner;") val compatVersion = supportApiDatabase.getCallVersion(compatClassName, name, newDesc, true) return compatVersion >= 0 } ?: false } override fun visitAttribute(context: XmlContext, attribute: Attr) { super.visitAttribute(RewriteIssueXmlContext(context, xmlIssueRewriter), attribute) } override fun visitElement(context: XmlContext, element: Element) { super.visitElement(RewriteIssueXmlContext(context, xmlIssueRewriter), element) } override fun createUastHandler(context: JavaContext): UElementHandler { return super.createUastHandler(RewriteIssueJavaContext(context, javaIssueRewriter)) } private open class SilentSupportIssueRewriter : IssueRewriter { override fun rewriteIssue(issue: Issue, location: Location?, message: String?, quickFixData: LintFix?): Issue? { if (ApiDetector.UNSUPPORTED.id == issue.id) { return UNSUPPORTED } else { return issue } } } private inner class JavaIssueRewriter : SilentSupportIssueRewriter(), RewriteIssueJavaContext.JavaIssueRewriter { override fun rewriteIssue(context: JavaContext, issue: Issue, element: UElement, location: Location?, message: String?): Issue? { if (element is UCallExpression) { val expression = element val method = element.resolve() val containingClass = method!!.containingClass val evaluator = context.evaluator val name = getInternalMethodName(method) val owner = evaluator.getInternalName(containingClass!!) val desc = evaluator.getInternalDescription(method, false, false) val receiver: UExpression? if (expression.isMethodCall()) { receiver = expression.receiver if (receiver != null && receiver !is UThisExpression && receiver !is PsiSuperExpression) { val type = receiver.getExpressionType() if (type is PsiClassType) { val expressionOwner = evaluator.getInternalName((type as PsiClassType?)!!) if (expressionOwner != null && expressionOwner != owner) { if (checkSupport(expressionOwner, name, desc)) { return null } } } } else { // Unqualified call; need to search in our super hierarchy var cls = expression.getContainingClass() if (receiver is UThisExpression || receiver is USuperExpression) { val pte = receiver as UInstanceExpression? val resolved = pte!!.resolve() if (resolved is PsiClass) { cls = resolved as PsiClass? } } while (cls != null) { if (cls is PsiAnonymousClass) { // If it's an unqualified call in an anonymous class, we need to // rely on the resolve method to find out whether the method is // picked up from the anonymous class chain or any outer classes var found = false val anonymousBaseType = cls.baseClassType val anonymousBase = anonymousBaseType.resolve() if (anonymousBase != null && anonymousBase .isInheritor(containingClass, true)) { cls = anonymousBase found = true } else { val surroundingBaseType = PsiTreeUtil .getParentOfType(cls, PsiClass::class.java, true) if (surroundingBaseType != null && surroundingBaseType .isInheritor(containingClass, true)) { cls = surroundingBaseType found = true } } if (!found) { break } } val expressionOwner = evaluator.getInternalName(cls) if (expressionOwner == null || "java/lang/Object" == expressionOwner) { break } if (checkSupport(expressionOwner, name, desc)) { return null } cls = cls.superClass } } } } return issue } } companion object { /** * Accessing an unsupported API */ @JvmStatic val UNSUPPORTED = Issue.create( "NewApiSupport", ApiDetector.UNSUPPORTED.getBriefDescription(TextFormat.RAW), ApiDetector.UNSUPPORTED.getExplanation(TextFormat.RAW), ApiDetector.UNSUPPORTED.category, ApiDetector.UNSUPPORTED.priority, ApiDetector.UNSUPPORTED.defaultSeverity, Implementation( SilentSupportApiDetector::class.java, ApiDetector.UNSUPPORTED.implementation.scope, *ApiDetector.UNSUPPORTED.implementation.analysisScopes ) ) } }
apache-2.0
081bb435618705f3658b7b81c9e2ef50
45.775401
137
0.556076
5.788882
false
false
false
false
Esri/arcgis-runtime-samples-android
kotlin/browse-building-floors/src/main/java/com/esri/arcgisruntime/sample/browsebuildingfloors/MainActivity.kt
1
6658
/* Copyright 2021 Esri * * 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.esri.arcgisruntime.sample.browsebuildingfloors import android.content.Context import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.esri.arcgisruntime.loadable.LoadStatus import com.esri.arcgisruntime.mapping.ArcGISMap import com.esri.arcgisruntime.mapping.floor.FloorLevel import com.esri.arcgisruntime.mapping.floor.FloorManager import com.esri.arcgisruntime.mapping.view.MapView import com.esri.arcgisruntime.portal.Portal import com.esri.arcgisruntime.portal.PortalItem import com.esri.arcgisruntime.sample.browsebuildingfloors.databinding.ActivityMainBinding import com.esri.arcgisruntime.sample.browsebuildingfloors.databinding.BrowseFloorsSpinnerItemBinding class MainActivity : AppCompatActivity() { private val TAG: String = MainActivity::class.java.simpleName private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val mapView: MapView by lazy { activityMainBinding.mapView } private val levelSpinner: Spinner by lazy { activityMainBinding.levelSpinner } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // load the portal and create a map from the portal item val portal = Portal("https://www.arcgis.com/", false) val portalItem = PortalItem(portal, "f133a698536f44c8884ad81f80b6cfc7") val map = ArcGISMap(portalItem) // set the map to be displayed in the layout's MapView mapView.map = map map.addDoneLoadingListener { if (map.loadStatus == LoadStatus.LOADED && map.floorDefinition != null) { // get and load the floor manager val floorManager = map.floorManager floorManager.loadAsync() floorManager.addDoneLoadingListener { if (floorManager.loadStatus == LoadStatus.LOADED) { // set up spinner and initial floor level to ground floor initializeFloorSpinner(floorManager) } else { val error = "Error loading floor manager: " + floorManager.loadError.message Log.e(TAG, error) Toast.makeText(this, error, Toast.LENGTH_LONG).show() } } } else { val error = "Error loading map or map is not floor-aware" Toast.makeText(this, error, Toast.LENGTH_LONG).show() Log.e(TAG, error) } } } /** * Set and update the floor spinner. Shows the currently selected floor * and hides the other floors using [floorManager]. */ private fun initializeFloorSpinner(floorManager: FloorManager) { levelSpinner.apply { // set the spinner adapter for the floor selection adapter = FloorsAdapter(this@MainActivity, floorManager.levels) // handle on spinner item selected onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected( parentView: AdapterView<*>?, selectedItemView: View?, position: Int, id: Long ) { // set all the floors to invisible to reset the floorManager floorManager.levels.forEach { floorLevel -> floorLevel.isVisible = false } // set the currently selected floor to be visible floorManager.levels[position].isVisible = true } // ignore if nothing is selected override fun onNothingSelected(parentView: AdapterView<*>?) {} } // Select the ground floor using `verticalOrder`. // The floor at index 0 might not have a vertical order of 0 if, // for example, the building starts with basements. // To select the ground floor, we can search for a level with a // `verticalOrder` of 0. You can also use level ID, number or name // to locate a floor. setSelection(floorManager.levels.indexOf( floorManager.levels.first { it.verticalOrder == 0 } )) } } /** * Adapter to display a list of floor levels */ private class FloorsAdapter( context: Context, private var floorLevels: MutableList<FloorLevel> ) : BaseAdapter() { private val mLayoutInflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater override fun getCount(): Int { return floorLevels.size } override fun getItem(position: Int): Any { return floorLevels[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { // bind the view to the layout inflater val listItemBinding = BrowseFloorsSpinnerItemBinding.inflate(this.mLayoutInflater).apply { // bind the long name of the floor to it's respective text view listItem.text = floorLevels[position].longName } return listItemBinding.root } } override fun onPause() { mapView.pause() super.onPause() } override fun onResume() { super.onResume() mapView.resume() } override fun onDestroy() { mapView.dispose() super.onDestroy() } }
apache-2.0
39f93b455b5dd24801ca7247e3cff824
36.404494
100
0.619105
5.157242
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl-provider-plugins/src/main/kotlin/org/gradle/kotlin/dsl/provider/plugins/DefaultProjectSchemaProvider.kt
3
9244
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.provider.plugins import org.gradle.api.NamedDomainObjectCollectionSchema import org.gradle.api.NamedDomainObjectCollectionSchema.NamedDomainObjectSchema import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.api.artifacts.dsl.RepositoryHandler import org.gradle.api.plugins.ExtensionAware import org.gradle.api.reflect.HasPublicType import org.gradle.api.reflect.TypeOf import org.gradle.api.tasks.SourceSet import org.gradle.api.tasks.SourceSetContainer import org.gradle.api.tasks.TaskContainer import org.gradle.internal.deprecation.DeprecatableConfiguration import org.gradle.kotlin.dsl.accessors.ConfigurationEntry import org.gradle.kotlin.dsl.accessors.ProjectSchema import org.gradle.kotlin.dsl.accessors.ProjectSchemaEntry import org.gradle.kotlin.dsl.accessors.ProjectSchemaProvider import org.gradle.kotlin.dsl.accessors.SchemaType import org.gradle.kotlin.dsl.accessors.TypedProjectSchema import java.lang.reflect.Modifier import kotlin.reflect.KVisibility class DefaultProjectSchemaProvider : ProjectSchemaProvider { override fun schemaFor(project: Project): TypedProjectSchema = targetSchemaFor(project, typeOfProject).let { targetSchema -> ProjectSchema( targetSchema.extensions, targetSchema.conventions, targetSchema.tasks, targetSchema.containerElements, accessibleConfigurationsOf(project) ).map(::SchemaType) } } internal data class TargetTypedSchema( val extensions: List<ProjectSchemaEntry<TypeOf<*>>>, val conventions: List<ProjectSchemaEntry<TypeOf<*>>>, val tasks: List<ProjectSchemaEntry<TypeOf<*>>>, val containerElements: List<ProjectSchemaEntry<TypeOf<*>>> ) internal fun targetSchemaFor(target: Any, targetType: TypeOf<*>): TargetTypedSchema { val extensions = mutableListOf<ProjectSchemaEntry<TypeOf<*>>>() val conventions = mutableListOf<ProjectSchemaEntry<TypeOf<*>>>() val tasks = mutableListOf<ProjectSchemaEntry<TypeOf<*>>>() val containerElements = mutableListOf<ProjectSchemaEntry<TypeOf<*>>>() fun collectSchemaOf(target: Any, targetType: TypeOf<*>) { if (target is ExtensionAware) { accessibleContainerSchema(target.extensions.extensionsSchema).forEach { schema -> extensions.add(ProjectSchemaEntry(targetType, schema.name, schema.publicType)) collectSchemaOf(target.extensions.getByName(schema.name), schema.publicType) } } if (target is Project) { @Suppress("deprecation") accessibleConventionsSchema(target.convention.plugins).forEach { (name, type) -> conventions.add(ProjectSchemaEntry(targetType, name, type)) collectSchemaOf(target.convention.plugins[name]!!, type) } accessibleContainerSchema(target.tasks.collectionSchema).forEach { schema -> tasks.add(ProjectSchemaEntry(typeOfTaskContainer, schema.name, schema.publicType)) } collectSchemaOf(target.dependencies, typeOfDependencyHandler) collectSchemaOf(target.repositories, typeOfRepositoryHandler) // WARN eagerly realize all source sets sourceSetsOf(target)?.forEach { sourceSet -> collectSchemaOf(sourceSet, typeOfSourceSet) } } if (target is NamedDomainObjectContainer<*>) { accessibleContainerSchema(target.collectionSchema).forEach { schema -> containerElements.add(ProjectSchemaEntry(targetType, schema.name, schema.publicType)) } } } collectSchemaOf(target, targetType) return TargetTypedSchema( extensions, conventions, tasks, containerElements ) } private fun accessibleConventionsSchema(plugins: Map<String, Any>) = plugins.filterKeys(::isPublic).mapValues { inferPublicTypeOfConvention(it.value) } private fun accessibleContainerSchema(collectionSchema: NamedDomainObjectCollectionSchema) = collectionSchema.elements .filter { isPublic(it.name) } .map(NamedDomainObjectSchema::toFirstKotlinPublicOrSelf) private fun NamedDomainObjectSchema.toFirstKotlinPublicOrSelf() = publicType.concreteClass.let { schemaType -> // Because a public Java class might not correspond necessarily to a // public Kotlin type due to Kotlin `internal` semantics, we check // whether the public Java class is also the first public Kotlin type, // otherwise we compute a new schema entry with the correct Kotlin type. val firstPublicKotlinType = schemaType.firstPublicKotlinAccessorTypeOrSelf when { firstPublicKotlinType === schemaType -> this else -> ProjectSchemaNamedDomainObjectSchema( name, TypeOf.typeOf(firstPublicKotlinType) ) } } internal val Class<*>.firstPublicKotlinAccessorTypeOrSelf: Class<*> get() = firstPublicKotlinAccessorType ?: this private val Class<*>.firstPublicKotlinAccessorType: Class<*>? get() = accessorTypePrecedenceSequence().find { it.isKotlinPublic } internal fun Class<*>.accessorTypePrecedenceSequence(): Sequence<Class<*>> = sequence { // First, all the classes in the hierarchy, subclasses before superclasses val classes = ancestorClassesIncludingSelf.toList() yieldAll(classes) // Then all supported interfaces sorted by subtyping (subtypes before supertypes) val interfaces = mutableListOf<Class<*>>() classes.forEach { `class` -> `class`.interfaces.forEach { `interface` -> when (val indexOfSupertype = interfaces.indexOfFirst { it.isAssignableFrom(`interface`) }) { -1 -> interfaces.add(`interface`) else -> if (interfaces[indexOfSupertype] != `interface`) { interfaces.add(indexOfSupertype, `interface`) } } } } yieldAll(interfaces) } internal val Class<*>.ancestorClassesIncludingSelf: Sequence<Class<*>> get() = sequence { yield(this@ancestorClassesIncludingSelf) var superclass: Class<*>? = superclass while (superclass != null) { val thisSuperclass: Class<*> = superclass val nextSuperclass = thisSuperclass.superclass if (nextSuperclass != null) { // skip java.lang.Object yield(thisSuperclass) } superclass = nextSuperclass } } private val Class<*>.isKotlinPublic: Boolean get() = isKotlinVisible && kotlin.visibility == KVisibility.PUBLIC private val Class<*>.isKotlinVisible: Boolean get() = isPublic && !isLocalClass && !isAnonymousClass && !isSynthetic private val Class<*>.isPublic get() = Modifier.isPublic(modifiers) private class ProjectSchemaNamedDomainObjectSchema( private val objectName: String, private val objectPublicType: TypeOf<*> ) : NamedDomainObjectSchema { override fun getName() = objectName override fun getPublicType() = objectPublicType } private fun sourceSetsOf(project: Project) = project.extensions.findByName("sourceSets") as? SourceSetContainer private fun inferPublicTypeOfConvention(instance: Any) = if (instance is HasPublicType) instance.publicType else TypeOf.typeOf(instance::class.java.firstNonSyntheticOrSelf) private val Class<*>.firstNonSyntheticOrSelf get() = firstNonSyntheticOrNull ?: this private val Class<*>.firstNonSyntheticOrNull: Class<*>? get() = takeIf { !isSynthetic } ?: superclass?.firstNonSyntheticOrNull private fun accessibleConfigurationsOf(project: Project) = project.configurations .filter { isPublic(it.name) } .map(::toConfigurationEntry) private fun toConfigurationEntry(configuration: Configuration) = (configuration as DeprecatableConfiguration).run { ConfigurationEntry(name, declarationAlternatives ?: listOf()) } private fun isPublic(name: String): Boolean = !name.startsWith("_") private val typeOfProject = typeOf<Project>() private val typeOfSourceSet = typeOf<SourceSet>() private val typeOfDependencyHandler = typeOf<DependencyHandler>() private val typeOfRepositoryHandler = typeOf<RepositoryHandler>() private val typeOfTaskContainer = typeOf<TaskContainer>() internal inline fun <reified T> typeOf(): TypeOf<T> = object : TypeOf<T>() {}
apache-2.0
b2546fe8ce4ba3a463f0453ce78c0eba
31.435088
107
0.710731
4.774793
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl-plugins/src/integTest/kotlin/org/gradle/kotlin/dsl/plugins/precompiled/PrecompiledScriptPluginAccessorsTest.kt
2
30104
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.plugins.precompiled import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.inOrder import com.nhaarman.mockito_kotlin.mock import org.codehaus.groovy.runtime.StringGroovyMethods import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.PluginManager import org.gradle.integtests.fixtures.executer.ExecutionFailure import org.gradle.integtests.fixtures.executer.ExecutionResult import org.gradle.kotlin.dsl.fixtures.FoldersDsl import org.gradle.kotlin.dsl.fixtures.bytecode.InternalName import org.gradle.kotlin.dsl.fixtures.bytecode.RETURN import org.gradle.kotlin.dsl.fixtures.bytecode.internalName import org.gradle.kotlin.dsl.fixtures.bytecode.publicClass import org.gradle.kotlin.dsl.fixtures.bytecode.publicDefaultConstructor import org.gradle.kotlin.dsl.fixtures.bytecode.publicMethod import org.gradle.kotlin.dsl.fixtures.containsMultiLineString import org.gradle.kotlin.dsl.fixtures.normalisedPath import org.gradle.kotlin.dsl.fixtures.pluginDescriptorEntryFor import org.gradle.kotlin.dsl.support.zipTo import org.gradle.test.fixtures.file.LeaksFileHandles import org.gradle.util.GradleVersion import org.gradle.util.internal.TextUtil.replaceLineSeparatorsOf import org.gradle.util.internal.ToBeImplemented import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.descriptors.Visibility import org.jetbrains.kotlin.fir.analysis.checkers.toVisibilityOrNull import org.jetbrains.kotlin.psi.psiUtil.visibilityModifierType import org.junit.Assert.assertTrue import org.junit.Test import java.io.File @LeaksFileHandles("Kotlin Compiler Daemon working directory") class PrecompiledScriptPluginAccessorsTest : AbstractPrecompiledScriptPluginTest() { @Test fun `cannot use type-safe accessors for extensions contributed in afterEvaluate`() { withFolders { "producer/src/main/kotlin" { withFile( "producer.plugin.gradle.kts", """ extensions.add("before", "before") afterEvaluate { extensions.add("after", "after") } """ ) } "consumer/src/main/kotlin" { withFile( "consumer.plugin.gradle.kts", """ plugins { id("producer.plugin") } println(before) // ok println(after) // compilation error """ ) } } withDefaultSettings().appendText( """ include("producer", "consumer") """ ) withKotlinDslPlugin().appendText( """ subprojects { apply(plugin = "org.gradle.kotlin.kotlin-dsl") $repositoriesBlock } project(":consumer") { dependencies { implementation(project(":producer")) } } """ ) buildAndFail("compileKotlin").apply { assertHasCause("Compilation error.") assertHasErrorOutput("Unresolved reference: after") } } @Test fun `can use type-safe accessors for plugin relying on gradleProperty provider`() { withFolders { "buildSrc" { "gradlePropertyPlugin" { withKotlinDslPlugin() withFile( "src/main/kotlin/gradlePropertyPlugin.gradle.kts", """ val property = providers.gradleProperty("theGradleProperty") if (property.isPresent) { println("property is present in plugin!") } extensions.add<Provider<String>>( "theGradleProperty", property ) """ ) } "gradlePropertyPluginConsumer" { withKotlinDslPlugin().appendText( """ dependencies { implementation(project(":gradlePropertyPlugin")) } """ ) withFile( "src/main/kotlin/gradlePropertyPluginConsumer.gradle.kts", """ plugins { id("gradlePropertyPlugin") } if (theGradleProperty.isPresent) { println("property is present in consumer!") } """ ) } withDefaultSettingsIn(relativePath).appendText( """ include("gradlePropertyPlugin") include("gradlePropertyPluginConsumer") """ ) withBuildScriptIn( relativePath, """ plugins { `java-library` } dependencies { subprojects.forEach { runtimeOnly(project(it.path)) } } """ ) } } withBuildScript( """ plugins { gradlePropertyPluginConsumer } """ ) build("help", "-PtheGradleProperty=42").apply { assertThat( output.count("property is present in plugin!"), equalTo(1) // not printed when building buildSrc ) assertThat( output.count("property is present in consumer!"), equalTo(1) ) } } @Test fun `can use type-safe accessors for applied plugins with CRLF line separators`() { withKotlinDslPlugin() withPrecompiledKotlinScript( "my-java-library.gradle.kts", replaceLineSeparatorsOf( """ plugins { java } java { } tasks.compileJava { } """, "\r\n" ) ) compileKotlin() } @Test fun `fails the build with help message for plugin spec with version`() { withDefaultSettings().appendText( """ rootProject.name = "invalid-plugin" """ ) withKotlinDslPlugin() withPrecompiledKotlinScript( "invalid-plugin.gradle.kts", """ plugins { id("a.plugin") version "1.0" } """ ) assertThat( buildFailureOutput("assemble"), containsMultiLineString( """ Invalid plugin request [id: 'a.plugin', version: '1.0']. Plugin requests from precompiled scripts must not include a version number. Please remove the version from the offending request and make sure the module containing the requested plugin 'a.plugin' is an implementation dependency of root project 'invalid-plugin'. """ ) ) } @ToBeImplemented("https://github.com/gradle/gradle/issues/17246") @Test fun `fails the build with help message for plugin spec with version in settings plugin`() { withDefaultSettings().appendText( """ rootProject.name = "invalid-plugin" """ ) withKotlinDslPlugin() withPrecompiledKotlinScript( "invalid-plugin.settings.gradle.kts", """ plugins { id("a.plugin") version "1.0" } """ ) build("assemble") // TODO Should fail: // assertThat( // buildFailureOutput("assemble"), // containsMultiLineString( // """ // Invalid plugin request [id: 'a.plugin', version: '1.0']. Plugin requests from precompiled scripts must not include a version number. Please remove the version from the offending request and make sure the module containing the requested plugin 'a.plugin' is an implementation dependency of root project 'invalid-plugin'. // """ // ) // ) } @Test fun `can use type-safe accessors with same name but different meaning in sibling plugins`() { val externalPlugins = withExternalPlugins() withFolders { "buildSrc" { withDefaultSettingsIn(relativePath) withKotlinDslPlugin().appendText( implementationDependencyOn(externalPlugins) ) withFile( "src/main/kotlin/local-app.gradle.kts", """ plugins { `external-app` } println("*using " + external.name + " from local-app in " + project.name + "*") """ ) withFile( "src/main/kotlin/local-lib.gradle.kts", """ plugins { `external-lib` } println("*using " + external.name + " from local-lib in " + project.name + "*") """ ) } } withDefaultSettings().appendText( """ include("foo") include("bar") """ ) withFolders { "foo" { withFile( "build.gradle.kts", """ plugins { `local-app` } """ ) } "bar" { withFile( "build.gradle.kts", """ plugins { `local-lib` } """ ) } } assertThat( build("tasks").output, allOf( containsString("*using app from local-app in foo*"), containsString("*using lib from local-lib in bar*") ) ) } private fun implementationDependencyOn(file: File): String = """ dependencies { implementation(files("${file.normalisedPath}")) } """ @Test fun `can use type-safe accessors for the Kotlin Gradle plugin extensions`() { assumeNonEmbeddedGradleExecuter() // Unknown issue with accessing the plugin portal from pre-compiled script plugin in embedded test mode withKotlinDslPlugin().appendText( """ dependencies { implementation(kotlin("gradle-plugin")) } """ ) withPrecompiledKotlinScript( "kotlin-library.gradle.kts", """ plugins { kotlin("jvm") } kotlin { } tasks.compileKotlin { kotlinOptions { } } """ ) build("generatePrecompiledScriptPluginAccessors") compileKotlin() } @Test fun `can use type-safe accessors for plugins applied by sibling plugin`() { withKotlinDslPlugin() withPrecompiledKotlinScript( "my-java-library.gradle.kts", """ plugins { java } """ ) withPrecompiledKotlinScript( "my-java-module.gradle.kts", """ plugins { id("my-java-library") } java { } tasks.compileJava { } """ ) compileKotlin() } @Test fun `can use type-safe accessors from scripts with same name but different ids`() { val externalPlugins = withExternalPlugins() withKotlinDslPlugin() withKotlinBuildSrc() withFolders { "buildSrc" { existing("build.gradle.kts").appendText( implementationDependencyOn(externalPlugins) ) "src/main/kotlin" { withFile( "app/model.gradle.kts", """ package app plugins { `external-app` } println("*using " + external.name + " from app/model in " + project.name + "*") """ ) withFile( "lib/model.gradle.kts", """ package lib plugins { `external-lib` } println("*using " + external.name + " from lib/model in " + project.name + "*") """ ) } } } withDefaultSettings().appendText( """ include("lib") include("app") """ ) withFolders { "lib" { withFile( "build.gradle.kts", """ plugins { lib.model } """ ) } "app" { withFile( "build.gradle.kts", """ plugins { app.model } """ ) } } assertThat( build("tasks").output, allOf( containsString("*using app from app/model in app*"), containsString("*using lib from lib/model in lib*") ) ) } @Test fun `can apply sibling plugin whether it has a plugins block or not`() { withKotlinDslPlugin() withPrecompiledKotlinScript("no-plugins.gradle.kts", "") withPrecompiledKotlinScript( "java-plugin.gradle.kts", """ plugins { java } """ ) withPrecompiledKotlinScript( "plugins.gradle.kts", """ plugins { id("no-plugins") id("java-plugin") } java { } tasks.compileJava { } """ ) compileKotlin() } @Test fun `can apply sibling plugin from another package`() { withKotlinDslPlugin() withPrecompiledKotlinScript( "my/java-plugin.gradle.kts", """ package my plugins { java } """ ) withPrecompiledKotlinScript( "plugins.gradle.kts", """ plugins { id("my.java-plugin") } java { } tasks.compileJava { } """ ) compileKotlin() } @Test fun `generated type-safe accessors are internal`() { givenPrecompiledKotlinScript( "java-project.gradle.kts", """ plugins { java } """ ) val generatedSourceFiles = existing("build/generated-sources") .walkTopDown() .filter { it.isFile } .toList() assertTrue( generatedSourceFiles.isNotEmpty() ) data class Declaration( val packageName: String, val name: String, val visibility: Visibility? ) val generatedAccessors = KotlinParser.run { withProject { generatedSourceFiles.flatMap { file -> parse(file.name, file.readText()).run { val packageName = packageFqName.asString() declarations.map { declaration -> Declaration( packageName, declaration.name!!, declaration.visibilityModifierType()?.toVisibilityOrNull() ) } } } } } assertThat( "Only the generated Gradle Plugin wrapper is not internal", generatedAccessors.filterNot { it.visibility == Visibilities.Internal }, equalTo( listOf( Declaration( "", "JavaProjectPlugin", Visibilities.Public ) ) ) ) } @Test fun `can use core plugin spec builders`() { givenPrecompiledKotlinScript( "java-project.gradle.kts", """ plugins { java } """ ) val (project, pluginManager) = projectAndPluginManagerMocks() instantiatePrecompiledScriptOf( project, "Java_project_gradle" ) inOrder(pluginManager) { verify(pluginManager).apply("org.gradle.java") verifyNoMoreInteractions() } } @Test fun `can use plugin spec builders for plugins in the implementation classpath`() { // given: val pluginId = "my.plugin" val pluginJar = jarForPlugin(pluginId, "MyPlugin") withPrecompiledScriptApplying(pluginId, pluginJar) assertPrecompiledScriptPluginApplies( pluginId, "Plugin_gradle" ) } private fun assertPrecompiledScriptPluginApplies(pluginId: String, precompiledScriptClassName: String) { compileKotlin() val (project, pluginManager) = projectAndPluginManagerMocks() instantiatePrecompiledScriptOf( project, precompiledScriptClassName ) inOrder(pluginManager) { verify(pluginManager).apply(pluginId) verifyNoMoreInteractions() } } @Test fun `can use plugin specs with jruby-gradle-plugin`() { withKotlinDslPlugin().appendText( """ dependencies { implementation("com.github.jruby-gradle:jruby-gradle-plugin:1.4.0") } """ ) withPrecompiledKotlinScript( "plugin.gradle.kts", """ plugins { com.github.`jruby-gradle`.base } """ ) assertPrecompiledScriptPluginApplies( "com.github.jruby-gradle.base", "Plugin_gradle" ) } @Test fun `plugin application errors fail the build by default`() { val pluginId = "invalid.plugin" val pluginJar = jarWithInvalidPlugin(pluginId, "InvalidPlugin") withPrecompiledScriptApplying(pluginId, pluginJar) val assertions: ExecutionFailure.() -> Unit = { assertHasFailure("An exception occurred applying plugin request [id: '$pluginId']") { assertHasCause("'InvalidPlugin' is neither a plugin or a rule source and cannot be applied.") } } gradleExecuterFor(arrayOf("classes")) .withStackTraceChecksDisabled() .runWithFailure() .assertions() executer.beforeExecute { it.expectDeprecationWarning( "The org.gradle.kotlin.dsl.precompiled.accessors.strict system property has been deprecated. " + "This is scheduled to be removed in Gradle 9.0. " + "Consult the upgrading guide for further information: https://docs.gradle.org/${GradleVersion.current().version}/userguide/upgrading_version_7.html#strict-kotlin-dsl-precompiled-scripts-accessors-by-default" ) } gradleExecuterFor(arrayOf("--rerun-tasks", "classes", "-Dorg.gradle.kotlin.dsl.precompiled.accessors.strict=")) .withStackTraceChecksDisabled() .runWithFailure() .assertions() gradleExecuterFor(arrayOf("--rerun-tasks", "classes", "-Dorg.gradle.kotlin.dsl.precompiled.accessors.strict=true")) .withStackTraceChecksDisabled() .runWithFailure() .assertions() } @Test fun `plugin application errors can be ignored but are reported`() { val pluginId = "invalid.plugin" val pluginJar = jarWithInvalidPlugin(pluginId, "InvalidPlugin") withPrecompiledScriptApplying(pluginId, pluginJar) executer.beforeExecute { it.expectDeprecationWarning( "The org.gradle.kotlin.dsl.precompiled.accessors.strict system property has been deprecated. " + "This is scheduled to be removed in Gradle 9.0. " + "Consult the upgrading guide for further information: https://docs.gradle.org/${GradleVersion.current().version}/userguide/upgrading_version_7.html#strict-kotlin-dsl-precompiled-scripts-accessors-by-default" ) } val assertions: ExecutionResult.() -> Unit = { assertOutputContains("An exception occurred applying plugin request [id: '$pluginId']") assertOutputContains("'InvalidPlugin' is neither a plugin or a rule source and cannot be applied.") } gradleExecuterFor(arrayOf("--rerun-tasks", "classes", "-Dorg.gradle.kotlin.dsl.precompiled.accessors.strict=false")) .withStackTraceChecksDisabled() .run() .assertions() } private fun withPrecompiledScriptApplying(pluginId: String, pluginJar: File) { withKotlinDslPlugin().appendText( """ dependencies { implementation(files("${pluginJar.normalisedPath}")) } """ ) withPrecompiledKotlinScript( "plugin.gradle.kts", """ plugins { $pluginId } """ ) } @Test fun `can use plugin spec builders in multi-project builds with local and external plugins`() { testPluginSpecBuildersInMultiProjectBuildWithPluginsFromPackage(null) } @Test fun `can use plugin spec builders in multi-project builds with local and external plugins sharing package name`() { testPluginSpecBuildersInMultiProjectBuildWithPluginsFromPackage("p") } private fun testPluginSpecBuildersInMultiProjectBuildWithPluginsFromPackage(packageName: String?) { val packageDeclaration = packageName?.let { "package $it" } ?: "" val packageQualifier = packageName?.let { "$it." } ?: "" withProjectRoot(newDir("external-plugins")) { withFolders { "external-foo" { withKotlinDslPlugin() withFile( "src/main/kotlin/external-foo.gradle.kts", """ $packageDeclaration println("*external-foo applied*") """ ) } "external-bar" { withKotlinDslPlugin() withFile( "src/main/kotlin/external-bar.gradle.kts", """ $packageDeclaration println("*external-bar applied*") """ ) } withDefaultSettingsIn(relativePath).appendText( """ include("external-foo", "external-bar") """ ) } build("assemble") } val externalFoo = existing("external-plugins/external-foo/build/libs/external-foo.jar") val externalBar = existing("external-plugins/external-bar/build/libs/external-bar.jar") withFolders { "buildSrc" { "local-foo" { withFile( "src/main/kotlin/local-foo.gradle.kts", """ $packageDeclaration plugins { $packageQualifier`external-foo` } """ ) withKotlinDslPlugin().appendText( """ dependencies { implementation(files("${externalFoo.normalisedPath}")) } """ ) } "local-bar" { withFile( "src/main/kotlin/local-bar.gradle.kts", """ $packageDeclaration plugins { $packageQualifier`external-bar` } """ ) withKotlinDslPlugin().appendText( """ dependencies { implementation(files("${externalBar.normalisedPath}")) } """ ) } withDefaultSettingsIn(relativePath).appendText( """ include("local-foo", "local-bar") """ ) withFile( "build.gradle.kts", """ dependencies { subprojects.forEach { runtimeOnly(project(it.path)) } } """ ) } } withBuildScript( """ plugins { $packageQualifier`local-foo` $packageQualifier`local-bar` } """ ) assertThat( build("tasks").output, allOf( containsString("*external-foo applied*"), containsString("*external-bar applied*") ) ) } private fun withExternalPlugins(): File = withProjectRoot(newDir("external-plugins")) { withDefaultSettings() withKotlinDslPlugin() withFolders { "src/main/kotlin" { "extensions" { withFile( "Extensions.kt", """ open class App { var name: String = "app" } open class Lib { var name: String = "lib" } """ ) } withFile( "external-app.gradle.kts", """ extensions.create("external", App::class) """ ) withFile( "external-lib.gradle.kts", """ extensions.create("external", Lib::class) """ ) } } build("assemble") existing("build/libs/external-plugins.jar") } private fun FoldersDsl.withKotlinDslPlugin(): File = withKotlinDslPluginIn(relativePath) private val FoldersDsl.relativePath get() = root.relativeTo(projectRoot).path private fun jarWithInvalidPlugin(id: String, implClass: String): File = pluginJarWith( pluginDescriptorEntryFor(id, implClass), "$implClass.class" to publicClass(InternalName(implClass)) ) private fun jarForPlugin(id: String, implClass: String): File = pluginJarWith( pluginDescriptorEntryFor(id, implClass), "$implClass.class" to emptyPluginClassNamed(implClass) ) private fun emptyPluginClassNamed(implClass: String): ByteArray = publicClass(InternalName(implClass), interfaces = listOf(Plugin::class.internalName)) { publicDefaultConstructor() publicMethod("apply", "(Ljava/lang/Object;)V") { RETURN() } } private fun pluginJarWith(vararg entries: Pair<String, ByteArray>): File = newFile("my.plugin.jar").also { file -> zipTo(file, entries.asSequence()) } private fun projectAndPluginManagerMocks(): Pair<Project, PluginManager> { val pluginManager = mock<PluginManager>() val project = mock<Project> { on { getPluginManager() } doReturn pluginManager on { project } doAnswer { it.mock as Project } } return Pair(project, pluginManager) } private fun CharSequence.count(text: CharSequence): Int = StringGroovyMethods.count(this, text) }
apache-2.0
b70813a7f5ce141a0a0bc34986e259c3
29.907598
341
0.492493
5.724282
false
false
false
false
gradle/gradle
.teamcity/src/main/kotlin/configurations/CompileAll.kt
2
988
package configurations import model.CIBuildModel import model.Stage class CompileAll(model: CIBuildModel, stage: Stage) : BaseGradleBuildType(stage = stage, init = { id(buildTypeId(model)) name = "Compile All" description = "Compiles all production/test source code and warms up the build cache" features { publishBuildStatusToGithub(model) } applyDefaults( model, this, "compileAllBuild -PignoreIncomingBuildReceipt=true -DdisableLocalCache=true", extraParameters = buildScanTag("CompileAll") + " " + "-Porg.gradle.java.installations.auto-download=false" ) artifactRules = """$artifactRules subprojects/base-services/build/generated-resources/build-receipt/org/gradle/build-receipt.properties """.trimIndent() }) { companion object { fun buildTypeId(model: CIBuildModel) = buildTypeId(model.projectId) fun buildTypeId(projectId: String) = "${projectId}_CompileAllBuild" } }
apache-2.0
bf4d03ac1291430d4628f74836eb83e7
31.933333
114
0.703441
4.333333
false
false
false
false
AlmasB/FXGL
fxgl/src/main/kotlin/com/almasb/fxgl/dsl/components/ExpireCleanComponent.kt
1
1453
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.dsl.components import com.almasb.fxgl.entity.component.Component import javafx.util.Duration /** * Removes an entity from the world after a certain duration. * Useful for special effects or temporary entities. * * @author Almas Baimagambetov (AlmasB) ([email protected]) */ class ExpireCleanComponent( /** * The expire duration timer starts when the entity is attached to the world, * so it does not start immediately when this component is created. * * @param expire the duration after entity is removed from the world */ private val expire: Duration) : Component() { private var animate = false private var time = 0.0 override fun onUpdate(tpf: Double) { time += tpf if (animate) { updateOpacity() } if (time >= expire.toSeconds()) { entity.removeFromWorld() } } private fun updateOpacity() { entity.opacity = if (time >= expire.toSeconds()) 0.0 else 1 - time / expire.toSeconds() } /** * Enables diminishing opacity over time. * * @return this component */ fun animateOpacity() = this.apply { animate = true } override fun isComponentInjectionRequired(): Boolean = false }
mit
dae593901ea816c9f2503d2403114602
24.068966
95
0.626979
4.443425
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/listener/PlayerCommandPreprocessListener.kt
1
3841
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.listener import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelName import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelService import com.rpkit.chat.bukkit.snooper.RPKSnooperService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerCommandPreprocessEvent /** * Player command preprocess listener. * Picks up commands before they are sent to normal chat processing, allowing them to be interpreted as chat channel * commands. * Hacky and circumvents the command system, but users are stuck in their ways. */ class PlayerCommandPreprocessListener(private val plugin: RPKChatBukkit) : Listener { @EventHandler fun onPlayerCommandPreProcess(event: PlayerCommandPreprocessEvent) { handleQuickChannelSwitch(event) handleSnooping(event) } private fun handleSnooping(event: PlayerCommandPreprocessEvent) { val snooperService = Services[RPKSnooperService::class.java] ?: return snooperService.snoopers.thenAccept { snoopers -> snoopers.filter(RPKMinecraftProfile::isOnline) .forEach { minecraftProfile -> minecraftProfile.sendMessage(plugin.messages["command-snoop", mapOf( "sender_player" to event.player.name, "command" to event.message )]) } } } private fun handleQuickChannelSwitch(event: PlayerCommandPreprocessEvent) { val chatChannelName = event.message.split(Regex("\\s+"))[0].drop(1).lowercase() val chatChannelService = Services[RPKChatChannelService::class.java] ?: return val chatChannel = chatChannelService.getChatChannel(RPKChatChannelName(chatChannelName)) ?: return if (!event.player.hasPermission("rpkit.chat.command.chatchannel.${chatChannel.name.value}")) { event.isCancelled = true event.player.sendMessage(plugin.messages["no-permission-chatchannel", mapOf( "channel" to chatChannel.name.value )]) return } event.isCancelled = true val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(event.player) if (minecraftProfile == null) { event.player.sendMessage(plugin.messages["no-minecraft-profile"]) return } val profile = minecraftProfile.profile if (event.message.lowercase().startsWith("/$chatChannelName ")) { chatChannel.sendMessage(profile, minecraftProfile, event.message.split(Regex("\\s+")).drop(1).joinToString(" ")) } else if (event.message.lowercase().startsWith("/$chatChannelName")) { chatChannel.addSpeaker(minecraftProfile) event.player.sendMessage(plugin.messages["chatchannel-valid", mapOf( "channel" to chatChannel.name.value )]) } } }
apache-2.0
52ff2b39534409708ba2284d89bb9d56
43.674419
124
0.70867
4.759603
false
false
false
false
dnowak/webflux-twits
src/main/kotlin/twits/model.kt
1
4095
package twits import org.slf4j.LoggerFactory import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.core.publisher.toFlux import reactor.core.publisher.toMono import java.time.LocalDateTime import java.util.LinkedList import java.util.concurrent.atomic.AtomicLong data class PostId(val id: Long) class UserRepository(private val eventBus: EventBus, private val eventRepository: EventRepository) { fun user(id: UserId): Mono<User> { val events = eventRepository .findByAggregateId(AggregateId(AggregateType.USER, id)) .collectList() .block()!! val withOptionalCreate = events.toFlux() .switchIfEmpty(createUserEvent(id)) .collectList() .block()!! return withOptionalCreate.toFlux() .reduce(User(eventBus), { u, e -> on(u, e) }) } private fun createUserEvent(id: UserId): Mono<Event> = Mono.fromCallable({ val event = UserCreatedEvent(id) eventBus.publish(event) event }) } class PostRepository(private val eventBus: EventBus) { private val counter = AtomicLong() fun create(publisher: UserId, text: String): Mono<PostId> { val id = PostId(counter.incrementAndGet()) val event = PostCreatedEvent(id, publisher, text) eventBus.publish(event) return id.toMono() } } data class UserId(val name: String) class User(private val eventBus: EventBus) { companion object { private val log = LoggerFactory.getLogger(User::class.java) } private var userId: UserId? = null private var created: LocalDateTime? = null private var followedList = LinkedList<UserId>() private var followersList = LinkedList<UserId>() private var wallList = LinkedList<Post>() private var timelineList = LinkedList<Post>() val followed: Collection<UserId> get() = followedList val followers: Collection<UserId> get() = followersList val id: UserId get() = userId!! fun on(event: UserCreatedEvent) { log.debug("on: {}", event) userId = event.id created = event.timestamp } fun on(event: PostSentEvent) { log.debug("on: {}", event) wallList.add(Post(event.id, event.message, event.timestamp)) } fun on(event: PostReceivedEvent) { log.debug("on: {}", event) timelineList.add(Post(event.author, event.message, event.timestamp)) } fun post(post: Post) { apply(PostSentEvent(userId!!, post.text)) } fun receive(post: Post) { apply(PostReceivedEvent(userId!!, post.userId, post.text)) } fun apply(event: Event) { eventBus.publish(event) on(this, event) } fun posts(): Flux<Post> = wallList.toFlux() fun follow(followedId: UserId) { if (!followedList.contains(followedId)) { apply(FollowingStartedEvent(id, followedId)) } } fun on(event: FollowingStartedEvent) { log.debug("on: {}", event) followedList.add(event.followedId) } fun unfollow(followedId: UserId) { if (followedList.contains(followedId)) { apply(FollowingEndedEvent(id, followedId)) } } fun on(event: FollowingEndedEvent) { log.debug("on: {}", event) followedList.remove(event.followedId) } fun addFollower(followerId: UserId) { if (!followersList.contains(followerId)) { apply(FollowerAddedEvent(id, followerId)) } } fun on(event: FollowerAddedEvent) { log.debug("on: {}", event) followersList.add(event.followerId) } fun removeFollower(followerId: UserId) { if (followersList.contains(followerId)) { apply(FollowerRemovedEvent(id, followerId)) } } fun on(event: FollowerRemovedEvent) { log.debug("on: {}", event) followersList.remove(event.followerId) } } data class Post(val userId: UserId, val text: String, val timestamp: LocalDateTime)
apache-2.0
4ac18de6fbfd9eb42f7799887e3a6124
27.241379
100
0.631502
4.187117
false
false
false
false
hea3ven/Malleable
src/main/java/com/hea3ven/malleable/item/ItemMetalAxe.kt
1
1049
package com.hea3ven.malleable.item import com.hea3ven.malleable.metal.Metal import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.init.Blocks import net.minecraft.item.ItemStack import net.minecraft.item.ItemTool //class ItemMetalAxe(override val metal: Metal) : ItemAxe(metal.toolMaterial), ItemMetalSingle { class ItemMetalAxe(override val metal: Metal) : ItemTool(metal.toolMaterial, EFFECTIVE_ON), ItemMetalSingle { override fun getStrVsBlock(stack: ItemStack, state: IBlockState): Float { val material = state.getMaterial(); if ( material != Material.WOOD && material != Material.PLANTS && material != Material.VINE ) return super.getStrVsBlock(stack, state) else return this.efficiencyOnProperMaterial; } companion object { private val EFFECTIVE_ON = setOf(Blocks.PLANKS, Blocks.BOOKSHELF, Blocks.LOG, Blocks.LOG2, Blocks.CHEST, Blocks.PUMPKIN, Blocks.LIT_PUMPKIN, Blocks.MELON_BLOCK, Blocks.LADDER, Blocks.WOODEN_BUTTON, Blocks.WOODEN_PRESSURE_PLATE) } }
mit
241c37359071cd58e9fbafab3f9ac1bd
39.346154
109
0.781697
3.340764
false
false
false
false
luxons/seven-wonders
sw-ui/src/main/kotlin/com/palantir/blueprintjs/BpCard.kt
1
753
@file:JsModule("@blueprintjs/core") package com.palantir.blueprintjs import org.w3c.dom.events.MouseEvent import react.PureComponent import react.RState import react.ReactElement external interface ICardProps : IProps { var elevation: Elevation? get() = definedExternally set(value) = definedExternally var interactive: Boolean? get() = definedExternally set(value) = definedExternally var onClick: ((e: MouseEvent) -> Unit)? get() = definedExternally set(value) = definedExternally } open external class Card : PureComponent<ICardProps, RState> { override fun render(): ReactElement companion object { var displayName: String var defaultProps: ICardProps } }
mit
07d039b24cd711579dfb2fe1a491f0cc
24.965517
62
0.697211
4.536145
false
false
false
false
cketti/okhttp
okhttp/src/main/kotlin/okhttp3/MediaType.kt
1
5984
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3 import java.nio.charset.Charset import java.util.Locale import java.util.regex.Pattern /** * An [RFC 2045][rfc_2045] Media Type, appropriate to describe the content type of an HTTP request * or response body. * * [rfc_2045]: http://tools.ietf.org/html/rfc2045 */ class MediaType private constructor( private val mediaType: String, /** * Returns the high-level media type, such as "text", "image", "audio", "video", or "application". */ @get:JvmName("type") val type: String, /** * Returns a specific media subtype, such as "plain" or "png", "mpeg", "mp4" or "xml". */ @get:JvmName("subtype") val subtype: String, /** Alternating parameter names with their values, like `["charset', "utf-8"]`. */ private val parameterNamesAndValues: Array<String> ) { /** * Returns the charset of this media type, or [defaultValue] if either this media type doesn't * specify a charset, of it its charset is unsupported by the current runtime. */ @JvmOverloads fun charset(defaultValue: Charset? = null): Charset? { val charset = parameter("charset") ?: return defaultValue return try { Charset.forName(charset) } catch (_: IllegalArgumentException) { defaultValue // This charset is invalid or unsupported. Give up. } } /** * Returns the parameter [name] of this media type, or null if this media type does not define * such a parameter. */ fun parameter(name: String): String? { for (i in parameterNamesAndValues.indices step 2) { if (parameterNamesAndValues[i].equals(name, ignoreCase = true)) { return parameterNamesAndValues[i + 1] } } return null } @JvmName("-deprecated_type") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "type"), level = DeprecationLevel.ERROR) fun type() = type @JvmName("-deprecated_subtype") @Deprecated( message = "moved to val", replaceWith = ReplaceWith(expression = "subtype"), level = DeprecationLevel.ERROR) fun subtype() = subtype /** * Returns the encoded media type, like "text/plain; charset=utf-8", appropriate for use in a * Content-Type header. */ override fun toString() = mediaType override fun equals(other: Any?) = other is MediaType && other.mediaType == mediaType override fun hashCode() = mediaType.hashCode() companion object { private const val TOKEN = "([a-zA-Z0-9-!#$%&'*+.^_`{|}~]+)" private const val QUOTED = "\"([^\"]*)\"" private val TYPE_SUBTYPE = Pattern.compile("$TOKEN/$TOKEN") private val PARAMETER = Pattern.compile(";\\s*(?:$TOKEN=(?:$TOKEN|$QUOTED))?") /** * Returns a media type for this string. * * @throws IllegalArgumentException if this is not a well-formed media type. */ @JvmStatic @JvmName("get") fun String.toMediaType(): MediaType { val typeSubtype = TYPE_SUBTYPE.matcher(this) require(typeSubtype.lookingAt()) { "No subtype found for: \"$this\"" } val type = typeSubtype.group(1).toLowerCase(Locale.US) val subtype = typeSubtype.group(2).toLowerCase(Locale.US) val parameterNamesAndValues = mutableListOf<String>() val parameter = PARAMETER.matcher(this) var s = typeSubtype.end() while (s < length) { parameter.region(s, length) require(parameter.lookingAt()) { "Parameter is not formatted correctly: \"${substring(s)}\" for: \"$this\"" } val name = parameter.group(1) if (name == null) { s = parameter.end() continue } val token = parameter.group(2) val value = when { token == null -> { // Value is "double-quoted". That's valid and our regex group already strips the quotes. parameter.group(3) } token.startsWith("'") && token.endsWith("'") && token.length > 2 -> { // If the token is 'single-quoted' it's invalid! But we're lenient and strip the quotes. token.substring(1, token.length - 1) } else -> token } parameterNamesAndValues += name parameterNamesAndValues += value s = parameter.end() } return MediaType(this, type, subtype, parameterNamesAndValues.toTypedArray()) } /** Returns a media type for this, or null if this is not a well-formed media type. */ @JvmStatic @JvmName("parse") fun String.toMediaTypeOrNull(): MediaType? { return try { toMediaType() } catch (_: IllegalArgumentException) { null } } @JvmName("-deprecated_get") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "mediaType.toMediaType()", imports = ["okhttp3.MediaType.Companion.toMediaType"]), level = DeprecationLevel.ERROR) fun get(mediaType: String): MediaType = mediaType.toMediaType() @JvmName("-deprecated_parse") @Deprecated( message = "moved to extension function", replaceWith = ReplaceWith( expression = "mediaType.toMediaTypeOrNull()", imports = ["okhttp3.MediaType.Companion.toMediaTypeOrNull"]), level = DeprecationLevel.ERROR) fun parse(mediaType: String): MediaType? = mediaType.toMediaTypeOrNull() } }
apache-2.0
08415ccff288616318a93ac7e324585d
32.244444
100
0.63887
4.339376
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/test/kotlin/org/jitsi/nlj/rtcp/KeyframeRequesterTest.kt
1
6729
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.rtcp import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.format.PayloadType import org.jitsi.nlj.resources.logging.StdoutLogger import org.jitsi.nlj.resources.node.onOutput import org.jitsi.nlj.rtp.RtpExtension import org.jitsi.nlj.rtp.RtpExtensionType import org.jitsi.nlj.rtp.SsrcAssociationType import org.jitsi.nlj.stats.NodeStatsBlock import org.jitsi.nlj.util.ReadOnlyStreamInformationStore import org.jitsi.nlj.util.RtpExtensionHandler import org.jitsi.nlj.util.RtpPayloadTypesChangedHandler import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbFirPacket import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbPliPacket import org.jitsi.utils.ms import org.jitsi.utils.secs import org.jitsi.utils.time.FakeClock class KeyframeRequesterTest : ShouldSpec() { override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf private val streamInformationStore = object : ReadOnlyStreamInformationStore { override val rtpExtensions: List<RtpExtension> = mutableListOf() override val rtpPayloadTypes: Map<Byte, PayloadType> = mutableMapOf() override var supportsFir: Boolean = true override var supportsPli: Boolean = true override val supportsRemb: Boolean = true override val supportsTcc: Boolean = true override fun onRtpExtensionMapping(rtpExtensionType: RtpExtensionType, handler: RtpExtensionHandler) { // no-op } override fun onRtpPayloadTypesChanged(handler: RtpPayloadTypesChangedHandler) { // no-op } override val primaryMediaSsrcs: Set<Long> = setOf(123L, 456L, 789L) override val receiveSsrcs: Set<Long> = setOf(123L, 456L, 789L, 321L, 654L) override fun getLocalPrimarySsrc(secondarySsrc: Long): Long? = null override fun getRemoteSecondarySsrc(primarySsrc: Long, associationType: SsrcAssociationType): Long? = null override fun getNodeStats(): NodeStatsBlock = NodeStatsBlock("dummy") } private val logger = StdoutLogger() private val clock: FakeClock = FakeClock() private val keyframeRequester = KeyframeRequester(streamInformationStore, logger, clock) private val sentKeyframeRequests = mutableListOf<PacketInfo>() init { keyframeRequester.onOutput { sentKeyframeRequests.add(it) } context("requesting a keyframe") { context("without a specific SSRC") { keyframeRequester.requestKeyframe() should("result in a sent PLI request with the first video SSRC") { sentKeyframeRequests shouldHaveSize 1 val packet = sentKeyframeRequests.last().packet packet.shouldBeInstanceOf<RtcpFbPliPacket>() packet.mediaSourceSsrc shouldBe 123L } } context("when PLI is supported") { keyframeRequester.requestKeyframe(123L) should("result in a sent PLI request") { sentKeyframeRequests shouldHaveSize 1 val packet = sentKeyframeRequests.last().packet packet.shouldBeInstanceOf<RtcpFbPliPacket>() packet.mediaSourceSsrc shouldBe 123L } context("and then requesting again") { sentKeyframeRequests.clear() context("within the wait interval") { clock.elapse(10.ms) context("on the same SSRC") { keyframeRequester.requestKeyframe(123L) should("not send anything") { sentKeyframeRequests.shouldBeEmpty() } } context("on a different SSRC") { keyframeRequester.requestKeyframe(456L) should("result in a sent PLI request") { sentKeyframeRequests shouldHaveSize 1 val packet = sentKeyframeRequests.last().packet packet.shouldBeInstanceOf<RtcpFbPliPacket>() packet.mediaSourceSsrc shouldBe 456L } } } context("after the wait interval has expired") { clock.elapse(1.secs) keyframeRequester.requestKeyframe(123L) should("result in a sent PLI request") { sentKeyframeRequests shouldHaveSize 1 val packet = sentKeyframeRequests.last().packet packet.shouldBeInstanceOf<RtcpFbPliPacket>() packet.mediaSourceSsrc shouldBe 123L } } } } context("when PLI isn't supported") { streamInformationStore.supportsPli = false keyframeRequester.requestKeyframe(123L) should("result in a sent FIR request") { sentKeyframeRequests shouldHaveSize 1 val packet = sentKeyframeRequests.last().packet packet.shouldBeInstanceOf<RtcpFbFirPacket>() packet.mediaSenderSsrc shouldBe 123L } } context("when neither PLI nor FIR is supported") { streamInformationStore.supportsFir = false streamInformationStore.supportsPli = false keyframeRequester.requestKeyframe(123L) should("not send anything") { sentKeyframeRequests.shouldBeEmpty() } } } } }
apache-2.0
1f1f30e56449d2a5a7093f78e4eb014e
44.77551
114
0.618368
5.160276
false
false
false
false
spennihana/HackerDesktop
src/main/kt/com/hnd/util/PrettyPrint.kt
1
6037
package com.hnd.util import org.joda.time.DurationFieldType import org.joda.time.Period import org.joda.time.PeriodType import org.joda.time.format.PeriodFormat import java.util.* import java.util.concurrent.TimeUnit object PrettyPrint { fun msecs(msecs: Long, truncate: Boolean): String { var msec = msecs val hr = TimeUnit.MILLISECONDS.toHours(msec) msec -= TimeUnit.HOURS.toMillis(hr) val min = TimeUnit.MILLISECONDS.toMinutes(msec) msec -= TimeUnit.MINUTES.toMillis(min) val sec = TimeUnit.MILLISECONDS.toSeconds(msec) msec -= TimeUnit.SECONDS.toMillis(sec) val ms = TimeUnit.MILLISECONDS.toMillis(msec) if( !truncate ) return String.format("%02d:%02d:%02d.%03d", hr, min, sec, ms) if( hr != 0L ) return String.format("%2d:%02d:%02d.%03d", hr, min, sec, ms) if( min != 0L ) return String.format("%2d min %2d.%03d sec", min, sec, ms) return String.format("%2d.%03d sec", sec, ms) } fun usecs(usecs: Long): String { var us = usecs val hr = TimeUnit.MICROSECONDS.toHours(us) us -= TimeUnit.HOURS.toMicros(hr) val min = TimeUnit.MICROSECONDS.toMinutes(us) us -= TimeUnit.MINUTES.toMicros(min) val sec = TimeUnit.MICROSECONDS.toSeconds(us) us -= TimeUnit.SECONDS.toMicros(sec) val ms = TimeUnit.MICROSECONDS.toMillis(us) us -= TimeUnit.MILLISECONDS.toMicros(ms) if( hr != 0L) return String.format("%2d:%02d:%02d.%03d", hr, min, sec, ms) if( min != 0L) return String.format("%2d min %2d.%03d sec", min, sec, ms) if( sec != 0L) return String.format("%2d.%03d sec", sec, ms) if( ms != 0L) return String.format("%3d.%03d msec", ms, us) return String.format("%3d usec", us) } fun toAge(from: Date?, to: Date?): String { if (from == null || to == null) return "N/A" val period = Period(from.time, to.time) val dtf = object : ArrayList<DurationFieldType>() { init { add(DurationFieldType.years()) add(DurationFieldType.months()) add(DurationFieldType.days()) if (period.years == 0 && period.months == 0 && period.days == 0) { add(DurationFieldType.hours()) add(DurationFieldType.minutes()) } } }.toTypedArray() val pf = PeriodFormat.getDefault() return pf.print(period.normalizedStandard(PeriodType.forFields(dtf))) } // Return X such that (bytes < 1L<<(X*10)) internal fun byteScale(bytes: Long): Int { if (bytes < 0) return -1 for (i in 0..5) if (bytes < 1L shl i * 10) return i return 6 } internal fun bytesScaled(bytes: Long, scale: Int): Double { if (scale <= 0) return bytes.toDouble() return bytes / (1L shl (scale - 1) * 10).toDouble() } internal val SCALE = arrayOf("N/A (-ve)", "Zero ", "%4.0f B", "%.1f KB", "%.1f MB", "%.2f GB", "%.3f TB", "%.3f PB") fun bytes(bytes: Long): String { return bytes(bytes, byteScale(bytes)) } internal fun bytes(bytes: Long, scale: Int): String { return String.format(SCALE[scale + 1], bytesScaled(bytes, scale)) } fun bytesPerSecond(bytes: Long): String { if (bytes < 0) return "N/A" return bytes(bytes) + "/S" } internal var powers10 = doubleArrayOf(0.0000000001, 0.000000001, 0.00000001, 0.0000001, 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0) var powers10i = longArrayOf(1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L) fun pow10(exp: Int): Double { return if (exp >= -10 && exp <= 10) powers10[exp + 10] else Math.pow(10.0, exp.toDouble()) } fun pow10i(exp: Int): Long { return if (exp > -1 && exp < 19) powers10i[exp] else Math.pow(10.0, exp.toDouble()).toLong() } fun fitsIntoInt(d: Double): Boolean { return Math.abs(d.toInt() - d) < 1e-8 } // About as clumsy and random as a blaster... fun UUID(lo: Long, hi: Long): String { val lo0 = lo shr 32 and 0xFFFFFFFFL val lo1 = lo shr 16 and 0xFFFFL val lo2 = lo shr 0 and 0xFFFFL val hi0 = hi shr 48 and 0xFFFFL val hi1 = hi shr 0 and 0xFFFFFFFFFFFFL return String.format("%08X-%04X-%04X-%04X-%012X", lo0, lo1, lo2, hi0, hi1) } fun uuid(uuid: java.util.UUID?): String { return if (uuid == null) "(N/A)" else UUID(uuid.leastSignificantBits, uuid.mostSignificantBits) } private fun x2(d: Double, scale: Double): String { var s = java.lang.Double.toString(d) // Double math roundoff error means sometimes we get very long trailing // strings of junk 0's with 1 digit at the end... when we *know* the data // has only "scale" digits. Chop back to actual digits val ex = Math.log10(scale).toInt() val x = s.indexOf('.') val y = x + 1 + -ex if (x != -1 && y < s.length) s = s.substring(0, x + 1 + -ex) while (s[s.length - 1] == '0') s = s.substring(0, s.length - 1) return s } fun formatPct(pct: Double): String { var s = "N/A" if( !pct.isNaN() ) s = String.format("%5.2f %%", 100 * pct) return s } /** * This method takes a number, and returns the * string form of the number with the proper * ordinal indicator attached (e.g. 1->1st, and 22->22nd) * @param i - number to have ordinal indicator attached * * * @return string form of number along with ordinal indicator as a suffix */ fun withOrdinalIndicator(i: Long): String { val ord: String // Grab second to last digit var d = (Math.abs(i) / Math.pow(10.0, 1.0)).toInt() % 10 if (d == 1) ord = "th" //teen values all end in "th" else { // not a weird teen number d = (Math.abs(i) / Math.pow(10.0, 0.0)).toInt() % 10 when (d) { 1 -> ord = "st" 2 -> ord = "nd" 3 -> ord = "rd" else -> ord = "th" } } return i.toString() + ord } }
apache-2.0
706bd39c46230ea902215b49ee9bbab9
34.721893
276
0.625973
3.174027
false
false
false
false
collinx/susi_android
app/src/main/java/org/fossasia/susi/ai/signup/SignUpActivity.kt
2
7919
package org.fossasia.susi.ai.signup import android.app.ProgressDialog import android.content.DialogInterface import android.content.Intent import android.graphics.Color import android.os.Bundle import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.view.MenuItem import android.view.View import kotlinx.android.synthetic.main.activity_sign_up.* import org.fossasia.susi.ai.R import org.fossasia.susi.ai.forgotpassword.ForgotPasswordActivity import org.fossasia.susi.ai.login.LoginActivity import org.fossasia.susi.ai.helper.AlertboxHelper import org.fossasia.susi.ai.helper.Constant import org.fossasia.susi.ai.helper.CredentialHelper import org.fossasia.susi.ai.signup.contract.ISignUpPresenter import org.fossasia.susi.ai.signup.contract.ISignUpView /** * <h1>The SignUp activity.</h1> * <h2>This activity is used to signUp into the app.</h2> * * Created by mayanktripathi on 05/07/17. */ class SignUpActivity : AppCompatActivity(), ISignUpView { lateinit var signUpPresenter: ISignUpPresenter lateinit var progressDialog: ProgressDialog override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sign_up) setupPasswordWatcher() if(savedInstanceState!=null){ email.editText?.setText(savedInstanceState.getCharSequenceArray(Constant.SAVED_STATES)[0].toString()) password.editText?.setText(savedInstanceState.getCharSequenceArray(Constant.SAVED_STATES)[1].toString()) confirm_password.editText?.setText(savedInstanceState.getCharSequenceArray(Constant.SAVED_STATES)[2].toString()) if(savedInstanceState.getBoolean(Constant.SERVER)) { input_url.visibility = View.VISIBLE } else { input_url.visibility = View.GONE } } progressDialog = ProgressDialog(this@SignUpActivity) progressDialog.setCancelable(false) progressDialog.setMessage(this.getString(R.string.signing_up)) addListeners() signUpPresenter = SignUpPresenter(this) signUpPresenter.onAttach(this) } fun addListeners() { showURL() signUp() cancelSignUp() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finish() return true } return super.onOptionsItemSelected(item) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) val values = arrayOf<CharSequence>(email.editText?.text.toString(), password.editText?.text.toString(), confirm_password.editText?.text.toString()) outState.putCharSequenceArray(Constant.SAVED_STATES, values) outState.putBoolean(Constant.SERVER, customer_server.isChecked) } override fun onBackPressed() { val alertDialog = AlertDialog.Builder(this@SignUpActivity) alertDialog.setCancelable(false) alertDialog.setMessage(R.string.error_cancelling_signUp_process_text) alertDialog.setPositiveButton(R.string.yes) { _, _ -> [email protected]() } alertDialog.setNegativeButton((R.string.no), null) val alert = alertDialog.create() alert.show() } override fun alertSuccess() { val dialogClickListener = DialogInterface.OnClickListener { _, _ -> finish() } val alertTitle = getString(R.string.signup) val alertMessage = getString(R.string.signup_msg) val successAlertboxHelper = AlertboxHelper(this@SignUpActivity, alertTitle, alertMessage, dialogClickListener, null, resources.getString(R.string.ok), null, resources.getColor(R.color.md_blue_500)) successAlertboxHelper.showAlertBox() } override fun alertFailure() { val dialogClickListener = DialogInterface.OnClickListener { _, _ -> val intent = Intent(this@SignUpActivity, LoginActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) finish() } val dialogClickListenern = DialogInterface.OnClickListener { _, _ -> val intent = Intent(this@SignUpActivity, ForgotPasswordActivity::class.java) startActivity(intent) finish() } val alertTitle = getString(R.string.error_email) val alertMessage = getString(R.string.error_msg) val failureAlertboxHelper = AlertboxHelper(this@SignUpActivity, alertTitle, alertMessage, dialogClickListener, dialogClickListenern, resources.getString(R.string.ok), resources.getString(R.string.forgot_pass_activity), resources.getColor(R.color.md_blue_500)) failureAlertboxHelper.showAlertBox() } override fun setErrorConpass(msg: String) { confirm_password?.error = msg } override fun enableSignUp(bool: Boolean) { sign_up?.isEnabled = bool } override fun clearField() { CredentialHelper.clearFields(email, password, confirm_password) } override fun showProgress(bool: Boolean) { if (bool) progressDialog.show() else progressDialog.dismiss() } override fun invalidCredentials(isEmpty: Boolean, what: String) { if (isEmpty) { when (what) { Constant.EMAIL -> email.error = getString(R.string.email_cannot_be_empty) Constant.PASSWORD -> password.error = getString(R.string.password_cannot_be_empty) Constant.INPUT_URL -> input_url.error = getString(R.string.url_cannot_be_empty) Constant.CONFIRM_PASSWORD -> confirm_password.error = getString(R.string.field_cannot_be_empty) } } else { when (what) { Constant.EMAIL -> email.error = getString(R.string.invalid_email) Constant.INPUT_URL -> input_url.error = getString(R.string.invalid_url) Constant.PASSWORD -> password.error = getString(R.string.error_password_matching) } } } override fun passwordInvalid() { password.error = getString(R.string.pass_validation_text) sign_up.isEnabled = true } fun showURL() { customer_server.setOnClickListener { input_url.visibility = if(customer_server.isChecked) View.VISIBLE else View.GONE} } fun setupPasswordWatcher() { password.editText?.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus -> password.error = null if (!hasFocus) signUpPresenter.checkForPassword(password.editText?.text.toString()) } } fun cancelSignUp() { progressDialog.setOnCancelListener({ signUpPresenter.cancelSignUp() sign_up.isEnabled = true }) } override fun onSignUpError(title: String?, message: String?) { val notSuccessAlertboxHelper = AlertboxHelper(this@SignUpActivity, title, message, null, null, getString(R.string.ok), null, Color.BLUE) notSuccessAlertboxHelper.showAlertBox() sign_up.isEnabled = true } fun signUp() { sign_up.setOnClickListener { email.error = null password.error = null confirm_password.error = null input_url.error = null val stringEmail = email.editText?.text.toString() val stringPassword = password.editText?.text.toString() val stringConPassword = confirm_password.editText?.text.toString() val stringURL = input_url.editText?.text.toString() signUpPresenter.signUp(stringEmail, stringPassword, stringConPassword, !customer_server.isChecked, stringURL) } } override fun onDestroy() { signUpPresenter.onDetach() super.onDestroy() } }
apache-2.0
a5c49e785285e5bbd8607a0faca5aa54
38.20297
267
0.677863
4.499432
false
false
false
false
wireapp/wire-android
storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/errors/ErrorsTable127to128MigrationTest.kt
1
1999
package com.waz.zclient.storage.userdatabase.errors import com.waz.zclient.storage.db.users.migration.USER_DATABASE_MIGRATION_127_TO_128 import com.waz.zclient.storage.userdatabase.UserDatabaseMigrationTest import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test @ExperimentalCoroutinesApi class ErrorsTable127to128MigrationTest : UserDatabaseMigrationTest(127, 128) { @Test fun givenErrorInsertedIntoErrorsTableVersion127_whenMigratedToVersion128_thenAssertDataIsStillIntact() { val id = "id" val type = "type" val users = "users" val message = "test message" val conversationId = "testConvId" val resCode = 1 val resMessage = "message" val resLabel = "label" val timestamp = 1584698132 ErrorsTableTestHelper.insertError( id = id, errorType = type, users = users, messages = message, conversationId = conversationId, resCode = resCode, resMessage = resMessage, resLabel = resLabel, time = timestamp, openHelper = testOpenHelper ) validateMigration(USER_DATABASE_MIGRATION_127_TO_128) runBlocking { val syncJob = allErrors()[0] with(syncJob) { assertEquals(this.id, id) assertEquals(this.errorType, type) assertEquals(this.users, users) assertEquals(this.messages, message) assertEquals(this.conversationId, conversationId) assertEquals(this.responseCode, resCode) assertEquals(this.responseMessage, resMessage) assertEquals(this.responseLabel, resLabel) assertEquals(this.time, timestamp) } } } private suspend fun allErrors() = getDatabase().errorsDao().allErrors() }
gpl-3.0
e4c18c4cb5812a808f991da945e0de40
33.465517
108
0.638819
4.840194
false
true
false
false
toastkidjp/Jitte
app/src/main/java/jp/toastkid/yobidashi/tab/model/EditorTab.kt
1
632
package jp.toastkid.yobidashi.tab.model import java.io.File import java.util.UUID /** * Model of editor tab. * * @author toastkidjp */ internal class EditorTab: Tab { private val editorTab: Boolean = true private val id: String = UUID.randomUUID().toString() private var titleStr: String = "Editor" var path: String = "" override fun id(): String = id override fun setScrolled(scrollY: Int) = Unit override fun getScrolled(): Int = 0 override fun title(): String = titleStr fun setFileInformation(file: File) { path = file.absolutePath titleStr = file.name } }
epl-1.0
9289af60e2381197af247a31a39adabf
17.617647
57
0.658228
4
false
false
false
false
ModerateFish/component
framework/src/main/java/com/thornbirds/frameworkext/component/page/StackedPageRouter.kt
1
3464
package com.thornbirds.frameworkext.component.page import androidx.annotation.MainThread import com.thornbirds.frameworkext.component.route.* import com.thornbirds.frameworkext.component.route.RouteComponentController.Companion.STATE_DESTROYED import com.thornbirds.frameworkext.component.route.RouteComponentController.Companion.STATE_STARTED import java.util.* /** * @author YangLi [email protected] */ internal class StackedPageRouter( private val mRouterController: RouterController ) : PageRouter<PageEntry, PageCreator, RouterController>() { private val mPageStack = LinkedList<PageEntry>() private fun size(): Int { return mPageStack.size } private fun top(): PageEntry? { return if (mPageStack.isEmpty()) null else mPageStack.first } private fun pop(): PageEntry? { return if (mPageStack.isEmpty()) null else mPageStack.removeFirst() } private fun push(entry: PageEntry) { mPageStack.addFirst(entry) } override fun doStartPage(route: String, params: IPageParams?): Boolean { val creator = resolveRoute(route) if (creator == null) { val parentRouter = mRouterController.parentRouter if (parentRouter != null) { return parentRouter.startPage(route, params) } logE("gotoPage failed, no route found for $route") return false } val entry = creator.create(params) if (entry == null) { logE("gotoPage failed, no page found for $route") return false } return doAddPageInner(entry) } private fun doAddPageInner(newEntry: PageEntry): Boolean { val state = mRouterController.state if (state == STATE_DESTROYED) { return false } val topEntry = top() if (topEntry != null) { if (topEntry === newEntry) { return true } topEntry.performStop() } push(newEntry) newEntry.performCreate(mRouterController) if (state == STATE_STARTED) { newEntry.performStart() } return true } override fun doPopPage(page: RouterController?): Boolean { if (page != null && top()?.matchController(page) == false) { return false } if (size() <= 1) { return mRouterController.exitRouter() } else { val state = mRouterController.state val popped = pop() ?: return false val newCurrent = top() if (state == STATE_STARTED) { newCurrent?.performStart() popped.performStop() } popped.performDestroy() return true } } @MainThread fun dispatchStart() { val entry = top() entry?.performStart() } @MainThread fun dispatchStop() { val entry = top() entry?.performStop() } @MainThread fun dispatchDestroy() { onDestroy() for (entry in mPageStack) { entry.performDestroy() } mPageStack.clear() } @MainThread fun dispatchBackPress(): Boolean { val entry = top() ?: return false if (entry.performBackPress()) { return true } if (size() > 1) { doPopPage(null) return true } return false } }
apache-2.0
b0b5ed226926631a327b0c965783d2fe
26.943548
101
0.579388
4.637216
false
false
false
false
mayuki/AgqrPlayer4Tv
AgqrPlayer4Tv/app/src/main/java/org/misuzilla/agqrplayer4tv/model/TimetableProgram.kt
1
1170
package org.misuzilla.agqrplayer4tv.model import java.io.Serializable class TimetableProgram( var title: String, var mailAddress: String?, var personality: String?, var start: TimetableProgramTime, var end: TimetableProgramTime = TimetableProgramTime(0, 0, 0) ) : Serializable { val isPlaying: Boolean get () = start <= LogicalDateTime.now.time && end >= LogicalDateTime.now.time override fun equals(other: Any?): Boolean { if (other == null) return false if (other !is TimetableProgram) return false return (this.title == other.title && this.mailAddress == other.mailAddress && this.personality == other.personality && this.start == other.start && this.end == other.end) } override fun hashCode(): Int { return this.title.hashCode() } override fun toString() = "TimetableProgram: ${title} <${mailAddress}> (${personality}) ${start}-${end}" companion object { val DEFAULT = TimetableProgram("超A&G+", "", "", TimetableProgramTime(0, 0, 0), TimetableProgramTime(5, 59, 59)) } }
mit
08e610fb9ab546dd9e9113116d682ad9
31.444444
119
0.61387
4.358209
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/ItemEntity.kt
1
1746
package com.github.shynixn.blockball.core.logic.persistence.entity import com.github.shynixn.blockball.api.persistence.entity.Item /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class ItemEntity( override var type: String = "", override var dataValue: Int = 0, override var unbreakable: Boolean = false, override var displayName: String? = null, override var lore: List<String>? = null, override var skin: String? = null, override var nbt: String? = null ) : Item { constructor(init: ItemEntity.() -> Unit) : this() { init.invoke(this) } }
apache-2.0
7ed56e7399b6f9b992cb17cb02469454
38.681818
81
0.722795
4.12766
false
false
false
false
talhacohen/android
app/src/main/java/com/etesync/syncadapter/resource/LocalGroup.kt
1
9349
/* * Copyright © 2013 – 2015 Ricki Hirner (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ package com.etesync.syncadapter.resource import android.content.ContentProviderOperation import android.content.ContentUris import android.content.ContentValues import android.net.Uri import android.os.Parcel import android.os.RemoteException import android.provider.ContactsContract import android.provider.ContactsContract.CommonDataKinds.GroupMembership import android.provider.ContactsContract.Groups import android.provider.ContactsContract.RawContacts.Data import android.text.TextUtils import at.bitfire.vcard4android.* import at.bitfire.vcard4android.GroupMethod.GROUP_VCARDS import com.etesync.syncadapter.App import ezvcard.VCardVersion import java.io.ByteArrayOutputStream import java.util.* import java.util.logging.Level class LocalGroup : AndroidGroup, LocalAddress { companion object { /** marshalled list of member UIDs, as sent by server */ val COLUMN_PENDING_MEMBERS = Groups.SYNC3 /** * Processes all groups with non-null {@link #COLUMN_PENDING_MEMBERS}: the pending memberships * are (if possible) applied, keeping cached memberships in sync. * @param addressBook address book to take groups from */ fun applyPendingMemberships(addressBook: LocalAddressBook) { addressBook.provider!!.query( addressBook.groupsSyncUri(), arrayOf(Groups._ID, COLUMN_PENDING_MEMBERS), "$COLUMN_PENDING_MEMBERS IS NOT NULL", null, null )?.use { cursor -> val batch = BatchOperation(addressBook.provider) while (cursor.moveToNext()) { val id = cursor.getLong(0) // extract list of member UIDs val members = LinkedList<String>() val raw = cursor.getBlob(1) val parcel = Parcel.obtain() try { parcel.unmarshall(raw, 0, raw.size) parcel.setDataPosition(0) parcel.readStringList(members) } finally { parcel.recycle() } // insert memberships val membersIds = members.map {uid -> Constants.log.fine("Assigning member: $uid") (addressBook.findByUid(uid) as LocalContact).id!! } val group = addressBook.findGroupById(id) group.setMembers(batch, membersIds) batch.commit() } } } } private var saveAsDirty = false // When true, the resource will be saved as dirty override val uuid: String? get() = fileName override val content: String get() { val contact: Contact contact = this.contact!! App.log.log(Level.FINE, "Preparing upload of VCard $uuid", contact) val os = ByteArrayOutputStream() contact.write(VCardVersion.V4_0, GROUP_VCARDS, os) return os.toString() } override val isLocalOnly: Boolean get() = TextUtils.isEmpty(eTag) constructor(addressBook: AndroidAddressBook<out AndroidContact, LocalGroup>, values: ContentValues) : super(addressBook, values) {} constructor(addressBook: AndroidAddressBook<out AndroidContact, LocalGroup>, contact: Contact, fileName: String?, eTag: String?) : super(addressBook, contact, fileName, eTag) {} override fun contentValues(): ContentValues { val values = super.contentValues() val members = Parcel.obtain() try { members.writeStringList(contact?.members) values.put(COLUMN_PENDING_MEMBERS, members.marshall()) } finally { members.recycle() } if (saveAsDirty) { values.put(Groups.DIRTY, true) } return values } override fun clearDirty(eTag: String) { val id = requireNotNull(id) val values = ContentValues(2) values.put(Groups.DIRTY, 0) this.eTag = eTag values.put(AndroidGroup.COLUMN_ETAG, eTag) update(values) // update cached group memberships val batch = BatchOperation(addressBook.provider!!) // delete cached group memberships batch.enqueue(BatchOperation.Operation( ContentProviderOperation.newDelete(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI)) .withSelection( CachedGroupMembership.MIMETYPE + "=? AND " + CachedGroupMembership.GROUP_ID + "=?", arrayOf(CachedGroupMembership.CONTENT_ITEM_TYPE, id.toString()) ) )) // insert updated cached group memberships for (member in getMembers()) batch.enqueue(BatchOperation.Operation( ContentProviderOperation.newInsert(addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI)) .withValue(CachedGroupMembership.MIMETYPE, CachedGroupMembership.CONTENT_ITEM_TYPE) .withValue(CachedGroupMembership.RAW_CONTACT_ID, member) .withValue(CachedGroupMembership.GROUP_ID, id) .withYieldAllowed(true) )) batch.commit() } override fun prepareForUpload() { val uid = UUID.randomUUID().toString() val values = ContentValues(2) values.put(AndroidGroup.COLUMN_FILENAME, uid) values.put(AndroidGroup.COLUMN_UID, uid) update(values) fileName = uid } override fun resetDeleted() { val values = ContentValues(1) values.put(Groups.DELETED, 0) addressBook.provider!!.update(groupSyncUri(), values, null, null) } private fun setMembers(batch: BatchOperation, members: List<Long>) { val id = id!! val addressBook = this.addressBook as LocalAddressBook Constants.log.fine("Assigning members to group $id") // required for workaround for Android 7 which sets DIRTY flag when only meta-data is changed val changeContactIDs = HashSet<Long>() // delete all memberships and cached memberships for this group for (contact in addressBook.getByGroupMembership(id)) { contact.removeGroupMemberships(batch) changeContactIDs += contact.id!! } // insert memberships for (memberId in members) { Constants.log.fine("Assigning member: $memberId") addressBook.findContactByID(memberId).let { member -> member.addToGroup(batch, id) changeContactIDs += member.id!! } ?: Constants.log.warning("Group member not found: $memberId") } if (LocalContact.HASH_HACK) // workaround for Android 7 which sets DIRTY flag when only meta-data is changed changeContactIDs .map { addressBook.findContactByID(it) } .forEach { it.updateHashCode(batch) } // remove pending memberships batch.enqueue(BatchOperation.Operation( ContentProviderOperation.newUpdate(addressBook.syncAdapterURI(ContentUris.withAppendedId(Groups.CONTENT_URI, id))) .withValue(COLUMN_PENDING_MEMBERS, null) .withYieldAllowed(true) )) } fun createAsDirty(members: List<Long>): Uri { saveAsDirty = true val ret = this.add() val batch = BatchOperation(addressBook.provider!!) setMembers(batch, members) batch.commit() return ret } // helpers private fun groupSyncUri(): Uri { val id = requireNotNull(id) return ContentUris.withAppendedId(addressBook.groupsSyncUri(), id) } /** * Lists all members of this group. * @return list of all members' raw contact IDs * @throws RemoteException on contact provider errors */ internal fun getMembers(): List<Long> { val id = requireNotNull(id) val members = LinkedList<Long>() addressBook.provider!!.query( addressBook.syncAdapterURI(ContactsContract.Data.CONTENT_URI), arrayOf(Data.RAW_CONTACT_ID), "${GroupMembership.MIMETYPE}=? AND ${GroupMembership.GROUP_ROW_ID}=?", arrayOf(GroupMembership.CONTENT_ITEM_TYPE, id.toString()), null )?.use { cursor -> while (cursor.moveToNext()) members += cursor.getLong(0) } return members } // factory object Factory: AndroidGroupFactory<LocalGroup> { override fun fromProvider(addressBook: AndroidAddressBook<out AndroidContact, LocalGroup>, values: ContentValues) = LocalGroup(addressBook, values) } }
gpl-3.0
9088de918d0beff7088f27bf0512db61
35.365759
132
0.607854
5.101528
false
false
false
false
dushmis/dagger
java/dagger/lint/DaggerKotlinIssueDetector.kt
1
11236
/* * Copyright (C) 2020 The Dagger Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dagger.lint import com.android.tools.lint.client.api.JavaEvaluator import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.LintFix import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.android.tools.lint.detector.api.SourceCodeScanner import com.android.tools.lint.detector.api.TextFormat import com.android.tools.lint.detector.api.isKotlin import dagger.lint.DaggerKotlinIssueDetector.Companion.ISSUE_FIELD_SITE_TARGET_ON_QUALIFIER_ANNOTATION import dagger.lint.DaggerKotlinIssueDetector.Companion.ISSUE_JVM_STATIC_PROVIDES_IN_OBJECT import dagger.lint.DaggerKotlinIssueDetector.Companion.ISSUE_MODULE_COMPANION_OBJECTS import dagger.lint.DaggerKotlinIssueDetector.Companion.ISSUE_MODULE_COMPANION_OBJECTS_NOT_IN_MODULE_PARENT import java.util.EnumSet import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.uast.UClass import org.jetbrains.uast.UElement import org.jetbrains.uast.UField import org.jetbrains.uast.UMethod import org.jetbrains.uast.getUastParentOfType import org.jetbrains.uast.kotlin.KotlinUClass import org.jetbrains.uast.toUElement /** * This is a simple lint check to catch common Dagger+Kotlin usage issues. * * - [ISSUE_FIELD_SITE_TARGET_ON_QUALIFIER_ANNOTATION] covers using `field:` site targets for member * injections, which are redundant as of Dagger 2.25. * - [ISSUE_JVM_STATIC_PROVIDES_IN_OBJECT] covers using `@JvmStatic` for object * `@Provides`-annotated functions, which are redundant as of Dagger 2.25. @JvmStatic on companion * object functions are redundant as of Dagger 2.26. * - [ISSUE_MODULE_COMPANION_OBJECTS] covers annotating companion objects with `@Module`, as they * are now part of the enclosing module class's API in Dagger 2.26. This will also error if the * enclosing class is _not_ in a `@Module`-annotated class, as this object just should be moved to a * top-level object to avoid confusion. * - [ISSUE_MODULE_COMPANION_OBJECTS_NOT_IN_MODULE_PARENT] covers annotating companion objects with * `@Module` when the parent class is _not_ also annotated with `@Module`. While technically legal, * these should be moved up to top-level objects to avoid confusion. */ @Suppress("UnstableApiUsage") // Lots of Lint APIs are marked with @Beta. class DaggerKotlinIssueDetector : Detector(), SourceCodeScanner { companion object { // We use the overloaded constructor that takes a varargs of `Scope` as the last param. // This is to enable on-the-fly IDE checks. We are telling lint to run on both // JAVA and TEST_SOURCES in the `scope` parameter but by providing the `analysisScopes` // params, we're indicating that this check can run on either JAVA or TEST_SOURCES and // doesn't require both of them together. // From discussion on lint-dev https://groups.google.com/d/msg/lint-dev/ULQMzW1ZlP0/1dG4Vj3-AQAJ // This was supposed to be fixed in AS 3.4 but still required as recently as 3.6. private val SCOPES = Implementation( DaggerKotlinIssueDetector::class.java, EnumSet.of(Scope.JAVA_FILE, Scope.TEST_SOURCES), EnumSet.of(Scope.JAVA_FILE), EnumSet.of(Scope.TEST_SOURCES) ) private val ISSUE_JVM_STATIC_PROVIDES_IN_OBJECT: Issue = Issue.create( id = "JvmStaticProvidesInObjectDetector", briefDescription = "@JvmStatic used for @Provides function in an object class", explanation = """ It's redundant to annotate @Provides functions in object classes with @JvmStatic. """, category = Category.CORRECTNESS, priority = 5, severity = Severity.WARNING, implementation = SCOPES ) private val ISSUE_FIELD_SITE_TARGET_ON_QUALIFIER_ANNOTATION: Issue = Issue.create( id = "FieldSiteTargetOnQualifierAnnotation", briefDescription = "Redundant 'field:' used for Dagger qualifier annotation.", explanation = """ It's redundant to use 'field:' site-targets for qualifier annotations. """, category = Category.CORRECTNESS, priority = 5, severity = Severity.WARNING, implementation = SCOPES ) private val ISSUE_MODULE_COMPANION_OBJECTS: Issue = Issue.create( id = "ModuleCompanionObjects", briefDescription = "Module companion objects should not be annotated with @Module.", explanation = """ Companion objects in @Module-annotated classes are considered part of the API. """, category = Category.CORRECTNESS, priority = 5, severity = Severity.WARNING, implementation = SCOPES ) private val ISSUE_MODULE_COMPANION_OBJECTS_NOT_IN_MODULE_PARENT: Issue = Issue.create( id = "ModuleCompanionObjectsNotInModuleParent", briefDescription = "Companion objects should not be annotated with @Module.", explanation = """ Companion objects in @Module-annotated classes are considered part of the API. This companion object is not a companion to an @Module-annotated class though, and should be moved to a top-level object declaration instead otherwise Dagger will ignore companion object. """, category = Category.CORRECTNESS, priority = 5, severity = Severity.WARNING, implementation = SCOPES ) private const val PROVIDES_ANNOTATION = "dagger.Provides" private const val JVM_STATIC_ANNOTATION = "kotlin.jvm.JvmStatic" private const val INJECT_ANNOTATION = "javax.inject.Inject" private const val QUALIFIER_ANNOTATION = "javax.inject.Qualifier" private const val MODULE_ANNOTATION = "dagger.Module" val issues: List<Issue> = listOf( ISSUE_JVM_STATIC_PROVIDES_IN_OBJECT, ISSUE_FIELD_SITE_TARGET_ON_QUALIFIER_ANNOTATION, ISSUE_MODULE_COMPANION_OBJECTS, ISSUE_MODULE_COMPANION_OBJECTS_NOT_IN_MODULE_PARENT ) } override fun getApplicableUastTypes(): List<Class<out UElement>>? { return listOf(UMethod::class.java, UField::class.java, UClass::class.java) } override fun createUastHandler(context: JavaContext): UElementHandler? { if (!isKotlin(context.psiFile)) { // This is only relevant for Kotlin files. return null } return object : UElementHandler() { override fun visitField(node: UField) { if (!context.evaluator.isLateInit(node)) { return } // Can't use hasAnnotation because it doesn't capture all annotations! val injectAnnotation = node.annotations.find { it.qualifiedName == INJECT_ANNOTATION } ?: return // Look for qualifier annotations node.annotations.forEach { annotation -> if (annotation === injectAnnotation) { // Skip the inject annotation return@forEach } // Check if it's a FIELD site target val sourcePsi = annotation.sourcePsi if (sourcePsi is KtAnnotationEntry && sourcePsi.useSiteTarget?.getAnnotationUseSiteTarget() == AnnotationUseSiteTarget.FIELD ) { // Check if this annotation is a qualifier annotation if (annotation.resolve()?.hasAnnotation(QUALIFIER_ANNOTATION) == true) { context.report( ISSUE_FIELD_SITE_TARGET_ON_QUALIFIER_ANNOTATION, context.getLocation(annotation), ISSUE_FIELD_SITE_TARGET_ON_QUALIFIER_ANNOTATION .getBriefDescription(TextFormat.TEXT), LintFix.create() .name("Remove 'field:'") .replace() .text("field:") .with("") .autoFix() .build() ) } } } } override fun visitMethod(node: UMethod) { if (!node.isConstructor && node.hasAnnotation(PROVIDES_ANNOTATION) && node.hasAnnotation(JVM_STATIC_ANNOTATION) ) { val containingClass = node.containingClass?.toUElement(UClass::class.java) ?: return if (containingClass.isObject()) { val annotation = node.findAnnotation(JVM_STATIC_ANNOTATION)!! context.report( ISSUE_JVM_STATIC_PROVIDES_IN_OBJECT, context.getLocation(annotation), ISSUE_JVM_STATIC_PROVIDES_IN_OBJECT.getBriefDescription(TextFormat.TEXT), LintFix.create() .name("Remove @JvmStatic") .replace() .pattern("(@(kotlin\\.jvm\\.)?JvmStatic)") .with("") .autoFix() .build() ) } } } override fun visitClass(node: UClass) { if (node.hasAnnotation(MODULE_ANNOTATION) && node.isCompanionObject(context.evaluator)) { val parent = node.getUastParentOfType(UClass::class.java, false)!! if (parent.hasAnnotation(MODULE_ANNOTATION)) { context.report( ISSUE_MODULE_COMPANION_OBJECTS, context.getLocation(node as UElement), ISSUE_MODULE_COMPANION_OBJECTS.getBriefDescription(TextFormat.TEXT), LintFix.create() .name("Remove @Module") .replace() .pattern("(@(dagger\\.)?Module)") .with("") .autoFix() .build() ) } else { context.report( ISSUE_MODULE_COMPANION_OBJECTS_NOT_IN_MODULE_PARENT, context.getLocation(node as UElement), ISSUE_MODULE_COMPANION_OBJECTS_NOT_IN_MODULE_PARENT .getBriefDescription(TextFormat.TEXT) ) } } } } } /** @return whether or not the [this] is a Kotlin `companion object` type. */ private fun UClass.isCompanionObject(evaluator: JavaEvaluator): Boolean { return isObject() && evaluator.hasModifier(this, KtTokens.COMPANION_KEYWORD) } /** @return whether or not the [this] is a Kotlin `object` type. */ private fun UClass.isObject(): Boolean { return this is KotlinUClass && ktClass is KtObjectDeclaration } }
apache-2.0
776134319b98cb522b35ae5f9ed7a699
41.885496
106
0.674795
4.497998
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UINavigationBar.kt
1
8977
package com.yy.codex.uikit import android.app.Activity import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.os.Build import android.support.annotation.RequiresApi import android.util.AttributeSet import android.view.View import com.yy.codex.foundation.NSInvocation import java.util.HashMap /** * Created by cuiminghui on 2017/1/18. */ class UINavigationBar : UIView { constructor(context: Context, view: View) : super(context, view) {} constructor(context: Context) : super(context) {} constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {} constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {} @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {} override fun init() { super.init() val constraint = UIConstraint() constraint.centerHorizontally = true constraint.top = "0" constraint.width = "100%" constraint.height = "44" this.constraint = constraint } override fun willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) setBackgroundColor(barTintColor) } override fun didMoveToSuperview() { super.didMoveToSuperview() if (context != null && context is Activity) { val invocation = NSInvocation(context, "getSupportActionBar") val actionBar = invocation.invoke() if (actionBar != null) { val actionBarInvocation = NSInvocation(actionBar, "hide") actionBarInvocation.invoke() } else { val _invocation = NSInvocation(context, "getActionBar") val _actionBar = _invocation.invoke() if (_actionBar != null) { val _actionBarInvocation = NSInvocation(_actionBar, "hide") _actionBarInvocation.invoke() } } } } /* Layout Length */ fun length(): Double { if (materialDesign) { return 48.0 } return 44.0 } /* Material Design */ private var materialDesignInitialized = false override fun materialDesignDidChanged() { super.materialDesignDidChanged() if (!materialDesignInitialized && materialDesign) { materialDesignInitialized = true barTintColor = UIColor(0x3f / 255.0, 0x51 / 255.0, 0xb5 / 255.0, 1.0) tintColor = UIColor.whiteColor titleTextAttributes = object : HashMap<String, Any>() { init { put(NSAttributedString.NSForegroundColorAttributeName, UIColor.whiteColor) put(NSAttributedString.NSFontAttributeName, UIFont.systemBold(17f)) } } constraint?.let { it.height = "48" } layoutSubviews() resetItemsView() invalidate() } } /* BarTintColor */ var barTintColor: UIColor = UIColor(0xf8 / 255.0, 0xf8 / 255.0, 0xf8 / 255.0, 1.0) set(barTintColor) { field = barTintColor setBackgroundColor(barTintColor) } /* Title Attributes */ var titleTextAttributes: HashMap<String, Any>? = null set(titleTextAttributes) { field = titleTextAttributes resetItemsView() } /* Line Color */ var bottomLineColor: UIColor = UIColor(0xb2 / 255.0, 0xb2 / 255.0, 0xb2 / 255.0, 0.5) set(bottomLineColor) { field = bottomLineColor invalidate() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (!materialDesign) { val paint = Paint() paint.color = bottomLineColor.toInt() canvas.drawLine(0f, (canvas.height - 1).toFloat(), canvas.width.toFloat(), (canvas.height - 1).toFloat(), paint) } } /* Items */ private var items: List<UINavigationItem> = listOf() private var itemsView: List<UINavigationItemView> = listOf() private var currentAnimation: UIViewAnimation? = null fun setItems(items: List<UINavigationItem>) { currentAnimation?.cancel() this.items = items resetItemsProps() resetBackItems() resetItemsView() } fun pushNavigationItem(item: UINavigationItem, animated: Boolean) { currentAnimation?.cancel() val mutableItems = items.toMutableList() mutableItems.add(item) this.items = mutableItems.toList() resetItemsProps() resetBackItems() resetItemsView() if (animated) { doPushAnimation() } } fun doPushAnimation() { if (itemsView.size >= 2) { val topItemView = itemsView[itemsView.size - 1] val backItemView = itemsView[itemsView.size - 2] topItemView.alpha = 1f topItemView.animateToFront(false) backItemView.alpha = 1f backItemView.animateFromFrontToBack(false) currentAnimation = UIViewAnimator.springWithBounciness(1.0, 75.0, Runnable { topItemView.animateToFront(true) backItemView.animateFromFrontToBack(true) }, Runnable { backItemView.alpha = 0f }) } } fun popNavigationItem(animated: Boolean) { currentAnimation?.cancel() if (items.count() >= 2) { if (animated) { doPopAnimation(Runnable { if (items.count() >= 2) { val mutableItems = items.toMutableList() mutableItems.removeAt(mutableItems.count() - 1) items = mutableItems.toList() resetItemsView() } }) } else { if (items.count() >= 2) { val mutableItems = items.toMutableList() mutableItems.removeAt(mutableItems.count() - 1) items = mutableItems.toList() resetItemsView() } } } } fun doPopAnimation(completion: Runnable) { if (itemsView.size >= 2) { val topItemView = itemsView[itemsView.size - 1] val backItemView = itemsView[itemsView.size - 2] topItemView.alpha = 1f backItemView.alpha = 1f topItemView.animateToGone(false) backItemView.animateFromBackToFront(false) currentAnimation = UIViewAnimator.springWithBounciness(1.0, 75.0, Runnable { topItemView.animateToGone(true) backItemView.animateFromBackToFront(true) }, Runnable { topItemView.alpha = 0f completion.run() }) } } fun resetItemsProps() { for (item in items) { item.navigationBar = this } } fun resetBackItems() { for ((index, item) in items.withIndex()) { if (index > 0) { if (item.leftBarButtonItems.count() <= 0 || item.leftBarButtonItems.first().isSystemBackItem) { item.setLeftBarButtonItem(items[index - 1].backBarButtonItem) } } else { if (item.leftBarButtonItems.count() == 1 && item.leftBarButtonItems.first().isSystemBackItem) { item.setLeftBarButtonItem(null) } } } } fun resetItemsView() { for (itemView in itemsView) { itemView.removeFromSuperview() } val theItemsView: MutableList<UINavigationItemView> = mutableListOf() for ((index, item) in items.withIndex()) { val frontView = if (materialDesign) UINavigationItemView_MaterialDesign(context) else UINavigationItemView(context) item.frontView = frontView item.setNeedsUpdate() theItemsView.add(frontView) frontView.constraint = UIConstraint.full() addSubview(frontView) frontView.layoutSubviews() if (index < items.count() - 1) { frontView.alpha = 0f frontView.titleView?.alpha = 0f frontView.leftViews.forEach { it.alpha = 0f } frontView.rightViews.forEach { it.alpha = 0f } } else { frontView.alpha = 1f frontView.titleView?.alpha = 1f frontView.leftViews.forEach { it.alpha = 1f } frontView.rightViews.forEach { it.alpha = 1f } } } this.itemsView = theItemsView layoutSubviews() } }
gpl-3.0
d0882dec1fdca7e73039ccc9931e0817
32.371747
145
0.570235
4.709864
false
false
false
false
cubex2/ObsidianAnimator
API/src/main/java/obsidianAPI/render/part/Part.kt
1
2119
package obsidianAPI.render.part import obsidianAPI.render.ModelObj /** * An abstract object for tracking information about a part (limb, position of model etc). */ abstract class Part(@JvmField val modelObj: ModelObj?, internalName: String) : IPart { @JvmField protected var valueX: Float = 0.toFloat() @JvmField protected var valueY: Float = 0.toFloat() @JvmField protected var valueZ: Float = 0.toFloat() var originalValues: FloatArray //------------------------------------------ // Basics //------------------------------------------ val internalName: String = internalName.toLowerCase() override val name: String get() = internalName var values: FloatArray get() = floatArrayOf(valueX, valueY, valueZ) set(values) { valueX = values[0] valueY = values[1] valueZ = values[2] } init { valueX = 0.0f valueY = 0.0f valueZ = 0.0f originalValues = floatArrayOf(0.0f, 0.0f, 0.0f) } fun setValue(f: Float, i: Int) { when (i) { 0 -> valueX = f 1 -> valueY = f 2 -> valueZ = f } } fun getValue(i: Int): Float { when (i) { 0 -> return valueX 1 -> return valueY 2 -> return valueZ } return 0.0f } fun setToOriginalValues() { values = originalValues } override fun getParentPart(): IPart? = null override fun getRotationPoint(axis: Int): Float = 0f override fun rotate() { // NO OP } override fun equals(o: Any?): Boolean { if (this === o) return true if (o == null || javaClass != o.javaClass) return false val part = o as Part? return if (internalName != part!!.internalName) false else modelObj == part.modelObj } override fun hashCode(): Int { var result = internalName.hashCode() result = 31 * result + (modelObj?.hashCode() ?: 0) return result } }
gpl-3.0
23a2d1c7b09386f4322dbe24df7ff876
21.542553
92
0.522416
4.187747
false
false
false
false
chrisbanes/tivi
ui/discover/src/main/java/app/tivi/home/discover/DiscoverViewModel.kt
1
5047
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.home.discover import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import app.tivi.api.UiMessageManager import app.tivi.domain.interactors.UpdatePopularShows import app.tivi.domain.interactors.UpdateRecommendedShows import app.tivi.domain.interactors.UpdateTrendingShows import app.tivi.domain.observers.ObserveNextShowEpisodeToWatch import app.tivi.domain.observers.ObservePopularShows import app.tivi.domain.observers.ObserveRecommendedShows import app.tivi.domain.observers.ObserveTraktAuthState import app.tivi.domain.observers.ObserveTrendingShows import app.tivi.domain.observers.ObserveUserDetails import app.tivi.extensions.combine import app.tivi.util.Logger import app.tivi.util.ObservableLoadingCounter import app.tivi.util.collectStatus import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel internal class DiscoverViewModel @Inject constructor( private val updatePopularShows: UpdatePopularShows, observePopularShows: ObservePopularShows, private val updateTrendingShows: UpdateTrendingShows, observeTrendingShows: ObserveTrendingShows, private val updateRecommendedShows: UpdateRecommendedShows, observeRecommendedShows: ObserveRecommendedShows, observeNextShowEpisodeToWatch: ObserveNextShowEpisodeToWatch, observeTraktAuthState: ObserveTraktAuthState, observeUserDetails: ObserveUserDetails, private val logger: Logger ) : ViewModel() { private val trendingLoadingState = ObservableLoadingCounter() private val popularLoadingState = ObservableLoadingCounter() private val recommendedLoadingState = ObservableLoadingCounter() private val uiMessageManager = UiMessageManager() val state: StateFlow<DiscoverViewState> = combine( trendingLoadingState.observable, popularLoadingState.observable, recommendedLoadingState.observable, observeTrendingShows.flow, observePopularShows.flow, observeRecommendedShows.flow, observeNextShowEpisodeToWatch.flow, observeTraktAuthState.flow, observeUserDetails.flow, uiMessageManager.message ) { trendingLoad, popularLoad, recommendLoad, trending, popular, recommended, nextShow, authState, user, message -> DiscoverViewState( user = user, authState = authState, trendingItems = trending, trendingRefreshing = trendingLoad, popularItems = popular, popularRefreshing = popularLoad, recommendedItems = recommended, recommendedRefreshing = recommendLoad, nextEpisodeWithShowToWatched = nextShow, message = message ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(), initialValue = DiscoverViewState.Empty ) init { observeTrendingShows(ObserveTrendingShows.Params(10)) observePopularShows(ObservePopularShows.Params(10)) observeRecommendedShows(ObserveRecommendedShows.Params(10)) observeNextShowEpisodeToWatch(Unit) observeTraktAuthState(Unit) observeUserDetails(ObserveUserDetails.Params("me")) viewModelScope.launch { // Each time the auth state changes, refresh... observeTraktAuthState.flow.collect { refresh(false) } } } fun refresh(fromUser: Boolean = true) { viewModelScope.launch { updatePopularShows( UpdatePopularShows.Params(UpdatePopularShows.Page.REFRESH, fromUser) ).collectStatus(popularLoadingState, logger, uiMessageManager) } viewModelScope.launch { updateTrendingShows( UpdateTrendingShows.Params(UpdateTrendingShows.Page.REFRESH, fromUser) ).collectStatus(trendingLoadingState, logger, uiMessageManager) } viewModelScope.launch { updateRecommendedShows( UpdateRecommendedShows.Params(forceRefresh = fromUser) ).collectStatus(recommendedLoadingState, logger, uiMessageManager) } } fun clearMessage(id: Long) { viewModelScope.launch { uiMessageManager.clearMessage(id) } } }
apache-2.0
01ac5fc12cc1d2778df35d7399de6e99
38.124031
91
0.734496
5.062187
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/browser/view/reader/ReaderModeUi.kt
1
3183
/* * Copyright (c) 2022 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.view.reader import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.selection.SelectionContainer import androidx.compose.foundation.verticalScroll import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.R @Composable internal fun ReaderModeUi(title: String, text: MutableState<String>) { val preferenceApplier = PreferenceApplier(LocalContext.current) val scrollState = rememberScrollState() Box( modifier = Modifier .fillMaxWidth() .fillMaxHeight() .background(Color(preferenceApplier.editorBackgroundColor())) .padding(16.dp) ) { Column(Modifier.verticalScroll(scrollState)) { SelectionContainer { Text( text = title, color = Color(preferenceApplier.editorFontColor()), fontSize = 30.sp, modifier = Modifier.fillMaxWidth() ) } SelectionContainer { Text( text = text.value, color = Color(preferenceApplier.editorFontColor()), fontSize = 16.sp, modifier = Modifier .fillMaxWidth() .fillMaxHeight() ) } } Image( painterResource(R.drawable.ic_close_black), contentDescription = stringResource(id = R.string.close), colorFilter = ColorFilter.tint(Color(preferenceApplier.fontColor), BlendMode.SrcIn), modifier = Modifier .size(60.dp) .padding(16.dp) .align(Alignment.TopEnd) .clickable { text.value = "" } ) } }
epl-1.0
201f25e459a82ed6bb700d89448b5621
36.023256
96
0.672322
5.012598
false
false
false
false
youkai-app/Youkai
app/src/main/kotlin/app/youkai/ui/common/widget/BarInfoView.kt
1
3496
package app.youkai.ui.common.widget import android.content.Context import android.support.annotation.IntegerRes import android.text.SpannableString import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.TextView import app.youkai.R import app.youkai.placeholdertextview.PlaceholderTextView import app.youkai.util.ext.getLayoutInflater import app.youkai.util.ext.toPx /** * A custom view for displaying key info in an eye-catching style with an icon. * * See: http://i.imgur.com/U1N3u2J.png */ class BarInfoView : FrameLayout { lateinit var iconView: ImageView lateinit var textView: TextView lateinit var chevronView: View constructor(context: Context) : super(context) { init(context, null, null, null) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(context, attrs, null, null) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context, attrs, defStyleAttr, null) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init(context, attrs, defStyleAttr, defStyleRes) } private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int?, defStyleRes: Int?) { /* Inflate the layout */ context.getLayoutInflater().inflate(R.layout.view_bar_info, this, true) /* Get view references */ iconView = findViewById<ImageView>(R.id.icon) textView = findViewById<PlaceholderTextView>(R.id.text) chevronView = findViewById(R.id.chevron) /* Set root layout attributes */ val padding = 16.toPx(context) setPadding(padding, padding, padding, padding) /* Get values from the layout */ val a = context.theme.obtainStyledAttributes( attrs, R.styleable.BarInfoView, defStyleAttr ?: 0, defStyleRes ?: 0 ) val icon: Int val text: String val rounded: Boolean try { icon = a.getResourceId(R.styleable.BarInfoView_biv_icon, R.drawable.ic_bar_info_view_default_icon) text = a.getString(R.styleable.BarInfoView_biv_text) ?: "" rounded = a.getBoolean(R.styleable.BarInfoView_biv_roundedCorners, false) } finally { a.recycle() } /* Use the values */ setIcon(icon) setText(text) setRoundedCorners(rounded) } fun setIcon(@IntegerRes resource: Int) { iconView.setImageResource(resource) } fun setText(text: String) { textView.text = text } fun setText(text: SpannableString) { textView.setText(text, TextView.BufferType.SPANNABLE) } fun setRoundedCorners(rounded: Boolean = true) { rootView.setBackgroundResource( if (rounded) { R.drawable.background_bar_info_view_rounded } else { R.drawable.background_bar_info_view } ) } private fun showChevron(show: Boolean = true) { chevronView.visibility = if (show) VISIBLE else GONE } override fun setOnClickListener(l: OnClickListener?) { showChevron(l != null) super.setOnClickListener(l) } }
gpl-3.0
08f07d70deb0fdd8897d23b6ae6cba21
30.223214
145
0.646453
4.359102
false
false
false
false
fossasia/open-event-android
app/src/main/java/org/fossasia/openevent/general/order/OrderDetailsViewModel.kt
1
2974
package org.fossasia.openevent.general.order import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import org.fossasia.openevent.general.R import org.fossasia.openevent.general.attendees.Attendee import org.fossasia.openevent.general.auth.AuthHolder import org.fossasia.openevent.general.common.SingleLiveEvent import org.fossasia.openevent.general.data.Resource import org.fossasia.openevent.general.event.Event import org.fossasia.openevent.general.event.EventService import org.fossasia.openevent.general.utils.extensions.withDefaultSchedulers import org.fossasia.openevent.general.utils.nullToEmpty import timber.log.Timber class OrderDetailsViewModel( private val eventService: EventService, private val orderService: OrderService, private val authHolder: AuthHolder, private val resource: Resource ) : ViewModel() { private val compositeDisposable = CompositeDisposable() val message = SingleLiveEvent<String>() private val mutableEvent = MutableLiveData<Event>() val event: LiveData<Event> = mutableEvent private val mutableAttendees = MutableLiveData<List<Attendee>>() val attendees: LiveData<List<Attendee>> = mutableAttendees private val mutableProgress = MutableLiveData<Boolean>() val progress: LiveData<Boolean> = mutableProgress var currentTicketPosition: Int = 0 var brightness: Float? = 0f fun loadEvent(id: Long) { if (id == -1L) { throw IllegalStateException("ID should never be -1") } compositeDisposable += eventService.getEventById(id) .withDefaultSchedulers() .subscribe({ mutableEvent.value = it }, { Timber.e(it, "Error fetching event %d", id) message.value = resource.getString(R.string.error_fetching_event_message) }) } fun getToken() = authHolder.getAuthorization().nullToEmpty() fun loadAttendeeDetails(orderId: Long) { if (orderId == -1L) return compositeDisposable += orderService .getOrderById(orderId) .flatMap { order -> orderService.getAttendeesUnderOrder(order.attendees.map { it.id }) } .withDefaultSchedulers() .doOnSubscribe { mutableProgress.value = true }.doFinally { mutableProgress.value = false }.subscribe({ mutableAttendees.value = it Timber.d("Fetched attendees of size %s", it) }, { Timber.e(it, "Error fetching attendee details") message.value = resource.getString(R.string.error_fetching_attendee_details_message) }) } override fun onCleared() { super.onCleared() compositeDisposable.clear() } }
apache-2.0
e2d98dc123b936917499e8125a283fc6
36.175
100
0.679892
4.989933
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/api/item/inventory/container/ContainerBuilder.kt
1
2423
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.api.item.inventory.container import org.lanternpowered.api.entity.player.Player import org.lanternpowered.api.item.ItemTypes import org.lanternpowered.api.item.inventory.Inventory import org.lanternpowered.api.item.inventory.behavior.ShiftClickBehavior import org.lanternpowered.api.item.inventory.container.layout.ContainerLayout import org.lanternpowered.api.item.inventory.entity.PlayerInventory import org.lanternpowered.api.text.textOf /** * Constructs a new container. */ fun container(fn: ContainerBuilder.() -> Unit): Container { TODO() } /** * A builder to construct [ExtendedContainer]s. */ interface ContainerBuilder { /** * Applies the layout of the container. */ fun <L : ContainerLayout> layout(type: ExtendedContainerType<L>): L /** * Applies the layout of the container. */ fun <L : ContainerLayout> layout(type: ExtendedContainerType<L>, fn: L.() -> Unit): L = this.layout(type).apply(fn) fun shiftClickBehavior(behavior: ShiftClickBehavior) } fun testFurnace(player: Player, playerInventory: PlayerInventory, furnaceInventory: Inventory) { val container = container { layout(ContainerTypes.Furnace) { top.slots(furnaceInventory) bottom.slots(playerInventory.primary) } } player.openInventory(container) } fun test(player: Player, playerInventory: PlayerInventory, furnaceInventory: Inventory) { val container = container { layout(ContainerTypes.Generic9x5) { title = textOf("My Fancy Furnace") top { fill(ContainerFills.Black) val slots = furnaceInventory.slots() get(1, 1).slot(slots[0]) // Input get(1, 2).button { icon(ItemTypes.BLAZE_POWDER) } get(1, 3).slot(slots[1]) // Fuel get(3, 2).slot(slots[2]) // Output } bottom { slots(playerInventory.primary) } } } player.openInventory(container) }
mit
f676d7178690ab11a67abb39aadbb86f
30.467532
96
0.65291
4.099831
false
false
false
false
Kotlin/kotlinx.serialization
core/jvmMain/src/kotlinx/serialization/internal/Platform.kt
1
6418
/* * Copyright 2017-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.internal import kotlinx.serialization.* import java.lang.reflect.* import kotlin.reflect.* @Suppress("NOTHING_TO_INLINE") internal actual inline fun <T> Array<T>.getChecked(index: Int): T { return get(index) } @Suppress("NOTHING_TO_INLINE") internal actual inline fun BooleanArray.getChecked(index: Int): Boolean { return get(index) } @Suppress("UNCHECKED_CAST") internal actual fun <T : Any> KClass<T>.compiledSerializerImpl(): KSerializer<T>? = this.constructSerializerForGivenTypeArgs() @Suppress("UNCHECKED_CAST") internal actual fun <T : Any, E : T?> ArrayList<E>.toNativeArrayImpl(eClass: KClass<T>): Array<E> = toArray(java.lang.reflect.Array.newInstance(eClass.java, size) as Array<E>) internal actual fun KClass<*>.platformSpecificSerializerNotRegistered(): Nothing = serializerNotRegistered() internal fun Class<*>.serializerNotRegistered(): Nothing { throw SerializationException( "Serializer for class '${simpleName}' is not found.\n" + "Mark the class as @Serializable or provide the serializer explicitly." ) } internal actual fun <T : Any> KClass<T>.constructSerializerForGivenTypeArgs(vararg args: KSerializer<Any?>): KSerializer<T>? { return java.constructSerializerForGivenTypeArgs(*args) } @Suppress("UNCHECKED_CAST") internal fun <T: Any> Class<T>.constructSerializerForGivenTypeArgs(vararg args: KSerializer<Any?>): KSerializer<T>? { if (isEnum && isNotAnnotated()) { return createEnumSerializer() } // Fall-through if the serializer is not found -- lookup on companions (for sealed interfaces) or fallback to polymorphic if applicable if (isInterface) interfaceSerializer()?.let { return it } // Search for serializer defined on companion object. val serializer = invokeSerializerOnCompanion<T>(this, *args) if (serializer != null) return serializer // Check whether it's serializable object findObjectSerializer()?.let { return it } // Search for default serializer if no serializer is defined in companion object. // It is required for named companions val fromNamedCompanion = try { declaredClasses.singleOrNull { it.simpleName == ("\$serializer") } ?.getField("INSTANCE")?.get(null) as? KSerializer<T> } catch (e: NoSuchFieldException) { null } if (fromNamedCompanion != null) return fromNamedCompanion // Check for polymorphic return if (isPolymorphicSerializer()) { PolymorphicSerializer(this.kotlin) } else { null } } private fun <T: Any> Class<T>.isNotAnnotated(): Boolean { /* * For annotated enums search serializer directly (or do not search at all?) */ return getAnnotation(Serializable::class.java) == null && getAnnotation(Polymorphic::class.java) == null } private fun <T: Any> Class<T>.isPolymorphicSerializer(): Boolean { /* * Last resort: check for @Polymorphic or Serializable(with = PolymorphicSerializer::class) * annotations. */ if (getAnnotation(Polymorphic::class.java) != null) { return true } val serializable = getAnnotation(Serializable::class.java) if (serializable != null && serializable.with == PolymorphicSerializer::class) { return true } return false } private fun <T: Any> Class<T>.interfaceSerializer(): KSerializer<T>? { /* * Interfaces are @Polymorphic by default. * Check if it has no annotations or `@Serializable(with = PolymorphicSerializer::class)`, * otherwise bailout. */ val serializable = getAnnotation(Serializable::class.java) if (serializable == null || serializable.with == PolymorphicSerializer::class) { return PolymorphicSerializer(this.kotlin) } return null } @Suppress("UNCHECKED_CAST") private fun <T : Any> invokeSerializerOnCompanion(jClass: Class<*>, vararg args: KSerializer<Any?>): KSerializer<T>? { val companion = jClass.companionOrNull() ?: return null return try { val types = if (args.isEmpty()) emptyArray() else Array(args.size) { KSerializer::class.java } companion.javaClass.getDeclaredMethod("serializer", *types) .invoke(companion, *args) as? KSerializer<T> } catch (e: NoSuchMethodException) { null } catch (e: InvocationTargetException) { val cause = e.cause ?: throw e throw InvocationTargetException(cause, cause.message ?: e.message) } } private fun Class<*>.companionOrNull() = try { val companion = getDeclaredField("Companion") companion.isAccessible = true companion.get(null) } catch (e: Throwable) { null } @Suppress("UNCHECKED_CAST") private fun <T : Any> Class<T>.createEnumSerializer(): KSerializer<T> { val constants = enumConstants return EnumSerializer(canonicalName, constants as Array<out Enum<*>>) as KSerializer<T> } private fun <T : Any> Class<T>.findObjectSerializer(): KSerializer<T>? { // Check it is an object without using kotlin-reflect val field = declaredFields.singleOrNull { it.name == "INSTANCE" && it.type == this && Modifier.isStatic(it.modifiers) } ?: return null // Retrieve its instance and call serializer() val instance = field.get(null) val method = methods.singleOrNull { it.name == "serializer" && it.parameterTypes.isEmpty() && it.returnType == KSerializer::class.java } ?: return null val result = method.invoke(instance) @Suppress("UNCHECKED_CAST") return result as? KSerializer<T> } /** * Checks if an [this@isInstanceOf] is an instance of a given [kclass]. * * This check is a replacement for [KClass.isInstance] because * on JVM it requires kotlin-reflect.jar in classpath * (see https://youtrack.jetbrains.com/issue/KT-14720). * * On JS and Native, this function delegates to aforementioned * [KClass.isInstance] since it is supported there out-of-the box; * on JVM, it falls back to java.lang.Class.isInstance, which causes * difference when applied to function types with big arity. */ internal actual fun Any.isInstanceOf(kclass: KClass<*>): Boolean = kclass.javaObjectType.isInstance(this) internal actual fun isReferenceArray(rootClass: KClass<Any>): Boolean = rootClass.java.isArray
apache-2.0
61e0c4c227d68d9bd76f104f5651bba3
37.662651
139
0.695232
4.29585
false
false
false
false
RoverPlatform/rover-android
core/src/main/kotlin/io/rover/sdk/core/data/graphql/GraphQlApiService.kt
1
7864
package io.rover.sdk.core.data.graphql import android.net.Uri import io.rover.sdk.core.data.APIException import io.rover.sdk.core.data.AuthenticationContext import io.rover.sdk.core.data.GraphQlRequest import io.rover.sdk.core.data.NetworkError import io.rover.sdk.core.data.NetworkResult import io.rover.sdk.core.data.domain.EventSnapshot import io.rover.sdk.core.data.domain.Experience import io.rover.sdk.core.data.graphql.operations.SendEventsRequest import io.rover.sdk.core.data.http.HttpClientResponse import io.rover.sdk.core.data.http.HttpRequest import io.rover.sdk.core.data.http.HttpVerb import io.rover.sdk.core.data.http.NetworkClient import io.rover.sdk.core.data.graphql.operations.FetchExperienceRequest import io.rover.sdk.core.logging.log import io.rover.sdk.core.platform.DateFormattingInterface import io.rover.sdk.core.streams.Publishers import io.rover.sdk.core.streams.map import org.json.JSONException import org.reactivestreams.Publisher import java.io.IOException import java.net.URL /** * Responsible for providing access the Rover cloud API, powered by GraphQL. */ class GraphQlApiService( private val endpoint: URL, private val authenticationContext: AuthenticationContext, private val networkClient: NetworkClient, private val dateFormatting: DateFormattingInterface ) : GraphQlApiServiceInterface { private fun urlRequest(mutation: Boolean, queryParams: Map<String, String>): HttpRequest { val uri = Uri.parse(endpoint.toString()) val builder = uri.buildUpon() queryParams.forEach { (k, v) -> builder.appendQueryParameter(k, v) } return HttpRequest( URL(builder.toString()), hashMapOf<String, String>().apply { if (mutation) { this["Content-Type"] = "application/json" } when { authenticationContext.sdkToken != null -> this["x-rover-account-token"] = authenticationContext.sdkToken!! authenticationContext.bearerToken != null -> this["authorization"] = "Bearer ${authenticationContext.bearerToken}" } this.entries.forEach { (key, value) -> this[key] = value } }, if (mutation) { HttpVerb.POST } else { HttpVerb.GET } ) } private fun <TEntity> httpResult(httpRequest: GraphQlRequest<TEntity>, httpResponse: HttpClientResponse): NetworkResult<TEntity> = when (httpResponse) { is HttpClientResponse.ConnectionFailure -> NetworkResult.Error(httpResponse.reason, true) is HttpClientResponse.ApplicationError -> { log.w("Given GraphQL error reason: ${httpResponse.reportedReason}") NetworkResult.Error( NetworkError.InvalidStatusCode(httpResponse.responseCode, httpResponse.reportedReason), when { // actually won't see any 200 codes here; already filtered about in the // HttpClient response mapping. httpResponse.responseCode < 300 -> false // 3xx redirects httpResponse.responseCode < 400 -> false // 4xx request errors (we don't want to retry these; onus is likely on // request creator). httpResponse.responseCode < 500 -> false // 5xx - any transient errors from the backend. else -> true } ) } is HttpClientResponse.Success -> { try { val body = httpResponse.bufferedInputStream.use { it.reader(Charsets.UTF_8).readText() } log.v("RESPONSE BODY: $body") when (body) { "" -> NetworkResult.Error(NetworkError.EmptyResponseData(), false) else -> { try { NetworkResult.Success( httpRequest.decode(body) ) } catch (e: APIException) { log.w("API error: $e") NetworkResult.Error<TEntity>( NetworkError.InvalidResponseData(e.message ?: "API returned unknown error."), // retry is not appropriate when we're getting a domain-level // error from the GraphQL API. false ) } catch (e: JSONException) { // because the traceback information has some utility for diagnosing // JSON decode errors, even though we're treating them as soft // errors, throw the traceback onto the console: log.w("JSON decode problem details: $e, ${e.stackTrace.joinToString("\n")}") NetworkResult.Error<TEntity>( NetworkError.InvalidResponseData(e.message ?: "API returned unknown error."), // retry is not appropriate when we're getting a domain-level // error from the GraphQL API. false ) } } } } catch (exception: IOException) { NetworkResult.Error<TEntity>(exception, true) } } } override fun <TEntity> operation(request: GraphQlRequest<TEntity>): Publisher<NetworkResult<TEntity>> { // TODO: once we change urlRequest() to use query parameters and GET for non-mutation // requests, replace true `below` with `request.mutation`. val urlRequest = urlRequest(request.mutation, request.encodeQueryParameters()) val bodyData = request.encodeBody() log.v("going to make network request $urlRequest") return if (authenticationContext.isAvailable()) { networkClient.request(urlRequest, bodyData).map { httpClientResponse -> httpResult(request, httpClientResponse) } } else { Publishers.just( NetworkResult.Error( Throwable("Rover API authentication not available."), true ) ) } } override fun submitEvents(events: List<EventSnapshot>): Publisher<NetworkResult<String>> { return if (!authenticationContext.isAvailable()) { log.w("Events may not be submitted without a Rover authentication context being configured.") Publishers.just( NetworkResult.Error( Exception("Attempt to submit Events without Rover authentication context being configured."), false ) ) } else { operation( SendEventsRequest( dateFormatting, events ) ) } } /** * Retrieves the experience when subscribed and yields it to the subscriber. */ override fun fetchExperience( query: FetchExperienceRequest.ExperienceQueryIdentifier ): Publisher<NetworkResult<Experience>> { return this.operation( FetchExperienceRequest(query) ) } }
apache-2.0
2d01848969a6edab72ae630e06d9f297
42.932961
134
0.548321
5.573352
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/waking/GivenALibrary/WhenWakingALibraryServerFourTimes.kt
2
2603
package com.lasthopesoftware.bluewater.client.connection.waking.GivenALibrary import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.connection.builder.lookup.LookupServers import com.lasthopesoftware.bluewater.client.connection.builder.lookup.ServerInfo import com.lasthopesoftware.bluewater.client.connection.waking.AlarmConfiguration import com.lasthopesoftware.bluewater.client.connection.waking.MachineAddress import com.lasthopesoftware.bluewater.client.connection.waking.PokeServer import com.lasthopesoftware.bluewater.client.connection.waking.ServerAlarm import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.joda.time.Duration import org.junit.BeforeClass import org.junit.Test import java.util.* class WhenWakingALibraryServerFourTimes { companion object { private val expectedPokedMachineAddresses = arrayOf( MachineAddress("local-address", "AB-E0-9F-24-F5"), MachineAddress("local-address", "99-53-7F-2C-A1"), MachineAddress("second-local-address", "AB-E0-9F-24-F5"), MachineAddress("second-local-address", "99-53-7F-2C-A1"), MachineAddress("remote-address", "AB-E0-9F-24-F5"), MachineAddress("remote-address", "99-53-7F-2C-A1") ) private val pokedMachineAddresses: MutableList<MachineAddress> = ArrayList() @BeforeClass @JvmStatic fun before() { val lookupServers = mockk<LookupServers>() every { lookupServers.promiseServerInformation(any()) } returns Promise<ServerInfo?>( ServerInfo( 5001, 5002, "remote-address", listOf("local-address", "second-local-address"), listOf("AB-E0-9F-24-F5", "99-53-7F-2C-A1"), null ) ) val pokeServer = mockk<PokeServer>() every { pokeServer.promiseWakeSignal(any(), any(), any()) } answers { Unit.toPromise() } every { pokeServer.promiseWakeSignal(any(), 4, Duration.standardSeconds(60)) } answers { pokedMachineAddresses.add(firstArg()) Unit.toPromise() } val serverAlarm = ServerAlarm( lookupServers, pokeServer, AlarmConfiguration(4, Duration.standardMinutes(1)) ) serverAlarm.awakeLibraryServer(LibraryId(14)).toFuture().get() } } @Test fun thenTheMachineIsAlertedAtAllEndpoints() { assertThat(pokedMachineAddresses) .containsExactlyInAnyOrder(*expectedPokedMachineAddresses) } }
lgpl-3.0
9c2952784e06cb9ddaae6fda61475a06
34.657534
91
0.771033
3.536685
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/preferences/PreferencesActivity.kt
1
3316
/***************************************************************************** * PreferencesActivity.java * * Copyright © 2011-2014 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc.gui.preferences import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.appcompat.widget.Toolbar import androidx.core.view.ViewCompat import com.google.android.material.appbar.AppBarLayout import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.tools.RESULT_RESTART import org.videolan.tools.RESULT_RESTART_APP import org.videolan.tools.RESULT_UPDATE_ARTISTS import org.videolan.vlc.PlaybackService import org.videolan.vlc.R import org.videolan.vlc.gui.BaseActivity @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi class PreferencesActivity : BaseActivity() { private var mAppBarLayout: AppBarLayout? = null override val displayTitle = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.preferences_activity) setSupportActionBar(findViewById<View>(R.id.main_toolbar) as Toolbar) if (savedInstanceState == null) { supportFragmentManager.beginTransaction() .replace(R.id.fragment_placeholder, PreferencesFragment()) .commit() } mAppBarLayout = findViewById(R.id.appbar) mAppBarLayout!!.post { ViewCompat.setElevation(mAppBarLayout!!, resources.getDimensionPixelSize(R.dimen.default_appbar_elevation).toFloat()) } } internal fun expandBar() { mAppBarLayout!!.setExpanded(true) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { if (!supportFragmentManager.popBackStackImmediate()) finish() return true } return super.onOptionsItemSelected(item) } fun restartMediaPlayer() { val le = PlaybackService.restartPlayer if (le.hasObservers()) le.value = true } fun exitAndRescan() { setRestart() val intent = intent finish() startActivity(intent) } fun setRestart() { setResult(RESULT_RESTART) } fun setRestartApp() { setResult(RESULT_RESTART_APP) } fun updateArtists() { setResult(RESULT_UPDATE_ARTISTS) } fun detectHeadset(detect: Boolean) { val le = PlaybackService.headSetDetection if (le.hasObservers()) le.value = detect } }
gpl-2.0
f0b2463d13a3cd00864cd419de62ff56
32.15
150
0.690498
4.776657
false
false
false
false
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/request/graph/SelectionTree.kt
1
2193
package com.github.pgutkowski.kgraphql.request.graph import com.github.pgutkowski.kgraphql.RequestException import com.github.pgutkowski.kgraphql.request.Arguments import java.util.* class SelectionSetBuilder : ArrayList<SelectionNode>(){ fun build() : SelectionTree { return SelectionTree(*this.toTypedArray()) } override fun add(element: SelectionNode): Boolean { when { element.key.isBlank() -> throw RequestException("cannot handle blank property in object : $this") any { it.aliasOrKey == element.aliasOrKey } -> return false else -> return super.add(element) } } } data class SelectionTree(val nodes: List<SelectionNode>) : Collection<SelectionNode> by nodes { constructor(vararg graphNodes : SelectionNode) : this(graphNodes.toList()) operator fun get(aliasOrKey: String) = find { it.aliasOrKey == aliasOrKey } } fun leaf(key : String, alias: String? = null) = SelectionNode(key, alias) fun leafs(vararg keys : String): Array<SelectionNode> { return keys.map { SelectionNode(it) }.toTypedArray() } fun branch(key: String, vararg nodes: SelectionNode) = SelectionNode(key = key, alias = null, children = SelectionTree(*nodes)) fun argLeaf(key: String, args: Arguments) = SelectionNode(key = key, alias = null, children = null, arguments = args) fun args(vararg args: Pair<String, String>) = Arguments(*args) fun argBranch(key: String, args: Arguments, vararg nodes: SelectionNode): SelectionNode { return SelectionNode(key = key, alias = null, children = if (nodes.isNotEmpty()) SelectionTree(*nodes) else null, arguments = args) } fun argBranch(key: String, alias: String, args: Arguments, vararg nodes: SelectionNode): SelectionNode { return SelectionNode(key, alias, if (nodes.isNotEmpty()) SelectionTree(*nodes) else null, args) } fun extFragment(key: String, typeCondition: String, vararg nodes: SelectionNode) : Fragment.External { return Fragment.External(key, SelectionTree(*nodes), typeCondition) } fun inlineFragment(typeCondition: String, vararg nodes: SelectionNode) : Fragment.Inline { return Fragment.Inline(SelectionTree(*nodes), typeCondition, null) }
mit
1fd817d20560c48aeb8f7893984cb252
38.890909
135
0.726858
3.980036
false
false
false
false
googlecodelabs/kotlin-coroutines
ktx-library-codelab/step-06/app/src/main/java/com/example/android/kotlinktxworkshop/MainActivity.kt
1
3266
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.kotlinktxworkshop import android.Manifest.permission.ACCESS_FINE_LOCATION import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.Observer import androidx.lifecycle.asLiveData import androidx.lifecycle.lifecycleScope import com.example.android.myktxlibrary.awaitLastLocation import com.example.android.myktxlibrary.findAndSetText import com.example.android.myktxlibrary.hasPermission import com.example.android.myktxlibrary.locationFlow import com.example.android.myktxlibrary.showLocation import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationServices import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { private lateinit var fusedLocationClient: FusedLocationProviderClient override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) fusedLocationClient = LocationServices.getFusedLocationProviderClient(this) startUpdatingLocation() } override fun onStart() { super.onStart() if (!hasPermission(ACCESS_FINE_LOCATION)) { requestPermissions(arrayOf(ACCESS_FINE_LOCATION), 0) } lifecycleScope.launch { getLastKnownLocation() } } private suspend fun getLastKnownLocation() { try { val lastLocation = fusedLocationClient.awaitLastLocation() showLocation(R.id.textView, lastLocation) } catch (e: Exception) { findAndSetText(R.id.textView, "Unable to get location.") Log.d(TAG, "Unable to get location", e) } } private fun startUpdatingLocation() { fusedLocationClient.locationFlow() .conflate() .catch { e -> findAndSetText(R.id.textView, "Unable to get location.") Log.d(TAG, "Unable to get location", e) } .asLiveData() .observe(this, Observer { location -> showLocation(R.id.textView, location) Log.d(TAG, location.toString()) }) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { recreate() } } } const val TAG = "KTXCODELAB"
apache-2.0
10d4aa9441c578827d42ea2c3ecdce74
33.378947
96
0.69902
4.810015
false
false
false
false
nemerosa/ontrack
ontrack-json/src/main/java/net/nemerosa/ontrack/json/SimpleDurationDeserializer.kt
1
1535
package net.nemerosa.ontrack.json import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import java.time.Duration class SimpleDurationDeserializer : JsonDeserializer<Duration>() { override fun deserialize(jp: JsonParser, ctxt: DeserializationContext): Duration { val s = jp.readValueAs(String::class.java) return parse(s) } companion object { private val regexDuration = "^(\\d+)[hdw]$".toRegex() private val regexDays = "^(\\d+)$".toRegex() fun parse(s: String): Duration = if (s.isBlank()) { Duration.ZERO } else { val mr = regexDuration.matchEntire(s) if (mr != null) { val count = mr.groupValues[1].toLong(10) when (s.last()) { 'h' -> Duration.ofHours(count) 'd' -> Duration.ofDays(count) 'w' -> Duration.ofDays(count * 7) else -> error("Cannot parse the duration: $s") } } else { val md = regexDays.matchEntire(s) if (md != null) { val count = s.toLong(10) Duration.ofDays(count) } else { error("Cannot parse the duration: $s") } } } } }
mit
62e1b99373cf0e00cc3755d67eb7cfc3
33.909091
86
0.497068
4.873016
false
false
false
false
goodwinnk/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/TypeConstraint.kt
1
2005
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.lang.resolve.processors.inference import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiElement import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula import com.intellij.psi.impl.source.resolve.graphInference.constraints.TypeCompatibilityConstraint import org.jetbrains.plugins.groovy.lang.psi.impl.GrLiteralClassType import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil class TypeConstraint(val leftType: PsiType, private val rightType: PsiType?, val context: PsiElement) : ConstraintFormula { override fun reduce(session: InferenceSession, constraints: MutableList<ConstraintFormula>): Boolean { if (session !is GroovyInferenceSession) return true var argType = rightType ?: PsiType.NULL if (argType is GrTupleType) { val rawWildcardType = TypesUtil.rawWildcard(argType, context) argType = rawWildcardType ?: argType } if (argType !is GrLiteralClassType) argType = com.intellij.psi.util.PsiUtil.captureToplevelWildcards(argType, context) if (argType is GrMapType && session.skipClosureBlock) argType = TypesUtil.createTypeByFQClassName(CommonClassNames.JAVA_UTIL_MAP, context) val t = session.siteSubstitutor.substitute(session.substituteWithInferenceVariables(leftType)) val s = session.siteSubstitutor.substitute(session.substituteWithInferenceVariables(argType)) constraints.add(TypeCompatibilityConstraint(t, s)) return true } override fun apply(substitutor: PsiSubstitutor, cache: Boolean) {} }
apache-2.0
8efd421d8ebed1413a238280e82216f5
51.763158
140
0.805985
4.445676
false
false
false
false