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
chrislo27/RhythmHeavenRemixEditor2
core/src/main/kotlin/io/github/chrislo27/toolboks/aabbcollision/CollisionResolver.kt
2
5655
package io.github.chrislo27.toolboks.aabbcollision import com.badlogic.gdx.math.Rectangle import com.badlogic.gdx.utils.Pool import com.badlogic.gdx.utils.ReflectionPool import io.github.chrislo27.toolboks.util.gdxutils.intersects import io.github.chrislo27.toolboks.util.gdxutils.maxX import io.github.chrislo27.toolboks.util.gdxutils.maxY import java.util.* /** * Swept AABB collision. * https://www.gamedev.net/resources/_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084 */ class CollisionResolver { private val resultPool: Pool<CollisionResult> = ReflectionPool(CollisionResult::class.java, 4) private val tempResults = LinkedList<CollisionResult>() private val broadphase = Rectangle(0f, 0f, 1f, 1f) var timescale = 1f /** * Return a [CollisionResult] back to the pool. */ fun returnBorrowedResult(result: CollisionResult) { resultPool.free(result) } /** * Finds the collision point for the moving [body] against the [target]. */ fun findCollisionPoint(body: PhysicsBody, target: PhysicsBody, result: CollisionResult): CollisionResult { result.reset() // get the distance from each possible edge val xEntryDist: Float val yEntryDist: Float val xExitDist: Float val yExitDist: Float if (body.velocity.x > 0) { xEntryDist = target.bounds.getX() - body.bounds.maxX xExitDist = target.bounds.maxX - body.bounds.getX() } else { xEntryDist = target.bounds.maxX - body.bounds.getX() xExitDist = target.bounds.getX() - body.bounds.maxX } if (body.velocity.y > 0) { yEntryDist = target.bounds.getY() - body.bounds.maxY yExitDist = target.bounds.maxY - body.bounds.getY() } else { yEntryDist = target.bounds.maxY - body.bounds.getY() yExitDist = target.bounds.getY() - body.bounds.maxY } var xEntryTime: Float var yEntryTime: Float val xExitTime: Float val yExitTime: Float if (body.velocity.x == 0f) { xEntryTime = Float.NEGATIVE_INFINITY xExitTime = Float.POSITIVE_INFINITY } else { xEntryTime = xEntryDist / (body.velocity.x * timescale) xExitTime = xExitDist / (body.velocity.x * timescale) } if (body.velocity.y == 0f) { yEntryTime = Float.NEGATIVE_INFINITY yExitTime = Float.POSITIVE_INFINITY } else { yEntryTime = yEntryDist / (body.velocity.y * timescale) yExitTime = yExitDist / (body.velocity.y * timescale) } if (xEntryTime == -0f) { xEntryTime = 0f } if (yEntryTime == -0f) { yEntryTime = 0f } val entryTime = Math.max(xEntryTime, yEntryTime) val exitTime = Math.min(xExitTime, yExitTime) // if there was no collision if (entryTime > exitTime || (xEntryTime < 0 && yEntryTime < 0) || xEntryTime > 1 || yEntryTime > 1) { result.reset() return result } else { // calculate normal of collided surface if (xEntryTime > yEntryTime) { if (xEntryDist < 0.0f) { result.normal = Normal.RIGHT } else { result.normal = Normal.LEFT } } else { if (yEntryDist < 0.0f) { result.normal = Normal.TOP } else { result.normal = Normal.BOTTOM } } // return the time of collision result.makeValid() result.distance = entryTime result.collider = body result.collidedWith = target return result } } /** * Finds a list of collision points between a moving [body] and some [other][others] bodies. * The returned list is sorted by nearest to farthest contact. */ fun findCollisionPoints(body: PhysicsBody, others: List<PhysicsBody>): List<CollisionResult> { val results: List<CollisionResult> val borrowed = tempResults borrowed.clear() broadphase.set(body.bounds.getX(), body.bounds.getY(), body.bounds.getWidth(), body.bounds.getHeight()) broadphase.setX(broadphase.getX() + Math.min(0f, body.velocity.x)) broadphase.setY(broadphase.getY() + Math.min(0f, body.velocity.y)) broadphase.setWidth(body.bounds.getWidth() + Math.abs(body.velocity.x)) broadphase.setHeight(body.bounds.getHeight() + Math.abs(body.velocity.y)) results = others.filter { pb -> pb !== body && pb.bounds.intersects(broadphase) }.map { pb -> val temp = resultPool.obtain() borrowed += temp findCollisionPoint(body, pb, temp) }.filter(CollisionResult::collided).sorted() borrowed.filter { it !in results }.forEach(this::returnBorrowedResult) borrowed.clear() return results.takeUnless(List<CollisionResult>::isEmpty) ?: listOf(resultPool.obtain()) } /** * The same as [findCollisionPoints], but returns the first item in the list. The other items * in the list will be immediately returned to the pool. */ fun findFirstCollisionPoint(body: PhysicsBody, others: List<PhysicsBody>): CollisionResult { val results = findCollisionPoints(body, others) results.drop(1).forEach(this::returnBorrowedResult) return results.first() } }
gpl-3.0
2a23a2a2952053425e5cdac2221b7f08
34.35
115
0.602653
4.100798
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/ui/view/AboutView.kt
1
2038
/* * (C) Copyright 2019 Lukas Morawietz (https://github.com/F43nd1r) * * 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.faendir.acra.ui.view import com.faendir.acra.i18n.Messages import com.faendir.acra.navigation.View import com.faendir.acra.ui.component.HasAcrariumTitle import com.faendir.acra.i18n.TranslatableText import com.faendir.acra.ui.component.Translatable import com.faendir.acra.ui.view.main.MainView import com.vaadin.flow.component.html.Div import com.vaadin.flow.component.orderedlayout.FlexComponent import com.vaadin.flow.component.orderedlayout.FlexComponent.JustifyContentMode import com.vaadin.flow.component.orderedlayout.FlexLayout import com.vaadin.flow.router.Route import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.info.BuildProperties /** * @author lukas * @since 06.09.19 */ @Suppress("LeakingThis") @View @Route(value = "about", layout = MainView::class) class AboutView(@Autowired val buildProperties: BuildProperties) : FlexLayout(), HasAcrariumTitle { init { setSizeFull() justifyContentMode = JustifyContentMode.CENTER alignItems = FlexComponent.Alignment.CENTER setFlexDirection(FlexDirection.COLUMN) val info = Div() info.element.setProperty("innerHTML", getTranslation(Messages.FOOTER)) val version = Translatable.createDiv(Messages.ABOUT_VERSION, buildProperties.version) add(info, version) } override val title = TranslatableText(Messages.ABOUT) }
apache-2.0
4e9d521e4f6a953c088963513f62116d
36.759259
99
0.766438
3.996078
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.kt
1
13343
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.ui import com.intellij.application.options.RegistryManager import com.intellij.ide.ui.UISettings.Companion.setupAntialiasing import com.intellij.jdkEx.JdkEx import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.MouseGestureManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.ui.popup.util.PopupUtil import com.intellij.openapi.util.* import com.intellij.openapi.wm.* import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy import com.intellij.openapi.wm.ex.IdeFrameEx import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.openapi.wm.impl.* import com.intellij.openapi.wm.impl.LinuxIdeMenuBar.Companion.doBindAppMenuOfParent import com.intellij.openapi.wm.impl.customFrameDecorations.header.CustomFrameDialogContent.Companion.getCustomContentHolder import com.intellij.ui.AppUIUtil import com.intellij.ui.BalloonLayout import com.intellij.ui.ComponentUtil import com.intellij.ui.FrameState import com.intellij.util.SystemProperties import com.intellij.util.containers.ContainerUtil import com.intellij.util.ui.ImageUtil import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.NonNls import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.resolvedPromise import java.awt.* import java.awt.event.ActionListener import java.awt.event.KeyEvent import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.nio.file.Path import javax.swing.* open class FrameWrapper @JvmOverloads constructor(project: Project?, @param:NonNls protected open val dimensionKey: String? = null, private val isDialog: Boolean = false, var title: String = "", open var component: JComponent? = null) : Disposable, DataProvider { open var preferredFocusedComponent: JComponent? = null private var images: List<Image>? = null private var isCloseOnEsc = false private var onCloseHandler: BooleanGetter? = null private var frame: Window? = null private var project: Project? = null private var focusWatcher: FocusWatcher? = null private var isDisposing = false var isDisposed = false private set protected var statusBar: StatusBar? = null set(value) { field?.let { Disposer.dispose(it) } field = value } init { project?.let { setProject(it) } } fun setProject(project: Project) { this.project = project ApplicationManager.getApplication().messageBus.connect(this).subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosing(project: Project) { if (project === [email protected]) { close() } } }) } open fun show() { show(true) } fun show(restoreBounds: Boolean) { val frame = getFrame() if (frame is JFrame) { frame.defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE } else { (frame as JDialog).defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE } frame.addWindowListener(object : WindowAdapter() { override fun windowClosing(e: WindowEvent) { close() } }) UIUtil.decorateWindowHeader((frame as RootPaneContainer).rootPane) if (frame is JFrame) { UIUtil.setCustomTitleBar(frame, frame.rootPane) { runnable -> Disposer.register(this, Disposable { runnable.run() }) } } val focusListener = object : WindowAdapter() { override fun windowOpened(e: WindowEvent) { val focusManager = IdeFocusManager.getInstance(project) val toFocus = preferredFocusedComponent ?: focusManager.getFocusTargetFor(component!!) if (toFocus != null) { focusManager.requestFocus(toFocus, true) } } } frame.addWindowListener(focusListener) if (RegistryManager.getInstance().`is`("ide.perProjectModality")) { frame.isAlwaysOnTop = true } Disposer.register(this, Disposable { frame.removeWindowListener(focusListener) }) if (isCloseOnEsc) { addCloseOnEsc(frame as RootPaneContainer) } if (IdeFrameDecorator.isCustomDecorationActive()) { component = getCustomContentHolder(frame, component!!) } frame.contentPane.add(component!!, BorderLayout.CENTER) if (frame is JFrame) { frame.title = title } else { (frame as JDialog).title = title } if (images == null) { AppUIUtil.updateWindowIcon(frame) } else { // unwrap the image before setting as frame's icon frame.setIconImages(ContainerUtil.map(images!!) { image: Image? -> ImageUtil.toBufferedImage((image)!!) }) } val state = dimensionKey?.let { dimensionKey -> getWindowStateService(project).getState(dimensionKey, frame) } if (restoreBounds) { loadFrameState(state) } if (SystemInfo.isLinux && frame is JFrame && GlobalMenuLinux.isAvailable()) { val parentFrame = WindowManager.getInstance().getFrame(project) if (parentFrame != null) { doBindAppMenuOfParent(frame, parentFrame) } } focusWatcher = FocusWatcher() focusWatcher!!.install(component!!) frame.isVisible = true } fun close() { if (isDisposed || (onCloseHandler != null && !onCloseHandler!!.get())) { return } // if you remove this line problems will start happen on Mac OS X // 2 projects opened, call Cmd+D on the second opened project and then Esc. // Weird situation: 2nd IdeFrame will be active, but focus will be somewhere inside the 1st IdeFrame // App is unusable until Cmd+Tab, Cmd+tab frame?.isVisible = false Disposer.dispose(this) } override fun dispose() { if (isDisposed) { return } val frame = frame val statusBar = statusBar this.frame = null preferredFocusedComponent = null project = null if (component != null && focusWatcher != null) { focusWatcher!!.deinstall(component) } focusWatcher = null component = null images = null isDisposed = true if (statusBar != null) { Disposer.dispose(statusBar) } if (frame != null) { frame.isVisible = false val rootPane = (frame as RootPaneContainer).rootPane frame.removeAll() DialogWrapper.cleanupRootPane(rootPane) if (frame is IdeFrame) { MouseGestureManager.getInstance().remove(frame) } frame.dispose() DialogWrapper.cleanupWindowListeners(frame) } } private fun addCloseOnEsc(frame: RootPaneContainer) { val rootPane = frame.rootPane val closeAction = ActionListener { if (!PopupUtil.handleEscKeyEvent()) { close() } } rootPane.registerKeyboardAction(closeAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW) ActionUtil.registerForEveryKeyboardShortcut(rootPane, closeAction, CommonShortcuts.getCloseActiveWindow()) } fun getFrame(): Window { assert(!isDisposed) { "Already disposed!" } var result = frame if (result == null) { val parent = WindowManager.getInstance().getIdeFrame(project)!! result = if (isDialog) createJDialog(parent) else createJFrame(parent) frame = result } return result } val isActive: Boolean get() = frame?.isActive == true protected open fun createJFrame(parent: IdeFrame): JFrame = MyJFrame(this, parent) protected open fun createJDialog(parent: IdeFrame): JDialog = MyJDialog(this, parent) protected open fun getNorthExtension(key: String?): IdeRootPaneNorthExtension? = null override fun getData(@NonNls dataId: String): Any? { return if (CommonDataKeys.PROJECT.`is`(dataId)) project else null } private fun getDataInner(dataId: String): Any? { return when { CommonDataKeys.PROJECT.`is`(dataId) -> project else -> getData(dataId) } } fun closeOnEsc() { isCloseOnEsc = true } fun setImage(image: Image?) { setImages(listOfNotNull(image)) } fun setImages(value: List<Image>?) { images = value } fun setOnCloseHandler(value: BooleanGetter?) { onCloseHandler = value } protected open fun loadFrameState(state: WindowState?) { val frame = getFrame() if (state == null) { val ideFrame = WindowManagerEx.getInstanceEx().getIdeFrame(project) if (ideFrame != null) { frame.bounds = ideFrame.suggestChildFrameBounds() } } else { state.applyTo(frame) } (frame as RootPaneContainer).rootPane.revalidate() } private class MyJFrame(private var owner: FrameWrapper, private val parent: IdeFrame) : JFrame(), DataProvider, IdeFrame.Child, IdeFrameEx { private var frameTitle: String? = null private var fileTitle: String? = null private var file: Path? = null init { FrameState.setFrameStateListener(this) glassPane = IdeGlassPaneImpl(getRootPane(), true) if (SystemInfo.isMac && !(SystemInfo.isMacSystemMenu && SystemProperties.`is`("mac.system.menu.singleton"))) { jMenuBar = IdeMenuBar.createMenuBar() } MouseGestureManager.getInstance().add(this) focusTraversalPolicy = IdeFocusTraversalPolicy() } override fun isInFullScreen() = false override fun toggleFullScreen(state: Boolean): Promise<*> = resolvedPromise<Any>() override fun addNotify() { if (IdeFrameDecorator.isCustomDecorationActive()) { JdkEx.setHasCustomDecoration(this) } super.addNotify() } override fun getComponent(): JComponent = getRootPane() override fun getStatusBar(): StatusBar? { return (if (owner.isDisposing) null else owner.statusBar) ?: parent.statusBar } override fun suggestChildFrameBounds(): Rectangle = parent.suggestChildFrameBounds() override fun getProject() = parent.project override fun setFrameTitle(title: String) { frameTitle = title updateTitle() } override fun setFileTitle(fileTitle: String?, ioFile: Path?) { this.fileTitle = fileTitle file = ioFile updateTitle() } override fun getNorthExtension(key: String): IdeRootPaneNorthExtension? { return owner.getNorthExtension(key) } override fun getBalloonLayout(): BalloonLayout? { return null } private fun updateTitle() { ProjectFrameHelper.updateTitle(this, frameTitle, fileTitle, file, null) } override fun dispose() { val owner = owner if (owner.isDisposing) { return } owner.isDisposing = true Disposer.dispose(owner) super.dispose() rootPane = null menuBar = null } override fun getData(dataId: String): Any? { return when { IdeFrame.KEY.`is`(dataId) -> this owner.isDisposing -> null else -> owner.getDataInner(dataId) } } override fun paint(g: Graphics) { setupAntialiasing(g) super.paint(g) } } fun setLocation(location: Point) { getFrame().location = location } fun setSize(size: Dimension?) { getFrame().size = size } private class MyJDialog(private val owner: FrameWrapper, private val parent: IdeFrame) : JDialog(ComponentUtil.getWindow(parent.component)), DataProvider, IdeFrame.Child { override fun getComponent(): JComponent = getRootPane() override fun getStatusBar(): StatusBar? = null override fun getBalloonLayout(): BalloonLayout? = null override fun suggestChildFrameBounds(): Rectangle = parent.suggestChildFrameBounds() override fun getProject(): Project? = parent.project init { glassPane = IdeGlassPaneImpl(getRootPane()) getRootPane().putClientProperty("Window.style", "small") background = UIUtil.getPanelBackground() MouseGestureManager.getInstance().add(this) focusTraversalPolicy = IdeFocusTraversalPolicy() } override fun setFrameTitle(title: String) { setTitle(title) } override fun dispose() { if (owner.isDisposing) { return } owner.isDisposing = true Disposer.dispose(owner) super.dispose() rootPane = null } override fun getData(dataId: String): Any? { return when { IdeFrame.KEY.`is`(dataId) -> this owner.isDisposing -> null else -> owner.getDataInner(dataId) } } override fun paint(g: Graphics) { setupAntialiasing(g) super.paint(g) } } } private fun getWindowStateService(project: Project?): WindowStateService { return if (project == null) WindowStateService.getInstance() else WindowStateService.getInstance(project) }
apache-2.0
ee8a64eeecb73e77bb7c40b54a8e3587
29.817552
173
0.684629
4.811756
false
false
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/gui/EnergyDisplayType.kt
1
2312
package net.ndrei.teslacorelib.gui import net.minecraft.util.text.TextFormatting import net.ndrei.teslacorelib.MOD_ID import net.ndrei.teslacorelib.localization.GUI_ENERGY import net.ndrei.teslacorelib.localization.localizeModString import net.ndrei.teslacorelib.localization.makeTextComponent enum class EnergyDisplayType(val energySystem: String, val lightColor: TextFormatting, val darkColor: TextFormatting, val emptyIcon: IGuiIcon, val fullIcon: IGuiIcon, val workIcon: IGuiIcon, val tesla: Float) { TESLA("Tesla", TextFormatting.AQUA, TextFormatting.DARK_AQUA, GuiIcon.ENERGY_EMPTY_TESLA, GuiIcon.ENERGY_FULL_TESLA, GuiIcon.ENERGY_WORK_TESLA, 1.0f) , RF("Redstone Flux", TextFormatting.RED, TextFormatting.DARK_RED, GuiIcon.ENERGY_EMPTY_RF, GuiIcon.ENERGY_FULL_RF, GuiIcon.ENERGY_WORK_RF, 1.0f) //,MJ("BuildCraft MJ", TextFormatting.AQUA, TextFormatting.DARK_AQUA, GuiIcon.ENERGY_EMPTY_MJ, GuiIcon.ENERGY_FULL_MJ, 10.0f, 227, 134) ; fun fromTesla(tesla: Long) = (tesla.toFloat() / this.tesla).toLong() fun makeTextComponent(format: TextFormatting? = null) = localizeModString(MOD_ID, GUI_ENERGY, this.energySystem) { if (format != null) { +format } } fun formatPower(power: Long) = String.format("%,d", Math.round(power.toDouble() / this.tesla.toDouble())) fun makeTextComponent(power: Long, format: TextFormatting? = null) = localizeModString(MOD_ID, GUI_ENERGY, "${this.energySystem}_format") { if (format != null) { +format } +formatPower(power).makeTextComponent(format) } fun makeLightTextComponent(power: Long) = localizeModString(MOD_ID, GUI_ENERGY, "${this.energySystem}_format") { [email protected] +formatPower(power).makeTextComponent([email protected]) } fun makeDarkTextComponent(power: Long) = localizeModString(MOD_ID, GUI_ENERGY, "${this.energySystem}_format") { [email protected] +formatPower(power).makeTextComponent([email protected]) } }
mit
db09c1b4554ed1e1c22f02cb8ea6f257
44.333333
153
0.657872
4.027875
false
false
false
false
smmribeiro/intellij-community
plugins/completion-ml-ranking-models/src/com/jetbrains/completion/ml/ranker/ExperimentRustMLRankingProvider.kt
12
756
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.completion.ml.ranker import com.intellij.completion.ml.ranker.ExperimentModelProvider import com.intellij.internal.ml.catboost.CatBoostJarCompletionModelProvider import com.intellij.lang.Language class ExperimentRustMLRankingProvider : CatBoostJarCompletionModelProvider( CompletionRankingModelsBundle.message("ml.completion.experiment.model.rust"), "rust_features_exp", "rust_model_exp"), ExperimentModelProvider { override fun isLanguageSupported(language: Language): Boolean = language.id.compareTo("Rust", ignoreCase = true) == 0 override fun experimentGroupNumber(): Int = 13 }
apache-2.0
256648bd9b77e83ad65cf533ef8a5b16
53
145
0.814815
4.554217
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MayBeConstantInspection.kt
1
5229
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.VariableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.MayBeConstantInspection.Status.* import org.jetbrains.kotlin.idea.quickfix.AddConstModifierFix import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.propertyVisitor import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.constants.ErrorValue import org.jetbrains.kotlin.resolve.constants.NullValue import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.constants.evaluate.isStandaloneOnlyConstant import org.jetbrains.kotlin.resolve.jvm.annotations.hasJvmFieldAnnotation import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class MayBeConstantInspection : AbstractKotlinInspection() { enum class Status { NONE, MIGHT_BE_CONST, MIGHT_BE_CONST_ERRONEOUS, JVM_FIELD_MIGHT_BE_CONST, JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER, JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return propertyVisitor { property -> when (val status = property.getStatus()) { NONE, JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER, MIGHT_BE_CONST_ERRONEOUS, JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS -> return@propertyVisitor MIGHT_BE_CONST, JVM_FIELD_MIGHT_BE_CONST -> { holder.registerProblem( property.nameIdentifier ?: property, if (status == JVM_FIELD_MIGHT_BE_CONST) KotlinBundle.message("const.might.be.used.instead.of.jvmfield") else KotlinBundle.message("might.be.const"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(AddConstModifierFix(property)) ) } } } } companion object { fun KtProperty.getStatus(): Status { if (isLocal || isVar || getter != null || hasModifier(KtTokens.CONST_KEYWORD) || hasModifier(KtTokens.OVERRIDE_KEYWORD) || hasActualModifier() ) { return NONE } val containingClassOrObject = this.containingClassOrObject if (!isTopLevel && containingClassOrObject !is KtObjectDeclaration) return NONE if (containingClassOrObject?.isObjectLiteral() == true) return NONE val initializer = initializer // For some reason constant evaluation does not work for property.analyze() val context = (initializer ?: this).safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL) val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? VariableDescriptor ?: return NONE val type = propertyDescriptor.type if (!KotlinBuiltIns.isPrimitiveType(type) && !KotlinBuiltIns.isString(type)) return NONE val withJvmField = propertyDescriptor.hasJvmFieldAnnotation() if (annotationEntries.isNotEmpty() && !withJvmField) return NONE return when { initializer != null -> { val compileTimeConstant = ConstantExpressionEvaluator.getConstant( initializer, context ) ?: return NONE val erroneousConstant = compileTimeConstant.usesNonConstValAsConstant compileTimeConstant.toConstantValue(propertyDescriptor.type).takeIf { !it.isStandaloneOnlyConstant() && it !is NullValue && it !is ErrorValue } ?: return NONE when { withJvmField -> if (erroneousConstant) JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS else JVM_FIELD_MIGHT_BE_CONST else -> if (erroneousConstant) MIGHT_BE_CONST_ERRONEOUS else MIGHT_BE_CONST } } withJvmField -> JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER else -> NONE } } } }
apache-2.0
b5c8ec7d20945227ccbbc5a1080d1422
49.278846
158
0.659782
5.324847
false
false
false
false
afollestad/assent
rationales/src/main/java/com/afollestad/assent/rationale/SnackBarRationaleHandler.kt
1
2215
/** * Designed and developed by Aidan Follestad (@afollestad) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package com.afollestad.assent.rationale import android.app.Activity import android.view.View import androidx.fragment.app.Fragment import com.afollestad.assent.Permission import com.afollestad.assent.askForPermissions import com.google.android.material.snackbar.Snackbar internal class SnackBarRationaleHandler( private val root: View, context: Activity, requester: Requester ) : RationaleHandler(context, requester) { override fun showRationale( permission: Permission, message: CharSequence, confirm: ConfirmCallback ) { val dismissListener = object : Snackbar.Callback() { override fun onDismissed( transientBottomBar: Snackbar?, event: Int ) = confirm(isConfirmed = false) } Snackbar.make(root, message, Snackbar.LENGTH_INDEFINITE) .apply { setAction(android.R.string.ok) { removeCallback(dismissListener) confirm(isConfirmed = true) } addCallback(dismissListener) show() } } override fun onDestroy() = Unit } fun Fragment.createSnackBarRationale( root: View, block: RationaleHandler.() -> Unit ): RationaleHandler { return SnackBarRationaleHandler( root = root, context = activity ?: error("Fragment not attached"), requester = ::askForPermissions ).apply(block) } fun Activity.createSnackBarRationale( root: View, block: RationaleHandler.() -> Unit ): RationaleHandler { return SnackBarRationaleHandler( root = root, context = this, requester = ::askForPermissions ).apply(block) }
apache-2.0
8485c8ff76dbe1c41776052432d85a57
27.397436
75
0.716027
4.309339
false
false
false
false
jotomo/AndroidAPS
app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt
1
3404
package info.nightscout.androidaps.plugins.general.automation.actions import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.resources.ResourceHelper import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.`when` import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) @PrepareForTest(NSUpload::class, RxBusWrapper::class) class ActionNotificationTest : TestBase() { @Mock lateinit var resourceHelper: ResourceHelper @Mock lateinit var rxBus: RxBusWrapper @Mock lateinit var nsUpload: NSUpload private lateinit var sut: ActionNotification var injector: HasAndroidInjector = HasAndroidInjector { AndroidInjector { if (it is ActionNotification) { it.resourceHelper = resourceHelper it.rxBus = rxBus it.nsUpload = nsUpload } if (it is PumpEnactResult) { it.aapsLogger = aapsLogger it.resourceHelper = resourceHelper } } } @Before fun setup() { PowerMockito.mockStatic(NSUpload::class.java) `when`(resourceHelper.gs(R.string.ok)).thenReturn("OK") `when`(resourceHelper.gs(R.string.notification)).thenReturn("Notification") `when`(resourceHelper.gs(ArgumentMatchers.eq(R.string.notification_message), ArgumentMatchers.anyString())).thenReturn("Notification: %s") sut = ActionNotification(injector) } @Test fun friendlyNameTest() { Assert.assertEquals(R.string.notification, sut.friendlyName()) } @Test fun shortDescriptionTest() { sut.text = InputString(injector, "Asd") Assert.assertEquals("Notification: %s", sut.shortDescription()) } @Test fun iconTest() { Assert.assertEquals(R.drawable.ic_notifications, sut.icon()) } @Test fun doActionTest() { sut.doAction(object : Callback() { override fun run() { Assert.assertTrue(result.success) } }) Mockito.verify(rxBus, Mockito.times(2)).send(anyObject()) PowerMockito.verifyStatic(NSUpload::class.java, Mockito.times(1)) } @Test fun hasDialogTest() { Assert.assertTrue(sut.hasDialog()) } @Test fun toJSONTest() { sut.text = InputString(injector, "Asd") Assert.assertEquals("{\"data\":{\"text\":\"Asd\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionNotification\"}", sut.toJSON()) } @Test fun fromJSONTest() { sut.text = InputString(injector, "Asd") sut.fromJSON("{\"text\":\"Asd\"}") Assert.assertEquals("Asd", sut.text.value) } }
agpl-3.0
f34f4051310e0276bdfee1eb4f7eb0c3
34.842105
168
0.696827
4.606225
false
true
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/DefaultValueEntityImpl.kt
1
7579
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.deft.api.annotations.Default import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class DefaultValueEntityImpl : DefaultValueEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _name: String? = null override val name: String get() = _name!! override var isGenerated: Boolean = super<DefaultValueEntity>.isGenerated override var anotherName: String = super<DefaultValueEntity>.anotherName override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: DefaultValueEntityData?) : ModifiableWorkspaceEntityBase<DefaultValueEntity>(), DefaultValueEntity.Builder { constructor() : this(DefaultValueEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity DefaultValueEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isNameInitialized()) { error("Field DefaultValueEntity#name should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as DefaultValueEntity this.entitySource = dataSource.entitySource this.name = dataSource.name this.isGenerated = dataSource.isGenerated this.anotherName = dataSource.anotherName if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var name: String get() = getEntityData().name set(value) { checkModificationAllowed() getEntityData().name = value changedProperty.add("name") } override var isGenerated: Boolean get() = getEntityData().isGenerated set(value) { checkModificationAllowed() getEntityData().isGenerated = value changedProperty.add("isGenerated") } override var anotherName: String get() = getEntityData().anotherName set(value) { checkModificationAllowed() getEntityData().anotherName = value changedProperty.add("anotherName") } override fun getEntityData(): DefaultValueEntityData = result ?: super.getEntityData() as DefaultValueEntityData override fun getEntityClass(): Class<DefaultValueEntity> = DefaultValueEntity::class.java } } class DefaultValueEntityData : WorkspaceEntityData<DefaultValueEntity>() { lateinit var name: String var isGenerated: Boolean = true var anotherName: String = "Another Text" fun isNameInitialized(): Boolean = ::name.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<DefaultValueEntity> { val modifiable = DefaultValueEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): DefaultValueEntity { val entity = DefaultValueEntityImpl() entity._name = name entity.isGenerated = isGenerated entity.anotherName = anotherName entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return DefaultValueEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return DefaultValueEntity(name, entitySource) { this.isGenerated = [email protected] this.anotherName = [email protected] } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as DefaultValueEntityData if (this.entitySource != other.entitySource) return false if (this.name != other.name) return false if (this.isGenerated != other.isGenerated) return false if (this.anotherName != other.anotherName) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as DefaultValueEntityData if (this.name != other.name) return false if (this.isGenerated != other.isGenerated) return false if (this.anotherName != other.anotherName) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + name.hashCode() result = 31 * result + isGenerated.hashCode() result = 31 * result + anotherName.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + name.hashCode() result = 31 * result + isGenerated.hashCode() result = 31 * result + anotherName.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
b4e6f0fc59de47a8b288fab23a740415
31.952174
136
0.726217
5.226897
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/WithSoftLinkEntityImpl.kt
1
7378
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class WithSoftLinkEntityImpl : WithSoftLinkEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _link: NameId? = null override val link: NameId get() = _link!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: WithSoftLinkEntityData?) : ModifiableWorkspaceEntityBase<WithSoftLinkEntity>(), WithSoftLinkEntity.Builder { constructor() : this(WithSoftLinkEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity WithSoftLinkEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isLinkInitialized()) { error("Field WithSoftLinkEntity#link should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as WithSoftLinkEntity this.entitySource = dataSource.entitySource this.link = dataSource.link if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var link: NameId get() = getEntityData().link set(value) { checkModificationAllowed() getEntityData().link = value changedProperty.add("link") } override fun getEntityData(): WithSoftLinkEntityData = result ?: super.getEntityData() as WithSoftLinkEntityData override fun getEntityClass(): Class<WithSoftLinkEntity> = WithSoftLinkEntity::class.java } } class WithSoftLinkEntityData : WorkspaceEntityData<WithSoftLinkEntity>(), SoftLinkable { lateinit var link: NameId fun isLinkInitialized(): Boolean = ::link.isInitialized override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() result.add(link) return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { index.index(this, link) } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val removedItem_link = mutablePreviousSet.remove(link) if (!removedItem_link) { index.index(this, link) } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false val link_data = if (link == oldLink) { changed = true newLink as NameId } else { null } if (link_data != null) { link = link_data } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<WithSoftLinkEntity> { val modifiable = WithSoftLinkEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): WithSoftLinkEntity { val entity = WithSoftLinkEntityImpl() entity._link = link entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return WithSoftLinkEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return WithSoftLinkEntity(link, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as WithSoftLinkEntityData if (this.entitySource != other.entitySource) return false if (this.link != other.link) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as WithSoftLinkEntityData if (this.link != other.link) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + link.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + link.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(NameId::class.java) collector.sameForAllEntities = true } }
apache-2.0
ef122f1656d2b229678df7ec8e6cf7ab
30.130802
136
0.725806
5.199436
false
false
false
false
ThePreviousOne/Untitled
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryPresenter.kt
2
9386
package eu.kanade.tachiyomi.ui.library import android.os.Bundle import android.util.Pair import eu.kanade.tachiyomi.data.cache.CoverCache import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaCategory import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import eu.kanade.tachiyomi.data.source.SourceManager import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import rx.Observable import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import rx.subjects.BehaviorSubject import rx.subjects.PublishSubject import uy.kohesive.injekt.injectLazy import java.io.IOException import java.io.InputStream import java.util.* /** * Presenter of [LibraryFragment]. */ class LibraryPresenter : BasePresenter<LibraryFragment>() { /** * Categories of the library. */ var categories: List<Category> = emptyList() /** * Currently selected manga. */ val selectedMangas = mutableListOf<Manga>() /** * Search query of the library. */ val searchSubject: BehaviorSubject<String> = BehaviorSubject.create() /** * Subject to notify the library's viewpager for updates. */ val libraryMangaSubject: BehaviorSubject<LibraryMangaEvent> = BehaviorSubject.create() /** * Subject to notify the UI of selection updates. */ val selectionSubject: PublishSubject<LibrarySelectionEvent> = PublishSubject.create() /** * Database. */ val db: DatabaseHelper by injectLazy() /** * Preferences. */ val preferences: PreferencesHelper by injectLazy() /** * Cover cache. */ val coverCache: CoverCache by injectLazy() /** * Source manager. */ val sourceManager: SourceManager by injectLazy() /** * Download manager. */ val downloadManager: DownloadManager by injectLazy() companion object { /** * Id of the restartable that listens for library updates. */ const val GET_LIBRARY = 1 } override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) restartableLatestCache(GET_LIBRARY, { getLibraryObservable() }, { view, pair -> view.onNextLibraryUpdate(pair.first, pair.second) }) if (savedState == null) { start(GET_LIBRARY) } } /** * Get the categories and all its manga from the database. * * @return an observable of the categories and its manga. */ fun getLibraryObservable(): Observable<Pair<List<Category>, Map<Int, List<Manga>>>> { return Observable.combineLatest(getCategoriesObservable(), getLibraryMangasObservable(), { dbCategories, libraryManga -> val categories = if (libraryManga.containsKey(0)) arrayListOf(Category.createDefault()) + dbCategories else dbCategories this.categories = categories Pair(categories, libraryManga) }) .observeOn(AndroidSchedulers.mainThread()) } /** * Get the categories from the database. * * @return an observable of the categories. */ fun getCategoriesObservable(): Observable<List<Category>> { return db.getCategories().asRxObservable() } /** * Get the manga grouped by categories. * * @return an observable containing a map with the category id as key and a list of manga as the * value. */ fun getLibraryMangasObservable(): Observable<Map<Int, List<Manga>>> { return db.getLibraryMangas().asRxObservable() .flatMap { mangas -> Observable.from(mangas) // Filter library by options .filter { filterManga(it) } .groupBy { it.category } .flatMap { group -> group.toList().map { Pair(group.key, it) } } .toMap({ it.first }, { it.second }) } } /** * Resubscribes to library if needed. */ fun subscribeLibrary() { if (isUnsubscribed(GET_LIBRARY)) { start(GET_LIBRARY) } } /** * Resubscribes to library. */ fun resubscribeLibrary() { start(GET_LIBRARY) } /** * Filters an entry of the library. * * @param manga a favorite manga from the database. * @return true if the entry is included, false otherwise. */ fun filterManga(manga: Manga): Boolean { // Filter out manga without source val source = sourceManager.get(manga.source) ?: return false val prefFilterDownloaded = preferences.filterDownloaded().getOrDefault() val prefFilterUnread = preferences.filterUnread().getOrDefault() // Check if filter option is selected if (prefFilterDownloaded || prefFilterUnread) { // Does it have downloaded chapters. var hasDownloaded = false var hasUnread = false if (prefFilterUnread) { // Does it have unread chapters. hasUnread = manga.unread > 0 } if (prefFilterDownloaded) { val mangaDir = downloadManager.getAbsoluteMangaDirectory(source, manga) if (mangaDir.exists()) { for (file in mangaDir.listFiles()) { if (file.isDirectory && file.listFiles().isNotEmpty()) { hasDownloaded = true break } } } } // Return correct filter status if (prefFilterDownloaded && prefFilterUnread) { return (hasDownloaded && hasUnread) } else { return (hasDownloaded || hasUnread) } } else { return true } } /** * Called when a manga is opened. */ fun onOpenManga() { // Avoid further db updates for the library when it's not needed stop(GET_LIBRARY) } /** * Sets the selection for a given manga. * * @param manga the manga whose selection has changed. * @param selected whether it's now selected or not. */ fun setSelection(manga: Manga, selected: Boolean) { if (selected) { selectedMangas.add(manga) selectionSubject.onNext(LibrarySelectionEvent.Selected(manga)) } else { selectedMangas.remove(manga) selectionSubject.onNext(LibrarySelectionEvent.Unselected(manga)) } } /** * Clears all the manga selections and notifies the UI. */ fun clearSelections() { selectedMangas.clear() selectionSubject.onNext(LibrarySelectionEvent.Cleared()) } /** * Returns the common categories for the given list of manga. * * @param mangas the list of manga. */ fun getCommonCategories(mangas: List<Manga>): Collection<Category> = mangas.toSet() .map { db.getCategoriesForManga(it).executeAsBlocking() } .reduce { set1: Iterable<Category>, set2 -> set1.intersect(set2) } /** * Remove the selected manga from the library. */ fun removeMangaFromLibrary() { // Create a set of the list val mangaToDelete = selectedMangas.toSet() Observable.from(mangaToDelete) .subscribeOn(Schedulers.io()) .doOnNext { it.favorite = false coverCache.deleteFromCache(it.thumbnail_url) } .toList() .flatMap { db.insertMangas(it).asRxObservable() } .subscribe() } /** * Move the given list of manga to categories. * * @param categories the selected categories. * @param mangas the list of manga to move. */ fun moveMangasToCategories(categories: List<Category>, mangas: List<Manga>) { val mc = ArrayList<MangaCategory>() for (manga in mangas) { for (cat in categories) { mc.add(MangaCategory.create(manga, cat)) } } db.setMangaCategories(mc, mangas) } /** * Update cover with local file. * * @param inputStream the new cover. * @param manga the manga edited. * @return true if the cover is updated, false otherwise */ @Throws(IOException::class) fun editCoverWithStream(inputStream: InputStream, manga: Manga): Boolean { if (manga.thumbnail_url != null && manga.favorite) { coverCache.copyToCache(manga.thumbnail_url!!, inputStream) return true } return false } /** * Changes the active display mode. */ fun swapDisplayMode() { val displayAsList = preferences.libraryAsList().getOrDefault() preferences.libraryAsList().set(!displayAsList) } }
gpl-3.0
0cf6c41d584f1b812100ea97d1f721b9
29.083333
100
0.592691
4.99787
false
false
false
false
siosio/intellij-community
plugins/git4idea/src/git4idea/index/GitStageDiffUtil.kt
1
16048
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index import com.intellij.diff.DiffContentFactory import com.intellij.diff.DiffContentFactoryEx import com.intellij.diff.DiffRequestFactoryImpl import com.intellij.diff.chains.DiffRequestProducerException import com.intellij.diff.contents.DiffContent import com.intellij.diff.contents.DocumentContent import com.intellij.diff.requests.DiffRequest import com.intellij.diff.requests.SimpleDiffRequest import com.intellij.diff.util.DiffUserDataKeys import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.openapi.util.UserDataHolder import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.FileStatus import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.changes.* import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer import com.intellij.openapi.vcs.changes.actions.diff.UnversionedDiffRequestProducer import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.impl.ContentRevisionCache import com.intellij.openapi.vcs.merge.MergeUtils.putRevisionInfos import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcsUtil.VcsFileUtil import git4idea.GitContentRevision import git4idea.GitRevisionNumber import git4idea.GitUtil import git4idea.i18n.GitBundle import git4idea.index.KindTag.Companion.getTag import git4idea.index.ui.GitFileStatusNode import git4idea.index.ui.NodeKind import git4idea.index.vfs.GitIndexFileSystemRefresher import git4idea.index.vfs.GitIndexVirtualFile import git4idea.merge.GitMergeUtil import git4idea.repo.GitRepositoryManager import git4idea.util.GitFileUtils import org.jetbrains.annotations.Nls import java.io.IOException fun createTwoSidesDiffRequestProducer(project: Project, statusNode: GitFileStatusNode): ChangeDiffRequestChain.Producer? { return when (statusNode.kind) { NodeKind.STAGED -> StagedProducer(project, statusNode) NodeKind.UNSTAGED -> UnStagedProducer(project, statusNode) NodeKind.CONFLICTED -> MergedProducer(project, statusNode) NodeKind.UNTRACKED -> UnversionedDiffRequestProducer.create(project, statusNode.filePath, getTag(NodeKind.UNSTAGED)) NodeKind.IGNORED -> null } } fun createThreeSidesDiffRequestProducer(project: Project, statusNode: GitFileStatusNode): ChangeDiffRequestChain.Producer? { val hasThreeSides = statusNode.has(ContentVersion.HEAD) && statusNode.has(ContentVersion.STAGED) && statusNode.has(ContentVersion.LOCAL) return when (statusNode.kind) { NodeKind.STAGED -> if (hasThreeSides) ThreeSidesProducer(project, statusNode) else StagedProducer(project, statusNode) NodeKind.UNSTAGED -> if (hasThreeSides) ThreeSidesProducer(project, statusNode) else UnStagedProducer(project, statusNode) NodeKind.CONFLICTED -> MergedProducer(project, statusNode) NodeKind.UNTRACKED -> UnversionedDiffRequestProducer.create(project, statusNode.filePath, getTag(NodeKind.UNSTAGED)) NodeKind.IGNORED -> null } } fun createChange(project: Project, root: VirtualFile, status: GitFileStatus, beforeVersion: ContentVersion, afterVersion: ContentVersion): Change? { val bRev = createContentRevision(project, root, status, beforeVersion) val aRev = createContentRevision(project, root, status, afterVersion) return if (bRev != null || aRev != null) Change(bRev, aRev) else null } private fun createContentRevision(project: Project, root: VirtualFile, status: GitFileStatus, version: ContentVersion): ContentRevision? { if (!status.has(version)) return null return when (version) { ContentVersion.HEAD -> HeadContentRevision(project, root, status) ContentVersion.STAGED -> StagedContentRevision(project, root, status) ContentVersion.LOCAL -> CurrentContentRevision(status.path(version)) } } @Throws(VcsException::class, IOException::class) private fun headDiffContent(project: Project, root: VirtualFile, status: GitFileStatus): DiffContent { if (!status.has(ContentVersion.HEAD)) return DiffContentFactory.getInstance().createEmpty() val submodule = GitContentRevision.getRepositoryIfSubmodule(project, status.path) if (submodule != null) { val hash = GitIndexUtil.loadSubmoduleHashAt(submodule.repository, submodule.parent, GitRevisionNumber.HEAD) ?: throw VcsException(DiffBundle.message("error.cant.show.diff.cant.load.revision.content")) return DiffContentFactory.getInstance().create(project, hash.asString()) } val headContent = headContentBytes(project, root, status) return DiffContentFactoryEx.getInstanceEx().createFromBytes(project, headContent, status.path) } @Throws(VcsException::class) private fun stagedDiffContent(project: Project, root: VirtualFile, status: GitFileStatus): DiffContent { if (!status.has(ContentVersion.STAGED)) return DiffContentFactory.getInstance().createEmpty() val submodule = GitContentRevision.getRepositoryIfSubmodule(project, status.path) if (submodule != null) { val hash = GitIndexUtil.loadStagedSubmoduleHash(submodule.repository, submodule.parent) return DiffContentFactory.getInstance().create(project, hash.asString()) } val indexFile = stagedContentFile(project, root, status) return DiffContentFactory.getInstance().create(project, indexFile) } @Throws(VcsException::class) private fun localDiffContent(project: Project, status: GitFileStatus): DiffContent { if (!status.has(ContentVersion.LOCAL)) return DiffContentFactory.getInstance().createEmpty() val submodule = GitContentRevision.getRepositoryIfSubmodule(project, status.path) if (submodule != null) { val revision = submodule.repository.currentRevision ?: throw VcsException(DiffBundle.message("error.cant.show.diff.cant.load.revision.content")) return DiffContentFactory.getInstance().create(project, revision) } val localFile: VirtualFile = status.path(ContentVersion.LOCAL).virtualFile ?: throw VcsException(GitBundle.message("stage.diff.local.content.exception.message", status.path)) return DiffContentFactory.getInstance().create(project, localFile) } @Throws(VcsException::class) private fun headContentBytes(project: Project, root: VirtualFile, status: GitFileStatus): ByteArray { val filePath = status.path(ContentVersion.HEAD) return GitFileUtils.getFileContent(project, root, GitUtil.HEAD, VcsFileUtil.relativePath(root, filePath)) } @Throws(VcsException::class) private fun stagedContentFile(project: Project, root: VirtualFile, status: GitFileStatus): VirtualFile { val filePath = status.path(ContentVersion.STAGED) return GitIndexFileSystemRefresher.getInstance(project).getFile(root, filePath) ?: throw VcsException(GitBundle.message("stage.diff.staged.content.exception.message", status.path)) } fun compareHeadWithStaged(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest { return StagedDiffRequest(headDiffContent(project, root, status), stagedDiffContent(project, root, status), GitUtil.HEAD, GitBundle.message("stage.content.staged"), getTitle(status, NodeKind.STAGED)).apply { putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_LEFT_ACTION_TEXT, GitBundle.message("action.label.reset.staged.range")) } } fun compareStagedWithLocal(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest { return StagedDiffRequest(stagedDiffContent(project, root, status), localDiffContent(project, status), GitBundle.message("stage.content.staged"), GitBundle.message("stage.content.local"), getTitle(status, NodeKind.UNSTAGED)).apply { putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_RIGHT_ACTION_TEXT, GitBundle.message("action.label.add.unstaged.range")) putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_LEFT_ACTION_TEXT, DiffBundle.message("action.presentation.diff.revert.text")) } } fun compareThreeVersions(project: Project, root: VirtualFile, status: GitFileStatus): DiffRequest { val title = getTitle(status) return StagedDiffRequest(headDiffContent(project, root, status), stagedDiffContent(project, root, status), localDiffContent(project, status), GitUtil.HEAD, GitBundle.message("stage.content.staged"), GitBundle.message("stage.content.local"), title).apply { putUserData(DiffUserDataKeys.THREESIDE_DIFF_COLORS_MODE, DiffUserDataKeys.ThreeSideDiffColors.LEFT_TO_RIGHT) putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_RIGHT_TO_BASE_ACTION_TEXT, GitBundle.message("action.label.add.unstaged.range")) putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_BASE_TO_RIGHT_ACTION_TEXT, DiffBundle.message("action.presentation.diff.revert.text")) putUserData(DiffUserDataKeysEx.VCS_DIFF_ACCEPT_LEFT_TO_BASE_ACTION_TEXT, GitBundle.message("action.label.reset.staged.range")) } } private class UnStagedProducer constructor(private val project: Project, file: GitFileStatusNode) : GitFileStatusNodeProducerBase(file) { @Throws(VcsException::class) override fun processImpl(): DiffRequest { return compareStagedWithLocal(project, statusNode.root, statusNode.status) } } private class StagedProducer constructor(private val project: Project, file: GitFileStatusNode) : GitFileStatusNodeProducerBase(file) { @Throws(VcsException::class, IOException::class) override fun processImpl(): DiffRequest { return compareHeadWithStaged(project, statusNode.root, statusNode.status) } } class ThreeSidesProducer(private val project: Project, statusNode: GitFileStatusNode) : GitFileStatusNodeProducerBase(statusNode) { @Throws(VcsException::class, IOException::class) override fun processImpl(): DiffRequest { return compareThreeVersions(project, statusNode.root, statusNode.status) } } class MergedProducer(private val project: Project, statusNode: GitFileStatusNode) : GitFileStatusNodeProducerBase(statusNode) { @Throws(VcsException::class, IOException::class) override fun processImpl(): DiffRequest { val repository = GitRepositoryManager.getInstance(project).getRepositoryForRoot(statusNode.root) val mergeData = GitMergeUtil.loadMergeData(project, statusNode.root, statusNode.filePath, repository?.let { GitMergeUtil.isReverseRoot(it) } ?: false) val title = getTitle(statusNode.status, statusNode.kind) val titles = listOf(ChangeDiffRequestProducer.getYourVersion(), ChangeDiffRequestProducer.getBaseVersion(), ChangeDiffRequestProducer.getServerVersion()) val contents = listOf(mergeData.CURRENT, mergeData.ORIGINAL, mergeData.LAST).map { DiffContentFactory.getInstance().createFromBytes(project, it, statusNode.filePath) } val request = SimpleDiffRequest(title, contents, titles) putRevisionInfos(request, mergeData) return request } } private class StagedDiffRequest(contents: List<DiffContent>, titles: List<String>, @Nls title: String? = null) : SimpleDiffRequest(title, contents, titles) { constructor(content1: DiffContent, content2: DiffContent, @Nls title1: String, @Nls title2: String, @Nls title: String? = null) : this(listOf(content1, content2), listOf(title1, title2), title) constructor(content1: DiffContent, content2: DiffContent, content3: DiffContent, @Nls title1: String, @Nls title2: String, @Nls title3: String, @Nls title: String? = null) : this(listOf(content1, content2, content3), listOf(title1, title2, title3), title) override fun onAssigned(isAssigned: Boolean) { super.onAssigned(isAssigned) if (!isAssigned) { for (content in contents) { if (content is DocumentContent) { val file = FileDocumentManager.getInstance().getFile(content.document) if (file is GitIndexVirtualFile) { FileDocumentManager.getInstance().saveDocument(content.document) } } } } } } abstract class GitFileStatusNodeProducerBase(val statusNode: GitFileStatusNode) : ChangeDiffRequestChain.Producer { private val kind = statusNode.kind @Throws(VcsException::class, IOException::class) abstract fun processImpl(): DiffRequest @Throws(DiffRequestProducerException::class) override fun process(context: UserDataHolder, indicator: ProgressIndicator): DiffRequest { try { return processImpl() } catch (e: VcsException) { throw DiffRequestProducerException(e) } catch (e: IOException) { throw DiffRequestProducerException(e) } } override fun getFilePath(): FilePath { return statusNode.filePath } override fun getFileStatus(): FileStatus { return statusNode.fileStatus } override fun getName(): String { return statusNode.filePath.presentableUrl } override fun getTag(): ChangesBrowserNode.Tag? { return getTag(kind) } override fun equals(o: Any?): Boolean { if (this === o) return true if (o == null || javaClass != o.javaClass) return false val wrapper = o as GitFileStatusNodeProducerBase return statusNode == wrapper.statusNode } override fun hashCode(): Int { return statusNode.hashCode() } } private class HeadContentRevision(val project: Project, val root: VirtualFile, val status: GitFileStatus) : ByteBackedContentRevision { override fun getFile(): FilePath = status.path(ContentVersion.HEAD) override fun getRevisionNumber(): VcsRevisionNumber = TextRevisionNumber(GitUtil.HEAD) override fun getContent(): String? = ContentRevisionCache.getAsString(contentAsBytes, file, null) @Throws(VcsException::class) override fun getContentAsBytes(): ByteArray = headContentBytes(project, root, status) } private class StagedContentRevision(val project: Project, val root: VirtualFile, val status: GitFileStatus) : ByteBackedContentRevision { override fun getFile(): FilePath = status.path(ContentVersion.STAGED) override fun getRevisionNumber(): VcsRevisionNumber = TextRevisionNumber(GitBundle.message("stage.content.staged")) override fun getContent(): String? = ContentRevisionCache.getAsString(contentAsBytes, file, null) @Throws(VcsException::class) override fun getContentAsBytes(): ByteArray = stagedContentFile(project, root, status).contentsToByteArray() } private class KindTag(private val kind: NodeKind) : ChangesBrowserNode.Tag { override fun toString(): String = GitBundle.message(kind.key) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as KindTag if (kind != other.kind) return false return true } override fun hashCode(): Int { return kind.hashCode() } companion object { private val tags = NodeKind.values().associateWith { KindTag(it) } internal fun getTag(nodeKind: NodeKind) = tags[nodeKind]!! } } private fun GitFileStatusNode.has(contentVersion: ContentVersion): Boolean = status.has(contentVersion) @Nls private fun getTitle(status: GitFileStatus, kind: NodeKind): String { return DiffRequestFactoryImpl.getTitle(status.path, kind.origPath(status), DiffRequestFactoryImpl.DIFF_TITLE_RENAME_SEPARATOR) } @Nls private fun getTitle(status: GitFileStatus): String { return DiffRequestFactoryImpl.getTitle(status.path, status.origPath, DiffRequestFactoryImpl.DIFF_TITLE_RENAME_SEPARATOR) }
apache-2.0
a1a3e7a6a114f7a318c2e1aee9a7f05d
44.985673
140
0.75916
4.699268
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveClassesOrPackages/KotlinAwareDelegatingMoveDestination.kt
2
4061
// 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.move.moveClassesOrPackages import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiPackage import com.intellij.psi.PsiRecursiveElementWalkingVisitor import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.MoveDestination import com.intellij.usageView.UsageInfo import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.move.createMoveUsageInfoIfPossible import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.analyzeConflictsInFile import org.jetbrains.kotlin.idea.search.projectScope import org.jetbrains.kotlin.idea.stubindex.KotlinExactPackagesIndex import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf class KotlinAwareDelegatingMoveDestination( private val delegate: MoveDestination, private val targetPackage: PsiPackage?, private val targetDirectory: PsiDirectory? ) : MoveDestination by delegate { override fun analyzeModuleConflicts( elements: Collection<PsiElement>, conflicts: MultiMap<PsiElement, String>, usages: Array<out UsageInfo> ) { delegate.analyzeModuleConflicts(elements, conflicts, usages) if (targetPackage == null || targetDirectory == null) return val project = targetDirectory.project val moveTarget = KotlinDirectoryMoveTarget(FqName(targetPackage.qualifiedName), targetDirectory.virtualFile) val packagesIndex = KotlinExactPackagesIndex.getInstance() val directoriesToMove = elements.flatMapTo(LinkedHashSet<PsiDirectory>()) { (it as? PsiPackage)?.directories?.toList() ?: emptyList() } val projectScope = project.projectScope() val filesToProcess = elements.flatMapTo(LinkedHashSet<KtFile>()) { if (it is PsiPackage) packagesIndex[it.qualifiedName, project, projectScope] else emptyList() } val extraElementsForReferenceSearch = LinkedHashSet<PsiElement>() val extraElementCollector = object : PsiRecursiveElementWalkingVisitor() { override fun visitElement(element: PsiElement) { if (element is KtNamedDeclaration && element.hasModifier(KtTokens.INTERNAL_KEYWORD)) { element.parentsWithSelf.lastOrNull { it is KtNamedDeclaration }?.let { extraElementsForReferenceSearch += it } stopWalking() } super.visitElement(element) } } filesToProcess.flatMap { it.declarations }.forEach { it.accept(extraElementCollector) } val progressIndicator = ProgressManager.getInstance().progressIndicator!! progressIndicator.pushState() val extraUsages = ArrayList<UsageInfo>() try { progressIndicator.text = KotlinBundle.message("text.looking.for.usages") for ((index, element) in extraElementsForReferenceSearch.withIndex()) { progressIndicator.fraction = (index + 1) / extraElementsForReferenceSearch.size.toDouble() ReferencesSearch.search(element, projectScope).mapNotNullTo(extraUsages) { ref -> createMoveUsageInfoIfPossible(ref, element, addImportToOriginalFile = true, isInternal = false) } } } finally { progressIndicator.popState() } filesToProcess.forEach { analyzeConflictsInFile(it, extraUsages, moveTarget, directoriesToMove, conflicts) {} } } }
apache-2.0
371a98114a3fc1b72f51590121305834
47.939759
158
0.731101
5.199744
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/ImportFix.kt
5
1929
// 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.quickfix import com.intellij.codeInspection.HintAction import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtSimpleNameExpression internal open class ImportFix(expression: KtSimpleNameExpression) : AbstractImportFix(expression, MyFactory) { override fun elementsToCheckDiagnostics(): Collection<PsiElement> { val expression = element ?: return emptyList() return listOfNotNull(expression, expression.parent?.takeIf { it is KtCallExpression }) } companion object MyFactory : Factory() { override fun createImportAction(diagnostic: Diagnostic): ImportFix? { val simpleNameExpression = when (val element = diagnostic.psiElement) { is KtSimpleNameExpression -> element is KtCallExpression -> element.calleeExpression else -> null } as? KtSimpleNameExpression ?: return null val hintsEnabled = AbstractImportFixInfo.isHintsEnabled(diagnostic.psiFile) return if (hintsEnabled) ImportFixWithHint(simpleNameExpression) else ImportFix(simpleNameExpression) } } } internal class ImportFixWithHint(expression: KtSimpleNameExpression): ImportFix(expression), HintAction { override fun fixSilently(editor: Editor): Boolean { if (isOutdated()) return false val element = element ?: return false val project = element.project val addImportAction = createActionWithAutoImportsFilter(project, editor, element) return if (addImportAction.isUnambiguous()) { addImportAction.execute() true } else false } }
apache-2.0
8cea033daf8ef341e1f4fcf1428943f4
43.860465
120
0.724209
5.199461
false
false
false
false
nrizzio/Signal-Android
image-editor/lib/src/main/java/org/signal/imageeditor/core/renderers/TrashRenderer.kt
2
4308
package org.signal.imageeditor.core.renderers import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.graphics.drawable.Drawable import android.os.Parcel import android.os.Parcelable import android.view.animation.Interpolator import androidx.appcompat.content.res.AppCompatResources import androidx.interpolator.view.animation.FastOutSlowInInterpolator import org.signal.core.util.DimensionUnit import org.signal.imageeditor.R import org.signal.imageeditor.core.Bounds import org.signal.imageeditor.core.Renderer import org.signal.imageeditor.core.RendererContext internal class TrashRenderer : InvalidateableRenderer, Renderer, Parcelable { private val outlinePaint = Paint().apply { isAntiAlias = true color = Color.WHITE style = Paint.Style.STROKE strokeWidth = DimensionUnit.DP.toPixels(1.5f) } private val shadePaint = Paint().apply { isAntiAlias = true color = 0x99000000.toInt() style = Paint.Style.FILL } private val bounds = RectF() private val diameterSmall = DimensionUnit.DP.toPixels(41f) private val diameterLarge = DimensionUnit.DP.toPixels(54f) private val trashSize: Int = DimensionUnit.DP.toPixels(24f).toInt() private val padBottom = DimensionUnit.DP.toPixels(16f) private val interpolator: Interpolator = FastOutSlowInInterpolator() private var startTime = 0L private var isExpanding = false private val buttonCenter = FloatArray(2) constructor() override fun render(rendererContext: RendererContext) { super.render(rendererContext) val frameRenderTime = System.currentTimeMillis() val trash: Drawable = requireNotNull(AppCompatResources.getDrawable(rendererContext.context, R.drawable.ic_trash_white_24)) trash.setBounds(0, 0, trashSize, trashSize) val diameter = getInterpolatedDiameter(frameRenderTime - startTime) rendererContext.canvas.save() rendererContext.mapRect(bounds, Bounds.FULL_BOUNDS) buttonCenter[0] = bounds.centerX() buttonCenter[1] = bounds.bottom - diameterLarge / 2f - padBottom rendererContext.canvasMatrix.setToIdentity() rendererContext.canvas.drawCircle(buttonCenter[0], buttonCenter[1], diameter / 2f, shadePaint) rendererContext.canvas.drawCircle(buttonCenter[0], buttonCenter[1], diameter / 2f, outlinePaint) rendererContext.canvas.translate(bounds.centerX(), bounds.bottom - diameterLarge / 2f - padBottom) rendererContext.canvas.translate(- (trashSize / 2f), - (trashSize / 2f)) trash.draw(rendererContext.canvas) rendererContext.canvas.restore() if (frameRenderTime - DURATION < startTime) { invalidate() } } private fun getInterpolatedDiameter(timeElapsed: Long): Float { return if (timeElapsed >= DURATION) { if (isExpanding) { diameterLarge } else { diameterSmall } } else { val interpolatedFraction = interpolator.getInterpolation(timeElapsed / DURATION.toFloat()) if (isExpanding) { interpolateFromFraction(interpolatedFraction) } else { interpolateFromFraction(1 - interpolatedFraction) } } } private fun interpolateFromFraction(fraction: Float): Float { return diameterSmall + (diameterLarge - diameterSmall) * fraction } fun expand() { if (isExpanding) { return } isExpanding = true startTime = System.currentTimeMillis() invalidate() } fun shrink() { if (!isExpanding) { return } isExpanding = false startTime = System.currentTimeMillis() invalidate() } override fun hitTest(x: Float, y: Float): Boolean { val dx = x - buttonCenter[0] val dy = y - buttonCenter[1] val radius = diameterLarge / 2 return dx * dx + dy * dy < radius * radius } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) {} companion object { private const val DURATION = 150L @JvmField val CREATOR: Parcelable.Creator<TrashRenderer> = object : Parcelable.Creator<TrashRenderer> { override fun createFromParcel(`in`: Parcel): TrashRenderer { return TrashRenderer() } override fun newArray(size: Int): Array<TrashRenderer?> { return arrayOfNulls(size) } } } }
gpl-3.0
a1d987c9c2ed61192cebf9eafef48743
27.912752
127
0.719824
4.308
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/androidMain/kotlin/androidx/compose/foundation/text/selection/AndroidSelectionHandles.android.kt
3
11329
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text.selection import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.Handle import androidx.compose.foundation.text.selection.HandleReferencePoint.TopLeft import androidx.compose.foundation.text.selection.HandleReferencePoint.TopMiddle import androidx.compose.foundation.text.selection.HandleReferencePoint.TopRight import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.draw.CacheDrawScope import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.BlendMode import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.ImageBitmapConfig import androidx.compose.ui.graphics.drawscope.CanvasDrawScope import androidx.compose.ui.graphics.drawscope.scale import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.ResolvedTextDirection import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.window.Popup import androidx.compose.ui.window.PopupPositionProvider import androidx.compose.ui.window.PopupProperties import kotlin.math.ceil import kotlin.math.roundToInt @Composable internal actual fun SelectionHandle( position: Offset, isStartHandle: Boolean, direction: ResolvedTextDirection, handlesCrossed: Boolean, modifier: Modifier, content: @Composable (() -> Unit)? ) { val isLeft = isLeft(isStartHandle, direction, handlesCrossed) // The left selection handle's top right is placed at the given position, and vice versa. val handleReferencePoint = if (isLeft) { HandleReferencePoint.TopRight } else { HandleReferencePoint.TopLeft } HandlePopup(position = position, handleReferencePoint = handleReferencePoint) { if (content == null) { DefaultSelectionHandle( modifier = modifier .semantics { this[SelectionHandleInfoKey] = SelectionHandleInfo( handle = if (isStartHandle) { Handle.SelectionStart } else { Handle.SelectionEnd }, position = position ) }, isStartHandle = isStartHandle, direction = direction, handlesCrossed = handlesCrossed ) } else { content() } } } @Composable /*@VisibleForTesting*/ internal fun DefaultSelectionHandle( modifier: Modifier, isStartHandle: Boolean, direction: ResolvedTextDirection, handlesCrossed: Boolean ) { Spacer( modifier.size(HandleWidth, HandleHeight) .drawSelectionHandle(isStartHandle, direction, handlesCrossed) ) } @Suppress("ModifierInspectorInfo") internal fun Modifier.drawSelectionHandle( isStartHandle: Boolean, direction: ResolvedTextDirection, handlesCrossed: Boolean ) = composed { val handleColor = LocalTextSelectionColors.current.handleColor this.then( Modifier.drawWithCache { val radius = size.width / 2f val handleImage = createHandleImage(radius) val colorFilter = ColorFilter.tint(handleColor) onDrawWithContent { drawContent() val isLeft = isLeft(isStartHandle, direction, handlesCrossed) if (isLeft) { // Flip the selection handle horizontally. scale(scaleX = -1f, scaleY = 1f) { drawImage( image = handleImage, colorFilter = colorFilter ) } } else { drawImage( image = handleImage, colorFilter = colorFilter ) } } } ) } /** * The cache for the image mask created to draw selection/cursor handle, so that we don't need to * recreate them. */ private object HandleImageCache { var imageBitmap: ImageBitmap? = null var canvas: Canvas? = null var canvasDrawScope: CanvasDrawScope? = null } /** * Create an image bitmap for the basic shape of a selection handle or cursor handle. It is an * circle with a rectangle covering its left top part. * * To draw the right selection handle, directly draw this image bitmap. * To draw the left selection handle, mirror the canvas first and then draw this image bitmap. * To draw the cursor handle, translate and rotated the canvas 45 degrees, then draw this image * bitmap. * * @param radius the radius of circle in selection/cursor handle. * CanvasDrawScope objects so that we only recreate them when necessary. */ internal fun CacheDrawScope.createHandleImage(radius: Float): ImageBitmap { // The edge length of the square bounding box of the selection/cursor handle. This is also // the size of the bitmap needed for the bitmap mask. val edge = ceil(radius).toInt() * 2 var imageBitmap = HandleImageCache.imageBitmap var canvas = HandleImageCache.canvas var drawScope = HandleImageCache.canvasDrawScope // If the cached bitmap is null or too small, we need to create new bitmap. if ( imageBitmap == null || canvas == null || edge > imageBitmap.width || edge > imageBitmap.height ) { imageBitmap = ImageBitmap( width = edge, height = edge, config = ImageBitmapConfig.Alpha8 ) HandleImageCache.imageBitmap = imageBitmap canvas = Canvas(imageBitmap) HandleImageCache.canvas = canvas } if (drawScope == null) { drawScope = CanvasDrawScope() HandleImageCache.canvasDrawScope = drawScope } drawScope.draw( this, layoutDirection, canvas, Size(imageBitmap.width.toFloat(), imageBitmap.height.toFloat()) ) { // Clear the previously rendered portion within this ImageBitmap as we could // be re-using it drawRect( color = Color.Black, size = size, blendMode = BlendMode.Clear ) // Draw the rectangle at top left. drawRect( color = Color(0xFF000000), topLeft = Offset.Zero, size = Size(radius, radius) ) // Draw the circle drawCircle( color = Color(0xFF000000), radius = radius, center = Offset(radius, radius) ) } return imageBitmap } @Composable internal fun HandlePopup( position: Offset, handleReferencePoint: HandleReferencePoint, content: @Composable () -> Unit ) { val intOffset = IntOffset(position.x.roundToInt(), position.y.roundToInt()) val popupPositioner = remember(handleReferencePoint, intOffset) { HandlePositionProvider(handleReferencePoint, intOffset) } Popup( popupPositionProvider = popupPositioner, properties = PopupProperties( excludeFromSystemGesture = true, clippingEnabled = false ), content = content ) } /** * The enum that specifies how a selection/cursor handle is placed to its given position. * When this value is [TopLeft], the top left corner of the handle will be placed at the * given position. * When this value is [TopRight], the top right corner of the handle will be placed at the * given position. * When this value is [TopMiddle], the handle top edge's middle point will be placed at the given * position. */ internal enum class HandleReferencePoint { TopLeft, TopRight, TopMiddle } /** * This [PopupPositionProvider] for [HandlePopup]. It will position the selection handle * to the [offset] in its anchor layout. * * @see HandleReferencePoint */ /*@VisibleForTesting*/ internal class HandlePositionProvider( private val handleReferencePoint: HandleReferencePoint, private val offset: IntOffset ) : PopupPositionProvider { override fun calculatePosition( anchorBounds: IntRect, windowSize: IntSize, layoutDirection: LayoutDirection, popupContentSize: IntSize ): IntOffset { return when (handleReferencePoint) { HandleReferencePoint.TopLeft -> IntOffset( x = anchorBounds.left + offset.x, y = anchorBounds.top + offset.y ) HandleReferencePoint.TopRight -> IntOffset( x = anchorBounds.left + offset.x - popupContentSize.width, y = anchorBounds.top + offset.y ) HandleReferencePoint.TopMiddle -> IntOffset( x = anchorBounds.left + offset.x - popupContentSize.width / 2, y = anchorBounds.top + offset.y ) } } } /** * Computes whether the handle's appearance should be left-pointing or right-pointing. */ private fun isLeft( isStartHandle: Boolean, direction: ResolvedTextDirection, handlesCrossed: Boolean ): Boolean { return if (isStartHandle) { isHandleLtrDirection(direction, handlesCrossed) } else { !isHandleLtrDirection(direction, handlesCrossed) } } /** * This method is to check if the selection handles should use the natural Ltr pointing * direction. * If the context is Ltr and the handles are not crossed, or if the context is Rtl and the handles * are crossed, return true. * * In Ltr context, the start handle should point to the left, and the end handle should point to * the right. However, in Rtl context or when handles are crossed, the start handle should point to * the right, and the end handle should point to left. */ /*@VisibleForTesting*/ internal fun isHandleLtrDirection( direction: ResolvedTextDirection, areHandlesCrossed: Boolean ): Boolean { return direction == ResolvedTextDirection.Ltr && !areHandlesCrossed || direction == ResolvedTextDirection.Rtl && areHandlesCrossed }
apache-2.0
6b8c5610d431d7de0fc8a874800c3107
33.330303
99
0.659723
4.862232
false
false
false
false
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/descriptor/IdentifierDescriptor.kt
1
705
package com.onyx.descriptor import com.onyx.extension.common.ClassMetadata import com.onyx.persistence.annotations.values.IdentifierGenerator /** * Created by timothy.osborn on 12/11/14. * * General information about a key identifier for an entity */ data class IdentifierDescriptor( var generator: IdentifierGenerator = IdentifierGenerator.NONE, override var name: String = "", override var type: Class<*> = ClassMetadata.ANY_CLASS ) : IndexDescriptor(),BaseDescriptor { override fun hashCode(): Int = super.hashCode() + generator.hashCode() override fun equals(other: Any?): Boolean = super.equals(other) && (other as IdentifierDescriptor).generator == generator }
agpl-3.0
1eecf2476de8d8a59833f79582c60cdf
38.166667
125
0.740426
4.462025
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/declarations.kt
2
10442
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.tree import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitor import org.jetbrains.kotlin.nj2k.types.JKNoType abstract class JKDeclaration : JKTreeElement(), PsiOwner by PsiOwnerImpl() { abstract val name: JKNameIdentifier } class JKClass( name: JKNameIdentifier, inheritance: JKInheritanceInfo, var classKind: ClassKind, typeParameterList: JKTypeParameterList, classBody: JKClassBody, annotationList: JKAnnotationList, otherModifierElements: List<JKOtherModifierElement>, visibilityElement: JKVisibilityModifierElement, modalityElement: JKModalityModifierElement, recordComponents: List<JKJavaRecordComponent> = emptyList() ) : JKDeclaration(), JKVisibilityOwner, JKOtherModifiersOwner, JKModalityOwner, JKTypeParameterListOwner, JKAnnotationListOwner { override fun accept(visitor: JKVisitor) = visitor.visitClass(this) override var name by child(name) val inheritance by child(inheritance) override var typeParameterList: JKTypeParameterList by child(typeParameterList) var classBody: JKClassBody by child(classBody) override var annotationList: JKAnnotationList by child(annotationList) override var otherModifierElements by children(otherModifierElements) override var visibilityElement by child(visibilityElement) override var modalityElement by child(modalityElement) var recordComponents: List<JKJavaRecordComponent> by children(recordComponents) enum class ClassKind(val text: String) { ANNOTATION("annotation class"), CLASS("class"), ENUM("enum class"), INTERFACE("interface"), OBJECT("object"), COMPANION("companion object"), RECORD("data class") } } abstract class JKVariable : JKDeclaration(), JKAnnotationListOwner { abstract var type: JKTypeElement abstract var initializer: JKExpression } class JKLocalVariable( type: JKTypeElement, name: JKNameIdentifier, initializer: JKExpression, mutabilityElement: JKMutabilityModifierElement, annotationList: JKAnnotationList = JKAnnotationList() ) : JKVariable(), JKMutabilityOwner { override var initializer by child(initializer) override var name by child(name) override var type by child(type) override var annotationList by child(annotationList) override var mutabilityElement by child(mutabilityElement) override fun accept(visitor: JKVisitor) = visitor.visitLocalVariable(this) } class JKForLoopVariable( type: JKTypeElement, name: JKNameIdentifier, initializer: JKExpression, annotationList: JKAnnotationList = JKAnnotationList() ) : JKVariable() { override var initializer by child(initializer) override var name by child(name) override var type by child(type) override var annotationList by child(annotationList) override fun accept(visitor: JKVisitor) = visitor.visitForLoopVariable(this) } open class JKParameter( type: JKTypeElement, name: JKNameIdentifier, var isVarArgs: Boolean = false, initializer: JKExpression = JKStubExpression(), annotationList: JKAnnotationList = JKAnnotationList() ) : JKVariable(), JKModifiersListOwner { override var initializer by child(initializer) override var name by child(name) override var type by child(type) override var annotationList by child(annotationList) override fun accept(visitor: JKVisitor) = visitor.visitParameter(this) } class JKJavaRecordComponent( type: JKTypeElement, name: JKNameIdentifier, isVarArgs: Boolean, annotationList: JKAnnotationList ) : JKParameter(type, name, isVarArgs, annotationList = annotationList) class JKEnumConstant( name: JKNameIdentifier, arguments: JKArgumentList, body: JKClassBody, type: JKTypeElement, annotationList: JKAnnotationList = JKAnnotationList() ) : JKVariable() { override var name: JKNameIdentifier by child(name) val arguments: JKArgumentList by child(arguments) val body: JKClassBody by child(body) override var type: JKTypeElement by child(type) override var initializer: JKExpression by child(JKStubExpression()) override var annotationList by child(annotationList) override fun accept(visitor: JKVisitor) = visitor.visitEnumConstant(this) } class JKTypeParameter( name: JKNameIdentifier, upperBounds: List<JKTypeElement>, annotationList: JKAnnotationList = JKAnnotationList() ) : JKDeclaration(), JKAnnotationListOwner { override var name: JKNameIdentifier by child(name) var upperBounds: List<JKTypeElement> by children(upperBounds) override var annotationList by child(annotationList) override fun accept(visitor: JKVisitor) = visitor.visitTypeParameter(this) } abstract class JKMethod : JKDeclaration(), JKVisibilityOwner, JKModalityOwner, JKOtherModifiersOwner, JKTypeParameterListOwner, JKAnnotationListOwner { abstract var parameters: List<JKParameter> abstract var returnType: JKTypeElement abstract var block: JKBlock val leftParen = JKTokenElementImpl("(") val rightParen = JKTokenElementImpl(")") } class JKMethodImpl( returnType: JKTypeElement, name: JKNameIdentifier, parameters: List<JKParameter>, block: JKBlock, typeParameterList: JKTypeParameterList, annotationList: JKAnnotationList, throwsList: List<JKTypeElement>, otherModifierElements: List<JKOtherModifierElement>, visibilityElement: JKVisibilityModifierElement, modalityElement: JKModalityModifierElement ) : JKMethod() { override fun accept(visitor: JKVisitor) = visitor.visitMethod(this) override var returnType: JKTypeElement by child(returnType) override var name: JKNameIdentifier by child(name) override var parameters: List<JKParameter> by children(parameters) override var block: JKBlock by child(block) override var typeParameterList: JKTypeParameterList by child(typeParameterList) override var annotationList: JKAnnotationList by child(annotationList) var throwsList: List<JKTypeElement> by children(throwsList) override var otherModifierElements by children(otherModifierElements) override var visibilityElement by child(visibilityElement) override var modalityElement by child(modalityElement) } abstract class JKConstructor : JKMethod() { abstract var delegationCall: JKExpression } class JKConstructorImpl( name: JKNameIdentifier, parameters: List<JKParameter>, block: JKBlock, delegationCall: JKExpression, annotationList: JKAnnotationList, otherModifierElements: List<JKOtherModifierElement>, visibilityElement: JKVisibilityModifierElement, modalityElement: JKModalityModifierElement ) : JKConstructor() { override var returnType: JKTypeElement by child(JKTypeElement(JKNoType)) override var name: JKNameIdentifier by child(name) override var parameters: List<JKParameter> by children(parameters) override var block: JKBlock by child(block) override var delegationCall: JKExpression by child(delegationCall) override var typeParameterList: JKTypeParameterList by child(JKTypeParameterList()) override var annotationList: JKAnnotationList by child(annotationList) override var otherModifierElements by children(otherModifierElements) override var visibilityElement by child(visibilityElement) override var modalityElement by child(modalityElement) override fun accept(visitor: JKVisitor) = visitor.visitConstructor(this) } class JKKtPrimaryConstructor( name: JKNameIdentifier, parameters: List<JKParameter>, delegationCall: JKExpression, annotationList: JKAnnotationList, otherModifierElements: List<JKOtherModifierElement>, visibilityElement: JKVisibilityModifierElement, modalityElement: JKModalityModifierElement ) : JKConstructor() { override var returnType: JKTypeElement by child(JKTypeElement(JKNoType)) override var name: JKNameIdentifier by child(name) override var parameters: List<JKParameter> by children(parameters) override var block: JKBlock by child(JKBodyStub) override var delegationCall: JKExpression by child(delegationCall) override var typeParameterList: JKTypeParameterList by child(JKTypeParameterList()) override var annotationList: JKAnnotationList by child(annotationList) override var otherModifierElements by children(otherModifierElements) override var visibilityElement by child(visibilityElement) override var modalityElement by child(modalityElement) override fun accept(visitor: JKVisitor) = visitor.visitKtPrimaryConstructor(this) } class JKField( type: JKTypeElement, name: JKNameIdentifier, initializer: JKExpression, annotationList: JKAnnotationList, otherModifierElements: List<JKOtherModifierElement>, visibilityElement: JKVisibilityModifierElement, modalityElement: JKModalityModifierElement, mutabilityElement: JKMutabilityModifierElement ) : JKVariable(), JKVisibilityOwner, JKMutabilityOwner, JKModalityOwner, JKOtherModifiersOwner, JKAnnotationListOwner { override var annotationList: JKAnnotationList by child(annotationList) override var initializer: JKExpression by child(initializer) override var type by child(type) override var name: JKNameIdentifier by child(name) override var otherModifierElements by children(otherModifierElements) override var visibilityElement by child(visibilityElement) override var modalityElement by child(modalityElement) override var mutabilityElement by child(mutabilityElement) override fun accept(visitor: JKVisitor) = visitor.visitField(this) } sealed class JKInitDeclaration(block: JKBlock) : JKDeclaration() { var block: JKBlock by child(block) abstract val isStatic: Boolean override val name: JKNameIdentifier by child(JKNameIdentifier("<init>")) } class JKKtInitDeclaration(block: JKBlock) : JKInitDeclaration(block) { override val isStatic: Boolean get() = false override fun accept(visitor: JKVisitor) = visitor.visitKtInitDeclaration(this) } class JKJavaStaticInitDeclaration(block: JKBlock) : JKInitDeclaration(block) { override val isStatic: Boolean get() = true override fun accept(visitor: JKVisitor) = visitor.visitJavaStaticInitDeclaration(this) }
apache-2.0
32b8619ac46c92c738a81058e42990ed
38.703422
134
0.775235
5.273737
false
false
false
false
GunoH/intellij-community
plugins/ide-features-trainer/src/training/statistic/StatisticBase.kt
2
17971
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.statistic import com.intellij.ide.TipsOfTheDayUsagesCollector.TipInfoValidationRule import com.intellij.ide.plugins.PluginManager import com.intellij.ide.ui.text.ShortcutsRenderingUtil import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.* import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.keymap.Keymap import com.intellij.openapi.keymap.KeymapManager import com.intellij.openapi.keymap.impl.DefaultKeymapImpl import com.intellij.openapi.util.BuildNumber import com.intellij.util.TimeoutUtil import training.lang.LangManager import training.learn.CourseManager import training.learn.course.IftModule import training.learn.course.Lesson import training.learn.lesson.LessonManager import training.statistic.FeatureUsageStatisticConsts.ACTION_ID import training.statistic.FeatureUsageStatisticConsts.COMPLETED_COUNT import training.statistic.FeatureUsageStatisticConsts.COURSE_SIZE import training.statistic.FeatureUsageStatisticConsts.DURATION import training.statistic.FeatureUsageStatisticConsts.EXPAND_WELCOME_PANEL import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_ENTRY_PLACE import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_EXPERIENCED_USER import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_HAS_BEEN_SENT import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_LIKENESS_ANSWER import training.statistic.FeatureUsageStatisticConsts.FEEDBACK_OPENED_VIA_NOTIFICATION import training.statistic.FeatureUsageStatisticConsts.HELP_LINK_CLICKED import training.statistic.FeatureUsageStatisticConsts.INTERNAL_PROBLEM import training.statistic.FeatureUsageStatisticConsts.KEYMAP_SCHEME import training.statistic.FeatureUsageStatisticConsts.LANGUAGE import training.statistic.FeatureUsageStatisticConsts.LAST_BUILD_LEARNING_OPENED import training.statistic.FeatureUsageStatisticConsts.LEARN_PROJECT_OPENED_FIRST_TIME import training.statistic.FeatureUsageStatisticConsts.LEARN_PROJECT_OPENING_WAY import training.statistic.FeatureUsageStatisticConsts.LESSON_ID import training.statistic.FeatureUsageStatisticConsts.LESSON_LINK_CLICKED_FROM_TIP import training.statistic.FeatureUsageStatisticConsts.LESSON_STARTING_WAY import training.statistic.FeatureUsageStatisticConsts.MODULE_NAME import training.statistic.FeatureUsageStatisticConsts.NEED_SHOW_NEW_LESSONS_NOTIFICATIONS import training.statistic.FeatureUsageStatisticConsts.NEW_LESSONS_COUNT import training.statistic.FeatureUsageStatisticConsts.NEW_LESSONS_NOTIFICATION_SHOWN import training.statistic.FeatureUsageStatisticConsts.NON_LEARNING_PROJECT_OPENED import training.statistic.FeatureUsageStatisticConsts.ONBOARDING_FEEDBACK_DIALOG_RESULT import training.statistic.FeatureUsageStatisticConsts.ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN import training.statistic.FeatureUsageStatisticConsts.PASSED import training.statistic.FeatureUsageStatisticConsts.PROBLEM import training.statistic.FeatureUsageStatisticConsts.PROGRESS import training.statistic.FeatureUsageStatisticConsts.REASON import training.statistic.FeatureUsageStatisticConsts.RESTORE import training.statistic.FeatureUsageStatisticConsts.SHORTCUT_CLICKED import training.statistic.FeatureUsageStatisticConsts.SHOULD_SHOW_NEW_LESSONS import training.statistic.FeatureUsageStatisticConsts.SHOW_NEW_LESSONS import training.statistic.FeatureUsageStatisticConsts.START import training.statistic.FeatureUsageStatisticConsts.START_MODULE_ACTION import training.statistic.FeatureUsageStatisticConsts.STOPPED import training.statistic.FeatureUsageStatisticConsts.TASK_ID import training.statistic.FeatureUsageStatisticConsts.TIP_ID import java.awt.event.KeyEvent import java.util.concurrent.ConcurrentHashMap import javax.swing.JOptionPane enum class LessonStartingWay { NEXT_BUTTON, PREV_BUTTON, RESTART_BUTTON, RESTORE_LINK, ONBOARDING_PROMOTER, LEARN_TAB, TIP_AND_TRICK_PROMOTER, NO_SDK_RESTART } internal enum class FeedbackEntryPlace { WELCOME_SCREEN, LEARNING_PROJECT, ANOTHER_PROJECT } internal enum class FeedbackLikenessAnswer { NO_ANSWER, LIKE, DISLIKE } enum class LearningInternalProblems { NO_SDK_CONFIGURED, // Before learning start we are trying to autoconfigure SDK or at least ask about location } internal class StatisticBase : CounterUsagesCollector() { override fun getGroup() = GROUP private data class LessonProgress(val lessonId: String, val taskId: Int) enum class LearnProjectOpeningWay { LEARN_IDE, ONBOARDING_PROMOTER } enum class LessonStopReason { CLOSE_PROJECT, RESTART, CLOSE_FILE, OPEN_MODULES, OPEN_NEXT_OR_PREV_LESSON, EXIT_LINK } companion object { private val LOG = logger<StatisticBase>() private val sessionLessonTimestamp: ConcurrentHashMap<String, Long> = ConcurrentHashMap() private var prevRestoreLessonProgress: LessonProgress = LessonProgress("", 0) private val GROUP: EventLogGroup = EventLogGroup("ideFeaturesTrainer", 19) var isLearnProjectCloseLogged = false // FIELDS private val lessonIdField = EventFields.StringValidatedByCustomRule(LESSON_ID, IdeFeaturesTrainerRuleValidator::class.java) private val languageField = EventFields.StringValidatedByCustomRule(LANGUAGE, SupportedLanguageRuleValidator::class.java) private val completedCountField = EventFields.Int(COMPLETED_COUNT) private val courseSizeField = EventFields.Int(COURSE_SIZE) private val moduleNameField = EventFields.StringValidatedByCustomRule(MODULE_NAME, IdeFeaturesTrainerModuleRuleValidator::class.java) private val taskIdField = EventFields.StringValidatedByCustomRule(TASK_ID, TaskIdRuleValidator::class.java) private val actionIdField = EventFields.StringValidatedByCustomRule(ACTION_ID, ActionIdRuleValidator::class.java) private val keymapSchemeField = EventFields.StringValidatedByCustomRule(KEYMAP_SCHEME, KeymapSchemeRuleValidator::class.java) private val versionField = EventFields.Version private val inputEventField = EventFields.InputEvent private val learnProjectOpeningWayField = EventFields.Enum<LearnProjectOpeningWay>(LEARN_PROJECT_OPENING_WAY) private val reasonField = EventFields.Enum<LessonStopReason>(REASON) private val newLessonsCount = EventFields.Int(NEW_LESSONS_COUNT) private val showNewLessonsState = EventFields.Boolean(SHOULD_SHOW_NEW_LESSONS) private val tipIdField = EventFields.StringValidatedByCustomRule(TIP_ID, TipInfoValidationRule::class.java) private val lessonStartingWayField = EventFields.Enum<LessonStartingWay>(LESSON_STARTING_WAY) private val feedbackEntryPlace = EventFields.Enum<FeedbackEntryPlace>(FEEDBACK_ENTRY_PLACE) private val feedbackHasBeenSent = EventFields.Boolean(FEEDBACK_HAS_BEEN_SENT) private val feedbackOpenedViaNotification = EventFields.Boolean(FEEDBACK_OPENED_VIA_NOTIFICATION) private val feedbackLikenessAnswer = EventFields.Enum<FeedbackLikenessAnswer>(FEEDBACK_LIKENESS_ANSWER) private val feedbackExperiencedUser = EventFields.Boolean(FEEDBACK_EXPERIENCED_USER) private val internalProblemField = EventFields.Enum<LearningInternalProblems>(PROBLEM) private val lastBuildLearningOpened = object : PrimitiveEventField<String?>() { override val name: String = LAST_BUILD_LEARNING_OPENED override val validationRule: List<String> get() = listOf("{regexp#version}") override fun addData(fuData: FeatureUsageData, value: String?) { if (value != null) { fuData.addData(name, value) } } } // EVENTS private val lessonStartedEvent: EventId3<String?, String?, LessonStartingWay> = GROUP.registerEvent(START, lessonIdField, languageField, lessonStartingWayField) private val lessonPassedEvent: EventId3<String?, String?, Long> = GROUP.registerEvent(PASSED, lessonIdField, languageField, EventFields.Long(DURATION)) private val lessonStoppedEvent = GROUP.registerVarargEvent(STOPPED, lessonIdField, taskIdField, languageField, reasonField) private val progressUpdatedEvent = GROUP.registerVarargEvent(PROGRESS, lessonIdField, completedCountField, courseSizeField, languageField) private val moduleStartedEvent: EventId2<String?, String?> = GROUP.registerEvent(START_MODULE_ACTION, moduleNameField, languageField) private val welcomeScreenPanelExpandedEvent: EventId1<String?> = GROUP.registerEvent(EXPAND_WELCOME_PANEL, languageField) private val shortcutClickedEvent = GROUP.registerVarargEvent(SHORTCUT_CLICKED, inputEventField, keymapSchemeField, lessonIdField, taskIdField, actionIdField, versionField) private val restorePerformedEvent = GROUP.registerVarargEvent(RESTORE, lessonIdField, taskIdField, versionField) private val learnProjectOpenedFirstTimeEvent: EventId2<LearnProjectOpeningWay, String?> = GROUP.registerEvent(LEARN_PROJECT_OPENED_FIRST_TIME, learnProjectOpeningWayField, languageField) private val nonLearningProjectOpened: EventId1<LearnProjectOpeningWay> = GROUP.registerEvent(NON_LEARNING_PROJECT_OPENED, learnProjectOpeningWayField) private val newLessonsNotificationShown = GROUP.registerEvent(NEW_LESSONS_NOTIFICATION_SHOWN, newLessonsCount, lastBuildLearningOpened) private val showNewLessonsEvent = GROUP.registerEvent(SHOW_NEW_LESSONS, newLessonsCount, lastBuildLearningOpened) private val needShowNewLessonsNotifications = GROUP.registerEvent(NEED_SHOW_NEW_LESSONS_NOTIFICATIONS, newLessonsCount, lastBuildLearningOpened, showNewLessonsState) private val internalProblem = GROUP.registerEvent(INTERNAL_PROBLEM, internalProblemField, lessonIdField, languageField) private val lessonLinkClickedFromTip = GROUP.registerEvent(LESSON_LINK_CLICKED_FROM_TIP, lessonIdField, languageField, tipIdField) private val helpLinkClicked = GROUP.registerEvent(HELP_LINK_CLICKED, lessonIdField, languageField) private val onboardingFeedbackNotificationShown = GROUP.registerEvent(ONBOARDING_FEEDBACK_NOTIFICATION_SHOWN, feedbackEntryPlace) private val onboardingFeedbackDialogResult = GROUP.registerVarargEvent(ONBOARDING_FEEDBACK_DIALOG_RESULT, feedbackEntryPlace, feedbackHasBeenSent, feedbackOpenedViaNotification, feedbackLikenessAnswer, feedbackExperiencedUser, ) // LOGGING fun logLessonStarted(lesson: Lesson, startingWay: LessonStartingWay) { sessionLessonTimestamp[lesson.id] = System.nanoTime() lessonStartedEvent.log(lesson.id, courseLanguage(), startingWay) } fun logLessonPassed(lesson: Lesson) { val timestamp = sessionLessonTimestamp[lesson.id] if (timestamp == null) { LOG.warn("Unable to find timestamp for a lesson: ${lesson.name}") return } val delta = TimeoutUtil.getDurationMillis(timestamp) lessonPassedEvent.log(lesson.id, courseLanguage(), delta) progressUpdatedEvent.log(lessonIdField with lesson.id, completedCountField with completedCount(), courseSizeField with CourseManager.instance.lessonsForModules.size, languageField with courseLanguage()) } fun logLessonStopped(reason: LessonStopReason) { val lessonManager = LessonManager.instance if (lessonManager.lessonIsRunning()) { val lessonId = lessonManager.currentLesson!!.id val taskId = lessonManager.currentLessonExecutor!!.currentTaskIndex lessonStoppedEvent.log(lessonIdField with lessonId, taskIdField with taskId.toString(), languageField with courseLanguage(), reasonField with reason ) if (reason == LessonStopReason.CLOSE_PROJECT || reason == LessonStopReason.EXIT_LINK) { isLearnProjectCloseLogged = true } } } fun logModuleStarted(module: IftModule) { moduleStartedEvent.log(module.id, courseLanguage()) } fun logWelcomeScreenPanelExpanded() { welcomeScreenPanelExpandedEvent.log(courseLanguage()) } fun logShortcutClicked(actionId: String) { val lessonManager = LessonManager.instance if (lessonManager.lessonIsRunning()) { val lesson = lessonManager.currentLesson!! val keymap = getDefaultKeymap() ?: return shortcutClickedEvent.log(inputEventField with createInputEvent(actionId), keymapSchemeField with keymap.name, lessonIdField with lesson.id, taskIdField with lessonManager.currentLessonExecutor?.currentTaskIndex.toString(), actionIdField with actionId, versionField with getPluginVersion(lesson)) } } fun logRestorePerformed(lesson: Lesson, taskId: Int) { val curLessonProgress = LessonProgress(lesson.id, taskId) if (curLessonProgress != prevRestoreLessonProgress) { prevRestoreLessonProgress = curLessonProgress restorePerformedEvent.log(lessonIdField with lesson.id, taskIdField with taskId.toString(), versionField with getPluginVersion(lesson)) } } fun logLearnProjectOpenedForTheFirstTime(way: LearnProjectOpeningWay) { val langManager = LangManager.getInstance() val languageId = langManager.getLanguageId() ?: return if (langManager.getLearningProjectPath(languageId) == null) { LearnProjectState.instance.firstTimeOpenedWay = way learnProjectOpenedFirstTimeEvent.log(way, courseLanguage()) } } fun logNonLearningProjectOpened(way: LearnProjectOpeningWay) { nonLearningProjectOpened.log(way) } fun logNewLessonsNotification(newLessonsCount: Int, previousOpenedVersion: BuildNumber?) { newLessonsNotificationShown.log(newLessonsCount, previousOpenedVersion?.asString()) } fun logShowNewLessonsEvent(newLessonsCount: Int, previousOpenedVersion: BuildNumber?) { showNewLessonsEvent.log(newLessonsCount, previousOpenedVersion?.asString()) } fun logShowNewLessonsNotificationState(newLessonsCount: Int, previousOpenedVersion: BuildNumber?, showNewLessons: Boolean) { needShowNewLessonsNotifications.log(newLessonsCount, previousOpenedVersion?.asString(), showNewLessons) } fun logLessonLinkClickedFromTip(lessonId: String, tipId: String) { lessonLinkClickedFromTip.log(lessonId, courseLanguage(), tipId) } fun logHelpLinkClicked(lessonId: String) { helpLinkClicked.log(lessonId, courseLanguage()) } fun logOnboardingFeedbackNotification(place: FeedbackEntryPlace) { onboardingFeedbackNotificationShown.log(place) } fun logOnboardingFeedbackDialogResult(place: FeedbackEntryPlace, hasBeenSent: Boolean, openedViaNotification: Boolean, likenessAnswer: FeedbackLikenessAnswer, experiencedUser: Boolean) { onboardingFeedbackDialogResult.log( feedbackEntryPlace with place, feedbackHasBeenSent with hasBeenSent, feedbackOpenedViaNotification with openedViaNotification, feedbackLikenessAnswer with likenessAnswer, feedbackExperiencedUser with experiencedUser ) } fun logLearningProblem(problem: LearningInternalProblems, lesson: Lesson) { internalProblem.log(problem, lesson.id, courseLanguage()) } private fun courseLanguage() = LangManager.getInstance().getLangSupport()?.primaryLanguage?.toLowerCase() ?: "" private fun completedCount(): Int = CourseManager.instance.lessonsForModules.count { it.passed } private fun createInputEvent(actionId: String): FusInputEvent? { val keyStroke = ShortcutsRenderingUtil.getShortcutByActionId(actionId)?.firstKeyStroke ?: return null val inputEvent = KeyEvent(JOptionPane.getRootFrame(), KeyEvent.KEY_PRESSED, System.currentTimeMillis(), keyStroke.modifiers, keyStroke.keyCode, keyStroke.keyChar, KeyEvent.KEY_LOCATION_STANDARD) return FusInputEvent(inputEvent, "") } private fun getPluginVersion(lesson: Lesson): String? { return PluginManager.getPluginByClass(lesson::class.java)?.version } private fun getDefaultKeymap(): Keymap? { val keymap = KeymapManager.getInstance().activeKeymap if (keymap is DefaultKeymapImpl) { return keymap } return keymap.parent as? DefaultKeymapImpl } } }
apache-2.0
1b3c48df16cc9a44e946ed0167ec2443
53.13253
158
0.73179
5.19093
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/checker/regression/kt251.kt
13
677
class A() { var x: Int = 0 get() = <error>"s"</error> set(value: <error>String</error>) { field = <error>value</error> } val y: Int get(): <error>String</error> = "s" val z: Int get() { return <error>"s"</error> } var a: Any = 1 set(v: <error>String</error>) { field = v } val b: Int get(): <error>Any</error> = "s" val c: Int get() { return 1 } val d = 1 get() { return field } val e = 1 get(): <error>String</error> { return <error>field</error> } }
apache-2.0
b9529a5a3e3c6ba712b1f40b144a62d4
19.545455
43
0.391433
3.582011
false
false
false
false
GunoH/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/util/CoroutineFrameBuilder.kt
4
9572
// 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.debugger.coroutine.util import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.debugger.jdi.StackFrameProxyImpl import com.intellij.debugger.jdi.ThreadReferenceProxyImpl import com.intellij.xdebugger.frame.XNamedValue import com.sun.jdi.ObjectReference import org.jetbrains.kotlin.idea.debugger.coroutine.data.* import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.ContinuationHolder import org.jetbrains.kotlin.idea.debugger.coroutine.proxy.safeSkipCoroutineStackFrameProxy import java.lang.Integer.min class CoroutineFrameBuilder { companion object { val log by logger private const val PRE_FETCH_FRAME_COUNT = 5 fun build(coroutine: CoroutineInfoData, suspendContext: SuspendContextImpl): CoroutineFrameItemLists? = when { coroutine.isRunning() -> buildStackFrameForActive(coroutine, suspendContext) coroutine.isSuspended() -> CoroutineFrameItemLists(coroutine.stackTrace, coroutine.creationStackTrace) else -> null } private fun buildStackFrameForActive(coroutine: CoroutineInfoData, suspendContext: SuspendContextImpl): CoroutineFrameItemLists? { val activeThread = coroutine.activeThread ?: return null val coroutineStackFrameList = mutableListOf<CoroutineStackFrameItem>() val threadReferenceProxyImpl = ThreadReferenceProxyImpl(suspendContext.debugProcess.virtualMachineProxy, activeThread) val realFrames = threadReferenceProxyImpl.forceFrames() for (runningStackFrameProxy in realFrames) { val preflightStackFrame = coroutineExitFrame(runningStackFrameProxy, suspendContext) if (preflightStackFrame != null) { buildRealStackFrameItem(preflightStackFrame.stackFrameProxy)?.let { coroutineStackFrameList.add(it) } val coroutineFrameLists = build(preflightStackFrame, suspendContext) coroutineStackFrameList.addAll(coroutineFrameLists.frames) return CoroutineFrameItemLists(coroutineStackFrameList, coroutine.creationStackTrace) } else { buildRealStackFrameItem(runningStackFrameProxy)?.let { coroutineStackFrameList.add(it) } } } return CoroutineFrameItemLists(coroutineStackFrameList, coroutine.creationStackTrace) } /** * Used by CoroutineAsyncStackTraceProvider to build XFramesView */ fun build(preflightFrame: CoroutinePreflightFrame, suspendContext: SuspendContextImpl): CoroutineFrameItemLists { val stackFrames = mutableListOf<CoroutineStackFrameItem>() val (restoredStackTrace, _) = restoredStackTrace( preflightFrame, ) stackFrames.addAll(restoredStackTrace) // @TODO perhaps we need to merge the dropped variables with the frame below... val framesLeft = preflightFrame.threadPreCoroutineFrames stackFrames.addAll(framesLeft.mapIndexedNotNull { _, stackFrameProxyImpl -> suspendContext.invokeInManagerThread { buildRealStackFrameItem(stackFrameProxyImpl) } }) return CoroutineFrameItemLists(stackFrames, preflightFrame.coroutineInfoData.creationStackTrace) } private fun restoredStackTrace( preflightFrame: CoroutinePreflightFrame, ): Pair<List<CoroutineStackFrameItem>, List<XNamedValue>> { val preflightFrameLocation = preflightFrame.stackFrameProxy.location() val coroutineStackFrame = preflightFrame.coroutineInfoData.stackTrace val preCoroutineTopFrameLocation = preflightFrame.threadPreCoroutineFrames.firstOrNull()?.location() val variablesRemovedFromTopRestoredFrame = mutableListOf<XNamedValue>() val stripTopStackTrace = coroutineStackFrame.dropWhile { it.location.isFilterFromTop(preflightFrameLocation).apply { if (this) variablesRemovedFromTopRestoredFrame.addAll(it.spilledVariables) } } // @TODO Need to merge variablesRemovedFromTopRestoredFrame into stripTopStackTrace.firstOrNull().spilledVariables val variablesRemovedFromBottomRestoredFrame = mutableListOf<XNamedValue>() val restoredFrames = when (preCoroutineTopFrameLocation) { null -> stripTopStackTrace else -> stripTopStackTrace.dropLastWhile { it.location.isFilterFromBottom(preCoroutineTopFrameLocation) .apply { variablesRemovedFromBottomRestoredFrame.addAll(it.spilledVariables) } } } return Pair(restoredFrames, variablesRemovedFromBottomRestoredFrame) } data class CoroutineFrameItemLists( val frames: List<CoroutineStackFrameItem>, val creationFrames: List<CreationCoroutineStackFrameItem> ) { fun allFrames() = frames + creationFrames } private fun buildRealStackFrameItem( frame: StackFrameProxyImpl ): RunningCoroutineStackFrameItem? { val location = frame.location() ?: return null return if (!location.safeCoroutineExitPointLineNumber()) RunningCoroutineStackFrameItem(safeSkipCoroutineStackFrameProxy(frame), location) else null } /** * Used by CoroutineStackFrameInterceptor to check if that frame is 'exit' coroutine frame. */ fun coroutineExitFrame( frame: StackFrameProxyImpl, suspendContext: SuspendContextImpl ): CoroutinePreflightFrame? { return suspendContext.invokeInManagerThread { val sem = frame.location().getSuspendExitMode() val preflightStackFrame = if (sem.isCoroutineFound()) { lookupContinuation(suspendContext, frame, sem) } else null preflightStackFrame } } fun lookupContinuation( suspendContext: SuspendContextImpl, frame: StackFrameProxyImpl, mode: SuspendExitMode ): CoroutinePreflightFrame? { if (!mode.isCoroutineFound()) return null val theFollowingFrames = theFollowingFrames(frame) ?: emptyList() if (mode.isSuspendMethodParameter()) { if (theFollowingFrames.isNotEmpty()) { // have to check next frame if that's invokeSuspend:-1 before proceed, otherwise skip lookForTheFollowingFrame(theFollowingFrames) ?: return null } else return null } if (threadAndContextSupportsEvaluation(suspendContext, frame)) { val context = suspendContext.executionContext() ?: return null val continuation = when (mode) { SuspendExitMode.SUSPEND_LAMBDA -> getThisContinuation(frame) SuspendExitMode.SUSPEND_METHOD_PARAMETER -> getLVTContinuation(frame) else -> null } ?: return null val continuationHolder = ContinuationHolder.instance(context) val coroutineInfo = continuationHolder.extractCoroutineInfoData(continuation) ?: return null return CoroutinePreflightFrame( coroutineInfo, frame, theFollowingFrames, mode, coroutineInfo.topFrameVariables ) } return null } private fun lookForTheFollowingFrame(theFollowingFrames: List<StackFrameProxyImpl>): StackFrameProxyImpl? { for (i in 0 until min(PRE_FETCH_FRAME_COUNT, theFollowingFrames.size)) { // pre-scan PRE_FETCH_FRAME_COUNT frames val nextFrame = theFollowingFrames[i] if (nextFrame.location().getSuspendExitMode() != SuspendExitMode.NONE) { return nextFrame } } return null } private fun getLVTContinuation(frame: StackFrameProxyImpl?) = frame?.continuationVariableValue() private fun getThisContinuation(frame: StackFrameProxyImpl?): ObjectReference? = frame?.thisVariableValue() private fun theFollowingFrames(frame: StackFrameProxyImpl): List<StackFrameProxyImpl>? { val frames = frame.threadProxy().frames() val indexOfCurrentFrame = frames.indexOf(frame) if (indexOfCurrentFrame >= 0) { val indexOfGetCoroutineSuspended = hasGetCoroutineSuspended(frames) // @TODO if found - skip this thread stack if (indexOfGetCoroutineSuspended < 0 && frames.size > indexOfCurrentFrame + 1) return frames.drop(indexOfCurrentFrame + 1) } else { log.error("Frame isn't found on the thread stack.") } return null } } }
apache-2.0
19ac488092750074e4e46e1db5d4f61f
46.386139
158
0.637275
6.326504
false
false
false
false
siosio/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/ScopeColumn.kt
2
2223
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns import com.intellij.util.ui.ColumnInfo import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.PackagesTableItem import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.editors.PackageScopeTableCellEditor import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PackageScopeTableCellRenderer import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer internal class ScopeColumn( private val scopeSetter: (packageModel: PackageModel, newScope: PackageScope) -> Unit ) : ColumnInfo<PackagesTableItem<*>, ScopeViewModel<*>>( PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.columns.scope") ) { override fun getRenderer(item: PackagesTableItem<*>): TableCellRenderer = PackageScopeTableCellRenderer override fun getEditor(item: PackagesTableItem<*>): TableCellEditor = PackageScopeTableCellEditor override fun isCellEditable(item: PackagesTableItem<*>?) = true override fun valueOf(item: PackagesTableItem<*>): ScopeViewModel<*> = when (item) { is PackagesTableItem.InstalledPackage -> { val selectedScope = item.installedScopes.first() ScopeViewModel.InstalledPackage(item.packageModel, item.installedScopes, item.defaultScope, selectedScope = selectedScope) } is PackagesTableItem.InstallablePackage -> { val selectedScope = item.selectedPackageModel.selectedScope ScopeViewModel.InstallablePackage(item.packageModel, item.availableScopes, item.defaultScope, selectedScope = selectedScope) } } override fun setValue(item: PackagesTableItem<*>?, value: ScopeViewModel<*>?) { if (value !is ScopeViewModel) return scopeSetter(value.packageModel, value.selectedScope) } }
apache-2.0
500c43ba7b70b9a195d02cbe9565cc66
53.219512
139
0.791273
5.280285
false
false
false
false
JetBrains/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/jvm/ToolConfig.kt
2
2215
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.tool import org.jetbrains.kotlin.konan.target.HostManager import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.konan.target.PlatformManager import org.jetbrains.kotlin.konan.target.customerDistribution import org.jetbrains.kotlin.konan.util.KonanHomeProvider import org.jetbrains.kotlin.konan.util.defaultTargetSubstitutions import org.jetbrains.kotlin.native.interop.gen.jvm.KotlinPlatform class ToolConfig(userProvidedTargetName: String?, flavor: KotlinPlatform) { private val konanHome = KonanHomeProvider.determineKonanHome() private val distribution = customerDistribution(konanHome) private val platformManager = PlatformManager(distribution) private val targetManager = platformManager.targetManager(userProvidedTargetName) private val host = HostManager.host val target = targetManager.target private val platform = platformManager.platform(target) val clang = platform.clang val substitutions = defaultTargetSubstitutions(target) fun downloadDependencies() = platform.downloadDependencies() val defaultCompilerOpts = platform.clang.targetLibclangArgs.toList() val platformCompilerOpts = if (flavor == KotlinPlatform.JVM) platform.clang.hostCompilerArgsForJni.toList() else emptyList() val llvmHome = platform.absoluteLlvmHome val sysRoot = platform.absoluteTargetSysRoot val libclang = when (host) { KonanTarget.MINGW_X64 -> "$llvmHome/bin/libclang.dll" else -> "$llvmHome/lib/${System.mapLibraryName("clang")}" } }
apache-2.0
d9747fb7c2997c6ef9f0dfb44834be9e
37.859649
85
0.768397
4.538934
false
false
false
false
jwren/intellij-community
plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/composeUtils.kt
4
3142
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.debugger import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.DebugProcess import com.intellij.debugger.requests.ClassPrepareRequestor import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.runReadAction import com.intellij.psi.JavaPsiFacade import com.sun.jdi.ReferenceType import com.sun.jdi.request.ClassPrepareRequest import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil import org.jetbrains.kotlin.load.kotlin.PackagePartClassUtils import org.jetbrains.kotlin.psi.KtFile private const val COMPOSABLE_SINGLETONS_PREFIX = "ComposableSingletons" private const val ANDROIDX_COMPOSE_PACKAGE_NAME = "androidx.compose" /** * Compute the name of the ComposableSingletons class for the given file. * * Compose compiler plugin creates per-file ComposableSingletons classes to cache * composable lambdas without captured variables. We need to locate these classes in order * to search them for breakpoint locations. * * NOTE: The pattern for ComposableSingletons classes needs to be kept in sync with the * code in `ComposerLambdaMemoization.getOrCreateComposableSingletonsClass`. * The optimization was introduced in I8c967b14c5d9bf67e5646e60f630f2e29e006366 */ fun computeComposableSingletonsClassName(file: KtFile): String { // The code in `ComposerLambdaMemoization` always uses the file short name and // ignores `JvmName` annotations, but (implicitly) respects `JvmPackageName` // annotations. val filePath = file.virtualFile?.path ?: file.name val fileName = filePath.split('/').last() val shortName = PackagePartClassUtils.getFilePartShortName(fileName) val fileClassFqName = runReadAction { JvmFileClassUtil.getFileClassInfoNoResolve(file) }.facadeClassFqName val classNameSuffix = "$COMPOSABLE_SINGLETONS_PREFIX\$$shortName" val filePackageName = fileClassFqName.parent() if (filePackageName.isRoot) { return classNameSuffix } return "${filePackageName.asString()}.$classNameSuffix" } fun SourcePosition.isInsideProjectWithCompose(): Boolean = ReadAction.nonBlocking<Boolean> { JavaPsiFacade.getInstance(file.project).findPackage(ANDROIDX_COMPOSE_PACKAGE_NAME) != null }.executeSynchronously() fun getComposableSingletonsClasses(debugProcess: DebugProcess, file: KtFile): List<ReferenceType> { val vm = debugProcess.virtualMachineProxy val composableSingletonsClassName = computeComposableSingletonsClassName(file) return vm.classesByName(composableSingletonsClassName).flatMap { referenceType -> if (referenceType.isPrepared) vm.nestedTypes(referenceType) else listOf() } } fun getClassPrepareRequestForComposableSingletons( debugProcess: DebugProcess, requestor: ClassPrepareRequestor, file: KtFile ): ClassPrepareRequest? { return debugProcess.requestsManager.createClassPrepareRequest( requestor, "${computeComposableSingletonsClassName(file)}\$*" ) }
apache-2.0
058056f844478d065cb9071a82efd9e2
45.205882
120
0.790898
4.634218
false
false
false
false
jwren/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/VfsCodeBlockModificationListener.kt
1
1774
// 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.caches.project import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.vfs.AsyncVfsEventsListener import com.intellij.vfs.AsyncVfsEventsPostProcessor import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable import org.jetbrains.kotlin.idea.core.util.runInReadActionWithWriteActionPriority import org.jetbrains.kotlin.idea.util.ProjectRootsUtil class VfsCodeBlockModificationListener: StartupActivity.Background { override fun runActivity(project: Project) { val disposable = KotlinPluginDisposable.getInstance(project) val ocbModificationListener = KotlinCodeBlockModificationListener.getInstance(project) val vfsEventsListener = AsyncVfsEventsListener { events: List<VFileEvent> -> val projectRelatedVfsFileChange = events.any { event -> val file = event.takeIf { it.isFromRefresh || it is VFileContentChangeEvent }?.file ?: return@any false runInReadActionWithWriteActionPriority { ProjectRootsUtil.isProjectSourceFile(project, file) } ?: true } if (projectRelatedVfsFileChange) { ocbModificationListener.incModificationCount() } } AsyncVfsEventsPostProcessor.getInstance().addListener(vfsEventsListener, disposable) } }
apache-2.0
e5bf84a3281f9158a6b9da17e26b0b19
52.787879
158
0.76212
5.172012
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/defaultNamed3.kt
13
183
class Transformer { fun transform(x: Int = 0, y: Int = 1, f: (Int) -> Int) = f(x + y) } fun bar(x: Int) = x * x val y = Transformer().transform(x = 2, y = 3) { <caret>bar(it) }
apache-2.0
703605adbb1b7c7319ce73ea63ad6a73
25.142857
69
0.535519
2.407895
false
false
false
false
smmribeiro/intellij-community
plugins/changeReminder/src/com/jetbrains/changeReminder/util.kt
12
1476
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.changeReminder import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.ProjectLevelVcsManager import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.data.index.VcsLogPersistentIndex import com.intellij.vcs.log.impl.VcsLogManager import git4idea.GitVcs fun getGitRootFiles(project: Project, files: Collection<FilePath>): Map<VirtualFile, Collection<FilePath>> { val rootFiles = HashMap<VirtualFile, HashSet<FilePath>>() val projectLevelVcsManager = ProjectLevelVcsManager.getInstance(project) files.forEach { filePath -> val fileVcs = projectLevelVcsManager.getVcsRootObjectFor(filePath) if (fileVcs != null && fileVcs.vcs is GitVcs) { rootFiles.getOrPut(fileVcs.path) { HashSet() }.add(filePath) } } return rootFiles } fun <T, K> MutableMap<T, K>.retainAll(keys: Collection<T>) = this.keys.subtract(keys).forEach { this.remove(it) } internal fun Project.getGitRoots() = ProjectLevelVcsManager.getInstance(this).allVcsRoots.filter { it.vcs is GitVcs } internal fun Project.anyGitRootsForIndexing(): Boolean { val gitRoots = this.getGitRoots() val rootsForIndex = VcsLogPersistentIndex.getRootsForIndexing(VcsLogManager.findLogProviders(gitRoots, this)) return rootsForIndex.isNotEmpty() }
apache-2.0
68089828887efd29f380f503ebd98b9c
40.027778
140
0.783875
4.032787
false
false
false
false
aurae/PermissionsDispatcher
processor/src/main/kotlin/permissions/dispatcher/processor/impl/kotlin/WriteSettingsHelper.kt
1
1167
package permissions.dispatcher.processor.impl.kotlin import com.squareup.javapoet.ClassName import com.squareup.kotlinpoet.FunSpec class WriteSettingsHelper : SensitivePermissionInterface { private val PERMISSION_UTILS = ClassName.get("permissions.dispatcher", "PermissionUtils") private val SETTINGS = ClassName.get("android.provider", "Settings") private val INTENT = ClassName.get("android.content", "Intent") private val URI = ClassName.get("android.net", "Uri") override fun addHasSelfPermissionsCondition(builder: FunSpec.Builder, activity: String, permissionField: String) { builder.beginControlFlow("if (%T.hasSelfPermissions(%N, %N) || %T.System.canWrite(%N))", PERMISSION_UTILS, activity, permissionField, SETTINGS, activity) } override fun addRequestPermissionsStatement(builder: FunSpec.Builder, activity: String, requestCodeField: String) { builder.addStatement("%T intent = %T(%T.ACTION_MANAGE_WRITE_SETTINGS, %T.parse(\"package:\" + %N.getPackageName()))", INTENT, INTENT, SETTINGS, URI, activity) builder.addStatement("%N.startActivityForResult(intent, %N)", activity, requestCodeField) } }
apache-2.0
903fa5553d05c88cd09bcf7a7598b9ac
54.619048
166
0.749786
4.471264
false
false
false
false
migafgarcia/programming-challenges
advent_of_code/2018/solutions/day_12_b.kt
1
1858
import java.io.File // 2463 fun main(args: Array<String>) { assert(score(".#....##....#####...#######....#.#..##.", 3) == 325) val regex = Regex(".* => .*") val margin = 3 val nIterations = 50000000000 val lines = File(args[0]).readLines() var leftPots = 0 var state = StringBuilder(lines[0].split(":")[1].trim()) val transitions = lines.filter { it.matches(regex) }.map { line -> val split = line.split("=>") Pair(split[0].trim(), split[1].trim()[0]) }.toMap() println("0 -> $state") val scores = ArrayList<Int>(5000) scores.add(score(state.toString(), leftPots)) for (gen in 1..nIterations) { val leftEmptyPots = CharArray(maxOf(margin - state.indexOf('#'), 0)) { '.' } state.insert(0, leftEmptyPots) leftPots += leftEmptyPots.size val rightEmptyPots = CharArray(maxOf(margin - (state.length - state.lastIndexOf('#')), 0) + 1) { '.' } state.append(rightEmptyPots) val nextState = StringBuilder(state) transitions.forEach { t, u -> var patternIndex = state.indexOf(t, 0) while (patternIndex != -1) { nextState[patternIndex + 2] = u patternIndex = state.indexOf(t, patternIndex + 1) } } state = nextState scores.add(score(state.toString(), leftPots)) val convergenceDelta = 5 val distinct = scores.takeLast(convergenceDelta).zipWithNext().map { it.second - it.first } if(scores.size >= 5 && distinct.all { it == distinct.last() }) { println(scores.last() + (nIterations - gen) * distinct.last()) break } } } private fun score(state: String, leftPots: Int): Int = (0 until state.length) .filter { state[it] == '#' } .sumBy { it - leftPots }
mit
bba20fc0544b9ae81378132feb85f4aa
28.046875
110
0.55113
3.903361
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/settings/nodeselector/NodeSelectorUpdate.kt
1
2966
/** * BreadWallet * * Created by Pablo Budelli <[email protected]> on 11/14/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.settings.nodeselector import com.breadwallet.crypto.WalletManagerState import com.breadwallet.ui.settings.nodeselector.NodeSelector.E import com.breadwallet.ui.settings.nodeselector.NodeSelector.F import com.breadwallet.ui.settings.nodeselector.NodeSelector.M import com.spotify.mobius.Next import com.spotify.mobius.Next.dispatch import com.spotify.mobius.Next.next import com.spotify.mobius.Update object NodeSelectorUpdate : Update<M, E, F>, NodeSelectorUpdateSpec { override fun update( model: M, event: E ): Next<M, F> = patch(model, event) override fun onSwitchButtonClicked(model: M): Next<M, F> { return dispatch( if (model.mode == NodeSelector.Mode.AUTOMATIC) { setOf(F.ShowNodeDialog) } else { setOf(F.SetToAutomatic) } ) } override fun setCustomNode( model: M, event: E.SetCustomNode ): Next<M, F> = next( model.copy( mode = NodeSelector.Mode.AUTOMATIC, currentNode = event.node ), setOf(F.SetCustomNode(event.node)) ) override fun onConnectionStateUpdated( model: M, event: E.OnConnectionStateUpdated ): Next<M, F> = next( model.copy( connected = when (event.state) { WalletManagerState.SYNCING(), WalletManagerState.CONNECTED() -> true else -> false } ) ) override fun onConnectionInfoLoaded( model: M, event: E.OnConnectionInfoLoaded ): Next<M, F> = next(model.copy(mode = event.mode, currentNode = event.node)) }
mit
a5061471485ea34b94711cebd0e4e1f6
34.73494
88
0.66588
4.400593
false
false
false
false
cmcpasserby/MayaCharm
src/main/kotlin/settings/ui/SdkSelector.kt
1
1078
package settings.ui import MayaBundle as Loc import com.intellij.openapi.ui.ComboBox import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Insets import javax.swing.JLabel import javax.swing.JPanel class SdkSelector : JPanel(GridBagLayout()) { private val comboBox = ComboBox<String>() init { with(GridBagConstraints()) { insets = Insets(2, 2, 2, 2) gridx = 0 gridy = 0 fill = GridBagConstraints.HORIZONTAL add(JLabel(Loc.message("mayacharm.ActiveMayaSdk")), this) gridx = 1 weightx = 0.1 add(comboBox, this) } } var selectedItem: String? get() = comboBox.selectedItem as String? set(value) { comboBox.selectedItem = value } var items: List<String> get() = List<String>(comboBox.itemCount) { comboBox.getItemAt(it) } set(value) { comboBox.removeAllItems() for (s in value) { comboBox.addItem(s) } } }
mit
bd2105eed85e106af4f72c294caf96b7
24.666667
75
0.583488
4.436214
false
false
false
false
quran/quran_android
app/src/main/java/com/quran/labs/androidquran/ui/fragment/SuraListFragment.kt
2
5335
package com.quran.labs.androidquran.ui.fragment import android.app.Activity import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.quran.data.core.QuranInfo import com.quran.labs.androidquran.QuranApplication import com.quran.labs.androidquran.R import com.quran.labs.androidquran.data.Constants import com.quran.labs.androidquran.data.Constants.JUZ2_COUNT import com.quran.labs.androidquran.data.Constants.SURAS_COUNT import com.quran.labs.androidquran.data.QuranDisplayData import com.quran.labs.androidquran.ui.QuranActivity import com.quran.labs.androidquran.ui.helpers.QuranListAdapter import com.quran.labs.androidquran.ui.helpers.QuranRow import com.quran.labs.androidquran.util.QuranSettings import com.quran.labs.androidquran.util.QuranUtils import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.observers.DisposableSingleObserver import javax.inject.Inject class SuraListFragment : Fragment() { @Inject lateinit var quranInfo: QuranInfo @Inject lateinit var quranDisplayData: QuranDisplayData @Inject lateinit var quranSettings: QuranSettings private lateinit var recyclerView: RecyclerView private var numberOfPages = 0 private var showSuraTranslatedName = false private var disposable: Disposable? = null override fun onAttach(context: Context) { super.onAttach(context) (context.applicationContext as QuranApplication).applicationComponent.inject(this) numberOfPages = quranInfo.numberOfPages } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val view: View = inflater.inflate(R.layout.quran_list, container, false) recyclerView = view.findViewById(R.id.recycler_view) recyclerView.apply { layoutManager = LinearLayoutManager(context) itemAnimator = DefaultItemAnimator() adapter = QuranListAdapter(requireActivity(), recyclerView, getSuraList(), false) } return view } override fun onResume() { super.onResume() val activity = requireActivity() if (activity is QuranActivity) { val newValueOfShowSuraTranslatedName = quranSettings.isShowSuraTranslatedName if (showSuraTranslatedName != newValueOfShowSuraTranslatedName) { showHideSuraTranslatedName() showSuraTranslatedName = newValueOfShowSuraTranslatedName } disposable = (requireActivity() as QuranActivity).latestPageObservable .first(Constants.NO_PAGE) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(object : DisposableSingleObserver<Int>() { override fun onSuccess(recentPage: Int) { if (recentPage != Constants.NO_PAGE) { val sura = quranDisplayData.safelyGetSuraOnPage(recentPage) val juz = quranInfo.getJuzFromPage(recentPage) val position = sura + juz - 1 recyclerView.scrollToPosition(position) } } override fun onError(e: Throwable) {} }) if (quranSettings.isArabicNames) updateScrollBarPositionHoneycomb() } } override fun onPause() { disposable?.dispose() super.onPause() } private fun updateScrollBarPositionHoneycomb() { recyclerView.verticalScrollbarPosition = View.SCROLLBAR_POSITION_LEFT } private fun getSuraList(): Array<QuranRow> { var next: Int var pos = 0 var sura = 1 val elements = arrayOfNulls<QuranRow>(SURAS_COUNT + JUZ2_COUNT) val activity: Activity = requireActivity() val wantPrefix = activity.resources.getBoolean(R.bool.show_surat_prefix) val wantTranslation = quranSettings.isShowSuraTranslatedName for (juz in 1..JUZ2_COUNT) { val headerTitle = activity.getString( R.string.juz2_description, QuranUtils.getLocalizedNumber(activity, juz) ) val headerBuilder = QuranRow.Builder() .withType(QuranRow.HEADER) .withText(headerTitle) .withPage(quranInfo.getStartingPageForJuz(juz)) elements[pos++] = headerBuilder.build() next = if (juz == JUZ2_COUNT) { numberOfPages + 1 } else quranInfo.getStartingPageForJuz(juz + 1) while (sura <= SURAS_COUNT && quranInfo.getPageNumberForSura(sura) < next) { val builder = QuranRow.Builder() .withText(quranDisplayData.getSuraName(activity, sura, wantPrefix, wantTranslation)) .withMetadata(quranDisplayData.getSuraListMetaString(activity, sura)) .withSura(sura) .withPage(quranInfo.getPageNumberForSura(sura)) elements[pos++] = builder.build() sura++ } } return elements.filterNotNull().toTypedArray() } private fun showHideSuraTranslatedName() { val elements = getSuraList() (recyclerView.adapter as QuranListAdapter).setElements(elements) recyclerView.adapter?.notifyDataSetChanged() } companion object { fun newInstance(): SuraListFragment = SuraListFragment() } }
gpl-3.0
56348795f1c0d55079ca37d26b8caf9c
34.566667
94
0.736457
4.50211
false
false
false
false
seventhroot/elysium
bukkit/rpk-economy-bukkit/src/main/kotlin/com/rpkit/economy/bukkit/command/money/MoneyAddCommand.kt
1
14582
/* * Copyright 2020 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.economy.bukkit.command.money import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.economy.bukkit.RPKEconomyBukkit import com.rpkit.economy.bukkit.currency.RPKCurrency import com.rpkit.economy.bukkit.currency.RPKCurrencyProvider import com.rpkit.economy.bukkit.economy.RPKEconomyProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.conversations.* import org.bukkit.entity.Player /** * Money add command. * Gives money to a player's active character. */ class MoneyAddCommand(private val plugin: RPKEconomyBukkit): CommandExecutor { private val conversationFactory = ConversationFactory(plugin) .withModality(true) .withFirstPrompt(ProfilePrompt()) .withEscapeSequence("cancel") .thatExcludesNonPlayersWithMessage(plugin.messages["not-from-console"]) .addConversationAbandonedListener { event -> if (!event.gracefulExit()) { val conversable = event.context.forWhom if (conversable is Player) { conversable.sendMessage(plugin.messages["operation-cancelled"]) } } } override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender is Player) { if (sender.hasPermission("rpkit.economy.command.money.add")) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val economyProvider = plugin.core.serviceManager.getServiceProvider(RPKEconomyProvider::class) val currencyProvider = plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class) if (args.isNotEmpty()) { val bukkitPlayer = plugin.server.getPlayer(args[0]) if (bukkitPlayer != null) { val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) if (minecraftProfile != null) { val profile = minecraftProfile.profile if (profile is RPKProfile) { if (args.size > 1) { val character = characterProvider.getCharacters(profile) .firstOrNull { character -> character.name.startsWith(args[1]) } if (character != null) { if (args.size > 2) { val currency = currencyProvider.getCurrency(args[2]) if (currency != null) { if (args.size > 3) { try { val amount = args[3].toInt() if (amount >= 0) { if (economyProvider.getBalance(character, currency) + amount <= 1728) { economyProvider.setBalance(character, currency, economyProvider.getBalance(character, currency) + amount) sender.sendMessage(plugin.messages["money-add-amount-valid"]) sender.sendMessage(plugin.messages["money-add-valid"]) } else { sender.sendMessage(plugin.messages["money-add-amount-invalid-amount-limit"]) } } else { sender.sendMessage(plugin.messages["money-add-value-invalid-value-negative"]) } } catch (exception: NumberFormatException) { sender.sendMessage(plugin.messages["money-add-value-invalid-value-number"]) } } else { conversationFactory.buildConversation(sender).begin() } } else { sender.sendMessage(plugin.messages["money-add-currency-invalid-currency"]) } } else { conversationFactory.buildConversation(sender).begin() } } else { sender.sendMessage(plugin.messages["money-add-character-invalid-character"]) } } else { conversationFactory.buildConversation(sender).begin() } } else { sender.sendMessage(plugin.messages["no-profile"]) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["money-add-player-invalid-player"]) } } else { conversationFactory.buildConversation(sender).begin() } } else { sender.sendMessage(plugin.messages["no-permission-money-add"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } return true } private inner class ProfilePrompt: ValidatingPrompt() { override fun acceptValidatedInput(context: ConversationContext, input: String): Prompt { val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class) val profile = profileProvider.getProfile(input) context.setSessionData("profile", profile) return ProfileSetPrompt() } override fun isInputValid(context: ConversationContext, input: String): Boolean { val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class) return profileProvider.getProfile(input) != null } override fun getPromptText(context: ConversationContext): String { return plugin.messages["money-add-profile-prompt"] } override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String { return plugin.messages["money-add-profile-invalid-profile"] } } private inner class ProfileSetPrompt : MessagePrompt() { override fun getNextPrompt(context: ConversationContext): Prompt { return CharacterPrompt() } override fun getPromptText(context: ConversationContext): String { return plugin.messages["money-add-profile-valid"] } } private inner class CharacterPrompt: ValidatingPrompt() { override fun isInputValid(context: ConversationContext, input: String): Boolean { return plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) .getCharacters(context.getSessionData("profile") as RPKProfile) .any { character -> character.name == input } } override fun acceptValidatedInput(context: ConversationContext, input: String): Prompt { context.setSessionData("character", plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) .getCharacters(context.getSessionData("profile") as RPKProfile) .first { character -> character.name == input } ) return CharacterSetPrompt() } override fun getPromptText(context: ConversationContext): String { return plugin.messages["money-add-character-prompt"] + "\n" + plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) .getCharacters(context.getSessionData("profile") as RPKProfile) .joinToString("\n") { character -> plugin.messages["money-add-character-prompt-list-item", mapOf( Pair("character", character.name) )] } } override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String { return plugin.messages["money-add-character-invalid-character"] } } private inner class CharacterSetPrompt: MessagePrompt() { override fun getNextPrompt(context: ConversationContext): Prompt { return CurrencyPrompt() } override fun getPromptText(context: ConversationContext): String { return plugin.messages["money-add-character-valid"] } } private inner class CurrencyPrompt: ValidatingPrompt() { override fun isInputValid(context: ConversationContext, input: String): Boolean { return plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class).getCurrency(input) != null } override fun acceptValidatedInput(context: ConversationContext, input: String): Prompt { context.setSessionData("currency", plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class).getCurrency(input)) return CurrencySetPrompt() } override fun getPromptText(context: ConversationContext): String { return plugin.messages["money-add-currency-prompt"] + "\n" + plugin.core.serviceManager.getServiceProvider(RPKCurrencyProvider::class).currencies .joinToString("\n") { currency -> plugin.messages["money-add-currency-prompt-list-item", mapOf( Pair("currency", currency.name) )] } } override fun getFailedValidationText(context: ConversationContext, invalidInput: String): String { return plugin.messages["money-add-currency-invalid-currency"] } } private inner class CurrencySetPrompt: MessagePrompt() { override fun getNextPrompt(context: ConversationContext): Prompt { return AmountPrompt() } override fun getPromptText(context: ConversationContext): String { return plugin.messages["money-add-currency-valid"] } } private inner class AmountPrompt: NumericPrompt() { override fun isNumberValid(context: ConversationContext, input: Number): Boolean { return input.toInt() > 0 } override fun acceptValidatedInput(context: ConversationContext, input: Number): Prompt { context.setSessionData("amount", input.toInt()) return AmountSetPrompt() } override fun getPromptText(context: ConversationContext): String { return plugin.messages["money-add-amount-prompt"] } override fun getFailedValidationText(context: ConversationContext, invalidInput: Number): String { return plugin.messages["money-add-amount-invalid-amount-negative"] } override fun getInputNotNumericText(context: ConversationContext, invalidInput: String): String { return plugin.messages["money-add-amount-invalid-amount-number"] } } private inner class AmountSetPrompt: MessagePrompt() { override fun getNextPrompt(context: ConversationContext): Prompt { return MoneyAddCompletePrompt() } override fun getPromptText(context: ConversationContext): String { return plugin.messages["money-add-amount-valid"] } } private inner class MoneyAddCompletePrompt: MessagePrompt() { override fun getNextPrompt(context: ConversationContext): Prompt? { return END_OF_CONVERSATION } override fun getPromptText(context: ConversationContext): String { val economyProvider = plugin.core.serviceManager.getServiceProvider(RPKEconomyProvider::class) val character = context.getSessionData("character") as RPKCharacter val currency = context.getSessionData("currency") as RPKCurrency val amount = context.getSessionData("amount") as Int if (economyProvider.getBalance(character, currency) + amount <= 1728) { economyProvider.setBalance(character, currency, economyProvider.getBalance(character, currency) + amount) } else { return plugin.messages["money-add-amount-invalid-amount-limit"] } return plugin.messages["money-add-valid"] } } }
apache-2.0
6808e7635fa9cfb6f51f9e88882f52c0
47.936242
169
0.570429
6.075833
false
false
false
false
siosio/nablarch-helper
src/main/java/siosio/repository/psi/ComponentXmlTagElement.kt
1
983
package siosio.repository.psi import com.intellij.ide.util.* import com.intellij.navigation.* import com.intellij.psi.* import com.intellij.psi.xml.* import siosio.* import javax.swing.* class ComponentXmlTagElement(private val xmlTag: XmlTag) : XmlTag by xmlTag, NavigatablePsiElement { override fun canNavigate(): Boolean = PsiNavigationSupport.getInstance().canNavigate(this) override fun canNavigateToSource(): Boolean = canNavigate() override fun getPresentation(): ItemPresentation { return object: ItemPresentation { override fun getLocationString(): String? = containingFile.name override fun getIcon(unused: Boolean): Icon? = nablarchIcon override fun getPresentableText(): String? = name } } override fun navigate(requestFocus: Boolean) { PsiNavigationSupport.getInstance().getDescriptor(this)?.navigate(requestFocus) } override fun getIcon(flags: Int): Icon = nablarchIcon }
apache-2.0
b52167e79bf4bd0c4545a7c61b183113
30.709677
100
0.723296
4.989848
false
false
false
false
markusfisch/BinaryEye
app/src/main/kotlin/de/markusfisch/android/binaryeye/graphics/Mapping.kt
1
2023
package de.markusfisch.android.binaryeye.graphics import android.graphics.Matrix import android.graphics.Rect import android.graphics.RectF import de.markusfisch.android.zxingcpp.ZxingCpp.Position import kotlin.math.roundToInt data class FrameMetrics( var width: Int = 0, var height: Int = 0, var orientation: Int = 0 ) fun Rect.setFrameRoi( frameMetrics: FrameMetrics, viewRect: Rect, viewRoi: Rect ) { Matrix().apply { // Map ROI from view coordinates to frame coordinates. setTranslate(-viewRect.left.toFloat(), -viewRect.top.toFloat()) postScale(1f / viewRect.width(), 1f / viewRect.height()) postRotate(-frameMetrics.orientation.toFloat(), .5f, .5f) postScale(frameMetrics.width.toFloat(), frameMetrics.height.toFloat()) val frameRoiF = RectF() val viewRoiF = RectF( viewRoi.left.toFloat(), viewRoi.top.toFloat(), viewRoi.right.toFloat(), viewRoi.bottom.toFloat() ) mapRect(frameRoiF, viewRoiF) set( frameRoiF.left.roundToInt(), frameRoiF.top.roundToInt(), frameRoiF.right.roundToInt(), frameRoiF.bottom.roundToInt() ) } } fun Matrix.setFrameToView( frameMetrics: FrameMetrics, viewRect: Rect, viewRoi: Rect? = null ) { // Configure this matrix to map points in frame coordinates to // view coordinates. val uprightWidth: Int val uprightHeight: Int when (frameMetrics.orientation) { 90, 270 -> { uprightWidth = frameMetrics.height uprightHeight = frameMetrics.width } else -> { uprightWidth = frameMetrics.width uprightHeight = frameMetrics.height } } setScale( viewRect.width().toFloat() / uprightWidth, viewRect.height().toFloat() / uprightHeight ) viewRoi?.let { postTranslate(viewRoi.left.toFloat(), viewRoi.top.toFloat()) } } fun Matrix.mapPosition( position: Position, coords: FloatArray ): Int { var i = 0 setOf( position.topLeft, position.topRight, position.bottomRight, position.bottomLeft ).forEach { coords[i++] = it.x.toFloat() coords[i++] = it.y.toFloat() } mapPoints(coords) return i }
mit
47a774dd260b8ba8a034567488f94bd8
22.252874
72
0.7217
3.102761
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/references/ColorsFindUsagesHandlerFactory.kt
1
2036
package com.gmail.blueboxware.libgdxplugin.references import com.gmail.blueboxware.libgdxplugin.utils.getParentOfType import com.gmail.blueboxware.libgdxplugin.utils.isColorsPutCall import com.intellij.find.findUsages.FindUsagesHandler import com.intellij.find.findUsages.FindUsagesHandlerFactory import com.intellij.psi.PsiElement import com.intellij.psi.PsiLiteralExpression import com.intellij.psi.PsiMethodCallExpression import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.psiUtil.isPlainWithEscapes /* * Copyright 2018 Blue Box Ware * * 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. */ class ColorsFindUsagesHandlerFactory : FindUsagesHandlerFactory() { override fun createFindUsagesHandler(element: PsiElement, forHighlightUsages: Boolean): FindUsagesHandler? = if (!forHighlightUsages) { (element as? PsiLiteralExpression)?.let(::ColorsFindUsagesHandler) ?: (element as? KtStringTemplateExpression)?.let(::ColorsFindUsagesHandler) } else { null } override fun canFindUsages(element: PsiElement): Boolean = when (element) { is PsiLiteralExpression -> element.getParentOfType<PsiMethodCallExpression>()?.isColorsPutCall() == true is KtStringTemplateExpression -> element.isPlainWithEscapes() && element.getParentOfType<KtCallExpression>()?.isColorsPutCall() == true else -> false } }
apache-2.0
626b78f4e730c476c1d2a0fe5f35a88a
38.921569
116
0.749509
4.977995
false
false
false
false
vjache/klips
src/main/java/org/klips/engine/rete/ProxyNode.kt
1
2385
package org.klips.engine.rete import org.klips.dsl.Facet import org.klips.dsl.Facet.FacetRef import org.klips.engine.Binding import org.klips.engine.Modification import org.klips.engine.util.ListSet import org.klips.engine.util.Log import org.klips.engine.util.SimpleEntry import org.klips.engine.util.activationHappen import kotlin.collections.Map.Entry abstract class ProxyNode(log:Log, node: Node, val renamingBinding: Binding) : Node(log), Consumer { var node: Node = node set(value) { value.addConsumer(this) field = value } init { node.addConsumer(this) } val bindingRevIndex = mutableMapOf<Facet<*>, Facet<*>>().apply { renamingBinding.forEach { put(it.value, it.key) } if (size != renamingBinding.size) throw IllegalStateException("Renaming must be bijection.") if (renamingBinding.all { it.key == it.value }) throw IllegalStateException("Renaming must not be identity.") } @Suppress("UNCHECKED_CAST") override val refs: Set<FacetRef<*>> by lazy { val notRenamed = node.refs.minus(renamingBinding.refs as Set<FacetRef<*>>) (bindingRevIndex.keys as Set<FacetRef<*>>).union(notRenamed) } override fun consume(source: Node, mdf: Modification<Binding>) { log.reteEvent { activationHappen() "P-CONSUME: $mdf, $this" } notifyConsumers(mdf.inherit(proxifyBinding(mdf.arg))) } protected abstract fun proxifyBinding(former: Binding):Binding override fun toString() = "P-Node($refs) [${System.identityHashCode(this)}]" inner class ProxyBinding(val data: Binding) : Binding() { override val entries: Set<Entry<Facet<*>, Facet<*>>> = ListSet { data.map { SimpleEntry(renamingBinding[it.key] ?: it.key, it.value) } } override val keys: Set<FacetRef<*>> get() = [email protected] override val size: Int get() = keys.size override val values: Collection<Facet<*>> get () = data.values override fun containsKey(key: Facet<*>) = keys.contains(key) override fun containsValue(value: Facet<*>) = values.contains(value) override fun get(key: Facet<*>) = data[bindingRevIndex[key]] override fun isEmpty() = keys.isEmpty() } }
apache-2.0
aa5faf5f6b9e7c03b4ecfe387e03830b
33.085714
99
0.638155
4.069966
false
false
false
false
facebook/fresco
samples/showcase/src/main/java/com/facebook/fresco/samples/showcase/misc/LogcatRequestListener2.kt
2
3016
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.fresco.samples.showcase.misc import android.util.Log import com.facebook.imagepipeline.listener.RequestListener2 import com.facebook.imagepipeline.producers.ProducerContext class LogcatRequestListener2( val logExtraMap: Boolean = true, val tag: String = "LogcatRequestListener2" ) : RequestListener2 { override fun onRequestStart(producerContext: ProducerContext) { Log.d(tag, "onRequestStart ${toString(producerContext)}") } override fun onRequestSuccess(producerContext: ProducerContext) { Log.d(tag, "onRequestSuccess ${toString(producerContext)}") } override fun onRequestFailure(producerContext: ProducerContext, throwable: Throwable?) { Log.d(tag, "onRequestFailure ${toString(producerContext)}") } override fun onRequestCancellation(producerContext: ProducerContext) { Log.d(tag, "onRequestCancellation ${toString(producerContext)}") } override fun onProducerFinishWithCancellation( producerContext: ProducerContext, producerName: String, extraMap: MutableMap<String, String>? ) { Log.d( tag, "onProducerFinishWithCancellation $producerContext, producerName=$producerName, extras=$extraMap") } override fun onProducerStart(producerContext: ProducerContext, producerName: String) { Log.d(tag, "onProducerStart ${toString(producerContext)}, producerName=$producerName") } override fun onProducerEvent( producerContext: ProducerContext, producerName: String, eventName: String ) { Log.d( tag, "onProducerEvent ${toString(producerContext)}, producerName=$producerName, event=$eventName") } override fun onProducerFinishWithSuccess( producerContext: ProducerContext, producerName: String, extraMap: MutableMap<String, String>? ) { Log.d( tag, "onProducerFinishWithSuccess ${toString(producerContext)}, producerName=$producerName, extras=$extraMap") } override fun onProducerFinishWithFailure( producerContext: ProducerContext, producerName: String?, t: Throwable?, extraMap: MutableMap<String, String>? ) { Log.d( tag, "onProducerFinishWithFailure ${toString(producerContext)}, producerName=$producerName, extras=$extraMap") } override fun onUltimateProducerReached( producerContext: ProducerContext, producerName: String, successful: Boolean ) { Log.d( tag, "onUltimateProducerReached ${toString(producerContext)}, producer=$producerName, successful=$successful") } override fun requiresExtraMap(producerContext: ProducerContext, producerName: String) = logExtraMap private fun toString(producerContext: ProducerContext) = producerContext.run { "id=$id, extras=$extras, request=$imageRequest" } }
mit
0dbbd8538040f655e8e4eec54ce7f3f9
30.747368
113
0.725464
4.597561
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/games/views/GameHeaderView.kt
1
4303
package ca.josephroque.bowlingcompanion.games.views import android.content.Context import android.os.Bundle import android.os.Parcelable import android.support.v4.content.ContextCompat import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import ca.josephroque.bowlingcompanion.R import kotlinx.android.synthetic.main.view_game_header.view.tv_game_number as gameNumber import kotlinx.android.synthetic.main.view_game_header.view.tv_next_ball as nextBall import kotlinx.android.synthetic.main.view_game_header.view.tv_prev_ball as prevBall /** * Copyright (C) 2018 Joseph Roque * * Header of a game which displays the game number and navigation buttons. */ class GameHeaderView : LinearLayout, View.OnClickListener { companion object { @Suppress("unused") private const val TAG = "GameHeaderView" private const val SUPER_STATE = "${TAG}_super_state" private const val STATE_CURRENT_GAME = "${TAG}_current_game" private const val STATE_NEXT_FRAME = "${TAG}_next_frame" private const val STATE_PREV_FRAME = "${TAG}_prev_frame" private const val STATE_MANUAL_SCORE = "${TAG}_manual" } var delegate: GameHeaderInteractionDelegate? = null var currentGame: Int = 0 set(value) { gameNumber.text = String.format(resources.getString(R.string.game_number), value + 1) } var hasPreviousFrame: Boolean = false set(value) { field = value invalidateButtons() } var hasNextFrame: Boolean = true set(value) { field = value invalidateButtons() } var isManualScoreSet: Boolean = false set(value) { field = value invalidateButtons() } // MARK: Constructors constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { LayoutInflater.from(context).inflate(R.layout.view_game_header, this, true) setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimaryLight)) gameNumber.text = String.format(resources.getString(R.string.game_number), currentGame + 1) nextBall.setOnClickListener(this) prevBall.setOnClickListener(this) } // MARK: Lifecycle functions override fun onSaveInstanceState(): Parcelable { return Bundle().apply { putParcelable(SUPER_STATE, super.onSaveInstanceState()) putInt(STATE_CURRENT_GAME, currentGame) putBoolean(STATE_NEXT_FRAME, hasNextFrame) putBoolean(STATE_PREV_FRAME, hasPreviousFrame) putBoolean(STATE_MANUAL_SCORE, isManualScoreSet) } } override fun onRestoreInstanceState(state: Parcelable?) { var superState: Parcelable? = null if (state is Bundle) { currentGame = state.getInt(STATE_CURRENT_GAME) hasNextFrame = state.getBoolean(STATE_NEXT_FRAME) hasPreviousFrame = state.getBoolean(STATE_PREV_FRAME) isManualScoreSet = state.getBoolean(STATE_MANUAL_SCORE) superState = state.getParcelable(SUPER_STATE) } super.onRestoreInstanceState(superState) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() delegate = null } // MARK: OnClickListener override fun onClick(v: View?) { val view = v ?: return when (view.id) { R.id.tv_prev_ball -> delegate?.onPrevBall() R.id.tv_next_ball -> delegate?.onNextBall() } } // MARK: Private functions private fun invalidateButtons() { val prevVisibility = if (!isManualScoreSet && hasPreviousFrame) View.VISIBLE else View.INVISIBLE prevBall.post { prevBall.visibility = prevVisibility } val nextVisibility = if (hasNextFrame) View.VISIBLE else View.INVISIBLE nextBall.post { nextBall.visibility = nextVisibility } } // MARK: GameHeaderInteractionDelegate interface GameHeaderInteractionDelegate { fun onNextBall() fun onPrevBall() } }
mit
23c4d03e46be0d2c96d35c27091a9392
33.424
114
0.673716
4.501046
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/search_nearest/SearchNearestActivity.kt
1
6477
package com.arcao.geocaching4locus.search_nearest import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.activity.result.contract.ActivityResultContract import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.widget.Toolbar import androidx.databinding.DataBindingUtil import com.arcao.geocaching4locus.R import com.arcao.geocaching4locus.authentication.LoginActivity import com.arcao.geocaching4locus.base.AbstractActionBarActivity import com.arcao.geocaching4locus.base.fragment.SliderDialogFragment import com.arcao.geocaching4locus.base.util.PermissionUtil import com.arcao.geocaching4locus.base.util.exhaustive import com.arcao.geocaching4locus.base.util.invoke import com.arcao.geocaching4locus.base.util.showLocusMissingError import com.arcao.geocaching4locus.base.util.withObserve import com.arcao.geocaching4locus.databinding.ActivitySearchNearestBinding import com.arcao.geocaching4locus.error.ErrorActivity import com.arcao.geocaching4locus.search_nearest.fragment.NoLocationPermissionErrorDialogFragment import com.arcao.geocaching4locus.search_nearest.fragment.NoLocationProviderDialogFragment import com.arcao.geocaching4locus.settings.SettingsActivity import com.arcao.geocaching4locus.settings.fragment.FilterPreferenceFragment import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class SearchNearestActivity : AbstractActionBarActivity(), SliderDialogFragment.DialogListener { private val viewModel by viewModel<SearchNearestViewModel> { parametersOf(intent) } private lateinit var binding: ActivitySearchNearestBinding private val settingsActivity = registerForActivityResult(SettingsActivity.Contract) {} private val requestLocationPermission = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions() ) { result -> if (result.all { it.value }) { viewModel.retrieveCoordinates() } else { NoLocationPermissionErrorDialogFragment.newInstance().show(supportFragmentManager) } } private val loginActivity = registerForActivityResult(LoginActivity.Contract) { success -> if (success) viewModel.download() } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_search_nearest) binding.lifecycleOwner = this binding.vm = viewModel @Suppress("USELESS_CAST") val toolbar = binding.toolbar as Toolbar val latitude = binding.incCoordinates.latitude val longitude = binding.incCoordinates.longitude setSupportActionBar(toolbar) val actionBar = supportActionBar if (actionBar != null) { actionBar.title = title actionBar.setDisplayHomeAsUpEnabled(true) } latitude.setOnFocusChangeListener { _, hasFocus -> if (!hasFocus) viewModel.formatCoordinates() } longitude.setOnFocusChangeListener { _, hasFocus -> if (!hasFocus) viewModel.formatCoordinates() } viewModel.action.withObserve(this, ::handleAction) viewModel.progress.withObserve(this, ::handleProgress) } @Suppress("IMPLICIT_CAST_TO_ANY") fun handleAction(action: SearchNearestAction) { when (action) { SearchNearestAction.SignIn -> loginActivity.launch(null) is SearchNearestAction.Error -> { startActivity(action.intent) setResult(Activity.RESULT_CANCELED) } is SearchNearestAction.Finish -> { startActivity(action.intent) setResult(Activity.RESULT_OK) finish() } is SearchNearestAction.LocusMapNotInstalled -> showLocusMissingError() SearchNearestAction.RequestGpsLocationPermission -> requestLocationPermission.launch( PermissionUtil.PERMISSION_LOCATION_GPS ) SearchNearestAction.RequestWifiLocationPermission -> requestLocationPermission.launch( PermissionUtil.PERMISSION_LOCATION_WIFI ) SearchNearestAction.WrongCoordinatesFormat -> startActivity( ErrorActivity.IntentBuilder(this) .message(R.string.error_coordinates_format) .build() ) SearchNearestAction.ShowFilters -> { settingsActivity.launch(FilterPreferenceFragment::class.java) } SearchNearestAction.LocationProviderDisabled -> NoLocationProviderDialogFragment.newInstance().show(supportFragmentManager) is SearchNearestAction.RequestCacheCount -> SliderDialogFragment.newInstance( title = R.string.title_geocache_count, min = action.step, max = action.max, step = action.step, defaultValue = action.value ).show(supportFragmentManager, "COUNTER") }.exhaustive } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.toolbar_search_nearest, menu) return true } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.main_activity_option_menu_preferences -> { settingsActivity.launch(null) true } android.R.id.home -> { finish() true } else -> super.onOptionsItemSelected(item) } override fun onProgressCancel(requestId: Int) { viewModel.cancelProgress() } // ---------------- SliderDialogFragment.DialogListener methods ---------------- override fun onDialogClosed(fragment: SliderDialogFragment) { viewModel.requestedCaches(fragment.getValue()) } object Contract : ActivityResultContract<Intent?, Boolean>() { override fun createIntent(context: Context, input: Intent?) = Intent(context, SearchNearestActivity::class.java).apply { input?.let { putExtras(it) } } override fun parseResult(resultCode: Int, intent: Intent?): Boolean { return resultCode == Activity.RESULT_OK } } }
gpl-3.0
d6ee24695274562027a54eb63247b216
39.735849
98
0.694149
5.231826
false
false
false
false
ajalt/clikt
samples/validation/src/main/kotlin/com/github/ajalt/clikt/samples/validation/main.kt
1
1388
package com.github.ajalt.clikt.samples.validation import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.convert import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.int import java.net.URL data class Quad(val a: Int, val b: Int, val c: Int, val d: Int) class Cli : CliktCommand(help = "Validation examples") { val count by option(help = "A positive even number").int() .check("Should be a positive, even integer") { it > 0 && it % 2 == 0 } val biggerCount by option(help = "A number larger than --count").int() .validate { require(count == null || count!! < it) { "--bigger-count must be larger than --count" } } val quad by option(help = "A four-valued option") .int() .transformValues(4) { Quad(it[0], it[1], it[2], it[3]) } val sum by option(help = "All values will be added") .int() .transformAll { it.sum() } val url by argument(help = "A URL") .convert { URL(it) } override fun run() { echo("count: $count") echo("biggerCount: $biggerCount") echo("quad: $quad") echo("sum: $sum") echo("url: $url") } } fun main(args: Array<String>) = Cli().main(args)
apache-2.0
915ccff8bb403211db3f29156ede81ef
31.27907
78
0.613112
3.549872
false
false
false
false
cketti/k-9
app/k9mail/src/main/java/com/fsck/k9/resources/K9CoreResourceProvider.kt
1
3088
package com.fsck.k9.resources import android.content.Context import com.fsck.k9.CoreResourceProvider import com.fsck.k9.notification.PushNotificationState import com.fsck.k9.ui.R class K9CoreResourceProvider(private val context: Context) : CoreResourceProvider { override fun defaultSignature(): String = context.getString(R.string.default_signature) override fun defaultIdentityDescription(): String = context.getString(R.string.default_identity_description) override fun contactDisplayNamePrefix(): String = context.getString(R.string.message_to_label) override fun contactUnknownSender(): String = context.getString(R.string.unknown_sender) override fun contactUnknownRecipient(): String = context.getString(R.string.unknown_recipient) override fun messageHeaderFrom(): String = context.getString(R.string.message_compose_quote_header_from) override fun messageHeaderTo(): String = context.getString(R.string.message_compose_quote_header_to) override fun messageHeaderCc(): String = context.getString(R.string.message_compose_quote_header_cc) override fun messageHeaderDate(): String = context.getString(R.string.message_compose_quote_header_send_date) override fun messageHeaderSubject(): String = context.getString(R.string.message_compose_quote_header_subject) override fun messageHeaderSeparator(): String = context.getString(R.string.message_compose_quote_header_separator) override fun noSubject(): String = context.getString(R.string.general_no_subject) override fun userAgent(): String = context.getString(R.string.message_header_mua) override fun encryptedSubject(): String = context.getString(R.string.encrypted_subject) override fun replyHeader(sender: String): String = context.getString(R.string.message_compose_reply_header_fmt, sender) override fun replyHeader(sender: String, sentDate: String): String = context.getString(R.string.message_compose_reply_header_fmt_with_date, sentDate, sender) override fun searchUnifiedInboxTitle(): String = context.getString(R.string.integrated_inbox_title) override fun searchUnifiedInboxDetail(): String = context.getString(R.string.integrated_inbox_detail) override fun outboxFolderName(): String = context.getString(R.string.special_mailbox_name_outbox) override val iconPushNotification: Int = R.drawable.ic_push_notification override fun pushNotificationText(notificationState: PushNotificationState): String { val resId = when (notificationState) { PushNotificationState.INITIALIZING -> R.string.push_notification_state_initializing PushNotificationState.LISTENING -> R.string.push_notification_state_listening PushNotificationState.WAIT_BACKGROUND_SYNC -> R.string.push_notification_state_wait_background_sync PushNotificationState.WAIT_NETWORK -> R.string.push_notification_state_wait_network } return context.getString(resId) } override fun pushNotificationInfoText(): String = context.getString(R.string.push_notification_info) }
apache-2.0
870fcca67bfd1cd015588cca3c1731be
58.384615
118
0.774611
4.294854
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/diagnostic/github/TranslationGitHubAppService.kt
1
2163
package cn.yiiguxing.plugin.translate.diagnostic.github import cn.yiiguxing.plugin.translate.diagnostic.github.auth.* import cn.yiiguxing.plugin.translate.message import cn.yiiguxing.plugin.translate.util.Application import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.util.concurrency.annotations.RequiresEdt import javax.swing.JComponent @Service internal class TranslationGitHubAppService private constructor() { companion object { private const val CLIENT_ID = "e8a353548fe014bb27de" private val SCOPES: Array<out String> = arrayOf("public_repo") val instance: TranslationGitHubAppService = service() } @RequiresEdt fun auth(project: Project?, parentComponent: JComponent?): GitHubCredentials? { Application.assertIsDispatchThread() val deviceCode = getDeviceCode(project, parentComponent) ?: return null val ok = GitHubDeviceLoginDialog(project, parentComponent, deviceCode).showAndGet() return if (ok) authorize(project, parentComponent, deviceCode) else null } private fun getDeviceCode(project: Project?, parentComponent: JComponent?): GitHubDeviceCode? { return try { GitHubDeviceCodeTask(project, parentComponent, CLIENT_ID, *SCOPES).queueAndGet() } catch (e: Exception) { val message = message("github.retrieving.device.code.failed.message", e.message.toString()) throw TranslationGitHubAppException(message, e) } } private fun authorize( project: Project?, parentComponent: JComponent?, deviceCode: GitHubDeviceCode ): GitHubCredentials? { return try { GitHubDeviceAuthTask(project, parentComponent, CLIENT_ID, deviceCode).queueAndGet() } catch (e: Exception) { val errorMessage = (e as? GitHubDeviceAuthException)?.errorDescription ?: e.message ?: "" val message = message("github.authentication.failed.message", errorMessage) throw TranslationGitHubAppException(message, e) } } }
mit
be9c1443cfbc63d6a53c31f2e2bfc81c
36.964912
103
0.714748
4.743421
false
false
false
false
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/shengshiyuan/helloworld/101.String.kt
1
1448
package com.zj.example.kotlin.shengshiyuan.helloworld /** * * CreateTime: 2019/1/21 09:37 * @author 郑炯 */ fun main(args: Array<String>) { val demo = Demo101() demo.test1() } class Demo101 { /* 创建字符串有两种方式:两种内存区域(pool,heap) 1," " 引号创建的字符串在字符串池中 2,new,new创建字符串时首先查看池中是否有相同值的字符串,如果有,则拷贝一份到堆中,然后返回堆中的地址; 如果池中没有,则在堆中创建一份,然后返回堆中的地址(注意,此时不需要从堆中复制到池中,否则, 将使得堆中的字符串永远是池中的子集,导致浪费池的空间)! 3.另外,对字符串进行赋值时,如果右操作数含有一个或一个以上的字符串引用时, 则在堆中再建立一个字符串对象,返回引用;如String s=str1+ "blog"; */ fun test1() { val str1 = "z" val str2 = "j" val str3 = str1 + str2 val str4 = "z" + "j" val str5 = str1 + "j" println(str3 == "zj") //true //kotlin中===才是比较内存地址 println(str3 === "zj") //false println(str3.equals("zj")) //true println(str4 === ("z" + "j")) //true println(str5 === ("z" + "j")) //false println(str5 === "zj") //false } }
mit
d75b9219bb702bb93bb8cd9ea3d73229
19.428571
59
0.54
2.409639
false
false
false
false
chillcoding-at-the-beach/my-cute-heart
MyCuteHeart/app/src/main/java/com/chillcoding/ilove/view/dialog/EndGameDialog.kt
1
3595
package com.chillcoding.ilove.view.dialog import android.app.AlertDialog import android.app.Dialog import android.app.DialogFragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import com.chillcoding.ilove.App import com.chillcoding.ilove.MainActivity import com.chillcoding.ilove.R import com.chillcoding.ilove.SecondActivity import com.chillcoding.ilove.extension.DelegatesExt import com.chillcoding.ilove.extension.playGame import com.chillcoding.ilove.extension.setUpNewGame import com.chillcoding.ilove.model.FragmentId import com.chillcoding.ilove.model.GameData import com.chillcoding.ilove.view.GameView import com.chillcoding.ilove.view.activity.AwardsActivity import kotlinx.android.synthetic.main.dialog_end_game.view.* import org.jetbrains.anko.share import org.jetbrains.anko.startActivity import java.util.* /** * Created by macha on 01/08/2017. */ class EndGameDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { var bestScore: Int by DelegatesExt.preference(activity, App.PREF_BEST_SCORE, 0) val builder = AlertDialog.Builder(activity) val successString = resources.getStringArray(R.array.word_success) val endGameView = (LayoutInflater.from(activity)).inflate(R.layout.dialog_end_game, null) val data = arguments.getParcelable<GameData>(App.STATE_GAME_DATA) endGameView.dialogTitleTextView.text = "${successString[Random().nextInt(successString.size)].toUpperCase()}!" endGameView.dialogScoreTextView.text = "${data.score}" endGameView.dialogLevelTextView.text = "${resources.getString(R.string.word_level)} ${data.level}" when { data.score < GameView.TAPS_PER_LEVEL -> { endGameView.dialogTitleTextView.text = getString(R.string.failure).toUpperCase() endGameView.dialogLevelTextView.text = getString(R.string.you_can_better_text) endGameView.starImageView.setColorFilter(App.sColors[1]) endGameView.middleStarImageView.setColorFilter(App.sColors[1]) endGameView.endStarImageView.setColorFilter(App.sColors[1]) } data.score > bestScore -> { bestScore = data.score endGameView.dialogBestTextView.visibility = View.VISIBLE endGameView.starImageView.setColorFilter(App.sColors[7]) endGameView.middleStarImageView.setColorFilter(App.sColors[7]) endGameView.endStarImageView.setColorFilter(App.sColors[7]) if (data.awardUnlocked) { endGameView.dialogAwardTextView.visibility = View.VISIBLE builder.setNegativeButton(R.string.action_see_awards, { _, _ -> startActivity<AwardsActivity>() }) } else builder.setNegativeButton(R.string.action_see_top, { _, _ -> startActivity<SecondActivity>(SecondActivity.FRAGMENT_ID to FragmentId.TOP.ordinal) }) } } val activity = (activity as MainActivity) val score = data.score activity.setUpNewGame() builder.setView(endGameView) .setPositiveButton(R.string.action_play, { _, _ -> activity.playGame(true) }) .setNeutralButton(R.string.action_share, { _, _ -> share("${getString(R.string.text_share_score)} ${score} <3 \n" + "${getString(R.string.text_from)} ${getString(R.string.url_app)}", "I Love") }) return builder.create() } }
gpl-3.0
aad1e5cb2fadbe6ba89558bb47126b23
48.930556
167
0.685953
4.12744
false
false
false
false
wakingrufus/mastodon-jfx
src/main/kotlin/com/github/wakingrufus/mastodon/ui/SettingsView.kt
1
4071
package com.github.wakingrufus.mastodon.ui import com.github.wakingrufus.mastodon.data.AccountState import com.github.wakingrufus.mastodon.data.NotificationFeed import com.github.wakingrufus.mastodon.data.StatusFeed import com.github.wakingrufus.mastodon.ui.styles.DefaultStyles import com.sys1yagi.mastodon4j.api.entity.Account import javafx.collections.ObservableList import javafx.geometry.Pos import javafx.scene.paint.Color import javafx.stage.StageStyle import mu.KLogging import tornadofx.* class SettingsView(accountFragment: (String, Account) -> AccountFragment = { s: String, a: Account -> find(params = mapOf("server" to s, "account" to a)) }) : View() { companion object : KLogging() val createAccount: () -> Unit by param() val accountStates: ObservableList<AccountState> by param() val viewFeed: (StatusFeed) -> Any by param() val viewNotifications: (NotificationFeed) -> Any by param() val newToot: () -> Any by param() override val root = vbox { style { minWidth = 30.em minHeight = 100.percent backgroundColor = multi(DefaultStyles.backdropColor) padding = CssBox(top = 1.px, right = 1.px, bottom = 1.px, left = 1.px) } vbox { style { id = "accountListWrapper" textFill = Color.WHITE minHeight = 100.percent backgroundColor = multi(DefaultStyles.backgroundColor) } children.bind(accountStates) { hbox { vbox { this += accountFragment(it.client.getInstanceName(), it.account) hbox { button("⌂") { addClass(DefaultStyles.smallButton) accessibleText = "Home" action { viewFeed(it.homeFeed) } } button("👥") { addClass(DefaultStyles.smallButton) accessibleText = "Public" action { viewFeed(it.publicFeed) } } button("🌎") { addClass(DefaultStyles.smallButton) accessibleText = "Federated" action { viewFeed(it.federatedFeed) } } button("🔔") { addClass(DefaultStyles.smallButton) accessibleText = "Notifications" action { viewNotifications(it.notificationFeed) } } button("📝") { addClass(DefaultStyles.smallButton) accessibleText = "New Toot" action { find<TootEditor>(mapOf("client" to it.client)).apply { openModal(stageStyle = StageStyle.UTILITY, block = true) } } } } } } } hbox { style { alignment = Pos.BOTTOM_CENTER maxHeight = 2.em minWidth = 100.percent } button { addClass(DefaultStyles.smallButton) text = "Add" setOnAction { createAccount() } } } } } }
mit
328098a3d6fa8f720bf20f9228fb5abd
39.989899
119
0.426177
5.888244
false
false
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/widget/RadarScanExView.kt
1
7413
package com.angcyo.uiview.widget import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.Choreographer import android.view.View import com.angcyo.uiview.R import com.angcyo.uiview.kotlin.density import com.angcyo.uiview.kotlin.getColor import com.angcyo.uiview.skin.SkinHelper /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:雷达扫描效果 * 创建人员:Robi * 创建时间:2017/06/08 11:46 * 修改人员:Robi * 修改时间:2017/06/08 11:46 * 修改备注: * Version: 1.0.0 */ class RadarScanExView(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet), Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { sweepAngle += 3 //控制扫描速度 mChoreographer.postFrameCallback(this) } /**田字格线之间的距离*/ var lineSpace = 10 * density private val lineCirclePath: Path by lazy { Path() } private val drawLinePath: Path by lazy { Path() } private val linePaint: Paint by lazy { Paint(Paint.ANTI_ALIAS_FLAG) } val paint: Paint by lazy { Paint(Paint.ANTI_ALIAS_FLAG) } var circleWidth = 2 * density var scanDrawRectF = RectF() val scanMatrix = Matrix() var sweepAngle = 0f set(value) { field = value % 360 scanMatrix.reset() scanMatrix.postRotate(field, (measuredWidth / 2).toFloat(), (measuredHeight / 2).toFloat()) postInvalidate() } val mChoreographer: Choreographer by lazy { Choreographer.getInstance() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val size = Math.min(measuredHeight, measuredWidth) setMeasuredDimension(size, size) } override fun onAttachedToWindow() { super.onAttachedToWindow() if (visibility == VISIBLE) { postFrameCallback() } } private fun postFrameCallback() { mChoreographer.removeFrameCallback(this) mChoreographer.postFrameCallback(this) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() mChoreographer.removeFrameCallback(this) } override fun onVisibilityChanged(changedView: View?, visibility: Int) { super.onVisibilityChanged(changedView, visibility) if (visibility == VISIBLE) { postFrameCallback() } else { mChoreographer.removeFrameCallback(this) } } override fun onDraw(canvas: Canvas) { //有效的绘制直径 val size = Math.min(measuredWidth, measuredHeight) val centerX = measuredWidth / 2 val centerY = measuredHeight / 2 var circleRadius = size / 2f //绘制田字格 canvas.save() lineCirclePath.reset() lineCirclePath.addCircle(centerX.toFloat(), centerY.toFloat(), circleRadius, Path.Direction.CW) canvas.clipPath(lineCirclePath) linePaint.color = getColor(R.color.default_base_line) linePaint.strokeWidth = 1 * density linePaint.style = Paint.Style.FILL_AND_STROKE val intervals = 1f * density linePaint.pathEffect = DashPathEffect(floatArrayOf(intervals, intervals), 0f) var lineTop = lineSpace while (lineTop < measuredHeight) { drawLinePath.reset() drawLinePath.moveTo(0.toFloat(), lineTop) drawLinePath.lineTo(measuredWidth.toFloat(), lineTop) canvas.drawPath(drawLinePath, linePaint) lineTop += lineSpace } var lineLeft = lineSpace while (lineLeft < measuredWidth) { drawLinePath.reset() drawLinePath.moveTo(lineLeft, 0.toFloat()) drawLinePath.lineTo(lineLeft, measuredHeight.toFloat()) canvas.drawPath(drawLinePath, linePaint) lineLeft += lineSpace } canvas.restore() //绘制扫描弧度 canvas.save() val shaderColor: Int val shaderStartColor: Int val lineColor: Int if (isInEditMode) { paint.color = SkinHelper.getTranColor(Color.RED, 0x40) lineColor = Color.GREEN shaderStartColor = SkinHelper.getTranColor(Color.RED, 0x40) shaderColor = SkinHelper.getTranColor(Color.RED, 0xFF) } else { paint.color = SkinHelper.getTranColor(SkinHelper.getSkin().themeSubColor, 0x40) lineColor = SkinHelper.getSkin().themeSubColor shaderStartColor = SkinHelper.getTranColor(SkinHelper.getSkin().themeSubColor, 0x40) shaderColor = SkinHelper.getTranColor(SkinHelper.getSkin().themeSubColor, 0xAA) //SkinHelper.getSkin().themeSubColor// SkinHelper.getTranColor(SkinHelper.getSkin().themeSubColor, 0xFF) } paint.style = Paint.Style.FILL_AND_STROKE paint.strokeWidth = circleWidth //圈的厚度 val arcOffset = circleWidth / 2 scanDrawRectF.set(centerX - circleRadius + arcOffset, centerY - circleRadius + arcOffset, centerX + circleRadius - arcOffset, centerY + circleRadius - arcOffset) //雷达区域扫描arc paint.shader = object : SweepGradient((measuredWidth / 2).toFloat(), (measuredWidth / 2).toFloat(), intArrayOf(Color.TRANSPARENT, shaderStartColor, shaderColor), floatArrayOf(0f, 0.6f, 1f)) { } if (!isInEditMode) { canvas.concat(scanMatrix) } canvas.drawArc(scanDrawRectF, 0f, 360f /*(36 * 6).toFloat()*/, true, paint) //外圈轮廓渐变arc paint.style = Paint.Style.STROKE paint.shader = object : SweepGradient((measuredWidth / 2).toFloat(), (measuredWidth / 2).toFloat(), intArrayOf(Color.TRANSPARENT, shaderStartColor, shaderColor), floatArrayOf(0f, 0.1f, 1f)) { } canvas.drawArc(scanDrawRectF, 0f, 360f /*(36 * 6).toFloat()*/, false, paint) //开始扫描线 paint.color = lineColor paint.style = Paint.Style.FILL_AND_STROKE paint.strokeWidth = 2 * circleWidth // drawLinePath.reset() // drawLinePath.moveTo(0.toFloat(), lineTop) // drawLinePath.lineTo(measuredWidth.toFloat(), lineTop) canvas.drawLine(centerX.toFloat(), centerY.toFloat(), measuredWidth.toFloat(), centerY.toFloat(), paint) canvas.restore() // //绘制圆圈 // canvas.save() // canvas.translate((measuredWidth / 2).toFloat(), (measuredHeight / 2).toFloat()) // paint.shader = object : LinearGradient(0f, 0f, (measuredWidth / 2).toFloat(), (measuredWidth / 2).toFloat(), // intArrayOf(Color.TRANSPARENT, Color.RED), floatArrayOf(0f, 1f), TileMode.CLAMP) { // } // paint.style = Paint.Style.FILL_AND_STROKE // paint.strokeWidth = circleWidth //圈的厚度 // canvas.drawCircle(0f, 0f, circleRadius - circleWidth / 2, paint) // // canvas.restore() } }
apache-2.0
1896c37dedb2d204cfba43a794e67d7d
33.191176
196
0.619758
4.305339
false
false
false
false
ngageoint/mage-android
mage/src/main/java/mil/nga/giat/mage/location/LocationFetchService.kt
1
2456
package mil.nga.giat.mage.location import android.content.Context import android.content.Intent import android.content.SharedPreferences import androidx.lifecycle.LifecycleService import androidx.lifecycle.lifecycleScope import dagger.hilt.android.AndroidEntryPoint import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import mil.nga.giat.mage.R import mil.nga.giat.mage.data.location.LocationRepository import javax.inject.Inject @AndroidEntryPoint class LocationFetchService : LifecycleService(), SharedPreferences.OnSharedPreferenceChangeListener { @Inject @ApplicationContext lateinit var context: Context @Inject lateinit var preferences: SharedPreferences @Inject lateinit var locationRepository: LocationRepository private var locationFetchFrequency: Long = 0 private var pollJob: Job? = null override fun onCreate() { super.onCreate() locationFetchFrequency = getLocationFetchFrequency() preferences.registerOnSharedPreferenceChangeListener(this) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) if (pollJob?.isActive != true) { startPoll() } return START_NOT_STICKY } override fun onDestroy() { super.onDestroy() preferences.unregisterOnSharedPreferenceChangeListener(this) stopPoll() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { if (key.equals(getString(R.string.userFetchFrequencyKey), ignoreCase = true)) { locationFetchFrequency = getLocationFetchFrequency() stopPoll() startPoll() } } private fun startPoll() { pollJob = poll() } private fun stopPoll() { pollJob?.cancel() } private fun poll(): Job { return lifecycleScope.launch { while (isActive) { locationRepository.fetch() delay(timeMillis = getLocationFetchFrequency()) } } } private fun getLocationFetchFrequency(): Long { return preferences.getInt(getString(R.string.userFetchFrequencyKey), resources.getInteger(R.integer.userFetchFrequencyDefaultValue)).toLong() } }
apache-2.0
c3fdc9d370e440a205de794b8c735647
27.894118
149
0.706026
5.106029
false
false
false
false
jiangkang/KTools
tools/src/main/java/com/jiangkang/tools/widget/KNotification.kt
1
4381
package com.jiangkang.tools.widget import android.app.* import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.drawable.Icon import android.os.Build import android.provider.Settings import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import com.jiangkang.tools.extend.notificationManager import kotlin.random.Random /** * Created by jiangkang on 2017/9/23. * description:快速创建通知栏 */ object KNotification { const val channelIdNormal = "ktools_channel_normal" const val shortcutInfoId = "ktools_shortcut_info_id" private const val requestCode = 1111 @JvmStatic fun createNotification(context: Context, @DrawableRes smallIconID: Int, title: String, content: String, intent: Intent): Int { val pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT) val notification = NotificationCompat.Builder(context, channelIdNormal) .setContentTitle(title) .setContentText(content) .setSmallIcon(smallIconID) .setAutoCancel(true) .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH) .setVisibility(NotificationCompat.VISIBILITY_SECRET) .addAction(android.R.drawable.ic_btn_speak_now, "Voice", pendingIntent) .build() val id = Random(System.currentTimeMillis()).nextInt() context.notificationManager.notify(id, notification) return id } fun createNotification(context: Context, @DrawableRes smallIconID: Int, bitmap: Bitmap, intent: Intent): Int { val pendingIntent = PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT) val notification = NotificationCompat.Builder(context, channelIdNormal) .setSmallIcon(smallIconID) .setAutoCancel(true) .setContentTitle("大图Notification") .setContentText("一个简单的描述") .setLargeIcon(bitmap) .setStyle(NotificationCompat.BigPictureStyle().bigPicture(bitmap)) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_HIGH) .setAutoCancel(true) .build() val id = Random(System.currentTimeMillis()).nextInt() context.notificationManager.notify(id, notification) return id } /** * 应用启动时调用 */ fun createNotificationChannel(context: Context) { val channel = NotificationChannel(channelIdNormal, channelIdNormal, NotificationManager.IMPORTANCE_HIGH).apply { description = "应用中的普通通知" } context.notificationManager.createNotificationChannel(channel) } fun openSettingsPage(context: Context) { val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS).apply { putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) putExtra(Settings.EXTRA_CHANNEL_ID, context.notificationManager.getNotificationChannel(channelIdNormal).id) } context.startActivity(intent) } @RequiresApi(Build.VERSION_CODES.R) inline fun <reified T : Activity> createBubble(context: Context) { val pendingIntent = PendingIntent.getActivity(context, 0, Intent(context, T::class.java), 0) val bubbleData = Notification.BubbleMetadata.Builder(shortcutInfoId) .setDesiredHeight(600) .setIcon(Icon.createWithResource(context, android.R.drawable.btn_star)) .setIntent(pendingIntent) .build() val chatBot = Person.Builder() .setBot(true) .setName("BubbleBot") .setImportant(true) .build() val notification = Notification.Builder(context, channelIdNormal) .setBubbleMetadata(bubbleData) .addPerson(chatBot) .build() val id = Random(System.currentTimeMillis()).nextInt() context.notificationManager.notify(id, notification) } }
mit
5f25c5492fa4ba32d6cc3565db73ac13
40.519231
130
0.670141
5.025611
false
false
false
false
Aidlab/Android-Example
app/src/main/java/com/aidlab/example/VitalsDataSource.kt
1
1283
package com.aidlab.example import java.nio.FloatBuffer class VitalsDataSource(private val maxSamples: Int = 1000) { //-- Public ------------------------------------------------------------------------------------ fun add(sample: Float) { i++ samples.add(sample) if( samples.size > maxSamples ) samples.removeAt(0) } fun clear() { i = 0 normalizedSamples.clear() samples.clear() } fun normalize(upperBound: Float = 1f, lowerBound: Float = -1f) { val currentMax = samples.max() ?: 0.0f val currentMin = samples.min() ?: 0.0f var maxmin = currentMax - currentMin if( maxmin == 0.0f ) maxmin = 1.0f for (i in 0 until samples.count()) { val sample = (((upperBound - lowerBound) * (samples[i] - currentMin)) / maxmin) + lowerBound normalizedSamples.put(i, sample) } } fun samples(): FloatBuffer? { return normalizedSamples } //-- Private ----------------------------------------------------------------------------------- private var i: Int = 0 private var normalizedSamples: FloatBuffer = FloatBuffer.allocate(maxSamples) private var samples: MutableList<Float> = ArrayList() }
mit
fa3b4898beaeb4efebd1a15ef56ec59c
24.66
104
0.509743
4.582143
false
false
false
false
kharchenkovitaliypt/AndroidMvp
sample/src/main/java/com/idapgroup/android/mvpsample/SampleActivity.kt
1
2147
package com.idapgroup.android.mvpsample import android.app.ProgressDialog import android.os.Bundle import android.support.v7.app.AlertDialog import android.widget.TextView import com.idapgroup.android.mvp.impl.BasePresenterActivity class SampleActivity : BasePresenterActivity<SampleMvp.View, SampleMvp.Presenter>(), SampleMvp.View { var loadDialog: ProgressDialog? = null override fun onCreatePresenter() = SamplePresenter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.screen_sample) findViewById(R.id.ask).setOnClickListener { val question = (findViewById(R.id.question) as TextView).text presenter.onAsk(question.toString()) } findViewById(R.id.confirm).setOnClickListener { presenter.onConfirm() } findViewById(R.id.takeUntilDetachView).setOnClickListener { presenter.takeUntilDetachView() } if (savedInstanceState != null) { if(savedInstanceState.getBoolean("load_dialog_shown", false)) { showLoad() } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean("load_dialog_shown", loadDialog != null) } override fun goToMain() { finish() } override fun showMessage(message: String) { (findViewById(R.id.result) as TextView).text = message } override fun showLoad() { val loadDialog = ProgressDialog(this) loadDialog.setMessage("Processing...") loadDialog.isIndeterminate = true loadDialog.setCancelable(false) loadDialog.setCanceledOnTouchOutside(false) loadDialog.show() this.loadDialog = loadDialog } override fun hideLoad() { loadDialog!!.hide() loadDialog = null } override fun showError(error: Throwable) { AlertDialog.Builder(this) .setMessage(error.toString()) .setPositiveButton(android.R.string.ok, { _, _ -> }) .show() } }
apache-2.0
04ac39c769d1a58ce6b42b3e763cd090
30.115942
101
0.653936
4.913043
false
false
false
false
toastkidjp/Jitte
article/src/main/java/jp/toastkid/article_viewer/article/list/ArticleListFragment.kt
1
13900
/* * Copyright (c) 2019 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.article_viewer.article.list import android.app.Activity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.annotation.LayoutRes import androidx.core.graphics.ColorUtils import androidx.core.view.isVisible import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import jp.toastkid.article_viewer.R import jp.toastkid.article_viewer.article.ArticleRepository import jp.toastkid.article_viewer.article.data.AppDatabase import jp.toastkid.article_viewer.article.list.date.DateFilterDialogFragment import jp.toastkid.article_viewer.article.list.date.FilterByMonthUseCase import jp.toastkid.article_viewer.article.list.listener.ArticleLoadStateListener import jp.toastkid.article_viewer.article.list.menu.ArticleListMenuPopupActionUseCase import jp.toastkid.article_viewer.article.list.menu.MenuPopup import jp.toastkid.article_viewer.article.list.sort.Sort import jp.toastkid.article_viewer.article.list.sort.SortSettingDialogFragment import jp.toastkid.article_viewer.article.list.usecase.UpdateUseCase import jp.toastkid.article_viewer.bookmark.BookmarkFragment import jp.toastkid.article_viewer.databinding.AppBarArticleListBinding import jp.toastkid.article_viewer.databinding.FragmentArticleListBinding import jp.toastkid.article_viewer.zip.ZipFileChooserIntentFactory import jp.toastkid.article_viewer.zip.ZipLoaderService import jp.toastkid.lib.AppBarViewModel import jp.toastkid.lib.ContentScrollable import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.input.Inputs import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.lib.tab.OnBackCloseableTabUiFragment import jp.toastkid.lib.view.RecyclerViewScroller import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.debounce import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Article list fragment. * * @author toastkidjp */ class ArticleListFragment : Fragment(), ContentScrollable, OnBackCloseableTabUiFragment { /** * List item adapter. */ private lateinit var adapter: Adapter private lateinit var binding: FragmentArticleListBinding private lateinit var appBarBinding: AppBarArticleListBinding /** * Preferences wrapper. */ private lateinit var preferencesWrapper: PreferenceApplier /** * Use for read articles from DB. */ private lateinit var articleRepository: ArticleRepository /** * Use for receiving broadcast. */ private val progressBroadcastReceiver = object : BroadcastReceiver() { override fun onReceive(p0: Context?, p1: Intent?) { viewModel?.hideProgress() showFeedback() } private fun showFeedback() { contentViewModel?.snackShort(R.string.message_done_import) } } private var contentViewModel: ContentViewModel? = null private var viewModel: ArticleListFragmentViewModel? = null private var searchUseCase: ArticleSearchUseCase? = null private val inputChannel = Channel<String>() private val setTargetLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode != Activity.RESULT_OK) { return@registerForActivityResult } UpdateUseCase(viewModel) { context }.invokeIfNeed(it.data?.data) } override fun onAttach(context: Context) { super.onAttach(context) preferencesWrapper = PreferenceApplier(context) context.registerReceiver( progressBroadcastReceiver, ZipLoaderService.makeProgressBroadcastIntentFilter() ) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) context?.let { initializeRepository(it) } setHasOptionsMenu(true) } private fun initializeRepository(activityContext: Context) { val dataBase = AppDatabase.find(activityContext) articleRepository = dataBase.articleRepository() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { super.onCreateView(inflater, container, savedInstanceState) binding = DataBindingUtil.inflate( inflater, LAYOUT_ID, container, false) appBarBinding = DataBindingUtil.inflate( inflater, R.layout.app_bar_article_list, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val activityContext = activity ?: return contentViewModel = ViewModelProvider(activityContext).get(ContentViewModel::class.java) val menuPopup = MenuPopup( activityContext, ArticleListMenuPopupActionUseCase( articleRepository, AppDatabase.find(activityContext).bookmarkRepository(), { adapter.refresh() contentViewModel?.snackWithAction( "Deleted: \"${it.title}\".", "UNDO" ) { CoroutineScope(Dispatchers.IO).launch { articleRepository.insert(it) } } } ) ) adapter = Adapter( LayoutInflater.from(context), { contentViewModel?.newArticle(it) }, { contentViewModel?.newArticleOnBackground(it) }, { itemView, searchResult -> menuPopup.show(itemView, searchResult) } ) binding.results.adapter = adapter binding.results.layoutManager = LinearLayoutManager(activityContext, RecyclerView.VERTICAL, false) activity?.let { val activityViewModel = ViewModelProvider(it).get(ArticleListFragmentViewModel::class.java) activityViewModel.search.observe(it, { searchInput -> searchUseCase?.search(searchInput) if (appBarBinding.input.text.isNullOrEmpty()) { appBarBinding.input.setText(searchInput) appBarBinding.searchClear.isVisible = searchInput?.length != 0 } }) appBarBinding.input.setOnEditorActionListener { textView, _, _ -> val keyword = textView.text.toString() activityViewModel.search(keyword) Inputs.hideKeyboard(appBarBinding.input) true } } appBarBinding.searchClear.setOnClickListener { appBarBinding.input.setText("") viewModel?.clearSearchWord() } appBarBinding.input.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) = Unit override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit override fun onTextChanged(charSequence: CharSequence?, p1: Int, p2: Int, p3: Int) { CoroutineScope(Dispatchers.Default).launch { inputChannel.send(charSequence.toString()) } appBarBinding.searchClear.isVisible = charSequence?.length != 0 } }) CoroutineScope(Dispatchers.Default).launch { inputChannel.receiveAsFlow() .distinctUntilChanged() .debounce(1400L) .collect { withContext(Dispatchers.Main) { searchUseCase?.filter(it) } } } viewModel = ViewModelProvider(this).get(ArticleListFragmentViewModel::class.java) viewModel?.progressVisibility?.observe(viewLifecycleOwner, { it?.getContentIfNotHandled()?.let { isVisible -> binding.progressCircular.isVisible = isVisible } }) viewModel?.progress?.observe(viewLifecycleOwner, { it?.getContentIfNotHandled()?.let { message -> appBarBinding.searchResult.text = message } }) viewModel?.messageId?.observe(viewLifecycleOwner, { it?.getContentIfNotHandled()?.let { messageId -> appBarBinding.searchResult.setText(messageId) } }) viewModel?.sort?.observe(viewLifecycleOwner, { it?.getContentIfNotHandled()?.let { searchUseCase?.all() } }) viewModel?.filter?.observe(viewLifecycleOwner, { val keyword = it ?: return@observe searchUseCase?.filter(keyword, true) }) parentFragmentManager.setFragmentResultListener( "sorting", viewLifecycleOwner, { key, result -> val sort = result[key] as? Sort ?: return@setFragmentResultListener viewModel?.sort(sort) } ) parentFragmentManager.setFragmentResultListener( "date_filter", viewLifecycleOwner, { _, result -> val year = result.getInt("year") val month = result.getInt("month") FilterByMonthUseCase( ViewModelProvider(this).get(ArticleListFragmentViewModel::class.java) ).invoke(year, month) } ) searchUseCase = ArticleSearchUseCase( ListLoaderUseCase(adapter), articleRepository, preferencesWrapper ) adapter.addLoadStateListener( ArticleLoadStateListener(contentViewModel, { adapter.itemCount }, { activityContext.getString(it) }) ) searchUseCase?.search(appBarBinding.input.text?.toString()) } override fun onResume() { super.onResume() preferencesWrapper.colorPair().setTo(appBarBinding.input) val buttonColor = ColorUtils.setAlphaComponent(preferencesWrapper.fontColor, 196) appBarBinding.input.setHintTextColor(buttonColor) appBarBinding.searchClear.setColorFilter(buttonColor) activity?.let { ViewModelProvider(it).get(AppBarViewModel::class.java) .replace(appBarBinding.root) } } override fun onCreateOptionsMenu(menu: Menu, menuInflater: MenuInflater) { super.onCreateOptionsMenu(menu, menuInflater) menuInflater.inflate(R.menu.menu_article_list, menu) menu.findItem(R.id.action_switch_title_filter)?.isChecked = preferencesWrapper.useTitleFilter() } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_all_article -> { activity?.let { ViewModelProvider(it).get(ArticleListFragmentViewModel::class.java) .search(null) } true } R.id.action_bookmark -> { contentViewModel?.nextFragment(BookmarkFragment::class.java) true } R.id.action_set_target -> { setTargetLauncher.launch(ZipFileChooserIntentFactory()()) true } R.id.action_sort -> { val dialogFragment = SortSettingDialogFragment() dialogFragment.show(parentFragmentManager, "") true } R.id.action_date_filter -> { val dateFilterDialogFragment = DateFilterDialogFragment() dateFilterDialogFragment.show(parentFragmentManager, "") true } R.id.action_switch_title_filter -> { val newState = !item.isChecked preferencesWrapper.switchUseTitleFilter(newState) item.isChecked = newState true } else -> super.onOptionsItemSelected(item) } } override fun toTop() { RecyclerViewScroller.toTop(binding.results, adapter.itemCount) } override fun toBottom() { RecyclerViewScroller.toBottom(binding.results, adapter.itemCount) } override fun onDetach() { searchUseCase?.dispose() inputChannel.cancel() context?.unregisterReceiver(progressBroadcastReceiver) setTargetLauncher.unregister() parentFragmentManager.clearFragmentResultListener("sorting") parentFragmentManager.clearFragmentResultListener("date_filter") super.onDetach() } companion object { @LayoutRes private val LAYOUT_ID = R.layout.fragment_article_list } }
epl-1.0
aa00b43d9fb462d196eb2e6d4a12890e
35.106494
112
0.648417
5.463836
false
false
false
false
7hens/KDroid
core/src/main/java/cn/thens/kdroid/core/log/PrettyPrinter.kt
1
2136
package cn.thens.kdroid.core.log class PrettyPrinter(private val printer: LinePrinter) : StoryPrinter, PrettyIgnored { val settings = PrettySettings() private val style: PrettyStyle get() = settings.style private val chunkPrinter = ChunkPrinter(LinePrinter { message -> printer.print(style.middle + message) }) override fun print(message: String) { printer.printIfNotEmpty(style.top) printHeader(settings.methodCount) printer.printIfNotEmpty(style.divider) chunkPrinter.print(message) printer.printIfNotEmpty(style.bottom) } private fun IPrinter.printIfNotEmpty(text: String) { if (text.isNotEmpty()) print(text) } private fun printHeader(methodCount: Int) { val trace = Thread.currentThread().stackTrace val stackOffset = getStackOffset(trace) + settings.methodOffset val headerLineCount = Math.min(methodCount, trace.size - 1 - stackOffset) var offset = "" for (i in 0 until headerLineCount) { val stackIndex = i + stackOffset printer.print(settings.style.middle + offset + trace[stackIndex].prettyInfo()) offset += " " } } private fun StackTraceElement.prettyInfo(): String { val className = className.substring(className.lastIndexOf(".") + 1) val threadName = Thread.currentThread().name // val spaceLength = 100 - (className.length + methodName.length + fileName.length) // val spaces = if (spaceLength <= 0) "" else (0..spaceLength).joinToString("") { " " } return "$className.$methodName ($fileName:$lineNumber) on Thread: $threadName" } private fun getStackOffset(trace: Array<StackTraceElement>): Int { var isInOffsetClass = false for (i in 0 until trace.size) { val traceElement = trace[i] val cls = Class.forName(traceElement.className) if (PrettyIgnored::class.java.isAssignableFrom(cls)) { isInOffsetClass = true } else if (isInOffsetClass) { return i } } return 0 } }
apache-2.0
196bd3d1898e3f637d8951efa139cf39
37.854545
109
0.639045
4.477987
false
false
false
false
GoogleCloudPlatform/bigquery-utils
tools/sql_extraction/src/test/kotlin/output/QueryFragmentTest.kt
1
3200
package com.google.cloud.sqlecosystem.sqlextraction.output import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.RelaxedMockK import org.junit.Before import kotlin.test.Test import kotlin.test.assertEquals class QueryFragmentTest { @RelaxedMockK lateinit var location: Location @RelaxedMockK lateinit var literalA: QueryFragment @RelaxedMockK lateinit var literalB: QueryFragment @Before fun setUp() = MockKAnnotations.init(this) @Test fun `toCombinedString for literal`() { val fragment = QueryFragment.createLiteral( FragmentCount.SINGLE, location, "test" ) val result = fragment.toCombinedString() assertEquals("test", result) } @Test fun `toCombinedString for optional literal`() { val fragment = QueryFragment.createLiteral( FragmentCount.OPTIONAL, location, "test" ) val result = fragment.toCombinedString() assertEquals("test?", result) } @Test fun `toCombinedString for multiple literal`() { val fragment = QueryFragment.createLiteral( FragmentCount.MULTIPLE, location, "test" ) val result = fragment.toCombinedString() assertEquals("test*", result) } @Test fun `toCombinedString for complex and`() { every { literalA.toCombinedString() } returns "testA" every { literalB.toCombinedString() } returns "testB" val fragment = QueryFragment.createComplex( FragmentCount.SINGLE, listOf(literalA, literalB), ComplexType.AND ) val result = fragment.toCombinedString() assertEquals("(testAtestB)", result) } @Test fun `toCombinedString for complex or`() { every { literalA.toCombinedString() } returns "testA" every { literalB.toCombinedString() } returns "testB" val fragment = QueryFragment.createComplex( FragmentCount.SINGLE, listOf(literalA, literalB), ComplexType.OR ) val result = fragment.toCombinedString() assertEquals("(testA|testB)", result) } @Test fun `toCombinedString for complex and optional`() { every { literalA.toCombinedString() } returns "testA" every { literalB.toCombinedString() } returns "testB" val fragment = QueryFragment.createComplex( FragmentCount.OPTIONAL, listOf(literalA, literalB), ComplexType.AND ) val result = fragment.toCombinedString() assertEquals("(testAtestB)?", result) } @Test fun `toCombinedString for complex and multiple`() { every { literalA.toCombinedString() } returns "testA" every { literalB.toCombinedString() } returns "testB" val fragment = QueryFragment.createComplex( FragmentCount.MULTIPLE, listOf(literalA, literalB), ComplexType.OR ) val result = fragment.toCombinedString() assertEquals("(testA|testB)*", result) } }
apache-2.0
53cb7c424c105da64975cecdc2f4ec8c
24.608
61
0.619688
4.657933
false
true
false
false
Kotlin/dokka
plugins/javadoc/src/main/kotlin/org/jetbrains/dokka/javadoc/renderer/JavadocContentToTemplateMapTranslator.kt
1
14273
package org.jetbrains.dokka.javadoc.renderer import org.jetbrains.dokka.javadoc.location.JavadocLocationProvider import org.jetbrains.dokka.javadoc.pages.* import org.jetbrains.dokka.javadoc.toNormalized import org.jetbrains.dokka.Platform import org.jetbrains.dokka.base.renderers.sourceSets import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.links.parent import org.jetbrains.dokka.links.sureClassNames import org.jetbrains.dokka.model.ImplementedInterfaces import org.jetbrains.dokka.model.InheritedMember import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.utilities.formatToEndWithHtml import java.io.File import java.nio.file.Paths internal class JavadocContentToTemplateMapTranslator( private val locationProvider: JavadocLocationProvider, private val context: DokkaContext, ) { fun templateMapForPageNode(node: JavadocPageNode): TemplateMap = mapOf( "docName" to "docName", // todo docname "pathToRoot" to pathToRoot(node), "contextRoot" to node, "kind" to "main", ) + templateMapForNode(node) private fun templateMapForNode(node: JavadocPageNode): TemplateMap = when (node) { is JavadocModulePageNode -> InnerTranslator(node).templateMapForJavadocContentNode(node.content) is JavadocClasslikePageNode -> InnerTranslator(node).templateMapForClasslikeNode(node) is JavadocPackagePageNode -> InnerTranslator(node).templateMapForPackagePageNode(node) is TreeViewPage -> InnerTranslator(node).templateMapForTreeViewPage(node) is AllClassesPage -> InnerTranslator(node).templateMapForAllClassesPage(node) is IndexPage -> InnerTranslator(node).templateMapForIndexPage(node) is DeprecatedPage -> InnerTranslator(node).templateMapForDeprecatedPage(node) else -> emptyMap() } private fun pathToRoot(node: JavadocPageNode): String { return when (node) { is JavadocModulePageNode -> "" else -> run { val link = locationProvider.resolve(node, skipExtension = true) val dir = Paths.get(link).parent?.toNormalized().orEmpty() return dir.split(File.separator).filter { it.isNotEmpty() }.joinToString("/") { ".." }.let { if (it.isNotEmpty()) "$it/" else it } } } } private inner class InnerTranslator(val contextNode: JavadocPageNode) { private val htmlTranslator = JavadocContentToHtmlTranslator(locationProvider, context) fun templateMapForAllClassesPage(node: AllClassesPage): TemplateMap = mapOf( "title" to "All Classes", "list" to node.classEntries ) fun templateMapForIndexPage(node: IndexPage): TemplateMap = mapOf( "id" to node.id, "title" to node.title, "kind" to "indexPage", "prevLetter" to if (node.id > 1) "index-${node.id - 1}" else "", "nextLetter" to if (node.id < node.keys.size) "index-${node.id + 1}" else "", "dictionary" to node.keys, "elements" to node.elements.map { templateMapForIndexableNode(it) } ) fun templateMapForDeprecatedPage(node: DeprecatedPage): TemplateMap = mapOf( "id" to node.name, "title" to "Deprecated", "kind" to "deprecated", "sections" to node.elements.toList().sortedBy { (section, _) -> section.getPosition() } .map { (s, e) -> templateMapForDeprecatedPageSection(s, e) } ) fun templateMapForDeprecatedPageSection( section: DeprecatedPageSection, elements: Set<DeprecatedNode> ): TemplateMap = mapOf( "id" to section.id, "header" to section.header, "caption" to section.caption, "elements" to elements.map { node -> mapOf( "name" to node.name, "address" to locationProvider.resolve(node.address, contextNode.sourceSets(), contextNode) ?.formatToEndWithHtml().orEmpty(), "description" to htmlForContentNodes(node.description, contextNode) ) } ) fun templateMapForTreeViewPage(node: TreeViewPage): TemplateMap = mapOf( "title" to node.title, "name" to node.name, "kind" to node.kind, "list" to node.packages.orEmpty() + node.classes.orEmpty(), "classGraph" to node.classGraph, "interfaceGraph" to node.interfaceGraph ) fun templateMapForPackagePageNode(node: JavadocPackagePageNode): TemplateMap = mapOf( "kind" to "package" ) + templateMapForJavadocContentNode(node.content) fun templateMapForFunctionNode(node: JavadocFunctionNode): TemplateMap = mapOf( "brief" to htmlForContentNodes(node.brief, contextNode), "description" to htmlForContentNodes(node.description,contextNode), "parameters" to node.parameters.map { templateMapForParameterNode(it) }, "inlineParameters" to node.parameters.joinToString { renderInlineParameter(it) }, "anchorLink" to node.getAnchor(), "signature" to templateMapForSignatureNode(node.signature), "name" to node.name ) fun templateMapForClasslikeNode(node: JavadocClasslikePageNode): TemplateMap = mapOf( "constructors" to node.constructors.map { templateMapForFunctionNode(it) }, "signature" to templateMapForSignatureNode(node.signature), "methods" to templateMapForClasslikeMethods(node.methods), "classlikeDocumentation" to htmlForContentNodes(node.description, node), "entries" to node.entries.map { templateMapForEntryNode(it) }, "properties" to node.properties.map { templateMapForPropertyNode(it) }, "classlikes" to node.classlikes.map { templateMapForNestedClasslikeNode(it) }, "implementedInterfaces" to templateMapForImplementedInterfaces(node).sorted(), "kind" to node.kind, "packageName" to node.packageName, "name" to node.name ) + templateMapForJavadocContentNode(node.content) fun templateMapForSignatureNode(node: JavadocSignatureContentNode): TemplateMap = mapOf( "annotations" to node.annotations?.let { htmlForContentNode(it, contextNode) }, "signatureWithoutModifiers" to htmlForContentNode(node.signatureWithoutModifiers, contextNode), "modifiers" to node.modifiers?.let { htmlForContentNode(it, contextNode) }, "supertypes" to node.supertypes?.let { htmlForContentNode(it, contextNode) } ) private fun NavigableJavadocNode.typeForIndexable() = when (this) { is JavadocClasslikePageNode -> "class" is JavadocFunctionNode -> "function" is JavadocEntryNode -> "enum entry" is JavadocParameterNode -> "parameter" is JavadocPropertyNode -> "property" is JavadocPackagePageNode -> "package" else -> "" } fun templateMapForIndexableNode(node: NavigableJavadocNode): TemplateMap { val origin = node.getDRI().parent return mapOf( "address" to locationProvider.resolve(node.getDRI(), contextNode.sourceSets(), contextNode) ?.formatToEndWithHtml().orEmpty(), "type" to node.typeForIndexable(), "isMember" to (node !is JavadocPackagePageNode), "name" to if (node is JavadocFunctionNode) node.getAnchor() else node.getId(), "description" to ((node as? WithBrief)?.let { htmlForContentNodes( it.brief, contextNode ).takeIf { desc -> desc.isNotBlank() } } ?: "&nbsp;"), "origin" to origin.indexableOriginSignature(), ) } private fun DRI.indexableOriginSignature(): String { val packageName = packageName?.takeIf { it.isNotBlank() } val className = classNames?.let { "<a href=${locationProvider.resolve(this, contextNode.sourceSets(), contextNode) ?.formatToEndWithHtml().orEmpty()}>$it</a>" } return listOfNotNull(packageName, className).joinToString(".") } fun templateMapForJavadocContentNode(node: JavadocContentNode): TemplateMap = when (node) { is TitleNode -> templateMapForTitleNode(node) is JavadocContentGroup -> templateMapForJavadocContentGroup(node) is LeafListNode -> templateMapForLeafListNode(node) is RootListNode -> templateMapForRootListNode(node) else -> emptyMap() } fun templateMapForJavadocContentNode(node: ContentNode): TemplateMap = (node as? JavadocContentNode)?.let { templateMapForJavadocContentNode(it) } ?: emptyMap() private fun templateMapForParameterNode(node: JavadocParameterNode): TemplateMap = mapOf( "description" to htmlForContentNodes(node.description, contextNode), "name" to node.name, "type" to htmlForContentNode(node.type, contextNode) ) private fun templateMapForImplementedInterfaces(node: JavadocClasslikePageNode) = node.extra[ImplementedInterfaces]?.interfaces?.entries?.firstOrNull { it.key.analysisPlatform == Platform.jvm }?.value?.map { it.dri.displayable() } // TODO: REMOVE HARDCODED JVM DEPENDENCY .orEmpty() private fun templateMapForClasslikeMethods(nodes: List<JavadocFunctionNode>): TemplateMap { val (inherited, own) = nodes.partition { it.isInherited } return mapOf( "own" to own.map { templateMapForFunctionNode(it) }, "inherited" to inherited.map { templateMapForInheritedMethod(it) } .groupBy { it["inheritedFrom"] as String }.entries.map { mapOf( "inheritedFrom" to it.key, "names" to it.value.map { it["name"] as String }.sorted().joinToString() ) } ) } private fun templateMapForInheritedMethod(node: JavadocFunctionNode): TemplateMap { val inheritedFrom = node.extra[InheritedMember]?.inheritedFrom return mapOf( "inheritedFrom" to inheritedFrom?.entries?.firstOrNull { it.key.analysisPlatform == Platform.jvm }?.value?.displayable() // TODO: REMOVE HARDCODED JVM DEPENDENCY .orEmpty(), "name" to node.name ) } private fun templateMapForNestedClasslikeNode(node: JavadocClasslikePageNode): TemplateMap { return mapOf( "modifiers" to node.signature.modifiers?.let { htmlForContentNode(it, contextNode) }, "signature" to node.name, "address" to locationProvider.resolve( contextNode.children.first { (it as? JavadocClasslikePageNode)?.dri?.first() == node.dri.first() }, contextNode ).formatToEndWithHtml(), "description" to htmlForContentNodes(node.description, node) ) } private fun templateMapForPropertyNode(node: JavadocPropertyNode): TemplateMap { return mapOf( "modifiers" to node.signature.modifiers?.let { htmlForContentNode(it, contextNode) }, "signature" to htmlForContentNode(node.signature.signatureWithoutModifiers, contextNode), "description" to htmlForContentNodes(node.brief, contextNode) ) } private fun templateMapForEntryNode(node: JavadocEntryNode): TemplateMap { return mapOf( "signature" to templateMapForSignatureNode(node.signature), "brief" to htmlForContentNodes(node.brief, contextNode) ) } private fun templateMapForTitleNode(node: TitleNode): TemplateMap { return mapOf( "title" to node.title, "subtitle" to htmlForContentNodes(node.subtitle, contextNode), "version" to node.version, "packageName" to node.parent ) } private fun templateMapForJavadocContentGroup(note: JavadocContentGroup): TemplateMap { return note.children.fold(emptyMap()) { map, child -> map + templateMapForJavadocContentNode(child) } } private fun templateMapForLeafListNode(node: LeafListNode): TemplateMap { return mapOf( "tabTitle" to node.tabTitle, "colTitle" to node.colTitle, "list" to node.entries ) } private fun templateMapForRootListNode(node: RootListNode): TemplateMap { return mapOf( "lists" to node.entries.map { templateMapForLeafListNode(it) } ) } private fun renderInlineParameter(parameter: JavadocParameterNode): String = htmlForContentNode(parameter.type, contextNode) + " ${parameter.name}" private fun htmlForContentNode(node: ContentNode, relativeNode: PageNode) = htmlTranslator.htmlForContentNode(node, relativeNode) private fun htmlForContentNodes(nodes: List<ContentNode>, relativeNode: PageNode) = htmlTranslator.htmlForContentNodes(nodes, relativeNode) } private fun DRI.displayable(): String = "${packageName}.${sureClassNames}" }
apache-2.0
de5c622d63190a4778bfa8c6ce6cfffe
46.105611
201
0.611084
4.879658
false
false
false
false
rpradal/OCTOMeuh
app/src/main/kotlin/com/octo/mob/octomeuh/transversal/injection/AppModule.kt
1
1442
package com.octo.mob.octomeuh.transversal.injection import android.app.Application import android.content.Context import android.content.SharedPreferences import android.media.AudioManager import android.preference.PreferenceManager import com.google.firebase.analytics.FirebaseAnalytics import com.octo.mob.octomeuh.countdown.manager.PreferencesPersistor import com.octo.mob.octomeuh.countdown.manager.PreferencesPersistorImpl import com.octo.mob.octomeuh.transversal.AnalyticsManager import com.octo.mob.octomeuh.transversal.AnswersAnalyticsManager import dagger.Module import dagger.Provides import javax.inject.Singleton @Module class AppModule(private val application: Application) { @Provides @Singleton fun providesAppManager(firebaseAnalytics: FirebaseAnalytics): AnalyticsManager = AnswersAnalyticsManager(application, firebaseAnalytics) @Provides @Singleton fun providesFirebaseAnalytics(): FirebaseAnalytics = FirebaseAnalytics.getInstance(application) @Provides @Singleton fun providesSharedPreferences(): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(application) @Provides @Singleton fun providesPreferencesPersistor(sharedPreferences: SharedPreferences): PreferencesPersistor = PreferencesPersistorImpl(sharedPreferences) @Provides fun providesAudioManager(): AudioManager = application.getSystemService(Context.AUDIO_SERVICE) as AudioManager }
mit
8724d1bbc45729ad1067e1706afc9f0f
36.973684
142
0.837032
5.400749
false
false
false
false
Ex-Silicium/scripture-core
src/main/kotlin/com/exsilicium/scripture/shared/model/Verse.kt
1
1611
package com.exsilicium.scripture.shared.model /** * A verse with a chapter, number, and optional part letter (i.e. 'a', 'b', 'c', or 'd'). */ data class Verse( val chapter: Int, val verseNumber: Int, val part: Char? = null ) : Comparable<Verse> { init { require(chapter >= 0) require(verseNumber >= 0) require(part == null || part in MIN_PART_CHAR..MAX_PART_CHAR) } override fun compareTo(other: Verse): Int { return chapter.compareTo(other.chapter).let { if (it != 0) it else verseNumber.compareTo(other.verseNumber).let { when { it != 0 -> it part == null -> if (other.part == null) 0 else -1 else -> if (other.part == null) 1 else part.compareTo(other.part) } } } } override fun toString(): String { val chapterAndVerse = "$chapter:$verseNumber" return if (part == null) chapterAndVerse else "$chapterAndVerse$part" } internal fun verseNumberAndPart(): String { return if (part == null) verseNumber.toString() else "$verseNumber$part" } @Throws(UnsupportedOperationException::class) internal operator fun minus(other: Verse): Int { if (chapter == other.chapter) { return verseNumber - other.verseNumber } throw UnsupportedOperationException("Cannot subtract verse with different chapter") } companion object { internal const val MIN_PART_CHAR = 'a' internal const val MAX_PART_CHAR = 'd' } }
apache-2.0
401e44adc8640fadef3485635b3af59b
31.22
91
0.577902
4.173575
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/util/LinkRef.kt
1
18808
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.util import com.vladsch.md.nav.vcs.GitHubLinkResolver import com.vladsch.plugin.util.ifEmptyNullArgs import com.vladsch.plugin.util.splicer import com.vladsch.plugin.util.suffixWith import com.vladsch.plugin.util.urlDecode import java.util.* open class LinkRef(val containingFile: FileRef, fullPath: String, anchorText: String?, val targetRef: FileRef?, val isNormalized: Boolean) : PathInfo(fullPath) { val anchor: String? = anchorText?.removePrefix("#") val hasAnchor: Boolean get() = anchor != null val isSelfAnchor: Boolean get() = _fullPath.isEmpty() && hasAnchor val isResolved: Boolean get() = targetRef != null override val isEmpty: Boolean get() = _fullPath.isEmpty() && !hasAnchor val isDoNothingAnchor: Boolean get() = isSelfAnchor && (anchor.isNullOrEmpty()) val anchorText: String get() = if (anchor == null) EMPTY_STRING else "#$anchor" val notEmptyAnchorText: String get() = "#$anchor" val filePathWithAnchor: String get() = super.filePath + anchorText val filePathNoExtWithAnchor: String get() = super.filePathNoExt + anchorText override fun toString(): String = filePathWithAnchor open val linkExtensions: Array<String> get() { return when { ext in IMAGE_EXTENSIONS -> IMAGE_EXTENSIONS ext.isEmpty() || ext in MARKDOWN_EXTENSIONS -> MARKDOWN_EXTENSIONS else -> arrayOf(ext, *MARKDOWN_EXTENSIONS) } } fun resolve(resolver: GitHubLinkResolver, inList: List<PathInfo>? = null): LinkRef? { val targetRef = resolver.resolve(this, 0, inList) return if (targetRef == null) null else resolver.linkRef(this, targetRef, null, null, null) } val remoteURL: String? by lazy { when { targetRef is ProjectFileRef -> targetRef.gitHubVcsRoot?.baseUrl.suffixWith('/') + filePath + this.anchorText isExternal -> filePath + this.anchorText else -> null } } fun withTargetRef(targetRef: FileRef?): LinkRef { return LinkRef(containingFile, _fullPath, anchor, targetRef, isNormalized) } // convert file name to link open fun fileToLink(linkAddress: String, exclusionMap: Map<String, String>?): String = urlEncode(linkAddress, exclusionMap) // convert link to file name open fun linkToFile(linkAddress: String): String = urlDecode(linkAddress) // prepare text for matching files, wrap in (?:) so matches as a block open fun linkToFileRegex(linkText: String): String = linkAsFileRegex(linkText) // make a copy of everything but fullPath and return the same type of link open fun replaceFilePath(fullPath: String, withTargetRef: Boolean = false, isNormalized: Boolean? = null): LinkRef { return LinkRef(containingFile, fullPath, anchor, if (withTargetRef) targetRef else null, isNormalized ?: this.isNormalized) } // remove anchor from ref and return a new copy open fun removeAnchor(): LinkRef { return LinkRef(containingFile, filePath, null, targetRef, isNormalized) } open fun replaceFilePath(fullPath: String, targetRef: FileRef, isNormalized: Boolean? = null): LinkRef { return LinkRef(containingFile, fullPath, anchor, targetRef, isNormalized ?: this.isNormalized) } open fun replaceFilePathAndAnchor(fullPath: String, withTargetRef: Boolean = false, replaceAnchor: String? = null, isNormalized: Boolean? = null): LinkRef { return LinkRef(containingFile, fullPath, replaceAnchor, if (withTargetRef) targetRef else null, isNormalized ?: this.isNormalized) } companion object { @JvmStatic fun parseLinkRef(containingFile: FileRef, fullPath: String, targetRef: FileRef?): LinkRef { return parseLinkRef(containingFile, fullPath, targetRef, ::LinkRef) } @JvmStatic fun parseWikiLinkRef(containingFile: FileRef, fullPath: String, targetRef: FileRef?): WikiLinkRef { return parseLinkRef(containingFile, fullPath, targetRef, ::WikiLinkRef) as WikiLinkRef } @JvmStatic fun parseImageLinkRef(containingFile: FileRef, fullPath: String, targetRef: FileRef?): ImageLinkRef { return parseLinkRef(containingFile, fullPath, targetRef, ::ImageLinkRef) as ImageLinkRef } @JvmStatic fun <T : LinkRef> parseLinkRef(containingFile: FileRef, fullPath: String, targetRef: FileRef?, linkRefType: (containingFile: FileRef, linkRef: String, anchor: String?, targetRef: FileRef?, isNormalized: Boolean) -> T): LinkRef { var linkRef = PathInfo.cleanFullPath(fullPath) var anchor: String? = null // if the target file name has anchor, and linkRef does not contain URL encoded #, then we leave the anchor as part of the link if (targetRef == null || !(!linkRef.contains("%23") && targetRef.fileNameContainsAnchor())) { val anchorPos = linkRef.indexOf('#') if (anchorPos >= 0) { anchor = if (anchorPos == linkRef.lastIndex) EMPTY_STRING else linkRef.substring(anchorPos + 1) linkRef = if (anchorPos == 0) EMPTY_STRING else linkRef.substring(0, anchorPos) } } return linkRefType(containingFile, linkRef, anchor, targetRef, false) } // URL encode/decode handling @JvmStatic fun urlEncode(linkAddress: String, exclusionMap: Map<String, String>?): String { return mapLinkChars(linkAddress, fileUrlMap, exclusionMap) } @JvmStatic fun urlDecode(linkAddress: String): String { return linkAddress.urlDecode() } // prepare text for matching files, wrap in (?:) so matches as a block @JvmStatic fun linkAsFileRegex(linkText: String): String { return "(?:\\Q$linkText\\E)" } @JvmStatic fun mapLinkChars(linkAddress: String, charMap: Map<String, String>, exclusionMap: Map<String, String>?): String { var result = linkAddress for (pair in charMap) { if (exclusionMap == null || !exclusionMap.containsKey(pair.key)) { result = result.replace(pair.key, pair.value) } } return result } @JvmStatic @Suppress("UNUSED_PARAMETER") fun mapLinkCharsRegex(linkAddress: String, charMap: Map<String, Regex>): String { var result = linkAddress for (pair in charMap) { result = result.replace(pair.value, pair.key) } return result } @JvmStatic fun unmapLinkChars(linkAddress: String, charMap: Map<String, String>, exclusionMap: Map<String, String>?): String { var result = linkAddress for (pair in charMap) { if (exclusionMap == null || !exclusionMap.containsKey(pair.key)) { result = result.replace(pair.value, pair.key) } } return result } // more efficient when multiple chars map to the same value, creates a regex to match all keys @JvmStatic @Suppress("UNUSED_PARAMETER") fun linkRegexMap(charMap: Map<String, String>, exclusionMap: Map<String, String>? = null): Map<String, Regex> { val regExMap = HashMap<String, Regex>() // val useMap = if (exclusionMap == null) charMap else charMap.filter { !exclusionMap.containsKey(it.key) } for (char in charMap.values) { val regex = charMap.filter { it.value == char }.keys.map { "\\Q$it\\E" }.reduce(splicer("|")) regExMap[char] = regex.toRegex() } return regExMap } // char in file name to link map @JvmField val fileUrlMap: Map<String, String> = mapOf( Pair("%", "%25"), // NOTE: must be first in list otherwise will replace % of url encoded entities Pair(" ", "%20"), Pair("!", "%21"), Pair("#", "%23"), Pair("$", "%24"), Pair("&", "%26"), Pair("'", "%27"), Pair("(", "%28"), Pair(")", "%29"), Pair("*", "%2A"), Pair("+", "%2B"), Pair(",", "%2C"), //Pair("/", "%2F"), // not supported, used for directory separator //Pair(":", "%3A"), // not supported, windows needs this for drive specification Pair(";", "%3B"), Pair("<", "%3C"), Pair("=", "%3D"), Pair(">", "%3E"), Pair("?", "%3F"), Pair("@", "%40"), Pair("[", "%5B"), Pair("\\", "%5C"), Pair("]", "%5D"), Pair("^", "%5E"), Pair("`", "%60"), Pair("{", "%7B"), Pair("}", "%7D") ) // char in file name to link map @JvmField val gitBookFileUrlExclusionsMap: Map<String, String> = mapOf( Pair("+", "%2B") ) // CAUTION: just copies link address without figuring out whether it will resolve as is @JvmStatic fun from(linkRef: LinkRef, exclusionMap: Map<String, String>?): LinkRef { @Suppress("NAME_SHADOWING") var linkRef: LinkRef = linkRef return when (linkRef) { is ImageLinkRef -> LinkRef(linkRef.containingFile, if (linkRef.filePath.isEmpty()) linkRef.containingFile.fileNameNoExt else linkRef.fileName, linkRef.anchor, linkRef.targetRef, false) is WikiLinkRef -> { var wikiLink = WikiLinkRef.linkAsFile(linkRef.filePath) var withExt = false if (linkRef.hasAnchor && (linkRef.targetRef?.fileNameContainsAnchor() == true)) { wikiLink += linkRef.anchorText linkRef = linkRef.removeAnchor() } if (linkRef.targetRef?.isWikiPage == false && !linkRef.hasExt) { wikiLink += WIKI_PAGE_EXTENSION withExt = true } if (wikiLink.equals(if (withExt) linkRef.containingFile.fileName else linkRef.containingFile.fileNameNoExt, ignoreCase = true)) LinkRef(linkRef.containingFile, "", linkRef.anchor.orEmpty(), linkRef.targetRef, false) else LinkRef(linkRef.containingFile, urlEncode(wikiLink, exclusionMap), wikiLink.ifEmptyNullArgs(linkRef.anchor.orEmpty(), linkRef.anchor), linkRef.targetRef, false) } else -> linkRef } } } open fun withContainingFile(destFile: FileRef): LinkRef { return LinkRef(destFile, filePath, anchor, targetRef, isNormalized) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LinkRef) return false if (!super.equals(other)) return false if (containingFile != other.containingFile) return false if (anchor != other.anchor) return false return true } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + containingFile.hashCode() result = 31 * result + (anchor?.hashCode() ?: 0) return result } } // this is a [[]] style link ref open class WikiLinkRef(containingFile: FileRef, fullPath: String, anchor: String?, targetRef: FileRef?, isNormalized: Boolean) : LinkRef(containingFile, fullPath, anchor, targetRef, isNormalized) { override val linkExtensions: Array<String> get() = WIKI_PAGE_EXTENSIONS // convert file name to link override fun fileToLink(linkAddress: String, exclusionMap: Map<String, String>?): String = fileAsLink(linkAddress, exclusionMap) // convert link to file name override fun linkToFile(linkAddress: String): String = linkAsFile(linkAddress) // prepare text for matching files, wrap in (?:) so matches as a block override fun linkToFileRegex(linkText: String): String = linkAsFileRegex(linkText) // make a copy of everything but fullPath and return the same type of link override fun replaceFilePath(fullPath: String, withTargetRef: Boolean, isNormalized: Boolean?): LinkRef { return WikiLinkRef(containingFile, fullPath, anchor, if (withTargetRef) targetRef else null, isNormalized ?: this.isNormalized) } override fun replaceFilePath(fullPath: String, targetRef: FileRef, isNormalized: Boolean?): LinkRef { return WikiLinkRef(containingFile, fullPath, anchor, targetRef, isNormalized ?: this.isNormalized) } // remove anchor from ref and return a new copy override fun removeAnchor(): LinkRef { return WikiLinkRef(containingFile, filePath, null, targetRef, isNormalized) } override fun replaceFilePathAndAnchor(fullPath: String, withTargetRef: Boolean, replaceAnchor: String?, isNormalized: Boolean?): LinkRef { return WikiLinkRef(containingFile, fullPath, replaceAnchor, if (withTargetRef) targetRef else null, isNormalized ?: this.isNormalized) } override fun withContainingFile(destFile: FileRef): WikiLinkRef { return WikiLinkRef(destFile, filePath, anchor, targetRef, isNormalized) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is WikiLinkRef) return false if (!super.equals(other)) return false return true } override fun hashCode(): Int { return super.hashCode() } companion object { // convert file name to link, usually url encode @JvmStatic @Suppress("UNUSED_PARAMETER") fun fileAsLink(linkAddress: String, exclusionMap: Map<String, String>? = null): String = linkAddress.replace('-', ' ') @JvmStatic val wikiLinkRegexMap: Map<String, Regex> by lazy { linkRegexMap(wikiLinkMap) } // convert link to file name, usually url decode @JvmStatic fun linkAsFile(linkAddress: String): String = mapLinkCharsRegex(linkAddress, wikiLinkRegexMap) // prepare text for matching files, wrap in (?:) so matches as a block @JvmStatic @Suppress("UNUSED_PARAMETER") fun linkAsFileRegex(linkText: String): String { // GitHub Wiki Change: No longer true // return "(?:\\Q" + linkText.replace(wikiLinkMatchRegex, "\\\\E(?:-| |\\\\+|>|<|/)\\\\Q") + "\\E)" return "(?:\\Q" + linkText.replace(wikiLinkMatchRegex, "\\\\E(?:-| |\\\\+|/)\\\\Q") + "\\E)" } @JvmField val wikiLinkMap: Map<String, String> = mapOf( Pair(" ", "-"), Pair("+", "-"), Pair("/", "-") // GitHub Wiki Change: No longer true // Pair("<", "-"), // Pair(">", "-") ) // GitHub Wiki Change: No longer true // val wikiLinkMatchRegex = "-| |\\+|>|<|/".toRegex() val wikiLinkMatchRegex: Regex = "-| |\\+|/".toRegex() // CAUTION: just copies link address without figuring out whether it will resolve as is @JvmStatic fun from(linkRef: LinkRef): WikiLinkRef? { return when (linkRef) { is ImageLinkRef -> null is WikiLinkRef -> linkRef else -> { when { linkRef.path.isNotEmpty() && linkRef.hasExt && !linkRef.isWikiPageExt -> null // won't resolve as wiki link else -> WikiLinkRef(linkRef.containingFile, fileAsLink(urlDecode(if (linkRef.filePath.isEmpty()) linkRef.containingFile.fileNameNoExt else if (linkRef.isWikiPageExt) linkRef.fileNameNoExt else linkRef.fileName)), linkRef.anchor, linkRef.targetRef, false) } } } } } } open class ImageLinkRef(containingFile: FileRef, fullPath: String, anchor: String?, targetRef: FileRef?, isNormalized: Boolean) : LinkRef(containingFile, fullPath, anchor, targetRef, isNormalized) { override val linkExtensions: Array<String> get() = IMAGE_EXTENSIONS // make a copy of everything but fullPath and targetRef and return the same type of link override fun replaceFilePath(fullPath: String, withTargetRef: Boolean, isNormalized: Boolean?): LinkRef { return ImageLinkRef(containingFile, fullPath, anchor, if (withTargetRef) targetRef else null, isNormalized ?: this.isNormalized) } override fun replaceFilePath(fullPath: String, targetRef: FileRef, isNormalized: Boolean?): LinkRef { return ImageLinkRef(containingFile, fullPath, anchor, targetRef, isNormalized ?: this.isNormalized) } // remove anchor from ref and return a new copy override fun removeAnchor(): LinkRef { return ImageLinkRef(containingFile, filePath, null, targetRef, isNormalized) } override fun replaceFilePathAndAnchor(fullPath: String, withTargetRef: Boolean, replaceAnchor: String?, isNormalized: Boolean?): LinkRef { return ImageLinkRef(containingFile, fullPath, replaceAnchor, if (withTargetRef) targetRef else null, isNormalized ?: this.isNormalized) } override fun withContainingFile(destFile: FileRef): ImageLinkRef { return ImageLinkRef(destFile, filePath, anchor, targetRef, isNormalized) } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ImageLinkRef) return false if (!super.equals(other)) return false return true } override fun hashCode(): Int { return super.hashCode() } // CAUTION: just copies link address without figuring out whether it will resolve as is companion object { @JvmStatic fun from(linkRef: LinkRef): LinkRef? { return when (linkRef) { is ImageLinkRef -> linkRef is WikiLinkRef -> null else -> // FIX: add validation for type of file and extension and return null when it is not possible to convert ImageLinkRef(linkRef.containingFile, if (linkRef.filePath.isEmpty()) linkRef.containingFile.fileName else linkRef.fileName, linkRef.anchor, linkRef.targetRef, false) } } } }
apache-2.0
26925949cc1a0d96acc26ee0aea59fc4
41.552036
278
0.612824
4.513559
false
false
false
false
polson/MetroTripper
app/src/main/java/com/philsoft/metrotripper/app/state/transformer/StopListTransformer.kt
1
1901
package com.philsoft.metrotripper.app.state.transformer import com.philsoft.metrotripper.app.state.AppState import com.philsoft.metrotripper.app.state.AppUiEvent.Initialize import com.philsoft.metrotripper.app.state.MapUiEvent.MarkerClicked import com.philsoft.metrotripper.app.state.StopHeadingUiEvent.SaveStopButtonClicked import com.philsoft.metrotripper.app.state.StopListAction import com.philsoft.metrotripper.app.state.StopListUiEvent.StopSearched import com.philsoft.metrotripper.app.state.StopListUiEvent.StopSelectedFromDrawer import com.philsoft.metrotripper.model.Stop class StopListTransformer : ViewActionTransformer<StopListAction>() { override fun handleEvent(state: AppState) = state.appUiEvent.run { when (this) { is Initialize -> handleInitialize(state) is SaveStopButtonClicked -> handleSaveStopButtonClicked(state) is StopSelectedFromDrawer -> handleStopSelected(stop) is StopSearched -> handleStopSearched(state) is MarkerClicked -> handleMarkerClicked(state) } } private fun handleMarkerClicked(state: AppState) { if (state.selectedStop != null) { send(StopListAction.SetStopSelected(state.selectedStop.stopId)) } } private fun handleStopSearched(state: AppState) { if (state.selectedStop != null) { send(StopListAction.SetStopSelected(state.selectedStop.stopId)) } } private fun handleStopSelected(stop: Stop) { send(StopListAction.SetStopSelected(stop.stopId)) } private fun handleSaveStopButtonClicked(state: AppState) { val stops = state.savedStopsMap.values.toList() send(StopListAction.ShowStops(stops)) } private fun handleInitialize(state: AppState) { val stops = state.savedStopsMap.values.toList() send(StopListAction.ShowStops(stops)) } }
apache-2.0
3bb251c3ab5218a12a94df63b119ab5e
37.795918
83
0.732772
4.400463
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/libs/clip/ClippingUrlOpener.kt
1
2152
package jp.toastkid.yobidashi.libs.clip import android.content.Context import android.net.Uri import androidx.core.net.toUri import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.Urls import jp.toastkid.lib.clip.Clipboard import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.libs.network.NetworkChecker /** * Clipping URL opener, this class invoked containing URL in clipboard. * * @author toastkidjp */ class ClippingUrlOpener { /** * Invoke action. * * @param context [Context](Nullable) * @param onClick callback */ operator fun invoke(context: Context?, onClick: (Uri) -> Unit) { if (context == null || NetworkChecker.isNotAvailable(context)) { return } val activityContext = context val clipboardContent = Clipboard.getPrimary(activityContext)?.toString() ?: return val preferenceApplier = PreferenceApplier(activityContext) val lastClipped = preferenceApplier.lastClippedWord() if (shouldNotFeedback(clipboardContent, lastClipped)) { return } preferenceApplier.setLastClippedWord(clipboardContent) feedbackToUser(context, clipboardContent, onClick) } private fun shouldNotFeedback(clipboardContent: String, lastClippedWord: String) = Urls.isInvalidUrl(clipboardContent) || clipboardContent == lastClippedWord || clipboardContent.length > 100 private fun feedbackToUser( context: Context, clipboardContent: String, onClick: (Uri) -> Unit ) { val contentViewModel = (context as? ViewModelStoreOwner)?.let { ViewModelProvider(it).get(ContentViewModel::class.java) } contentViewModel?.snackWithAction( context.getString(R.string.message_clipping_url_open, clipboardContent), context.getString(R.string.open), { onClick(clipboardContent.toUri()) } ) } }
epl-1.0
914c98a21aad5a98c0766416d71b27c0
30.661765
90
0.681227
4.890909
false
false
false
false
googlecodelabs/fido2-codelab
android/app/src/main/java/com/example/android/fido2/ui/home/HomeViewModel.kt
2
2954
/* * Copyright 2019 Google Inc. All Rights Reserved. * * 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.fido2.ui.home import android.app.PendingIntent import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.android.fido2.repository.AuthRepository import com.example.android.fido2.repository.SignInState import com.google.android.gms.fido.fido2.api.common.PublicKeyCredential import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val repository: AuthRepository ) : ViewModel() { private val _processing = MutableStateFlow(false) val processing = _processing.asStateFlow() val currentUsername = repository.signInState.map { state -> when (state) { is SignInState.SigningIn -> state.username is SignInState.SignedIn -> state.username else -> "(user)" } }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), "(user)") val credentials = repository.credentials.stateIn( viewModelScope, SharingStarted.WhileSubscribed(), emptyList() ) fun reauth() { viewModelScope.launch { repository.clearCredentials() } } fun signOut() { viewModelScope.launch { repository.signOut() } } suspend fun registerRequest(): PendingIntent? { _processing.value = true try { return repository.registerRequest() } finally { _processing.value = false } } fun registerResponse(credential: PublicKeyCredential) { viewModelScope.launch { _processing.value = true try { repository.registerResponse(credential) } finally { _processing.value = false } } } fun removeKey(credentialId: String) { viewModelScope.launch { _processing.value = true try { repository.removeKey(credentialId) } finally { _processing.value = false } } } }
apache-2.0
d2f81bfd140a05a8b8a11ef4f0be8764
29.453608
75
0.671632
4.803252
false
false
false
false
blackbbc/Tucao
app/src/main/kotlin/me/sweetll/tucao/di/module/NetworkModule.kt
1
4501
package me.sweetll.tucao.di.module import com.franmontiel.persistentcookiejar.PersistentCookieJar import com.franmontiel.persistentcookiejar.cache.SetCookieCache import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor import dagger.Module import dagger.Provides import me.sweetll.tucao.AppApplication import me.sweetll.tucao.di.service.ApiConfig import okhttp3.CookieJar import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.converter.simplexml.SimpleXmlConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Named import javax.inject.Singleton @Module class NetworkModule { @Provides @Singleton fun provideCookieJar(): CookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(AppApplication.get())) @Provides @Singleton @Named("raw") fun provideRawOkHttpClient(cookieJar: CookieJar): OkHttpClient = OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .cookieJar(cookieJar) .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build() @Provides @Singleton @Named("download") fun provideDownloadOkHttpClient(cookieJar: CookieJar): OkHttpClient = OkHttpClient.Builder() .cookieJar(cookieJar) .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS)) .build() @Provides @Singleton @Named("json") fun provideJsonClient(cookieJar: CookieJar, @Named("apiKey") apiKey: String): OkHttpClient = OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .cookieJar(cookieJar) .addInterceptor { chain -> val url = chain.request().url() .newBuilder() .addQueryParameter("apikey", apiKey) .addQueryParameter("type", "json") .build() val request = chain.request().newBuilder() .url(url) .build() val response = chain.proceed(request) response } .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build() @Provides @Singleton @Named("xml") fun provideXmlClient(cookieJar: CookieJar): OkHttpClient = OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .cookieJar(cookieJar) .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .build() @Provides @Singleton @Named("raw") fun provideRawRetrofit(@Named("raw") client: OkHttpClient) : Retrofit = Retrofit.Builder() .baseUrl(ApiConfig.BASE_RAW_API_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) .build() @Provides @Singleton @Named("download") fun provideDownloadRetrofit(@Named("download") client: OkHttpClient) : Retrofit = Retrofit.Builder() .baseUrl(ApiConfig.BASE_RAW_API_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) .build() @Provides @Singleton @Named("json") fun provideJsonRetrofit(@Named("json") client: OkHttpClient) : Retrofit = Retrofit.Builder() .baseUrl(ApiConfig.BASE_JSON_API_URL) .addConverterFactory(MoshiConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) .build() @Provides @Singleton @Named("xml") fun provideXmlRetrofit(@Named("xml") client: OkHttpClient) : Retrofit = Retrofit.Builder() .baseUrl(ApiConfig.BASE_XML_API_URL) .addConverterFactory(SimpleXmlConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(client) .build() }
mit
ee09f0f66485d88bbd8c8318ed282ff0
36.823529
127
0.663186
5.19746
false
false
false
false
square/duktape-android
zipline-loader/src/commonTest/kotlin/app/cash/zipline/loader/ZiplineManifestTest.kt
1
7610
/* * Copyright (C) 2021 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 app.cash.zipline.loader import app.cash.zipline.loader.internal.fetcher.decodeToManifest import app.cash.zipline.loader.internal.fetcher.encodeToString import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import okio.ByteString.Companion.encodeUtf8 class ZiplineManifestTest { @Test fun manifestSortsModulesOnCreate() { val unsorted = ZiplineManifest.create( modules = mapOf( "bravo" to ZiplineManifest.Module( url = "/bravo.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf("alpha"), ), "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf(), ), ), mainFunction = "zipline.ziplineMain" ) val sorted = ZiplineManifest.create( modules = mapOf( "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf(), ), "bravo" to ZiplineManifest.Module( url = "/bravo.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf("alpha"), ), ), mainFunction = "zipline.ziplineMain" ) assertEquals(sorted, unsorted) } @Test fun manifestChecksThatModulesAreSortedIfClassIsCopied() { val empty = ZiplineManifest.create( modules = mapOf( "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf(), ) ), mainFunction = "zipline.ziplineMain" ) val unsortedException = assertFailsWith<IllegalArgumentException> { empty.copy( modules = mapOf( "bravo" to ZiplineManifest.Module( url = "/bravo.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf("alpha"), ), "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf(), ) ) ) } assertEquals( "Modules are not topologically sorted and can not be loaded", unsortedException.message ) } @Test fun failsOnCreateWhenCyclicalDependencies() { val selfDependencyException = assertFailsWith<IllegalArgumentException> { ZiplineManifest.create( modules = mapOf( "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf("alpha"), ), ), mainFunction = "zipline.ziplineMain", ) } assertEquals( "No topological ordering is possible for [alpha]", selfDependencyException.message ) val cyclicalException = assertFailsWith<IllegalArgumentException> { ZiplineManifest.create( modules = mapOf( "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf("bravo"), ), "bravo" to ZiplineManifest.Module( url = "/bravo.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf("alpha"), ), ) ) } assertEquals( "No topological ordering is possible for [alpha, bravo]", cyclicalException.message ) } @Test fun usesLastSortedModuleAsMainModuleId() { val manifest = ZiplineManifest.create( modules = mapOf( "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf(), ), "bravo" to ZiplineManifest.Module( url = "/bravo.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf("alpha"), ), ), mainFunction = "zipline.ziplineMain" ) assertEquals("bravo", manifest.mainModuleId) } @Test fun serializesToJson() { val original = ZiplineManifest.create( modules = mapOf( "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf(), ), "bravo" to ZiplineManifest.Module( url = "/bravo.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf("alpha"), ), ), mainFunction = "zipline.ziplineMain", ) val serialized = original.encodeToString() assertEquals( """ |{ | "unsigned": { | "signatures": { | }, | "freshAtEpochMs": null, | "baseUrl": null | }, | "modules": { | "alpha": { | "url": "/alpha.zipline", | "sha256": "616263313233", | "dependsOnIds": [ | ] | }, | "bravo": { | "url": "/bravo.zipline", | "sha256": "616263313233", | "dependsOnIds": [ | "alpha" | ] | } | }, | "mainModuleId": "bravo", | "mainFunction": "zipline.ziplineMain", | "version": null |} """.trimMargin(), prettyPrint(serialized) ) val parsed = serialized.decodeToManifest() assertEquals(original, parsed) } /** Omit all but the mandatory fields and confirm that the manifest can still parse. */ @Test fun absentFieldsDefaultedWhenParsing() { val serialized = """ |{ | "modules": { | "alpha": { | "url": "/alpha.zipline", | "sha256": "616263313233" | } | }, | "mainModuleId": "/alpha.zipline" |} """.trimMargin() val manifest = ZiplineManifest.create( modules = mapOf( "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf(), ), ), mainModuleId = "/alpha.zipline", ) assertEquals( manifest, serialized.decodeToManifest(), ) } @Test fun unknownFieldsIgnoredWhenParsing() { val serialized = """ |{ | "unknownField": 5, | "modules": { | "alpha": { | "url": "/alpha.zipline", | "sha256": "616263313233" | } | }, | "mainModuleId": "/alpha.zipline" |} """.trimMargin() val manifest = ZiplineManifest.create( modules = mapOf( "alpha" to ZiplineManifest.Module( url = "/alpha.zipline", sha256 = "abc123".encodeUtf8(), dependsOnIds = listOf(), ) ), mainModuleId = "/alpha.zipline", ) assertEquals( manifest, serialized.decodeToManifest(), ) } }
apache-2.0
8a63c36eca19164b3b96eab34feabe72
26.672727
89
0.549934
4.323864
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/user/UserActivity.kt
1
4976
package de.westnordost.streetcomplete.user import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.commit import androidx.lifecycle.lifecycleScope import de.westnordost.streetcomplete.FragmentContainerActivity import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.quest.QuestType import de.westnordost.streetcomplete.data.user.UserLoginStatusSource import de.westnordost.streetcomplete.data.user.achievements.Achievement import kotlinx.coroutines.launch import javax.inject.Inject /** Shows all the user information, login etc. * This activity coordinates quite a number of fragments, which all call back to this one. In order * of appearance: * The LoginFragment, the UserFragment (which contains the viewpager with more * fragments) and the "fake" dialogs AchievementInfoFragment and QuestTypeInfoFragment. * */ class UserActivity : FragmentContainerActivity(R.layout.activity_user), AchievementsFragment.Listener, QuestStatisticsFragment.Listener { @Inject internal lateinit var userLoginStatusSource: UserLoginStatusSource private val countryDetailsFragment get() = supportFragmentManager.findFragmentById(R.id.countryDetailsFragment) as CountryInfoFragment? private val questTypeDetailsFragment get() = supportFragmentManager.findFragmentById(R.id.questTypeDetailsFragment) as QuestTypeInfoFragment? private val achievementDetailsFragment get() = supportFragmentManager.findFragmentById(R.id.achievementDetailsFragment) as AchievementInfoFragment? private val loginStatusListener = object : UserLoginStatusSource.Listener { override fun onLoggedIn() { lifecycleScope.launch { replaceMainFragment(UserFragment()) }} override fun onLoggedOut() { lifecycleScope.launch { replaceMainFragment(LoginFragment()) }} } init { Injector.applicationComponent.inject(this) } /* --------------------------------------- Lifecycle --------------------------------------- */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { mainFragment = when { intent.getBooleanExtra(EXTRA_LAUNCH_AUTH, false) -> LoginFragment.create(true) userLoginStatusSource.isLoggedIn -> UserFragment() else -> LoginFragment.create() } } userLoginStatusSource.addListener(loginStatusListener) } override fun onBackPressed() { val countryDetailsFragment = countryDetailsFragment if (countryDetailsFragment != null && countryDetailsFragment.isShowing) { countryDetailsFragment.dismiss() return } val questTypeDetailsFragment = questTypeDetailsFragment if (questTypeDetailsFragment != null && questTypeDetailsFragment.isShowing) { questTypeDetailsFragment.dismiss() return } val achievementDetailsFragment = achievementDetailsFragment if (achievementDetailsFragment != null && achievementDetailsFragment.isShowing) { achievementDetailsFragment.dismiss() return } super.onBackPressed() } override fun onDestroy() { super.onDestroy() userLoginStatusSource.removeListener(loginStatusListener) } /* ---------------------------- AchievementsFragment.Listener ------------------------------- */ override fun onClickedAchievement(achievement: Achievement, level: Int, achievementBubbleView: View) { achievementDetailsFragment?.show(achievement, level, achievementBubbleView) } /* --------------------------- QuestStatisticsFragment.Listener ----------------------------- */ override fun onClickedQuestType(questType: QuestType<*>, solvedCount: Int, questBubbleView: View) { questTypeDetailsFragment?.show(questType, solvedCount, questBubbleView) } override fun onClickedCountryFlag(country: String, solvedCount: Int, rank: Int?, countryBubbleView: View) { countryDetailsFragment?.show(country, solvedCount, rank, countryBubbleView) } /* ------------------------------------------------------------------------------------------ */ private fun replaceMainFragment(fragment: Fragment) { supportFragmentManager.popBackStack("main", FragmentManager.POP_BACK_STACK_INCLUSIVE) supportFragmentManager.commit { setCustomAnimations( R.anim.fade_in_from_bottom, R.anim.fade_out_to_top, R.anim.fade_in_from_bottom, R.anim.fade_out_to_top ) replace(R.id.fragment_container, fragment) } } companion object { const val EXTRA_LAUNCH_AUTH = "de.westnordost.streetcomplete.user.launch_auth" } }
gpl-3.0
b3e85148b45d6b31679ea365c9f39388
40.466667
111
0.684686
5.565996
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/Prefs.kt
1
2444
package de.westnordost.streetcomplete import androidx.appcompat.app.AppCompatDelegate /** Constant class to have all the identifiers for shared preferences in one place */ object Prefs { const val OAUTH = "oauth" const val OAUTH_ACCESS_TOKEN = "oauth.accessToken" const val OAUTH_ACCESS_TOKEN_SECRET = "oauth.accessTokenSecret" const val MAP_TILECACHE_IN_MB = "map.tilecache" const val SHOW_NOTES_NOT_PHRASED_AS_QUESTIONS = "display.nonQuestionNotes" const val AUTOSYNC = "autosync" const val KEEP_SCREEN_ON = "display.keepScreenOn" const val UNGLUE_HINT_TIMES_SHOWN = "unglueHint.shown" const val THEME_SELECT = "theme.select" const val THEME_BACKGROUND = "theme.background_type" const val RESURVEY_INTERVALS = "quests.resurveyIntervals" const val OSM_USER_ID = "osm.userid" const val OSM_USER_NAME = "osm.username" const val OSM_UNREAD_MESSAGES = "osm.unread_messages" const val USER_DAYS_ACTIVE = "days_active" const val USER_GLOBAL_RANK = "user_global_rank" const val USER_LAST_TIMESTAMP_ACTIVE = "last_timestamp_active" const val IS_SYNCHRONIZING_STATISTICS = "is_synchronizing_statistics" const val TEAM_MODE_INDEX_IN_TEAM = "team_mode.index_in_team" const val TEAM_MODE_TEAM_SIZE = "team_mode.team_size" // not shown anywhere directly const val SELECTED_QUESTS_PRESET = "selectedQuestsPreset" const val LAST_EDIT_TIME = "changesets.lastChangeTime" const val MAP_LATITUDE = "map.latitude" const val MAP_LONGITUDE = "map.longitude" const val LAST_PICKED_PREFIX = "imageListLastPicked." const val FINISHED_FIRST_LOCATION_REQUEST = "location.firstPermissionRequestFinished" const val LAST_VERSION = "lastVersion" const val LAST_VERSION_DATA = "lastVersion_data" const val HAS_SHOWN_TUTORIAL = "hasShownTutorial" const val QUEST_SELECTION_HINT_STATE = "questSelectionHintState" const val PIN_SPRITES_VERSION = "TangramPinsSpriteSheet.version" const val PIN_SPRITES = "TangramPinsSpriteSheet.sprites" enum class Autosync { ON, WIFI, OFF } enum class Theme(val appCompatNightMode: Int) { LIGHT(AppCompatDelegate.MODE_NIGHT_NO), DARK(AppCompatDelegate.MODE_NIGHT_YES), AUTO(AppCompatDelegate.MODE_NIGHT_AUTO), SYSTEM(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM); } enum class ResurveyIntervals { LESS_OFTEN, DEFAULT, MORE_OFTEN } }
gpl-3.0
8388f55bb6ad557418edc6d10525ce51
40.423729
89
0.721768
3.771605
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/mappers/CollectionItemMapper.kt
1
3745
package com.boardgamegeek.mappers import com.boardgamegeek.entities.CollectionItemEntity import com.boardgamegeek.entities.CollectionItemGameEntity import com.boardgamegeek.extensions.sortName import com.boardgamegeek.extensions.toMillis import com.boardgamegeek.io.model.CollectionItem import com.boardgamegeek.provider.BggContract import java.text.SimpleDateFormat import java.util.* private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US) private val dateTimeFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US) fun CollectionItem.mapToEntities(): Pair<CollectionItemEntity, CollectionItemGameEntity> { val item = CollectionItemEntity( gameId = objectid, gameName = if (originalname.isNullOrBlank()) name else originalname, collectionId = collid.toIntOrNull() ?: BggContract.INVALID_ID, collectionName = name, sortName = if (originalname.isNullOrBlank()) name.sortName(sortindex) else name, gameYearPublished = yearpublished?.toIntOrNull() ?: CollectionItemEntity.YEAR_UNKNOWN, collectionYearPublished = yearpublished?.toIntOrNull() ?: CollectionItemEntity.YEAR_UNKNOWN, imageUrl = image.orEmpty(), thumbnailUrl = thumbnail.orEmpty(), rating = stats?.rating?.toDoubleOrNull() ?: 0.0, numberOfPlays = numplays, comment = comment.orEmpty(), wantPartsList = wantpartslist.orEmpty(), conditionText = conditiontext.orEmpty(), hasPartsList = haspartslist.orEmpty(), wishListComment = wishlistcomment.orEmpty(), own = own?.equals("1") ?: false, previouslyOwned = prevowned?.equals("1") ?: false, forTrade = fortrade?.equals("1") ?: false, wantInTrade = want?.equals("1") ?: false, wantToPlay = wanttoplay?.equals("1") ?: false, wantToBuy = wanttobuy?.equals("1") ?: false, wishList = wishlist?.equals("1") ?: false, wishListPriority = wishlistpriority, preOrdered = preordered?.equals("1") ?: false, lastModifiedDate = lastmodified.toMillis(dateTimeFormat), pricePaidCurrency = pp_currency.orEmpty(), pricePaid = pricepaid?.toDoubleOrNull() ?: 0.0, currentValueCurrency = cv_currency.orEmpty(), currentValue = currvalue?.toDoubleOrNull() ?: 0.0, quantity = quantity?.toIntOrNull() ?: 1, acquisitionDate = acquisitiondate.toMillis(dateFormat), acquiredFrom = acquiredfrom.orEmpty(), privateComment = privatecomment.orEmpty(), inventoryLocation = inventorylocation.orEmpty() ) val game = CollectionItemGameEntity( gameId = objectid, gameName = if (originalname.isNullOrBlank()) name else originalname, sortName = if (originalname.isNullOrBlank()) name.sortName(sortindex) else name, yearPublished = yearpublished?.toIntOrNull() ?: CollectionItemGameEntity.YEAR_UNKNOWN, imageUrl = image.orEmpty(), thumbnailUrl = thumbnail.orEmpty(), minNumberOfPlayers = stats?.minplayers ?: 0, maxNumberOfPlayers = stats?.maxplayers ?: 0, minPlayingTime = stats?.minplaytime ?: 0, maxPlayingTime = stats?.maxplaytime ?: 0, playingTime = stats?.playingtime ?: 0, numberOwned = stats?.numowned?.toIntOrNull() ?: 0, numberOfUsersRated = stats?.usersrated?.toIntOrNull() ?: 0, rating = stats?.rating?.toDoubleOrNull() ?: 0.0, average = stats?.average?.toDoubleOrNull() ?: 0.0, bayesAverage = stats?.bayesaverage?.toDoubleOrNull() ?: 0.0, standardDeviation = stats?.stddev?.toDoubleOrNull() ?: 0.0, median = stats?.median?.toDoubleOrNull() ?: 0.0, numberOfPlays = numplays ) return item to game }
gpl-3.0
982c49f183e48a317de8f5f880317259
48.276316
100
0.68251
4.56151
false
false
false
false
shadowfox-ninja/ShadowUtils
shadow-android/src/main/java/tech/shadowfox/shadow/android/utils/PrefsManager.kt
1
9130
@file:Suppress("LeakingThis", "MemberVisibilityCanPrivate", "unused", "NOTHING_TO_INLINE", "FunctionName") package tech.shadowfox.shadow.android.utils import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import java.util.HashMap import kotlin.properties.Delegates import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty import kotlin.reflect.KClass /** * Copyright 2017 Camaron Crowe * * 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. **/ sealed class PrefsManager { protected fun addManagedContainer(container: PrefsContainer): PrefsContainer { if (!prefsMap.containsKey(container.namespace)) { prefsMap.put(container.namespace, container) } else { if (!(prefsMap[container.namespace] === container)) throw RuntimeException("A namespace with the key ${container.namespace} already exists.") } return prefsMap[container.namespace]!! } protected fun getManagedContainer(namespace: String): SharedPreferences { prefsMap[namespace]!!.let { return if (namespace == COMMON_NAMESPACE) { PreferenceManager.getDefaultSharedPreferences(context) } else { context.getSharedPreferences("${PrefsManager.context.packageName}.${it.namespace}", it.privacy) } } } companion object { const val COMMON_NAMESPACE = "COMMON_NAMESPACE" const val PROTECTED_NAMESPACE = "PROTECTED_NAMESPACE" private val protectedNamespace = hashSetOf(PROTECTED_NAMESPACE) private val prefsMap: HashMap<String, PrefsContainer> = HashMap() private var context: Context by Delegates.notNull() fun init(context: Context) { this.context = context } fun protectedNamespace(namespace: String) { protectedNamespace.add(namespace) } fun unprotectNamespace(namespace: String) { if (namespace != PROTECTED_NAMESPACE) protectedNamespace.remove(namespace) } fun clear(namespace: String? = null) { if (!namespace.isNullOrBlank()) { prefsMap[namespace]?.clear() } else { prefsMap.filterKeys { it !in protectedNamespace } .forEach { it.value.clear() } } } } } abstract class PrefsContainer(val namespace: String, val privacy: Int = Context.MODE_PRIVATE) : PrefsManager() { init { addManagedContainer(this) } protected val preferenceManager: SharedPreferences by lazy { getManagedContainer(namespace) } @SuppressLint("ApplySharedPref") fun clear() { preferenceManager.edit().clear().commit() } inner protected class NullableStringPref(private val key: String? = null, private val transformer: PreferenceTransformer<String>? = null, private val onChange: ((String?) -> Unit)? = null) : ReadWriteProperty<Any, String?> { @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: Any, property: KProperty<*>): String? { val name = key ?: property.name return if (transformer != null) { transformer.decode(preferenceManager.getString(name, null)) } else { preferenceManager.getString(name, null) } } override fun setValue(thisRef: Any, property: KProperty<*>, value: String?) { val name = property.name val edit = preferenceManager.edit() if (transformer != null) { edit.putString(name, transformer.encode(value)) } else { edit.putString(name, value) } edit.apply() onChange?.invoke(value) } } inline protected fun <reified T : Enum<T>> PrefsContainer.EnumPref(defaultValue: T, key: String? = null, customPrefix: String? = null, transformer: PreferenceTransformer<String>? = null, noinline onChange: ((T) -> Unit)? = null) = object : DelegateProvider<ReadWriteProperty<Any, T>> { override fun provideDelegate(thisRef: Any?, property: KProperty<*>) = object : ReadWriteProperty<Any, T> { private val prefName = key ?: property.defaultDelegateName(customPrefix) override fun getValue(thisRef: Any, property: KProperty<*>): T { val prefName = key ?: property.name val name: String? = if (transformer != null) { transformer.decode(preferenceManager.getString(prefName, defaultValue.name)) } else { preferenceManager.getString(prefName, defaultValue.name) } return try { name?.let { kotlin.enumValueOf<T>(name) } ?: defaultValue } catch (_: Exception) { defaultValue } } override fun setValue(thisRef: Any, property: KProperty<*>, value: T) { val edit = preferenceManager.edit() if (transformer != null) { edit.putString(prefName, transformer.encode(value.name)) } else { edit.putString(prefName, value.name) } edit.apply() onChange?.invoke(value) } } } inner protected open class SharedPref<T>(private val defaultValue: T, private val key: String? = null, private val transformer: PreferenceTransformer<T>? = null, private val onChange: ((T) -> Unit)? = null) : ReadWriteProperty<Any, T> { @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: Any, property: KProperty<*>): T { val name = key ?: property.name return if (transformer != null) transformer.decode(preferenceManager.getString(name, null)) ?: defaultValue else when (defaultValue) { is Boolean -> preferenceManager.getBoolean(name, defaultValue) as T is Float -> preferenceManager.getFloat(name, defaultValue) as T is Int -> preferenceManager.getInt(name, defaultValue) as T is Long -> preferenceManager.getLong(name, defaultValue) as T is String -> preferenceManager.getString(name, defaultValue) as T else -> throw UnsupportedOperationException("Unsupported preference type ${property.javaClass} on property $name") } } override fun setValue(thisRef: Any, property: KProperty<*>, value: T) { val name = key ?: property.name val edit = preferenceManager.edit() if (transformer != null) edit.putString(name, transformer.encode(value)) else when (defaultValue) { is Boolean -> edit.putBoolean(name, value as Boolean) is Float -> edit.putFloat(name, value as Float) is Int -> edit.putInt(name, value as Int) is Long -> edit.putLong(name, value as Long) is String -> edit.putString(name, value as String) else -> throw UnsupportedOperationException("Unsupported preference type ${property.javaClass} on property $name") } edit.apply() onChange?.invoke(value) } } } interface DelegateProvider<out T> { operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): T } inline fun KProperty<*>.defaultDelegateName(customPrefix: String?, separator: String = "::") = (customPrefix ?: if (this is KClass<*>) this.java.canonicalName else null)?.let { it + separator + name } ?: name abstract class PreferenceTransformer<T> { abstract fun encode(value: T?): String? abstract fun decode(value: String?): T? }
apache-2.0
97b7285298e9c7e7228e3f1f673a0495
41.078341
166
0.571413
5.415184
false
false
false
false
ageery/kwicket
kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/form/KButton.kt
1
1695
package org.kwicket.wicket.core.markup.html.form import org.apache.wicket.WicketRuntimeException import org.apache.wicket.behavior.Behavior import org.apache.wicket.markup.html.form.Button import org.apache.wicket.model.IModel import org.kwicket.NonAjaxHandler import org.kwicket.component.init /** * [Button] with named and default constructor arguments. */ open class KButton( id: String, model: IModel<String>? = null, defaultFormProcessing: Boolean? = null, private val onSubmit: NonAjaxHandler, private val onError: NonAjaxHandler? = null, outputMarkupId: Boolean? = null, outputMarkupPlaceholderTag: Boolean? = null, escapeModelStrings: Boolean? = null, enabled: Boolean? = null, visible: Boolean? = null, required: Boolean? = null, label: IModel<String>? = null, behaviors: List<Behavior>? = null ) : Button(id, model) { init { init( outputMarkupId = outputMarkupId, outputMarkupPlaceholderTag = outputMarkupPlaceholderTag, behaviors = behaviors, escapeModelStrings = escapeModelStrings, renderBodyOnly = renderBodyOnly, enabled = enabled, visible = visible, required = required, label = label ) defaultFormProcessing?.let { this.defaultFormProcessing = it } //this.defaultFormProcessing = defaultFormProcessing ?: this.defaultFormProcessing } override fun onSubmit() { onSubmit.invoke() } override fun onError() { onError?.invoke() ?: throw WicketRuntimeException("No onError handler defined for ${javaClass.name} with id=$id") } }
apache-2.0
7ee4c891367dbc7963c5fb86f5491056
30.407407
111
0.667257
4.695291
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/completion/BibtexStringProvider.kt
1
2314
package nl.hannahsten.texifyidea.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.util.ProcessingContext import com.intellij.util.containers.ContainerUtil import nl.hannahsten.texifyidea.TexifyIcons import nl.hannahsten.texifyidea.lang.Described import nl.hannahsten.texifyidea.psi.BibtexComment import nl.hannahsten.texifyidea.psi.BibtexEntry import nl.hannahsten.texifyidea.psi.BibtexTag import nl.hannahsten.texifyidea.util.* /** * I think this provides autocompletion for strings defined with @string{..} commands. * * @author Hannah Schellekens */ object BibtexStringProvider : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { val psiFile = parameters.originalFile val strings: List<Triple<String, String, BibtexEntry>> = psiFile.childrenOfType(BibtexEntry::class).asSequence() .filter { it.tokenType() == "@string" } .mapNotNull { val tag = it.firstChildOfType(BibtexTag::class) ?: return@mapNotNull null val key = tag.key val content = tag.content ?: return@mapNotNull null Triple(key.text, content.text, it) } .toList() result.addAllElements( ContainerUtil.map2List(strings) { LookupElementBuilder.create(StringDescription(it!!.third), it.first) .withPresentableText(it.first) .bold() .withTypeText(it.second, true) .withIcon(TexifyIcons.STRING) } ) } class StringDescription(entry: BibtexEntry?) : Described { override val description: String init { val previous = entry?.previousSiblingIgnoreWhitespace() val comment = previous?.lastChildOfType(BibtexComment::class) ?: entry?.previousSiblingIgnoreWhitespace() this.description = comment?.text?.replace(Regex("^%\\s?"), "") ?: "User defined string." } } }
mit
0d14fbdc4511e5c533142a7c6a5867da
40.339286
124
0.687986
5.119469
false
false
false
false
lightem90/Sismic
app/src/main/java/com/polito/sismic/Domain/Database/Tables.kt
1
6880
package com.polito.sismic.Domain.Database /** * Created by Matteo on 13/08/2017. */ object ReportTable { val NAME = "Reports" val ID = "_id" val TITLE = "title" val USERID = "userID" val DATE = "date" val COMMITTED = "committed" val PDF = "pdf_uri" } object ReportMediaTable { val NAME = "Media" val ID = "_id" val URL = "filepath" val TYPE = "type" val NOTE = "note" val SIZE = "size" val REPORT_ID = "report_id" } object LocalizationInfoTable { val NAME = "Localization" val ID = "_id" val LATITUDE = "latitude" val LONGITUDE = "longitude" val COUNTRY = "country" val REGION = "region" val PROVINCE = "province" val COMUNE = "comune" val ADDRESS = "address" val CAP = "cap" val SISMIC_ZONE = "zone" val SISMIC_ZONE_INT = "zone_int" val ISTAT_CODE = "code" val REPORT_ID = "report_id" } object CatastoInfoTable { val NAME = "General" val ID = "_id" val FOGLIO = "foglio" val MAPPALE = "mappale" val PARTICELLA = "particella" val FOGLIO_CART = "foglio_cart" val EDIFICIO = "edificio" val AGGR_STR = "aggr_str" val ZONA_URB = "zona_urb" val PIANO_URB = "piano_urb" val VINCOLI_URB = "vincoli_urb" val REPORT_ID = "report_id" } object ResultsInfoTable { val NAME = "Results" val ID = "_id" val RESULT = "result" val SIZE = "size" val REPORT_ID = "report_id" } object DatiSismogeneticiInfoTable { val NAME = "DatiSismogenetici" val ID = "_id" val NEId = "ne_id" val NELat = "ne_lat" val NELon = "ne_lon" val NEDist = "ne_dist" val NOId = "no_id" val NOLat = "no_lat" val NOLon = "no_lon" val NODist = "no_dist" val SEId = "se_id" val SELat = "se_lat" val SELon = "se_lon" val SEDist = "se_dist" val SOId = "so_id" val SOLat = "so_lat" val SOLon = "so_lon" val SODist = "so_dist" val DATA_LIST = "data_list" val REPORT_ID = "report_id" } object ParametriSismiciInfoTable { val NAME = "ParametriSismici" val ID = "_id" val VITA_NOMINALE = "vita_nominale" val CLASSE_USO = "classe_uso" val VITA_REALE = "vita_reale" val DATA_LIST = "data_list" val REPORT_ID = "report_id" } object SpettriDiProgettoInfoTable { val NAME = "SpettriDiProgetto" val ID = "_id" val CATEGORIA_SUOLO = "categoria_suolo" val CATEGORIA_TOPOGRAFICA = "categoria_topografica" val CLASSE_DUTTILITA = "classe_duttilita" val TIPOLOGIA = "tipologia" val Q0 = "q0" val ALFA = "alfa" val KR = "kr" val DATA_LIST = "data_list" val REPORT_ID = "report_id" } object CaratteristicheGeneraliInfoTable { val NAME = "CaratteristicheGenerali" val ID = "_id" val ANNO_COSTRUZIONE = "anno_costruzione" val TIPOLOGIA_STRUTTURALE = "tipologia_strutturale" val STATO_EDIFICIO = "stato_edificio" val TOTALE_UNITA_USO = "totale_unita" val REPORT_ID = "report_id" } object RilieviInfoTable { val NAME = "Rilievi" val ID = "_id" val NUMERO_PIANI = "numero_piani" val ALTEZZA_PIANO_TERRA = "altezza_piano_terra" val ALTEZZA_PIANI_SUPERIORI = "altezza_piani_superiori" val ALTEZZA_TOT = "altezza_totale" val AREA = "area" val PERIMETRO = "perimetro" val CENTRO_GRAVITA_X = "centro_gravita_x" val CENTRO_GRAVITA_Y = "centro_gravita_y" val T1 = "t1" val PUNTI_PIANTA = "point_list" val REPORT_ID = "report_id" } object DatiStrutturaliInfoTable { val NAME = "DatiStrutturali" val ID = "_id" val TIPO_FONDAZIONI = "tipo_fondazioni" val ALTEZZA_FONDAZIONI = "altezza_fondazioni" val TIPO_SOLAIO = "tipo_solaio" val PESO_SOLAIO = "peso_solaio" val PESO_SOLAIO_STRING = "peso_solaio_string" val G2_SOLAIO = "g2_solaio" val QK_SOLAIO = "qk_solaio" val Q_SOLAIO = "q_solaio" val TIPO_COPERTURA = "tipo_copertura" val PESO_COPERTURA = "peso_copertura" val PESO_COPERTURA_STRING = "peso_copertura_string" val G2_COPERTURA = "g2_copertura" val QK_COPERTURA = "qk_copertura" val Q_COPERTURA = "q_copertura" val PESO_TOTALE = "peso_totale" val REPORT_ID = "report_id" } object CaratteristichePilastriInfoTable { val NAME = "CaratteristichePilastriInfoTable" val ID = "_id" val CLASSE_CALCESTRUZZO = "classe_calcestruzzo" val CONOSCENZA_CALCESTRUZZO = "conoscenza_calcestruzzo" val EPS2 = "eps2" val EPSU = "epsu" val RCK = "rck" val FCK = "fck" val ECM = "ecm" val FCD = "fcd" val FCM = "fcm" val CLASSE_ACCIAIO = "classe_acciaio" val CONOSCENZA_ACCIAIO = "conoscenza_acciaio" val EPSY = "epsy" val EPSUY = "epsuy" val E = "e" val FYK = "fyk" val FYD = "fyd" val BX = "bx" val HY = "hy" val C = "c" val NUM_FERRI = "num_ferri" val DIAM_FERRI = "diametro_ferri" val AREA_FERRI = "area_ferri" val PUNTI_DOMINIO = "domain_points" val STATI_LIMITE = "limit_state_points" val REPORT_ID = "report_id" } object MagliaStrutturaleInfoTable { val NAME = "MagliaStrutturale" val ID = "_id" val NUM_X = "num_x" val NUM_Y = "num_y" val DIST_X = "dist_x" val DIST_Y = "dist_y" val AREA = "area" val NUM_TOT = "num_tot" val REPORT_ID = "report_id" }
mit
8c13fc5261078ba2bd77b5e87c240223
30.856481
63
0.47689
3.16613
false
false
false
false
herolynx/elepantry-android
app/src/main/java/com/herolynx/elepantry/ext/google/firebase/db/FirebaseDb.kt
1
819
package com.herolynx.elepantry.ext.google.firebase.db import com.google.firebase.database.FirebaseDatabase import com.herolynx.elepantry.ext.google.firebase.auth.FirebaseAuth import com.herolynx.elepantry.resources.core.model.Resource import com.herolynx.elepantry.resources.core.model.View object FirebaseDb { private val database = FirebaseDatabase.getInstance() private fun userId() = FirebaseAuth.getCurrentUser().get().uid fun userViews() = userRepo("views", View::class.java, View::id) fun userResources() = userRepo("resources", Resource::class.java, Resource::id) private fun <T> userRepo(name: String, entityClass: Class<T>, idGetter: (T) -> String) = FirebaseRepository( database.getReference(name).child(userId()), entityClass, idGetter ) }
gpl-3.0
066b6ff1301ce58a9372d2a320233ada
33.166667
112
0.730159
4.221649
false
false
false
false
FHannes/intellij-community
platform/platform-impl/src/com/intellij/ui/components/components.kt
7
8503
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui.components import com.intellij.BundleBase import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.FileChooserFactory import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.openapi.ui.ComponentWithBrowseButton.BrowseFolderActionListener import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.DialogWrapper.IdeModalityType import com.intellij.openapi.ui.TextComponentAccessor import com.intellij.openapi.ui.ex.MultiLineLabel import com.intellij.openapi.vcs.changes.issueLinks.LinkMouseListenerBase import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.* import com.intellij.ui.components.labels.LinkLabel import com.intellij.util.FontUtil import com.intellij.util.ui.SwingHelper import com.intellij.util.ui.SwingHelper.addHistoryOnExpansion import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import java.awt.* import java.util.regex.Pattern import javax.swing.* import javax.swing.text.BadLocationException import javax.swing.text.Segment private val HREF_PATTERN = Pattern.compile("<a(?:\\s+href\\s*=\\s*[\"']([^\"']*)[\"'])?\\s*>([^<]*)</a>") private val LINK_TEXT_ATTRIBUTES: SimpleTextAttributes get() = SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, UI.getColor("link.foreground")) fun Label(text: String, style: UIUtil.ComponentStyle? = null, fontColor: UIUtil.FontColor? = null, bold: Boolean = false): JLabel { val finalText = BundleBase.replaceMnemonicAmpersand(text) val label: JLabel if (fontColor == null) { label = if (finalText.contains('\n')) MultiLineLabel(finalText) else JLabel(finalText) style?.let { UIUtil.applyStyle(it, label) } } else { label = JBLabel(finalText, style ?: UIUtil.ComponentStyle.REGULAR, fontColor) } if (bold) { label.font = label.font.deriveFont(Font.BOLD) } // surrounded by space to avoid false match if (text.contains(" -> ")) { label.text = text.replace(" -> ", " ${FontUtil.rightArrow(label.font)} ") } return label } fun Link(text: String, style: UIUtil.ComponentStyle? = null, action: () -> Unit): JComponent { val result = LinkLabel.create(text, action) style?.let { UIUtil.applyStyle(it, result) } return result } fun noteComponent(note: String): JComponent { val matcher = HREF_PATTERN.matcher(note) if (!matcher.find()) { return Label(note) } val noteComponent = SimpleColoredComponent() var prev = 0 do { if (matcher.start() != prev) { noteComponent.append(note.substring(prev, matcher.start())) } noteComponent.append(matcher.group(2), LINK_TEXT_ATTRIBUTES, SimpleColoredComponent.BrowserLauncherTag(matcher.group(1))) prev = matcher.end() } while (matcher.find()) LinkMouseListenerBase.installSingleTagOn(noteComponent) if (prev < note.length) { noteComponent.append(note.substring(prev)) } return noteComponent } @JvmOverloads fun htmlComponent(text: String = "", font: Font = UIUtil.getLabelFont(), background: Color? = null, foreground: Color? = null, lineWrap: Boolean = false): JEditorPane { val pane = SwingHelper.createHtmlViewer(lineWrap, font, background, foreground) if (!text.isNullOrEmpty()) { pane.text = "<html><head>${UIUtil.getCssFontDeclaration(font, UIUtil.getLabelForeground(), null, null)}</head><body>$text</body></html>" } pane.border = null pane.disabledTextColor = UIUtil.getLabelDisabledForeground() pane.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE) return pane } fun RadioButton(text: String) = JRadioButton(BundleBase.replaceMnemonicAmpersand(text)) fun CheckBox(text: String, selected: Boolean = false, toolTip: String? = null): JCheckBox { val component = JCheckBox(BundleBase.replaceMnemonicAmpersand(text), selected) toolTip?.let { component.toolTipText = it } return component } @JvmOverloads fun Panel(title: String? = null, layout: LayoutManager2? = BorderLayout()): JPanel { val panel = JPanel(layout) title?.let { setTitledBorder(it, panel) } return panel } private fun setTitledBorder(title: String, panel: JPanel) { val border = IdeBorderFactory.createTitledBorder(title, false) panel.border = border border.acceptMinimumSize(panel) } fun dialog(title: String, panel: JComponent, resizable: Boolean = false, focusedComponent: JComponent? = null, okActionEnabled: Boolean = true, project: Project? = null, parent: Component? = null, errorText: String? = null, modality: IdeModalityType = IdeModalityType.IDE, ok: (() -> Unit)? = null): DialogWrapper { return object: DialogWrapper(project, parent, true, modality) { init { setTitle(title) setResizable(resizable) if (!okActionEnabled) { this.okAction.isEnabled = false } setErrorText(errorText) init() } override fun createCenterPanel() = panel override fun getPreferredFocusedComponent() = focusedComponent override fun doOKAction() { ok?.let { if (okAction.isEnabled) { it() } } super.doOKAction() } } } @JvmOverloads fun <T : JComponent> installFileCompletionAndBrowseDialog(project: Project?, component: ComponentWithBrowseButton<T>, textField: JTextField, @Nls(capitalization = Nls.Capitalization.Title) browseDialogTitle: String, fileChooserDescriptor: FileChooserDescriptor, textComponentAccessor: TextComponentAccessor<T>, fileChoosen: ((chosenFile: VirtualFile) -> String)? = null) { component.addActionListener( object : BrowseFolderActionListener<T>(browseDialogTitle, null, component, project, fileChooserDescriptor, textComponentAccessor) { override fun onFileChosen(chosenFile: VirtualFile) { if (fileChoosen == null) { super.onFileChosen(chosenFile) } else { textComponentAccessor.setText(myTextComponent.childComponent, fileChoosen(chosenFile)) } } }) FileChooserFactory.getInstance().installFileCompletion(textField, fileChooserDescriptor, true, project) } @JvmOverloads fun textFieldWithHistoryWithBrowseButton(project: Project?, browseDialogTitle: String, fileChooserDescriptor: FileChooserDescriptor, historyProvider: (() -> List<String>)? = null, fileChoosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithHistoryWithBrowseButton { val component = TextFieldWithHistoryWithBrowseButton() val textFieldWithHistory = component.childComponent textFieldWithHistory.setHistorySize(-1) textFieldWithHistory.setMinimumAndPreferredWidth(0) if (historyProvider != null) { addHistoryOnExpansion(textFieldWithHistory, historyProvider) } installFileCompletionAndBrowseDialog( project, component, component.childComponent.textEditor, browseDialogTitle, fileChooserDescriptor, TextComponentAccessor.TEXT_FIELD_WITH_HISTORY_WHOLE_TEXT, fileChoosen = fileChoosen ) return component } val JPasswordField.chars: CharSequence? get() { val doc = document if (doc.length == 0) { return "" } val segment = Segment() try { doc.getText(0, doc.length, segment) } catch (e: BadLocationException) { return null } return segment }
apache-2.0
8cf4c7faba78450a83dc4a50429d0820
35.033898
168
0.682112
4.641376
false
false
false
false
gotev/android-upload-service
uploadservice/src/main/java/net/gotev/uploadservice/HttpUploadRequest.kt
2
4141
package net.gotev.uploadservice import android.content.Context import android.util.Base64 import net.gotev.uploadservice.data.HttpUploadTaskParameters import net.gotev.uploadservice.data.NameValue import net.gotev.uploadservice.extensions.addHeader import net.gotev.uploadservice.extensions.isValidHttpUrl import java.util.Locale /** * Represents a generic HTTP upload request.<br></br> * Subclass to create your own custom HTTP upload request. * @param context application context * @param serverUrl URL of the server side script that handles the request */ abstract class HttpUploadRequest<B : HttpUploadRequest<B>>(context: Context, serverUrl: String) : UploadRequest<B>(context, serverUrl) { protected val httpParams = HttpUploadTaskParameters() init { require(serverUrl.isValidHttpUrl()) { "Specify either http:// or https:// as protocol" } } override fun getAdditionalParameters() = httpParams.toPersistableData() /** * Adds a header to this upload request. * * @param headerName header name * @param headerValue header value * @return self instance */ fun addHeader(headerName: String, headerValue: String): B { httpParams.requestHeaders.addHeader(headerName, headerValue) return self() } /** * Sets the HTTP Basic Authentication header. * @param username HTTP Basic Auth username * @param password HTTP Basic Auth password * @return self instance */ fun setBasicAuth(username: String, password: String): B { val auth = Base64.encodeToString("$username:$password".toByteArray(), Base64.NO_WRAP) return addHeader("Authorization", "Basic $auth") } /** * Sets HTTP Bearer authentication with a token. * @param bearerToken bearer authorization token * @return self instance */ fun setBearerAuth(bearerToken: String): B { return addHeader("Authorization", "Bearer $bearerToken") } /** * Adds a parameter to this upload request. * * @param paramName parameter name * @param paramValue parameter value * @return self instance */ open fun addParameter(paramName: String, paramValue: String): B { httpParams.requestParameters.add(NameValue(paramName, paramValue)) return self() } /** * Adds a parameter with multiple values to this upload request. * * @param paramName parameter name * @param array values * @return self instance */ open fun addArrayParameter(paramName: String, vararg array: String): B { for (value in array) { httpParams.requestParameters.add(NameValue(paramName, value)) } return self() } /** * Adds a parameter with multiple values to this upload request. * * @param paramName parameter name * @param list values * @return self instance */ open fun addArrayParameter(paramName: String, list: List<String>): B { for (value in list) { httpParams.requestParameters.add(NameValue(paramName, value)) } return self() } /** * Sets the HTTP method to use. By default it's set to POST. * * @param method new HTTP method to use * @return self instance */ fun setMethod(method: String): B { httpParams.method = method.toUpperCase(Locale.ROOT) return self() } /** * Sets if this upload request is using fixed length streaming mode. * By default it's set to true. * If it uses fixed length streaming mode, then the value returned by * [HttpUploadTask.getBodyLength] will be automatically used to properly set the * underlying [java.net.HttpURLConnection], otherwise chunked streaming mode will be used. * @param fixedLength true to use fixed length streaming mode (this is the default setting) or * false to use chunked streaming mode. * @return self instance */ fun setUsesFixedLengthStreamingMode(fixedLength: Boolean): B { httpParams.usesFixedLengthStreamingMode = fixedLength return self() } }
apache-2.0
07886c3e303f126705499c099cf4274b
32.128
98
0.672784
4.673815
false
false
false
false
nhaarman/mockito-kotlin
tests/src/test/kotlin/test/EqTest.kt
1
2734
package test /* * The MIT License * * Copyright (c) 2016 Niek Haarman * Copyright (c) 2007 Mockito contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import com.nhaarman.expect.expect import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import org.junit.After import org.junit.Before import org.junit.Test import org.mockito.Mockito class EqTest : TestBase() { private val interfaceInstance: MyInterface = MyClass() private val openClassInstance: MyClass = MyClass() private val closedClassInstance: ClosedClass = ClosedClass() private lateinit var doAnswer: Open @Before fun setup() { /* Create a proper Mockito state */ doAnswer = Mockito.doAnswer { }.`when`(mock()) } @After override fun tearDown() { super.tearDown() /* Close `any` Mockito state */ doAnswer.go(0) } @Test fun eqInterfaceInstance() { /* When */ val result = eq(interfaceInstance) /* Then */ expect(result).toNotBeNull() } @Test fun eqOpenClassInstance() { /* When */ val result = eq(openClassInstance) /* Then */ expect(result).toNotBeNull() } @Test fun eqClosedClassInstance() { /* When */ val result = eq(closedClassInstance) /* Then */ expect(result).toNotBeNull() } @Test fun nullArgument() { /* Given */ val s: String? = null /* When */ val result = eq(s) /* Then */ expect(result).toBeNull() } private interface MyInterface private open class MyClass : MyInterface class ClosedClass }
mit
a6c7fb0718d331c1d5a695d458efb5fb
26.069307
80
0.666789
4.46732
false
true
false
false
gpolitis/jitsi-videobridge
jvb/src/main/kotlin/org/jitsi/videobridge/octo/OctoEndpoint.kt
1
5509
/* * 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.videobridge.octo import org.jitsi.nlj.MediaSourceDesc import org.jitsi.nlj.PacketHandler import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.TransceiverEventHandler import org.jitsi.nlj.format.PayloadType import org.jitsi.nlj.rtp.RtpExtension import org.jitsi.utils.MediaType import org.jitsi.utils.logging2.Logger import org.jitsi.videobridge.AbstractEndpoint import org.jitsi.videobridge.Conference import org.jitsi.videobridge.cc.allocation.VideoConstraints import org.jitsi.videobridge.message.AddReceiverMessage import org.jitsi.videobridge.message.BridgeChannelMessage import org.jitsi.videobridge.message.RemoveReceiverMessage /** * Represents an endpoint in a conference, which is connected to another * jitsi-videobridge instance. * * @author Boris Grozev */ class OctoEndpoint( conference: Conference, id: String, private val octoEndpoints: OctoEndpoints, parentLogger: Logger ) : AbstractEndpoint(conference, id, parentLogger), ConfOctoTransport.IncomingOctoEpPacketHandler { private val transceiverEventHandler = object : TransceiverEventHandler { override fun audioLevelReceived(sourceSsrc: Long, level: Long) = conference.speechActivity.levelChanged(this@OctoEndpoint, level) } private val transceiver = OctoTransceiver(id, transceiverEventHandler, logger).apply { setIncomingPacketHandler(object : PacketHandler { override fun processPacket(packetInfo: PacketInfo) { packetInfo.endpointId = id conference.handleIncomingPacket(packetInfo) } }) // This handler will be used for all packets that come out of // the transceiver, but this is only used for RTCP (keyframe requests) setOutgoingPacketHandler(object : PacketHandler { override fun processPacket(packetInfo: PacketInfo) { conference.tentacle.send(packetInfo) } }) } init { conference.tentacle.addHandler(id, this) } override fun handleIncomingPacket(packetInfo: OctoPacketInfo) { transceiver.handleIncomingPacket(packetInfo) } override fun sendMessage(msg: BridgeChannelMessage) { // This is intentionally a no-op. Since a conference can have // multiple OctoEndpoint instances, but we want a single message // to be sent through Octo, the message should be sent through the // single OctoEndpoints instance. } override fun requestKeyframe(mediaSsrc: Long) { transceiver.requestKeyframe(mediaSsrc) } override fun requestKeyframe() { transceiver.requestKeyframe() } override fun shouldExpire(): Boolean = !transceiver.hasReceiveSsrcs() override val mediaSource: MediaSourceDesc? get() = transceiver.mediaSources.firstOrNull() /** * This [OctoEndpoint] aggregates the constraints from the local endpoints on this bridge, and propagates the max * constraints to the bridge that is local for the sending endpoint via an [AddReceiverMessage]. */ override fun sendVideoConstraints(maxVideoConstraints: VideoConstraints) { conference.tentacle.sendMessage( AddReceiverMessage( conference.tentacle.bridgeId, id, maxVideoConstraints ) ) } override fun receivesSsrc(ssrc: Long): Boolean = transceiver.receivesSsrc(ssrc) override fun addReceiveSsrc(ssrc: Long, mediaType: MediaType?) { // This is controlled through setReceiveSsrcs. } override fun addPayloadType(payloadType: PayloadType?) { transceiver.addPayloadType(payloadType) } override fun addRtpExtension(rtpExtension: RtpExtension?) { transceiver.addRtpExtension(rtpExtension) } fun setMediaSources(sources: Array<MediaSourceDesc>) { transceiver.mediaSources = sources } override fun expire() { if (super.isExpired()) { return } super.expire() conference.tentacle.sendMessage(RemoveReceiverMessage(conference.tentacle.bridgeId, id)) transceiver.stop() logger.debug { transceiver.getNodeStats().prettyPrint() } conference.tentacle.removeHandler(id, this) octoEndpoints.endpointExpired(this) } /** * Sets the set SSRCs we expect to receive from this endpoint. */ fun setReceiveSsrcs(ssrcsByMediaType: Map<MediaType, Set<Long>>) { transceiver.setReceiveSsrcs(ssrcsByMediaType) } // The endpoint is sending audio if our Receiver object is receiving audio from the endpoint. override fun isSendingAudio(): Boolean = transceiver.isReceivingAudio // The endpoint is sending video if our Receiver object is receiving video from the endpoint. override fun isSendingVideo(): Boolean = transceiver.isReceivingVideo }
apache-2.0
0dffa29718d80e8c3c897d2fbfe8850c
35.006536
117
0.710655
4.613903
false
false
false
false
fallGamlet/DnestrCinema
KinotirApi/src/main/java/com/kinotir/api/mappers/HtmlTicketsMapper.kt
1
3202
package com.kinotir.api.mappers import com.kinotir.api.TicketJson import com.kinotir.api.TicketPlaceJson import org.jsoup.Jsoup import org.jsoup.nodes.Element import org.jsoup.select.Elements internal class HtmlTicketsMapper : Mapper<String?, List<TicketJson>> { override fun map(src: String?): List<TicketJson> { return src?.let { Jsoup.parse(it) } ?.select(".orders .items > .item") ?.mapNotNull { parseItem(it) } ?: emptyList() } private fun parseItem(item: Element?): TicketJson? { item ?: return null val linkA = item.select("h2>a")?.first() val ticketItem = TicketJson( title = linkA?.text(), url = linkA?.attr("href"), ticketPlaces = parseTicketPlaces(item.select(".tickets > li")) ) parseTicketInfo(item.select(".order-data > li"), ticketItem) return ticketItem } private fun parseTicketInfo(infoItems: Elements?, ticketItem: TicketJson) { infoItems ?.mapNotNull { el -> val value = if (el.childNodeSize() >= 2) el.childNode(1).toString().trim() else null value?.let { Pair(el, it) } } ?.forEach { val el = it.first val value = it.second when { el.select(">b:containsOwn(Заказ)").isNotEmpty() -> ticketItem.id = value el.select(">b:containsOwn(Зал кинотеатра)").isNotEmpty() -> ticketItem.room = value el.select(">b:containsOwn(Статус)").isNotEmpty() -> ticketItem.status = value el.select(">b:containsOwn(Дата сеанса)").isNotEmpty() -> ticketItem.date = value el.select(">b:containsOwn(Время сеанса)").isNotEmpty() -> ticketItem.time = value } } } private fun parseTicketPlaces(items: Elements?): List<TicketPlaceJson> { return items?.mapNotNull { parseTicketPlace(it) } ?: emptyList() } private fun parseTicketPlace(item: Element?): TicketPlaceJson? { item ?: return null val place = TicketPlaceJson( url = item.select("div.code > img")?.first()?.attr("src") ) parseTicketPlaceInfo(item.select(".additional > ul > li"), place) return place } private fun parseTicketPlaceInfo(infoItems: Elements?, ticketPlace: TicketPlaceJson) { if (infoItems == null || infoItems.isEmpty()) return var row: String? = null var place: String? = null infoItems.forEach { el -> if (el.childNodeSize() >= 2) { val value = el.childNode(1).toString().trim() when { el.select(">b:containsOwn(Ряд)").isNotEmpty() -> row = value el.select(">b:containsOwn(Место)").isNotEmpty() -> place = value } } } ticketPlace.row = row ticketPlace.place = place } }
gpl-3.0
b08c311dcc2d082bdbc4aa9253728a36
35.616279
90
0.536996
4.325549
false
false
false
false
wiltonlazary/kotlin-native
samples/torch/src/torchMain/kotlin/SmallDemos.kt
1
2587
/* * Copyright 2010-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/LICENSE.txt file. */ package sample.torch // If you are curious you can also try one of these private fun demonstrateTensors() { disposeScoped { val x = use { tensor(0f, 1f, 2f) } val y = use { tensor(0f, -1f, -2f) } val m = use { tensor( arrayOf(1f, -1f, 0f), arrayOf(0f, -1f, 0f), arrayOf(0f, 0f, -.5f)) } println("Hello, Torch!\nx = $x\ny = $y\n" + "|x| = ${x.abs()}\n|y| = ${y.abs()}\n" + "2x=${use { x * 2f }}\nx+y = ${use { x + y }}\nx-y = ${use { x - y }}\nxy = ${x * y}\n" + "m=\n${use { m }}\nm·y = ${use { m * y }}\nm+m =\n${use { m + m }}\nm·m =\n${use { m * m }}") } } private fun demonstrateModules() { val input = tensor(arrayOf(-1f)) val abs = Abs(input) println("abs of $input is $abs, gradient is ${Abs.inputGradient(input, tensor(arrayOf(1f)), abs)}") val relu = Relu(input) println("relu of $input is $relu, gradient is ${Relu.inputGradient(input, tensor(arrayOf(1f)), relu)}") } private fun demonstrateManualBackpropagationFor1LinearLayer( inputs: FloatMatrix = tensor(arrayOf(1f, -1f), arrayOf(1f, -1f)), labels: FloatMatrix = tensor(arrayOf(5f), arrayOf(5f)), learningRate: Float = .1f) { val linear = Linear(weight = randomInit(1, 2), bias = randomInit(1)) val error = MeanSquaredError(labels) for (i in 0 until 100) { disposeScoped { val output = use { linear(inputs) } val loss = use { error(output) } val outputGradient = use { error.inputGradient(output, tensor(learningRate), loss) } val inputGradient = use { linear.inputGradient(inputs, outputGradient, output) } val parameterGradient = linear.parameterGradient(inputs, outputGradient, inputGradient). also { use { it.first } }.also { use { it.second } } println("input: $inputs, \n" + "output: $output, \n" + "labels: $labels, \n" + "mean squared error: $loss, \n" + "output gradient: $outputGradient, \n" + "input gradient: $inputGradient, \n" + "parameter gradient: $parameterGradient") linear.weight -= parameterGradient.first linear.bias -= parameterGradient.second } } }
apache-2.0
150bdaae2652ff39ee4193609c7cc161
40.709677
109
0.541973
3.541096
false
false
false
false
nemerosa/ontrack
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/GQLTypeIndicatorView.kt
1
5002
package net.nemerosa.ontrack.extension.indicators.ui.graphql import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategoryService import net.nemerosa.ontrack.extension.indicators.model.IndicatorTypeService import net.nemerosa.ontrack.extension.indicators.model.Rating import net.nemerosa.ontrack.extension.indicators.portfolio.IndicatorView import net.nemerosa.ontrack.extension.indicators.stats.IndicatorStatsService import net.nemerosa.ontrack.graphql.schema.GQLFieldContributor import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.schema.graphQLFieldContributions import net.nemerosa.ontrack.graphql.support.listType import net.nemerosa.ontrack.graphql.support.stringField import org.springframework.stereotype.Component @Component class GQLTypeIndicatorView( private val indicatorCategory: GQLTypeIndicatorCategory, private val indicatorCategoryService: IndicatorCategoryService, private val indicatorTypeService: IndicatorTypeService, private val indicatorViewProjectReport: GQLTypeIndicatorViewProjectReport, private val indicatorReportingService: GQLIndicatorReportingService, private val indicatorStatsService: IndicatorStatsService, private val fieldContributors: List<GQLFieldContributor> ) : GQLType { override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("List of categories to display for a portfolio or a list of portfolios.") // ID .stringField(IndicatorView::id, "Unique ID for this view") // Name .stringField(IndicatorView::name, "Name of the view") // Categories .field { it.name(IndicatorView::categories.name) .description("Selected categories for this view") .type(listType(indicatorCategory.typeRef)) .dataFetcher { env -> val view: IndicatorView = env.getSource() view.categories.mapNotNull { id -> indicatorCategoryService.findCategoryById(id) } } } // Project reports - List<IndicatorViewProjectReport> .field { it.name("reports") .description("List of indicator stats per project for all categories in this view") .type(listType(indicatorViewProjectReport.typeRef)) .arguments(indicatorReportingService.arguments) .durationArgument() .rateArgument() .dataFetcher { env -> val view: IndicatorView = env.getSource() // Gets the trending duration val duration = env.getDurationArgument() // Gets the rate condition val rate = env.getRateArgument() // Gets the list of all categories val categories = view.categories.mapNotNull(indicatorCategoryService::findCategoryById) // Gets the list of all the types val types = categories.flatMap(indicatorTypeService::findByCategory) // Gets the list of projects for this report, based on field arguments val projects = indicatorReportingService.findProjects(env, types) // Getting the stats for each project projects.map { project -> IndicatorViewProjectReport( project = project, viewStats = categories.map { category -> indicatorStatsService.getStatsForCategoryAndProject(category, project, duration) } ) }.filter { projectReport -> if (rate != null) { // At least one avg rate in one category must be worse or equal to this rate projectReport.viewStats.any { stats -> stats.stats.avg?.let { candidate -> Rating.asRating(candidate.value) <= rate } ?: false } } else { true } } } } // Links .fields(IndicatorView::class.java.graphQLFieldContributions(fieldContributors)) //OK .build() override fun getTypeName(): String = IndicatorView::class.java.simpleName }
mit
f0c419da767f7d456977465b1e70840c
51.114583
116
0.579568
6.129902
false
false
false
false
nemerosa/ontrack
ontrack-it-utils/src/main/java/net/nemerosa/ontrack/it/AbstractServiceTestJUnit4Support.kt
1
19592
package net.nemerosa.ontrack.it import net.nemerosa.ontrack.model.security.* import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.settings.SecuritySettings import net.nemerosa.ontrack.model.settings.SettingsManagerService import net.nemerosa.ontrack.model.structure.* import net.nemerosa.ontrack.model.structure.Branch.Companion.of import net.nemerosa.ontrack.model.structure.Build.Companion.of import net.nemerosa.ontrack.model.structure.ID.Companion.of import net.nemerosa.ontrack.model.structure.NameDescription.Companion.nd import net.nemerosa.ontrack.model.structure.Project.Companion.of import net.nemerosa.ontrack.model.structure.PromotionRun.Companion.of import net.nemerosa.ontrack.model.structure.Signature.Companion.of import net.nemerosa.ontrack.test.TestUtils.uid import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.authentication.TestingAuthenticationToken import org.springframework.security.core.context.SecurityContext import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.context.SecurityContextImpl import java.util.concurrent.Callable @Deprecated(message = "JUnit is deprecated", replaceWith = ReplaceWith("AbstractServiceTestSupport")) abstract class AbstractServiceTestJUnit4Support : AbstractITTestJUnit4Support() { @Autowired protected lateinit var accountService: AccountService @Autowired protected lateinit var structureService: StructureService @Autowired protected lateinit var propertyService: PropertyService @Autowired protected lateinit var settingsManagerService: SettingsManagerService @Autowired protected lateinit var cachedSettingsService: CachedSettingsService @Autowired protected lateinit var securityService: SecurityService @Autowired protected lateinit var rolesService: RolesService protected fun doCreateAccountGroup(): AccountGroup { return asUser().with(AccountGroupManagement::class.java).call { val name = uid("G") accountService.createGroup( AccountGroupInput(name, "") ) } } protected fun doCreateAccount(accountGroup: AccountGroup): Account { return doCreateAccount(listOf(accountGroup)) } protected fun doCreateAccount( accountGroups: List<AccountGroup> = emptyList(), disabled: Boolean = false, locked: Boolean = false, ): Account { return asUser().with(AccountManagement::class.java).call { val name = uid("A") accountService.create( AccountInput( name, "Test $name", "[email protected]", "test", accountGroups.map { it.id() }, disabled = disabled, locked = locked, ) ) } } protected fun doCreateAccountWithGlobalRole(role: String): Account { val account = doCreateAccount() return asUser().with(AccountManagement::class.java).call { accountService.saveGlobalPermission( PermissionTargetType.ACCOUNT, account.id(), PermissionInput(role) ) account } } protected fun doCreateAccountWithProjectRole(project: Project, role: String): Account { val account = doCreateAccount() return asUser().with(project, ProjectAuthorisationMgt::class.java).call { accountService.saveProjectPermission( project.id, PermissionTargetType.ACCOUNT, account.id(), PermissionInput(role) ) account } } protected fun doCreateAccountGroupWithGlobalRole(role: String): AccountGroup { val group = doCreateAccountGroup() return asUser().with(AccountGroupManagement::class.java).call { accountService.saveGlobalPermission( PermissionTargetType.GROUP, group.id(), PermissionInput(role) ) group } } protected fun <T> setProperty(projectEntity: ProjectEntity, propertyTypeClass: Class<out PropertyType<T>>, data: T) { asUser().with(projectEntity, ProjectEdit::class.java).execute(Runnable { propertyService.editProperty( projectEntity, propertyTypeClass, data ) } ) } protected fun <T> deleteProperty(projectEntity: ProjectEntity?, propertyTypeClass: Class<out PropertyType<T>>) { asUser().with(projectEntity!!, ProjectEdit::class.java).execute(Runnable { propertyService.deleteProperty( projectEntity, propertyTypeClass ) } ) } protected fun <T> getProperty(projectEntity: ProjectEntity, propertyTypeClass: Class<out PropertyType<T>>): T { return asUser().with(projectEntity, ProjectEdit::class.java).call { propertyService.getProperty( projectEntity, propertyTypeClass ).value } } @JvmOverloads protected fun doCreateProject(nameDescription: NameDescription = nameDescription()): Project { return asUser().with(ProjectCreation::class.java).call { structureService.newProject( of(nameDescription) ) } } @JvmOverloads protected fun doCreateBranch(project: Project = doCreateProject(), nameDescription: NameDescription = nameDescription()): Branch { return asUser().with(project.id(), BranchCreate::class.java).call { structureService.newBranch( of(project, nameDescription) ) } } @JvmOverloads protected fun doCreateBuild(branch: Branch = doCreateBranch(), nameDescription: NameDescription = nameDescription(), signature: Signature = of("test")): Build { return asUser().with(branch.projectId(), BuildCreate::class.java).call { structureService.newBuild( of( branch, nameDescription, signature ) ) } } @JvmOverloads fun doValidateBuild( build: Build, vs: ValidationStamp, statusId: ValidationRunStatusID?, runData: ValidationRunData<*>? = null ): ValidationRun { return asUser().withView(build).with(build, ValidationRunCreate::class.java).call { structureService.newValidationRun( build, ValidationRunRequest( vs.name, statusId, runData?.descriptor?.id, runData?.data, null ) ) } } fun doValidateBuild(build: Build, vsName: String, statusId: ValidationRunStatusID): ValidationRun { val vs = doCreateValidationStamp(build.branch, nd(vsName, "")) return doValidateBuild(build, vs, statusId) } @JvmOverloads protected fun doCreatePromotionLevel(branch: Branch = doCreateBranch(), nameDescription: NameDescription = nameDescription()): PromotionLevel { return asUser().with(branch.projectId(), PromotionLevelCreate::class.java).call { structureService.newPromotionLevel( PromotionLevel.of( branch, nameDescription ) ) } } protected fun doCreateValidationStamp(): ValidationStamp { return doCreateValidationStamp(doCreateBranch(), nameDescription()) } protected fun doCreateValidationStamp(config: ValidationDataTypeConfig<*>?): ValidationStamp { return doCreateValidationStamp(doCreateBranch(), nameDescription(), config) } @JvmOverloads fun doCreateValidationStamp(branch: Branch, nameDescription: NameDescription, config: ValidationDataTypeConfig<*>? = null): ValidationStamp { return asUser().with(branch.project.id(), ValidationStampCreate::class.java).call { structureService.newValidationStamp( ValidationStamp.of( branch, nameDescription ).withDataType(config) ) } } @JvmOverloads protected fun doPromote(build: Build, promotionLevel: PromotionLevel, description: String?, signature: Signature = of("test")): PromotionRun { return asUser().with(build.projectId(), PromotionRunCreate::class.java).call { structureService.newPromotionRun( of( build, promotionLevel, signature, description ) ) } } protected fun <T> doSetProperty(entity: ProjectEntity, propertyType: Class<out PropertyType<T>>, data: T) { asUser().with(entity, ProjectEdit::class.java).call { propertyService.editProperty( entity, propertyType, data ) } } protected fun asUser(): UserCall = UserCall() protected fun asUserWithAuthenticationSource(authenticationSource: AuthenticationSource): UserCall = UserCall(authenticationSource) protected fun asAdmin(): AdminCall = AdminCall() protected fun asAnonymous(): AnonymousCall { return AnonymousCall() } protected fun asUserWithView(vararg entities: ProjectEntity): ConfigurableAccountCall { var user: ConfigurableAccountCall = asUser() for (entity in entities) { user = user.withView(entity) } return user } protected fun asFixedAccount(account: Account): AccountCall<*> { return FixedAccountCall(account) } protected fun <T> asFixedAccount(account: Account, code: () -> T): T = asFixedAccount(account).call(code) protected fun asConfigurableAccount(account: Account): ConfigurableAccountCall { return ConfigurableAccountCall(account) } protected fun asGlobalRole(role: String): AccountCall<*> { return FixedAccountCall(doCreateAccountWithGlobalRole(role)) } protected fun <T> asGlobalRole(role: String, code: () -> T): T = asGlobalRole(role).call(code) protected fun <T> view(projectEntity: ProjectEntity, callable: Callable<T>): T { return asUser().with(projectEntity.projectId(), ProjectView::class.java).call { callable.call() } } /** * This must always be called from [withGrantViewToAll] or [withNoGrantViewToAll]. */ private fun securitySettings(settings: SecuritySettings): SecuritySettings = asUser().with(GlobalSettings::class.java).call { val old = cachedSettingsService.getCachedSettings(SecuritySettings::class.java) settingsManagerService.saveSettings(settings) old } private fun <T> withSettings(grantViewToAll: Boolean, grantParticipationToAll: Boolean = true, task: () -> T): T { val old = securitySettings(SecuritySettings( isGrantProjectViewToAll = grantViewToAll, isGrantProjectParticipationToAll = grantParticipationToAll )) return try { task() } finally { securitySettings(old) } } protected fun <T> withGrantViewToAll(task: () -> T): T = withSettings( grantViewToAll = true, grantParticipationToAll = true, task = task ) protected fun <T> withGrantViewAndNOParticipationToAll(task: () -> T): T = withSettings( grantViewToAll = true, grantParticipationToAll = false, task = task ) protected fun <T> withNoGrantViewToAll(task: () -> T): T = withSettings( grantViewToAll = false, grantParticipationToAll = true, task = task ) protected interface ContextCall { fun <T> call(call: () -> T): T } protected abstract class AbstractContextCall : ContextCall { override fun <T> call(call: () -> T): T { // Gets the current context val oldContext = SecurityContextHolder.getContext() return try { // Sets the new context contextSetup() // Call call() } finally { // Restores the context SecurityContextHolder.setContext(oldContext) } } fun execute(task: () -> Unit) = call(task) fun execute(task: Runnable) { call { task.run() } } protected abstract fun contextSetup() } protected class AnonymousCall : AbstractContextCall() { override fun contextSetup() { val context: SecurityContext = SecurityContextImpl() context.authentication = null SecurityContextHolder.setContext(context) } } protected open inner class AccountCall<T : AccountCall<T>>( protected val account: Account ) : AbstractContextCall() { override fun contextSetup() { val context: SecurityContext = SecurityContextImpl() val ontrackAuthenticatedUser = createOntrackAuthenticatedUser() val authentication = TestingAuthenticationToken( ontrackAuthenticatedUser, "", account.role.name ) context.authentication = authentication SecurityContextHolder.setContext(context) } protected open fun createOntrackAuthenticatedUser(): OntrackAuthenticatedUser = accountService.withACL(TestOntrackUser(account)) } protected inner class FixedAccountCall(account: Account) : AccountCall<FixedAccountCall>(account) protected open inner class ConfigurableAccountCall( account: Account ) : AccountCall<ConfigurableAccountCall>(account) { /** * Global function associated to any global role to create */ private val globalFunctions = mutableSetOf<Class<out GlobalFunction>>() /** * Project function associated to any project role to create */ private val projectFunctions = mutableMapOf<Int, MutableSet<Class<out ProjectFunction>>>() /** * Associates a list of global functions to this account */ @SafeVarargs fun with(vararg fn: Class<out GlobalFunction>): ConfigurableAccountCall { globalFunctions.addAll(fn) return this } /** * Associates a list of project functions for a given project to this account */ fun with(projectId: Int, fn: Class<out ProjectFunction>): ConfigurableAccountCall { val projectFns = projectFunctions.getOrPut(projectId) { mutableSetOf() } projectFns.add(fn) return this } /** * Associates a list of project functions for a given project (designated by the [entity][e]) to this account */ fun with(e: ProjectEntity, fn: Class<out ProjectFunction>): ConfigurableAccountCall { return with(e.projectId(), fn) } /** * Grants the [ProjectView] function to this account and the project designated by the [entity][e]. */ fun withView(e: ProjectEntity): ConfigurableAccountCall { return with(e, ProjectView::class.java) } override fun contextSetup() { val context: SecurityContext = SecurityContextImpl() val ontrackAuthenticatedUser = createOntrackAuthenticatedUser() val authentication = TestingAuthenticationToken( ontrackAuthenticatedUser, "", account.role.name ) context.authentication = authentication SecurityContextHolder.setContext(context) } override fun createOntrackAuthenticatedUser(): OntrackAuthenticatedUser { // Configures the account securityService.asAdmin { // Creating a global role if some global functions are required if (globalFunctions.isNotEmpty()) { val globalRoleId = uid("GR") rolesService.registerGlobalRole( id = globalRoleId, name = "Test role $globalRoleId", description = "Test role $globalRoleId", globalFunctions = globalFunctions.toList(), projectFunctions = emptyList() ) accountService.saveGlobalPermission( PermissionTargetType.ACCOUNT, account.id(), PermissionInput(globalRoleId) ) } // Project permissions projectFunctions.forEach { (projectId, functions) -> if (functions.isNotEmpty()) { val projectRoleId = uid("PR") rolesService.registerProjectRole( id = projectRoleId, name = "Test role $projectRoleId", description = "Test role $projectRoleId", projectFunctions = functions.toList() ) accountService.saveProjectPermission( of(projectId), PermissionTargetType.ACCOUNT, account.id(), PermissionInput(projectRoleId) ) } } } // Loading the account return super.createOntrackAuthenticatedUser() } } protected inner class UserCall( authenticationSource: AuthenticationSource? = null, ) : ConfigurableAccountCall( securityService.asAdmin { val name = uid("U") val accountInput = AccountInput( name, "$name von Test", "[email protected]", "xxx", emptyList(), disabled = false, locked = false, ) if (authenticationSource != null) { accountService.create(accountInput, authenticationSource) } else { accountService.create(accountInput) } } ) protected inner class AdminCall : AccountCall<AdminCall>( // Loading the predefined admin account securityService.asAdmin { accountService.getAccount(of(1)) } ) }
mit
0ace49fa41132e4e019ff611e69546d9
35.966038
164
0.583555
5.787888
false
false
false
false
goodwinnk/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/migLayout/patched/MigLayout.kt
4
13751
/* * License (BSD): * ============== * * Copyright (c) 2004, Mikael Grev, MiG InfoCom AB. (miglayout (at) miginfocom (dot) com) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * Neither the name of the MiG InfoCom AB nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * @version 1.0 * @author Mikael Grev, MiG InfoCom AB * Date: 2006-sep-08 */ package com.intellij.ui.layout.migLayout.patched import gnu.trove.THashMap import net.miginfocom.layout.* import java.awt.* import java.awt.event.ActionListener import javax.swing.* /** A very flexible layout manager. * Read the documentation that came with this layout manager for information on usage. */ open class MigLayout @JvmOverloads constructor(val layoutConstraints: LC = LC(), val columnConstraints: AC = AC(), val rowConstraints: AC = AC()) : LayoutManager2 { @Transient private var cacheParentW: ContainerWrapper? = null @Transient private val componentWrapperToConstraints = THashMap<ComponentWrapper, CC>() @Transient private var debugTimer: Timer? = null @Transient private var grid: Grid? = null @Transient private var lastModCount = PlatformDefaults.getModCount() @Transient private var lastHash = -1 @Transient private var lastInvalidSize: Dimension? = null @Transient private var lastWasInvalid = false @Transient private var lastParentSize: Dimension? = null @Transient private var dirty = true var isDebugEnabled: Boolean = false private val debugMillis: Int get() { val globalDebugMillis = LayoutUtil.getGlobalDebugMillis() return if (globalDebugMillis > 0) globalDebugMillis else layoutConstraints.debugMillis } private var lastSize: Long = 0 private fun stopDebug() { if (debugTimer != null) { debugTimer!!.stop() debugTimer = null } } /** Sets the debugging state for this layout manager instance. If debug is turned on a timer will repaint the last laid out parent * with debug information on top. * * Red fill and dashed red outline is used to indicate occupied cells in the grid. Blue dashed outline indicate * component bounds set. * * Note that debug can also be set on the layout constraints. There it will be persisted. The value set here will not. See the class * JavaDocs for information. * @param parentWrapper The parent to set debug for. */ private fun startDebug(parentWrapper: ComponentWrapper?) { if (debugTimer?.delay == debugMillis) { return } debugTimer?.stop() debugTimer = Timer(debugMillis, ActionListener { val grid = grid if (grid != null && (grid.container.component as Component).isShowing) { grid.paintDebug() } else { debugTimer!!.stop() debugTimer = null } }) val parent = parentWrapper?.parent?.component as? Component if (parent != null) { SwingUtilities.invokeLater { val p = parent.parent ?: return@invokeLater if (p is JComponent) { p.revalidate() } else { parent.invalidate() p.validate() } } } debugTimer!!.initialDelay = 100 debugTimer!!.start() } /** Check if something has changed and if so recreate it to the cached objects. * @param parent The parent that is the target for this layout manager. */ private fun checkCache(parent: Container) { if (dirty) { grid = null } componentWrapperToConstraints.retainEntries { wrapper, _ -> (wrapper as SwingComponentWrapper).component.parent === parent } // check if the grid is valid val mc = PlatformDefaults.getModCount() if (lastModCount != mc) { grid = null lastModCount = mc } if (parent.isValid) { lastWasInvalid = false } else if (!lastWasInvalid) { lastWasInvalid = true var hash = 0 var resetLastInvalidOnParent = false // Added in 3.7.3 to resolve a timing regression introduced in 3.7.1 for (wrapper in componentWrapperToConstraints.keys) { val component = wrapper.component if (component is JTextArea || component is JEditorPane) { resetLastInvalidOnParent = true } hash = hash xor wrapper.layoutHashCode hash += 285134905 } if (resetLastInvalidOnParent) { resetLastInvalidOnParent(parent) } if (hash != lastHash) { grid = null lastHash = hash } val ps = parent.size if (lastInvalidSize == null || lastInvalidSize != ps) { grid = null lastInvalidSize = ps } } val par = checkParent(parent) if (debugMillis > 0) { startDebug(par) } else { stopDebug() } if (grid == null) { grid = Grid(par!!, layoutConstraints, rowConstraints, columnConstraints, componentWrapperToConstraints, null) } dirty = false } /** * @since 3.7.3 */ private fun resetLastInvalidOnParent(parent: Container?) { @Suppress("NAME_SHADOWING") var parent = parent while (parent != null) { val layoutManager = parent.layout if (layoutManager is MigLayout) { layoutManager.lastWasInvalid = false } parent = parent.parent } } private fun checkParent(parent: Container?): ContainerWrapper? { if (parent == null) { return null } if (cacheParentW == null || cacheParentW!!.component !== parent) { cacheParentW = SwingContainerWrapper((parent as JComponent?)!!) } return cacheParentW } override fun layoutContainer(parent: Container) { synchronized(parent.treeLock) { checkCache(parent) val insets = parent.insets val bounds = intArrayOf(insets.left, insets.top, parent.width - insets.left - insets.right, parent.height - insets.top - insets.bottom) val isDebugEnabled = isDebugEnabled || debugMillis > 0 if (grid!!.layout(bounds, layoutConstraints.alignX, layoutConstraints.alignY, isDebugEnabled)) { grid = null checkCache(parent) grid!!.layout(bounds, layoutConstraints.alignX, layoutConstraints.alignY, isDebugEnabled) } val newSize = grid!!.height[1] + (grid!!.width[1].toLong() shl 32) if (lastSize != newSize) { lastSize = newSize val containerWrapper = checkParent(parent) val win = SwingUtilities.getAncestorOfClass(Window::class.java, containerWrapper!!.component as Component) as? Window if (win != null) { if (win.isVisible) { SwingUtilities.invokeLater { adjustWindowSize(containerWrapper) } } else { adjustWindowSize(containerWrapper) } } } lastInvalidSize = null } } /** Checks the parent window/popup if its size is within parameters as set by the LC. * @param parent The parent who's window to possibly adjust the size for. */ private fun adjustWindowSize(parent: ContainerWrapper?) { val wBounds = layoutConstraints.packWidth val hBounds = layoutConstraints.packHeight if (wBounds === BoundSize.NULL_SIZE && hBounds === BoundSize.NULL_SIZE) { return } val packable = getPackable(parent!!.component as Component) ?: return val pc = parent.component as Component var c = pc as? Container ?: pc.parent while (c != null) { val layout = c.layout if (layout is BoxLayout || layout is OverlayLayout) { (layout as LayoutManager2).invalidateLayout(c) } c = c.parent } val prefSize = packable.preferredSize val targetW = constrain(checkParent(packable), packable.width, prefSize.width, wBounds) val targetH = constrain(checkParent(packable), packable.height, prefSize.height, hBounds) val p = if (packable.isShowing) packable.locationOnScreen else packable.location val x = Math.round(p.x - (targetW - packable.width) * (1 - layoutConstraints.packWidthAlign)) val y = Math.round(p.y - (targetH - packable.height) * (1 - layoutConstraints.packHeightAlign)) if (packable is JPopupMenu) { val popupMenu = packable as JPopupMenu? popupMenu!!.isVisible = false popupMenu.setPopupSize(targetW, targetH) val invoker = popupMenu.invoker val popPoint = Point(x, y) SwingUtilities.convertPointFromScreen(popPoint, invoker) packable.show(invoker, popPoint.x, popPoint.y) // reset preferred size so we don't read it again. packable.preferredSize = null } else { packable.setBounds(x, y, targetW, targetH) } } /** * Returns a high level window or popup to pack, if any. */ private fun getPackable(comp: Component): Container? { val popup = findType(JPopupMenu::class.java, comp) if (popup != null) { // Lightweight/HeavyWeight popup must be handled separately var popupComp: Container? = popup while (popupComp != null) { if (popupComp.javaClass.name.contains("HeavyWeightWindow")) { // return the heavy weight window for normal processing return popupComp } popupComp = popupComp.parent } return popup // Return the JPopup. } return findType(Window::class.java, comp) } private fun constrain(parent: ContainerWrapper?, winSize: Int, prefSize: Int, constrain: BoundSize?): Int { if (constrain == null) { return winSize } var retSize = winSize constrain.preferred?.let { wUV -> retSize = wUV.getPixels(prefSize.toFloat(), parent, parent) } retSize = constrain.constrain(retSize, prefSize.toFloat(), parent) return if (constrain.gapPush) Math.max(winSize, retSize) else retSize } fun getComponentConstraints(): Map<Component, CC> { val result = THashMap<Component, CC>() for (entry in componentWrapperToConstraints) { result.put((entry.key as SwingComponentWrapper).component, entry.value) } return result } override fun minimumLayoutSize(parent: Container): Dimension { synchronized(parent.treeLock) { return getSizeImpl(parent, LayoutUtil.MIN) } } override fun preferredLayoutSize(parent: Container): Dimension { synchronized(parent.treeLock) { if (lastParentSize == null || parent.size != lastParentSize) { for (wrapper in componentWrapperToConstraints.keys) { if (wrapper.contentBias != -1) { layoutContainer(parent) break } } } lastParentSize = parent.size return getSizeImpl(parent, LayoutUtil.PREF) } } override fun maximumLayoutSize(parent: Container): Dimension = Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE) private fun getSizeImpl(parent: Container, sizeType: Int): Dimension { checkCache(parent) val i = parent.insets val grid = grid val w = LayoutUtil.getSizeSafe(grid?.width, sizeType) + i.left + i.right val h = LayoutUtil.getSizeSafe(grid?.height, sizeType) + i.top + i.bottom return Dimension(w, h) } override fun getLayoutAlignmentX(parent: Container): Float { val alignX = layoutConstraints.alignX ?: return 0f return alignX.getPixels(1f, checkParent(parent), null).toFloat() } override fun getLayoutAlignmentY(parent: Container): Float { val alignY = layoutConstraints.alignY ?: return 0f return alignY.getPixels(1f, checkParent(parent), null).toFloat() } override fun addLayoutComponent(s: String, comp: Component) { addLayoutComponent(comp, s) } override fun addLayoutComponent(comp: Component, constraints: Any?) { synchronized(comp.parent.treeLock) { val componentWrapper = SwingComponentWrapper(comp as JComponent) if (constraints != null) { componentWrapperToConstraints.put(componentWrapper, constraints as CC) } dirty = true } } override fun removeLayoutComponent(comp: Component) { synchronized(comp.parent.treeLock) { componentWrapperToConstraints.remove(SwingComponentWrapper(comp as JComponent)) // to clear references grid = null } } override fun invalidateLayout(target: Container) { dirty = true } } private fun <E> findType(clazz: Class<E>, comp: Component?): E? { @Suppress("NAME_SHADOWING") var comp = comp while (comp != null && !clazz.isInstance(comp)) { comp = comp.parent } @Suppress("UNCHECKED_CAST") return comp as E? }
apache-2.0
ba7410946b6b15f978acac1737390907
30.907193
164
0.674642
4.328297
false
false
false
false
d9n/intellij-rust
src/main/kotlin/org/rust/lang/refactoring/RsPromoteModuleToDirectoryAction.kt
1
2320
package org.rust.lang.refactoring import com.intellij.lang.Language import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.impl.file.PsiFileImplUtil import com.intellij.refactoring.RefactoringActionHandler import com.intellij.refactoring.actions.BaseRefactoringAction import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import org.rust.ide.utils.checkWriteAccessAllowed import org.rust.lang.RsLanguage import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.ext.RsMod class RsPromoteModuleToDirectoryAction : BaseRefactoringAction() { override fun isEnabledOnElements(elements: Array<out PsiElement>): Boolean = elements.all { it is RsFile && it.name != RsMod.MOD_RS } override fun getHandler(dataContext: DataContext): RefactoringActionHandler = Handler override fun isAvailableInEditorOnly(): Boolean = false override fun isAvailableForLanguage(language: Language): Boolean = language.`is`(RsLanguage) private object Handler : RefactoringActionHandler { override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) { invoke(project, arrayOf(file), dataContext) } override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) { WriteCommandAction.runWriteCommandAction(project) { for (element in elements.filterIsInstance<RsFile>()) { expandModule(element) } } } } companion object { fun expandModule(file: RsFile) { checkWriteAccessAllowed() val dirName = FileUtil.getNameWithoutExtension(file.name) val directory = file.containingDirectory?.createSubdirectory(dirName) ?: error("Can't expand file: no parent directory for $file at ${file.virtualFile.path}") MoveFilesOrDirectoriesUtil.doMoveFile(file, directory) PsiFileImplUtil.setName(file, RsMod.MOD_RS) } } }
mit
af54f6cfb2892de9409693fb8b6c888b
40.428571
107
0.734052
4.946695
false
false
false
false
olonho/carkot
translator/src/test/kotlin/tests/get_set_operators_1/get_set_operators_1.kt
1
425
class get_set_operators_1_class { var cap = 9 operator fun get(x: Int): Int { return x + 8 } operator fun set(x: Int, y: Int): Unit { cap = x + y } } fun get_set_operators_1_get(arg: Int): Int { val b = get_set_operators_1_class() return b[arg] } fun get_set_operators_1_set(ind: Int, arg: Int): Int { val b = get_set_operators_1_class() b[ind] = arg return b.cap }
mit
0e8ae65982d58fcc5d229eba68857f96
18.363636
54
0.56
2.81457
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/NinePatchEx.kt
1
4096
package com.soywiz.korge.view import com.soywiz.kds.* import com.soywiz.korge.debug.* import com.soywiz.korge.render.* import com.soywiz.korim.bitmap.* import com.soywiz.korio.file.* import com.soywiz.korma.geom.* import com.soywiz.korui.* inline fun Container.ninePatch( ninePatch: NinePatchBmpSlice?, width: Double = ninePatch?.dwidth ?: 16.0, height: Double = ninePatch?.dheight ?: 16.0, callback: @ViewDslMarker NinePatchEx.() -> Unit = {} ) = NinePatchEx(ninePatch, width, height).addTo(this, callback) class NinePatchEx( ninePatch: NinePatchBmpSlice?, override var width: Double = ninePatch?.width?.toDouble() ?: 16.0, override var height: Double = ninePatch?.height?.toDouble() ?: 16.0 ) : View(), ViewFileRef by ViewFileRef.Mixin() { var ninePatch: NinePatchBmpSlice? = ninePatch var smoothing = true private val bounds = RectangleInt() override fun renderInternal(ctx: RenderContext) { if (!visible) return lazyLoadRenderInternal(ctx, this) val m = globalMatrix val xscale = m.a val yscale = m.d bounds.setTo(0, 0, (width * xscale).toInt(), (height * yscale).toInt()) m.keep { prescale(1.0 / xscale, 1.0 / yscale) val ninePatch = ninePatch if (ninePatch != null) { recomputeVerticesIfRequired() val tvaCached = [email protected] if (tvaCached != null) { if (cachedMatrix != m) { cachedMatrix.copyFrom(m) tvaCached.copyFrom(tva!!) tvaCached.applyMatrix(m) } ctx.useBatcher { batch -> batch.drawVertices(tvaCached, ctx.getTex(ninePatch.content.bmp), smoothing, blendMode.factors) } } } } } private var tva: TexturedVertexArray? = null private var tvaCached: TexturedVertexArray? = null private var cachedMatrix: Matrix = Matrix() private var cachedNinePatch: NinePatchBmpSlice? = null private val cachedBounds = RectangleInt() private fun recomputeVerticesIfRequired() { val viewBounds = this.bounds if (cachedBounds.rect == viewBounds.rect && cachedNinePatch == ninePatch) return cachedBounds.rect.copyFrom(viewBounds.rect) cachedNinePatch = ninePatch val ninePatch = ninePatch if (ninePatch == null) { tva = null tvaCached = null return } val numQuads = ninePatch.info.totalSegments val indices = TexturedVertexArray.quadIndices(numQuads) val tva = TexturedVertexArray(numQuads * 4, indices) var index = 0 val matrix = Matrix() ninePatch.info.computeScale(viewBounds) { segment, x, y, width, height -> val bmpSlice = ninePatch.getSegmentBmpSlice(segment) tva.quad(index++ * 4, x.toFloat(), y.toFloat(), width.toFloat(), height.toFloat(), matrix, bmpSlice, renderColorMul, renderColorAdd ) } this.tva = tva this.tvaCached = TexturedVertexArray(numQuads * 4, indices) this.cachedMatrix.setToNan() } override fun getLocalBoundsInternal(out: Rectangle) { out.setTo(0.0, 0.0, width, height) } override suspend fun forceLoadSourceFile(views: Views, currentVfs: VfsFile, sourceFile: String?) { baseForceLoadSourceFile(views, currentVfs, sourceFile) //println("### Trying to load sourceImage=$sourceImage") ninePatch = try { currentVfs["$sourceFile"].readNinePatch() } catch (e: Throwable) { NinePatchBitmap32(Bitmap32(62, 62)) } } override fun buildDebugComponent(views: Views, container: UiContainer) { container.uiCollapsibleSection("9-PatchImage") { uiEditableValue(::sourceFile, kind = UiTextEditableValue.Kind.FILE(views.currentVfs) { it.baseName.endsWith(".9.png") }) } super.buildDebugComponent(views, container) } }
apache-2.0
771ed0a464c08071a2fc1148df4b7e82
34.617391
119
0.621826
4.043435
false
false
false
false
Ribesg/anko
dsl/static/src/common/AnkoContext.kt
1
3480
package org.jetbrains.anko import android.app.Activity import android.app.Fragment import android.content.Context import android.content.ContextWrapper import android.view.View import android.view.ViewGroup import android.view.ViewManager import org.jetbrains.anko.internals.AnkoInternals import org.jetbrains.anko.internals.AnkoInternals.createAnkoContext interface AnkoContext<T> : ViewManager { val ctx: Context val owner: T val view: View override fun updateViewLayout(view: View, params: ViewGroup.LayoutParams) { throw UnsupportedOperationException() } override fun removeView(view: View) { throw UnsupportedOperationException() } companion object { fun create(ctx: Context): AnkoContext<Context> = AnkoContextImpl(ctx, ctx, false) fun createReusable(ctx: Context): AnkoContext<Context> = ReusableAnkoContext(ctx, ctx, false) fun <T> create(ctx: Context, owner: T): AnkoContext<T> = AnkoContextImpl(ctx, owner, false) fun <T> createReusable(ctx: Context, owner: T): AnkoContext<T> = ReusableAnkoContext(ctx, owner, false) fun <T: ViewGroup> createDelegate(owner: T): AnkoContext<T> = DelegatingAnkoContext(owner) } } internal class DelegatingAnkoContext<T: ViewGroup>(override val owner: T): AnkoContext<T> { override val ctx = owner.context override val view: View = owner override fun addView(view: View?, params: ViewGroup.LayoutParams?) { if (view == null) return if (params == null) { owner.addView(view) } else { owner.addView(view, params) } } } internal class ReusableAnkoContext<T>( override val ctx: Context, override val owner: T, private val setContentView: Boolean ) : AnkoContextImpl<T>(ctx, owner, setContentView) { override fun alreadyHasView() {} } open class AnkoContextImpl<T>( override val ctx: Context, override val owner: T, private val setContentView: Boolean ) : AnkoContext<T> { private var myView: View? = null override val view: View get() = myView ?: throw IllegalStateException("View was not set previously") override fun addView(view: View?, params: ViewGroup.LayoutParams?) { if (view == null) return if (myView != null) { alreadyHasView() } this.myView = view if (setContentView) { doAddView(ctx, view) } } private fun doAddView(context: Context, view: View) { when (context) { is Activity -> context.setContentView(view) is ContextWrapper -> doAddView(context.baseContext, view) else -> throw IllegalStateException("Context is not an Activity, can't set content view") } } open protected fun alreadyHasView(): Unit = throw IllegalStateException("View is already set: $myView") } @AnkoInternals.NoBinding fun Context.UI(setContentView: Boolean, init: AnkoContext<Context>.() -> Unit) = createAnkoContext(this, init, setContentView) fun Context.UI(init: AnkoContext<Context>.() -> Unit) = createAnkoContext(this, init) fun Fragment.UI(init: AnkoContext<Fragment>.() -> Unit): AnkoContext<Fragment> = createAnkoContext(activity, init) interface AnkoComponent<T> { fun createView(ui: AnkoContext<T>): View } fun <T : Activity> AnkoComponent<T>.setContentView(activity: T) = createView(AnkoContextImpl(activity, activity, true))
apache-2.0
6be7d1ab72dfd3539692782877243edd
31.839623
114
0.68046
4.382872
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/analytics/FeedFunnel.kt
2
1843
package org.wikipedia.analytics import org.wikipedia.WikipediaApp import org.wikipedia.feed.model.CardType class FeedFunnel(app: WikipediaApp) : TimedFunnel(app, SCHEMA_NAME, REVISION, SAMPLE_LOG_100) { private var entered = false fun enter() { if (!entered) { entered = true resetDuration() log( "action", "enter" ) } } fun exit() { if (entered) { entered = false log( "action", "exit" ) } } fun cardShown(cardType: CardType, languageCode: String?) { if (EXCLUDED_CARDS.contains(cardType)) { return } log( "action", "cardShown", "cardType", cardType.code(), "language", languageCode ) } fun cardClicked(cardType: CardType, languageCode: String?) { if (EXCLUDED_CARDS.contains(cardType)) { return } log( "action", "cardClicked", "cardType", cardType.code(), "language", languageCode ) } fun requestMore(age: Int) { log( "action", "more", "age", age ) } fun refresh(age: Int) { log( "action", "refresh", "age", age ) } fun dismissCard(cardType: CardType, position: Int) { log( "action", "dismiss", "cardType", cardType.code(), "position", position ) } companion object { private const val SCHEMA_NAME = "MobileWikiAppFeed" private const val REVISION = 18115458 private val EXCLUDED_CARDS = listOf(CardType.SEARCH_BAR, CardType.PROGRESS) } }
apache-2.0
8f0552156f392ff31e4aacd6d56d79f6
22.628205
95
0.483451
4.689567
false
false
false
false
chaseberry/Sprint
src/main/kotlin/edu/csh/chase/sprint/Response.kt
1
2322
package edu.csh.chase.sprint import edu.csh.chase.kjson.Json import edu.csh.chase.kjson.JsonBase import okhttp3.Headers import java.io.IOException import okhttp3.Response as OkResponse sealed class Response(val request: Request) { abstract override fun toString(): String class Success(request: Request, val statusCode: Int, val body: ByteArray?, val headers: Headers?) : Response(request) { constructor(request: Request, response: OkResponse) : this(request, response.code, response.body?.bytes(), response.headers) val bodyAsJson: JsonBase? get() = bodyAsString?.let { Json.parse(it) } val bodyAsString: String? get() = body?.let { String(it) } override fun toString(): String = bodyAsString ?: "null" } class Failure(request: Request, val statusCode: Int, val body: ByteArray?, val headers: Headers?) : Response(request) { constructor(request: Request, response: OkResponse) : this(request, response.code, response.body?.bytes(), response.headers) val bodyAsJson: JsonBase? get() = bodyAsString?.let { Json.parse(it) } val bodyAsString: String? get() = body?.let { String(it) } override fun toString(): String = bodyAsString ?: "null" } class ConnectionError(request: Request, val error: IOException) : Response(request) { override fun toString(): String = error.message ?: "null" } val code: Int? get() = when (this) { is Success -> statusCode is Failure -> statusCode else -> null } companion object { fun from(response: okhttp3.Response, request: Request): Response { val code = response.code return if (code in 200..299) { Response.Success( request = request, statusCode = code, body = response.body?.use { it.bytes() }, headers = response.headers ) } else { Response.Failure( request = request, statusCode = code, body = response.body?.use { it.bytes() }, headers = response.headers ) } } } }
apache-2.0
656391232dcab85cb8b215232aa3b12b
29.565789
132
0.572351
4.607143
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/imagemanipulator/actions/CropAction.kt
2
1170
package abi42_0_0.expo.modules.imagemanipulator.actions import android.graphics.Bitmap private const val KEY_ORIGIN_X = "originX" private const val KEY_ORIGIN_Y = "originY" private const val KEY_WIDTH = "width" private const val KEY_HEIGHT = "height" class CropAction(private val originX: Int, private val originY: Int, private val width: Int, private val height: Int) : Action { override fun run(bitmap: Bitmap): Bitmap { require( originX <= bitmap.width && originY <= bitmap.height && originX + width <= bitmap.width && originY + height <= bitmap.height ) { "Invalid crop options have been passed. Please make sure the requested crop rectangle is inside source image." } return Bitmap.createBitmap(bitmap, originX, originY, width, height) } companion object { fun fromObject(o: Any): CropAction { require(o is Map<*, *>) val originX = (o[KEY_ORIGIN_X] as Double).toInt() val originY = (o[KEY_ORIGIN_Y] as Double).toInt() val width = (o[KEY_WIDTH] as Double).toInt() val height = (o[KEY_HEIGHT] as Double).toInt() return CropAction(originX, originY, width, height) } } }
bsd-3-clause
508a20cd6604f1378710b97db4e26927
36.741935
128
0.675214
3.848684
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/input/rotary/RotaryScrollEventTest.kt
3
7599
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.input.rotary import android.view.MotionEvent.ACTION_SCROLL import android.view.View import android.view.ViewConfiguration import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.requiredSize import androidx.compose.runtime.Composable import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.focusTarget import androidx.compose.ui.platform.LocalView import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onRoot import androidx.compose.ui.test.performRotaryScrollInput import androidx.compose.ui.unit.dp import androidx.core.view.InputDeviceCompat.SOURCE_ROTARY_ENCODER import androidx.core.view.ViewConfigurationCompat.getScaledHorizontalScrollFactor import androidx.core.view.ViewConfigurationCompat.getScaledVerticalScrollFactor import androidx.test.core.view.MotionEventBuilder import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @OptIn(ExperimentalComposeUiApi::class) @MediumTest @RunWith(AndroidJUnit4::class) class RotaryScrollEventTest { @get:Rule val rule = createComposeRule() private val initialFocus = FocusRequester() private lateinit var rootView: View private var receivedEvent: RotaryScrollEvent? = null private val tolerance: Float = 0.000001f @Test fun androidWearCrownRotation_triggersRotaryEvent() { // Arrange. ContentWithInitialFocus { Box( modifier = Modifier .onRotaryScrollEvent { receivedEvent = it true } .focusable(initiallyFocused = true) ) } // Act. rule.runOnIdle { rootView.dispatchGenericMotionEvent( MotionEventBuilder.newBuilder() .setAction(ACTION_SCROLL) .setSource(SOURCE_ROTARY_ENCODER) .build() ) } // Assert. rule.runOnIdle { assertThat(receivedEvent).isNotNull() } } @Test fun focusedItemReceivesHorizontalRotaryEvent() { // Arrange. ContentWithInitialFocus { Box( modifier = Modifier .onRotaryScrollEvent { receivedEvent = it true } .focusable(initiallyFocused = true) ) } // Act. @OptIn(ExperimentalTestApi::class) rule.onRoot().performRotaryScrollInput { rotateToScrollHorizontally(3.0f) } // Assert. rule.runOnIdle { with(checkNotNull(receivedEvent)) { assertThat(verticalScrollPixels) .isWithin(tolerance).of(3.0f * verticalScrollFactor / horizontalScrollFactor) assertThat(horizontalScrollPixels).isWithin(tolerance).of(3.0f) } } } @Test fun focusedItemReceivesVerticalRotaryEvent() { // Arrange. ContentWithInitialFocus { Box( modifier = Modifier .onRotaryScrollEvent { receivedEvent = it true } .focusable(initiallyFocused = true) ) } // Act. @OptIn(ExperimentalTestApi::class) rule.onRoot().performRotaryScrollInput { rotateToScrollVertically(3.0f) } // Assert. rule.runOnIdle { with(checkNotNull(receivedEvent)) { assertThat(verticalScrollPixels).isWithin(tolerance).of(3.0f) assertThat(horizontalScrollPixels) .isWithin(tolerance).of(3.0f * horizontalScrollFactor / verticalScrollFactor) } } } @Test fun rotaryEventHasTime() { val TIME = 1234567890L // Arrange. ContentWithInitialFocus { Box( modifier = Modifier .onRotaryScrollEvent { receivedEvent = it true } .focusable(initiallyFocused = true) ) } // Act. rule.runOnIdle { rootView.dispatchGenericMotionEvent( MotionEventBuilder.newBuilder() .setAction(ACTION_SCROLL) .setSource(SOURCE_ROTARY_ENCODER) .setEventTime(TIME) .build() ) } // Assert. rule.runOnIdle { with(checkNotNull(receivedEvent)) { assertThat(uptimeMillis).isEqualTo(TIME) } } } @Test fun rotaryEventUsesTestTime() { val TIME_DELTA = 1234L val receivedEvents = mutableListOf<RotaryScrollEvent>() // Arrange. ContentWithInitialFocus { Box( modifier = Modifier .onRotaryScrollEvent { receivedEvents.add(it) true } .focusable(initiallyFocused = true) ) } // Act. @OptIn(ExperimentalTestApi::class) rule.onRoot().performRotaryScrollInput { rotateToScrollVertically(3.0f) advanceEventTime(TIME_DELTA) rotateToScrollVertically(3.0f) } // Assert. rule.runOnIdle { assertThat(receivedEvents.size).isEqualTo(2) assertThat(receivedEvents[1].uptimeMillis - receivedEvents[0].uptimeMillis) .isEqualTo(TIME_DELTA) } } private fun Modifier.focusable(initiallyFocused: Boolean = false) = this .then(if (initiallyFocused) Modifier.focusRequester(initialFocus) else Modifier) .focusTarget() private fun ContentWithInitialFocus(content: @Composable () -> Unit) { rule.setContent { rootView = LocalView.current Box(modifier = Modifier.requiredSize(10.dp, 10.dp)) { content() } } rule.runOnIdle { initialFocus.requestFocus() } } private val horizontalScrollFactor: Float get() = getScaledHorizontalScrollFactor( ViewConfiguration.get(rootView.context), rootView.context ) private val verticalScrollFactor: Float get() = getScaledVerticalScrollFactor( ViewConfiguration.get(rootView.context), rootView.context ) }
apache-2.0
c3211dd0611864c69eef03adc1086115
30.6625
97
0.600079
5.093164
false
true
false
false
exponent/exponent
packages/expo-image/android/src/main/java/expo/modules/image/okhttp/OkHttpClientProgressInterceptor.kt
2
1871
package expo.modules.image.okhttp import com.facebook.react.modules.network.ProgressListener import com.facebook.react.modules.network.ProgressResponseBody import okhttp3.Interceptor import okhttp3.Response import java.io.IOException import java.lang.ref.WeakReference import java.util.* object OkHttpClientProgressInterceptor : Interceptor { private val mProgressListeners: MutableMap<String, MutableCollection<WeakReference<ProgressListener>>> = HashMap() /** * Mostly copied from https://github.com/square/okhttp/blob/97a5e7a9e0cdafd2bb7cbc9a8bb1931082aaa0e4/samples/guide/src/main/java/okhttp3/recipes/Progress.java#L62-L69 * * @return An instance of [OkHttpClient.Builder] configured for notifying * [OkHttpClientProgressInterceptor] of new request information. */ @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val weakThis = WeakReference(this) val requestUrl = chain.call().request().url().toString() val originalResponse = chain.proceed(chain.request()) return originalResponse.newBuilder() .body(ProgressResponseBody(originalResponse.body()) { bytesWritten, contentLength, done -> val strongThis = weakThis.get() ?: return@ProgressResponseBody val urlListeners = strongThis.mProgressListeners[requestUrl] urlListeners?.forEach { it.get()?.onProgress(bytesWritten, contentLength, done) } if (done) { strongThis.mProgressListeners.remove(requestUrl) } }) .build() } fun registerProgressListener(requestUrl: String, requestListener: ProgressListener) { var requestListeners = mProgressListeners[requestUrl] if (requestListeners == null) { requestListeners = HashSet() mProgressListeners[requestUrl] = requestListeners } requestListeners.add(WeakReference(requestListener)) } }
bsd-3-clause
1ffd2a21584f9696a01e2ce7e183928e
40.577778
168
0.755211
4.444181
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/person/PersonContactItemsAdapter.kt
1
2430
package de.tum.`in`.tumcampusapp.component.tumui.person import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.tumui.person.adapteritems.AbstractContactItem import de.tum.`in`.tumcampusapp.component.tumui.person.adapteritems.MobilePhoneContactItem import de.tum.`in`.tumcampusapp.component.tumui.person.adapteritems.PhoneContactItem import kotlinx.android.synthetic.main.person_contact_item.view.* class PersonContactItemsAdapter( private val items: List<AbstractContactItem> ) : RecyclerView.Adapter<PersonContactItemsAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.person_contact_item, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val contactItem = items[position] // Figure out if this is the first item of its kind // If so, display the icon; otherwise, don't val classItems = items.filter { item -> if (contactItem::class.java == MobilePhoneContactItem::class.java) { // If it's a mobile phone number, we consider it part of the PhoneContactItem items item::class.java == contactItem::class.java || item::class.java == PhoneContactItem::class.java } else { item::class.java == contactItem::class.java } } val isFirstOfItsKind = classItems.first() == contactItem holder.bind(contactItem, isFirstOfItsKind) } override fun getItemCount() = items.size class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(item: AbstractContactItem, showIcon: Boolean = true) = with(itemView) { val resourceId = if (showIcon) item.iconResourceId else android.R.color.transparent iconImageView.setImageResource(resourceId) labelTextView.text = context.getString(item.labelResourceId) valueTextView.text = item.value setOnClickListener { val intent = item.getIntent(context) ?: return@setOnClickListener context.startActivity(intent) } } } }
gpl-3.0
eda8f8181b54ebae5de1b0090e1e5d2f
40.20339
111
0.690535
4.559099
false
false
false
false
androidx/androidx
compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/visualinspection/AnimatedVisibiltyContentSizeChange.kt
3
3227
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.animation.demos.visualinspection import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateContentSize import androidx.compose.animation.demos.gesture.pastelColors import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material.Button import androidx.compose.material.Checkbox import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Preview @Composable fun AnimatedVisibilityContentSizeChange() { Column { val isOpen = remember { mutableStateOf(true) } val itemListState = remember { mutableStateOf(listOf(1)) } val itemList = itemListState.value val (checked, onCheckedChanged) = remember { mutableStateOf(false) } Row( Modifier.height(60.dp).fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { Button( onClick = { isOpen.value = !isOpen.value }, modifier = Modifier.align(Alignment.CenterVertically) ) { Text("Toggle\n visibility") } Row(modifier = Modifier.align(Alignment.CenterVertically)) { Checkbox( checked, onCheckedChanged, ) Text("animateContentSize", Modifier.clickable { onCheckedChanged(!checked) }) } Button( onClick = { itemListState.value = itemList + (itemList.size + 1) }, modifier = Modifier.align(Alignment.CenterVertically) ) { Text("Add\n item") } } AnimatedVisibility(visible = isOpen.value) { Column( Modifier.background(pastelColors[2]).fillMaxWidth() .then(if (checked) Modifier.animateContentSize() else Modifier) ) { itemList.map { Text("Item #$it", Modifier.align(Alignment.CenterHorizontally)) } } } } }
apache-2.0
57a723b1909c84770354fc1e39819c81
36.534884
93
0.672141
4.964615
false
false
false
false
androidx/androidx
compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/text/selection/SelectionManagerDragTest.kt
3
11523
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text.selection import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.style.ResolvedTextDirection import androidx.compose.ui.unit.IntSize import com.google.common.truth.Truth.assertThat import org.mockito.kotlin.mock import org.mockito.kotlin.spy import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class SelectionManagerDragTest { private val selectionRegistrar = SelectionRegistrarImpl() private val selectableKey = 1L private val selectable = FakeSelectable().also { it.selectableId = this.selectableKey } private val selectionManager = SelectionManager(selectionRegistrar) private val size = IntSize(500, 600) private val globalOffset = Offset(100f, 200f) private val windowOffset = Offset(100f, 200f) private val childToLocalOffset = Offset(300f, 400f) private val containerLayoutCoordinates = spy( MockCoordinates( size = size, globalOffset = globalOffset, windowOffset = windowOffset, childToLocalOffset = childToLocalOffset, isAttached = true ) ) private val startSelectable = FakeSelectable() private val endSelectable = FakeSelectable() private val startSelectableKey = 2L private val endSelectableKey = 3L private val startLayoutCoordinates = mock<LayoutCoordinates>() private val endLayoutCoordinates = mock<LayoutCoordinates>() private val fakeSubselection: Selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 0, selectableId = selectableKey ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 5, selectableId = selectableKey ) ) private val fakeInitialSelection: Selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 0, selectableId = startSelectableKey ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 5, selectableId = endSelectableKey ) ) private val fakeResultSelection: Selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 5, selectableId = endSelectableKey ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 0, selectableId = startSelectableKey ) ) private var selection: Selection? = fakeInitialSelection private val lambda: (Selection?) -> Unit = { selection = it } private val spyLambda = spy(lambda) @Before fun setup() { startSelectable.clear() endSelectable.clear() startSelectable.layoutCoordinate = startLayoutCoordinates startSelectable.selectableId = startSelectableKey endSelectable.layoutCoordinate = endLayoutCoordinates endSelectable.selectableId = endSelectableKey selectionRegistrar.subscribe(selectable) selectionRegistrar.subscribe(startSelectable) selectionRegistrar.subscribe(endSelectable) selectionRegistrar.subselections = mapOf( selectableKey to fakeSubselection ) selectable.clear() selectable.selectionToReturn = fakeResultSelection selectionManager.containerLayoutCoordinates = containerLayoutCoordinates selectionManager.onSelectionChange = spyLambda selectionManager.selection = selection selectionManager.hapticFeedBack = mock() } @Test fun handleDragObserver_onStart_startHandle_enable_draggingHandle_get_startHandle_info() { selectionManager.handleDragObserver(isStartHandle = true).onStart(Offset.Zero) verify(containerLayoutCoordinates, times(1)) .localPositionOf( sourceCoordinates = startLayoutCoordinates, relativeToSource = getAdjustedCoordinates(Offset.Zero) ) verify(spyLambda, times(0)).invoke(fakeResultSelection) } @Test fun handleDragObserver_onStart_endHandle_enable_draggingHandle_get_endHandle_info() { selectionManager.handleDragObserver(isStartHandle = false).onStart(Offset.Zero) verify(containerLayoutCoordinates, times(1)) .localPositionOf( sourceCoordinates = endLayoutCoordinates, relativeToSource = getAdjustedCoordinates(Offset.Zero) ) verify(spyLambda, times(0)).invoke(fakeResultSelection) } @Test fun handleDragObserver_onDrag_startHandle_reuse_endHandle_calls_getSelection_change() { val startOffset = Offset(30f, 50f) val dragDistance = Offset(100f, 100f) selectionManager.handleDragObserver(isStartHandle = true).onStart(startOffset) selectionManager.handleDragObserver(isStartHandle = true).onDrag(dragDistance) verify(containerLayoutCoordinates, times(1)) .localPositionOf( sourceCoordinates = endLayoutCoordinates, relativeToSource = getAdjustedCoordinates(Offset.Zero) ) assertThat(selectable.getSelectionCalledTimes).isEqualTo(1) assertThat(selectable.lastStartHandlePosition).isEqualTo(childToLocalOffset + dragDistance) assertThat(selectable.lastEndHandlePosition).isEqualTo(childToLocalOffset) assertThat(selectable.lastContainerLayoutCoordinates) .isEqualTo(selectionManager.requireContainerCoordinates()) assertThat(selectable.lastAdjustment) .isEqualTo(SelectionAdjustment.CharacterWithWordAccelerate) assertThat(selectable.lastIsStartHandle).isEqualTo(true) assertThat(selectable.lastPreviousSelection).isEqualTo(fakeSubselection) assertThat(selection).isEqualTo(fakeResultSelection) verify(spyLambda, times(1)).invoke(fakeResultSelection) } @Test fun handleDragObserver_onDrag_endHandle_reuse_startHandle_calls_getSelection_change() { val startOffset = Offset(30f, 50f) val dragDistance = Offset(100f, 100f) selectionManager.handleDragObserver(isStartHandle = false).onStart(startOffset) selectionManager.handleDragObserver(isStartHandle = false).onDrag(dragDistance) verify(containerLayoutCoordinates, times(1)) .localPositionOf( sourceCoordinates = startLayoutCoordinates, relativeToSource = getAdjustedCoordinates(Offset.Zero) ) assertThat(selectable.getSelectionCalledTimes).isEqualTo(1) assertThat(selectable.lastEndHandlePosition).isEqualTo(childToLocalOffset + dragDistance) assertThat(selectable.lastStartHandlePosition).isEqualTo(childToLocalOffset) assertThat(selectable.lastContainerLayoutCoordinates) .isEqualTo(selectionManager.requireContainerCoordinates()) assertThat(selectable.lastAdjustment) .isEqualTo(SelectionAdjustment.CharacterWithWordAccelerate) assertThat(selectable.lastIsStartHandle).isEqualTo(false) assertThat(selectable.lastPreviousSelection).isEqualTo(fakeSubselection) assertThat(selection).isEqualTo(fakeResultSelection) verify(spyLambda, times(1)).invoke(fakeResultSelection) } private fun getAdjustedCoordinates(position: Offset): Offset { return Offset(position.x, position.y - 1f) } } internal class FakeSelectable : Selectable { override var selectableId = 0L var lastEndHandlePosition: Offset? = null var lastStartHandlePosition: Offset? = null var lastPreviousHandlePosition: Offset? = null var lastContainerLayoutCoordinates: LayoutCoordinates? = null var lastAdjustment: SelectionAdjustment? = null var lastPreviousSelection: Selection? = null var lastIsStartHandle: Boolean? = null var getSelectionCalledTimes = 0 var getTextCalledTimes = 0 var selectionToReturn: Selection? = null var textToReturn: AnnotatedString? = null var handlePosition = Offset.Zero var boundingBox = Rect.Zero var layoutCoordinate: LayoutCoordinates? = null private val selectableKey = 1L private val fakeSelectAllSelection: Selection = Selection( start = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 0, selectableId = selectableKey ), end = Selection.AnchorInfo( direction = ResolvedTextDirection.Ltr, offset = 10, selectableId = selectableKey ) ) override fun updateSelection( startHandlePosition: Offset, endHandlePosition: Offset, previousHandlePosition: Offset?, isStartHandle: Boolean, containerLayoutCoordinates: LayoutCoordinates, adjustment: SelectionAdjustment, previousSelection: Selection? ): Pair<Selection?, Boolean> { getSelectionCalledTimes++ lastStartHandlePosition = startHandlePosition lastEndHandlePosition = endHandlePosition lastPreviousHandlePosition = previousHandlePosition lastContainerLayoutCoordinates = containerLayoutCoordinates lastAdjustment = adjustment lastPreviousSelection = previousSelection lastIsStartHandle = isStartHandle return Pair(selectionToReturn, false) } override fun getSelectAllSelection(): Selection? { return fakeSelectAllSelection } override fun getText(): AnnotatedString { getTextCalledTimes++ return textToReturn!! } override fun getLayoutCoordinates(): LayoutCoordinates? { return layoutCoordinate } override fun getHandlePosition(selection: Selection, isStartHandle: Boolean): Offset { return handlePosition } override fun getBoundingBox(offset: Int): Rect { return boundingBox } override fun getRangeOfLineContaining(offset: Int): TextRange { return TextRange.Zero } fun clear() { lastEndHandlePosition = null lastStartHandlePosition = null lastPreviousHandlePosition = null lastContainerLayoutCoordinates = null lastAdjustment = null lastPreviousSelection = null lastIsStartHandle = null getSelectionCalledTimes = 0 getTextCalledTimes = 0 selectionToReturn = null textToReturn = null } }
apache-2.0
34a462c7f0f21ebe868a8a559b7d2fb2
37.033003
99
0.70407
5.148794
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/workspace/VersionUtil.kt
1
7582
package org.elm.workspace import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.deser.std.StdDeserializer /** * A version number according to the [SemVer spec](https://semver.org) */ @JsonDeserialize(using = VersionDeserializer::class) data class Version( val x: Int, val y: Int, val z: Int, val preReleaseFields: List<String> = emptyList(), val buildFields: List<String> = emptyList() ) : Comparable<Version> { override fun toString(): String { val str = StringBuilder("$x.$y.$z") if (preReleaseFields.isNotEmpty()) str.append(preReleaseFields.joinToString(".", prefix = "-")) if (buildFields.isNotEmpty()) str.append(buildFields.joinToString(".", prefix = "+")) return str.toString() } override fun compareTo(other: Version) = when { x != other.x -> x.compareTo(other.x) y != other.y -> y.compareTo(other.y) z != other.z -> z.compareTo(other.z) preReleaseFields != other.preReleaseFields -> compareSemVerFields(preReleaseFields, other.preReleaseFields) else -> 0 } /** * Returns a "loose" form that ignores suffixes like alpha, rc-1, etc. */ val xyz: Version by lazy { Version(x, y, z) } companion object { val UNKNOWN: Version = Version(0, 0, 0) /** A weak definition of the version format defined in [the SemVer spec](https://semver.org) */ private val PATTERN = Regex("""(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z\-.]+)?(\+[0-9A-Za-z\-.]+)?""") fun parse(text: String): Version { val result = PATTERN.find(text) ?: throw ParseException("expected a version number, got '$text'") val (x, y, z, preReleaseInfo, buildInfo) = result.destructured return Version(x.toInt(), y.toInt(), z.toInt(), preReleaseFields = preReleaseInfo.parseExtraParts(), buildFields = buildInfo.parseExtraParts() ) } private fun String.parseExtraParts(): List<String> = takeIf { it.isNotEmpty() }?.drop(1)?.split(".") ?: emptyList() fun parseOrNull(text: String): Version? = try { parse(text) } catch (e: ParseException) { null } } } private fun compareSemVerFields(leftFields: List<String>, rightFields: List<String>): Int { // First, handle differences between normal versions and pre-release versions. // A normal version always has higher precedence than its pre-release versions. if (leftFields.isEmpty()) return 1 if (rightFields.isEmpty()) return -1 // Compare fields pair-wise for ((a, b) in leftFields.zip(rightFields)) { val result = compareSemVerField(a, b) if (result != 0) return result } // All pair-wise fields are the same: tie-breaker on number of fields return leftFields.size.compareTo(rightFields.size) } private fun compareSemVerField(a: String, b: String): Int { val a2 = a.toIntOrNull() val b2 = b.toIntOrNull() return when { a2 == null && b2 == null -> a.compareTo(b) // both fields are strings a2 == null && b2 != null -> 1 // numeric field has lower precedence than non-numeric field a2 != null && b2 == null -> -1 // ditto a2 != null && b2 != null -> a2.compareTo(b2) // both fields are integers else -> error("cannot happen") } } private class VersionDeserializer : StdDeserializer<Version>(Version::class.java) { override fun deserialize(p: JsonParser, ctxt: DeserializationContext) = try { Version.parse(p.text) } catch (e: ParseException) { throw ctxt.weirdStringException(p.text, Version::class.java, e.message) } } // CONSTRAINT ON VERSION NUMBERS @JsonDeserialize(using = ConstraintDeserializer::class) data class Constraint( val low: Version, val high: Version, val lowOp: Op, val highOp: Op ) { enum class Op { LESS_THAN, LESS_THAN_OR_EQUAL; override fun toString(): String = when (this) { LESS_THAN -> "<" LESS_THAN_OR_EQUAL -> "<=" } fun evaluate(left: Version, right: Version): Boolean = when (this) { LESS_THAN -> left < right LESS_THAN_OR_EQUAL -> left <= right } companion object { fun parse(text: String): Op = when (text) { "<" -> LESS_THAN "<=" -> LESS_THAN_OR_EQUAL else -> throw ParseException("expected '<' or '<=', got '$text'") } } } /** * Returns true if the constraint is satisfied using SemVer ordering (namely "1.0-beta" < "1.0") */ fun semVerContains(version: Version): Boolean = (lowOp.evaluate(low, version) && highOp.evaluate(version, high)) /** * Returns true if the constraint is satisfied solely by comparing x.y.z (so "1.0-beta" == "1.0") */ operator fun contains(version: Version): Boolean = copy(low = low.xyz, high = high.xyz).semVerContains(version.xyz) /** * Returns the intersection with [other] or null if the intersection is empty. */ infix fun intersect(other: Constraint): Constraint? { fun merge(op1: Op, op2: Op) = if (Op.LESS_THAN in listOf(op1, op2)) Op.LESS_THAN else Op.LESS_THAN_OR_EQUAL val (newLo, newLop) = when (low.compareTo(other.low)) { -1 -> other.low to other.lowOp 0 -> low to merge(lowOp, other.lowOp) 1 -> low to lowOp else -> error("unexpected compare result") } val (newHi, newHop) = when (high.compareTo(other.high)) { -1 -> high to highOp 0 -> high to merge(highOp, other.highOp) 1 -> other.high to other.highOp else -> error("unexpected compare result") } if (newLo >= newHi) return null return Constraint(newLo, newHi, newLop, newHop) } override fun toString() = "$low $lowOp v $highOp $high" companion object { fun parse(text: String): Constraint { val parts = text.split(" ") if (parts.size != 5) throw ParseException("expected something like '1.0.0 <= v < 2.0.0', got '$text'") val low = Version.parse(parts[0]) val lowOp = Op.parse(parts[1]) if (parts[2] != "v") throw ParseException("expected 'v', got '${parts[2]}'") val highOp = Op.parse(parts[3]) val high = Version.parse(parts[4]) return Constraint(low = low, lowOp = lowOp, highOp = highOp, high = high) } } } private class ConstraintDeserializer : StdDeserializer<Constraint>(Constraint::class.java) { override fun deserialize(p: JsonParser, ctxt: DeserializationContext) = try { Constraint.parse(p.text) } catch (e: ParseException) { throw ctxt.weirdStringException(p.text, Constraint::class.java, e.message) } } // MISC class ParseException(msg: String) : RuntimeException(msg)
mit
1801de46f04557ee773ef22f973852dc
35.109524
123
0.570034
4.138646
false
false
false
false
Soya93/Extract-Refactoring
platform/configuration-store-impl/src/BinaryXmlOutputter.kt
2
1833
package com.intellij.configurationStore import com.intellij.util.containers.isNullOrEmpty import org.jdom.* import java.io.DataOutputStream private enum class TypeMarker { ELEMENT, CDATA, TEXT, ELEMENT_END } fun output(doc: Document, out: DataOutputStream) { val content = doc.content val size = content.size for (i in 0..size - 1) { val obj = content[i] when (obj) { is Element -> printElement(out, doc.rootElement) } } out.flush() } fun writeElement(element: Element, out: DataOutputStream) { printElement(out, element) out.flush() } private fun printElement(out: DataOutputStream, element: Element) { out.writeByte(TypeMarker.ELEMENT.ordinal) out.writeUTF(element.name) val content = element.content printAttributes(out, element.attributes) for (item in content) { if (item is Element) { printElement(out, item) } else if (item is Text) { if (!isAllWhitespace(item)) { out.writeByte(TypeMarker.TEXT.ordinal) out.writeUTF(item.text) } } else if (item is CDATA) { out.writeByte(TypeMarker.CDATA.ordinal) out.writeUTF(item.text) } } out.writeByte(TypeMarker.ELEMENT_END.ordinal) } private fun printAttributes(out: DataOutputStream, attributes: List<Attribute>?) { if (attributes.isNullOrEmpty()) { val size = attributes?.size ?: 0 if (size > 255) { throw UnsupportedOperationException("attributes size > 255") } out.writeByte(size) return } for (attribute in attributes!!) { out.writeUTF(attribute.name) out.writeUTF(attribute.value) } } private fun isAllWhitespace(obj: Content): Boolean { val str = (obj as? Text)?.text ?: return false for (i in 0..str.length - 1) { if (!Verifier.isXMLWhitespace(str[i])) { return false } } return true }
apache-2.0
3d7703b2caa4cf48ec306e8fdc2ec228
22.512821
82
0.673759
3.72561
false
false
false
false
DanielMartinus/Stepper-Touch
library/src/main/java/nl/dionsegijn/steppertouch/StepperTouch.kt
1
9141
package nl.dionsegijn.steppertouch import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.Path import android.graphics.Rect import android.graphics.RectF import android.graphics.drawable.GradientDrawable import android.util.AttributeSet import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.dynamicanimation.animation.SpringAnimation import kotlinx.android.synthetic.main.stepper_touch.view.textViewNegative import kotlinx.android.synthetic.main.stepper_touch.view.textViewPositive import kotlinx.android.synthetic.main.stepper_touch.view.viewBackground import kotlinx.android.synthetic.main.stepper_touch.view.viewCounter import kotlinx.android.synthetic.main.stepper_touch.view.viewCounterText import kotlin.properties.Delegates /** * Created by dionsegijn on 3/19/17. */ class StepperTouch : ConstraintLayout { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { handleAttrs(attrs) } constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { handleAttrs(attrs) } // Drawing properties private val clippingBounds: RectF = RectF() private val clipPath = Path() // Animation properties private val stiffness: Float = 200f private val damping: Float = 0.6f private var startX: Float = 0f // Indication if tapping positive and negative sides is allowed var sideTapEnabled: Boolean = false private var allowDragging = false private var isTapped: Boolean = false var maxValue: Int = Integer.MAX_VALUE set(value) { field = value updateSideControls() } var minValue: Int = Integer.MIN_VALUE set(value) { field = value updateSideControls() } private val callbacks: MutableList<OnStepCallback> = mutableListOf() var count: Int by Delegates.observable(0) { _, old, new -> viewCounterText.text = new.toString() updateSideControls() notifyStepCallback(new, new > old) } // Style properties private var stepperBackground = R.color.stepper_background private var stepperActionColor = R.color.stepper_actions private var stepperActionColorDisabled = R.color.stepper_actions_disabled private var stepperTextColor = R.color.stepper_text private var stepperButtonColor = R.color.stepper_button private var stepperTextSize = 20 private var allowNegative = true private var allowPositive = true init { LayoutInflater.from(context).inflate(R.layout.stepper_touch, this, true) clipChildren = true if (android.os.Build.VERSION.SDK_INT >= 21) { viewCounter.elevation = 4f } setWillNotDraw(false) } private fun handleAttrs(attrs: AttributeSet) { val styles: TypedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.StepperTouch, 0, 0) try { stepperBackground = styles.getResourceId(R.styleable.StepperTouch_stepperBackgroundColor, R.color.stepper_background) stepperActionColor = styles.getResourceId(R.styleable.StepperTouch_stepperActionsColor, R.color.stepper_actions) stepperActionColorDisabled = styles.getResourceId( R.styleable.StepperTouch_stepperActionsDisabledColor, R.color.stepper_actions_disabled ) stepperTextColor = styles.getResourceId(R.styleable.StepperTouch_stepperTextColor, R.color.stepper_text) stepperButtonColor = styles.getResourceId(R.styleable.StepperTouch_stepperButtonColor, R.color.stepper_button) stepperTextSize = styles.getDimensionPixelSize(R.styleable.StepperTouch_stepperTextSize, stepperTextSize) allowNegative = styles.getBoolean(R.styleable.StepperTouch_stepperAllowNegative, true) allowPositive = styles.getBoolean(R.styleable.StepperTouch_stepperAllowPositive, true) } finally { styles.recycle() } updateStyling() } private fun updateStyling() { viewBackground.setBackgroundColor(ContextCompat.getColor(context, stepperBackground)) viewCounterText.setTextColor(ContextCompat.getColor(context, stepperTextColor)) viewCounterText.textSize = stepperTextSize.toFloat() updateSideControls() viewCounter.background?.apply { if (this is GradientDrawable) setColor(ContextCompat.getColor(context, stepperButtonColor)) } } override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { if (event.isInBounds(viewCounter)) { startX = event.x allowDragging = true } else if (sideTapEnabled) { isTapped = true viewCounter.x = event.x - viewCounter.width * 0.5f } parent.requestDisallowInterceptTouchEvent(true) return true } MotionEvent.ACTION_MOVE -> { if (allowDragging) { viewCounter.translationX = event.x - startX } return true } MotionEvent.ACTION_UP -> { allowDragging = false when { viewCounter.translationX > viewCounter.width * 0.5 && allowPositive -> { if (isLTR()) add() else subtract() } viewCounter.translationX < -(viewCounter.width * 0.5) && allowNegative -> { if (isLTR()) subtract() else add() } } if (viewCounter.translationX != 0f) { val animX = SpringAnimation(viewCounter, SpringAnimation.TRANSLATION_X, 0f) animX.spring.stiffness = stiffness animX.spring.dampingRatio = damping animX.start() } return true } else -> { parent.requestDisallowInterceptTouchEvent(false) return false } } } /** * Allow interact with negative section, if you disallow, the negative section will hide, * and it's not working * @param [allow] true if allow to use negative, false to disallow * */ fun allowNegative(allow: Boolean) { allowNegative = allow updateSideControls() } /** * Allow interact with positive section, if you disallow, the positive section will hide, * and it's not working * @param [allow] true if allow to use positive, false to disallow * */ fun allowPositive(allow: Boolean) { allowPositive = allow updateSideControls() } /** * Update visibility of the negative and positive views */ private fun updateSideControls() { textViewNegative.setVisibility(allowNegative) textViewPositive.setVisibility(allowPositive) textViewNegative.setTextColor( ContextCompat.getColor( context, if (count == minValue) stepperActionColorDisabled else stepperActionColor ) ) textViewPositive.setTextColor( ContextCompat.getColor( context, if (count == maxValue) stepperActionColorDisabled else stepperActionColor ) ) } fun setTextSize(pixels: Float) { viewCounterText.textSize = pixels } fun addStepCallback(callback: OnStepCallback) { callbacks.add(callback) } fun removeStepCallback(callback: OnStepCallback) { callbacks.remove(callback) } private fun notifyStepCallback(value: Int, positive: Boolean) { callbacks.forEach { it.onStep(value, positive) } } private fun add() { if (count != maxValue) count += 1 } private fun subtract() { if (count != minValue) count-- } override fun onDraw(canvas: Canvas) { clippingBounds.set(canvas.clipBounds) val r: Float = height.toFloat() / 2 clipPath.addRoundRect(clippingBounds, r, r, Path.Direction.CW) canvas.clipPath(clipPath) super.onDraw(canvas) } private fun MotionEvent.isInBounds(view: View): Boolean { val rect = Rect() view.getHitRect(rect) return rect.contains(x.toInt(), y.toInt()) } private fun View.setVisibility(isVisible: Boolean) { visibility = if (isVisible) View.VISIBLE else View.INVISIBLE } private fun View.isLTR(): Boolean { return ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_LTR } }
apache-2.0
e158b6430102c16b6864e49f1c8f18ca
34.157692
117
0.641396
4.857067
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/profile/topten/LocalTopTenEntry.kt
2
1350
package me.proxer.app.profile.topten import me.proxer.library.entity.ProxerIdItem import me.proxer.library.enums.Category import me.proxer.library.enums.Medium /** * @author Ruben Gees */ open class LocalTopTenEntry( override val id: String, open val name: String, open val category: Category, open val medium: Medium ) : ProxerIdItem { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LocalTopTenEntry) return false if (id != other.id) return false if (name != other.name) return false if (category != other.category) return false if (medium != other.medium) return false return true } override fun hashCode(): Int { var result = id.hashCode() result = 31 * result + name.hashCode() result = 31 * result + category.hashCode() result = 31 * result + medium.hashCode() return result } override fun toString(): String { return "LocalTopTenEntry(id='$id', name='$name', category=$category, medium=$medium)" } data class Ucp( override val id: String, override val name: String, override val category: Category, override val medium: Medium, val entryId: String ) : LocalTopTenEntry(id, name, category, medium) }
gpl-3.0
73754ac95e8cfaa9908953222c17c44c
27.125
93
0.633333
4.285714
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
prebuilt/src/main/kotlin/com/commonsense/android/kotlin/prebuilt/activities/InbuiltWebview.kt
1
1415
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.prebuilt.activities import android.content.* import android.net.* import android.os.* import android.webkit.* import com.commonsense.android.kotlin.system.base.* import com.commonsense.android.kotlin.views.extensions.* /** * Created by Kasper Tvede on 09-07-2017. */ open class InbuiltWebView : BaseActivity() { private val webView by lazy { WebView(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val uri = intent?.getParcelableExtra<Uri>(InbuiltWebView.uriIntentIndex) if (uri == null) { finish() return } setContentView(webView) webView.loadUri(uri) } override fun onDestroy() { super.onDestroy() webView.destroy() } //TODO add title, potential usage of CustomTabs (google project). //as well as JS... ect. // https://developer.chrome.com/multidevice/android/customtabs companion object { private const val uriIntentIndex = "uri" /** * */ fun showUri(uri: Uri, context: Context) { val intent = Intent(context, InbuiltWebView::class.java) intent.putExtra(uriIntentIndex, uri) context.startActivity(intent) } } }
mit
4b7058eda8ff89436488053d6a3f9eb0
25.716981
80
0.642403
4.353846
false
false
false
false
esofthead/mycollab
mycollab-core/src/main/java/com/mycollab/core/utils/PasswordCheckerUtil.kt
3
2034
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.core.utils import com.mycollab.core.InvalidPasswordException /** * @author MyCollab Ltd. * @since 1.0 */ object PasswordCheckerUtil { private val partialRegexChecks = arrayOf(".*[a-z]+.*", // lower ".*[A-Z]+.*", // upper ".*[\\d]+.*", // digits ".*[@#$%]+.*" // symbols ) @JvmStatic fun checkValidPassword(password: String) { if (password.length < 6) { throw InvalidPasswordException("Your password is too short - must be at least 6 characters") } else { checkPasswordStrength(password) } } private fun checkPasswordStrength(password: String) { var strengthPercentage = 0 if (password.matches(partialRegexChecks[0].toRegex())) { strengthPercentage += 25 } if (password.matches(partialRegexChecks[1].toRegex())) { strengthPercentage += 25 } if (password.matches(partialRegexChecks[2].toRegex())) { strengthPercentage += 25 } if (password.matches(partialRegexChecks[3].toRegex())) { strengthPercentage += 25 } if (strengthPercentage < 50) throw InvalidPasswordException("Password must contain at least one digit letter, one character and one symbol") } }
agpl-3.0
fd6d13c93636acc26def40577adb3d88
32.9
123
0.643384
4.497788
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathParenthesizedItemTypePsiImpl.kt
1
2948
/* * Copyright (C) 2016-2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xpath.psi.impl.xpath import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.tree.TokenSet import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.intellij.lang.* import uk.co.reecedunn.intellij.plugin.xdm.types.XdmEmptySequence import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType import uk.co.reecedunn.intellij.plugin.xdm.types.XdmSequenceType import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathParenthesizedItemType import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathElementType import uk.co.reecedunn.intellij.plugin.xpath.resources.XPathBundle private val XQUERY3 = listOf(XQuerySpec.REC_3_0_20140408, MarkLogic.VERSION_6_0) private val SEMANTICS = listOf(FormalSemanticsSpec.REC_1_0_20070123) private val SEQUENCE_TYPE = TokenSet.create( XPathElementType.SEQUENCE_TYPE, XPathElementType.EMPTY_SEQUENCE_TYPE ) class XPathParenthesizedItemTypePsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XPathParenthesizedItemType, VersionConformance, VersionConformanceName { // region XdmSequenceType // NOTE: The wrapped type may be a SequenceType, so locate and forward that type. private val sequenceType: XdmSequenceType get() = children().filterIsInstance<XdmSequenceType>().firstOrNull() ?: XdmEmptySequence override val typeName: String get() = "(${sequenceType.typeName})" override val itemType: XdmItemType? get() = sequenceType.itemType override val lowerBound: Int? get() = sequenceType.lowerBound override val upperBound: Int? get() = sequenceType.upperBound // endregion // region VersionConformance override val requiresConformance: List<Version> get() = if (findChildByType<PsiElement>(SEQUENCE_TYPE) != null) SEMANTICS else XQUERY3 override val conformanceElement: PsiElement get() = firstChild // endregion // region VersionConformanceName override val conformanceName: String? get() = when { findChildByType<PsiElement>(SEQUENCE_TYPE) != null -> XPathBundle.message("construct.parenthesized-sequence-type") else -> null } // endregion }
apache-2.0
3018d3adf0f3dc9913f155af751352f4
35.395062
126
0.748982
4.278665
false
false
false
false
dhleong/ideavim
src/com/maddyhome/idea/vim/ex/handler/GotoCharacterHandler.kt
1
2138
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * 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, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.ex.handler import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.command.CommandFlags import com.maddyhome.idea.vim.ex.CommandHandler import com.maddyhome.idea.vim.ex.CommandHandlerFlags import com.maddyhome.idea.vim.ex.CommandName import com.maddyhome.idea.vim.ex.ExCommand import com.maddyhome.idea.vim.ex.commands import com.maddyhome.idea.vim.ex.flags import com.maddyhome.idea.vim.group.MotionGroup import com.maddyhome.idea.vim.helper.enumSetOf import java.util.* class GotoCharacterHandler : CommandHandler.ForEachCaret() { override val names: Array<CommandName> = commands("go[to]") override val argFlags: CommandHandlerFlags = flags(RangeFlag.RANGE_IS_COUNT, ArgumentFlag.ARGUMENT_OPTIONAL) override val optFlags: EnumSet<CommandFlags> = enumSetOf(CommandFlags.FLAG_MOT_EXCLUSIVE) override fun execute(editor: Editor, caret: Caret, context: DataContext, cmd: ExCommand): Boolean { val count = cmd.getCount(editor, caret, context, 1, true) if (count <= 0) return false val offset = VimPlugin.getMotion().moveCaretToNthCharacter(editor, count - 1) if (offset == -1) return false MotionGroup.moveCaret(editor, caret, offset) return true } }
gpl-2.0
6537b3fde3a39553089e02e946eac83b
40.115385
110
0.774088
4.003745
false
false
false
false