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
toastkidjp/Yobidashi_kt
editor/src/test/java/jp/toastkid/editor/EditorContextMenuInitializerTest.kt
1
2269
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.editor import android.widget.EditText import androidx.lifecycle.ViewModelProvider import io.mockk.MockKAnnotations import io.mockk.Runs import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.mockk import io.mockk.unmockkAll import io.mockk.verify import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.ContentViewModel import jp.toastkid.yobidashi.libs.speech.SpeechMaker import org.junit.After import org.junit.Before import org.junit.Test class EditorContextMenuInitializerTest { @InjectMockKs private lateinit var editorContextMenuInitializer: EditorContextMenuInitializer @MockK private lateinit var editText: EditText @MockK private lateinit var speechMaker: SpeechMaker @MockK private lateinit var viewModelProvider: ViewModelProvider @Before fun setUp() { MockKAnnotations.init(this) every { editText.context }.returns(mockk()) every { viewModelProvider.get(BrowserViewModel::class.java) }.returns(mockk()) every { viewModelProvider.get(ContentViewModel::class.java) }.returns(mockk()) every { editText.customInsertionActionModeCallback = any() }.just(Runs) every { editText.customSelectionActionModeCallback = any() }.just(Runs) } @After fun tearDown() { unmockkAll() } @Test fun testEditTextIsNullCase() { editorContextMenuInitializer.invoke(null, speechMaker, viewModelProvider) verify(exactly = 0) { editText.context } } @Test fun testCompleteInitializing() { editorContextMenuInitializer.invoke(editText, speechMaker, viewModelProvider) verify(exactly = 1) { editText.context } verify(exactly = 1) { editText.customInsertionActionModeCallback = any() } verify(exactly = 1) { editText.customSelectionActionModeCallback = any() } } }
epl-1.0
7fb40b5f2529633e90fba3eabeb3dd3b
28.868421
88
0.739974
4.574597
false
true
false
false
devmil/muzei-bingimageoftheday
app/src/main/java/de/devmil/common/licensing/LicenseDefinition.kt
1
1770
/* * Copyright 2014 Devmil Solutions * * 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 de.devmil.common.licensing import org.json.JSONException import org.json.JSONObject import de.devmil.common.utils.LogUtil.LOGW /** * Created by devmil on 18.04.14. */ class LicenseDefinition private constructor(val id: String, val name: String, val url: String, val content: String) { companion object { private val ID_IDENTIFIER = "id" private val URL_IDENTIFIER = "url" private val NAME_IDENTIFIER = "name" private val CONTENT_IDENTIFIER = "content" fun readFromJSON(obj: JSONObject): LicenseDefinition? { try { val id = obj.getString(ID_IDENTIFIER) val name = obj.getString(NAME_IDENTIFIER) val url = obj.getString(URL_IDENTIFIER) val content = obj.getString(CONTENT_IDENTIFIER) val result = LicenseDefinition(id, name, url, content) return result } catch (e: JSONException) { LOGW(LicenseDefinition::class.java.simpleName, "Error reading LicenseDefinition", e) return null } } } }
apache-2.0
5b749677adc125f312bb0d0cb14d7d27
33.4
117
0.640678
4.402985
false
false
false
false
zalando/tracer
opentracing-kotlin/src/main/kotlin/org/zalando/opentracing/kotlin/suspend/TracerExtension.kt
1
1626
package org.zalando.opentracing.kotlin.suspend import io.opentracing.Span import io.opentracing.SpanContext import io.opentracing.Tracer import io.opentracing.tag.Tags import kotlinx.coroutines.CoroutineScope import org.zalando.opentracing.kotlin.record import kotlin.coroutines.coroutineContext @SuppressWarnings("TooGenericExceptionCaught") suspend inline fun <R> Tracer.trace( span: Span, crossinline block: suspend CoroutineScope.(Span) -> R ): R { try { return activeSpan(span) { this.block(span) } } catch (e: Exception) { span.record(e) throw e } finally { try { span.finish() } catch (closeException: Exception) { // Do Nothing } } } suspend inline fun <R> Tracer.trace( operation: String, spanBuilder: Tracer.SpanBuilder.() -> Unit, crossinline block: suspend CoroutineScope.(Span) -> R ): R { val builder = buildSpan(operation) builder.apply(spanBuilder) val span = builder.start() return trace(span, block) } suspend inline fun <R> Tracer.trace( operation: String, component: String? = null, kind: String? = null, parent: SpanContext? = null, crossinline block: suspend CoroutineScope.(Span) -> R ): R { val parentSpan = parent ?: coroutineContext.activeSpan()?.context() return trace( operation = operation, spanBuilder = { parentSpan?.let { asChildOf(parentSpan) } component?.let { withTag(Tags.COMPONENT, component) } kind?.let { withTag(Tags.SPAN_KIND, kind) } }, block = block ) }
mit
be9b959dc0a9432dcc6c2d82c17a2a9a
26.559322
71
0.650062
4.024752
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_hrs/src/main/java/no/nordicsemi/android/hrs/view/HRSContentView.kt
1
3962
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder 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 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.hrs.view import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import no.nordicsemi.android.hrs.R import no.nordicsemi.android.hrs.data.HRSData import no.nordicsemi.android.theme.ScreenSection import no.nordicsemi.android.ui.view.BatteryLevelView import no.nordicsemi.android.ui.view.SectionTitle @Composable internal fun HRSContentView(state: HRSData, zoomIn: Boolean, onEvent: (HRSScreenViewEvent) -> Unit) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(16.dp) ) { ScreenSection { SectionTitle( resId = R.drawable.ic_chart_line, title = stringResource(id = R.string.hrs_section_data), menu = { Menu(zoomIn, onEvent) } ) Spacer(modifier = Modifier.height(16.dp)) LineChartView(state, zoomIn) } Spacer(modifier = Modifier.height(16.dp)) state.batteryLevel?.let { BatteryLevelView(it) Spacer(modifier = Modifier.height(16.dp)) } Button( onClick = { onEvent(DisconnectEvent) } ) { Text(text = stringResource(id = R.string.disconnect)) } } } @Composable private fun Menu(zoomIn: Boolean, onEvent: (HRSScreenViewEvent) -> Unit) { val icon = when (zoomIn) { true -> R.drawable.ic_zoom_out false -> R.drawable.ic_zoom_in } IconButton(onClick = { onEvent(SwitchZoomEvent) }) { Icon( painter = painterResource(id = icon), contentDescription = stringResource(id = R.string.hrs_zoom_icon) ) } } @Preview @Composable private fun Preview() { HRSContentView(state = HRSData(), zoomIn = false) { } }
bsd-3-clause
a84d89bc65f5d6038658866a2d34c554
35.685185
101
0.722362
4.320611
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/RsFileType.kt
5
721
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang import com.intellij.openapi.fileTypes.LanguageFileType import com.intellij.openapi.vfs.VirtualFile import org.rust.ide.icons.RsIcons import javax.swing.Icon object RsFileType : LanguageFileType(RsLanguage) { object DEFAULTS { val EXTENSION: String = "rs" } override fun getName(): String = "Rust" override fun getIcon(): Icon = RsIcons.RUST_FILE override fun getDefaultExtension(): String = DEFAULTS.EXTENSION override fun getCharset(file: VirtualFile, content: ByteArray): String = "UTF-8" override fun getDescription(): String = "Rust Files" }
mit
86a90780d1db9cc4a6365b985da5b641
23.862069
84
0.725381
4.291667
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/formatter/blocks/RsFmtBlock.kt
3
5082
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter.blocks import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.formatter.FormatterUtil import org.rust.ide.formatter.RsFmtContext import org.rust.ide.formatter.RsFormattingModelBuilder import org.rust.ide.formatter.impl.* import org.rust.lang.core.psi.RsElementTypes.* import org.rust.lang.core.psi.RsExpr class RsFmtBlock( private val node: ASTNode, private val alignment: Alignment?, private val indent: Indent?, private val wrap: Wrap?, val ctx: RsFmtContext ) : ASTBlock { override fun getNode(): ASTNode = node override fun getTextRange(): TextRange = node.textRange override fun getAlignment(): Alignment? = alignment override fun getIndent(): Indent? = indent override fun getWrap(): Wrap? = wrap override fun getSubBlocks(): List<Block> = mySubBlocks private val mySubBlocks: List<Block> by lazy { buildChildren() } private fun buildChildren(): List<Block> { val sharedAlignment = when (node.elementType) { in FN_DECLS -> Alignment.createAlignment() VALUE_PARAMETER_LIST -> ctx.sharedAlignment DOT_EXPR -> if (node.treeParent.elementType == DOT_EXPR) ctx.sharedAlignment else Alignment.createAlignment() else -> null } var metLBrace = false val alignment = getAlignmentStrategy() val children = node.getChildren(null) .filter { !it.isWhitespaceOrEmpty() } .map { childNode: ASTNode -> if (node.isFlatBlock && childNode.isBlockDelim(node)) { metLBrace = true } val childCtx = ctx.copy( metLBrace = metLBrace, sharedAlignment = sharedAlignment) RsFormattingModelBuilder.createBlock( node = childNode, alignment = alignment.getAlignment(childNode, node, childCtx), indent = computeIndent(childNode, childCtx), wrap = null, ctx = childCtx) } // Create fake `.sth` block here, so child indentation will // be relative to it when it starts from new line. // In other words: foo().bar().baz() => foo().baz()[.baz()] // We are using dot as our representative. // The idea is nearly copy-pasted from Kotlin's formatter. if (node.elementType == DOT_EXPR) { val dotIndex = children.indexOfFirst { it.node.elementType == DOT } if (dotIndex != -1) { val dotBlock = children[dotIndex] val syntheticBlock = SyntheticRsFmtBlock( representative = dotBlock, subBlocks = children.subList(dotIndex, children.size), ctx = ctx) return children.subList(0, dotIndex).plusElement(syntheticBlock) } } return children } override fun getSpacing(child1: Block?, child2: Block): Spacing? = computeSpacing(child1, child2, ctx) override fun getChildAttributes(newChildIndex: Int): ChildAttributes { if (CommaList.forElement(node.elementType) != null && newChildIndex > 1) { val isBeforeClosingBrace = newChildIndex + 1 == subBlocks.size return if (isBeforeClosingBrace) ChildAttributes.DELEGATE_TO_PREV_CHILD else ChildAttributes.DELEGATE_TO_NEXT_CHILD } val indent = when { // Flat brace blocks do not have separate PSI node for content blocks // so we have to manually decide whether new child is before (no indent) // or after (normal indent) left brace node. node.isFlatBraceBlock -> { val lbraceIndex = subBlocks.indexOfFirst { it is ASTBlock && it.node.elementType == LBRACE } if (lbraceIndex != -1 && lbraceIndex < newChildIndex) { Indent.getNormalIndent() } else { Indent.getNoneIndent() } } // We are inside some kind of {...}, [...], (...) or <...> block node.isDelimitedBlock -> Indent.getNormalIndent() // Indent expressions (chain calls, binary expressions, ...) node.psi is RsExpr -> Indent.getContinuationWithoutFirstIndent() // Otherwise we don't want any indentation (null means continuation indent) else -> Indent.getNoneIndent() } return ChildAttributes(indent, null) } override fun isLeaf(): Boolean = node.firstChildNode == null override fun isIncomplete(): Boolean = myIsIncomplete private val myIsIncomplete: Boolean by lazy { FormatterUtil.isIncomplete(node) } override fun toString() = "${node.text} $textRange" }
mit
0d98d0bda22895b7ccb883465af6a40d
38.092308
108
0.604486
4.881844
false
false
false
false
MaisonWan/AppFileExplorer
FileExplorer/src/main/java/com/domker/app/explorer/helper/IconLruCache.kt
1
2124
package com.domker.app.explorer.helper import android.content.Context import android.graphics.drawable.Drawable import android.os.Build import android.util.LruCache import com.domker.app.explorer.R import com.domker.app.explorer.file.FileInfo import com.domker.app.explorer.file.FileManager import com.domker.app.explorer.file.FileType /** * 使用LRU算法缓存图标 * Created by wanlipeng on 2017/9/3. */ class IconLruCache(val context: Context) { private val size: Int = 1024 * 1024 * 30 private var mIconCache: LruCache<String, Drawable> = object : LruCache<String, Drawable>(size) { override fun sizeOf(key: String?, value: Drawable?): Int { return super.sizeOf(key, value) } } /** * 从内存缓存中获取一个Bitmap * @param fileInfo * @return */ fun getDrawable(fileInfo: FileInfo): Drawable { val path = fileInfo.file.absolutePath var key = if (fileInfo.isFile() && FileType.isApkFile(path)) { path } else { fileInfo.fileType.name } var drawable = mIconCache[key] if (drawable == null) { drawable = loadDrawable(fileInfo) mIconCache.put(key, drawable) } return drawable!! } /** * 加载资源 */ private fun loadDrawable(fileInfo: FileInfo) : Drawable { if (FileType.isApkFile(fileInfo.file.name)) { return FileManager.getApkIcon(context, fileInfo.file.absolutePath)!! } return when (fileInfo.fileType) { FileType.TYPE_DIRECTORY -> getResDrawable(R.drawable.fe_ic_folder_black) FileType.TYPE_IMAGE -> getResDrawable(R.drawable.fe_ic_wallpaper_black) FileType.TYPE_PDF -> getResDrawable(R.drawable.fe_ic_pdf_black) else -> getResDrawable(R.drawable.ic_menu_camera) } } /** * 根据资源ID加载 */ private fun getResDrawable(resId: Int): Drawable { return if (Build.VERSION.SDK_INT >= 21) context.getDrawable(resId) else context.resources.getDrawable(resId) } }
apache-2.0
89332d2f513f55207db265b3d9a9731f
29.880597
100
0.635397
3.901887
false
false
false
false
MyDogTom/detekt
detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/processors/ProjectLLOCProcessor.kt
1
612
package io.gitlab.arturbosch.detekt.core.processors import io.gitlab.arturbosch.detekt.api.DetektVisitor import io.gitlab.arturbosch.detekt.core.processors.util.LLOC import org.jetbrains.kotlin.com.intellij.openapi.util.Key import org.jetbrains.kotlin.psi.KtFile class ProjectLLOCProcessor : AbstractProcessor() { override val visitor = LLOCVisitor() override val key = LLOC_KEY } val LLOC_KEY = Key<Int>("lloc") class LLOCVisitor : DetektVisitor() { override fun visitKtFile(file: KtFile) { val lines = file.text.split("\n") val value = LLOC.analyze(lines) file.putUserData(LLOC_KEY, value) } }
apache-2.0
b49009f22f8ba70338d54e7e988b6581
25.608696
60
0.769608
3.326087
false
false
false
false
http4k/http4k
http4k-format/argo/src/main/kotlin/org/http4k/format/Argo.kt
1
3653
package org.http4k.format import argo.format.CompactJsonFormatter import argo.format.PrettyJsonFormatter import argo.jdom.JdomParser import argo.jdom.JsonNode import argo.jdom.JsonNodeFactories import argo.jdom.JsonNodeFactories.field import argo.jdom.JsonNodeFactories.`object` import argo.jdom.JsonNodeType.ARRAY import argo.jdom.JsonNodeType.FALSE import argo.jdom.JsonNodeType.NULL import argo.jdom.JsonNodeType.NUMBER import argo.jdom.JsonNodeType.OBJECT import argo.jdom.JsonNodeType.STRING import argo.jdom.JsonNodeType.TRUE import argo.jdom.JsonStringNode import org.http4k.format.JsonType.Object import java.math.BigDecimal import java.math.BigInteger object Argo : Json<JsonNode> { override fun typeOf(value: JsonNode): JsonType = when (value.type) { STRING -> JsonType.String TRUE -> JsonType.Boolean FALSE -> JsonType.Boolean NUMBER -> if (value.text.any { !it.isDigit() }) JsonType.Number else JsonType.Integer ARRAY -> JsonType.Array OBJECT -> Object NULL -> JsonType.Null else -> throw IllegalArgumentException("Don't know how to translate $value") } private val pretty = PrettyJsonFormatter() private val compact = CompactJsonFormatter() private val jdomParser = JdomParser() override fun String.asJsonObject(): JsonNode = let(jdomParser::parse) override fun String?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.string(it) } ?: JsonNodeFactories.nullNode() override fun Int?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(it.toLong()) } ?: JsonNodeFactories.nullNode() override fun Double?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(BigDecimal(it)) } ?: JsonNodeFactories.nullNode() override fun Long?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(it) } ?: JsonNodeFactories.nullNode() override fun BigDecimal?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(it) } ?: JsonNodeFactories.nullNode() override fun BigInteger?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.number(it) } ?: JsonNodeFactories.nullNode() override fun Boolean?.asJsonValue(): JsonNode = this?.let { JsonNodeFactories.booleanNode(it) } ?: JsonNodeFactories.nullNode() override fun <T : Iterable<JsonNode>> T.asJsonArray(): JsonNode = JsonNodeFactories.array(this) override fun JsonNode.asPrettyJsonString(): String = pretty.format(this) override fun JsonNode.asCompactJsonString(): String = compact.format(this) override fun <LIST : Iterable<Pair<String, JsonNode>>> LIST.asJsonObject(): JsonNode = `object`(associate { JsonNodeFactories.string(it.first) to it.second }) override fun fields(node: JsonNode) = if (typeOf(node) != Object) emptyList() else node.fieldList.map { it.name.text to it.value } override fun elements(value: JsonNode): Iterable<JsonNode> = value.elements override fun text(value: JsonNode): String = value.text override fun bool(value: JsonNode): Boolean = value.getBooleanValue() override fun integer(value: JsonNode) = value.getNumberValue().toLong() override fun decimal(value: JsonNode) = value.getNumberValue().toBigDecimal() override fun textValueOf(node: JsonNode, name: String): String = with(node.getNode(name)) { when (type) { STRING -> text TRUE -> "true" FALSE -> "false" NUMBER -> text else -> throw IllegalArgumentException("Don't know how to translate $node") } } }
apache-2.0
efb28ec24fbb32b687da0268627faf7a
41.476744
105
0.702163
4.287559
false
false
false
false
czyzby/gdx-setup
src/main/kotlin/com/github/czyzby/setup/data/libs/unofficial/lml.kt
1
6039
package com.github.czyzby.setup.data.libs.unofficial import com.github.czyzby.setup.data.platforms.* import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.views.Extension /** * Version of Czyzby's libraries. * @author MJ */ const val AUTUMN_VERSION = "1.9.1.9.6" /** * Guava-inspired LibGDX utilities. * @author MJ */ @Extension class Kiwi : ThirdPartyExtension() { override val id = "kiwi" override val defaultVersion = AUTUMN_VERSION override val url = "https://github.com/czyzby/gdx-lml/tree/master/kiwi" override fun initiateDependencies(project: Project) { addDependency(project, Core.ID, "com.github.czyzby:gdx-kiwi") addDependency(project, GWT.ID, "com.github.czyzby:gdx-kiwi:sources") addGwtInherit(project, "com.github.czyzby.kiwi.GdxKiwi") } } /** * Parser of HTML-like templates that produces Scene2D widgets. * @author MJ */ @Extension class LML : ThirdPartyExtension() { override val id = "lml" override val defaultVersion = AUTUMN_VERSION override val url = "https://github.com/czyzby/gdx-lml/tree/master/lml" override fun initiateDependencies(project: Project) { addDependency(project, Core.ID, "com.github.czyzby:gdx-lml") addDependency(project, GWT.ID, "com.github.czyzby:gdx-lml:sources") addGwtInherit(project, "com.github.czyzby.lml.GdxLml") Kiwi().initiate(project) } } /** * Parser of HTML-like templates that produces VisUI widgets. * @author MJ * @author Kotcrab */ @Extension class LMLVis : ThirdPartyExtension() { override val id = "lmlVis" override val defaultVersion = AUTUMN_VERSION override val url = "https://github.com/czyzby/gdx-lml/tree/master/lml-vis" override fun initiateDependencies(project: Project) { addDependency(project, Core.ID, "com.github.czyzby:gdx-lml-vis") addDependency(project, GWT.ID, "com.github.czyzby:gdx-lml-vis:sources") addGwtInherit(project, "com.github.czyzby.lml.vis.GdxLmlVis") LML().initiate(project) VisUI().initiate(project) } } /** * Dependency injection mechanism with component scan using LibGDX reflection API. * @author MJ */ @Extension class Autumn : ThirdPartyExtension() { override val id = "autumn" override val defaultVersion = AUTUMN_VERSION override val url = "https://github.com/czyzby/gdx-lml/tree/master/autumn" override fun initiateDependencies(project: Project) { addDependency(project, Core.ID, "com.github.czyzby:gdx-autumn") addDesktopDependency(project, "com.github.czyzby:gdx-autumn-fcs") addDependency(project, Headless.ID, "com.github.czyzby:gdx-autumn-fcs") addDependency(project, Android.ID, "com.github.czyzby:gdx-autumn-android") addDependency(project, GWT.ID, "com.github.czyzby:gdx-autumn:sources") addDependency(project, GWT.ID, "com.github.czyzby:gdx-autumn-gwt") addDependency(project, GWT.ID, "com.github.czyzby:gdx-autumn-gwt:sources") addGwtInherit(project, "com.github.czyzby.autumn.gwt.GdxAutumnGwt") Kiwi().initiate(project) } } /** * Model-view-controller framework on top of Autumn DI and LibGDX. * @author MJ */ @Extension class AutumnMVC : ThirdPartyExtension() { override val id = "autumnMvc" override val defaultVersion = AUTUMN_VERSION override val url = "https://github.com/czyzby/gdx-lml/tree/master/mvc" override fun initiateDependencies(project: Project) { addDependency(project, Core.ID, "com.github.czyzby:gdx-autumn-mvc") addDependency(project, GWT.ID, "com.github.czyzby:gdx-autumn-mvc:sources") addGwtInherit(project, "com.github.czyzby.autumn.mvc.GdxAutumnMvc") LML().initiate(project) Autumn().initiate(project) } } /** * Cross-platform web sockets support. * @author MJ */ @Extension class Websocket : ThirdPartyExtension() { override val id = "websocket" override val defaultVersion = AUTUMN_VERSION override val url = "https://github.com/czyzby/gdx-lml/tree/master/websocket" override fun initiateDependencies(project: Project) { addDependency(project, Core.ID, "com.github.czyzby:gdx-websocket") addDependency(project, Shared.ID, "com.github.czyzby:gdx-websocket") addDesktopDependency(project, "com.github.czyzby:gdx-websocket-common") addDependency(project, Headless.ID, "com.github.czyzby:gdx-websocket-common") addDependency(project, iOS.ID, "com.github.czyzby:gdx-websocket-common") addDependency(project, MOE.ID, "com.github.czyzby:gdx-websocket-common") addDependency(project, Android.ID, "com.github.czyzby:gdx-websocket-common") addAndroidPermission(project, "android.permission.INTERNET") addDependency(project, GWT.ID, "com.github.czyzby:gdx-websocket:sources") addDependency(project, GWT.ID, "com.github.czyzby:gdx-websocket-gwt") addDependency(project, GWT.ID, "com.github.czyzby:gdx-websocket-gwt:sources") addGwtInherit(project, "com.github.czyzby.websocket.GdxWebSocketGwt") } } /** * Cross-platform efficient serialization without reflection. * @author MJ */ @Extension class WebsocketSerialization : ThirdPartyExtension() { override val id = "websocketSerialization" override val defaultVersion = AUTUMN_VERSION override val url = "https://github.com/czyzby/gdx-lml/tree/master/websocket/natives/serialization" override fun initiateDependencies(project: Project) { addDependency(project, Core.ID, "com.github.czyzby:gdx-websocket-serialization") addDependency(project, Shared.ID, "com.github.czyzby:gdx-websocket-serialization") addDependency(project, Server.ID, "com.github.czyzby:gdx-websocket-serialization") addDependency(project, GWT.ID, "com.github.czyzby:gdx-websocket-serialization:sources") addGwtInherit(project, "com.github.czyzby.websocket.GdxWebSocketSerialization") Websocket().initiate(project) } }
unlicense
80b4065eb8dd91de275a08f5c8e88d96
33.907514
102
0.711376
3.760274
false
false
false
false
mixitconf/mixit
src/test/kotlin/mixit/import/SessionizeImportTests.kt
1
12087
package mixit.import import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import mixit.security.model.Cryptographer import mixit.talk.model.Language import mixit.talk.model.Talk import mixit.talk.model.TalkFormat import mixit.user.model.Link import mixit.user.model.Role import mixit.user.model.User import mixit.user.repository.UserRepository import mixit.util.encodeToMd5 import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.core.io.ClassPathResource import java.io.File import java.io.FileOutputStream import java.io.InputStream import java.net.URL import java.time.Duration import java.util.UUID inline fun <reified T> ObjectMapper.readValue(src: InputStream): T = readValue(src, jacksonTypeRef<T>()) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class SessionizeImportTests( @Autowired val objectMapper: ObjectMapper, @Autowired val userRepository: UserRepository, @Autowired val cryptographer: Cryptographer ) { // @Test fun `load speakers`() { initializeFolder() val papercallExports = objectMapper.readValue<List<PapercallExport>>(ClassPathResource("import/2020-papercall-export.json").inputStream) val speakersToPersist = importSpeakers(papercallExports) objectMapper.writeValue(File("/tmp/mixit/speakers_2020.json"), speakersToPersist) val sessionsToPersist = createSessions(papercallExports, speakersToPersist) objectMapper.writeValue(File("/tmp/mixit/talks_2020.json"), sessionsToPersist) } private fun importSpeakers(papercallExports: List<PapercallExport>): MutableList<User> { val papercallSpeakers = extractSpeakers(papercallExports) val speakersToPersist: MutableList<User> = mutableListOf() papercallSpeakers.forEach { papercallSpeaker -> val user = userRepository.findByNonEncryptedEmail(papercallSpeaker.email).block(Duration.ofSeconds(10)) if (user != null) { val updatedUser = updateUser(user, papercallSpeaker) speakersToPersist.add(updatedUser) } else { val createdUser = createUser(papercallSpeaker) speakersToPersist.add(createdUser) } } return speakersToPersist } private fun getImageName(speakerName: String): String { val speakerWithPngImage = listOf("julien_dubedout", "marilyn_kol", "benoit", "cedric_spalvieri", "nikola_lohinski") val imageName = sanitize(speakerName) return imageName + if (speakerWithPngImage.any { it == imageName }) ".png" else ".jpg" } private fun extractSpeakers(papercallExports: List<PapercallExport>): MutableList<PapercallProfile> { val speakers = mutableListOf<PapercallProfile>() // Add a reference to the talk in the user to be able to link them papercallExports.forEach { talk -> talk.profile.talkId = talk.id talk.co_presenter_profiles.forEach { coPresenter -> coPresenter.talkId = talk.id } } papercallExports .map { papercallExport -> papercallExport.profile } .forEach { speakers.add(it) } papercallExports .flatMap { papercallExport -> papercallExport.co_presenter_profiles } .forEach { speakers.add(it) } return speakers } private fun createUser(papercallSpeaker: PapercallProfile): User { var login = papercallSpeaker.email.substring(0, papercallSpeaker.email.indexOf("@")) val userCheck = userRepository.findOne(login).block(Duration.ofSeconds(10)) if (userCheck != null) { println("Login ${userCheck.login} already exist: try to create one with suffix") login += UUID.randomUUID().toString() val anotherUserCheck = userRepository.findOne(login).block(Duration.ofSeconds(10)) if (anotherUserCheck != null) { println("Login with suffix ${anotherUserCheck.login} already exist aborting import") throw IllegalArgumentException() } } println("User not found => ${papercallSpeaker.name} => login : $login") if (papercallSpeaker.avatar != null) { downloadImage(papercallSpeaker.avatar, getImageName(papercallSpeaker.name)) } println("User created") return User( login, firstNameOf(papercallSpeaker.name), lastName(papercallSpeaker.name), cryptographer.encrypt(papercallSpeaker.email), papercallSpeaker.company, bioToMap(papercallSpeaker.bio), papercallSpeaker.email.encodeToMd5(), "https://mixitconf.cleverapps.io/images/speakers/${getImageName(papercallSpeaker.name)}", Role.USER, if (papercallSpeaker.url.isNullOrEmpty()) listOf() else listOf(Link("site", papercallSpeaker.url)), // We store id in token to retrieve speaker later when we will save talk token = papercallSpeaker.talkId.orEmpty() ) } private fun updateUser(user: User, papercallSpeaker: PapercallProfile): User { println("User found => ${user.login} : ${user.lastname} ${user.firstname}") val imageUrl = getImageUrl(user, papercallSpeaker.avatar) if (imageUrl != null && imageUrl.contains("papercallio")) { downloadImage(imageUrl, getImageName(papercallSpeaker.name)) } println("User updated") return User( user.login, firstNameOf(papercallSpeaker.name), lastName(papercallSpeaker.name), user.email, if (papercallSpeaker.company == null) user.company else papercallSpeaker.company, if (papercallSpeaker.bio == null) user.description else bioToMap(papercallSpeaker.bio), papercallSpeaker.email.encodeToMd5(), "https://mixitconf.cleverapps.io/images/speakers/${getImageName(papercallSpeaker.name)}", user.role, if (papercallSpeaker.url.isNullOrEmpty()) listOf() else listOf(Link("site", papercallSpeaker.url)), // We store id in token to retrieve speaker later when we will save talk token = papercallSpeaker.talkId.orEmpty() ) } private fun lastName(name: String) = name.split(" ").drop(1).joinToString(" ") private fun firstNameOf(name: String) = name.split(" ").first() private fun createSessions( papercallExports: List<PapercallExport>, speakersToPersist: MutableList<User> ): List<Talk> { return papercallExports.map { export -> // We have to find the sessions speakers val sessionSpeakers: List<User> = speakersToPersist.filter { it.token == export.id } val title = export.talk?.title.orEmpty() val summary = export.talk?.abstract.orEmpty() val language = getLanguage(export) val topic = getTopic(export) val speakerIds = sessionSpeakers.map { it.login } val talkFormat = getTalkFormat(export) println("Session $title : speakers ${sessionSpeakers.map { it.firstname + it.lastname }}") println("Lng=$language topic=$topic format=$talkFormat") Talk( talkFormat, "2020", title, summary, speakerIds, language, topic = topic ) } } private fun getTalkFormat(export: PapercallExport): TalkFormat = when (export.talk?.talk_format) { "Long talk (50 minutes)" -> TalkFormat.TALK "Short talk (20 minutes)" -> TalkFormat.RANDOM "Workshop (110 minutes)" -> TalkFormat.WORKSHOP else -> TalkFormat.TALK } private fun getTopic(export: PapercallExport): String { val mixitTopics = listOf("maker", "design", "aliens", "tech", "ethic", "life style", "team") val papercallTopics: String = export.tags .map { it.lowercase() } .filter { mixitTopics.contains(it) } .firstOrNull().orEmpty().ifEmpty { "other" } return toMixitTopic(papercallTopics) } private fun getLanguage(export: PapercallExport): Language { val isInFrench = export.cfp_additional_question_answers .filter { question -> question.question_content == "Do you plan to present your talk in French?" } .filter { question -> question.content == "yes" } .isNotEmpty() return if (isInFrench) Language.FRENCH else Language.ENGLISH } } fun getImageUrl(user: User, pictureUrl: String?): String? { System.out.println("user ${user.lastname} -> ${user.photoUrl}") if (!user.photoUrl.isNullOrEmpty()) { if (user.photoUrl!!.contains("/mixitconf")) { return user.photoUrl } if (user.photoUrl!!.startsWith("/images")) { return "https://mixitconf.cleverapps.io${user.photoUrl}" } return user.photoUrl } else if (pictureUrl.isNullOrEmpty()) { return "https://www.gravatar.com/avatar/${user.emailHash}?s=400" } return pictureUrl } fun bioToMap(bio: String?) = if (bio == null) mapOf( Pair(Language.FRENCH, "UNKNOWN"), Pair(Language.ENGLISH, "UNKNOWN") ) else mapOf(Pair(Language.FRENCH, bio), Pair(Language.ENGLISH, bio)) val SPECIAL_SLUG_CHARACTERS = mapOf( Pair('é', 'e'), Pair('è', 'e'), Pair('ï', 'i'), Pair(' ', '_'), Pair('ê', 'e'), Pair('à', 'a'), Pair('-', '_'), Pair('_', '0'), Pair('∴', '0') ) fun sanitize(value: String): String = value.lowercase().toCharArray() .map { if (SPECIAL_SLUG_CHARACTERS.get(it) == null) it else SPECIAL_SLUG_CHARACTERS.get(it) }.joinToString("") fun initializeFolder() { // Check if /tmp/images/ exists ? val directory = File("/tmp/mixit/") if (!directory.exists()) { directory.mkdir() } } fun downloadImage(url: String, filename: String) { val emplacement = File("/tmp/mixit/$filename") if (emplacement.exists()) { emplacement.delete() } emplacement.createNewFile() FileOutputStream(emplacement).use { val out = it try { URL(url).openConnection().getInputStream().use { val b = ByteArray(1024) var c: Int = it.read(b) while (c != -1) { out.write(b, 0, c) c = it.read(b) } } } catch (e: Exception) { System.out.println("Impossible to load image for $filename") e.printStackTrace() } } } class PapercallExport( val id: String? = null, val state: String? = null, val talk: PapercallTalk? = null, val tags: List<String> = emptyList(), val profile: PapercallProfile, val co_presenter_profiles: List<PapercallProfile> = emptyList(), val cfp_additional_question_answers: List<PapercallAdditionalQuestion> ) class PapercallAdditionalQuestion( val question_content: String? = null, val content: String? = null ) class PapercallProfile( val name: String, val bio: String? = null, val twitter: String? = null, val company: String? = null, val url: String? = null, val email: String, val avatar: String? = null, var talkId: String? = null ) class PapercallTalk( val title: String? = null, val abstract: String? = null, val description: String? = null, val talk_format: String? = null ) fun toMixitTopic(rawTopic: String): String = when (rawTopic) { "Maker" -> "makers" "Design" -> "design" "Aliens" -> "aliens" "aliens" -> "aliens" "Tech" -> "tech" "Ethic" -> "ethics" "Life style" -> "lifestyle" "Team" -> "team" else -> "other" }
apache-2.0
cda3c862b64360144c35e3e80b6243c7
35.606061
125
0.63096
4.247539
false
false
false
false
pdvrieze/ProcessManager
java-common/src/commonMain/kotlin/net/devrieze/util/ArraySet.kt
1
9907
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package net.devrieze.util import nl.adaptivity.util.multiplatform.arraycopy import nl.adaptivity.util.multiplatform.fill /** * Created by pdvrieze on 11/10/16. */ private typealias BufferPos = Int private typealias OuterPos = Int class ArraySet<T>(initCapacity: Int = 10) : AbstractMutableSet<T>() { private inner class ArraySetIterator(private var pos: OuterPos = 0) : MutableListIterator<T> { init { if (pos < 0 || pos > size) throw IndexOutOfBoundsException() } override fun hasNext() = pos < size override fun hasPrevious() = pos > 0 override fun next(): T { if (pos >= size) throw NoSuchElementException("The iterator is at the end") return this@ArraySet[pos++] } override fun previous(): T { if (pos <= 0) throw NoSuchElementException("The iterator is at the end") --pos return this@ArraySet[pos] } override fun nextIndex() = pos override fun previousIndex() = pos - 1 override fun remove() { removeAt(pos - 1) } override fun add(element: T) { add(element) } override fun set(element: T) { if (this@ArraySet[pos] == element) return val otherPos = indexOf(element) if (otherPos >= 0) { swap(otherPos, pos) } else { val previous = buffer[pos]!! buffer[pos] = element add(previous) } } } @Suppress("UNCHECKED_CAST") private var buffer = arrayOfNulls<Any?>(maxOf(2, initCapacity)) as Array<T?> private var firstElemIdx = 0 private var nextElemIdx = 0 constructor(base: Iterable<T>) : this((base as? Collection)?.let { it.size + 5 } ?: 10) { addAll(base) } constructor(base: Sequence<T>) : this() { addAll(base) } constructor(vararg items: T) : this(items.asList()) operator fun get(pos: OuterPos): T { if (pos < 0 || pos >= size) throw IndexOutOfBoundsException("This index is invalid") val offset = (firstElemIdx + pos) % buffer.size return buffer[offset]!! } operator fun set(pos: OuterPos, value: T): T { return get(pos).apply { if (this != value) { if (!contains(value)) { buffer[pos.toBufferPos()] = value } else { // It's already contained, so just remove the previous value, don't add the new one removeAt(pos) } } } } private fun isInRange(offset: Int): Boolean { if (firstElemIdx <= nextElemIdx) { if (offset !in firstElemIdx..(nextElemIdx - 1)) return false } else if (offset in nextElemIdx..(firstElemIdx - 1)) { return false } return true } override val size: Int get() = (nextElemIdx + buffer.size - firstElemIdx) % buffer.size override fun isEmpty() = size == 0 override fun iterator(): MutableIterator<T> = listIterator() fun listIterator() = listIterator(0) fun listIterator(initPos: OuterPos): MutableListIterator<T> = ArraySetIterator(initPos) override fun contains(element: T) = indexOf(element) >= 0 override fun add(element: T): Boolean { if (contains(element)) { return false } val space = size if (space + 2 >= buffer.size) { reserve(buffer.size * 2) } buffer[nextElemIdx] = element nextElemIdx = (nextElemIdx + 1) % buffer.size return true } override fun addAll(elements: Collection<T>): Boolean { reserve(size + elements.size) return elements.fold(false) { acc, element -> add(element) or acc } } override fun containsAll(elements: Collection<T>): Boolean { return elements.all { contains(it) } } override fun retainAll(elements: Collection<T>): Boolean { val it = iterator() var changed = false while (it.hasNext()) { if (it.next() !in elements) { it.remove() changed = true } } return changed } private fun reserve(reservation: Int) { if (reservation < 0) throw IllegalArgumentException( "The reservation was $reservation but should be larger than or equal to 0") if (reservation + 1 < size) { reserve(size + 1); return } @Suppress("UNCHECKED_CAST") val newBuffer = arrayOfNulls<Any?>(reservation.coerceAtLeast(8)) as Array<T?> if (firstElemIdx <= nextElemIdx) { arraycopy(buffer, firstElemIdx, newBuffer, 0, nextElemIdx - firstElemIdx) nextElemIdx -= firstElemIdx } else { arraycopy(buffer, firstElemIdx, newBuffer, 0, buffer.size - firstElemIdx) arraycopy(buffer, 0, newBuffer, buffer.size - firstElemIdx, nextElemIdx) nextElemIdx += buffer.size - firstElemIdx } buffer = newBuffer firstElemIdx = 0 } override fun remove(element: T): Boolean { indexOf(element).let { pos -> if (pos < 0) { return false; } removeAt(pos) return true } } override fun removeAll(elements: Collection<T>): Boolean { return elements.fold(false) { acc, element-> remove(element) or acc } } @Suppress("NOTHING_TO_INLINE") private inline fun OuterPos.toBufferPos(): BufferPos = when { this < 0 || this >= size -> throw IndexOutOfBoundsException("Invalid position: $this") else -> (this + firstElemIdx) % buffer.size } @Suppress("NOTHING_TO_INLINE") private inline fun BufferPos.toOuterPos(): OuterPos = (buffer.size + this - firstElemIdx) % buffer.size fun swap(first: OuterPos, second: OuterPos) { bufferSwap(first.toBufferPos(), second.toBufferPos()) } private fun bufferSwap(firstPos: BufferPos, secondPos: BufferPos) { val firstValue = buffer[firstPos] buffer[firstPos] = buffer[secondPos] buffer[secondPos] = firstValue } @Deprecated("Use removeAt instead", ReplaceWith("removeAt(index)"), DeprecationLevel.WARNING) fun remove(index: OuterPos) = removeAt(index) fun removeAt(index: OuterPos) = removeAtOffset(index.toBufferPos()) private fun removeAtOffset(offset: BufferPos): T { @Suppress("UNCHECKED_CAST") val result = buffer[offset] as T val bufferSize = buffer.size if (offset + 1 == nextElemIdx) { // optimize removing the last element nextElemIdx-- if (nextElemIdx < 0) nextElemIdx += bufferSize buffer[nextElemIdx] = null } else if (offset == firstElemIdx) { // optimize removing the first element buffer[firstElemIdx++] = null if (firstElemIdx >= bufferSize) firstElemIdx -= bufferSize } else if (firstElemIdx < nextElemIdx) { // Default non-wrapped case, don't attempt to optimize smallest copy ___EEEOEEEE___ arraycopy(buffer, offset + 1, buffer, offset, nextElemIdx - offset - 1) buffer[--nextElemIdx] = null } else if (offset < nextElemIdx && offset < firstElemIdx) { // The offset is wrapped as well EOE_____EEE arraycopy(buffer, offset + 1, buffer, offset, nextElemIdx - offset - 1) buffer[--nextElemIdx] = null } else { // ofset>tail -> tail wrapped, we are in the head section EEE_____EOE arraycopy(buffer, firstElemIdx, buffer, firstElemIdx + 1, offset - firstElemIdx) buffer[firstElemIdx++] = null } return result } fun indexOf(element: T): OuterPos { if (firstElemIdx <= nextElemIdx) { for (i in firstElemIdx until nextElemIdx) { if (buffer[i] == element) { return i.toOuterPos() } } } else { for (i in (firstElemIdx until buffer.size)) { if (buffer[i] == element) { return i.toOuterPos() } } for (i in (0 until nextElemIdx)) { if (buffer[i] == element) { return i.toOuterPos() } } } return -1 } override fun clear() { fill(buffer, null) firstElemIdx = 0 nextElemIdx = 0 } } /** * Returns a mutable set containing all distinct elements from the given sequence. * * The returned set preserves the element iteration order of the original sequence. */ fun <T> Sequence<T>.toMutableArraySet(): MutableSet<T> { return ArraySet<T>().apply { for (item in this@toMutableArraySet) add(item) } } @Suppress("NOTHING_TO_INLINE") inline fun <T> Sequence<T>.toArraySet(): Set<T> = toMutableArraySet() fun <T> Iterable<T>.toMutableArraySet(): MutableSet<T> = ArraySet(this) @Suppress("NOTHING_TO_INLINE") inline fun <T> Iterable<T>.toArraySet(): Set<T> = toMutableArraySet()
lgpl-3.0
1bda51fe9138d87870d9ef44742a0a8f
31.061489
132
0.586656
4.279482
false
false
false
false
udevbe/westmalle
compositor/src/main/kotlin/org/westford/nativ/libinput/libinput_interface.kt
3
1206
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * 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 org.westford.nativ.libinput import org.freedesktop.jaccall.CType import org.freedesktop.jaccall.Field import org.freedesktop.jaccall.Struct @Struct(Field(name = "open_restricted", type = CType.POINTER, dataType = open_restricted::class), Field(name = "close_restricted", type = CType.POINTER, dataType = close_restricted::class)) class libinput_interface : Struct_libinput_interface()
agpl-3.0
aa2df7fef4bf6d31140a485ca14c2150
40.586207
105
0.719735
4.276596
false
false
false
false
brianmadden/krawler
src/test/kotlin/io/thelandscape/KrawlerTest.kt
1
5562
package io.thelandscape /** * Created by [email protected] on 12/4/16. * * Copyright (c) <2016> <H, 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. */ import com.nhaarman.mockitokotlin2.mock import io.thelandscape.krawler.crawler.History.KrawlHistoryEntry import io.thelandscape.krawler.crawler.History.KrawlHistoryIf import io.thelandscape.krawler.crawler.KrawlConfig import io.thelandscape.krawler.crawler.KrawlQueue.KrawlQueueEntry import io.thelandscape.krawler.crawler.KrawlQueue.KrawlQueueIf import io.thelandscape.krawler.crawler.Krawler import io.thelandscape.krawler.http.KrawlDocument import io.thelandscape.krawler.http.KrawlUrl import io.thelandscape.krawler.http.RequestProviderIf import io.thelandscape.krawler.robots.RoboMinderIf import io.thelandscape.krawler.robots.RobotsConfig import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.channels.produce import kotlinx.coroutines.runBlocking import org.apache.http.client.protocol.HttpClientContext import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class KrawlerTest { val exampleUrl = KrawlUrl.new("http://www.example.org") val mockConfig = KrawlConfig(emptyQueueWaitTime = 1, totalPages = 1, maxDepth = 4) val mockHistory = mock<KrawlHistoryIf>() val mockQueue = listOf(mock<KrawlQueueIf>()) val mockRequests = mock<RequestProviderIf>() val mockJob = Job() val mockMinder = mock<RoboMinderIf>() val mockContext = mock<HttpClientContext>() val preparedResponse = KrawlDocument(exampleUrl, prepareResponse(200, "<html><head><title>Test</title></head><body>" + "<div><a href=\"http://www.testone.com\">Test One</a>" + "<img src=\"imgone.jpg\" /></div></body></html>"), mockContext) class testCrawler(x: KrawlConfig, w: KrawlHistoryIf, y: List<KrawlQueueIf>, u: RobotsConfig?, v: RequestProviderIf, z: Job): Krawler(x, w, y, u, v, z) { val capture: MutableList<String> = mutableListOf() override fun shouldVisit(url: KrawlUrl): Boolean { return true } override fun shouldCheck(url: KrawlUrl): Boolean { return false } override fun visit(url: KrawlUrl, doc: KrawlDocument) { capture.add("VISIT - ${url.rawUrl}") } override fun check(url: KrawlUrl, statusCode: Int) { capture.add("CHECK - ${url.rawUrl}") } } val testKrawler = testCrawler(mockConfig, mockHistory, mockQueue, null, mockRequests, mockJob) @Before fun setUp() { // Mockito.registerInstanceCreator { KrawlUrl.new("") } testKrawler.minder = mockMinder testKrawler.capture.clear() } /** * Test the doCrawl method */ @Test fun testDoCrawl() = runBlocking { val allThree = GlobalScope.produce(Dispatchers.Default) { for (a in listOf(Krawler.KrawlAction.Noop, Krawler.KrawlAction.Visit(exampleUrl, preparedResponse), Krawler.KrawlAction.Check(exampleUrl, preparedResponse.statusCode))) send(a) } testKrawler.doCrawl(allThree) assertTrue(testKrawler.capture.contains("VISIT - http://www.example.org")) assertTrue(testKrawler.capture.contains("CHECK - http://www.example.org")) assertEquals(2, testKrawler.capture.size) } /** * TODO: Add this test when there is better support for coroutines in mockito @Test fun testFetch() = runBlocking { whenever(mockMinder.isSafeToVisit(any())).thenReturn(true) // Depth tests (max depth was set to 4) var resp = testKrawler.fetch(exampleUrl, 5, exampleUrl).await() assertTrue { resp is Krawler.KrawlAction.Noop } resp = testKrawler.fetch(exampleUrl, 3, exampleUrl).await() assertTrue { resp is Krawler.KrawlAction.Visit } } */ @Test fun testHarvestLinks() { val links: List<KrawlQueueEntry> = runBlocking { testKrawler.harvestLinks(preparedResponse, exampleUrl, KrawlHistoryEntry(), 0, 0) } assertEquals(2, links.size) val linksText = links.map { it.url } assertTrue { "http://www.testone.com/" in linksText } assertTrue { "http://www.example.org/imgone.jpg" in linksText } } }
mit
4bd157bd107c834ff54fb3f1289bcfb7
39.014388
120
0.686264
4.11695
false
true
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/settings/conventions/TexifyConventionsProjectSettingsManager.kt
1
1130
package nl.hannahsten.texifyidea.settings.conventions import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.project.Project /** * Settings manager that persists and loads settings from a project local settings file (i.e., below the .idea folder). * * The class is internal because clients should use the [TexifyConventionsSettingsManager] facade. */ @State(name = "Conventions", storages = [Storage("texifySettings.xml")]) internal class TexifyConventionsProjectSettingsManager(var project: Project? = null) : PersistentStateComponent<TexifyConventionsProjectState> { private var projectState: TexifyConventionsProjectState = TexifyConventionsProjectState() override fun getState(): TexifyConventionsProjectState = projectState override fun loadState(newState: TexifyConventionsProjectState) { if (!newState.scheme.isProjectScheme) throw IllegalStateException("ProjectSettingsManager can only save project schemes") projectState = newState } }
mit
46d73479463b75584ceb7f168d1a15f3
42.5
119
0.793805
5.183486
false
false
false
false
debop/debop4k
debop4k-core/src/main/kotlin/debop4k/core/json/JacksonSerializer.kt
1
2221
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.core.json import com.fasterxml.jackson.databind.ObjectMapper import debop4k.core.collections.emptyByteArray import debop4k.core.collections.isNullOrEmpty import debop4k.core.utils.EMPTY_STRING /** * Jackson Json Serializer * @author debop [email protected] */ class JacksonSerializer @JvmOverloads constructor(val mapper: ObjectMapper = DefaultObjectMapper) : JsonSerializer { /** 객체를 Json 직렬화를 수행하여 바이트 배열로 반환한다 */ override fun <T : Any> toByteArray(graph: T?): ByteArray { if (graph == null) return emptyByteArray return mapper.writeValueAsBytes(graph) } /** Json 데이터를 가진 바이트 배열을 읽어 지정된 수형의 인스턴스를 생성한다 */ override fun <T : Any> fromByteArray(jsonBytes: ByteArray?, clazz: Class<T>): T? { if (jsonBytes.isNullOrEmpty) return null return mapper.readValue(jsonBytes, clazz) } /** 객체를 Json 직렬화를 통해 문자열로 변환한다 */ override fun <T : Any> toString(graph: T?): String { if (graph == null) return EMPTY_STRING return mapper.writeValueAsString(graph) } /** Json 문자열을 역직렬화해서 지정된 수형의 인스턴스를 생성한다 */ override fun <T : Any> fromString(jsonText: String?, clazz: Class<T>): T? { if (jsonText.isNullOrEmpty()) return null return mapper.readValue(jsonText, clazz) } companion object { @JvmStatic @JvmOverloads fun of(mapper: ObjectMapper = DefaultObjectMapper) = JacksonSerializer(mapper) } }
apache-2.0
8f5c791fd848902cdcb704101eded35a
28.536232
92
0.713795
3.744485
false
false
false
false
clappr/clappr-android
clappr/src/main/kotlin/io/clappr/player/playback/MediaPlayerPlayback.kt
1
11490
package io.clappr.player.playback import android.content.Context import android.media.AudioManager import android.media.MediaPlayer import android.os.Bundle import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import io.clappr.player.base.Event import io.clappr.player.base.Options import io.clappr.player.base.UIObject import io.clappr.player.components.Playback import io.clappr.player.components.PlaybackEntry import io.clappr.player.components.PlaybackSupportCheck import io.clappr.player.log.Logger class MediaPlayerPlayback(source: String, mimeType: String? = null, options: Options = Options()): Playback(source, mimeType, options, name = entry.name, supportsSource = supportsSource) { enum class InternalState { NONE, IDLE, ERROR, ATTACHED, PREPARED, STARTED, PAUSED, STOPPED, BUFFERING } companion object { private const val TAG: String = "MediaPlayerPlayback" const val name = "media_player" val supportsSource: PlaybackSupportCheck = { _, _ -> true } val entry = PlaybackEntry( name = name, supportsSource = supportsSource, factory = { source, mimeType, options -> MediaPlayerPlayback(source, mimeType, options) }) } override val viewClass: Class<*> get() = PlaybackView::class.java private var mediaPlayer = MediaPlayer() private var internalState: InternalState = InternalState.NONE set(value) { val oldState = state field = value sendUpdateStateEvents(oldState) } init { mediaPlayer.setOnInfoListener { _, what, extra -> infoLog(what, extra)?.let { Logger.info(TAG, it) } when(what) { MediaPlayer.MEDIA_INFO_BUFFERING_START -> internalState = InternalState.BUFFERING MediaPlayer.MEDIA_INFO_BUFFERING_END -> internalState = InternalState.STARTED } false } mediaPlayer.setOnErrorListener { _, what, extra -> Logger.info(TAG, "error: $what($extra)" ) internalState = InternalState.ERROR true } mediaPlayer.setOnSeekCompleteListener { Logger.info(TAG, "seek completed") if (mediaPlayer.isPlaying) { trigger(Event.PLAYING.value) } } mediaPlayer.setOnVideoSizeChangedListener { _, width, height -> Logger.info(TAG, "video size: $width / $height") (view as? PlaybackView)?.videoWidth = width (view as? PlaybackView)?.videoHeight = height view?.requestLayout() } mediaPlayer.setOnPreparedListener { internalState = InternalState.PREPARED mediaPlayer.start() internalState = InternalState.STARTED } mediaPlayer.setOnBufferingUpdateListener { _, percent -> Logger.info(TAG, "buffered percentage: $percent") val bundle = Bundle() bundle.putDouble("percentage", percent.toDouble()) trigger(Event.DID_UPDATE_BUFFER.value, bundle) } mediaPlayer.setOnCompletionListener { internalState = InternalState.ATTACHED } mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC) mediaPlayer.setScreenOnWhilePlaying(true) try { mediaPlayer.setDataSource(source) internalState = InternalState.IDLE mediaPlayer.setDisplay(null) val holder = (view as? PlaybackView)?.holder holder?.addCallback(object: SurfaceHolder.Callback { override fun surfaceChanged(sh: SurfaceHolder, format: Int, width: Int, height: Int) { Logger.info(TAG, "surface changed: $format/$width/$height") } override fun surfaceDestroyed(sh: SurfaceHolder) { Logger.info(TAG, "surface destroyed") stop() mediaPlayer.setDisplay(null) internalState = InternalState.IDLE } override fun surfaceCreated(sh: SurfaceHolder) { Logger.info(TAG, "surface created") mediaPlayer.setDisplay(holder) internalState = InternalState.ATTACHED } }) } catch (e: Exception) { internalState = InternalState.ERROR } } private fun infoLog(what: Int, extra: Int): String? { val log = when(what) { MediaPlayer.MEDIA_INFO_BUFFERING_START -> "MEDIA_INFO_BUFFERING_START" MediaPlayer.MEDIA_INFO_BUFFERING_END -> "MEDIA_INFO_BUFFERING_END" MediaPlayer.MEDIA_INFO_UNKNOWN -> "MEDIA_INFO_UNKNOWN" MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING -> "MEDIA_INFO_VIDEO_TRACK_LAGGING" MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START -> "MEDIA_INFO_VIDEO_RENDERING_START" MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING -> "MEDIA_INFO_BAD_INTERLEAVING" MediaPlayer.MEDIA_INFO_NOT_SEEKABLE -> "MEDIA_INFO_NOT_SEEKABLE" MediaPlayer.MEDIA_INFO_METADATA_UPDATE -> "MEDIA_INFO_METADATA_UPDATE" MediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE -> "MEDIA_INFO_UNSUPPORTED_SUBTITLE" MediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT -> "MEDIA_INFO_SUBTITLE_TIMED_OUT" else -> "UNKNOWN" } return "$log ($what / $extra)" } protected class PlaybackView(context: Context?) : SurfaceView(context) { var videoHeight = 0 var videoWidth = 0 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var width = View.getDefaultSize(videoWidth, widthMeasureSpec) var height = View.getDefaultSize(videoHeight, heightMeasureSpec) Logger.info(TAG, "onMeasure: $width/$height") if ( (videoWidth > 0) && (videoHeight > 0) ) { if (videoWidth * height > width * videoHeight) { Logger.info(TAG, "image too tall") height = width * videoHeight / videoWidth } else if (videoWidth * height < width * videoHeight) { Logger.info(TAG, "image too wide") width = height * videoWidth / videoHeight } else { Logger.info(TAG, "aspect ratio is correct: $width/$height = $videoWidth/$videoHeight") } } Logger.info(TAG, "setting size to: $width/$height") setMeasuredDimension(width, height) } } override fun render() : UIObject { if (!play()) { this.once(Event.READY.value, { _: Bundle? -> play() }) } return this } override val state: State get() = getState(internalState) private fun getState (internal: InternalState) : State { return when (internal) { InternalState.NONE, InternalState.IDLE -> { State.NONE } InternalState.ATTACHED, InternalState.PREPARED, InternalState.STOPPED -> { State.IDLE } InternalState.STARTED -> { State.PLAYING } InternalState.PAUSED -> { State.PAUSED } InternalState.BUFFERING -> { State.STALLING } InternalState.ERROR -> { State.ERROR} } } override val mediaType: MediaType get() { return if (mediaPlayer.duration > -1) MediaType.VOD else MediaType.LIVE } override val duration: Double get() { if (state != State.NONE && state != State.ERROR && internalState != InternalState.ATTACHED) { val mediaDuration = mediaPlayer.duration if (mediaDuration > -1) { return mediaDuration / 1000.0 } } return Double.NaN } override val position: Double get() { if (state != State.NONE && state != State.ERROR && internalState != InternalState.ATTACHED) { val currentPosition = mediaPlayer.currentPosition if (currentPosition > -1) { return currentPosition / 1000.0 } } return Double.NaN } override val canPlay: Boolean get() = ( (state != State.NONE) && (state != State.ERROR) ) override val canPause: Boolean get() = ( (state != State.NONE) && (state != State.ERROR) && (mediaType == MediaType.VOD) ) override val canSeek: Boolean get() = ( (state != State.NONE) && (state != State.ERROR) && (mediaType == MediaType.VOD) ) val canStop: Boolean get() = ( (state == State.PLAYING) || (state == State.PAUSED) || (state == State.STALLING) ) override fun play(): Boolean { if (canPlay) { if (state != State.PLAYING) { trigger(Event.WILL_PLAY.value) } if (internalState == InternalState.ATTACHED) { mediaPlayer.prepareAsync() } else { mediaPlayer.start() } if (state == State.PAUSED) { internalState = InternalState.STARTED } return true } else { return false } } override fun pause(): Boolean { return if (canPause) { if ( (state == State.PLAYING) || (state == State.STALLING) ) { trigger(Event.WILL_PAUSE.value) mediaPlayer.pause() } if (state == State.PLAYING) { internalState = InternalState.PAUSED } true } else { false } } override fun stop(): Boolean { return if (canStop) { trigger(Event.WILL_STOP.value) try { mediaPlayer.stop() internalState = InternalState.STOPPED } catch (iee: IllegalStateException) { Logger.info(TAG, "stop - $iee") } true } else { false } } override fun seek(seconds: Int): Boolean { return if (canSeek) { trigger(Event.WILL_SEEK.value) mediaPlayer.seekTo(seconds * 1000) true } else { false } } private fun sendUpdateStateEvents(previousState: State) { if (state != previousState) { when (state) { State.IDLE -> { if (previousState == State.NONE) { trigger(Event.READY.value) } else if (internalState == InternalState.STOPPED) { trigger(Event.DID_STOP.value) } else if (previousState == State.PLAYING) { trigger(Event.DID_COMPLETE.value) } } State.PLAYING -> { trigger(Event.PLAYING.value) } State.PAUSED -> { trigger(Event.DID_PAUSE.value) } State.ERROR -> { trigger(Event.ERROR.value) } State.STALLING -> { trigger(Event.STALLING.value) } State.NONE -> { } } } } }
bsd-3-clause
e2728898fafdb3da8c74f29ddfc547aa
33.712991
188
0.551436
4.823678
false
false
false
false
lfkdsk/JustDB
src/sql/lexer/SqlLexer.kt
1
4074
package sql.lexer import sql.token.SqlIdToken import sql.token.SqlNumToken import sql.token.SqlStrToken import sql.token.SqlToken import utils.parsertools.ast.Token import utils.parsertools.exception.ParseException import utils.parsertools.lex.Lexer import java.io.LineNumberReader import java.io.Reader import java.util.* import java.util.regex.Matcher import java.util.regex.Pattern /** * Created by liufengkai on 2017/4/27. */ class SqlLexer(reader: Reader) : Lexer { private var reader: LineNumberReader = LineNumberReader(reader) private val regPattern: Pattern private val queue = ArrayList<SqlToken>() private var hasMore: Boolean = true private val regReg: SqlReg = SqlReg() init { // init reg pattern regPattern = Pattern.compile(regReg.hobbyReg) } @Throws(ParseException::class) private fun readLine() { val line: String? = reader.readLine() if (line == null) { hasMore = false return } val lineNum = reader.lineNumber val matcher = regPattern.matcher(line) /* 1.透明边界:允许环视这样就能避免一些词素匹配混乱 2.匹配边界:不允许正则里面包含对边界的限定符 */ matcher.useTransparentBounds(true) .useAnchoringBounds(false) var start = 0 val end = line.count() if (end == 0) return while (start < end) { matcher.region(start, end) // 出现匹配 if (matcher.lookingAt()) { addToken(lineNum, matcher) start = matcher.end() } else { throw ParseException("bad token at line $lineNum") } } queue.add(SqlIdToken(lineNum, SqlToken.EOL)) } /** * 填充队列 * * @param index 指定num * @return 返回状态 * @throws ParseException */ @Throws(ParseException::class) private fun fillQueue(index: Int): Boolean { while (index >= queue.count()) { if (hasMore) { readLine() } else { return false } } return true } override fun tokenAt(index: Int): Token { if (fillQueue(index)) { return queue[index] } else { return SqlToken.EOF } } override fun nextToken(): Token { if (fillQueue(0)) { return queue.removeAt(0) } else { return SqlToken.EOF } } /** * 所谓字符串转译 * @param str 传入字符串 * * * @return 返回字符串 */ private fun toStringLiteral(str: String): String { val builder = StringBuilder() val length = str.length - 1 var i = 1 while (i < length) { var ch = str[i] // 发现需要转译的\ if (ch == '\\' && i + 1 < length) { // 取下一个字符 val ch2 = str[i + 1] // 手动跳过 if (ch2 == '"' || ch2 == '\\') { ch = str[++i] // 手工转译嵌入\n } else if (ch2 == 'n') { ++i ch = '\n' } } builder.append(ch) i++ } return builder.toString() } /** * 通过匹配模式判断词素类型 * @param lineNum 行号 * * * @param matcher matcher */ private fun addToken(lineNum: Int, matcher: Matcher) { val first = matcher.group(SqlReg.RegType.NOT_EMPTY_INDEX.regId) if (first != null) { // 不是空格 if (matcher.group(SqlReg.RegType.ANNOTATION_INDEX.regId) == null) { // 不是注释 var token: SqlToken? = null // 是数字 if (matcher.group(SqlReg.RegType.FLOAT_NUMBER_INDEX.regId) != null) { if (first.contains("e") || first.contains("E") || first.contains(".")) { token = SqlNumToken(lineNum, SqlToken.REAL, first.toDouble()) } else { token = SqlNumToken(lineNum, SqlToken.NUM, first.toInt()) } // handler "" 空字串 } else if (first == "\"\"" || matcher.group(SqlReg.RegType.STRING_INDEX.regId) != null) { token = SqlStrToken(lineNum, toStringLiteral(first)) } else { // when (first) { // BoolToken.TRUE -> token = BoolToken(lineNum, BoolToken.BoolType.TRUE) // BoolToken.FALSE -> token = BoolToken(lineNum, BoolToken.BoolType.FALSE) // NullToken.NULL -> token = NullToken(lineNum) // else -> token = IdToken(lineNum, first!!) // } token = SqlIdToken(lineNum, first) } queue.add(token) } } } }
apache-2.0
c8e7291276e98d7e9d867c24e91bcbe5
19.912568
93
0.630946
2.931801
false
false
false
false
jingcai-wei/android-news
app/src/main/java/com/sky/android/news/ui/helper/RecyclerHelper.kt
1
2621
/* * Copyright (c) 2017 The sky Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sky.android.news.ui.helper import androidx.recyclerview.widget.RecyclerView import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.sky.android.common.util.DisplayUtil /** * Created by sky on 17-9-22. */ class RecyclerHelper(private val refreshLayout: SwipeRefreshLayout, private val recyclerView: RecyclerView, private val onCallback: OnCallback) : RecyclerView.OnScrollListener(), SwipeRefreshLayout.OnRefreshListener { var mLoadMore: Boolean = false init { refreshLayout.setOnRefreshListener(this) recyclerView.addOnScrollListener(this) } fun setLoadMore(loadMore: Boolean) { mLoadMore = loadMore } override fun onRefresh() { onCallback.onRefresh() } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (!mLoadMore) return if (newState == RecyclerView.SCROLL_STATE_IDLE && !refreshLayout.isRefreshing && isSlideToBottom(recyclerView)) { // 加载更多 refreshLayout.isRefreshing = true onCallback.onLoadMore() } } fun isRefreshing(): Boolean = refreshLayout.isRefreshing fun forceRefreshing() { if (isRefreshing()) return // 显示加载进度 refreshLayout.setProgressViewOffset(true, 0, DisplayUtil.dip2px(refreshLayout.context, 60f)) refreshLayout.isRefreshing = true } fun cancelRefreshing() { if (!isRefreshing()) return refreshLayout.isRefreshing = false } private fun isSlideToBottom(recyclerView: RecyclerView): Boolean { return recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset() >= recyclerView.computeVerticalScrollRange() } interface OnCallback { fun onRefresh() fun onLoadMore() } }
apache-2.0
a22d1b7c4989c45d713d845cf75a1d33
27.593407
96
0.67897
5.040698
false
false
false
false
clangen/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/shared/mixin/ViewModelMixin.kt
1
1351
package io.casey.musikcube.remote.ui.shared.mixin import android.os.Bundle import io.casey.musikcube.remote.framework.MixinBase import io.casey.musikcube.remote.framework.ViewModel class ViewModelMixin(private val provider: ViewModel.Provider): MixinBase() { private var viewModel: ViewModel<*>? = null fun <T: ViewModel<*>> get(): T { if (viewModel == null) { viewModel = provider.createViewModel() } @Suppress("unchecked_cast") return viewModel as T } override fun onCreate(bundle: Bundle) { super.onCreate(bundle) viewModel = ViewModel.restore(bundle.getLong(EXTRA_VIEW_MODEL_ID, -1)) if (viewModel == null) { viewModel = provider.createViewModel() } } override fun onResume() { super.onResume() viewModel?.onResume() } override fun onPause() { super.onPause() viewModel?.onPause() } override fun onSaveInstanceState(bundle: Bundle) { super.onSaveInstanceState(bundle) if (viewModel != null) { bundle.putLong(EXTRA_VIEW_MODEL_ID, viewModel!!.id) } } override fun onDestroy() { super.onDestroy() viewModel?.onDestroy() } companion object { const val EXTRA_VIEW_MODEL_ID = "extra_view_model_id" } }
bsd-3-clause
63a62c8b0877952770b99ef3e232f0cc
24.037037
78
0.617321
4.415033
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/muteparticipants/ViewState.kt
1
1108
package com.quickblox.sample.conference.kotlin.presentation.screens.muteparticipants import androidx.annotation.IntDef import com.quickblox.sample.conference.kotlin.presentation.screens.muteparticipants.ViewState.Companion.ERROR import com.quickblox.sample.conference.kotlin.presentation.screens.muteparticipants.ViewState.Companion.PROGRESS import com.quickblox.sample.conference.kotlin.presentation.screens.muteparticipants.ViewState.Companion.SHOW_LOGIN_SCREEN import com.quickblox.sample.conference.kotlin.presentation.screens.muteparticipants.ViewState.Companion.SHOW_PARTICIPANTS import com.quickblox.sample.conference.kotlin.presentation.screens.muteparticipants.ViewState.Companion.UPDATE_LIST /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ @IntDef(PROGRESS, ERROR, SHOW_PARTICIPANTS, UPDATE_LIST, SHOW_LOGIN_SCREEN) annotation class ViewState { companion object { const val PROGRESS = 0 const val ERROR = 1 const val SHOW_PARTICIPANTS = 2 const val UPDATE_LIST = 3 const val SHOW_LOGIN_SCREEN = 4 } }
bsd-3-clause
2747a3c005b3c8d6a916bfdf3e9de4b5
47.173913
121
0.801265
4.161654
false
false
false
false
TeamAmaze/AmazeFileManager
app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCommonsArchiveExtractor.kt
1
4944
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.compressed.extractcontents.helpers import android.content.Context import com.amaze.filemanager.R import com.amaze.filemanager.application.AppConfig import com.amaze.filemanager.fileoperations.utils.UpdatePosition import com.amaze.filemanager.filesystem.FileUtil import com.amaze.filemanager.filesystem.MakeDirectoryOperation import com.amaze.filemanager.filesystem.compressed.extractcontents.Extractor import com.amaze.filemanager.filesystem.files.GenericCopyUtil import org.apache.commons.compress.archivers.ArchiveEntry import org.apache.commons.compress.archivers.ArchiveInputStream import java.io.* import java.util.* abstract class AbstractCommonsArchiveExtractor( context: Context, filePath: String, outputPath: String, listener: OnUpdate, updatePosition: UpdatePosition ) : Extractor(context, filePath, outputPath, listener, updatePosition) { /** * Subclasses implement this method to create [ArchiveInputStream] instances with given archive * as [InputStream]. * * @param inputStream archive as [InputStream] */ abstract fun createFrom(inputStream: InputStream): ArchiveInputStream @Throws(IOException::class) @Suppress("EmptyWhileBlock") override fun extractWithFilter(filter: Filter) { var totalBytes: Long = 0 val archiveEntries = ArrayList<ArchiveEntry>() var inputStream = createFrom(FileInputStream(filePath)) var archiveEntry: ArchiveEntry? try { while (inputStream.nextEntry.also { archiveEntry = it } != null) { archiveEntry?.run { if (filter.shouldExtract(name, isDirectory)) { archiveEntries.add(this) totalBytes += size } } } if (archiveEntries.size > 0) { listener.onStart(totalBytes, archiveEntries[0].name) inputStream.close() inputStream = createFrom(FileInputStream(filePath)) archiveEntries.forEach { entry -> if (!listener.isCancelled) { listener.onUpdate(entry.name) // TAR is sequential, you need to walk all the way to the file you want while (entry.hashCode() != inputStream.nextEntry.hashCode()) {} extractEntry(context, inputStream, entry, outputPath) } } inputStream.close() listener.onFinish() } else { throw EmptyArchiveNotice() } } finally { inputStream.close() } } @Throws(IOException::class) protected fun extractEntry( context: Context, inputStream: ArchiveInputStream, entry: ArchiveEntry, outputDir: String ) { if (entry.isDirectory) { MakeDirectoryOperation.mkdir(File(outputDir, entry.name), context) return } val outputFile = File(outputDir, entry.name) if (false == outputFile.parentFile?.exists()) { MakeDirectoryOperation.mkdir(outputFile.parentFile, context) } FileUtil.getOutputStream(outputFile, context)?.let { fileOutputStream -> BufferedOutputStream(fileOutputStream).run { var len: Int val buf = ByteArray(GenericCopyUtil.DEFAULT_BUFFER_SIZE) while (inputStream.read(buf).also { len = it } != -1) { write(buf, 0, len) updatePosition.updatePosition(len.toLong()) } close() outputFile.setLastModified(entry.lastModifiedDate.time) } } ?: AppConfig.toast( context, context.getString( R.string.error_archive_cannot_extract, entry.name, outputDir ) ) } }
gpl-3.0
a94c6dbb7592e0c2dc6d42ec7e099d95
38.552
107
0.631675
5.060389
false
false
false
false
Gruveo/sdk-examples-android-kotlin
app/src/main/kotlin/com/gruveo/sdk/kotlin/MainActivity.kt
1
3924
package com.gruveo.sdk.kotlin import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.gruveo.sdk.Gruveo import com.gruveo.sdk.model.CallEndReason import com.gruveo.sdk.model.CallEndReason.* import kotlinx.android.synthetic.main.activity_main.* import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody class MainActivity : AppCompatActivity() { private val REQUEST_CALL = 1 private val SIGNER_URL = "https://api-demo.gruveo.com/signer" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) main_video_button.setOnClickListener { initCall(true) } main_voice_button.setOnClickListener { initCall(false) } } private fun initCall(videoCall: Boolean) { val otherExtras = Bundle().apply { putBoolean(Gruveo.GRV_EXTRA_VIBRATE_IN_CHAT, false) putBoolean(Gruveo.GRV_EXTRA_DISABLE_CHAT, false) } val code = main_edittext.text.toString() val result = Gruveo.Builder(this) .callCode(code) .videoCall(videoCall) .clientId("demo") .requestCode(REQUEST_CALL) .otherExtras(otherExtras) .eventsListener(eventsListener) .build() when (result) { Gruveo.GRV_INIT_MISSING_CALL_CODE -> { } Gruveo.GRV_INIT_INVALID_CALL_CODE -> { } Gruveo.GRV_INIT_MISSING_CLIENT_ID -> { } Gruveo.GRV_INIT_OFFLINE -> { } else -> { } } } private val eventsListener = object : Gruveo.EventsListener { override fun callInit(videoCall: Boolean, code: String) { } override fun requestToSignApiAuthToken(token: String) { Gruveo.authorize(signToken(token)) } override fun callEstablished(code: String) { } override fun callEnd(data: Intent, isInForeground: Boolean) { parseCallExtras(data) } override fun recordingStateChanged(us: Boolean, them: Boolean) { } override fun recordingFilename(filename: String) { } } private fun signToken(token: String): String { val body = RequestBody.create(MediaType.parse("text/plain"), token) val request = Request.Builder() .url(SIGNER_URL) .post(body) .build() val response = OkHttpClient().newCall(request).execute() return response.body()?.string() ?: "" } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CALL && resultCode == Activity.RESULT_OK && data != null) { parseCallExtras(data) } } private fun parseCallExtras(data: Intent) { val endReason = data.getSerializableExtra(Gruveo.GRV_RES_CALL_END_REASON) val callCode = data.getStringExtra(Gruveo.GRV_RES_CALL_CODE) val leftMessageTo = data.getStringExtra(Gruveo.GRV_RES_LEFT_MESSAGE_TO) val duration = data.getIntExtra(Gruveo.GRV_RES_CALL_DURATION, 0) val messagesSent = data.getIntExtra(Gruveo.GRV_RES_MESSAGES_SENT, 0) when (endReason as CallEndReason) { BUSY -> { } HANDLE_BUSY -> {} HANDLE_UNREACHABLE -> { } HANDLE_NONEXIST -> { } FREE_DEMO_ENDED -> { } ROOM_LIMIT_REACHED -> { } NO_CONNECTION -> { } INVALID_CREDENTIALS -> { } UNSUPPORTED_PROTOCOL_VERSION -> { } OTHER_PARTY -> { } else -> { } // USER - we hanged up the call } } }
mit
bb7e8c7bcfe3b4e0edaad35880d6c714
31.97479
94
0.603721
4.020492
false
false
false
false
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/base/ac/SearchActivity.kt
1
32744
package yuku.alkitab.base.ac import android.content.Context import android.content.Intent import android.database.Cursor import android.database.MatrixCursor import android.os.Bundle import android.os.SystemClock import android.text.SpannableStringBuilder import android.text.Spanned import android.text.TextUtils import android.text.style.ForegroundColorSpan import android.text.style.UnderlineSpan import android.util.SparseBooleanArray import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.AutoCompleteTextView import android.widget.CheckBox import android.widget.CompoundButton import android.widget.ImageButton import android.widget.TextView import androidx.annotation.Keep import androidx.appcompat.view.ActionMode import androidx.appcompat.widget.SearchView import androidx.core.content.res.ResourcesCompat import androidx.core.graphics.ColorUtils import androidx.core.view.isVisible import androidx.cursoradapter.widget.CursorAdapter import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.MaterialDialog import com.google.android.material.progressindicator.CircularProgressIndicator import com.google.android.material.snackbar.Snackbar import java.util.ArrayList import java.util.Locale import me.zhanghai.android.fastscroll.FastScrollerBuilder import yuku.afw.storage.Preferences import yuku.alkitab.base.App import yuku.alkitab.base.S import yuku.alkitab.base.ac.base.BaseActivity import yuku.alkitab.base.model.MVersion import yuku.alkitab.base.model.MVersionInternal import yuku.alkitab.base.storage.Prefkey import yuku.alkitab.base.util.AppLog import yuku.alkitab.base.util.Appearances import yuku.alkitab.base.util.ClipboardUtil import yuku.alkitab.base.util.Debouncer import yuku.alkitab.base.util.Foreground import yuku.alkitab.base.util.FormattedVerseText import yuku.alkitab.base.util.Jumper import yuku.alkitab.base.util.QueryTokenizer import yuku.alkitab.base.util.SearchEngine import yuku.alkitab.base.util.TextColorUtil import yuku.alkitab.debug.R import yuku.alkitab.model.Version import yuku.alkitab.util.Ari import yuku.alkitab.util.IntArrayList import yuku.alkitabintegration.display.Launcher private const val EXTRA_openedBookId = "openedBookId" private const val REQCODE_bookFilter = 1 private const val ID_CLEAR_HISTORY = -1L private const val COLINDEX_ID = 0 private const val COLINDEX_QUERY_STRING = 1 private const val TAG = "SearchActivity" class SearchActivity : BaseActivity() { private lateinit var root: View private lateinit var bVersion: TextView private lateinit var searchView: SearchView private lateinit var progressbar: CircularProgressIndicator private lateinit var bSearch: ImageButton private lateinit var lsSearchResults: RecyclerView private lateinit var tSearchTips: TextView private lateinit var panelFilter: View private lateinit var cFilterOlds: CheckBox private lateinit var cFilterNews: CheckBox private lateinit var cFilterSingleBook: CheckBox private lateinit var tFilterAdvanced: TextView private lateinit var bEditFilter: View private var hiliteColor = 0 private var selectedBookIds = SparseBooleanArray() private var openedBookId = 0 private var filterUserAction = 0 // when it's not user action, set to nonzero private val adapter = SearchAdapter(IntArrayList(), emptyList()) private var searchInVersion: Version = S.activeVersion() private var searchInVersionId: String = S.activeVersionId() private var textSizeMult = S.getDb().getPerVersionSettings(searchInVersionId).fontSizeMultiplier private lateinit var searchHistoryAdapter: SearchHistoryAdapter private var actionMode: ActionMode? = null private fun createActionModeCallback() = object : ActionMode.Callback { override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { menuInflater.inflate(R.menu.context_search, menu) return true } override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val checked_count = adapter.checkedPositions.size if (checked_count == 1) { mode.setTitle(R.string.verse_select_one_verse_selected) } else { mode.title = getString(R.string.verse_select_multiple_verse_selected, checked_count.toString()) } return true } override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { return when (item.itemId) { R.id.menuSelectAll -> { adapter.checkAll() true } R.id.menuCopy -> { val sb = SpannableStringBuilder() val aris = adapter.searchResults for (i in adapter.checkedPositions.sorted()) { val ari = aris[i] val reference = searchInVersion.reference(ari) val verseText = FormattedVerseText.removeSpecialCodes(searchInVersion.loadVerseText(ari)) val sb_len = sb.length sb.append(reference).append("\n").append(verseText).append("\n\n") if (adapter.checkedPositions.size < 1000) { // too much spans is very slow sb.setSpan(UnderlineSpan(), sb_len, sb_len + reference.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } ClipboardUtil.copyToClipboard(sb) Snackbar.make(root, R.string.search_selected_verse_copied, Snackbar.LENGTH_SHORT).show() mode.finish() true } else -> false } } override fun onDestroyActionMode(mode: ActionMode) { adapter.uncheckAll() actionMode = null } } private fun onCheckedVerseChanged() { @Suppress("NotifyDataSetChanged") adapter.notifyDataSetChanged() if (adapter.checkedPositions.isEmpty()) { actionMode?.finish() } else { actionMode?.invalidate() } } @Keep class SearchHistory(val entries: MutableList<Entry>) { @Keep class Entry(val query_string: String) } inner class SearchHistoryAdapter : CursorAdapter(App.context, null, 0) { var entries: MutableList<SearchHistory.Entry> = ArrayList() private var query_string: String? = null override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View { return layoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false) } override fun bindView(view: View, context: Context, cursor: Cursor) { val text1 = view.findViewById<TextView>(android.R.id.text1) val _id = cursor.getLong(COLINDEX_ID) val text = if (_id == -1L) { val sb = SpannableStringBuilder(getString(R.string.search_clear_history)) sb.setSpan(ForegroundColorSpan(ResourcesCompat.getColor(resources, R.color.escape, theme)), 0, sb.length, 0) sb } else { cursor.getString(COLINDEX_QUERY_STRING) } text1.text = text } override fun convertToString(cursor: Cursor): CharSequence { return cursor.getString(COLINDEX_QUERY_STRING) } fun setData(searchHistory: SearchHistory) { entries.clear() entries.addAll(searchHistory.entries) filter() } fun setQuery(query_string: String?) { this.query_string = query_string filter() } private fun filter() { val mc = MatrixCursor(arrayOf("_id", "query_string") /* Can be any string, but this must correspond to COLINDEX_ID and COLINDEX_QUERY_STRING */) for (i in entries.indices) { val entry = entries[i] val query_string = query_string if (query_string.isNullOrEmpty() || entry.query_string.lowercase(Locale.getDefault()).startsWith(query_string.lowercase(Locale.getDefault()))) { mc.addRow(arrayOf(i.toLong(), entry.query_string)) } } // add last item to clear search history only if there is something else if (mc.count > 0) { mc.addRow(arrayOf(ID_CLEAR_HISTORY, "")) } // sometimes this is called from bg. So we need to make sure this is run on UI thread. runOnUiThread { swapCursor(mc) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_search) root = findViewById(R.id.root) lsSearchResults = findViewById(R.id.lsSearchResults) lsSearchResults.adapter = adapter FastScrollerBuilder(lsSearchResults).build() tSearchTips = findViewById(R.id.tSearchTips) panelFilter = findViewById(R.id.panelFilter) cFilterOlds = findViewById(R.id.cFilterOlds) cFilterNews = findViewById(R.id.cFilterNews) cFilterSingleBook = findViewById(R.id.cFilterSingleBook) tFilterAdvanced = findViewById(R.id.tFilterAdvanced) bEditFilter = findViewById(R.id.bEditFilter) setSupportActionBar(findViewById(R.id.toolbar)) supportActionBar?.setDisplayHomeAsUpEnabled(true) bVersion = findViewById(R.id.bVersion) bVersion.setOnClickListener(bVersion_click) searchView = findViewById<SearchView>(R.id.searchView).apply { findAutoCompleteTextView()?.threshold = 0 suggestionsAdapter = SearchHistoryAdapter().also { searchHistoryAdapter = it } setOnSuggestionListener(object : SearchView.OnSuggestionListener { override fun onSuggestionSelect(position: Int): Boolean { return false } override fun onSuggestionClick(position: Int): Boolean { val c = searchHistoryAdapter.cursor ?: return false val ok = c.moveToPosition(position) if (!ok) return false val _id = c.getLong(COLINDEX_ID) if (_id == ID_CLEAR_HISTORY) { saveSearchHistory(null) searchHistoryAdapter.setData(loadSearchHistory()) } else { searchView.setQuery(c.getString(COLINDEX_QUERY_STRING), true) } return true } }) setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { search(query) return true } override fun onQueryTextChange(newText: String): Boolean { suggester.submit(newText) return true } }) // stop opening suggestion dropdown post { searchView.findAutoCompleteTextView()?.dismissDropDown() } } progressbar = findViewById(R.id.progressbar) bSearch = findViewById(R.id.bSearch) bSearch.setOnClickListener { search(searchView.query.toString()) } run { val sb = SpannableStringBuilder(tSearchTips.text) while (true) { val pos = TextUtils.indexOf(sb, "[q]") if (pos < 0) break sb.replace(pos, pos + 3, "\"") } tSearchTips.text = sb } val applied = S.applied() tSearchTips.setBackgroundColor(applied.backgroundColor) lsSearchResults.setBackgroundColor(applied.backgroundColor) Appearances.applyTextAppearance(tSearchTips, textSizeMult) hiliteColor = TextColorUtil.getSearchKeywordByBrightness(applied.backgroundBrightness) bEditFilter.setOnClickListener { bEditFilter_click() } cFilterOlds.setOnCheckedChangeListener(cFilterOlds_checkedChange) cFilterNews.setOnCheckedChangeListener(cFilterNews_checkedChange) cFilterSingleBook.setOnCheckedChangeListener(cFilterSingleBook_checkedChange) run { openedBookId = intent.getIntExtra(EXTRA_openedBookId, -1) val book = S.activeVersion().getBook(openedBookId) if (book == null) { // active version has changed somehow when this activity fainted. so, invalidate openedBookId openedBookId = -1 cFilterSingleBook.isEnabled = false } else { cFilterSingleBook.text = getString(R.string.search_bookname_only, book.shortName) } } for (book in searchInVersion.consecutiveBooks) { selectedBookIds.put(book.bookId, true) } configureFilterDisplayOldNewTest() if (usingRevIndex()) { SearchEngine.preloadRevIndex() } displaySearchInVersion() } private fun ViewGroup.findAutoCompleteTextView(): AutoCompleteTextView? { for (i in 0 until childCount) { val child = getChildAt(i) if (child is AutoCompleteTextView) { return child } else if (child is ViewGroup) { val res = child.findAutoCompleteTextView() if (res != null) { return res } } } return null } override fun onStart() { super.onStart() searchHistoryAdapter.setData(loadSearchHistory()) } private fun displaySearchInVersion() { val versionInitials = searchInVersion.initials bVersion.text = versionInitials searchView.queryHint = getString(R.string.search_in_version_short_name_placeholder, versionInitials) @Suppress("NotifyDataSetChanged") adapter.notifyDataSetChanged() } private fun configureFilterDisplayOldNewTest() { // the following variables will have value: // if some are off and some are on -> null. // if all on -> true. // if all off -> false. val olds = run { var c_on = 0 var c_off = 0 for (i in 0..38) { val on = selectedBookIds[i, false] if (on) c_on++ else c_off++ } when { c_on == 39 -> true c_off == 39 -> false else -> null } } val news = run { var c_on = 0 var c_off = 0 for (i in 39..65) { val nyala = selectedBookIds[i, false] if (nyala) c_on++ else c_off++ } when { c_on == 27 -> true c_off == 27 -> false else -> null } } val oneOfThemOn = run { var c = 0 var k = 0 for (i in 0 until selectedBookIds.size()) { if (selectedBookIds.valueAt(i)) { k = selectedBookIds.keyAt(i) c++ if (c > 1) break } } when (c) { 1 -> k else -> -1 } } filterUserAction++ when { olds != null && news != null -> { // both are either true or false cFilterOlds.isChecked = olds cFilterNews.isChecked = news cFilterSingleBook.visibility = View.VISIBLE cFilterSingleBook.isChecked = false tFilterAdvanced.visibility = View.GONE } oneOfThemOn != -1 && oneOfThemOn == openedBookId -> { cFilterOlds.isChecked = false cFilterNews.isChecked = false cFilterSingleBook.visibility = View.VISIBLE cFilterSingleBook.isChecked = true tFilterAdvanced.visibility = View.GONE } else -> { cFilterOlds.isChecked = false cFilterNews.isChecked = false cFilterSingleBook.visibility = View.GONE tFilterAdvanced.visibility = View.VISIBLE var cnt = 0 var bookId = 0 for (i in 0 until selectedBookIds.size()) { if (selectedBookIds.valueAt(i)) { cnt++ bookId = selectedBookIds.keyAt(i) } } if (cnt != 1) { tFilterAdvanced.text = getString(R.string.search_filter_multiple_books_selected, cnt.toString()) } else { tFilterAdvanced.text = searchInVersion.reference(bookId, 0, 0) } } } filterUserAction-- val singleBookReference = searchInVersion.reference(openedBookId, 0, 0) cFilterSingleBook.text = getString(R.string.search_bookname_only, singleBookReference) } private val cFilterOlds_checkedChange = CompoundButton.OnCheckedChangeListener { _, isChecked -> if (filterUserAction != 0) return@OnCheckedChangeListener filterUserAction++ if (isChecked) { cFilterSingleBook.visibility = View.VISIBLE cFilterSingleBook.isChecked = false tFilterAdvanced.visibility = View.GONE } setSelectedBookIdsBasedOnFilter() search(searchView.query.toString()) filterUserAction-- } private val cFilterNews_checkedChange = CompoundButton.OnCheckedChangeListener { _, isChecked -> if (filterUserAction != 0) return@OnCheckedChangeListener filterUserAction++ if (isChecked) { cFilterSingleBook.visibility = View.VISIBLE cFilterSingleBook.isChecked = false tFilterAdvanced.visibility = View.GONE } setSelectedBookIdsBasedOnFilter() search(searchView.query.toString()) filterUserAction-- } private val cFilterSingleBook_checkedChange = CompoundButton.OnCheckedChangeListener { _, isChecked -> if (filterUserAction != 0) return@OnCheckedChangeListener filterUserAction++ if (isChecked) { cFilterOlds.isChecked = false cFilterNews.isChecked = false } setSelectedBookIdsBasedOnFilter() search(searchView.query.toString()) filterUserAction-- } private val bVersion_click = View.OnClickListener { S.openVersionsDialog(this, false, searchInVersionId) { mv: MVersion -> val selectedVersion = mv.version if (selectedVersion == null) { MaterialDialog.Builder(this@SearchActivity) .content(getString(R.string.version_error_opening, mv.longName)) .positiveText(R.string.ok) .show() return@openVersionsDialog } searchInVersion = selectedVersion searchInVersionId = mv.versionId textSizeMult = S.getDb().getPerVersionSettings(searchInVersionId).fontSizeMultiplier Appearances.applyTextAppearance(tSearchTips, textSizeMult) displaySearchInVersion() configureFilterDisplayOldNewTest() bVersion.text = selectedVersion.initials @Suppress("NotifyDataSetChanged") adapter.notifyDataSetChanged() } } private fun setSelectedBookIdsBasedOnFilter() { selectedBookIds.clear() if (cFilterOlds.isChecked) for (i in 0..38) selectedBookIds.put(i, true) if (cFilterNews.isChecked) for (i in 39..65) selectedBookIds.put(i, true) if (openedBookId != -1) { if (cFilterSingleBook.isChecked) selectedBookIds.put(openedBookId, true) } } private fun bEditFilter_click() { @Suppress("deprecation") startActivityForResult(SearchBookFilterActivity.createIntent(selectedBookIds, searchInVersion.consecutiveBooks), REQCODE_bookFilter) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQCODE_bookFilter && resultCode == RESULT_OK) { val result = SearchBookFilterActivity.obtainResult(data) if (result != null) { selectedBookIds = result.selectedBookIds configureFilterDisplayOldNewTest() search(searchView.query.toString()) } return } @Suppress("deprecation") super.onActivityResult(requestCode, resultCode, data) } @JvmInline value class SearchRequest(val query: SearchEngine.Query) data class SearchResult(val query: SearchEngine.Query, val result: IntArrayList) /** * So we can delay a bit before updating suggestions. */ private val suggester = object : Debouncer<String, String>(200) { override fun process(payload: String): String { return payload } override fun onResult(result: String) { searchHistoryAdapter.setQuery(result) } } private val searcher = object : Debouncer<SearchRequest, SearchResult>(0) { override fun process(request: SearchRequest): SearchResult { val query = request.query val totalMs = System.currentTimeMillis() val cpuMs = SystemClock.currentThreadTimeMillis() val debugstats_revIndexUsed: Boolean val result = if (usingRevIndex()) { debugstats_revIndexUsed = true SearchEngine.searchByRevIndex(searchInVersion, query) } else { debugstats_revIndexUsed = false SearchEngine.searchByGrep(searchInVersion, query) } val debugstats_totalTimeMs = System.currentTimeMillis() - totalMs val debugstats_cpuTimeMs = SystemClock.currentThreadTimeMillis() - cpuMs AppLog.d( TAG, "Search results: ${result.size()}\n" + "Method: ${if (debugstats_revIndexUsed) "revindex" else "grep"}\n" + "Total time: $debugstats_totalTimeMs ms\n" + "CPU (thread) time: $debugstats_cpuTimeMs ms" ) return SearchResult(query, result) } override fun onResult(searchResult: SearchResult) { val (query, result) = searchResult progressbar.isVisible = false bSearch.isVisible = true actionMode?.finish() val tokens = QueryTokenizer.tokenize(query.query_string).toList() adapter.uncheckAll() adapter.setData(result, tokens) tSearchTips.isVisible = result.size() == 0 lsSearchResults.isVisible = result.size() > 0 if (result.size() > 0) { Snackbar.make(lsSearchResults, getString(R.string.size_hasil, result.size()), Snackbar.LENGTH_LONG).show() //# close soft keyboard val inputManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager inputManager.hideSoftInputFromWindow(searchView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) searchView.clearFocus() lsSearchResults.requestFocus() } else { /** * @return ari not 0 if fallback is to be shown */ fun shouldShowFallback(jumper: Jumper): Int { if (!jumper.parseSucceeded) return 0 val chapter_1 = jumper.chapter if (chapter_1 == 0) return 0 val version = searchInVersion val bookId = jumper.getBookId(version.consecutiveBooks) if (bookId == -1) return 0 val book = version.getBook(bookId) ?: return 0 if (chapter_1 > book.chapter_count) return 0 val verse_1 = jumper.verse return if (verse_1 != 0 && verse_1 > book.verse_counts[chapter_1 - 1]) { 0 } else { Ari.encode(bookId, chapter_1, verse_1) } } val zeroResultMessage = TextUtils.expandTemplate(getText(R.string.search_no_result), query.query_string) val fallbackAri = shouldShowFallback(Jumper(query.query_string)) if (fallbackAri != 0) { tSearchTips.text = buildString { append(zeroResultMessage) append("\n\n") append(TextUtils.expandTemplate(getText(R.string.search_no_result_fallback), searchInVersion.reference(fallbackAri))) } tSearchTips.setOnClickListener { if (Ari.toVerse(fallbackAri) == 0) { startActivity(Launcher.openAppAtBibleLocation(fallbackAri)) } else { startActivity(Launcher.openAppAtBibleLocationWithVerseSelected(fallbackAri)) } } } else { // If there is no books chosen, display a different message if (selectedBookIds.indexOfValue(true) < 0) { tSearchTips.setText(R.string.pilih_setidaknya_satu_kitab) } else { tSearchTips.text = zeroResultMessage } tSearchTips.isClickable = false tSearchTips.setOnClickListener(null) } } } } private fun search(query_string: String) { if (query_string.isBlank()) return val query = SearchEngine.Query() query.query_string = query_string query.bookIds = selectedBookIds progressbar.isVisible = true bSearch.isVisible = false searchHistoryAdapter.setData(addSearchHistoryEntry(query.query_string)) searchView.findAutoCompleteTextView()?.dismissDropDown() searcher.submit(SearchRequest(query)) } fun loadSearchHistory(): SearchHistory { val json = Preferences.getString(Prefkey.searchHistory, null) ?: return SearchHistory(mutableListOf()) return App.getDefaultGson().fromJson(json, SearchHistory::class.java) } fun saveSearchHistory(sh: SearchHistory?) { if (sh == null) { Preferences.remove(Prefkey.searchHistory) } else { val json = App.getDefaultGson().toJson(sh) Preferences.setString(Prefkey.searchHistory, json) } } // returns the modified SearchHistory private fun addSearchHistoryEntry(query_string: String): SearchHistory { val sh = loadSearchHistory() // look for this query_string and remove for (i in sh.entries.indices.reversed()) { if (query_string == sh.entries[i].query_string) { sh.entries.removeAt(i) } } sh.entries.add(0, SearchHistory.Entry(query_string)) // if more than MAX, remove last while (sh.entries.size > 20) { sh.entries.removeAt(sh.entries.size - 1) } saveSearchHistory(sh) return sh } private fun usingRevIndex(): Boolean { return searchInVersionId == MVersionInternal.getVersionInternalId() } class ResultHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val lReference: TextView = itemView.findViewById(R.id.lReference) val lSnippet: TextView = itemView.findViewById(R.id.lSnippet) } inner class SearchAdapter(val searchResults: IntArrayList, tokens: List<String>) : RecyclerView.Adapter<ResultHolder>() { init { setHasStableIds(true) } var rt = SearchEngine.ReadyTokens(tokens.toTypedArray()) val checkedPositions = mutableSetOf<Int>() override fun getItemCount(): Int { return searchResults.size() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ResultHolder { return ResultHolder(layoutInflater.inflate(R.layout.item_search_result, parent, false)) } override fun onBindViewHolder(holder: ResultHolder, bindPosition: Int) { val checked = bindPosition in checkedPositions val checkedBgColor: Int val checkedTextColor: Int if (checked) { val colorRgb = Preferences.getInt(R.string.pref_selectedVerseBgColor_key, R.integer.pref_selectedVerseBgColor_default) checkedBgColor = ColorUtils.setAlphaComponent(colorRgb, 0xa0) checkedTextColor = TextColorUtil.getForCheckedVerse(checkedBgColor) } else { // no need to calculate checkedBgColor = 0 checkedTextColor = 0 } val ari = searchResults[bindPosition] val sb = SpannableStringBuilder(searchInVersion.reference(ari)) Appearances.applySearchResultReferenceAppearance(holder.lReference, sb, textSizeMult) if (checked) { holder.lReference.setTextColor(checkedTextColor) } Appearances.applyTextAppearance(holder.lSnippet, textSizeMult) if (checked) { holder.lSnippet.setTextColor(checkedTextColor) } val verseText = FormattedVerseText.removeSpecialCodes(searchInVersion.loadVerseText(ari)) if (verseText != null) { holder.lSnippet.text = SearchEngine.hilite(verseText, rt, if (checked) checkedTextColor else hiliteColor) } else { holder.lSnippet.setText(R.string.generic_verse_not_available_in_this_version) } if (checked) { holder.itemView.setBackgroundColor(checkedBgColor) } else { holder.itemView.setBackgroundColor(0x0) } holder.itemView.setOnLongClickListener { if (actionMode == null) { actionMode = startSupportActionMode(createActionModeCallback()) } val position = holder.bindingAdapterPosition if (position in adapter.checkedPositions) { adapter.checkedPositions -= position } else { adapter.checkedPositions += position } onCheckedVerseChanged() true } holder.itemView.setOnClickListener { val position = holder.bindingAdapterPosition if (actionMode != null) { if (position in adapter.checkedPositions) { adapter.checkedPositions -= position } else { adapter.checkedPositions += position } onCheckedVerseChanged() } else { startActivity(Launcher.openAppAtBibleLocationWithVerseSelected(searchResults[position])) uncheckAll() } } } override fun getItemId(position: Int): Long { return searchResults[position].toLong() } fun checkAll() { val size = adapter.itemCount for (i in 0 until size) { checkedPositions += i } onCheckedVerseChanged() } fun uncheckAll() { checkedPositions.clear() onCheckedVerseChanged() } fun setData(searchResults: IntArrayList, tokens: List<String>) { this.searchResults.clear() for (i in 0 until searchResults.size()) { this.searchResults.add(searchResults[i]) } this.rt = SearchEngine.ReadyTokens(tokens.toTypedArray()) uncheckAll() } } companion object { fun createIntent(openedBookId: Int): Intent { return Intent(App.context, SearchActivity::class.java) .putExtra(EXTRA_openedBookId, openedBookId) } } }
apache-2.0
8ef2c9e7ca1261ec78bb562f4475cea2
37.84223
160
0.597484
5.021316
false
false
false
false
soywiz/korge
korge-spine/src/commonMain/kotlin/com/esotericsoftware/spine/attachments/AtlasAttachmentLoader.kt
1
3597
/****************************************************************************** * Spine Runtimes License Agreement * Last updated January 1, 2020. Replaces all prior versions. * * Copyright (c) 2013-2020, Esoteric Software LLC * * Integration of the Spine Runtimes into software or otherwise creating * derivative works of the Spine Runtimes is permitted under the terms and * conditions of Section 2 of the Spine Editor License Agreement: * http://esotericsoftware.com/spine-editor-license * * Otherwise, it is permitted to integrate the Spine Runtimes into software * or otherwise create derivative works of the Spine Runtimes (collectively, * "Products"), provided that each user of the Products must obtain their own * Spine Editor license and redistribution of the Products in any form must * include this license and copyright notice. * * THE SPINE RUNTIMES ARE PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, * BUSINESS INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 * THE SPINE RUNTIMES, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.esotericsoftware.spine.attachments import com.esotericsoftware.spine.* import com.soywiz.korim.atlas.* /** An [AttachmentLoader] that configures attachments using texture regions from an [Atlas]. * * * See [Loading skeleton data](http://esotericsoftware.com/spine-loading-skeleton-data#JSON-and-binary-data) in the * Spine Runtimes Guide. */ class AtlasAttachmentLoader(private val atlas: Atlas) : AttachmentLoader { private val regions = HashMap<String, SpineRegion>() private fun findRegion(path: String): SpineRegion? { return regions.getOrPut(path) { val entry = atlas.tryGetEntryByName(path) ?: error("Can't find '$path' in atlas") SpineRegion(entry) } } override fun newRegionAttachment(skin: Skin, name: String, path: String): RegionAttachment? { val region = findRegion(path) ?: throw RuntimeException("Region not found in atlas: $path (region attachment: $name)") val attachment = RegionAttachment(name) attachment.region = region return attachment } override fun newMeshAttachment(skin: Skin, name: String, path: String): MeshAttachment? { val region = findRegion(path) ?: throw RuntimeException("Region not found in atlas: $path (mesh attachment: $name)") val attachment = MeshAttachment(name) attachment.region = region return attachment } override fun newBoundingBoxAttachment(skin: Skin, name: String): BoundingBoxAttachment? { return BoundingBoxAttachment(name) } override fun newClippingAttachment(skin: Skin, name: String): ClippingAttachment? { return ClippingAttachment(name) } override fun newPathAttachment(skin: Skin, name: String): PathAttachment? { return PathAttachment(name) } override fun newPointAttachment(skin: Skin, name: String): PointAttachment? { return PointAttachment(name) } }
apache-2.0
9f335d9e30f250c19eef110036f3a98c
43.407407
115
0.710036
4.671429
false
false
false
false
Andr3Carvalh0/mGBA
app/src/main/java/io/mgba/ui/views/GameInformationView.kt
1
3028
package io.mgba.ui.views import android.content.Intent import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import com.google.android.material.bottomsheet.BottomSheetDialogFragment import io.mgba.R import io.mgba.data.local.model.Game import io.mgba.emulation.EmulationActivity import io.mgba.utilities.io.GlideUtils import io.mgba.utilities.io.GlideUtils.Colors import kotlinx.android.synthetic.main.game_information_view.* import java.lang.RuntimeException class GameInformationView : BottomSheetDialogFragment(), View.OnClickListener { private lateinit var game: Game override fun getTheme(): Int { return R.style.BottomSheetDialogTheme } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.game_information_view, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if(arguments == null) throw RuntimeException("The bottomsheet could retrive the game_item!") arguments?.let { //this.game = it.getParcelable(ARG_PLAY_GAME)!! prepareView() } } private fun prepareView() { game_title_bs.text = game.name game_desc_bs.text = game.description if (game_cover_bs != null && game.cover != null) { GlideUtils.init(this, game.cover!!) .setPlaceholders(R.drawable.placeholder, R.drawable.error) .colorView(Colors.VIBRANT, Colors.DARK_MUTED, listOf(game_play_bs, game_savetitle_bs)) .colorView(Colors.LIGHT_MUTED, Colors.LIGHT_VIBRANT, listOf(game_text_content_bs, game_image_content_bs)) .colorViewWithCustomBackground(Colors.LIGHT_MUTED, Colors.LIGHT_VIBRANT, listOf(game_header_bs)) .colorView(Colors.LIGHT_VIBRANT, true, listOf(game_title_bs)) .colorView(Colors.LIGHT_VIBRANT, false, listOf(game_desc_bs)) .build(game_cover_bs) } else { //set header color back to normal val background = game_header_bs.background if (background is GradientDrawable) { background.setColor(ContextCompat.getColor(context!!, R.color.colorPrimary)) } } } override fun onClick(v: View) { val it = Intent(context, EmulationActivity::class.java) //it.putExtra(ARG_PLAY_GAME, game) requireContext().startActivity(it) } companion object { fun show(game: Game): GameInformationView { val args = Bundle() //args.putParcelable(Constants.ARG_PLAY_GAME, game) val frag = GameInformationView() frag.arguments = args return frag } } }
mpl-2.0
3d242e40132df9e2f1234c394496ddb4
35.047619
125
0.666116
4.288952
false
false
false
false
vondear/RxTools
RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityRxCaptcha.kt
1
3661
package com.tamsiree.rxdemo.activity import android.graphics.drawable.Drawable import android.os.Bundle import android.widget.SeekBar import android.widget.SeekBar.OnSeekBarChangeListener import android.widget.Toast import com.bumptech.glide.Glide import com.bumptech.glide.request.target.SimpleTarget import com.bumptech.glide.request.transition.Transition import com.tamsiree.rxdemo.R import com.tamsiree.rxkit.RxDeviceTool.setPortrait import com.tamsiree.rxkit.TLog import com.tamsiree.rxkit.view.RxToast import com.tamsiree.rxui.activity.ActivityBase import com.tamsiree.rxui.view.RxCaptcha import com.tamsiree.rxui.view.swipecaptcha.RxSwipeCaptcha import com.tamsiree.rxui.view.swipecaptcha.RxSwipeCaptcha.OnCaptchaMatchCallback import kotlinx.android.synthetic.main.activity_rx_captcha.* /** * @author tamsiree */ class ActivityRxCaptcha : ActivityBase() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_rx_captcha) setPortrait(this) initView() } override fun initView() { rx_title.setLeftFinish(mContext) swipeCaptchaView.onCaptchaMatchCallback = object : OnCaptchaMatchCallback { override fun matchSuccess(rxSwipeCaptcha: RxSwipeCaptcha) { RxToast.success(mContext, "验证通过!", Toast.LENGTH_SHORT)?.show() //swipeCaptcha.createCaptcha(); dragBar.isEnabled = false } override fun matchFailed(rxSwipeCaptcha: RxSwipeCaptcha) { TLog.d("zxt", "matchFailed() called with: rxSwipeCaptcha = [$rxSwipeCaptcha]") RxToast.error(mContext, "验证失败:拖动滑块将悬浮头像正确拼合", Toast.LENGTH_SHORT)?.show() rxSwipeCaptcha.resetCaptcha() dragBar.progress = 0 } } dragBar.setOnSeekBarChangeListener(object : OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { swipeCaptchaView.setCurrentSwipeValue(progress) } override fun onStartTrackingTouch(seekBar: SeekBar) { //随便放这里是因为控件 dragBar.max = swipeCaptchaView.maxSwipeValue } override fun onStopTrackingTouch(seekBar: SeekBar) { TLog.d("zxt", "onStopTrackingTouch() called with: seekBar = [$seekBar]") swipeCaptchaView.matchCaptcha() } }) val simpleTarget: SimpleTarget<Drawable?> = object : SimpleTarget<Drawable?>() { override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable?>?) { swipeCaptchaView.setImageDrawable(resource) swipeCaptchaView.createCaptcha() } } //测试从网络加载图片是否ok Glide.with(this) .load(R.drawable.douyu) .into(simpleTarget) btn_get_code.setOnClickListener { RxCaptcha.build()!! .backColor(0xffffff)!! .codeLength(6)!! .fontSize(60)!! .lineNumber(0)!! .size(200, 70)!! .type(RxCaptcha.TYPE.CHARS)!! .into(iv_code) tv_code.text = RxCaptcha.build()?.getCode() } btnChange.setOnClickListener { swipeCaptchaView.createCaptcha() dragBar.isEnabled = true dragBar.progress = 0 } } override fun initData() { } }
apache-2.0
26a87897d50f41c638fc5104bdca6d3c
35.489796
101
0.632448
4.595116
false
false
false
false
openstreetview/android
app/src/main/java/com/telenav/osv/ui/fragment/camera/PreviewAreaFragment.kt
1
2620
package com.telenav.osv.ui.fragment.camera import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.telenav.osv.R import com.telenav.osv.common.model.base.KVBaseFragment import com.telenav.osv.common.toolbar.KVToolbar import com.telenav.osv.common.toolbar.ToolbarSettings import com.telenav.osv.utils.AnimationUtils /** * A simple [Fragment] subclass. * Use the [PreviewAreaFragment.newInstance] factory method to * create an instance of this fragment. */ class PreviewAreaFragment : KVBaseFragment() { /** * Flag which show in which status the current preview is. */ private var isMapPreview = true private val previewAreaOnClickListener = View.OnClickListener { _: View? -> activity?.let { if (isMapPreview) { AnimationUtils.resizeCameraUI(it, R.id.layout_activity_obd_fragment_camera_preview_container, R.id.layout_activity_obd_fragment_camera_preview_map_container) } else { AnimationUtils.resizeCameraUI(it, R.id.layout_activity_obd_fragment_camera_preview_map_container, R.id.layout_activity_obd_fragment_camera_preview_container) } isMapPreview = !isMapPreview } } private lateinit var clickPreviewArea: View override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun getToolbarSettings(kvToolbar: KVToolbar?): ToolbarSettings? { return null } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val root = inflater.inflate(R.layout.fragment_preview_area, container, false) clickPreviewArea = root.findViewById(R.id.view_fragment_preview_area_click_area) return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) clickPreviewArea.setOnClickListener(previewAreaOnClickListener) } override fun handleBackPressed(): Boolean { return false } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @return A new instance of fragment PreviewAreaFragment. */ @JvmStatic fun newInstance() = PreviewAreaFragment() const val TAG = "PreviewAreaFragment" } }
lgpl-3.0
a82b8e720038840c3ac9b58e3fbb8d02
33.473684
173
0.692366
4.572426
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/gallery/GalleryActivity.kt
1
32211
package org.wikipedia.gallery import android.app.Activity import android.app.DownloadManager import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Bitmap import android.graphics.Color import android.net.Uri import android.os.Bundle import android.util.Pair import android.view.Gravity import android.view.View import android.widget.FrameLayout import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.Constants import org.wikipedia.Constants.ImageEditType import org.wikipedia.Constants.InvokeSource import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.activity.BaseActivity import org.wikipedia.analytics.GalleryFunnel import org.wikipedia.auth.AccountUtil import org.wikipedia.bridge.JavaScriptActionHandler import org.wikipedia.commons.FilePageActivity import org.wikipedia.commons.ImageTagsProvider import org.wikipedia.databinding.ActivityGalleryBinding import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.descriptions.DescriptionEditActivity import org.wikipedia.history.HistoryEntry import org.wikipedia.page.ExclusiveBottomSheetPresenter import org.wikipedia.page.LinkMovementMethodExt import org.wikipedia.page.PageActivity import org.wikipedia.page.PageTitle import org.wikipedia.page.linkpreview.LinkPreviewDialog import org.wikipedia.richtext.RichTextUtil import org.wikipedia.suggestededits.PageSummaryForEdit import org.wikipedia.suggestededits.SuggestedEditsImageTagEditActivity import org.wikipedia.suggestededits.SuggestedEditsSnackbars import org.wikipedia.theme.Theme import org.wikipedia.util.* import org.wikipedia.util.log.L import org.wikipedia.views.PositionAwareFragmentStateAdapter import org.wikipedia.views.ViewAnimations import org.wikipedia.views.ViewUtil import java.io.File class GalleryActivity : BaseActivity(), LinkPreviewDialog.Callback, GalleryItemFragment.Callback { private lateinit var binding: ActivityGalleryBinding private lateinit var sourceWiki: WikiSite private lateinit var funnel: GalleryFunnel private lateinit var galleryAdapter: GalleryItemAdapter private var pageChangeListener = GalleryPageChangeListener() private var pageTitle: PageTitle? = null private var imageEditType: ImageEditType? = null private val disposables = CompositeDisposable() private var imageCaptionDisposable: Disposable? = null private var revision = 0L private var controlsShowing = true /** * If we have an intent that tells us a specific image to jump to within the gallery, * then this will be non-null. */ private var initialFilename: String? = null /** * If we come back from savedInstanceState, then this will be the previous pager position. */ private var initialImageIndex = -1 private var targetLanguageCode: String? = null private val app = WikipediaApp.instance private val bottomSheetPresenter = ExclusiveBottomSheetPresenter() private val downloadReceiver = MediaDownloadReceiver() private val downloadReceiverCallback = MediaDownloadReceiverCallback() private val requestAddCaptionLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == RESULT_OK) { val action = it.data?.getSerializableExtra(Constants.INTENT_EXTRA_ACTION) as DescriptionEditActivity.Action? SuggestedEditsSnackbars.show(this, action, true, targetLanguageCode, false) layOutGalleryDescription(currentItem) setResult(ACTIVITY_RESULT_IMAGE_CAPTION_ADDED) } } private val requestAddImageTagsLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == RESULT_OK) { val action = DescriptionEditActivity.Action.ADD_IMAGE_TAGS SuggestedEditsSnackbars.show(this, action, true, targetLanguageCode, true) { currentItem?.let { fragment -> fragment.imageTitle?.let { pageTitle -> startActivity(FilePageActivity.newIntent(this@GalleryActivity, pageTitle)) } } } layOutGalleryDescription(currentItem) setResult(ACTIVITY_RESULT_IMAGE_TAGS_ADDED) } } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityGalleryBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.title = "" setNavigationBarColor(Color.BLACK) binding.toolbarGradient.background = GradientUtil.getPowerGradient(R.color.black26, Gravity.TOP) binding.infoGradient.background = GradientUtil.getPowerGradient(R.color.black38, Gravity.BOTTOM) binding.descriptionText.movementMethod = linkMovementMethod binding.creditText.movementMethod = linkMovementMethod binding.errorView.setIconColorFilter(ContextCompat.getColor(this, R.color.base70)) binding.errorView.setErrorTextColor(ContextCompat.getColor(this, R.color.base70)) binding.errorView.backClickListener = View.OnClickListener { onBackPressed() } binding.errorView.retryClickListener = View.OnClickListener { binding.errorView.visibility = View.GONE loadGalleryContent() } if (intent.hasExtra(EXTRA_PAGETITLE)) { pageTitle = intent.getParcelableExtra(EXTRA_PAGETITLE) } initialFilename = intent.getStringExtra(EXTRA_FILENAME) revision = intent.getLongExtra(EXTRA_REVISION, 0) sourceWiki = intent.getParcelableExtra(EXTRA_WIKI)!! galleryAdapter = GalleryItemAdapter(this@GalleryActivity) binding.pager.adapter = galleryAdapter binding.pager.registerOnPageChangeCallback(pageChangeListener) binding.pager.offscreenPageLimit = 2 funnel = GalleryFunnel(app, intent.getParcelableExtra(EXTRA_WIKI), intent.getIntExtra(EXTRA_SOURCE, 0)) if (savedInstanceState == null) { initialFilename?.let { funnel.logGalleryOpen(pageTitle, it) } } else { controlsShowing = savedInstanceState.getBoolean(KEY_CONTROLS_SHOWING) initialImageIndex = savedInstanceState.getInt(KEY_PAGER_INDEX) // if we have a savedInstanceState, then the initial index overrides // the initial Title from our intent. initialFilename = null val fm = supportFragmentManager if (supportFragmentManager.backStackEntryCount > 0) { val ft = supportFragmentManager.beginTransaction() for (i in 0 until fm.backStackEntryCount) { val fragment = fm.findFragmentById(fm.getBackStackEntryAt(i).id) if (fragment is GalleryItemFragment) { ft.remove(fragment) } } ft.commitAllowingStateLoss() } } binding.toolbarContainer.post { if (isDestroyed) { return@post } setControlsShowing(controlsShowing) } if (TRANSITION_INFO != null && TRANSITION_INFO!!.width > 0 && TRANSITION_INFO!!.height > 0) { val aspect = TRANSITION_INFO!!.height / TRANSITION_INFO!!.width val params = if (DimenUtil.displayWidthPx < DimenUtil.displayHeightPx) FrameLayout.LayoutParams(DimenUtil.displayWidthPx, (DimenUtil.displayWidthPx * aspect).toInt()) else FrameLayout.LayoutParams((DimenUtil.displayHeightPx / aspect).toInt(), DimenUtil.displayHeightPx) params.gravity = Gravity.CENTER binding.transitionReceiver.layoutParams = params binding.transitionReceiver.visibility = View.VISIBLE ViewUtil.loadImage(binding.transitionReceiver, TRANSITION_INFO!!.src, TRANSITION_INFO!!.centerCrop, largeRoundedSize = false, force = false, listener = null) val transitionMillis = 500 binding.transitionReceiver.postDelayed({ if (isDestroyed) { return@postDelayed } loadGalleryContent() }, transitionMillis.toLong()) } else { TRANSITION_INFO = null binding.transitionReceiver.visibility = View.GONE loadGalleryContent() } binding.captionEditButton.setOnClickListener { onEditClick(it) } binding.ctaButton.setOnClickListener { onTranslateClick() } binding.licenseContainer.setOnClickListener { onLicenseClick() } binding.licenseContainer.setOnLongClickListener { onLicenseLongClick() } } public override fun onDestroy() { disposables.clear() disposeImageCaptionDisposable() binding.pager.unregisterOnPageChangeCallback(pageChangeListener) TRANSITION_INFO = null super.onDestroy() } public override fun onResume() { super.onResume() registerReceiver(downloadReceiver, IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) downloadReceiver.callback = downloadReceiverCallback } public override fun onPause() { super.onPause() downloadReceiver.callback = null unregisterReceiver(downloadReceiver) } override fun onDownload(item: GalleryItemFragment) { item.imageTitle?.let { funnel.logGallerySave(pageTitle, it.displayText) } if (item.imageTitle != null && item.mediaInfo != null) { downloadReceiver.download(this, item.imageTitle!!, item.mediaInfo!!) FeedbackUtil.showMessage(this, R.string.gallery_save_progress) } else { FeedbackUtil.showMessage(this, R.string.err_cannot_save_file) } } override fun onShare(item: GalleryItemFragment, bitmap: Bitmap?, subject: String, title: PageTitle) { item.imageTitle?.let { funnel.logGalleryShare(pageTitle, it.displayText) } if (bitmap != null && item.mediaInfo != null) { ShareUtil.shareImage(this, bitmap, File(ImageUrlUtil.getUrlForPreferredSize(item.mediaInfo!!.thumbUrl, Constants.PREFERRED_GALLERY_IMAGE_SIZE)).name, subject, title.uri) } else { ShareUtil.shareText(this, title) } } override fun setTheme() { setTheme(Theme.DARK.resourceId) } private fun onEditClick(v: View) { val item = currentItem if (item?.imageTitle == null || item.mediaInfo?.metadata == null) { return } val isProtected = v.tag != null && v.tag as Boolean if (isProtected) { AlertDialog.Builder(this) .setCancelable(false) .setTitle(R.string.page_protected_can_not_edit_title) .setMessage(R.string.page_protected_can_not_edit) .setPositiveButton(R.string.protected_page_warning_dialog_ok_button_text, null) .show() return } startCaptionEdit(item) } private fun startCaptionEdit(item: GalleryItemFragment) { val title = PageTitle(item.imageTitle!!.prefixedText, WikiSite(Service.COMMONS_URL, sourceWiki.languageCode)) val currentCaption = item.mediaInfo!!.captions[sourceWiki.languageCode] title.description = currentCaption val summary = PageSummaryForEdit(title.prefixedText, sourceWiki.languageCode, title, title.displayText, RichTextUtil.stripHtml(item.mediaInfo!!.metadata!!.imageDescription()), item.mediaInfo!!.thumbUrl) requestAddCaptionLauncher.launch(DescriptionEditActivity.newIntent(this, title, null, summary, null, DescriptionEditActivity.Action.ADD_CAPTION, InvokeSource.GALLERY_ACTIVITY)) } private fun onTranslateClick() { val item = currentItem if (item?.imageTitle == null || item.mediaInfo?.metadata == null || imageEditType == null) { return } when (imageEditType) { ImageEditType.ADD_TAGS -> startTagsEdit(item) ImageEditType.ADD_CAPTION_TRANSLATION -> startCaptionTranslation(item) else -> startCaptionEdit(item) } } private fun startTagsEdit(item: GalleryItemFragment) { requestAddImageTagsLauncher.launch(SuggestedEditsImageTagEditActivity.newIntent(this, item.mediaPage!!, InvokeSource.GALLERY_ACTIVITY)) } private fun startCaptionTranslation(item: GalleryItemFragment) { val sourceTitle = PageTitle(item.imageTitle!!.prefixedText, WikiSite(Service.COMMONS_URL, sourceWiki.languageCode)) val targetTitle = PageTitle(item.imageTitle!!.prefixedText, WikiSite(Service.COMMONS_URL, targetLanguageCode ?: app.languageState.appLanguageCodes[1])) val currentCaption = item.mediaInfo!!.captions[sourceWiki.languageCode].orEmpty().ifEmpty { RichTextUtil.stripHtml(item.mediaInfo!!.metadata!!.imageDescription()) } val sourceSummary = PageSummaryForEdit(sourceTitle.prefixedText, sourceTitle.wikiSite.languageCode, sourceTitle, sourceTitle.displayText, currentCaption, item.mediaInfo!!.thumbUrl) val targetSummary = PageSummaryForEdit(targetTitle.prefixedText, targetTitle.wikiSite.languageCode, targetTitle, targetTitle.displayText, null, item.mediaInfo!!.thumbUrl) requestAddCaptionLauncher.launch(DescriptionEditActivity.newIntent(this, targetTitle, null, sourceSummary, targetSummary, if (sourceSummary.lang == targetSummary.lang) DescriptionEditActivity.Action.ADD_CAPTION else DescriptionEditActivity.Action.TRANSLATE_CAPTION, InvokeSource.GALLERY_ACTIVITY)) } private fun onLicenseClick() { if (binding.licenseIcon.contentDescription == null) { return } FeedbackUtil.showMessageAsPlainText((binding.licenseIcon.context as Activity), binding.licenseIcon.contentDescription) } private fun onLicenseLongClick(): Boolean { val licenseUrl = binding.licenseIcon.tag as String if (licenseUrl.isNotEmpty()) { UriUtil.handleExternalLink(this@GalleryActivity, Uri.parse(UriUtil.resolveProtocolRelativeUrl(licenseUrl))) } return true } private fun disposeImageCaptionDisposable() { if (imageCaptionDisposable != null && !imageCaptionDisposable!!.isDisposed) { imageCaptionDisposable!!.dispose() } } private inner class GalleryPageChangeListener : OnPageChangeCallback() { private var currentPosition = -1 override fun onPageSelected(position: Int) { // the pager has settled on a new position currentItem?.let { item -> layOutGalleryDescription(item) item.imageTitle?.let { if (currentPosition != -1) { if (position < currentPosition) { funnel.logGallerySwipeLeft(pageTitle, it.displayText) } else if (position > currentPosition) { funnel.logGallerySwipeRight(pageTitle, it.displayText) } } } } currentPosition = position } override fun onPageScrollStateChanged(state: Int) { hideTransitionReceiver(false) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putBoolean(KEY_CONTROLS_SHOWING, controlsShowing) outState.putInt(KEY_PAGER_INDEX, binding.pager.currentItem) } private fun updateProgressBar(visible: Boolean) { binding.progressBar.isIndeterminate = true binding.progressBar.visibility = if (visible) View.VISIBLE else View.GONE } override fun onBackPressed() { // log the "gallery close" event only upon explicit closing of the activity // (back button, or home-as-up button in the toolbar) currentItem?.imageTitle?.let { funnel.logGalleryClose(pageTitle, it.displayText) } if (TRANSITION_INFO != null) { showTransitionReceiver() } super.onBackPressed() } fun onMediaLoaded() { hideTransitionReceiver(true) } private fun showTransitionReceiver() { binding.transitionReceiver.visibility = View.VISIBLE } private fun hideTransitionReceiver(delay: Boolean) { if (binding.transitionReceiver.visibility == View.GONE) { return } if (delay) { val hideDelayMillis = 250L binding.transitionReceiver.postDelayed({ if (isDestroyed) { return@postDelayed } binding.transitionReceiver.visibility = View.GONE }, hideDelayMillis) } else { binding.transitionReceiver.visibility = View.GONE } } private fun setControlsShowing(showing: Boolean) { controlsShowing = showing if (controlsShowing) { ViewAnimations.ensureTranslationY(binding.toolbarContainer, 0) ViewAnimations.ensureTranslationY(binding.infoContainer, 0) } else { ViewAnimations.ensureTranslationY(binding.toolbarContainer, -binding.toolbarContainer.height) ViewAnimations.ensureTranslationY(binding.infoContainer, binding.infoContainer.height) } binding.descriptionText.setTextIsSelectable(controlsShowing) } fun toggleControls() { setControlsShowing(!controlsShowing) } private fun showLinkPreview(title: PageTitle) { bottomSheetPresenter.show(supportFragmentManager, LinkPreviewDialog.newInstance(HistoryEntry(title, HistoryEntry.SOURCE_GALLERY), null)) } fun setViewPagerEnabled(enabled: Boolean) { binding.pager.isUserInputEnabled = enabled } private val linkMovementMethod = LinkMovementMethodExt { urlStr -> L.v("Link clicked was $urlStr") var url = UriUtil.resolveProtocolRelativeUrl(urlStr) if (url.startsWith("/wiki/")) { val title = PageTitle.titleForInternalLink(url, app.wikiSite) showLinkPreview(title) } else { val uri = Uri.parse(url) val authority = uri.authority if (authority != null && WikiSite.supportedAuthority(authority) && uri.path != null && uri.path!!.startsWith("/wiki/")) { val title = PageTitle.titleForUri(uri, WikiSite(uri)) showLinkPreview(title) } else { // if it's a /w/ URI, turn it into a full URI and go external if (url.startsWith("/w/")) { url = String.format("%1\$s://%2\$s", app.wikiSite.scheme(), app.wikiSite.authority()) + url } UriUtil.handleExternalLink(this@GalleryActivity, Uri.parse(url)) } } } private fun finishWithPageResult(resultTitle: PageTitle, historyEntry: HistoryEntry = HistoryEntry(resultTitle, HistoryEntry.SOURCE_GALLERY)) { val intent = PageActivity.newIntentForCurrentTab(this@GalleryActivity, historyEntry, resultTitle, false) setResult(ACTIVITY_RESULT_PAGE_SELECTED, intent) finish() } override fun onLinkPreviewLoadPage(title: PageTitle, entry: HistoryEntry, inNewTab: Boolean) { finishWithPageResult(title, entry) } override fun onLinkPreviewCopyLink(title: PageTitle) { ClipboardUtil.setPlainText(this, text = title.uri) FeedbackUtil.showMessage(this, R.string.address_copied) } override fun onLinkPreviewAddToList(title: PageTitle) { bottomSheetPresenter.showAddToListDialog(supportFragmentManager, title, InvokeSource.LINK_PREVIEW_MENU) } override fun onLinkPreviewShareLink(title: PageTitle) { ShareUtil.shareText(this, title) } fun showError(caught: Throwable?) { binding.errorView.setError(caught) binding.errorView.visibility = View.VISIBLE } private fun fetchGalleryItems() { pageTitle?.let { updateProgressBar(true) disposables.add(ServiceFactory.getRest(it.wikiSite) .getMediaList(it.prefixedText, revision) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ mediaList -> applyGalleryList(mediaList.getItems("image", "video")) }) { caught -> updateProgressBar(false) showError(caught) }) } } private fun loadGalleryContent() { updateProgressBar(false) fetchGalleryItems() } private fun applyGalleryList(mediaListItems: MutableList<MediaListItem>) { // first, verify that the collection contains the item that the user // initially requested, if we have one... var initialImagePos = -1 initialFilename?.let { for (item in mediaListItems) { // the namespace of a file could be in a different language than English. if (StringUtil.removeNamespace(item.title) == StringUtil.removeNamespace(it)) { initialImagePos = mediaListItems.indexOf(item) break } } if (initialImagePos == -1) { // the requested image is not present in the gallery collection, so add it manually. // (this can happen if the user clicked on an SVG file, since we hide SVGs // by default in the gallery; or lead image in the PageHeader or in the info box) initialImagePos = 0 mediaListItems.add(initialImagePos, MediaListItem(it)) } } // pass the collection to the adapter! galleryAdapter.setList(mediaListItems) if (initialImagePos != -1) { // if we have a target image to jump to, then do it! binding.pager.setCurrentItem(initialImagePos, false) } else if (initialImageIndex >= 0 && initialImageIndex < galleryAdapter.itemCount) { // if we have a target image index to jump to, then do it! binding.pager.setCurrentItem(initialImageIndex, false) } } private val currentItem get() = galleryAdapter.getFragmentAt(binding.pager.currentItem) as GalleryItemFragment? fun layOutGalleryDescription(callingFragment: GalleryItemFragment?) { val item = currentItem if (item != callingFragment) { return } if (item?.imageTitle == null || item.mediaInfo?.metadata == null) { binding.infoContainer.visibility = View.GONE return } updateProgressBar(true) disposeImageCaptionDisposable() imageCaptionDisposable = Observable.zip( ServiceFactory.get(Constants.commonsWikiSite).getEntitiesByTitle(item.imageTitle!!.prefixedText, Constants.COMMONS_DB_NAME), ServiceFactory.get(Constants.commonsWikiSite).getProtectionInfo(item.imageTitle!!.prefixedText) ) { entities, protectionInfoRsp -> val captions = entities.first?.labels?.values?.associate { it.language to it.value }.orEmpty() item.mediaInfo!!.captions = captions val depicts = ImageTagsProvider.getDepictsClaims(entities.first?.getStatements().orEmpty()) Pair(protectionInfoRsp.query?.isEditProtected == true, depicts.size) }.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ updateGalleryDescription(it.first, it.second) }, { L.e(it) updateGalleryDescription(false, 0) }) } fun updateGalleryDescription(isProtected: Boolean, tagsCount: Int) { updateProgressBar(false) val item = currentItem if (item?.imageTitle == null || item.mediaInfo?.metadata == null) { binding.infoContainer.visibility = View.GONE return } displayApplicableDescription(item) // Display the Caption Edit button based on whether the image is hosted on Commons, // and not the local Wikipedia. var captionEditable = AccountUtil.isLoggedIn && item.mediaInfo!!.thumbUrl.contains(Service.URL_FRAGMENT_FROM_COMMONS) binding.captionEditButton.visibility = if (captionEditable) View.VISIBLE else View.GONE binding.captionEditButton.setImageResource(R.drawable.ic_mode_edit_white_24dp) binding.captionEditButton.tag = isProtected if (isProtected) { binding.captionEditButton.setImageResource(R.drawable.ic_edit_pencil_locked) captionEditable = false } if (captionEditable) { binding.ctaContainer.visibility = View.VISIBLE decideImageEditType(item, tagsCount) } else { binding.ctaContainer.visibility = View.GONE } setLicenseInfo(item) } private fun decideImageEditType(item: GalleryItemFragment, tagsCount: Int) { imageEditType = null if (!item.mediaInfo!!.captions.containsKey(sourceWiki.languageCode)) { imageEditType = ImageEditType.ADD_CAPTION targetLanguageCode = sourceWiki.languageCode binding.ctaButtonText.text = getString(R.string.gallery_add_image_caption_button) return } if (tagsCount == 0) { imageEditType = ImageEditType.ADD_TAGS binding.ctaButtonText.text = getString(R.string.suggested_edits_feed_card_add_image_tags) return } // and if we have another language in which the caption doesn't exist, then offer // it to be translatable. if (app.languageState.appLanguageCodes.size > 1) { for (lang in app.languageState.appLanguageCodes) { if (!item.mediaInfo!!.captions.containsKey(lang)) { targetLanguageCode = lang imageEditType = ImageEditType.ADD_CAPTION_TRANSLATION binding.ctaButtonText.text = getString(R.string.gallery_add_image_caption_in_language_button, app.languageState.getAppLanguageLocalizedName(targetLanguageCode)) break } } } binding.ctaContainer.visibility = if (imageEditType == null) View.GONE else View.VISIBLE } private fun displayApplicableDescription(item: GalleryItemFragment) { // If we have a structured caption in our current language, then display that instead // of the unstructured description, and make it editable. val descriptionStr = item.mediaInfo?.captions!!.getOrElse(sourceWiki.languageCode) { StringUtil.fromHtml(item.mediaInfo!!.metadata!!.imageDescription()) } if (descriptionStr.isNotEmpty()) { binding.descriptionContainer.visibility = View.VISIBLE binding.descriptionText.text = StringUtil.strip(descriptionStr) } else { binding.descriptionContainer.visibility = View.GONE } } private fun setLicenseInfo(item: GalleryItemFragment) { val metadata = item.mediaInfo!!.metadata!! val license = ImageLicense(metadata.license(), metadata.licenseShortName(), metadata.licenseUrl()) // determine which icon to display... if (license.licenseIcon == R.drawable.ic_license_by) { binding.licenseIcon.setImageResource(R.drawable.ic_license_cc) binding.licenseIconBy.setImageResource(R.drawable.ic_license_by) binding.licenseIconBy.visibility = View.VISIBLE binding.licenseIconSa.setImageResource(R.drawable.ic_license_sharealike) binding.licenseIconSa.visibility = View.VISIBLE } else { binding.licenseIcon.setImageResource(license.licenseIcon) binding.licenseIconBy.visibility = View.GONE binding.licenseIconSa.visibility = View.GONE } // Set the icon's content description to the UsageTerms property. // (if UsageTerms is not present, then default to Fair Use) binding.licenseIcon.contentDescription = metadata.licenseShortName().ifBlank { getString(R.string.gallery_fair_use_license) } // Give the license URL to the icon, to be received by the click handler (may be null). binding.licenseIcon.tag = metadata.licenseUrl() DeviceUtil.setContextClickAsLongClick(binding.licenseContainer) val creditStr = metadata.artist().ifEmpty { metadata.credit() } // if we couldn't find a attribution string, then default to unknown binding.creditText.text = StringUtil.fromHtml(creditStr.ifBlank { getString(R.string.gallery_uploader_unknown) }) binding.infoContainer.visibility = View.VISIBLE } private inner class GalleryItemAdapter(activity: AppCompatActivity) : PositionAwareFragmentStateAdapter(activity) { private val list = mutableListOf<MediaListItem>() fun setList(list: List<MediaListItem>) { this.list.clear() this.list.addAll(list) notifyDataSetChanged() } override fun getItemCount(): Int { return list.size } override fun createFragment(position: Int): Fragment { return GalleryItemFragment.newInstance(pageTitle, list[position]) } } private inner class MediaDownloadReceiverCallback : MediaDownloadReceiver.Callback { override fun onSuccess() { FeedbackUtil.showMessage(this@GalleryActivity, R.string.gallery_save_success) } } companion object { private const val KEY_CONTROLS_SHOWING = "controlsShowing" private const val KEY_PAGER_INDEX = "pagerIndex" const val ACTIVITY_RESULT_PAGE_SELECTED = 1 const val ACTIVITY_RESULT_IMAGE_CAPTION_ADDED = 2 const val ACTIVITY_RESULT_IMAGE_TAGS_ADDED = 3 const val EXTRA_PAGETITLE = "pageTitle" const val EXTRA_FILENAME = "filename" const val EXTRA_WIKI = "wiki" const val EXTRA_REVISION = "revision" const val EXTRA_SOURCE = "source" private var TRANSITION_INFO: JavaScriptActionHandler.ImageHitInfo? = null fun newIntent(context: Context, pageTitle: PageTitle?, filename: String, wiki: WikiSite, revision: Long, source: Int): Intent { val intent = Intent() .setClass(context, GalleryActivity::class.java) .putExtra(EXTRA_FILENAME, filename) .putExtra(EXTRA_WIKI, wiki) .putExtra(EXTRA_REVISION, revision) .putExtra(EXTRA_SOURCE, source) if (pageTitle != null) { intent.putExtra(EXTRA_PAGETITLE, pageTitle) } return intent } fun setTransitionInfo(hitInfo: JavaScriptActionHandler.ImageHitInfo) { TRANSITION_INFO = hitInfo } } }
apache-2.0
288a5335188002bbce2ff31b9339b75d
43.490331
178
0.664276
5.063826
false
false
false
false
BilledTrain380/sporttag-psa
app/dto/src/main/kotlin/ch/schulealtendorf/psa/dto/participation/athletics/ResultDto.kt
1
1014
package ch.schulealtendorf.psa.dto.participation.athletics data class ResultDto @JvmOverloads constructor( val id: Int, val value: Long, val points: Int, val discipline: DisciplineDto, val distance: String? = null ) { val relativeValue: String init { val factor = discipline.unit.factor if (factor == 1) { this.relativeValue = this.value.toString() } else { this.relativeValue = (this.value.toDouble() / factor).toString() } } fun toBuilder() = Builder(this) class Builder internal constructor( private val dto: ResultDto ) { private var value = dto.value private var points = dto.points fun setValue(value: Long): Builder { this.value = value return this } fun setPoints(points: Int): Builder { this.points = points return this } fun build() = dto.copy(value = value, points = points) } }
gpl-3.0
f471522db3f3ca5d7ed9d17d1fa7b46e
23.142857
76
0.579882
4.408696
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/iface/ILoadMoreSupportAdapter.kt
1
1699
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.adapter.iface import android.support.annotation.IntDef interface ILoadMoreSupportAdapter { var loadMoreIndicatorPosition: Long @IndicatorPosition get @IndicatorPosition set var loadMoreSupportedPosition: Long @IndicatorPosition get @IndicatorPosition set @IntDef(flag = true, value = *longArrayOf(NONE, START, END, BOTH)) annotation class IndicatorPosition companion object { val ITEM_VIEW_TYPE_LOAD_INDICATOR = 0 const val NONE: Long = 0 const val START: Long = 1 const val END: Long = 2 const val BOTH: Long = START or END @IndicatorPosition fun apply(@IndicatorPosition orig: Long, @IndicatorPosition supported: Long): Long { return orig and supported } } }
gpl-3.0
4579ad783911bcfcb62aa0ae833833c4
31.692308
92
0.711006
4.506631
false
false
false
false
vimeo/vimeo-networking-java
api-core/src/main/java/com/vimeo/networking2/logging/VimeoLogger.kt
1
2664
/* * The MIT License (MIT) * * Copyright (c) 2020 Vimeo * * 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.vimeo.networking2.logging /** * Internal logger that delegates to a [LogDelegate] based on the desired [LogDelegate.Level]. * * @param logDelegate The class to which the logging implementation will be delegated. Default is no implementation. * @param logLevel The level of logs that should be sent. Default is no logs. */ @Suppress("FunctionMinLength") internal class VimeoLogger( private val logDelegate: LogDelegate? = null, private val logLevel: LogDelegate.Level = LogDelegate.Level.NONE ) : LogDelegate { override fun e(error: String) { if (logLevel.level <= LogDelegate.Level.ERROR.level) { logDelegate?.e(error.prependIdentifier()) } } override fun e(error: String, exception: Exception) { if (logLevel.level <= LogDelegate.Level.ERROR.level) { logDelegate?.e(error.prependIdentifier(), exception) } } override fun d(message: String) { if (logLevel.level <= LogDelegate.Level.DEBUG.level) { logDelegate?.d(message.prependIdentifier()) } } override fun v(message: String) { if (logLevel.level <= LogDelegate.Level.VERBOSE.level) { logDelegate?.v(message.prependIdentifier()) } } /** * Formats the message to include the library identifier. */ private fun String.prependIdentifier(): String = "$LIBRARY_IDENTIFIER: $this" private companion object { private const val LIBRARY_IDENTIFIER = "vimeo-networking" } }
mit
7363c7a0bc79050899e219a1885a40b2
37.057143
116
0.703829
4.381579
false
false
false
false
vimeo/vimeo-networking-java
models/src/main/java/com/vimeo/networking2/TeamEntity.kt
1
1646
package com.vimeo.networking2 import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import com.vimeo.networking2.common.Entity import com.vimeo.networking2.enums.TeamEntityType import com.vimeo.networking2.enums.asEnum /** * Represents a team entity. * * @param rawType a raw string representation of the types defined by [TeamEntityType] * @param uri a uri which returns a singular instance of this [TeamEntity] * @param teamUser when the [TeamEntity] is of type [TeamEntityType.TEAM_USER], this will have a value representing the * data for that type * @param teamGroup when the [TeamEntity] is of type [TeamEntityType.TEAM_GROUP], this will have a value representing * the data for that type * @param owner when the [TeamEntity] is of type [TeamEntityType.ALL_TEAM], this will have a value representing the * owner of the team. * @param displayOptions various client display options that are server driven. See class definition for more detail */ @JsonClass(generateAdapter = true) data class TeamEntity( @Json(name = "type") val rawType: String? = null, @Json(name = "uri") val uri: String? = null, @Json(name = "team_user") val teamUser: TeamMembership? = null, @Json(name = "team_group") val teamGroup: TeamGroup? = null, @Json(name = "owner") val owner: User? = null, @Json(name = "display_options") val displayOptions: TeamEntityDisplayOptions? = null ) : Entity { override val identifier: String? = uri } /** * @see [TeamEntity.rawType] * @see TeamEntityType */ val TeamEntity.type: TeamEntityType get() = rawType.asEnum(TeamEntityType.UNKNOWN)
mit
57eaf707984a262d8bb307ed22ec0f38
31.92
119
0.725395
3.757991
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/pastry/layers/PastryControl.kt
1
3371
package com.teamwizardry.librarianlib.facade.pastry.layers import com.teamwizardry.librarianlib.facade.layer.GuiLayer public open class PastryControl: GuiLayer { public constructor(posX: Int, posY: Int): super(posX, posY) public constructor(posX: Int, posY: Int, width: Int, height: Int): super(posX, posY, width, height) /** * The next control in the sequence */ public var next: PastryControl? = null /** * The previous control in the sequence */ public var previous: PastryControl? = null public fun <T: PastryControl> tabTo(next: T): T { this.next = next next.previous = this return next } // TODO: focus /** * Focuses the next control, or if there's no next control focuses the first control. * * If both next and previous are null this method simply blurs this layer and returns true. * The "first" control is found by recursively searching along [previous] until either null is encountered or a * layer is encountered a second time (to prevent infinite recursion) * * @return whether the focus successfully switched */ public fun focusNext(): Boolean { var target = next if (target == null) { if (previous === this) { target = this } else { var head = previous ?: run { // this.requestBlur() TODO return true } val encountered = mutableListOf(this, head) while (true) { val tip = head.previous if (tip == null || encountered.any { tip === it }) break head = tip encountered.add(head) } target = head } } return true // target.requestFocus() TODO } /** * Focuses the previous control, or if there's no previous control focuses the last control. * * If both next and previous are null this method simply blurs this layer and returns true. * The "last" control is found by recursively searching along [next] until either null is encountered or a * layer is encountered a second time (to prevent infinite recursion) * * @return whether the focus successfully switched */ public fun focusPrevious(): Boolean { var target = previous if (target == null) { if (next === this) { target = this } else { var head = next ?: run { // this.requestBlur() TODO return true } val encountered = mutableListOf(this, head) while (true) { val tip = head.next if (tip == null || encountered.any { tip === it }) break head = tip encountered.add(head) } target = head } } return true // target.requestFocus() TODO } // @Hook // private fun requestFocus(e: GuiLayerEvents.RequestFocus) { // e.allow = true // } // // @Hook // private fun mouseDown(e: GuiLayerEvents.MouseDown) { // requestFocusedState(mouseOver) // } }
lgpl-3.0
0d06a995f2e0f00cdd16c45fc5523d86
32.386139
115
0.537823
4.864358
false
false
false
false
recruit-mp/LightCalendarView
library/src/main/kotlin/jp/co/recruit_mp/android/lightcalendarview/MonthView.kt
1
2260
/* * Copyright (C) 2016 RECRUIT MARKETING PARTNERS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.co.recruit_mp.android.lightcalendarview import android.content.Context import android.view.ViewGroup import android.widget.LinearLayout import jp.co.recruit_mp.android.lightcalendarview.accent.Accent import java.util.* /** * 月カレンダーを表示する {@link LinearLayout} * Created by masayuki-recruit on 8/19/16. */ class MonthView(context: Context, settings: CalendarSettings, var month: Date) : LinearLayout(context) { internal var onDateSelected: ((date: Date) -> Unit)? = null private val weekDayLayout: WeekDayLayout = WeekDayLayout(context, settings) private val dayLayout: DayLayout = DayLayout(context, settings, month).apply { onDateSelected = { date -> [email protected]?.invoke(date) } } init { orientation = LinearLayout.VERTICAL addView(weekDayLayout, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) addView(dayLayout, LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) } fun setSelectedDate(date: Date) { dayLayout.setSelectedDay(date) } fun setAccents(date: Date, accents: Collection<Accent>) { dayLayout.apply { getDayView(date)?.setAccents(accents) }.invalidateDayViews() } fun setAccents(map: Map<Date, Collection<Accent>>) { map.forEach { it -> val (date, accents) = it dayLayout.getDayView(date)?.setAccents(accents) } dayLayout.invalidateDayViews() } override fun toString(): String = "MonthView($month)" }
apache-2.0
d4280f8aa89ce26aadae8f1420dbe5df
33.96875
157
0.714477
4.061706
false
false
false
false
sheungon/SotwtmSupportLib
lib-sotwtm-support/src/main/kotlin/com/sotwtm/support/activity/ActivityMessenger.kt
1
2264
package com.sotwtm.support.activity import android.content.pm.PackageManager import android.os.Build import androidx.annotation.StringRes import com.sotwtm.support.base.BaseMessenger import com.sotwtm.support.scope.ActivityScope import com.sotwtm.support.util.SnackbarDuration import java.lang.ref.WeakReference import javax.inject.Inject /** * Messenger for [AppHelpfulActivity] * @author sheungon */ @ActivityScope class ActivityMessenger(private val activityRef: WeakReference<out AppHelpfulActivity>) : BaseMessenger() { @Inject constructor(_activity: AppHelpfulActivity) : this(WeakReference(_activity)) override val activity: AppHelpfulActivity? get() = activityRef.get() override fun showLoadingDialog(@StringRes msgRes: Int) { activity?.showLoadingDialog(msgRes) } override fun showLoadingDialog(msg: String) { activity?.showLoadingDialog(msg) } override fun dismissLoadingDialog() { activity?.dismissLoadingDialog() } override fun showSnackBar( @StringRes messageRes: Int, @SnackbarDuration duration: Int ) { activity?.showSnackBar(messageRes, duration) } override fun showSnackBar( message: String, @SnackbarDuration duration: Int ) { activity?.showSnackBar(message, duration) } fun checkSelfPermission(permission: String): Int? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity?.checkSelfPermission(permission) } else { // In previous version always has permission PackageManager.PERMISSION_GRANTED } fun shouldShowRequestPermissionRationale(permission: String): Boolean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity?.shouldShowRequestPermissionRationale(permission) ?: false } else { // In previous version always has permission. So, no need to show request permission rationale false } fun requestPermissions( permissions: Array<String>, requestCode: Int ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { activity?.requestPermissions(permissions, requestCode) } } }
apache-2.0
54b6788c137381753c6f83d67dbd861a
28.789474
106
0.682862
4.868817
false
false
false
false
oldcwj/iPing
commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/CreateNewFolderDialog.kt
1
2553
package com.simplemobiletools.commons.dialogs import android.support.v7.app.AlertDialog import android.view.View import android.view.WindowManager import com.simplemobiletools.commons.R import com.simplemobiletools.commons.activities.BaseSimpleActivity import com.simplemobiletools.commons.extensions.* import kotlinx.android.synthetic.main.dialog_create_new_folder.view.* import java.io.File class CreateNewFolderDialog(val activity: BaseSimpleActivity, val path: String, val callback: (path: String) -> Unit) { init { val view = activity.layoutInflater.inflate(R.layout.dialog_create_new_folder, null) view.folder_path.text = activity.humanizePath(path).trimEnd('/') + "/" AlertDialog.Builder(activity) .setPositiveButton(R.string.ok, null) .setNegativeButton(R.string.cancel, null) .create().apply { window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) context.setupDialogStuff(view, this, R.string.create_new_folder) getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(View.OnClickListener { val name = view.folder_name.value when { name.isEmpty() -> activity.toast(R.string.empty_name) name.isAValidFilename() -> { val file = File(path, name) if (file.exists()) { activity.toast(R.string.name_taken) return@OnClickListener } createFolder(file, this) } else -> activity.toast(R.string.invalid_name) } }) } } private fun createFolder(file: File, alertDialog: AlertDialog) { if (activity.needsStupidWritePermissions(file.absolutePath)) { activity.handleSAFDialog(file) { try { val documentFile = activity.getFileDocument(file.absolutePath) documentFile?.createDirectory(file.name) sendSuccess(alertDialog, file) } catch (e: SecurityException) { activity.showErrorToast(e) } } } else if (file.mkdirs()) { sendSuccess(alertDialog, file) } } private fun sendSuccess(alertDialog: AlertDialog, file: File) { callback(file.absolutePath.trimEnd('/')) alertDialog.dismiss() } }
gpl-3.0
a9bd9e86d85bef06ddfa06b9caf137f6
40.177419
119
0.594203
4.957282
false
false
false
false
yschimke/okhttp
okhttp/src/jvmTest/java/okhttp3/internal/http/ExternalHttp2Example.kt
1
1389
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.http import okhttp3.OkHttpClient import okhttp3.Protocol import okhttp3.Request object ExternalHttp2Example { @JvmStatic fun main(args: Array<String>) { val client = OkHttpClient.Builder() .protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1)) .build() val call = client.newCall( Request.Builder() .url("https://www.google.ca/") .build() ) val response = call.execute() try { println(response.code) println("PROTOCOL ${response.protocol}") var line: String? while (response.body!!.source().readUtf8Line().also { line = it } != null) { println(line) } } finally { response.body!!.close() } client.connectionPool.evictAll() } }
apache-2.0
437df718b417acfd73b23b6f93f308d4
29.195652
82
0.676026
4.014451
false
false
false
false
actions-on-google/appactions-common-biis-kotlin
app/src/test/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksViewModelTest.kt
1
9563
/* * Copyright (C) 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.tasks import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.lifecycle.SavedStateHandle import com.example.android.architecture.blueprints.todoapp.MainCoroutineRule import com.example.android.architecture.blueprints.todoapp.R import com.example.android.architecture.blueprints.todoapp.assertLiveDataEventTriggered import com.example.android.architecture.blueprints.todoapp.assertSnackbarMessage import com.example.android.architecture.blueprints.todoapp.data.Task import com.example.android.architecture.blueprints.todoapp.data.source.FakeRepository import com.example.android.architecture.blueprints.todoapp.getOrAwaitValue import com.example.android.architecture.blueprints.todoapp.observeForTesting import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.junit.Before import org.junit.Rule import org.junit.Test /** * Unit tests for the implementation of [TasksViewModel] */ @ExperimentalCoroutinesApi class TasksViewModelTest { // Subject under test private lateinit var tasksViewModel: TasksViewModel // Use a fake repository to be injected into the viewmodel private lateinit var tasksRepository: FakeRepository // Set the main coroutines dispatcher for unit testing. @ExperimentalCoroutinesApi @get:Rule var mainCoroutineRule = MainCoroutineRule() // Executes each task synchronously using Architecture Components. @get:Rule var instantExecutorRule = InstantTaskExecutorRule() @Before fun setupViewModel() { // We initialise the tasks to 3, with one active and two completed tasksRepository = FakeRepository() val task1 = Task("Title1", "Description1") val task2 = Task("Title2", "Description2", true) val task3 = Task("Title3", "Description3", true) tasksRepository.addTasks(task1, task2, task3) tasksViewModel = TasksViewModel(tasksRepository, SavedStateHandle()) } @Test fun loadAllTasksFromRepository_loadingTogglesAndDataLoaded() { // Pause dispatcher so we can verify initial values mainCoroutineRule.pauseDispatcher() // Given an initialized TasksViewModel with initialized tasks // When loading of Tasks is requested tasksViewModel.setFiltering(TasksFilterType.ALL_TASKS) // Trigger loading of tasks tasksViewModel.loadTasks(true) // Observe the items to keep LiveData emitting tasksViewModel.items.observeForTesting { // Then progress indicator is shown assertThat(tasksViewModel.dataLoading.getOrAwaitValue()).isTrue() // Execute pending coroutines actions mainCoroutineRule.resumeDispatcher() // Then progress indicator is hidden assertThat(tasksViewModel.dataLoading.getOrAwaitValue()).isFalse() // And data correctly loaded assertThat(tasksViewModel.items.getOrAwaitValue()).hasSize(3) } } @Test fun loadActiveTasksFromRepositoryAndLoadIntoView() { // Given an initialized TasksViewModel with initialized tasks // When loading of Tasks is requested tasksViewModel.setFiltering(TasksFilterType.ACTIVE_TASKS) // Load tasks tasksViewModel.loadTasks(true) // Observe the items to keep LiveData emitting tasksViewModel.items.observeForTesting { // Then progress indicator is hidden assertThat(tasksViewModel.dataLoading.getOrAwaitValue()).isFalse() // And data correctly loaded assertThat(tasksViewModel.items.getOrAwaitValue()).hasSize(1) } } @Test fun loadCompletedTasksFromRepositoryAndLoadIntoView() { // Given an initialized TasksViewModel with initialized tasks // When loading of Tasks is requested tasksViewModel.setFiltering(TasksFilterType.COMPLETED_TASKS) // Load tasks tasksViewModel.loadTasks(true) // Observe the items to keep LiveData emitting tasksViewModel.items.observeForTesting { // Then progress indicator is hidden assertThat(tasksViewModel.dataLoading.getOrAwaitValue()).isFalse() // And data correctly loaded assertThat(tasksViewModel.items.getOrAwaitValue()).hasSize(2) } } @Test fun loadTasks_error() { // Make the repository return errors tasksRepository.setReturnError(true) // Load tasks tasksViewModel.loadTasks(true) // Observe the items to keep LiveData emitting tasksViewModel.items.observeForTesting { // Then progress indicator is hidden assertThat(tasksViewModel.dataLoading.getOrAwaitValue()).isFalse() // And the list of items is empty assertThat(tasksViewModel.items.getOrAwaitValue()).isEmpty() // And the snackbar updated assertSnackbarMessage(tasksViewModel.snackbarText, R.string.loading_tasks_error) } } @Test fun clickOnFab_showsAddTaskUi() { // When adding a new task tasksViewModel.addNewTask() // Then the event is triggered val value = tasksViewModel.newTaskEvent.getOrAwaitValue() assertThat(value.getContentIfNotHandled()).isNotNull() } @Test fun clickOnOpenTask_setsEvent() { // When opening a new task val taskId = "42" tasksViewModel.openTask(taskId) // Then the event is triggered assertLiveDataEventTriggered(tasksViewModel.openTaskEvent, taskId) } @Test fun clearCompletedTasks_clearsTasks() = mainCoroutineRule.runBlockingTest { // When completed tasks are cleared tasksViewModel.clearCompletedTasks() // Fetch tasks tasksViewModel.loadTasks(true) // Fetch tasks val allTasks = tasksViewModel.items.getOrAwaitValue() val completedTasks = allTasks.filter { it.isCompleted } // Verify there are no completed tasks left assertThat(completedTasks).isEmpty() // Verify active task is not cleared assertThat(allTasks).hasSize(1) // Verify snackbar is updated assertSnackbarMessage( tasksViewModel.snackbarText, R.string.completed_tasks_cleared ) } @Test fun showEditResultMessages_editOk_snackbarUpdated() { // When the viewmodel receives a result from another destination tasksViewModel.showEditResultMessage(EDIT_RESULT_OK) // The snackbar is updated assertSnackbarMessage( tasksViewModel.snackbarText, R.string.successfully_saved_task_message ) } @Test fun showEditResultMessages_addOk_snackbarUpdated() { // When the viewmodel receives a result from another destination tasksViewModel.showEditResultMessage(ADD_EDIT_RESULT_OK) // The snackbar is updated assertSnackbarMessage( tasksViewModel.snackbarText, R.string.successfully_added_task_message ) } @Test fun showEditResultMessages_deleteOk_snackbarUpdated() { // When the viewmodel receives a result from another destination tasksViewModel.showEditResultMessage(DELETE_RESULT_OK) // The snackbar is updated assertSnackbarMessage(tasksViewModel.snackbarText, R.string.successfully_deleted_task_message) } @Test fun completeTask_dataAndSnackbarUpdated() { // With a repository that has an active task val task = Task("Title", "Description") tasksRepository.addTasks(task) // Complete task tasksViewModel.completeTask(task, true) // Verify the task is completed assertThat(tasksRepository.tasksServiceData[task.id]?.isCompleted).isTrue() // The snackbar is updated assertSnackbarMessage( tasksViewModel.snackbarText, R.string.task_marked_complete ) } @Test fun activateTask_dataAndSnackbarUpdated() { // With a repository that has a completed task val task = Task("Title", "Description", true) tasksRepository.addTasks(task) // Activate task tasksViewModel.completeTask(task, false) // Verify the task is active assertThat(tasksRepository.tasksServiceData[task.id]?.isActive).isTrue() // The snackbar is updated assertSnackbarMessage( tasksViewModel.snackbarText, R.string.task_marked_active ) } @Test fun getTasksAddViewVisible() { // When the filter type is ALL_TASKS tasksViewModel.setFiltering(TasksFilterType.ALL_TASKS) // Then the "Add task" action is visible assertThat(tasksViewModel.tasksAddViewVisible.getOrAwaitValue()).isTrue() } }
apache-2.0
868cd4a61b8af9a300574263b99b3cd0
33.774545
102
0.696852
5.019948
false
true
false
false
fcostaa/kotlin-microservice
server-springboot-adapter/src/main/kotlin/com/felipecosta/microservice/server/ServerRestController.kt
1
2026
package com.felipecosta.microservice.server import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.util.AntPathMatcher import org.springframework.web.bind.annotation.* import java.util.regex.Pattern import javax.servlet.http.HttpServletRequest @RestController class ServerRestController { @GetMapping("**") fun handleGet(request: HttpServletRequest) = handlePath(request, GetPath(request.pathInfo)) @PostMapping("**") fun handlePost(request: HttpServletRequest) = handlePath(request, PostPath(request.pathInfo)) @PutMapping("**") fun handlePut(request: HttpServletRequest) = handlePath(request, PutPath(request.pathInfo)) @DeleteMapping("**") fun handleDelete(request: HttpServletRequest) = handlePath(request, DeletePath(request.pathInfo)) private fun handlePath(request: HttpServletRequest, actionHandler: ActionHandler): Any? = with(ServerUrlMappings.firstOrNull { matchPath(it.path, actionHandler.path) }) { when (this) { null -> ResponseEntity<Any?>(null, HttpStatus.NOT_FOUND) else -> with(this(SpringBootRequestAdapter(request))) { ResponseEntity<Any>(this.body, HttpStatus.valueOf(this.code)) } } } private fun matchPath(registeredPath: String, requestPath: String) = with(AntPathMatcher()) { match(normalizePath(registeredPath), requestPath) } private fun normalizePath(path: String): String { val pattern = Pattern.compile("(:\\w+)|(\\w+)|(/)") val matcher = pattern.matcher(path) val builder = StringBuilder() while (matcher.find()) { val variable = matcher.group(0) if (variable.startsWith(":")) { builder.append("{${variable.replace(":", "")}}") } else { builder.append(variable) } } return builder.toString() } }
mit
b6e695804c0b61f23ad631fa56937430
37.226415
101
0.647581
4.755869
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/settings/SettingsFragment.kt
1
8191
package nerd.tuxmobil.fahrplan.congress.settings import android.annotation.TargetApi import android.app.Activity.RESULT_OK import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.provider.Settings import androidx.preference.EditTextPreference import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.Preference.OnPreferenceChangeListener import androidx.preference.Preference.OnPreferenceClickListener import androidx.preference.Preference.SummaryProvider import androidx.preference.PreferenceCategory import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceScreen import androidx.preference.SwitchPreferenceCompat import info.metadude.android.eventfahrplan.commons.logging.Logging import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import nerd.tuxmobil.fahrplan.congress.BuildConfig import nerd.tuxmobil.fahrplan.congress.R import nerd.tuxmobil.fahrplan.congress.alarms.AlarmServices import nerd.tuxmobil.fahrplan.congress.contract.BundleKeys import nerd.tuxmobil.fahrplan.congress.extensions.toSpanned import nerd.tuxmobil.fahrplan.congress.extensions.withExtras import nerd.tuxmobil.fahrplan.congress.preferences.AlarmTonePreference import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository import nerd.tuxmobil.fahrplan.congress.utils.FahrplanMisc class SettingsFragment : PreferenceFragmentCompat() { private companion object { const val REQUEST_CODE_ALARM_TONE = 3439 } private val job = Job() private val coroutineScope = CoroutineScope(Dispatchers.Default + job) private val logging = Logging.get() override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.prefs) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val screen = requirePreference<PreferenceScreen>(getString(R.string.preference_key_screen)) val developmentCategory = requirePreference<PreferenceCategory>(getString(R.string.preference_key_category_development)) requirePreference<ListPreference>(resources.getString(R.string.preference_key_schedule_refresh_interval_index)).onPreferenceChangeListener = OnPreferenceChangeListener { _, _ -> coroutineScope.launch { delay(100) // Workaround because preference is written asynchronous. FahrplanMisc.setUpdateAlarm(requireContext(), true, logging) } true } if (!BuildConfig.DEBUG) { screen.removePreference(developmentCategory) } val categoryGeneral = requirePreference<PreferenceCategory>(getString(R.string.preference_key_category_general)) requirePreference<SwitchPreferenceCompat>(resources.getString(R.string.preference_key_auto_update_enabled)).onPreferenceChangeListener = OnPreferenceChangeListener { _: Preference?, newValue: Any -> val isAutoUpdateEnabled = newValue as Boolean if (isAutoUpdateEnabled) { FahrplanMisc.setUpdateAlarm(requireContext(), true, logging) } else { AlarmServices.newInstance(requireContext(), AppRepository).discardAutoUpdateAlarm() } true } requirePreference<SwitchPreferenceCompat>(resources.getString(R.string.preference_key_use_device_time_zone_enabled)).onPreferenceChangeListener = OnPreferenceChangeListener { _: Preference?, _: Any -> requestRedraw(BundleKeys.USE_DEVICE_TIME_ZONE_UPDATED) true } val appNotificationSettingsPreference = requirePreference<Preference>(getString(R.string.preference_key_app_notification_settings)) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { categoryGeneral.removePreference(appNotificationSettingsPreference) } else { appNotificationSettingsPreference.onPreferenceClickListener = OnPreferenceClickListener { preference: Preference -> launchAppNotificationSettings(preference.context) true } } val alternativeScheduleUrlPreference = requirePreference<EditTextPreference>(getString(R.string.preference_key_alternative_schedule_url)) if (BuildConfig.ENABLE_ALTERNATIVE_SCHEDULE_URL) { alternativeScheduleUrlPreference.onPreferenceChangeListener = OnPreferenceChangeListener { _: Preference?, _: Any? -> requestRedraw(BundleKeys.SCHEDULE_URL_UPDATED) true } alternativeScheduleUrlPreference.summaryProvider = SummaryProvider<EditTextPreference> { when (it.text.isNullOrEmpty()) { true -> getString(R.string.preference_summary_alternative_schedule_url) false -> it.text } } } else { categoryGeneral.removePreference(alternativeScheduleUrlPreference) } requirePreference<SwitchPreferenceCompat>(resources.getString(R.string.preference_key_alternative_highlighting_enabled)).onPreferenceChangeListener = OnPreferenceChangeListener { _: Preference?, _: Any? -> requestRedraw(BundleKeys.ALTERNATIVE_HIGHLIGHTING_UPDATED) true } val engelsystemCategory = requirePreference<PreferenceCategory>(getString(R.string.preference_engelsystem_category_key)) if (BuildConfig.ENABLE_ENGELSYSTEM_SHIFTS) { val urlPreference = requirePreference<EditTextPreference>(getString(R.string.preference_key_engelsystem_json_export_url)) urlPreference.summaryProvider = SummaryProvider<EditTextPreference> { when (it.text.isNullOrEmpty()) { true -> getString(R.string.preference_summary_engelsystem_json_export_url, getString(R.string.engelsystem_alias)) .toSpanned() false -> "${it.text!!.dropLast(23)}..." // Truncate to keep the key private. } } urlPreference.onPreferenceChangeListener = OnPreferenceChangeListener { _: Preference?, _: Any? -> requestRedraw(BundleKeys.ENGELSYSTEM_SHIFTS_URL_UPDATED) true } } else { screen.removePreference(engelsystemCategory) } } override fun onStop() { job.cancel() super.onStop() } override fun onDisplayPreferenceDialog(preference: Preference) { if (preference is AlarmTonePreference) { preference.showAlarmTonePicker(this, REQUEST_CODE_ALARM_TONE) } else { super.onDisplayPreferenceDialog(preference) } } override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { if (REQUEST_CODE_ALARM_TONE == requestCode && RESULT_OK == resultCode && intent != null) { val preference = requirePreference<AlarmTonePreference>(getString(R.string.preference_key_alarm_tone)) preference.onAlarmTonePicked(intent) } else { super.onActivityResult(requestCode, resultCode, intent) } } private fun requestRedraw(bundleKey: String) { val redrawIntent = Intent().withExtras(bundleKey to true) requireNotNull(activity).setResult(RESULT_OK, redrawIntent) } @TargetApi(Build.VERSION_CODES.O) private fun launchAppNotificationSettings(context: Context) { val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS).withExtras( Settings.EXTRA_APP_PACKAGE to context.packageName ) startActivity(intent) } /** * Returns a [Preference] for the given key or throws a [NullPointerException] * if none can be found. Uses [findPreference]. */ private fun <T : Preference> requirePreference(key: CharSequence): T = findPreference(key) ?: throw NullPointerException("Cannot find preference for '$key' key.") }
apache-2.0
d3f295381e2f24f6914474d3bf9d4692
45.276836
213
0.71078
5.213877
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/reference/LuaIndexReference.kt
2
2412
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.reference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiReferenceBase import com.intellij.util.IncorrectOperationException import com.tang.intellij.lua.psi.LuaElementFactory import com.tang.intellij.lua.psi.LuaIndexExpr import com.tang.intellij.lua.psi.resolve import com.tang.intellij.lua.search.SearchContext /** * * Created by TangZX on 2016/12/4. */ class LuaIndexReference internal constructor(element: LuaIndexExpr, private val id: PsiElement) : PsiReferenceBase<LuaIndexExpr>(element), LuaReference { override fun getRangeInElement(): TextRange { val start = id.node.startOffset - myElement.node.startOffset return TextRange(start, start + id.textLength) } @Throws(IncorrectOperationException::class) override fun handleElementRename(newElementName: String): PsiElement { val newId = LuaElementFactory.createIdentifier(myElement.project, newElementName) id.replace(newId) return newId } override fun isReferenceTo(element: PsiElement): Boolean { return myElement.manager.areElementsEquivalent(resolve(), element) } override fun resolve(): PsiElement? { return resolve(SearchContext.get(myElement.project)) } override fun resolve(context: SearchContext): PsiElement? { val ref = resolve(myElement, context) if (ref != null) { if (ref.containingFile == myElement.containingFile) { //优化,不要去解析 Node Tree if (ref.node.textRange == myElement.node.textRange) { return null//自己引用自己 } } } return ref } override fun getVariants(): Array<Any> = emptyArray() }
apache-2.0
951ecd7ee6dca47c5969c4d35f47f07e
34.058824
95
0.709732
4.431227
false
false
false
false
ohmae/DmsExplorer
mobile/src/main/java/net/mm2d/dmsexplorer/viewmodel/PhotoActivityModel.kt
1
2939
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.dmsexplorer.viewmodel import android.app.Activity import android.graphics.Color import android.net.Uri import androidx.annotation.ColorInt import androidx.core.content.ContextCompat import androidx.databinding.BaseObservable import androidx.databinding.Bindable import androidx.databinding.library.baseAdapters.BR import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import net.mm2d.android.util.DisplaySizeUtils import net.mm2d.android.util.Toaster import net.mm2d.android.util.toDisplayableString import net.mm2d.dmsexplorer.R import net.mm2d.dmsexplorer.Repository import net.mm2d.dmsexplorer.domain.model.PlaybackTargetModel import net.mm2d.dmsexplorer.settings.Settings import net.mm2d.dmsexplorer.util.Downloader import net.mm2d.dmsexplorer.view.base.BaseActivity /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class PhotoActivityModel( private val activity: BaseActivity, repository: Repository ) : BaseObservable() { private val targetModel: PlaybackTargetModel = repository.playbackTargetModel ?: throw IllegalStateException() val title: String @ColorInt val background: Int @get:Bindable var imageBinary: ByteArray? = null set(imageBinary) { field = imageBinary notifyPropertyChanged(BR.imageBinary) } @get:Bindable var isLoading = true set(loading) { field = loading notifyPropertyChanged(BR.loading) } @get:Bindable var rightNavigationSize: Int = 0 set(size) { field = size notifyPropertyChanged(BR.rightNavigationSize) } init { val settings = Settings.get() title = if (settings.shouldShowTitleInPhotoUi()) targetModel.title.toDisplayableString() else "" background = if (settings.isPhotoUiBackgroundTransparent) Color.TRANSPARENT else ContextCompat.getColor(activity, R.color.translucent_control) val uri = targetModel.uri check(!(uri === Uri.EMPTY)) Downloader.create(uri.toString()) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ data -> val model = repository.playbackTargetModel if (model?.uri == uri) { isLoading = false imageBinary = data } }, { Toaster.show(activity, R.string.toast_download_error) } ) } fun adjustPanel(activity: Activity) { rightNavigationSize = DisplaySizeUtils.getNavigationBarArea(activity).x } fun onClickBack() { activity.navigateUpTo() } }
mit
d503a356da36638fcd1c51a8ed96b0ac
28.826531
81
0.674991
4.462595
false
false
false
false
ZieIony/Carbon
samples/src/main/java/tk/zielony/carbonsamples/graph/BarChartActivity.kt
1
1693
package tk.zielony.carbonsamples.graph import android.content.Context import android.content.res.ColorStateList import android.os.Bundle import carbon.beta.ChartView import carbon.drawable.ColorStateListFactory import kotlinx.android.synthetic.main.activity_barchart.* import tk.zielony.carbonsamples.R import tk.zielony.carbonsamples.SampleAnnotation import tk.zielony.carbonsamples.ThemedActivity import tk.zielony.randomdata.DataContext import tk.zielony.randomdata.Generator import tk.zielony.randomdata.Matcher import tk.zielony.randomdata.RandomData import tk.zielony.randomdata.common.FloatGenerator import tk.zielony.randomdata.food.StringFruitGenerator class ColorGenerator(val context: Context) : Generator<ColorStateList>() { override fun next(dataContext: DataContext?): ColorStateList? { return ColorStateListFactory.makeControlPrimary(context) } override fun getDefaultMatcher(): Matcher { return Matcher { f -> f.name == "color" } } } @SampleAnnotation(layoutId = R.layout.activity_barchart, titleId = R.string.barChartActivity_title) class BarChartActivity : ThemedActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initToolbar() val randomData = RandomData() randomData.addGenerator(String::class.java, StringFruitGenerator()) randomData.addGenerator(Float::class.java, FloatGenerator(0f, 100f).withMatcher { field -> field.name == "value" }) randomData.addGenerator(ColorStateList::class.java, ColorGenerator(this)) val items = randomData.generateArray(ChartView.Item::class.java, 10) chart.setItems(items) } }
apache-2.0
1f84b14925dfed90fd204c6d03649f58
35.021277
123
0.770821
4.264484
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/helpers/NotificationsManager.kt
1
5773
package com.habitrpg.android.habitica.helpers import android.content.Context import androidx.core.app.NotificationManagerCompat import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.common.habitica.models.Notification import com.habitrpg.android.habitica.models.tasks.Task import io.reactivex.rxjava3.core.BackpressureStrategy import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.subjects.BehaviorSubject import io.reactivex.rxjava3.subjects.PublishSubject import java.lang.ref.WeakReference import java.util.Date interface NotificationsManager { val displayNotificationEvents: Flowable<Notification> var apiClient: WeakReference<ApiClient>? fun setNotifications(current: List<Notification>) fun getNotifications(): Flowable<List<Notification>> fun getNotification(id: String): Notification? fun dismissTaskNotification(context: Context, task: Task) } class MainNotificationsManager: NotificationsManager { private val displayNotificationSubject = PublishSubject.create<Notification>() private val seenNotifications: MutableMap<String, Boolean> override var apiClient: WeakReference<ApiClient>? = null private val notifications: BehaviorSubject<List<Notification>> private var lastNotificationHandling: Date? = null override val displayNotificationEvents: Flowable<Notification> get() { return displayNotificationSubject.toFlowable(BackpressureStrategy.DROP) } init { this.seenNotifications = HashMap() this.notifications = BehaviorSubject.create() } override fun setNotifications(current: List<Notification>) { this.notifications.onNext(current) this.handlePopupNotifications(current) } override fun getNotifications(): Flowable<List<Notification>> { return this.notifications.startWithArray(emptyList()) .toFlowable(BackpressureStrategy.LATEST) } override fun getNotification(id: String): Notification? { return this.notifications.value?.find { it.id == id } } override fun dismissTaskNotification(context: Context, task: Task) { NotificationManagerCompat.from(context).cancel(task.id.hashCode()) } private fun handlePopupNotifications(notifications: List<Notification>): Boolean { val now = Date() if (now.time - (lastNotificationHandling?.time ?: 0) < 300) { return true } lastNotificationHandling = now notifications .filter { !this.seenNotifications.containsKey(it.id) } .map { val notificationDisplayed = when (it.type) { Notification.Type.ACHIEVEMENT_PARTY_UP.type -> true Notification.Type.ACHIEVEMENT_PARTY_ON.type -> true Notification.Type.ACHIEVEMENT_BEAST_MASTER.type -> true Notification.Type.ACHIEVEMENT_MOUNT_MASTER.type -> true Notification.Type.ACHIEVEMENT_TRIAD_BINGO.type -> true Notification.Type.ACHIEVEMENT_GUILD_JOINED.type -> true Notification.Type.ACHIEVEMENT_CHALLENGE_JOINED.type -> true Notification.Type.ACHIEVEMENT_INVITED_FRIEND.type -> true Notification.Type.ACHIEVEMENT_ALL_YOUR_BASE.type -> true Notification.Type.ACHIEVEMENT_BACK_TO_BASICS.type -> true Notification.Type.ACHIEVEMENT_JUST_ADD_WATER.type -> true Notification.Type.ACHIEVEMENT_LOST_MASTERCLASSER.type -> true Notification.Type.ACHIEVEMENT_MIND_OVER_MATTER.type -> true Notification.Type.ACHIEVEMENT_DUST_DEVIL.type -> true Notification.Type.ACHIEVEMENT_ARID_AUTHORITY.type -> true Notification.Type.ACHIEVEMENT_MONSTER_MAGUS.type -> true Notification.Type.ACHIEVEMENT_UNDEAD_UNDERTAKER.type -> true Notification.Type.ACHIEVEMENT_PRIMED_FOR_PAINTING.type -> true Notification.Type.ACHIEVEMENT_PEARLY_PRO.type -> true Notification.Type.ACHIEVEMENT_TICKLED_PINK.type -> true Notification.Type.ACHIEVEMENT_ROSY_OUTLOOK.type -> true Notification.Type.ACHIEVEMENT_BUG_BONANZA.type -> true Notification.Type.ACHIEVEMENT_BARE_NECESSITIES.type -> true Notification.Type.ACHIEVEMENT_FRESHWATER_FRIENDS.type -> true Notification.Type.ACHIEVEMENT_GOOD_AS_GOLD.type -> true Notification.Type.ACHIEVEMENT_ALL_THAT_GLITTERS.type -> true Notification.Type.ACHIEVEMENT_GOOD_AS_GOLD.type -> true Notification.Type.ACHIEVEMENT_BONE_COLLECTOR.type -> true Notification.Type.ACHIEVEMENT_SKELETON_CREW.type -> true Notification.Type.ACHIEVEMENT_SEEING_RED.type -> true Notification.Type.ACHIEVEMENT_RED_LETTER_DAY.type -> true Notification.Type.ACHIEVEMENT_GENERIC.type -> true Notification.Type.ACHIEVEMENT_ONBOARDING_COMPLETE.type -> true Notification.Type.LOGIN_INCENTIVE.type -> true else -> false } if (notificationDisplayed) { displayNotificationSubject.onNext(it) this.seenNotifications[it.id] = true readNotification(it) } } return true } private fun readNotification(notification: Notification) { apiClient?.get()?.readNotification(notification.id) ?.subscribe({ }, ExceptionHandler.rx()) } }
gpl-3.0
43fba89c136d3975f5f6534148205cff
45.184
86
0.656678
5.214995
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/commonMain/kotlin/org/koin/core/module/dsl/OptionDSL.kt
1
2117
@file:OptIn(KoinInternalApi::class) package org.koin.core.module.dsl import org.koin.core.annotation.KoinInternalApi import org.koin.core.definition.BeanDefinition import org.koin.core.definition.Callbacks import org.koin.core.definition.OnCloseCallback import org.koin.core.instance.InstanceFactory import org.koin.core.instance.SingleInstanceFactory import org.koin.core.module.KoinDefinition import org.koin.core.module.Module import org.koin.core.qualifier.StringQualifier import org.koin.core.qualifier.TypeQualifier import kotlin.reflect.KClass /** * Koin DSL Options * * @author Arnaud Giuliani */ infix fun <T> KoinDefinition<T>.withOptions( options: BeanDefinition<T>.() -> Unit ): KoinDefinition<T> { val factory = second val module = first val def = second.beanDefinition val primary = def.qualifier def.also(options) if (def.qualifier != primary){ module.indexPrimaryType(factory) } module.indexSecondaryTypes(factory) if (def._createdAtStart && factory is SingleInstanceFactory<*>) { module.prepareForCreationAtStart(factory) } return this } @KoinInternalApi inline fun <reified R> Module.setupInstance( factory: InstanceFactory<R>, options: BeanDefinition<R>.() -> Unit ): KoinDefinition<R> { val def = factory.beanDefinition val koinDef = Pair(this, factory) def.also(options) indexPrimaryType(factory) indexSecondaryTypes(factory) if (def._createdAtStart && factory is SingleInstanceFactory<*>) { prepareForCreationAtStart(factory) } return koinDef } fun BeanDefinition<*>.named(name: String) { qualifier = StringQualifier(name) } inline fun <reified T> BeanDefinition<*>.named() { qualifier = TypeQualifier(T::class) } inline fun <reified T> BeanDefinition<out T>.bind() { secondaryTypes += T::class } fun BeanDefinition<*>.binds(classes: List<KClass<*>>) { secondaryTypes += classes } fun BeanDefinition<*>.createdAtStart() { _createdAtStart = true } fun <T> BeanDefinition<T>.onClose(onClose: OnCloseCallback<T>) { callbacks = Callbacks(onClose) }
apache-2.0
991c90f7a6598857687ea031c2fa8496
25.810127
69
0.729806
4.040076
false
false
false
false
InsertKoinIO/koin
core/koin-core/src/nativeMain/kotlin/org/koin/mp/KoinPlatformTools.kt
1
1473
package org.koin.mp import co.touchlab.stately.concurrency.Lock import co.touchlab.stately.concurrency.withLock import org.koin.core.context.KoinContext import org.koin.core.context.globalContextByMemoryModel import org.koin.core.logger.Level import org.koin.core.logger.Logger import org.koin.core.logger.PrintLogger import org.koin.mp.native.assertMainThread import kotlin.random.Random import kotlin.reflect.KClass actual object KoinPlatformTools { private val defaultContext: KoinContext by lazy { globalContextByMemoryModel() } actual fun getStackTrace(e: Exception): String = e.toString() + Exception().toString().split("\n") actual fun getClassName(kClass: KClass<*>): String = kClass.qualifiedName ?: "KClass@${kClass.hashCode()}" // TODO Better Id generation? actual fun generateId(): String = Random.nextDouble().hashCode().toString() actual fun defaultLazyMode(): LazyThreadSafetyMode = LazyThreadSafetyMode.PUBLICATION actual fun defaultLogger(level: Level): Logger = PrintLogger(level) actual fun defaultContext(): KoinContext = defaultContext @OptIn(ExperimentalStdlibApi::class) actual fun <R> synchronized(lock: Lockable, block: () -> R): R = if(isExperimentalMM()){ lock.lock.withLock { block() } } else { assertMainThread() block() } actual fun <K, V> safeHashMap(): MutableMap<K, V> = HashMap() } actual open class Lockable { internal val lock = Lock() }
apache-2.0
b92cae5b0b588d2f9540af72792a57ce
34.926829
110
0.731161
4.257225
false
false
false
false
michalfaber/android-drawer-template
app/src/main/kotlin/views/adapters/drawer/DrawerAdapter.kt
1
4531
package com.michalfaber.drawertemplate.views.adapters.drawer import android.support.v7.widget.RecyclerView import android.view.ViewGroup import com.michalfaber.drawertemplate.MainApplication import com.michalfaber.drawertemplate.R import com.michalfaber.drawertemplate.views.adapters.AdapterItem import com.michalfaber.drawertemplate.views.adapters.AdapterItemsSupervisor import com.michalfaber.drawertemplate.views.adapters.ViewHolderProvider import javax.inject.Inject /** * Adapter handles multiple view types. Type of view is determined by the hashCode of the specific ViewHolder class * */ public class DrawerAdapter(val adapterItems: List<AdapterItem>) : RecyclerView.Adapter<RecyclerView.ViewHolder>(), AdapterItemsSupervisor<AdapterItem> { private val items: MutableList<AdapterItem> = adapterItems.toCollection(arrayListOf<AdapterItem>()) private var selectedId: Long? = null var viewHolderProvider: ViewHolderProvider? = null [Inject] set init { // TODO: Create separate component MainApplication.graph.inject(this) /* Register functions which will be used to create fresh instances of specific View Holder and layout */ viewHolderProvider!!.registerViewHolderFactory(ViewHolderMedium::class, R.layout.drawer_item_medium, { drawerItemView -> ViewHolderMedium(drawerItemView) }) viewHolderProvider!!.registerViewHolderFactory(ViewHolderSmall::class, R.layout.drawer_item_small, { drawerItemView -> ViewHolderSmall(drawerItemView) }) viewHolderProvider!!.registerViewHolderFactory(ViewHolderSeparator::class, R.layout.drawer_item_separator, { drawerItemView -> ViewHolderSeparator(drawerItemView) }) viewHolderProvider!!.registerViewHolderFactory(ViewHolderHeader::class, R.layout.drawer_item_header, { drawerItemView -> ViewHolderHeader(drawerItemView) }) viewHolderProvider!!.registerViewHolderFactory(ViewHolderSpinner::class, R.layout.drawer_item_spinner, { drawerItemView -> ViewHolderSpinner(drawerItemView, this) }) viewHolderProvider!!.registerViewHolderFactory(ViewHolderSpinnerItem::class, R.layout.drawer_item_spinner_item, { drawerItemView -> ViewHolderSpinnerItem(drawerItemView, this) }) } public fun getItemIdAt(adapterPosition: Int): Long? { return if (adapterPosition >= 0 && adapterPosition < items.size()) items[adapterPosition].id else null } public fun select(id: Long) { if (id != selectedId) { items.filter { it.id == id && it.selectable == true } .take(1) .forEach { unselectPreviousAdapterItem() selectAdapterItem(it) } } } private fun selectAdapterItem(adapterItem: AdapterItem) { selectedId = adapterItem.id notifyItemChanged(indexOfItem(adapterItem)); } private fun unselectPreviousAdapterItem() { val prevSelectedItemIdx = items.indexOfFirst { it.id == selectedId } if (prevSelectedItemIdx >= 0) { notifyItemChanged(prevSelectedItemIdx); } } override fun removeItems(startsFrom: Int, subItems: List<AdapterItem>) { items.removeAll(subItems) notifyItemRangeRemoved(startsFrom, subItems.size()) } override fun addItems(startsFrom: Int, subItems: List<AdapterItem>) { items.addAll(startsFrom, subItems) notifyItemRangeInserted(startsFrom, subItems.size()) } override fun indexOfItem(item: AdapterItem): Int { return items.lastIndexOf(item) } override fun swapItem(index: Int, item: AdapterItem) { items[index] = item notifyItemChanged(index) } override fun getItemViewType(position: Int): Int { return items[position].viewType } override fun getItemCount(): Int { return items.size() } override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder? { return viewHolderProvider!!.provideViewHolder(viewGroup, viewType) } override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) { items[position].bindViewHolder(viewHolder) viewHolder.itemView.setActivated(items[position].id == selectedId) } override fun getItemId(position: Int): Long { return items[position].id } }
apache-2.0
a0f5f39a333f97581c3efcaf711fce9a
36.139344
152
0.691238
5.13137
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/track/TrackService.kt
1
2378
package eu.kanade.tachiyomi.data.track import androidx.annotation.CallSuper import androidx.annotation.ColorInt import androidx.annotation.DrawableRes import androidx.annotation.StringRes import eu.kanade.domain.base.BasePreferences import eu.kanade.domain.track.service.TrackPreferences import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.NetworkHelper import okhttp3.OkHttpClient import uy.kohesive.injekt.injectLazy abstract class TrackService(val id: Long) { val preferences: BasePreferences by injectLazy() val trackPreferences: TrackPreferences by injectLazy() val networkService: NetworkHelper by injectLazy() open val client: OkHttpClient get() = networkService.client // Name of the manga sync service to display @StringRes abstract fun nameRes(): Int // Application and remote support for reading dates open val supportsReadingDates: Boolean = false @DrawableRes abstract fun getLogo(): Int @ColorInt abstract fun getLogoColor(): Int abstract fun getStatusList(): List<Int> abstract fun getStatus(status: Int): String abstract fun getReadingStatus(): Int abstract fun getRereadingStatus(): Int abstract fun getCompletionStatus(): Int abstract fun getScoreList(): List<String> open fun indexToScore(index: Int): Float { return index.toFloat() } abstract fun displayScore(track: Track): String abstract suspend fun update(track: Track, didReadChapter: Boolean = false): Track abstract suspend fun bind(track: Track, hasReadChapters: Boolean = false): Track abstract suspend fun search(query: String): List<TrackSearch> abstract suspend fun refresh(track: Track): Track abstract suspend fun login(username: String, password: String) @CallSuper open fun logout() { trackPreferences.setTrackCredentials(this, "", "") } open val isLogged: Boolean get() = getUsername().isNotEmpty() && getPassword().isNotEmpty() fun getUsername() = trackPreferences.trackUsername(this).get() fun getPassword() = trackPreferences.trackPassword(this).get() fun saveCredentials(username: String, password: String) { trackPreferences.setTrackCredentials(this, username, password) } }
apache-2.0
6032851fb8f245a175ba19df4eeb950a
28.358025
85
0.736754
4.833333
false
false
false
false
sn3d/nomic
nomic-oozie/src/main/kotlin/nomic/oozie/adapter/RestOozieAdapter.kt
1
3935
/* * Copyright 2017 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nomic.oozie.adapter import com.mashape.unirest.http.Unirest import nomic.core.exception.WtfException import nomic.oozie.OozieServerException import org.json.JSONObject import org.json.JSONTokener /** * @author [email protected] */ class RestOozieAdapter(val oozieUrl: String = "http://localhost:11000") : OozieAdapter { /** * this function return a list of all running coordinators in Oozie. You can also filter * coordinators by [filter] */ override fun findRunningCoordinatorJobs(filter: (OozieJob) -> Boolean): List<OozieJob> { val json = Unirest.get("${oozieUrl}/oozie/v1/jobs?jobtype=coord&filter=status=PREP;status=RUNNING;status=PREPSUSPENDED;status=SUSPENDED;status=PREPPAUSED;status=PAUSED;") .header("Content-Type", "application/json") .asJson() val filteredCoordinators = json.body.`object`.getJSONArray("coordinatorjobs") .map(this::anyToJob) .filter(filter) .toList() return filteredCoordinators; } /** * find concrete job by ID */ override fun findJob(jobId: String): OozieJob { val json = Unirest.get("${oozieUrl}/oozie/v1/job/${jobId}") .header("Content-Type", "application/json") .asJson() return jsonToJob(json.body.`object`); } /** * killing the running job */ override fun killJob(job: OozieJob) { val resp = Unirest.put("${oozieUrl}/oozie/v1/job/${job.jobId}?action=kill").asString() if (resp.headers.containsKey("oozie-error-code")) { val message = resp.headers.getFirst("oozie-error-message") throw OozieServerException(message) } } /** * create the coordinator with params and start it */ override fun createAndStartJob(params:Map<String, String>):OozieJob { val resp = Unirest.post("${oozieUrl}/oozie/v1/jobs?action=start") .header("Content-Type", "application/xml") .header("Accept-Encoding", "gzip,deflate") .body(paramsToXml(params)) .asString() if (resp.headers.containsKey("oozie-error-code")) { val message = resp.headers.getFirst("oozie-error-message") throw OozieServerException(message) } // parse body to JSON val tokener = JSONTokener(resp.body) val jsonBody = JSONObject(tokener) return OozieJob(jobId = jsonBody.getString("id")) } //------------------------------------------------------------------------------------------------- // private functions //------------------------------------------------------------------------------------------------- private fun anyToJob(any: Any?) = if (any is JSONObject) jsonToJob(any) else throw WtfException() private fun jsonToJob(json: JSONObject) = OozieJob( jobId = json.getString("coordJobId"), jobName = json.getString("coordJobName"), jobPath = json.getString("coordJobPath"), status = json.getString("status") ) //private fun paramsToXml(params:Array<out Pair<String, String>>): String { private fun paramsToXml(params:Map<String, String>): String { val xml = StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") xml.append("<configuration>") params.forEach { param -> val name = param.key.toString() val value = param.value.toString() xml.append("<property>") xml.append("<name>${name}</name>") xml.append("<value>${value}</value>") xml.append("</property>") } xml.append("</configuration>") return xml.toString() } }
apache-2.0
22ac3c42a38d1d56fb042ad0b5aae2e9
29.511628
162
0.669377
3.545045
false
false
false
false
santoslucas/guarda-filme-android
app/src/main/java/com/guardafilme/data/MoviesProvider.kt
1
1605
package com.guardafilme.data import android.app.Activity import android.content.Context import info.movito.themoviedbapi.TmdbApi import info.movito.themoviedbapi.model.MovieDb import com.guardafilme.R import com.guardafilme.Utils import com.guardafilme.model.Movie import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread /** * Created by lucassantos on 12/10/17. */ class MoviesProvider { companion object { fun searchMovies(context: Context, query: String, onMoviesLoaded: (movies: List<Movie>) -> Unit) { doAsync { val searchResult = TmdbApi(context.getString(R.string.tmdb_key)).search.searchMovie(query, 0, "pt-BR", true, 0) uiThread { if (!(context as Activity).isDestroyed) { onMoviesLoaded(convertTmdbMoviesToInternal(searchResult.results)) } } } } private fun tmdbMovieToInternalMovie(tmdbMovie: MovieDb): Movie { val movie = Movie() movie.id = tmdbMovie.id movie.title = tmdbMovie.title movie.originalTitle = tmdbMovie.originalTitle movie.year = Utils.getYearFromMovieReleaseDate(tmdbMovie.releaseDate) movie.poster = tmdbMovie.posterPath ?: "" movie.backdrop = tmdbMovie.backdropPath ?: "" return movie } private fun convertTmdbMoviesToInternal(tmdbMoviesList: List<MovieDb>): List<Movie> { return tmdbMoviesList.map { tmdbMovie -> tmdbMovieToInternalMovie(tmdbMovie) } } } }
gpl-3.0
51e7ee35a09724fb6d7698daa7ea5b81
34.688889
127
0.644237
4.445983
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SuperClassNotInitialized.kt
2
12058
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix import com.intellij.codeInsight.hint.ShowParameterInfoHandler import com.intellij.codeInsight.intention.FileModifier import com.intellij.codeInsight.intention.HighPriorityAction import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.resolveToParameterDescriptorIfAny import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.isVisible import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.resolve.languageVersionSettings import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.hasExpectModifier import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.descriptorUtil.classId import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructorSubstitution import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.utils.addIfNotNull object SuperClassNotInitialized : KotlinIntentionActionsFactory() { private const val DISPLAY_MAX_PARAMS = 5 override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> { val delegator = diagnostic.psiElement as KtSuperTypeEntry val classOrObjectDeclaration = delegator.parent.parent as? KtClassOrObject ?: return emptyList() val typeRef = delegator.typeReference ?: return emptyList() val type = typeRef.analyze()[BindingContext.TYPE, typeRef] ?: return emptyList() if (type.isError) return emptyList() val superClass = (type.constructor.declarationDescriptor as? ClassDescriptor) ?: return emptyList() val classDescriptor = classOrObjectDeclaration.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return emptyList() val containingPackage = superClass.classId?.packageFqName val inSamePackage = containingPackage != null && containingPackage == classDescriptor.classId?.packageFqName val constructors = superClass.constructors.filter { it.isVisible(classDescriptor, delegator.getResolutionFacade().languageVersionSettings) && (superClass.modality != Modality.SEALED || inSamePackage && classDescriptor.visibility != DescriptorVisibilities.LOCAL) } if (constructors.isEmpty() && (!superClass.isExpect || superClass.kind != ClassKind.CLASS)) { return emptyList() // no accessible constructor } val fixes = ArrayList<IntentionAction>() fixes.add( AddParenthesisFix( delegator, putCaretIntoParenthesis = constructors.singleOrNull()?.valueParameters?.isNotEmpty() ?: true ) ) if (classOrObjectDeclaration is KtClass) { val superType = classDescriptor.typeConstructor.supertypes.firstOrNull { it.constructor.declarationDescriptor == superClass } if (superType != null) { val substitutor = TypeConstructorSubstitution.create(superClass.typeConstructor, superType.arguments).buildSubstitutor() val substitutedConstructors = constructors .asSequence() .filter { it.valueParameters.isNotEmpty() } .mapNotNull { it.substitute(substitutor) } .toList() if (substitutedConstructors.isNotEmpty()) { val parameterTypes: List<List<KotlinType>> = substitutedConstructors.map { it.valueParameters.map { it.type } } fun canRenderOnlyFirstParameters(n: Int) = parameterTypes.map { it.take(n) }.toSet().size == parameterTypes.size val maxParams = parameterTypes.maxOf { it.size } val maxParamsToDisplay = if (maxParams <= DISPLAY_MAX_PARAMS) { maxParams } else { (DISPLAY_MAX_PARAMS until maxParams).firstOrNull(::canRenderOnlyFirstParameters) ?: maxParams } for ((constructor, types) in substitutedConstructors.zip(parameterTypes)) { val typesRendered = types.asSequence().take(maxParamsToDisplay).map { DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(it) } .toList() val parameterString = typesRendered.joinToString(", ", "(", if (types.size <= maxParamsToDisplay) ")" else ",...)") val text = KotlinBundle.message("add.constructor.parameters.from.0.1", superClass.name.asString(), parameterString) fixes.addIfNotNull(AddParametersFix.create(delegator, classOrObjectDeclaration, constructor, text)) } } } } return fixes } private class AddParenthesisFix( element: KtSuperTypeEntry, val putCaretIntoParenthesis: Boolean ) : KotlinQuickFixAction<KtSuperTypeEntry>(element), HighPriorityAction { override fun getFamilyName() = KotlinBundle.message("change.to.constructor.invocation") //TODO? override fun getText() = familyName override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val context = (element.getStrictParentOfType<KtClassOrObject>() ?: element).analyze() val baseClass = AddDefaultConstructorFix.superTypeEntryToClass(element, context) val newSpecifier = element.replaced(KtPsiFactory(project).createSuperTypeCallEntry(element.text + "()")) if (baseClass != null && baseClass.hasExpectModifier() && baseClass.secondaryConstructors.isEmpty()) { baseClass.createPrimaryConstructorIfAbsent() } if (putCaretIntoParenthesis && newSpecifier.isPhysical) { if (editor != null) { val offset = newSpecifier.valueArgumentList!!.leftParenthesis!!.endOffset editor.moveCaret(offset) if (!isUnitTestMode()) { ShowParameterInfoHandler.invoke(project, editor, file, offset - 1, null, true) } } } } } private class AddParametersFix( element: KtSuperTypeEntry, classDeclaration: KtClass, private val parametersToAdd: Collection<KtParameter>, // non-physical parameter, no pointer is necessary private val argumentText: String, @Nls private val text: String ) : KotlinQuickFixAction<KtSuperTypeEntry>(element) { private val classDeclarationPointer = classDeclaration.createSmartPointer() companion object { fun create( element: KtSuperTypeEntry, classDeclaration: KtClass, superConstructor: ConstructorDescriptor, @Nls text: String ): AddParametersFix? { val superParameters = superConstructor.valueParameters assert(superParameters.isNotEmpty()) if (superParameters.any { it.type.isError }) return null val argumentText = StringBuilder() val oldParameters = classDeclaration.primaryConstructorParameters val parametersToAdd = ArrayList<KtParameter>() for (parameter in superParameters) { val nameRendered = parameter.name.render() val varargElementType = parameter.varargElementType if (argumentText.isNotEmpty()) { argumentText.append(", ") } argumentText.append(if (varargElementType != null) "*$nameRendered" else nameRendered) val nameString = parameter.name.asString() val existingParameter = oldParameters.firstOrNull { it.name == nameString } if (existingParameter != null) { val type = (existingParameter.resolveToParameterDescriptorIfAny() as? VariableDescriptor)?.type ?: return null if (type.isSubtypeOf(parameter.type)) continue // use existing parameter } val defaultValue = if (parameter.declaresDefaultValue()) { (DescriptorToSourceUtils.descriptorToDeclaration(parameter) as? KtParameter) ?.defaultValue?.text?.let { " = $it" } ?: "" } else { "" } val parameterText = if (varargElementType != null) { "vararg " + nameRendered + ":" + IdeDescriptorRenderers.SOURCE_CODE.renderType(varargElementType) } else { nameRendered + ":" + IdeDescriptorRenderers.SOURCE_CODE.renderType(parameter.type) } + defaultValue parametersToAdd.add(KtPsiFactory(element).createParameter(parameterText)) } return AddParametersFix(element, classDeclaration, parametersToAdd, argumentText.toString(), text) } } override fun getFamilyName() = KotlinBundle.message("add.constructor.parameters.from.superclass") override fun getText() = text override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val classDeclaration = classDeclarationPointer.element ?: return val factory = KtPsiFactory(project) val typeRefsToShorten = ArrayList<KtTypeReference>() val parameterList = classDeclaration.createPrimaryConstructorParameterListIfAbsent() for (parameter in parametersToAdd) { val newParameter = parameterList.addParameter(parameter) typeRefsToShorten.add(newParameter.typeReference!!) } val delegatorCall = factory.createSuperTypeCallEntry(element.text + "(" + argumentText + ")") element.replace(delegatorCall) ShortenReferences.DEFAULT.process(typeRefsToShorten) } override fun getFileModifierForPreview(target: PsiFile): FileModifier? { val clazz = classDeclarationPointer.element ?: return null val element = element ?: return null return AddParametersFix( PsiTreeUtil.findSameElementInCopy(element, target), PsiTreeUtil.findSameElementInCopy(clazz, target), parametersToAdd, argumentText, text ) } } }
apache-2.0
86b0fdefb3e5436fb5181f0ed1672669
48.826446
158
0.654503
5.706578
false
false
false
false
AcornUI/Acorn
acornui-core/src/main/kotlin/com/acornui/Hierarchy.kt
1
9942
/* * Copyright 2019 Poly Forest, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package com.acornui import com.acornui.collection.* /** * An abstract tree node. */ interface Node { /** * Returns a read-only list of the children. */ val children: List<Node> } //------------------------------------------------ // Hierarchy traversal methods //------------------------------------------------ /** * Flags for what relative nodes to skip when traversing a hierarchy. */ enum class TreeWalk { /** * Continues iteration normally. */ CONTINUE, /** * Skips all remaining nodes, halting iteration. */ HALT, /** * Skips current node's children. */ SKIP, /** * Discards nodes not descending from current node. * This will have no effect in post-order traversal. */ ISOLATE } //------------------------------------------------- // Level order //------------------------------------------------- /** * A level-order child walk. * Traverses this parent's hierarchy from top to bottom, breadth first, invoking a callback on each node. * (including `this` receiver object). * * @param reversed If true, the last node will be added to the queue first. * @param callback The callback to invoke on each node. * @return Returns the element, if any, where [callback] returned [TreeWalk.HALT]. */ fun Node.childWalkLevelOrder(reversed: Boolean, callback: (Node) -> TreeWalk): Node? { val openList = ArrayList<Node>() openList.add(this) var found: Node? = null loop@ while (openList.isNotEmpty()) { val next = openList.shift() when (callback(next)) { TreeWalk.HALT -> { found = next break@loop } TreeWalk.SKIP -> continue@loop TreeWalk.ISOLATE -> { openList.clear() } else -> { } } if (reversed) { for (i in next.children.lastIndex downTo 0) openList.add(next.children[i]) } else openList.addAll(next.children) } return found } fun Node.childWalkLevelOrder(callback: (Node) -> TreeWalk) { childWalkLevelOrder(false, callback) } fun Node.childWalkLevelOrderReversed(callback: (Node) -> TreeWalk) { childWalkLevelOrder(true, callback) } /** * Given a callback that returns true if the descendant is found, this method will return the first descendant with * the matching condition. * The tree traversal will be level-order. */ fun Node.findChildLevelOrder(reversed: Boolean, callback: Filter<Node>): Node? { return childWalkLevelOrder(reversed) { if (callback(it)) TreeWalk.HALT else TreeWalk.CONTINUE } } fun Node.findChildLevelOrder(callback: Filter<Node>): Node? { return findChildLevelOrder(reversed = false, callback = callback) } fun Node.findLastChildLevelOrder(callback: Filter<Node>): Node? { return findChildLevelOrder(reversed = true, callback = callback) } //------------------------------------------------- // Pre-order //------------------------------------------------- /** * A pre-order child walk. * * @param callback The callback to invoke on each child. * @return Returns the node, if any, where [callback] returned [TreeWalk.HALT] */ fun Node.childWalkPreorder(reversed: Boolean, callback: (Node) -> TreeWalk): Node? { val openList = ArrayList<Node>() openList.add(this) var found: Node? = null loop@ while (openList.isNotEmpty()) { val next = openList.pop() when (callback(next)) { TreeWalk.HALT -> { found = next break@loop } TreeWalk.SKIP -> continue@loop TreeWalk.ISOLATE -> { openList.clear() } else -> { } } if (reversed) { openList.addAll(next.children) } else for (i in next.children.lastIndex downTo 0) openList.add(next.children[i]) } return found } fun Node.childWalkPreorder(callback: (Node) -> TreeWalk) { childWalkPreorder(false, callback) } fun Node.childWalkPreorderReversed(callback: (Node) -> TreeWalk) { childWalkPreorder(true, callback) } /** * Given a callback that returns true if the descendant is found, this method will return the first descendant with * the matching condition. * The tree traversal will be pre-order. */ fun Node.findChildPreOrder(reversed: Boolean, callback: Filter<Node>): Node? { return childWalkPreorder(reversed) { if (callback(it)) TreeWalk.HALT else TreeWalk.CONTINUE } } fun Node.findChildPreOrder(callback: Filter<Node>): Node? { return findChildPreOrder(reversed = false, callback = callback) } fun Node.findLastChildPreOrder(callback: Filter<Node>): Node? { return findChildPreOrder(reversed = true, callback = callback) } /** * Starting from this Node as the root, walks down the left side until the end, returning that child. */ fun Node.leftDescendant(): Node { if (children.isEmpty()) return this return children.first().leftDescendant() } /** * Starting from this Node as the root, walks down the right side until the end, returning that child. */ fun Node.rightDescendant(): Node { if (children.isEmpty()) return this return children.last().rightDescendant() } interface NodeWithParent : Node { val parent: NodeWithParent? } fun NodeWithParent.previousSibling(): Node? { val p = parent ?: return null val c = p.children val index = c.indexOf(this) if (index == 0) return null return c[index - 1] } fun NodeWithParent.nextSibling(): Node? { val p = parent ?: return null val c = p.children val index = c.indexOf(this) if (index == c.lastIndex) return null return c[index + 1] } /** * Returns the lineage count. 0 if this child is the root, 1 if the root is the parent, * 2 if the root is the grandparent, 3 if the root is the great grandparent, and so on. */ fun NodeWithParent.ancestryCount(): Int { var count = 0 var p = parent while (p != null) { count++ p = p.parent } return count } inline fun NodeWithParent.ancestorWalk(callback: (NodeWithParent) -> Unit): Node? { var p: NodeWithParent? = this while (p != null) { callback(p) p = p.parent } return null } /** * Walks the ancestry chain on the display graph, returning the first element where the predicate returns true. * * @param predicate The ancestor (starting with `this`) is passed to this function, if true is returned, the ancestry * walk will stop and that ancestor will be returned. * @return Returns the first ancestor where [predicate] returns true. */ inline fun NodeWithParent.findAncestor(predicate: Filter<Node>): Node? { var p: NodeWithParent? = this while (p != null) { val found = predicate(p) if (found) return p p = p.parent } return null } /** * Walks the ancestry chain on the display graph, returning the child of the ancestor where [predicate] returned true. * * @param predicate The ancestor (starting with `parent`) is passed to this function, if true is returned, the ancestry * walk will stop and the child of that ancestor is returned. */ inline fun NodeWithParent.findAncestorBefore(predicate: Filter<Node>): Node? { var c = this var p: NodeWithParent? = parent while (p != null) { val found = predicate(p) if (found) return c c = p p = p.parent } return null } /** * Populates an ArrayList with a ChildRo's ancestry. * @return Returns the [out] ArrayList */ fun NodeWithParent.ancestry(): List<NodeWithParent> { val out = ArrayList<NodeWithParent>() ancestorWalk { out.add(it) } return out } fun NodeWithParent.root(): NodeWithParent { var root: NodeWithParent = this var p: NodeWithParent? = this while (p != null) { root = p p = p.parent } return root } /** * Returns the lowest common ancestor if there is one between the two children. */ fun NodeWithParent.lowestCommonAncestor(other: NodeWithParent): NodeWithParent? { val ancestry1 = ancestry() val ancestry2 = other.ancestry() return ancestry1.firstOrNull { ancestry2.contains(it) } } /** * Returns true if this node is before the [other] node. This considers the parent to come before the child. * Returns null if there is no common ancestor. */ fun NodeWithParent.isBefore(other: NodeWithParent): Boolean? { if (this === other) throw Exception("this === other") var a = this ancestorWalk { parentA -> var b = this other.ancestorWalk { parentB -> if (parentA === parentB) { val children = parentA.children val indexA = children.indexOf(a) val indexB = children.indexOf(b) return indexA < indexB } b = parentB } a = parentA } return null } /** * Returns true if this ChildRo is after the [other] ChildRo. This considers the parent to come before the child. * @throws Exception If [other] does not have a common ancestor. */ fun NodeWithParent.isAfter(other: NodeWithParent): Boolean { if (this === other) throw Exception("this === other") var a = this ancestorWalk { parentA -> var b = this other.ancestorWalk { parentB -> if (parentA === parentB) { val children = parentA.children val indexA = children.indexOf(a) val indexB = children.indexOf(b) return indexA > indexB } b = parentB } a = parentA } throw Exception("No common withAncestor") } /** * Returns true if this [Node] is the ancestor of the given [child]. * X is considered to be an ancestor of Y if doing a parent walk starting from Y, X is then reached. * This will return true if X === Y */ fun NodeWithParent.isAncestorOf(child: NodeWithParent): Boolean { return child.findAncestor { it === this } != null } fun NodeWithParent.isDescendantOf(ancestor: NodeWithParent): Boolean = ancestor.isAncestorOf(this)
apache-2.0
0a70d1df1bc3006fe0ba257b8e2a7297
25.026178
119
0.681251
3.508116
false
false
false
false
android/architecture-components-samples
WorkManagerSample/app/src/main/java/com/example/background/SelectImageActivity.kt
1
6964
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.background import android.Manifest import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.text.Html import android.text.Spanned import android.text.method.LinkMovementMethod import android.util.Log import android.view.View import androidx.annotation.VisibleForTesting import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.example.background.databinding.ActivitySelectBinding import com.google.android.material.snackbar.Snackbar import java.util.ArrayList /** * Helps select an image for the [FilterActivity] and handles permission requests. * * There are two sources for the images: [MediaStore] and [StockImages]. */ class SelectImageActivity : AppCompatActivity() { private var permissionRequestCount = 0 private var hasPermissions = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivitySelectBinding.inflate(layoutInflater).apply { setContentView(root) } with(binding) { // Show stock image credits. credits.text = fromHtml(getString(R.string.credits)) // Enable link following. credits.movementMethod = LinkMovementMethod.getInstance() } // We keep track of the number of times we requested for permissions. // If the user did not want to grant permissions twice - show a Snackbar and don't // ask for permissions again for the rest of the session. if (savedInstanceState != null) { permissionRequestCount = savedInstanceState.getInt(KEY_PERMISSIONS_REQUEST_COUNT, 0) } requestPermissionsIfNecessary() binding.selectImage.setOnClickListener { val chooseIntent = Intent( Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI ) startActivityForResult(chooseIntent, REQUEST_CODE_IMAGE) } binding.selectStockImage.setOnClickListener { startActivity( FilterActivity.newIntent( this@SelectImageActivity, StockImages.randomStockImage() ) ) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(KEY_PERMISSIONS_REQUEST_COUNT, permissionRequestCount) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK && data != null) { when (requestCode) { REQUEST_CODE_IMAGE -> handleImageRequestResult(data) else -> Log.d(TAG, "Unknown request code.") } } else { Log.e(TAG, String.format("Unexpected Result code \"%s\" or missing data.", resultCode)) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) // Check if permissions were granted after a permissions request flow. if (requestCode == REQUEST_CODE_PERMISSIONS) { requestPermissionsIfNecessary() // no-op if permissions are granted already. } } private fun requestPermissionsIfNecessary() { // Check to see if we have all the permissions we need. // Otherwise request permissions up to MAX_NUMBER_REQUESTED_PERMISSIONS. hasPermissions = checkAllPermissions() if (!hasPermissions) { if (permissionRequestCount < MAX_NUMBER_REQUEST_PERMISSIONS) { permissionRequestCount += 1 ActivityCompat.requestPermissions( this, sPermissions.toTypedArray(), REQUEST_CODE_PERMISSIONS ) } else { Snackbar.make( findViewById(R.id.coordinatorLayout), R.string.set_permissions_in_settings, Snackbar.LENGTH_INDEFINITE ).show() findViewById<View>(R.id.selectImage).isEnabled = false } } } private fun handleImageRequestResult(data: Intent) { // Get the imageUri the user picked, from the Intent.ACTION_PICK result. val imageUri = data.clipData!!.getItemAt(0).uri if (imageUri == null) { Log.e(TAG, "Invalid input image Uri.") return } startActivity(FilterActivity.newIntent(this, imageUri)) } private fun checkAllPermissions(): Boolean { var hasPermissions = true for (permission in sPermissions) { hasPermissions = hasPermissions and (ContextCompat.checkSelfPermission( this, permission ) == PackageManager.PERMISSION_GRANTED) } return hasPermissions } companion object { private const val TAG = "SelectImageActivity" private const val KEY_PERMISSIONS_REQUEST_COUNT = "KEY_PERMISSIONS_REQUEST_COUNT" private const val MAX_NUMBER_REQUEST_PERMISSIONS = 2 private const val REQUEST_CODE_IMAGE = 100 private const val REQUEST_CODE_PERMISSIONS = 101 // A list of permissions the application needs. @VisibleForTesting val sPermissions: MutableList<String> = object : ArrayList<String>() { init { add(Manifest.permission.INTERNET) add(Manifest.permission.WRITE_EXTERNAL_STORAGE) add(Manifest.permission.READ_EXTERNAL_STORAGE) } } private fun fromHtml(input: String): Spanned { return if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) { Html.fromHtml(input, Html.FROM_HTML_MODE_COMPACT) } else { // method deprecated at API 24. @Suppress("DEPRECATION") Html.fromHtml(input) } } } }
apache-2.0
1baeab543e4ff2c149bc8836e3e4bc3a
35.270833
99
0.645319
5.105572
false
false
false
false
kelsos/mbrc
app/src/main/kotlin/com/kelsos/mbrc/repository/data/LocalAlbumDataSource.kt
1
4784
package com.kelsos.mbrc.repository.data import com.kelsos.mbrc.data.CoverInfo import com.kelsos.mbrc.data.db.RemoteDatabase import com.kelsos.mbrc.data.library.Album import com.kelsos.mbrc.data.library.Album_Table import com.kelsos.mbrc.data.library.Track import com.kelsos.mbrc.data.library.Track_Table import com.kelsos.mbrc.di.modules.AppDispatchers import com.kelsos.mbrc.extensions.escapeLike import com.raizlabs.android.dbflow.kotlinextensions.database import com.raizlabs.android.dbflow.kotlinextensions.delete import com.raizlabs.android.dbflow.kotlinextensions.from import com.raizlabs.android.dbflow.kotlinextensions.innerJoin import com.raizlabs.android.dbflow.kotlinextensions.modelAdapter import com.raizlabs.android.dbflow.kotlinextensions.on import com.raizlabs.android.dbflow.kotlinextensions.select import com.raizlabs.android.dbflow.kotlinextensions.where import com.raizlabs.android.dbflow.list.FlowCursorList import com.raizlabs.android.dbflow.sql.language.OperatorGroup.clause import com.raizlabs.android.dbflow.sql.language.SQLite import com.raizlabs.android.dbflow.structure.database.transaction.FastStoreModelTransaction import kotlinx.coroutines.withContext import javax.inject.Inject class LocalAlbumDataSource @Inject constructor( private val dispatchers: AppDispatchers ) : LocalDataSource<Album> { override suspend fun deleteAll() = withContext(dispatchers.db) { delete(Album::class).execute() } override suspend fun saveAll(list: List<Album>) = withContext(dispatchers.db) { val adapter = modelAdapter<Album>() val updated = list.filter { it.id > 0 } val inserted = list.filter { it.id <= 0 } val transaction = FastStoreModelTransaction.insertBuilder(adapter) .addAll(inserted) .build() val updateTransaction = FastStoreModelTransaction.updateBuilder(adapter) .addAll(updated) .build() database<RemoteDatabase>().executeTransaction(transaction) database<RemoteDatabase>().executeTransaction(updateTransaction) } override suspend fun loadAllCursor(): FlowCursorList<Album> = withContext(dispatchers.db) { val query = (select from Album::class) .orderBy(Album_Table.artist, true) .orderBy(Album_Table.album, true) return@withContext FlowCursorList.Builder(Album::class.java).modelQueriable(query).build() } suspend fun getAlbumsByArtist(artist: String): FlowCursorList<Album> = withContext(dispatchers.db) { val selectAlbum = SQLite.select(Album_Table.album.withTable(), Album_Table.artist.withTable()).distinct() val artistOrAlbumArtist = clause(Track_Table.artist.withTable().`is`(artist)) .or(Track_Table.album_artist.withTable().`is`(artist)) val columns = clause(Track_Table.album.withTable().eq(Album_Table.album.withTable())) .and(Track_Table.album_artist.withTable().eq(Album_Table.artist.withTable())) val query = (selectAlbum from Album::class innerJoin Track::class on columns where artistOrAlbumArtist) .orderBy(Album_Table.artist.withTable(), true) .orderBy(Album_Table.album.withTable(), true) return@withContext FlowCursorList.Builder(Album::class.java).modelQueriable(query).build() } override suspend fun search(term: String): FlowCursorList<Album> = withContext(dispatchers.db) { val query = (select from Album::class where Album_Table.album.like("%${term.escapeLike()}%")) return@withContext FlowCursorList.Builder(Album::class.java).modelQueriable(query).build() } override suspend fun isEmpty(): Boolean = withContext(dispatchers.db) { return@withContext SQLite.selectCountOf().from(Album::class.java).longValue() == 0L } override suspend fun count(): Long = withContext(dispatchers.db) { return@withContext SQLite.selectCountOf().from(Album::class.java).longValue() } suspend fun updateCovers(updated: List<CoverInfo>) { withContext(dispatchers.db) { val albums = (select from Album::class) .orderBy(Album_Table.artist, true) .orderBy(Album_Table.album, true) .queryList() for ((artist, album, hash) in updated) { val cachedAlbum = albums.find { it.album == album && it.artist == artist } cachedAlbum?.cover = hash } val adapter = modelAdapter<Album>() val transaction = FastStoreModelTransaction.updateBuilder(adapter) .addAll(albums) .build() database<RemoteDatabase>().executeTransaction(transaction) } } override suspend fun removePreviousEntries(epoch: Long) { withContext(dispatchers.db) { SQLite.delete() .from(Album::class.java) .where(clause(Album_Table.date_added.lessThan(epoch)).or(Album_Table.date_added.isNull)) .execute() } } }
gpl-3.0
5da63dc68a2e9a9dc57f98cd2dd929b0
39.201681
98
0.737249
4.200176
false
false
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/codeVision/CodeVisionProviderBase.kt
1
3830
// 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.codeInsight.hints.codeVision import com.intellij.codeInsight.codeVision.* import com.intellij.codeInsight.codeVision.ui.model.ClickableTextCodeVisionEntry import com.intellij.codeInsight.hints.InlayHintsUtils import com.intellij.codeInsight.hints.settings.language.isInlaySettingsEditor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.roots.ProjectFileIndex import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.SmartPointerManager import com.intellij.psi.SyntaxTraverser import java.awt.event.MouseEvent abstract class CodeVisionProviderBase : DaemonBoundCodeVisionProvider { /** * WARNING! This method is executed also before the file is open. It must be fast! During it users see no editor. * @return true iff this provider may provide lenses for this file. */ abstract fun acceptsFile(file: PsiFile): Boolean /** * WARNING! This method is executed also before the file is open. It must be fast! During it users see no editor. * @return true iff this provider may provide lenses for this element. */ abstract fun acceptsElement(element: PsiElement): Boolean /** * @return text that user sees for a given element as a code lens */ abstract fun getHint(element: PsiElement, file: PsiFile): String? open fun logClickToFUS(element: PsiElement) {} override fun computeForEditor(editor: Editor, file: PsiFile): List<Pair<TextRange, CodeVisionEntry>> { if (!acceptsFile(file)) return emptyList() // we want to let this provider work only in tests dedicated for code vision, otherwise they harm performance if (ApplicationManager.getApplication().isUnitTestMode && !CodeVisionHost.isCodeLensTest(editor)) return emptyList() val virtualFile = file.virtualFile ?: return emptyList() if (ProjectFileIndex.getInstance(file.project).isInLibrarySource(virtualFile)) return emptyList() val lenses = ArrayList<Pair<TextRange, CodeVisionEntry>>() val traverser = SyntaxTraverser.psiTraverser(file) for (element in traverser) { if (!acceptsElement(element)) continue if (!InlayHintsUtils.isFirstInLine(element)) continue val hint = getHint(element, file) if (hint == null) continue val handler = ClickHandler(element) val range = InlayHintsUtils.getTextRangeWithoutLeadingCommentsAndWhitespaces(element) lenses.add(range to ClickableTextCodeVisionEntry(hint, id, handler)) } return lenses } private inner class ClickHandler( element: PsiElement ) : (MouseEvent?, Editor) -> Unit { private val elementPointer = SmartPointerManager.createPointer(element) override fun invoke(event: MouseEvent?, editor: Editor) { if (isInlaySettingsEditor(editor)) return val element = elementPointer.element ?: return logClickToFUS(element) handleClick(editor, element, event) } } abstract fun handleClick(editor: Editor, element: PsiElement, event: MouseEvent?) override fun getPlaceholderCollector(editor: Editor, psiFile: PsiFile?): CodeVisionPlaceholderCollector? { if (psiFile == null || !acceptsFile(psiFile)) return null return object: BypassBasedPlaceholderCollector { override fun collectPlaceholders(element: PsiElement, editor: Editor): List<TextRange> { if (!acceptsElement(element)) return emptyList() val range = InlayHintsUtils.getTextRangeWithoutLeadingCommentsAndWhitespaces(element) return listOf(range) } } } override val defaultAnchor: CodeVisionAnchorKind get() = CodeVisionAnchorKind.Default }
apache-2.0
9d8df97f53dfaf94b7ba74e39b33caea
41.566667
120
0.759791
4.745973
false
false
false
false
GunoH/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/sorting/MLSorter.kt
2
15506
// Copyright 2000-2022 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.completion.ml.sorting import com.intellij.codeInsight.completion.CompletionFinalSorter import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.ml.MLRankingIgnorable import com.intellij.codeInsight.lookup.LookupElement import com.intellij.codeInsight.lookup.LookupElementDecorator import com.intellij.codeInsight.lookup.LookupManager import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.completion.ml.features.RankingFeaturesOverrides import com.intellij.completion.ml.performance.MLCompletionPerformanceTracker import com.intellij.completion.ml.personalization.session.SessionFactorsUtils import com.intellij.completion.ml.settings.CompletionMLRankingSettings import com.intellij.completion.ml.storage.MutableLookupStorage import com.intellij.completion.ml.util.RelevanceUtil import com.intellij.completion.ml.util.prefix import com.intellij.completion.ml.util.queryLength import com.intellij.internal.ml.completion.DecoratingItemsPolicy import com.intellij.lang.Language import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Pair import com.intellij.openapi.util.registry.Registry import com.intellij.textMatching.PrefixMatchingUtil import java.util.* import java.util.concurrent.TimeUnit class MLSorterFactory : CompletionFinalSorter.Factory { override fun newSorter() = MLSorter() } class MLSorter : CompletionFinalSorter() { private companion object { private val LOG = logger<MLSorter>() private const val REORDER_ONLY_TOP_K = 5 } private val cachedScore: MutableMap<LookupElement, ItemRankInfo> = IdentityHashMap() private val reorderOnlyTopItems: Boolean = Registry.`is`("completion.ml.reorder.only.top.items", true) override fun getRelevanceObjects(items: MutableIterable<LookupElement>): Map<LookupElement, List<Pair<String, Any>>> { if (cachedScore.isEmpty()) { return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.NONE as Any)) } } if (hasUnknownFeatures(items)) { return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.UNDEFINED as Any)) } } if (!isCacheValid(items)) { return items.associate { it to listOf(Pair.create(FeatureUtils.ML_RANK, FeatureUtils.INVALID_CACHE as Any)) } } return items.associate { val result = mutableListOf<Pair<String, Any>>() val cached = cachedScore[it] if (cached != null) { result.add(Pair.create(FeatureUtils.ML_RANK, cached.mlRank)) result.add(Pair.create(FeatureUtils.BEFORE_ORDER, cached.positionBefore)) } it to result } } private fun isCacheValid(items: Iterable<LookupElement>): Boolean { return items.map { cachedScore[it]?.prefixLength }.toSet().size == 1 } private fun hasUnknownFeatures(items: Iterable<LookupElement>) = items.any { val score = cachedScore[it] score?.mlRank == null } override fun sort(items: MutableIterable<LookupElement>, parameters: CompletionParameters): Iterable<LookupElement?> { val lookup = LookupManager.getActiveLookup(parameters.editor) as? LookupImpl ?: return items val lookupStorage = MutableLookupStorage.get(lookup) ?: return items // Do nothing if unable to reorder items or to log the weights if (!lookupStorage.shouldComputeFeatures()) return items val startedTimestamp = System.currentTimeMillis() val queryLength = lookup.queryLength() val prefix = lookup.prefix() val positionsBefore = items.withIndex().associate { it.value to it.index } val elements = positionsBefore.keys.toList() val element2score = HashMap<LookupElement, Double?>(elements.size) tryFillFromCache(element2score, elements, queryLength) val itemsForScoring = if (element2score.size == elements.size) emptyList() else elements calculateScores(element2score, itemsForScoring, positionsBefore, queryLength, prefix, lookup, lookupStorage, parameters) val finalRanking = sortByMlScores(elements, element2score, positionsBefore, lookupStorage, lookup) lookupStorage.performanceTracker.sortingPerformed(itemsForScoring.size, System.currentTimeMillis() - startedTimestamp) LOG.assertTrue(elements.size == finalRanking.size, "MLSorter shouldn't filter items") return finalRanking } private fun tryFillFromCache(element2score: MutableMap<LookupElement, Double?>, items: List<LookupElement>, queryLength: Int) { for ((position, element) in items.withIndex()) { val cachedInfo = getCachedRankInfo(element, queryLength, position) if (cachedInfo == null) return element2score[element] = cachedInfo.mlRank } } private fun calculateScores(element2score: MutableMap<LookupElement, Double?>, items: List<LookupElement>, positionsBefore: Map<LookupElement, Int>, queryLength: Int, prefix: String, lookup: LookupImpl, lookupStorage: MutableLookupStorage, parameters: CompletionParameters) { if (items.isEmpty()) return val rankingModel = lookupStorage.model lookupStorage.initUserFactors(lookup.project) val meaningfulRelevanceExtractor = MeaningfulFeaturesExtractor() val relevanceObjects = lookup.getRelevanceObjects(items, false) val calculatedElementFeatures = mutableListOf<ElementFeatures>() for (element in items) { val position = positionsBefore.getValue(element) val (relevance, additional) = RelevanceUtil.asRelevanceMaps(relevanceObjects.getOrDefault(element, emptyList())) SessionFactorsUtils.saveElementFactorsTo(additional, lookupStorage, element) calculateAdditionalFeaturesTo(additional, element, queryLength, prefix.length, position, items.size, parameters) lookupStorage.performanceTracker.trackElementFeaturesCalculation(PrefixMatchingUtil.baseName) { PrefixMatchingUtil.calculateFeatures(element.lookupString, prefix, additional) } meaningfulRelevanceExtractor.processFeatures(relevance) calculatedElementFeatures.add(ElementFeatures(relevance, additional)) } val lookupFeatures = mutableMapOf<String, Any>() for (elementFeatureProvider in LookupFeatureProvider.forLanguage(lookupStorage.language)) { val features = elementFeatureProvider.calculateFeatures(calculatedElementFeatures) lookupFeatures.putAll(features) } val commonSessionFactors = SessionFactorsUtils.updateSessionFactors(lookupStorage, items) val meaningfulRelevance = meaningfulRelevanceExtractor.meaningfulFeatures() val features = RankingFeatures(lookupStorage.userFactors, lookupStorage.contextFactors, commonSessionFactors, lookupFeatures, meaningfulRelevance) val tracker = ModelTimeTracker() for ((i, element) in items.withIndex()) { val (relevance, additional) = overrideElementFeaturesIfNeeded(calculatedElementFeatures[i], lookupStorage.language) val score = tracker.measure { val position = positionsBefore.getValue(element) val elementFeatures = features.withElementFeatures(relevance, additional) return@measure calculateElementScore(rankingModel, element, position, elementFeatures, queryLength) } element2score[element] = score additional.putAll(relevance) lookupStorage.fireElementScored(element, additional, score) } tracker.finished(lookupStorage.performanceTracker) } private fun overrideElementFeaturesIfNeeded(elementFeatures: ElementFeatures, language: Language): ElementFeatures { for (it in RankingFeaturesOverrides.forLanguage(language)) { val overrides = it.getMlElementFeaturesOverrides(elementFeatures.additional) elementFeatures.additional.putAll(overrides) if (overrides.isNotEmpty()) LOG.debug("The next ML features was overridden: [${overrides.map { it.key }.joinToString()}]") val relevanceOverrides = it.getDefaultWeigherFeaturesOverrides(elementFeatures.relevance) elementFeatures.relevance.putAll(relevanceOverrides) if (relevanceOverrides.isNotEmpty()) LOG.debug("The next default weigher features was overridden: [${relevanceOverrides.map { it.key }.joinToString()}]") } return elementFeatures } private fun sortByMlScores(items: List<LookupElement>, element2score: Map<LookupElement, Double?>, positionsBefore: Map<LookupElement, Int>, lookupStorage: MutableLookupStorage, lookup: LookupImpl): List<LookupElement> { val shouldSort = element2score.values.none { it == null } && lookupStorage.shouldReRank() if (LOG.isDebugEnabled) { LOG.debug("ML sorting in completion used=$shouldSort for language=${lookupStorage.language.id}") } if (shouldSort) { lookupStorage.fireReorderedUsingMLScores() val decoratingItemsPolicy = lookupStorage.model?.decoratingPolicy() ?: DecoratingItemsPolicy.DISABLED val topItemsCount = if (reorderOnlyTopItems) REORDER_ONLY_TOP_K else Int.MAX_VALUE return items .filter { !it.isIgnored() } .reorderByMLScores(element2score, topItemsCount) .insertIgnoredItems(items) .markRelevantItemsIfNeeded(element2score, lookup, decoratingItemsPolicy) .addDiagnosticsIfNeeded(positionsBefore, topItemsCount, lookup) } return items } private fun calculateAdditionalFeaturesTo( additionalMap: MutableMap<String, Any>, lookupElement: LookupElement, oldQueryLength: Int, prefixLength: Int, position: Int, itemsCount: Int, parameters: CompletionParameters) { additionalMap["position"] = position additionalMap["relative_position"] = position.toDouble() / itemsCount additionalMap["query_length"] = oldQueryLength // old version of prefix_length feature additionalMap["prefix_length"] = prefixLength additionalMap["result_length"] = lookupElement.lookupString.length additionalMap["auto_popup"] = parameters.isAutoPopup additionalMap["completion_type"] = parameters.completionType.toString() additionalMap["invocation_count"] = parameters.invocationCount } private fun Iterable<LookupElement>.reorderByMLScores(element2score: Map<LookupElement, Double?>, toReorder: Int): Iterable<LookupElement> { val result = this .sortedByDescending { element2score.getValue(it) } .removeDuplicatesIfNeeded() .take(toReorder) .toCollection(linkedSetOf()) result.addAll(this) return result } private fun Iterable<LookupElement>.insertIgnoredItems(allItems: Iterable<LookupElement>): List<LookupElement> { val sortedItems = this.iterator() return allItems.mapNotNull { item -> when { item.isIgnored() -> item sortedItems.hasNext() -> sortedItems.next() else -> null } } } private fun Iterable<LookupElement>.removeDuplicatesIfNeeded(): Iterable<LookupElement> = if (Registry.`is`("completion.ml.reorder.without.duplicates", false)) this.distinctBy { it.lookupString } else this private fun List<LookupElement>.addDiagnosticsIfNeeded(positionsBefore: Map<LookupElement, Int>, reordered: Int, lookup: LookupImpl): List<LookupElement> { if (CompletionMLRankingSettings.getInstance().isShowDiffEnabled) { var positionChanged = false this.forEachIndexed { position, element -> val before = positionsBefore.getValue(element) if (before < reordered || position < reordered) { val diff = position - before positionChanged = positionChanged || diff != 0 ItemsDecoratorInitializer.itemPositionChanged(element, diff) } } ItemsDecoratorInitializer.markAsReordered(lookup, positionChanged) } return this } private fun List<LookupElement>.markRelevantItemsIfNeeded(element2score: Map<LookupElement, Double?>, lookup: LookupImpl, decoratingItemsPolicy: DecoratingItemsPolicy): List<LookupElement> { if (CompletionMLRankingSettings.getInstance().isDecorateRelevantEnabled) { val relevantItems = decoratingItemsPolicy.itemsToDecorate(this.map { element2score[it] ?: 0.0 }) for (index in relevantItems) { ItemsDecoratorInitializer.markAsRelevant(lookup, this.elementAt(index)) } } return this } private fun getCachedRankInfo(element: LookupElement, prefixLength: Int, position: Int): ItemRankInfo? { val cached = cachedScore[element] if (cached != null && prefixLength == cached.prefixLength && cached.positionBefore == position) { return cached } return null } /** * Null means we encountered unknown features and are unable to score */ private fun calculateElementScore(ranker: RankingModelWrapper?, element: LookupElement, position: Int, features: RankingFeatures, prefixLength: Int): Double? { val mlRank: Double? = if (ranker != null && ranker.canScore(features)) ranker.score(features) else null val info = ItemRankInfo(position, mlRank, prefixLength) cachedScore[element] = info return info.mlRank } private fun LookupElement.isIgnored(): Boolean { if (this is MLRankingIgnorable) return true var item: LookupElement = this while (item is LookupElementDecorator<*>) { item = item.delegate if (item is MLRankingIgnorable) return true } return false } /** * Extracts features that have different values */ private class MeaningfulFeaturesExtractor { private val meaningful = mutableSetOf<String>() private val values = mutableMapOf<String, Any>() fun processFeatures(features: Map<String, Any>) { for (feature in features) { when (values[feature.key]) { null -> values[feature.key] = feature.value feature.value -> Unit else -> meaningful.add(feature.key) } } } fun meaningfulFeatures(): Set<String> = meaningful } /* * Measures time on getting predictions from the ML model */ private class ModelTimeTracker { private var itemsScored: Int = 0 private var timeSpent: Long = 0L fun measure(scoringFun: () -> Double?): Double? { val start = System.nanoTime() val result = scoringFun.invoke() if (result != null) { itemsScored += 1 timeSpent += System.nanoTime() - start } return result } fun finished(performanceTracker: MLCompletionPerformanceTracker) { if (itemsScored != 0) { performanceTracker.itemsScored(itemsScored, TimeUnit.NANOSECONDS.toMillis(timeSpent)) } } } } private data class ItemRankInfo(val positionBefore: Int, val mlRank: Double?, val prefixLength: Int)
apache-2.0
c437e40bd6081431f62630cfb7061587
41.834254
142
0.704824
4.805082
false
false
false
false
jk1/intellij-community
platform/platform-tests/testSrc/com/intellij/ui/SvgRenderer.kt
2
6540
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui import com.intellij.icons.AllIcons import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.StringUtilRt import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.util.ui.LafIconLookup import gnu.trove.THashMap import org.apache.batik.anim.dom.SVGDOMImplementation import org.apache.batik.dom.GenericDOMImplementation import org.apache.batik.svggen.* import org.w3c.dom.Element import java.awt.Component import java.awt.GraphicsConfiguration import java.awt.Image import java.io.StringWriter import java.nio.file.Path import java.nio.file.Paths import javax.swing.Icon import javax.xml.transform.OutputKeys import javax.xml.transform.TransformerFactory import javax.xml.transform.dom.DOMSource import javax.xml.transform.stream.StreamResult // jFreeSvg produces not so compact and readable SVG as batik internal class SvgRenderer(val svgFileDir: Path, private val deviceConfiguration: GraphicsConfiguration) { private val xmlTransformer = TransformerFactory.newInstance().newTransformer() private val xmlFactory = GenericDOMImplementation.getDOMImplementation().createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null) private val context = SVGGeneratorContext.createDefault(xmlFactory) init { xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml") xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes") xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2") xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8") xmlTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes") context.imageHandler = object : ImageHandlerBase64Encoder() { override fun handleImage(image: Image, imageElement: Element, generatorContext: SVGGeneratorContext) { imageElement.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", findImagePath(image)) } private fun findImagePath(image: Image): String { fun isImage(iconWrapper: Icon): Boolean { if (iconWrapper === AllIcons.Actions.Stub) { return false } val thatImage = (iconWrapper as IconLoader.CachedImageIcon).doGetRealIcon()?.image return thatImage === image } for (name in arrayOf("checkBox", "radio", "gear", "spinnerRight")) { val iconWrapper = when (name) { "gear" -> IconLoader.getIcon("/general/gear.png") else -> LafIconLookup.findIcon(name) } ?: continue if (isImage(iconWrapper)) { return getIconRelativePath(iconWrapper.toString()) } } for (name in arrayOf("checkBox", "radio")) { val iconWrapper = LafIconLookup.findIcon(name, selected = true) ?: continue if (isImage(iconWrapper)) { return getIconRelativePath(iconWrapper.toString()) } } throw RuntimeException("unknown image") } } context.errorHandler = object: ErrorHandler { override fun handleError(error: SVGGraphics2DIOException) = throw error override fun handleError(error: SVGGraphics2DRuntimeException) = throw error } class PrefixInfo { var currentId = 0 } context.idGenerator = object : SVGIDGenerator() { private val prefixMap = THashMap<String, PrefixInfo>() override fun generateID(prefix: String): String { val info = prefixMap.getOrPut(prefix) { PrefixInfo() } return "${if (prefix == "clipPath") "" else prefix}${info.currentId++}" } } } private fun getIconRelativePath(outputPath: String): String { for ((moduleName, relativePath) in mapOf("intellij.platform.icons" to "platform/icons/src", "intellij.platform.ide.impl" to "platform/platform-impl/src")) { val index = outputPath.indexOf(moduleName) if (index > 0) { val iconPath = Paths.get(PathManagerEx.getCommunityHomePath(), relativePath, outputPath.substring(index + moduleName.length + 1 /* slash */)) assertThat(iconPath).exists() return FileUtilRt.toSystemIndependentName(svgFileDir.relativize(iconPath).toString()) } } throw RuntimeException("unknown icon location ($outputPath)") } // CSS (style) not used - attributes more readable and shorter // separate styles (in the defs) also not suitable, so, we keep it simple as is private fun svgGraphicsToString(svgGenerator: SVGGraphics2D, component: Component): String { val writer = StringWriter() writer.use { val root = svgGenerator.root root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", SVGSyntax.SVG_NAMESPACE_URI) root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink") root.setAttributeNS(null, "viewBox", "0 0 ${component.width} ${component.height}") xmlTransformer.transform(DOMSource(root), StreamResult(writer)) } // xlink is not used in some files and optimize imports on commit can modify file, so, as simple solution, disable inspection val result = "<!--suppress XmlUnusedNamespaceDeclaration -->\n" + writer .toString() // &#27;Remember // no idea why transformer/batik doesn't escape it correctly .replace(">&#27;", ">&amp;") return if (SystemInfoRt.isWindows) StringUtilRt.convertLineSeparators(result) else result } fun render(component: Component): String { val svgGenerator = SvgGraphics2dWithDeviceConfiguration(context, deviceConfiguration) component.paint(svgGenerator) return svgGraphicsToString(svgGenerator, component) } } private class SvgGraphics2dWithDeviceConfiguration : SVGGraphics2D { private val _deviceConfiguration: GraphicsConfiguration constructor(context: SVGGeneratorContext, _deviceConfiguration: GraphicsConfiguration) : super(context, false) { this._deviceConfiguration = _deviceConfiguration } private constructor(g: SvgGraphics2dWithDeviceConfiguration): super(g) { this._deviceConfiguration = g._deviceConfiguration } override fun getDeviceConfiguration() = _deviceConfiguration override fun create() = SvgGraphics2dWithDeviceConfiguration(this) }
apache-2.0
bc984c78b00eb200c99f7005b468d9ae
40.929487
149
0.721254
4.395161
false
true
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/cache/CoverCache.kt
2
3150
package eu.kanade.tachiyomi.data.cache import android.content.Context import coil.imageLoader import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.util.storage.DiskUtil import java.io.File import java.io.IOException import java.io.InputStream /** * Class used to create cover cache. * It is used to store the covers of the library. * Makes use of Glide (which can avoid repeating requests) to download covers. * Names of files are created with the md5 of the thumbnail URL. * * @param context the application context. * @constructor creates an instance of the cover cache. */ class CoverCache(private val context: Context) { companion object { private const val COVERS_DIR = "covers" private const val CUSTOM_COVERS_DIR = "covers/custom" } /** * Cache directory used for cache management. */ private val cacheDir = getCacheDir(COVERS_DIR) private val customCoverCacheDir = getCacheDir(CUSTOM_COVERS_DIR) /** * Returns the cover from cache. * * @param manga the manga. * @return cover image. */ fun getCoverFile(manga: Manga): File? { return manga.thumbnail_url?.let { File(cacheDir, DiskUtil.hashKeyForDisk(it)) } } /** * Returns the custom cover from cache. * * @param manga the manga. * @return cover image. */ fun getCustomCoverFile(manga: Manga): File { return File(customCoverCacheDir, DiskUtil.hashKeyForDisk(manga.id.toString())) } /** * Saves the given stream as the manga's custom cover to cache. * * @param manga the manga. * @param inputStream the stream to copy. * @throws IOException if there's any error. */ @Throws(IOException::class) fun setCustomCoverToCache(manga: Manga, inputStream: InputStream) { getCustomCoverFile(manga).outputStream().use { inputStream.copyTo(it) } } /** * Delete the cover files of the manga from the cache. * * @param manga the manga. * @param deleteCustomCover whether the custom cover should be deleted. * @return number of files that were deleted. */ fun deleteFromCache(manga: Manga, deleteCustomCover: Boolean = false): Int { var deleted = 0 getCoverFile(manga)?.let { if (it.exists() && it.delete()) ++deleted } if (deleteCustomCover) { if (deleteCustomCover(manga)) ++deleted } return deleted } /** * Delete custom cover of the manga from the cache * * @param manga the manga. * @return whether the cover was deleted. */ fun deleteCustomCover(manga: Manga): Boolean { return getCustomCoverFile(manga).let { it.exists() && it.delete() } } /** * Clear coil's memory cache. */ fun clearMemoryCache() { context.imageLoader.memoryCache.clear() } private fun getCacheDir(dir: String): File { return context.getExternalFilesDir(dir) ?: File(context.filesDir, dir).also { it.mkdirs() } } }
apache-2.0
c68209cde09b1199a939f00e5b03d7a0
26.631579
86
0.633016
4.22252
false
false
false
false
syrop/GPS-Texter
texter/src/main/kotlin/pl/org/seva/texter/movement/ActivityRecognitionObservable.kt
1
5261
/* * Copyright (C) 2017 Wiktor Nizio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.texter.movement import android.app.PendingIntent import androidx.lifecycle.Lifecycle import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import com.google.android.gms.common.ConnectionResult import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.location.ActivityRecognition import com.google.android.gms.location.ActivityRecognitionResult import com.google.android.gms.location.DetectedActivity import java.lang.ref.WeakReference import io.reactivex.subjects.PublishSubject import pl.org.seva.texter.main.instance import pl.org.seva.texter.main.observe val activityRecognition by instance<ActivityRecognitionObservable>() open class ActivityRecognitionObservable : GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { private var initialized: Boolean = false private var googleApiClient: GoogleApiClient? = null private var weakContext: WeakReference<Context>? = null private var activityRecognitionReceiver : BroadcastReceiver? = null fun initWithContext(context: Context) { if (initialized) { return } weakContext = WeakReference(context) googleApiClient?:let { googleApiClient = GoogleApiClient.Builder(context) .addApi(ActivityRecognition.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build() checkNotNull(googleApiClient).connect() } initialized = true } override fun onConnected(bundle: Bundle?) { val context = checkNotNull(weakContext).get() ?: return registerReceiver() val intent = Intent(ACTIVITY_RECOGNITION_INTENT) val pendingIntent = PendingIntent.getBroadcast( context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) ActivityRecognition.getClient(context).requestActivityUpdates( ACTIVITY_RECOGNITION_INTERVAL_MS, pendingIntent) } override fun onConnectionSuspended(i: Int) = unregisterReceiver() private fun registerReceiver() { val context = checkNotNull(weakContext).get() ?: return activityRecognitionReceiver = activityRecognitionReceiver?: ActivityRecognitionReceiver() context.registerReceiver(activityRecognitionReceiver, IntentFilter(ACTIVITY_RECOGNITION_INTENT)) } private fun unregisterReceiver() { val context = checkNotNull(weakContext).get() ?: return activityRecognitionReceiver?: return context.unregisterReceiver(activityRecognitionReceiver) } override fun onConnectionFailed(connectionResult: ConnectionResult) = Unit fun addActivityRecognitionListener(lifecycle: Lifecycle, stationary: () -> Unit, moving: () -> Unit) { lifecycle.observe { stationarySubject.subscribe { stationary() }} lifecycle.observe { movingSubject.subscribe { moving() }} } protected open fun onDeviceStationary() = stationarySubject.onNext(0) protected open fun onDeviceMoving() = movingSubject.onNext(0) private inner class ActivityRecognitionReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (ActivityRecognitionResult.hasResult(intent)) { val result = ActivityRecognitionResult.extractResult(intent) if (result probably DetectedActivity.STILL) { onDeviceStationary() } else { onDeviceMoving() } } } private infix fun ActivityRecognitionResult.probably(activity: Int) = mostProbableActivity.type == activity && getActivityConfidence(activity) >= MIN_CONFIDENCE } companion object { private const val ACTIVITY_RECOGNITION_INTENT = "activity_recognition_intent" private const val ACTIVITY_RECOGNITION_INTERVAL_MS = 1000L /** The device is only stationary if confidence >= this level. */ private const val MIN_CONFIDENCE = 75 // 70 does not work on LG G6 Android 7.0 private val stationarySubject = PublishSubject.create<Any>() private val movingSubject = PublishSubject.create<Any>() } }
gpl-3.0
538d45037436c7b839fd2d3f83021232
37.40146
106
0.703288
5.088008
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/utility/MinecraftReflection.kt
1
8701
/* * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * Copyright (C) 2012 Kristian S. Stangeland * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ /* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.utility import com.mcmoonlake.api.cached.CachedPackage import com.mcmoonlake.api.currentBukkitVersion import com.mcmoonlake.api.exception.MoonLakeException import com.mcmoonlake.api.isOrLater import com.mcmoonlake.api.reflect.ClassSource import com.mcmoonlake.api.version.MinecraftBukkitVersion object MinecraftReflection { /** member */ private const val PACKAGE_CRAFTBUKKIT = "org.bukkit.craftbukkit" private const val PACKAGE_MINECRAFT_SERVER = "net.minecraft.server" @JvmStatic private val PACKAGE_FULL_CRAFTBUKKIT = "$PACKAGE_CRAFTBUKKIT.${MinecraftBukkitVersion.currentVersion().version}" @JvmStatic private val PACKAGE_FULL_MINECRAFT_SERVER = "$PACKAGE_MINECRAFT_SERVER.${MinecraftBukkitVersion.currentVersion().version}" @JvmStatic private val PACKAGE_CACHED_CRAFTBUKKIT: CachedPackage by lazy { CachedPackage(PACKAGE_FULL_CRAFTBUKKIT, SOURCE) } @JvmStatic private val PACKAGE_CACHED_MINECRAFT_SERVER: CachedPackage by lazy { CachedPackage(PACKAGE_FULL_MINECRAFT_SERVER, SOURCE) } @JvmStatic private val SOURCE: ClassSource by lazy { ClassSource.fromClassLoader() } /** api */ @JvmStatic @JvmName("getMinecraftClass") @Throws(MoonLakeException::class) fun getMinecraftClass(className: String): Class<*> = PACKAGE_CACHED_MINECRAFT_SERVER.getPackageClass(className) @JvmStatic @JvmName("getMinecraftClass") @Throws(MoonLakeException::class) fun getMinecraftClass(className: String, vararg aliases: String): Class<*> = try { getMinecraftClass(className) } catch(e: MoonLakeException) { var result: Class<*>? = null for(alias in aliases) try { result = getMinecraftClass(alias) } catch(e: MoonLakeException) { } if(result != null) result.also { setMinecraftClass(className, it) } else throw MoonLakeException("未查找到 $className 以及别名 ${aliases.joinToString()} 的类.", e) } @JvmStatic @JvmName("getMinecraftClassOrNull") fun getMinecraftClassOrNull(className: String): Class<*>? = try { getMinecraftClass(className) } catch(e: MoonLakeException) { null } @JvmStatic @JvmName("getMinecraftClassOrNull") fun getMinecraftClassOrNull(className: String, vararg aliases: String): Class<*>? = try { getMinecraftClass(className, *aliases) } catch(e: MoonLakeException) { null } @JvmStatic @JvmName("setMinecraftClass") fun setMinecraftClass(className: String, clazz: Class<*>?): Class<*>? { PACKAGE_CACHED_MINECRAFT_SERVER.setPackageClass(className, clazz); return clazz; } @JvmStatic @JvmName("getCraftBukkitClass") @Throws(MoonLakeException::class) fun getCraftBukkitClass(className: String): Class<*> = PACKAGE_CACHED_CRAFTBUKKIT.getPackageClass(className) @JvmStatic @JvmName("getCraftBukkitClassOrNull") fun getCraftBukkitClassOrNull(className: String): Class<*>? = try { getCraftBukkitClass(className) } catch(e: MoonLakeException) { null } @JvmStatic @JvmName("setCraftBukkitClass") fun setCraftBukkitClass(className: String, clazz: Class<*>?): Class<*>? { PACKAGE_CACHED_CRAFTBUKKIT.setPackageClass(className, clazz); return clazz; } /** * * NMS -> ChatSerializer */ @JvmStatic val chatSerializerClass: Class<*> get() { if(currentBukkitVersion().isOrLater(MinecraftBukkitVersion.V1_8_R2)) return getMinecraftClass("IChatBaseComponent\$ChatSerializer") // 1.8.3+ return getMinecraftClass("ChatSerializer") } /** * * NMS -> IChatBaseComponent */ @JvmStatic val iChatBaseComponentClass: Class<*> get() = getMinecraftClass("IChatBaseComponent") /** * * NMS -> World */ @JvmStatic val worldClass: Class<*> get() = getMinecraftClass("World") /** * * NMS -> WorldServer */ @JvmStatic val worldServerClass: Class<*> get() = getMinecraftClass("WorldServer") /** * * OBC -> CraftWorld */ @JvmStatic val craftWorldClass: Class<*> get() = getCraftBukkitClass("CraftWorld") /** * * NMS -> Entity */ @JvmStatic val entityClass: Class<*> get() = getMinecraftClass("Entity") /** * * NMS -> EntityLiving */ @JvmStatic val entityLivingClass: Class<*> get() = getMinecraftClass("EntityLiving") /** * * OBC -> entity.CraftEntity */ @JvmStatic val craftEntityClass: Class<*> get() = getCraftBukkitClass("entity.CraftEntity") /** * * NMS -> EntityPlayer */ @JvmStatic val entityPlayerClass: Class<*> get() = getMinecraftClass("EntityPlayer") /** * * OBC -> entity.CraftPlayer */ @JvmStatic val craftPlayerClass: Class<*> get() = getCraftBukkitClass("entity.CraftPlayer") /** * * NMS -> EntityHuman */ @JvmStatic val entityHumanClass: Class<*> get() = getMinecraftClass("EntityHuman") /** * * NMS -> Item */ @JvmStatic val itemClass: Class<*> get() = getMinecraftClass("Item") /** * * NMS -> ItemStack */ @JvmStatic val itemStackClass: Class<*> get() = getMinecraftClass("ItemStack") /** * * OBC -> inventory.CraftItemStack */ @JvmStatic val craftItemStackClass: Class<*> get() = getCraftBukkitClass("inventory.CraftItemStack") /** * * NMS -> NBTBase */ @JvmStatic val nbtBaseClass: Class<*> get() = getMinecraftClass("NBTBase") /** * * NMS -> NBTTagCompound */ @JvmStatic val nbtTagCompoundClass: Class<*> get() = getMinecraftClass("NBTTagCompound") /** * * NMS -> PlayerConnection */ @JvmStatic val playerConnectionClass: Class<*> get() = getMinecraftClass("PlayerConnection") /** * * NMS -> Packet */ @JvmStatic val packetClass: Class<*> get() = getMinecraftClass("Packet") /** * * NMS -> PacketListener */ @JvmStatic val packetListenerClass: Class<*> get() = getMinecraftClass("PacketListener") /** * * NMS -> PacketDataSerializer */ @JvmStatic val packetDataSerializerClass: Class<*> get() = getMinecraftClass("PacketDataSerializer") /** * * NMS -> NetworkManager */ @JvmStatic val networkManagerClass: Class<*> get() = getMinecraftClass("NetworkManager") /** * * NMS -> MinecraftServer */ @JvmStatic val minecraftServerClass: Class<*> get() = getMinecraftClass("MinecraftServer") /** * * NMS -> ServerConnection */ @JvmStatic val serverConnectionClass: Class<*> get() = getMinecraftClass("ServerConnection") /** * * OBC -> CraftServer */ @JvmStatic val craftServerClass: Class<*> get() = getCraftBukkitClass("CraftServer") }
gpl-3.0
d8ff8413856798803279defbbb1cd60a
28.327703
127
0.648773
4.429082
false
false
false
false
cdcalc/cdcalc
core/src/main/kotlin/com/github/cdcalc/git/GitExtensions.kt
1
2997
package com.github.cdcalc.git import com.github.cdcalc.data.CommitTag import com.github.cdcalc.data.SemVer import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.lib.ObjectId import org.eclipse.jgit.lib.Ref import org.eclipse.jgit.revwalk.RevCommit import org.eclipse.jgit.revwalk.RevWalk import org.slf4j.Logger import org.slf4j.LoggerFactory fun Git.taggedCommits(): Map<ObjectId, CommitTag> { val branchCommit: Map<ObjectId, CommitTag> = this.tagList().call().map { val peel = this.repository.refDatabase.peel(it) if (peel.peeledObjectId != null) { CommitTag(peel.peeledObjectId, it.name) } else { CommitTag(it.objectId, it.name) } }.associateBy(keySelector = {it.objectId}, valueTransform = {it}) return branchCommit } fun Git.semVerTags(): List<RefSemVer> { return this.tagList() .call() .map { RefSemVer(it, SemVer.parse(it.name)) } } // https://github.com/centic9/jgit-cookbook/blob/master/src/main/java/org/dstadler/jgit/porcelain/ListTags.java fun Git.peeledObjectId(ref: Ref): ObjectId { val peel = this.repository.refDatabase.peel(ref) val objectId = peel.peeledObjectId ?: ref.objectId return objectId } fun <T> Git.processTags(tags: List<RefSemVer>, filter: (walk: RevWalk, headCommit: RevCommit, Sequence<RevCommitSemVer>) -> T) : T { val head = this.repository.resolve(Constants.HEAD) RevWalk(this.repository).use { walk -> val headCommit: RevCommit = walk.parseCommit(head) val map: Sequence<RevCommitSemVer> = tags.asSequence().map { (ref, semVer) -> val objectId = this.peeledObjectId(ref) val taggedCommit: RevCommit = walk.parseCommit(objectId) RevCommitSemVer(taggedCommit, semVer) } return filter(walk, headCommit, map) } } fun Git.aheadOfTag(tags: List<RefSemVer>, ignoreTagsOnHead: Boolean = false) : SemVerAhead { val log: Logger = LoggerFactory.getLogger(::aheadOfTag.name) val semVerAhead = processTags(tags) { walk, headCommit, sequence -> sequence.filter { (taggedCommit) -> when { ignoreTagsOnHead -> headCommit != taggedCommit else -> walk.isMergedInto(taggedCommit, headCommit) } }.map { (taggedCommit, semVer: SemVer) -> log.info("Check if " + headCommit.name + " is merged into " + taggedCommit.name) SemVerAhead( semVer, walk.countCommits(headCommit, taggedCommit), headCommit == taggedCommit) }.plus(SemVerAhead(SemVer.Empty, 0, false)) .first() } return semVerAhead } data class RefSemVer(val ref: Ref, val semVer: SemVer) data class RevCommitSemVer(val commit: RevCommit, val semVer: SemVer) data class SemVerAhead(val semVer: SemVer, val ahead: Int, val commitIsMatchingTag: Boolean)
mit
fd57aed8a4e3f2d898db1e0db2d9bd7c
34.678571
132
0.658325
3.784091
false
false
false
false
phylame/jem
commons/src/main/kotlin/jclp/log/LogImpls.kt
1
2227
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jclp.log import java.time.LocalDateTime import java.util.logging.Level import java.util.logging.Logger object SimpleFacade : LogFacade { override var level: LogLevel = LogLevel.INFO override fun log(tag: String, level: LogLevel, msg: String) { print(tag, level, msg) } override fun log(tag: String, level: LogLevel, msg: String, t: Throwable) { print(tag, level, msg) t.printStackTrace() } private fun print(tag: String, level: LogLevel, msg: String) { val text = "[${LocalDateTime.now()}] [${Thread.currentThread().name}] ${level.name[0]}/$tag: $msg" if (level == LogLevel.ERROR) { System.err.println(text) } else { println(text) } } } object JDKFacade : LogFacade { override var level: LogLevel = LogLevel.INFO override fun log(tag: String, level: LogLevel, msg: String) { Logger.getLogger(tag).let { it.level = mapLevel(level) it.log(mapLevel(level), msg) } } override fun log(tag: String, level: LogLevel, msg: String, t: Throwable) { Logger.getLogger(tag).let { it.level = mapLevel(level) it.log(mapLevel(level), msg, t) } } private fun mapLevel(level: LogLevel) = when (level) { LogLevel.ALL -> Level.ALL LogLevel.TRACE -> Level.FINER LogLevel.DEBUG -> Level.FINE LogLevel.INFO -> Level.INFO LogLevel.WARN -> Level.WARNING LogLevel.ERROR -> Level.SEVERE LogLevel.OFF -> Level.OFF } }
apache-2.0
b61867436cfd10021ec5d0e3bd588cf9
29.506849
106
0.636282
3.920775
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/nbt/lang/format/NbttFoldingBuilder.kt
1
4940
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.format import com.demonwav.mcdev.nbt.lang.gen.psi.NbttByteArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttCompound import com.demonwav.mcdev.nbt.lang.gen.psi.NbttIntArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttList import com.demonwav.mcdev.nbt.lang.gen.psi.NbttLongArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.lang.ASTNode import com.intellij.lang.folding.FoldingBuilder import com.intellij.lang.folding.FoldingDescriptor import com.intellij.openapi.editor.Document import com.intellij.openapi.util.TextRange class NbttFoldingBuilder : FoldingBuilder { override fun getPlaceholderText(node: ASTNode): String? { return when (node.elementType) { NbttTypes.BYTE_ARRAY, NbttTypes.INT_ARRAY, NbttTypes.LIST -> "..." NbttTypes.COMPOUND -> { val tagList = (node.psi as NbttCompound).getNamedTagList() if (tagList.isEmpty()) { return null } val tag = tagList[0].tag if (tagList.size == 1 && tag?.getList() == null && tag?.getCompound() == null && tag?.getIntArray() == null && tag?.getByteArray() == null ) { tagList[0].text } else { "..." } } else -> null } } override fun buildFoldRegions(node: ASTNode, document: Document): Array<FoldingDescriptor> { val list = mutableListOf<FoldingDescriptor>() foldChildren(node, list) return list.toTypedArray() } private fun foldChildren(node: ASTNode, list: MutableList<FoldingDescriptor>) { when (node.elementType) { NbttTypes.COMPOUND -> { val lbrace = node.findChildByType(NbttTypes.LBRACE) val rbrace = node.findChildByType(NbttTypes.RBRACE) if (lbrace != null && rbrace != null) { if (lbrace.textRange.endOffset != rbrace.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lbrace.textRange.endOffset, rbrace.textRange.startOffset) ) ) } } } NbttTypes.LIST -> { val lbracket = node.findChildByType(NbttTypes.LBRACKET) val rbracket = node.findChildByType(NbttTypes.RBRACKET) if (lbracket != null && rbracket != null) { if (lbracket.textRange.endOffset != rbracket.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lbracket.textRange.endOffset, rbracket.textRange.startOffset) ) ) } } } NbttTypes.BYTE_ARRAY, NbttTypes.INT_ARRAY, NbttTypes.LONG_ARRAY -> { val lparen = node.findChildByType(NbttTypes.LPAREN) val rparen = node.findChildByType(NbttTypes.RPAREN) if (lparen != null && rparen != null) { if (lparen.textRange.endOffset != rparen.textRange.startOffset) { list.add( FoldingDescriptor( node, TextRange(lparen.textRange.endOffset, rparen.textRange.startOffset) ) ) } } } } node.getChildren(null).forEach { foldChildren(it, list) } } override fun isCollapsedByDefault(node: ASTNode): Boolean { val psi = node.psi val size = when (psi) { is NbttByteArray -> psi.getByteList().size is NbttIntArray -> psi.getIntList().size is NbttLongArray -> psi.getLongList().size is NbttList -> psi.getTagList().size is NbttCompound -> { if (psi.getNamedTagList().size == 1) { val tag = psi.getNamedTagList()[0].tag if ( tag?.getList() == null && tag?.getCompound() == null && tag?.getIntArray() == null && tag?.getByteArray() == null ) { return true } } psi.getNamedTagList().size } else -> 0 } return size > 50 // TODO arbitrary? make a setting? } }
mit
75c5cdbbde522fc1ed1ac9d6178dba70
37.294574
103
0.504049
5.2
false
false
false
false
georocket/georocket
src/main/kotlin/io/georocket/tasks/Task.kt
1
1159
package io.georocket.tasks import com.fasterxml.jackson.annotation.JsonInclude import com.fasterxml.jackson.annotation.JsonSubTypes import com.fasterxml.jackson.annotation.JsonTypeInfo import java.time.Instant /** * A task currently being performed by GeoRocket * @author Michel Kraemer */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes( JsonSubTypes.Type(value = ImportingTask::class, name = "importing"), JsonSubTypes.Type(value = ReceivingTask::class, name = "receiving") ) @JsonInclude(value = JsonInclude.Include.NON_NULL) interface Task { /** * The task's unique ID */ val id: String /** * The correlation ID the task belongs to */ val correlationId: String /** * The time when GeoRocket has started to execute the task */ val startTime: Instant /** * The time when GeoRocket has finished executing the task (may be `null` * if GeoRocket has not finished the task yet) */ val endTime: Instant? /** * The error that occurred during the execution of the task (`null` if no * error has occurred) */ val error: TaskError? }
apache-2.0
fa3180ff9ec8f88ce231c81888ff852b
24.755556
96
0.714409
4.109929
false
false
false
false
Zeyad-37/RxRedux
core/src/main/java/com/zeyad/rxredux/core/vm/rxvm/ViewModelListenerHelper.kt
1
677
package com.zeyad.rxredux.core.vm.rxvm class ViewModelListenerHelper : ViewModelListener { override var effects: (effect: Effect) -> Unit = {} override var states: (state: State) -> Unit = {} override var progress: (progress: Progress) -> Unit = {} override var errors: (error: Error) -> Unit = {} fun errors(errors: (error: Error) -> Unit) { this.errors = errors } fun effects(effects: (effect: Effect) -> Unit) { this.effects = effects } fun states(states: (state: State) -> Unit) { this.states = states } fun progress(progress: (progress: Progress) -> Unit) { this.progress = progress } }
apache-2.0
1b1ac808fa450570f4c5f2f08bef1214
27.208333
60
0.608567
3.913295
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileEditorManagerExImpl.kt
2
4453
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.fileEditor.impl import com.intellij.codeWithMe.ClientId import com.intellij.openapi.application.EDT import com.intellij.openapi.application.TransactionGuard import com.intellij.openapi.application.TransactionGuardImpl import com.intellij.openapi.application.readAction import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.fileEditor.AsyncFileEditorProvider import com.intellij.openapi.fileEditor.FileEditor import com.intellij.openapi.fileEditor.FileEditorProvider import com.intellij.openapi.fileEditor.ex.FileEditorProviderManager import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.jetbrains.annotations.ApiStatus import java.util.concurrent.CancellationException @ApiStatus.Internal internal interface AsyncFileEditorOpener { suspend fun openFileImpl5(window: EditorWindow, virtualFile: VirtualFile, entry: HistoryEntry?, options: FileEditorOpenOptions): Pair<List<FileEditor>, List<FileEditorProvider>> } // todo convert FileEditorManagerImpl to kotlin open class FileEditorManagerExImpl(project: Project) : FileEditorManagerImpl(project), AsyncFileEditorOpener { companion object { private val LOG = logger<FileEditorManagerImpl>() } override suspend fun openFileImpl5(window: EditorWindow, virtualFile: VirtualFile, entry: HistoryEntry?, options: FileEditorOpenOptions): Pair<List<FileEditor>, List<FileEditorProvider>> { if (!ClientId.isCurrentlyUnderLocalId) { val clientManager = clientFileEditorManager ?: return Pair(emptyList(), emptyList()) val result = clientManager.openFile(file = virtualFile, forceCreate = false) return Pair(result.map { it.fileEditor }, result.map { it.provider }) } val file = getOriginalFile(virtualFile) var composite: EditorComposite? = if (options.isReopeningOnStartup) { null } else { withContext(Dispatchers.EDT) { window.getComposite(file) } } val newProviders: List<FileEditorProvider>? val builders: Array<AsyncFileEditorProvider.Builder?>? if (composite == null) { if (!canOpenFile(file)) { val p = EditorComposite.retrofit(null) return Pair(p.first.toList(), p.second.toList()) } // File is not opened yet. In this case we have to create editors and select the created EditorComposite. newProviders = FileEditorProviderManager.getInstance().getProvidersAsync(project, file) builders = arrayOfNulls(newProviders.size) for (i in newProviders.indices) { try { val provider = newProviders[i] builders[i] = readAction { if (!file.isValid) { return@readAction null } LOG.assertTrue(provider.accept(project, file), "Provider $provider doesn't accept file $file") if (provider is AsyncFileEditorProvider) provider.createEditorAsync(project, file) else null } } catch (e: ProcessCanceledException) { throw e } catch (e: CancellationException) { throw e } catch (e: Exception) { LOG.error(e) } catch (e: AssertionError) { LOG.error(e) } } } else { newProviders = null builders = null } withContext(Dispatchers.EDT) { if (!file.isValid) { return@withContext } // execute as part of project open process - maybe under modal progress, maybe not, // so, we cannot use NON_MODAL to get write-safe context, because it will lead to a deadlock (TransactionGuard.getInstance() as TransactionGuardImpl).performUserActivity { runBulkTabChange(window.owner) { composite = openFileImpl4Edt(window, file, entry, options, newProviders, builders) } } } val p = EditorComposite.retrofit(composite ?: return Pair(emptyList(), emptyList())) return Pair(p.first.toList(), p.second.toList()) } }
apache-2.0
b27ace8c352d471401c2e08f045badd2
37.730435
120
0.681338
4.829718
false
false
false
false
google/intellij-community
plugins/kotlin/j2k/new/tests/test/org/jetbrains/kotlin/nj2k/inference/mutability/AbstractMutabilityInferenceTest.kt
2
3815
// 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.nj2k.inference.mutability import com.intellij.openapi.application.runWriteAction import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.formatter.commitAndUnblockDocument import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.* import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.nj2k.descriptorByFileDirective import org.jetbrains.kotlin.nj2k.inference.AbstractConstraintCollectorTest import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.CallExpressionConstraintCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.CommonConstraintsCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.common.collectors.FunctionConstraintsCollector import org.jetbrains.kotlin.idea.j2k.post.processing.inference.mutability.* import org.jetbrains.kotlin.psi.KtConstructorCalleeExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtTypeElement import org.jetbrains.kotlin.psi.KtTypeReference import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import java.io.File abstract class AbstractMutabilityInferenceTest : AbstractConstraintCollectorTest() { override fun createInferenceFacade(resolutionFacade: ResolutionFacade): InferenceFacade { val typeEnhancer = MutabilityBoundTypeEnhancer() return InferenceFacade( object : ContextCollector(resolutionFacade) { override fun ClassReference.getState(typeElement: KtTypeElement?) = when (descriptor?.fqNameOrNull()) { in MutabilityStateUpdater.mutableToImmutable -> State.UNKNOWN in MutabilityStateUpdater.immutableToMutable -> State.UNKNOWN else -> State.UNUSED } }, ConstraintsCollectorAggregator( resolutionFacade, MutabilityConstraintBoundProvider(), listOf( CommonConstraintsCollector(), CallExpressionConstraintCollector(), FunctionConstraintsCollector(ResolveSuperFunctionsProvider(resolutionFacade)), MutabilityConstraintsCollector() ) ), MutabilityBoundTypeCalculator(resolutionFacade, typeEnhancer), MutabilityStateUpdater(), MutabilityDefaultStateProvider(), renderDebugTypes = true ) } override fun KtFile.afterInference(): Unit = runWriteAction { commitAndUnblockDocument() ShortenReferences.DEFAULT.process(this) } override fun KtFile.prepareFile() = runWriteAction { fun KtTypeReference.updateMutability() { MutabilityStateUpdater.changeState( typeElement ?: return, analyze()[BindingContext.TYPE, this]!!, toMutable = true ) for (typeArgument in typeElement!!.typeArgumentsAsTypes) { typeArgument.updateMutability() } } for (typeReference in collectDescendantsOfType<KtTypeReference>()) { if (typeReference.parent is KtConstructorCalleeExpression) continue typeReference.updateMutability() } deleteComments() } override fun getProjectDescriptor() = descriptorByFileDirective(File(testDataPath, fileName())) }
apache-2.0
ebf353e616389dae3ad85109252cc1c9
47.303797
158
0.720052
5.824427
false
true
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ide/projectWizard/NewProjectWizardConstants.kt
3
1137
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.projectWizard object NewProjectWizardConstants { object Language { const val JAVA = "Java" const val KOTLIN = "Kotlin" const val GROOVY = "Groovy" const val JAVASCRIPT = "JavaScript" const val HTML = "HTML" const val PYTHON = "Python" const val PHP = "PHP" const val RUBY = "Ruby" const val GO = "Go" const val SCALA = "Scala" val ALL = arrayOf(JAVA, KOTLIN, GROOVY, JAVASCRIPT, HTML, PYTHON, PHP, RUBY, GO, SCALA) val ALL_DSL = arrayOf(KOTLIN, GROOVY) } object BuildSystem { const val INTELLIJ = "IntelliJ" const val GRADLE = "Gradle" const val MAVEN = "Maven" const val SBT = "SBT" val ALL = arrayOf(INTELLIJ, GRADLE, MAVEN, SBT) } object Generators { const val EMPTY_PROJECT = "empty-project" const val EMPTY_WEB_PROJECT = "empty-web-project" const val SIMPLE_PROJECT = "simple-project" const val SIMPLE_MODULE = "simple-module" } const val OTHER = "other" const val NULL = "null" }
apache-2.0
ea773a01fc2acc6b64a13b630d3c84aa
28.179487
120
0.665787
3.667742
false
false
false
false
google/intellij-community
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/findUsages/handlers/KotlinFindMemberUsagesHandler.kt
3
18884
// 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.findUsages.handlers import com.intellij.codeInsight.highlighting.ReadWriteAccessDetector import com.intellij.find.FindManager import com.intellij.find.findUsages.AbstractFindUsagesDialog import com.intellij.find.findUsages.FindUsagesOptions import com.intellij.find.impl.FindManagerImpl import com.intellij.icons.AllIcons.Actions import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.openapi.wm.ToolWindowId import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiReference import com.intellij.psi.search.SearchScope import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.OverridingMethodsSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.usageView.UsageInfo import com.intellij.util.* import org.jetbrains.annotations.Nls import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics import org.jetbrains.kotlin.idea.base.util.excludeKotlinSources import org.jetbrains.kotlin.idea.findUsages.* import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.getTopMostOverriddenElementsToHighlight import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.isDataClassComponentFunction import org.jetbrains.kotlin.idea.findUsages.dialogs.KotlinFindFunctionUsagesDialog import org.jetbrains.kotlin.idea.findUsages.dialogs.KotlinFindPropertyUsagesDialog import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.filterDataClassComponentsIfDisabled import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.isOverridable import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchOverriders import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReadWriteAccessDetector import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters import org.jetbrains.kotlin.idea.search.isImportUsage import org.jetbrains.kotlin.idea.search.isOnlyKotlinSearch import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parameterIndex import javax.swing.event.HyperlinkEvent import javax.swing.event.HyperlinkListener abstract class KotlinFindMemberUsagesHandler<T : KtNamedDeclaration> protected constructor( declaration: T, elementsToSearch: Collection<PsiElement>, factory: KotlinFindUsagesHandlerFactory ) : KotlinFindUsagesHandler<T>(declaration, elementsToSearch, factory) { private class Function( declaration: KtFunction, elementsToSearch: Collection<PsiElement>, factory: KotlinFindUsagesHandlerFactory ) : KotlinFindMemberUsagesHandler<KtFunction>(declaration, elementsToSearch, factory) { override fun getFindUsagesOptions(dataContext: DataContext?): FindUsagesOptions = factory.findFunctionOptions override fun getPrimaryElements(): Array<PsiElement> = if (factory.findFunctionOptions.isSearchForBaseMethod) { val supers = KotlinFindUsagesSupport.getSuperMethods(psiElement as KtFunction, null) if (supers.contains(psiElement)) supers.toTypedArray() else (supers + psiElement).toTypedArray() } else super.getPrimaryElements() override fun getFindUsagesDialog( isSingleFile: Boolean, toShowInNewTab: Boolean, mustOpenInNewTab: Boolean ): AbstractFindUsagesDialog { val options = factory.findFunctionOptions val lightMethod = getElement().toLightMethods().firstOrNull() if (lightMethod != null) { return KotlinFindFunctionUsagesDialog(lightMethod, project, options, toShowInNewTab, mustOpenInNewTab, isSingleFile, this) } return super.getFindUsagesDialog(isSingleFile, toShowInNewTab, mustOpenInNewTab) } override fun createKotlinReferencesSearchOptions(options: FindUsagesOptions, forHighlight: Boolean): KotlinReferencesSearchOptions { val kotlinOptions = options as KotlinFunctionFindUsagesOptions return KotlinReferencesSearchOptions( acceptCallableOverrides = true, acceptOverloads = kotlinOptions.isIncludeOverloadUsages, acceptExtensionsOfDeclarationClass = kotlinOptions.isIncludeOverloadUsages, searchForExpectedUsages = kotlinOptions.searchExpected, searchForComponentConventions = !forHighlight ) } override fun applyQueryFilters(element: PsiElement, options: FindUsagesOptions, query: Query<PsiReference>): Query<PsiReference> { val kotlinOptions = options as KotlinFunctionFindUsagesOptions return query .applyFilter(kotlinOptions.isSkipImportStatements) { !it.isImportUsage() } } } private class Property( propertyDeclaration: KtNamedDeclaration, elementsToSearch: Collection<PsiElement>, factory: KotlinFindUsagesHandlerFactory ) : KotlinFindMemberUsagesHandler<KtNamedDeclaration>(propertyDeclaration, elementsToSearch, factory) { override fun processElementUsages( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ): Boolean { if (isUnitTestMode() || !isPropertyOfDataClass || psiElement.getDisableComponentAndDestructionSearch(resetSingleFind = false) ) return super.processElementUsages(element, processor, options) val indicator = ProgressManager.getInstance().progressIndicator val notificationCanceller = scheduleNotificationForDataClassComponent(project, element, indicator) try { return super.processElementUsages(element, processor, options) } finally { Disposer.dispose(notificationCanceller) } } private val isPropertyOfDataClass = runReadAction { propertyDeclaration.parent is KtParameterList && propertyDeclaration.parent.parent is KtPrimaryConstructor && propertyDeclaration.parent.parent.parent.let { it is KtClass && it.isData() } } override fun getPrimaryElements(): Array<PsiElement> { val element = psiElement as KtNamedDeclaration if (element is KtParameter && !element.hasValOrVar() && factory.findPropertyOptions.isSearchInOverridingMethods) { val function = element.ownerFunction if (function != null && function.isOverridable()) { function.toLightMethods().singleOrNull()?.let { method -> if (OverridingMethodsSearch.search(method).any()) { val parametersCount = method.parameterList.parametersCount val parameterIndex = element.parameterIndex() assert(parameterIndex < parametersCount) return OverridingMethodsSearch.search(method, true) .filter { method.parameterList.parametersCount == parametersCount } .mapNotNull { method.parameterList.parameters[parameterIndex].unwrapped } .toTypedArray() } } } } else if (factory.findPropertyOptions.isSearchForBaseAccessors) { val supers = KotlinFindUsagesSupport.getSuperMethods(element, null) return if (supers.contains(psiElement)) supers.toTypedArray() else (supers + psiElement).toTypedArray() } return super.getPrimaryElements() } override fun getFindUsagesOptions(dataContext: DataContext?): FindUsagesOptions = factory.findPropertyOptions override fun getFindUsagesDialog( isSingleFile: Boolean, toShowInNewTab: Boolean, mustOpenInNewTab: Boolean ): AbstractFindUsagesDialog { return KotlinFindPropertyUsagesDialog( getElement(), project, factory.findPropertyOptions, toShowInNewTab, mustOpenInNewTab, isSingleFile, this ) } override fun applyQueryFilters(element: PsiElement, options: FindUsagesOptions, query: Query<PsiReference>): Query<PsiReference> { val kotlinOptions = options as KotlinPropertyFindUsagesOptions if (!kotlinOptions.isReadAccess && !kotlinOptions.isWriteAccess) { return EmptyQuery() } val result = query.applyFilter(kotlinOptions.isSkipImportStatements) { !it.isImportUsage() } if (!kotlinOptions.isReadAccess || !kotlinOptions.isWriteAccess) { val detector = KotlinReadWriteAccessDetector() return FilteredQuery(result) { when (detector.getReferenceAccess(element, it)) { ReadWriteAccessDetector.Access.Read -> kotlinOptions.isReadAccess ReadWriteAccessDetector.Access.Write -> kotlinOptions.isWriteAccess ReadWriteAccessDetector.Access.ReadWrite -> kotlinOptions.isReadWriteAccess } } } return result } private fun PsiElement.getDisableComponentAndDestructionSearch(resetSingleFind: Boolean): Boolean { if (!isPropertyOfDataClass) return false if (forceDisableComponentAndDestructionSearch) return true if (KotlinFindPropertyUsagesDialog.getDisableComponentAndDestructionSearch(project)) return true return if (getUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY) == true) { if (resetSingleFind) { putUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY, null) } true } else false } override fun createKotlinReferencesSearchOptions(options: FindUsagesOptions, forHighlight: Boolean): KotlinReferencesSearchOptions { val kotlinOptions = options as KotlinPropertyFindUsagesOptions val disabledComponentsAndOperatorsSearch = !forHighlight && psiElement.getDisableComponentAndDestructionSearch(resetSingleFind = true) return KotlinReferencesSearchOptions( acceptCallableOverrides = true, acceptOverloads = false, acceptExtensionsOfDeclarationClass = false, searchForExpectedUsages = kotlinOptions.searchExpected, searchForOperatorConventions = !disabledComponentsAndOperatorsSearch, searchForComponentConventions = !disabledComponentsAndOperatorsSearch ) } } override fun createSearcher( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ): Searcher { return MySearcher(element, processor, options) } private inner class MySearcher( element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions ) : Searcher(element, processor, options) { private val kotlinOptions = options as KotlinCallableFindUsagesOptions override fun buildTaskList(forHighlight: Boolean): Boolean { val referenceProcessor = createReferenceProcessor(processor) val uniqueProcessor = CommonProcessors.UniqueProcessor(processor) if (options.isUsages) { val baseKotlinSearchOptions = createKotlinReferencesSearchOptions(options, forHighlight) val kotlinSearchOptions = if (element is KtNamedFunction && KotlinPsiHeuristics.isPossibleOperator(element)) { baseKotlinSearchOptions } else { baseKotlinSearchOptions.copy(searchForOperatorConventions = false) } val searchParameters = KotlinReferencesSearchParameters(element, options.searchScope, kotlinOptions = kotlinSearchOptions) addTask { applyQueryFilters(element, options, ReferencesSearch.search(searchParameters)).forEach(referenceProcessor) } if (element is KtElement && !isOnlyKotlinSearch(options.searchScope)) { // TODO: very bad code!! ReferencesSearch does not work correctly for constructors and annotation parameters val psiMethodScopeSearch = when { element is KtParameter && element.isDataClassComponentFunction -> options.searchScope.excludeKotlinSources(project) else -> options.searchScope } for (psiMethod in element.toLightMethods().filterDataClassComponentsIfDisabled(kotlinSearchOptions)) { addTask { val query = MethodReferencesSearch.search(psiMethod, psiMethodScopeSearch, true) applyQueryFilters( element, options, query ).forEach(referenceProcessor) } } } } if (kotlinOptions.searchOverrides) { addTask { val overriders = HierarchySearchRequest(element, options.searchScope, true).searchOverriders() overriders.all { val element = runReadAction { it.takeIf { it.isValid }?.navigationElement } ?: return@all true processUsage(uniqueProcessor, element) } } } return true } } protected abstract fun createKotlinReferencesSearchOptions( options: FindUsagesOptions, forHighlight: Boolean ): KotlinReferencesSearchOptions protected abstract fun applyQueryFilters( element: PsiElement, options: FindUsagesOptions, query: Query<PsiReference> ): Query<PsiReference> override fun isSearchForTextOccurrencesAvailable(psiElement: PsiElement, isSingleFile: Boolean): Boolean = !isSingleFile && psiElement !is KtParameter override fun findReferencesToHighlight(target: PsiElement, searchScope: SearchScope): Collection<PsiReference> { val baseDeclarations = getTopMostOverriddenElementsToHighlight(target) return if (baseDeclarations.isNotEmpty()) { baseDeclarations.flatMap { val handler = (FindManager.getInstance(project) as FindManagerImpl).findUsagesManager.getFindUsagesHandler(it!!, true) handler?.findReferencesToHighlight(it, searchScope) ?: emptyList() } } else { super.findReferencesToHighlight(target, searchScope) } } companion object { @Volatile @get:TestOnly var forceDisableComponentAndDestructionSearch = false private const val DISABLE_ONCE = "DISABLE_ONCE" private const val DISABLE = "DISABLE" private val DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TEXT @Nls get() = KotlinBundle.message( "find.usages.text.find.usages.for.data.class.components.and.destruction.declarations", DISABLE_ONCE, DISABLE ) private const val DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TIMEOUT = 5000 private val FIND_USAGES_ONES_FOR_DATA_CLASS_KEY = Key<Boolean>("FIND_USAGES_ONES") private fun scheduleNotificationForDataClassComponent( project: Project, element: PsiElement, indicator: ProgressIndicator ): Disposable { val notification = { val listener = HyperlinkListener { event -> if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) { indicator.cancel() if (event.description == DISABLE) { KotlinFindPropertyUsagesDialog.setDisableComponentAndDestructionSearch(project, /* value = */ true) } else { element.putUserData(FIND_USAGES_ONES_FOR_DATA_CLASS_KEY, true) } FindManager.getInstance(project).findUsages(element) } } val windowManager = ToolWindowManager.getInstance(project) windowManager.getToolWindow(ToolWindowId.FIND)?.let { toolWindow -> windowManager.notifyByBalloon( toolWindow.id, MessageType.INFO, DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TEXT, Actions.Find, listener ) } Unit } return Alarm().also { it.addRequest(notification, DISABLE_COMPONENT_AND_DESTRUCTION_SEARCH_TIMEOUT) } } fun getInstance( declaration: KtNamedDeclaration, elementsToSearch: Collection<PsiElement> = emptyList(), factory: KotlinFindUsagesHandlerFactory ): KotlinFindMemberUsagesHandler<out KtNamedDeclaration> { return if (declaration is KtFunction) Function(declaration, elementsToSearch, factory) else Property(declaration, elementsToSearch, factory) } } } fun Query<PsiReference>.applyFilter(flag: Boolean, condition: (PsiReference) -> Boolean): Query<PsiReference> { return if (flag) FilteredQuery(this, condition) else this }
apache-2.0
f6a6ec48682aceff536cec671207447a
45.058537
140
0.663525
6.015929
false
false
false
false
JetBrains/intellij-community
platform/lang-impl/src/com/intellij/refactoring/rename/impl/rename.kt
1
11848
// 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.refactoring.rename.impl import com.intellij.codeInsight.actions.VcsFacade import com.intellij.model.ModelPatch import com.intellij.model.Pointer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.EDT import com.intellij.openapi.application.readAction import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import com.intellij.psi.impl.search.runSearch import com.intellij.psi.search.GlobalSearchScope import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.rename.api.* import com.intellij.refactoring.rename.api.ModifiableRenameUsage.* import com.intellij.refactoring.rename.impl.FileUpdates.Companion.createFileUpdates import com.intellij.refactoring.rename.ui.* import com.intellij.util.Query import com.intellij.util.ui.UIUtil import kotlinx.coroutines.* import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.toList import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.fold import kotlinx.coroutines.flow.map import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.TestOnly internal typealias UsagePointer = Pointer<out RenameUsage> /** * Entry point to perform rename with a dialog initialized with [targetName]. */ internal fun showDialogAndRename(project: Project, target: RenameTarget, targetName: String = target.targetName) { ApplicationManager.getApplication().assertIsDispatchThread() val initOptions = RenameDialog.Options( targetName = targetName, renameOptions = renameOptions(project, target) ) val dialog = RenameDialog(project, target.presentation().presentableText, target.validator(), initOptions) if (!dialog.showAndGet()) { // cancelled return } val (newName: String, options: RenameOptions) = dialog.result() setTextOptions(target, options.textOptions) rename(project, target.createPointer(), newName, options, dialog.preview) } /** * Entry point to perform rename without a dialog. * @param preview whether the user explicitly requested the Preview */ internal fun rename( project: Project, targetPointer: Pointer<out RenameTarget>, newName: String, options: RenameOptions, preview: Boolean = false ) { val cs = CoroutineScope(CoroutineName("root rename coroutine")) rename(cs, project, targetPointer, newName, options, preview) } private fun rename( cs: CoroutineScope, project: Project, targetPointer: Pointer<out RenameTarget>, newName: String, options: RenameOptions, preview: Boolean ): Job { return cs.launch(Dispatchers.Default) { doRename(this, project, targetPointer, newName, options, preview) } } private suspend fun doRename( cs: CoroutineScope, project: Project, targetPointer: Pointer<out RenameTarget>, newName: String, options: RenameOptions, preview: Boolean ) { val query: Query<UsagePointer> = readAction { targetPointer.dereference()?.let { target -> buildQuery(project, target, options) } } ?: return val firstProgressTitle: String = targetPointer.progressTitle() ?: return // invalidated val channel: ReceiveChannel<UsagePointer> = runSearch(cs, project, query) val deferredUsages: Deferred<Collection<UsagePointer>> = withBackgroundIndicator(project, firstProgressTitle) { val (processedUsagePointers: Collection<UsagePointer>, forcePreview: Boolean) = if (preview) { ProcessUsagesResult(emptyList(), true) } else { processUsages(channel, newName) } if (forcePreview) { val usageView = showUsageView(project, targetPointer, newName, processedUsagePointers) appendUsages(usageView, channel, newName) cs.previewRenameAsync(project, targetPointer, newName, usageView) { runSearch(cs = this, project = project, query = query) } } else { cs.async { processedUsagePointers } } } val usagePointers: Collection<UsagePointer> = deferredUsages.await() val secondProgressTitle: String = targetPointer.progressTitle() ?: return val (fileUpdates: FileUpdates?, modelUpdate: ModelUpdate?) = withBackgroundIndicator(project, secondProgressTitle) { prepareRename(usagePointers, newName) } if (preview && fileUpdates != null && !previewInDialog(project, fileUpdates)) { return } val commandName: String = targetPointer.commandName(newName) ?: return WriteCommandAction .writeCommandAction(project) .withName(commandName) .run<Throwable> { if (modelUpdate != null) { targetPointer.dereference()?.targetName?.let { oldName -> val undoableAction = RenameUndoableAction(modelUpdate, oldName, newName) UndoManager.getInstance(project).undoableActionPerformed(undoableAction) } modelUpdate.updateModel(newName) } fileUpdates?.doUpdate() } } private data class ProcessUsagesResult( val processedUsagePointers: Collection<UsagePointer>, val forcePreview: Boolean ) private suspend fun processUsages(usageChannel: ReceiveChannel<UsagePointer>, newName: String): ProcessUsagesResult { if (ApplicationManager.getApplication().isUnitTestMode) { return ProcessUsagesResult(usageChannel.toList(), false) } val usagePointers = ArrayList<UsagePointer>() for (pointer: UsagePointer in usageChannel) { usagePointers += pointer val forcePreview: Boolean? = readAction { pointer.dereference()?.let { renameUsage -> renameUsage is TextRenameUsage || renameUsage.conflicts(newName).isNotEmpty() } } if (forcePreview == true) { return ProcessUsagesResult(usagePointers, true) } } return ProcessUsagesResult(usagePointers, false) } @ApiStatus.Internal suspend fun prepareRename(allUsages: Collection<UsagePointer>, newName: String): Pair<FileUpdates?, ModelUpdate?> { return coroutineScope { require(!ApplicationManager.getApplication().isReadAccessAllowed) val ( byFileUpdater: Map<FileUpdater, List<Pointer<out ModifiableRenameUsage>>>, byModelUpdater: Map<ModelUpdater, List<Pointer<out ModifiableRenameUsage>>> ) = readAction { classifyUsages(allUsages) } val fileUpdates: Deferred<FileUpdates?> = async { prepareFileUpdates(byFileUpdater, newName) } val modelUpdates: Deferred<ModelUpdate?> = async { prepareModelUpdate(byModelUpdater) } Pair( fileUpdates.await(), modelUpdates.await() ) } } private fun classifyUsages( allUsages: Collection<UsagePointer> ): Pair< Map<FileUpdater, List<Pointer<out ModifiableRenameUsage>>>, Map<ModelUpdater, List<Pointer<out ModifiableRenameUsage>>> > { ApplicationManager.getApplication().assertReadAccessAllowed() val byFileUpdater = HashMap<FileUpdater, MutableList<Pointer<out ModifiableRenameUsage>>>() val byModelUpdater = HashMap<ModelUpdater, MutableList<Pointer<out ModifiableRenameUsage>>>() for (pointer: UsagePointer in allUsages) { ProgressManager.checkCanceled() val renameUsage: ModifiableRenameUsage = pointer.dereference() as? ModifiableRenameUsage ?: continue @Suppress("UNCHECKED_CAST") val modifiablePointer = pointer as Pointer<out ModifiableRenameUsage> renameUsage.fileUpdater?.let { fileUpdater: FileUpdater -> byFileUpdater.getOrPut(fileUpdater) { ArrayList() }.add(modifiablePointer) } renameUsage.modelUpdater?.let { modelUpdater: ModelUpdater -> byModelUpdater.getOrPut(modelUpdater) { ArrayList() }.add(modifiablePointer) } } return Pair(byFileUpdater, byModelUpdater) } private suspend fun prepareFileUpdates( byFileUpdater: Map<FileUpdater, List<Pointer<out ModifiableRenameUsage>>>, newName: String ): FileUpdates? { return byFileUpdater.entries .asFlow() .map { (fileUpdater: FileUpdater, usagePointers: List<Pointer<out ModifiableRenameUsage>>) -> prepareFileUpdates(fileUpdater, usagePointers, newName) } .fold(null) { accumulator: FileUpdates?, value: FileUpdates? -> FileUpdates.merge(accumulator, value) } } private suspend fun prepareFileUpdates( fileUpdater: FileUpdater, usagePointers: List<Pointer<out ModifiableRenameUsage>>, newName: String ): FileUpdates? { return readAction { usagePointers.dereferenceOrNull()?.let { usages: List<ModifiableRenameUsage> -> createFileUpdates(fileUpdater.prepareFileUpdateBatch(usages, newName)) } } } private suspend fun prepareModelUpdate(byModelUpdater: Map<ModelUpdater, List<Pointer<out ModifiableRenameUsage>>>): ModelUpdate? { val updates: List<ModelUpdate> = byModelUpdater .flatMap { (modelUpdater: ModelUpdater, usagePointers: List<Pointer<out ModifiableRenameUsage>>) -> readAction { usagePointers.dereferenceOrNull() ?.let { usages: List<ModifiableRenameUsage> -> modelUpdater.prepareModelUpdateBatch(usages) } ?: emptyList() } } return when (updates.size) { 0 -> null 1 -> updates[0] else -> object : ModelUpdate { override fun updateModel(newName: String) { for (update: ModelUpdate in updates) { update.updateModel(newName) } } } } } private fun <X : Any> Collection<Pointer<out X>>.dereferenceOrNull(): List<X>? { ApplicationManager.getApplication().assertReadAccessAllowed() return this.mapNotNull { pointer: Pointer<out X> -> pointer.dereference() }.takeUnless { list: List<X> -> list.isEmpty() } } private suspend fun previewInDialog(project: Project, fileUpdates: FileUpdates): Boolean { if (!Registry.`is`("ide.rename.preview.dialog")) { return true } val preview: Map<VirtualFile, CharSequence> = readAction { fileUpdates.preview() } // write action might happen here, but this code is internal, used to check preview dialog val patch = object : ModelPatch { override fun getBranchChanges(): Map<VirtualFile, CharSequence> = preview override fun applyBranchChanges() = error("not implemented") } return withContext(Dispatchers.EDT) { VcsFacade.getInstance().createPatchPreviewComponent(project, patch)?.let { previewComponent -> DialogBuilder(project) .title(RefactoringBundle.message("rename.preview.tab.title")) .centerPanel(previewComponent) .showAndGet() } } != false } @Internal @TestOnly fun renameAndWait(project: Project, target: RenameTarget, newName: String) { val application = ApplicationManager.getApplication() application.assertIsDispatchThread() require(application.isUnitTestMode) val targetPointer = target.createPointer() val options = RenameOptions( textOptions = TextOptions( commentStringOccurrences = true, textOccurrences = true, ), searchScope = target.maximalSearchScope ?: GlobalSearchScope.projectScope(project) ) runBlocking { withTimeout(timeMillis = 1000 * 60 * 10) { val renameJob = rename(cs = this@withTimeout, project, targetPointer, newName, options, preview = false) while (renameJob.isActive) { UIUtil.dispatchAllInvocationEvents() delay(timeMillis = 10) } } } PsiDocumentManager.getInstance(project).commitAllDocuments() } internal object EmptyRenameValidator: RenameValidator { override fun validate(newName: String): RenameValidationResult { return RenameValidationResult.ok() } }
apache-2.0
016223f05833dd7a57d08505a6339574
34.797583
131
0.742488
4.551671
false
false
false
false
google/iosched
mobile/src/main/java/com/google/samples/apps/iosched/ui/sessiondetail/SessionDetailAdapter.kt
1
8589
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.iosched.ui.sessiondetail import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.LifecycleOwner import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.RecycledViewPool import com.google.samples.apps.iosched.R import com.google.samples.apps.iosched.databinding.ItemGenericSectionHeaderBinding import com.google.samples.apps.iosched.databinding.ItemSessionBinding import com.google.samples.apps.iosched.databinding.ItemSessionInfoBinding import com.google.samples.apps.iosched.databinding.ItemSpeakerBinding import com.google.samples.apps.iosched.model.Speaker import com.google.samples.apps.iosched.model.userdata.UserSession import com.google.samples.apps.iosched.ui.SectionHeader import com.google.samples.apps.iosched.ui.sessioncommon.OnSessionClickListener import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailViewHolder.HeaderViewHolder import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailViewHolder.RelatedViewHolder import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailViewHolder.SessionInfoViewHolder import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailViewHolder.SpeakerViewHolder import com.google.samples.apps.iosched.util.executeAfter /** * [RecyclerView.Adapter] for presenting a session details, composed of information about the * session, any speakers plus any related events. */ class SessionDetailAdapter( private val lifecycleOwner: LifecycleOwner, private val sessionDetailViewModel: SessionDetailViewModel, private val onSessionClickListener: OnSessionClickListener, private val tagRecycledViewPool: RecycledViewPool ) : RecyclerView.Adapter<SessionDetailViewHolder>() { private val differ = AsyncListDiffer<Any>(this, DiffCallback) var speakers: List<Speaker> = emptyList() set(value) { field = value differ.submitList(buildMergedList(sessionSpeakers = value)) } var related: List<UserSession> = emptyList() set(value) { field = value differ.submitList(buildMergedList(relatedSessions = value)) } init { differ.submitList(buildMergedList()) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SessionDetailViewHolder { val inflater = LayoutInflater.from(parent.context) return when (viewType) { R.layout.item_session_info -> SessionInfoViewHolder( ItemSessionInfoBinding.inflate(inflater, parent, false) ) R.layout.item_speaker -> SpeakerViewHolder( ItemSpeakerBinding.inflate(inflater, parent, false) ) R.layout.item_session -> RelatedViewHolder( ItemSessionBinding.inflate(inflater, parent, false).apply { tags.setRecycledViewPool(tagRecycledViewPool) } ) R.layout.item_generic_section_header -> HeaderViewHolder( ItemGenericSectionHeaderBinding.inflate(inflater, parent, false) ) else -> throw IllegalStateException("Unknown viewType $viewType") } } override fun onBindViewHolder(holder: SessionDetailViewHolder, position: Int) { when (holder) { is SessionInfoViewHolder -> holder.binding.executeAfter { viewModel = sessionDetailViewModel tagViewPool = tagRecycledViewPool lifecycleOwner = [email protected] } is SpeakerViewHolder -> holder.binding.executeAfter { val presenter = differ.currentList[position] as Speaker speaker = presenter eventListener = sessionDetailViewModel lifecycleOwner = [email protected] root.setTag(R.id.tag_speaker_id, presenter.id) // Used to identify clicked view } is RelatedViewHolder -> holder.binding.executeAfter { userSession = differ.currentList[position] as UserSession sessionClickListener = onSessionClickListener sessionStarClickListener = sessionDetailViewModel timeZoneId = sessionDetailViewModel.timeZoneId showTime = true lifecycleOwner = [email protected] } is HeaderViewHolder -> holder.binding.executeAfter { sectionHeader = differ.currentList[position] as SectionHeader } } } override fun getItemViewType(position: Int): Int { return when (differ.currentList[position]) { is SessionItem -> R.layout.item_session_info is Speaker -> R.layout.item_speaker is UserSession -> R.layout.item_session is SectionHeader -> R.layout.item_generic_section_header else -> throw IllegalStateException("Unknown view type at position $position") } } override fun getItemCount() = differ.currentList.size /** * This adapter displays heterogeneous data types but `RecyclerView` & `AsyncListDiffer` deal in * a single list of items. We therefore combine them into a merged list, using marker objects * for static items. We still hold separate lists of [speakers] and [related] sessions so that * we can provide them individually, as they're loaded. */ private fun buildMergedList( sessionSpeakers: List<Speaker> = speakers, relatedSessions: List<UserSession> = related ): List<Any> { val merged = mutableListOf<Any>(SessionItem) if (sessionSpeakers.isNotEmpty()) { merged += SectionHeader(R.string.session_detail_speakers_header) merged.addAll(sessionSpeakers) } if (relatedSessions.isNotEmpty()) { merged += SectionHeader(R.string.session_detail_related_header) merged.addAll(relatedSessions) } return merged } } // Marker object for use in our merged representation. object SessionItem /** * Diff items presented by this adapter. */ object DiffCallback : DiffUtil.ItemCallback<Any>() { override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean { return when { oldItem === SessionItem && newItem === SessionItem -> true oldItem is SectionHeader && newItem is SectionHeader -> oldItem == newItem oldItem is Speaker && newItem is Speaker -> oldItem.id == newItem.id oldItem is UserSession && newItem is UserSession -> oldItem.session.id == newItem.session.id else -> false } } @SuppressLint("DiffUtilEquals") // Workaround of https://issuetracker.google.com/issues/122928037 override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean { return when { oldItem is Speaker && newItem is Speaker -> oldItem == newItem oldItem is UserSession && newItem is UserSession -> oldItem == newItem else -> true } } } /** * [RecyclerView.ViewHolder] types used by this adapter. */ sealed class SessionDetailViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { class SessionInfoViewHolder( val binding: ItemSessionInfoBinding ) : SessionDetailViewHolder(binding.root) class SpeakerViewHolder( val binding: ItemSpeakerBinding ) : SessionDetailViewHolder(binding.root) class RelatedViewHolder( val binding: ItemSessionBinding ) : SessionDetailViewHolder(binding.root) class HeaderViewHolder( val binding: ItemGenericSectionHeaderBinding ) : SessionDetailViewHolder(binding.root) }
apache-2.0
61b5059d30fd2c98075127706cfef6ae
40.492754
101
0.696239
5.008163
false
false
false
false
exercism/xkotlin
exercises/practice/spiral-matrix/src/test/kotlin/SpiralMatrixTest.kt
1
1640
import org.junit.Assert.assertArrayEquals import org.junit.Ignore import org.junit.Test class SpiralMatrixTest { @Test fun testEmptySpiral() { val expected = emptyArray<IntArray>() assertArrayEquals(expected, SpiralMatrix.ofSize(0)) } @Ignore @Test fun testTrivialSpiral() { val expected = arrayOf( intArrayOf(1) ) assertArrayEquals(expected, SpiralMatrix.ofSize(1)) } @Ignore @Test fun testSpiralOfSize2() { val expected = arrayOf( intArrayOf(1, 2), intArrayOf(4, 3) ) assertArrayEquals(expected, SpiralMatrix.ofSize(2)) } @Ignore @Test fun testSpiralOfSize3() { val expected = arrayOf( intArrayOf(1, 2, 3), intArrayOf(8, 9, 4), intArrayOf(7, 6, 5) ) assertArrayEquals(expected, SpiralMatrix.ofSize(3)) } @Ignore @Test fun testSpiralOfSize4() { val expected = arrayOf( intArrayOf( 1, 2, 3, 4), intArrayOf(12, 13, 14, 5), intArrayOf(11, 16, 15, 6), intArrayOf(10, 9, 8, 7) ) assertArrayEquals(expected, SpiralMatrix.ofSize(4)) } @Ignore @Test fun testSpiralOfSize5() { val expected = arrayOf( intArrayOf( 1, 2, 3, 4, 5), intArrayOf(16, 17, 18, 19, 6), intArrayOf(15, 24, 25, 20, 7), intArrayOf(14, 23, 22, 21, 8), intArrayOf(13, 12, 11, 10, 9) ) assertArrayEquals(expected, SpiralMatrix.ofSize(5)) } }
mit
81428b9bb9cad3d71b981c84057c2809
21.162162
59
0.535976
3.644444
false
true
false
false
tiarebalbi/okhttp
okhttp/src/main/kotlin/okhttp3/internal/tls/BasicTrustRootIndex.kt
7
1832
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.tls import java.security.cert.X509Certificate import javax.security.auth.x500.X500Principal /** A simple index that of trusted root certificates that have been loaded into memory. */ class BasicTrustRootIndex(vararg caCerts: X509Certificate) : TrustRootIndex { private val subjectToCaCerts: Map<X500Principal, Set<X509Certificate>> init { val map = mutableMapOf<X500Principal, MutableSet<X509Certificate>>() for (caCert in caCerts) { map.getOrPut(caCert.subjectX500Principal) { mutableSetOf() }.add(caCert) } this.subjectToCaCerts = map } override fun findByIssuerAndSignature(cert: X509Certificate): X509Certificate? { val issuer = cert.issuerX500Principal val subjectCaCerts = subjectToCaCerts[issuer] ?: return null return subjectCaCerts.firstOrNull { try { cert.verify(it.publicKey) return@firstOrNull true } catch (_: Exception) { return@firstOrNull false } } } override fun equals(other: Any?): Boolean { return other === this || (other is BasicTrustRootIndex && other.subjectToCaCerts == subjectToCaCerts) } override fun hashCode(): Int { return subjectToCaCerts.hashCode() } }
apache-2.0
fc1477797da89b2e413a1a3cf0e8755c
32.309091
90
0.719978
4.089286
false
false
false
false
allotria/intellij-community
platform/platform-api/src/com/intellij/ui/tabs/impl/EditorTabPainterAdapter.kt
3
2548
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tabs.impl import com.intellij.openapi.util.registry.Registry import com.intellij.ui.tabs.JBTabPainter import java.awt.Graphics import java.awt.Graphics2D import java.awt.Rectangle class EditorTabPainterAdapter : TabPainterAdapter { private val magicOffset = 1 private val painter = JBEditorTabPainter() override val tabPainter: JBTabPainter get() = painter override fun paintBackground(label: TabLabel, g: Graphics, tabs: JBTabsImpl) { val info = label.info val isSelected = info == tabs.selectedInfo val rect = Rectangle(0, 0, label.width, label.height) val g2d = g as Graphics2D if (isSelected) { painter .paintSelectedTab(tabs.position, g2d, rect, tabs.borderThickness, info.tabColor, tabs.isActiveTabs(info), tabs.isHoveredTab(label)) paintBorders(g2d, label, tabs) } else { painter.paintTab(tabs.position, g2d, rect, tabs.borderThickness, info.tabColor, tabs.isActiveTabs(info), tabs.isHoveredTab(label)) paintBorders(g2d, label, tabs) } } private fun paintBorders(g: Graphics2D, label: TabLabel, tabs: JBTabsImpl) { val paintStandardBorder = !tabs.isSingleRow || (!tabs.position.isSide && Registry.`is`("ide.new.editor.tabs.vertical.borders")) val lastPinned = label.isLastPinned val nextToLastPinned = label.isNextToLastPinned val rect = Rectangle(0, 0, label.width, label.height) if (paintStandardBorder || lastPinned || nextToLastPinned) { val bounds = label.bounds if (bounds.x > magicOffset && (paintStandardBorder || nextToLastPinned)) { painter.paintLeftGap(tabs.position, g, rect, tabs.borderThickness) } if (bounds.x + bounds.width < tabs.width - magicOffset && (paintStandardBorder || lastPinned)) { painter.paintRightGap(tabs.position, g, rect, tabs.borderThickness) } } if (tabs.position.isSide && lastPinned) { val bounds = label.bounds if (bounds.y + bounds.height < tabs.height - magicOffset) { painter.paintBottomGap(tabs.position, g, rect, tabs.borderThickness) } } if (tabs.position.isSide && nextToLastPinned) { val bounds = label.bounds if (bounds.y + bounds.height < tabs.height - magicOffset) { painter.paintTopGap(tabs.position, g, rect, tabs.borderThickness) } } } }
apache-2.0
afbf0ccaeb9dc17fc80da27caec7c7ba
36.485294
140
0.686421
3.901991
false
false
false
false
zpao/buck
src/com/facebook/buck/multitenant/service/MemorySharingIntSet.kt
1
12150
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.multitenant.service import io.vavr.collection.HashSet import io.vavr.collection.Set import it.unimi.dsi.fastutil.ints.IntArrayList import it.unimi.dsi.fastutil.ints.IntCollection private val EMPTY_INT_SET: MemorySharingIntSet = MemorySharingIntSet.Unique(IntArray(0)) /** * A set of [Int] objects. Note that the type of storage we use depends on a combination of (1) the size of * the set and (2) how frequently it is updated. */ sealed class MemorySharingIntSet : Iterable<Int> { companion object { fun empty(): MemorySharingIntSet = EMPTY_INT_SET } abstract val size: Int /** * Returns `true` if [element] is found in the [MemorySharingIntSet]. */ abstract fun contains(element: Int): Boolean /** * Custom method for adding the values in this set to an [IntCollection]. This gives the * implementation the opportunity to avoid boxing and unboxing integers. */ fun addAllTo(destination: IntCollection) { /** Although it might be slightly more efficient to wrap the [IntArray] as an [IntCollection] so that we can use [IntCollection.addAll], as it does some some capacity checks before calling [IntCollection.add] in a loop, but [IntCollection] is a little annoying to implement, so we should only bother if profiling proves it is worth it. Incidentally, [it.unimi.dsi.fastutil.ints.IntIterators.wrap] (int[]) almost does what we need except [addAll] requires an [IntCollection] rather than an [IntListIterator]. */ for (value in iterator()) { destination.add(value) } } /** * Returns [true] if the [MemorySharingIntSet] is empty (contains no elements), [false] otherwise. */ fun isEmpty() = size == 0 /** * Unique representation of a [IntArray] that does not share any memory with another [MemorySharingIntSet]. * The [values] passed into the constructor must be sorted in incrementing order and contain no duplicates. */ class Unique(val values: IntArray) : MemorySharingIntSet() { override val size: Int get() = values.size override fun iterator(): Iterator<Int> = IntArrayList.wrap(values).iterator() override fun contains(element: Int): Boolean = values.binarySearch(element) in 0 until size } /** * Note this is backed by a persistent collection, which for a single instance, we expect to * take up more memory than if it were represented as a [IntArray]. */ class Persistent(val values: Set<Int>) : MemorySharingIntSet() { override val size: Int get() = values.size() override fun iterator(): Iterator<Int> = values.iterator() override fun contains(element: Int): Boolean = values.contains(element) } } fun MemorySharingIntSet?.isNullOrEmpty() = this == null || this.isEmpty() /** * Enum type that represents either an "add" or a "remove" to a [MemorySharingIntSet]. These can be * computed independently and later "applied" to a persistent collection to derive a new version. */ sealed class SetDelta : Comparable<SetDelta> { abstract val value: Int override fun compareTo(other: SetDelta): Int = value.compareTo(other.value) data class Add(override val value: Int) : SetDelta() data class Remove(override val value: Int) : SetDelta() } /** * Takes a list of individual updates applied to a repo at a point in time and computes the * aggregate changes that need to be made. */ fun <T> deriveDeltas( updates: List<Pair<T, SetDelta>>, loadPreviousState: (value: T) -> MemorySharingIntSet? ): Map<T, MemorySharingIntSet?> { val deltasByKey = groupDeltasByKey(updates) val deltaDeriveInfos = deltasByKey.map { (value, setDeltas) -> DeltaDeriveInfo(value, loadPreviousState(value), setDeltas) } return aggregateDeltaDeriveInfos(deltaDeriveInfos) } /** * Iterates the `deltas` and for each key, collects its corresponding deltas into its * own [List]. Returns [Map], grouped by a distinct key. */ private fun <T> groupDeltasByKey(deltas: List<Pair<T, SetDelta>>): Map<T, MutableList<SetDelta>> { /** [out] is effectively a multimap, but none of the Guava [ListMultimap] implementations work for us here because we want to be able to sort the [List] for each entry when we are done populating the map and Guava's [ListMultimap] returns the [List] for each entry as an unmodifiable view. */ val out = mutableMapOf<T, MutableList<SetDelta>>() deltas.forEach { (value, setDelta) -> out.getOrPut(value, { mutableListOf() }).add(setDelta) } return out } /** * Information needed to derive a new [MemorySharingIntSet] from an existing one. * @property value target whose [MemorySharingIntSet] this represents * @property previousState previous version of [MemorySharingIntSet] for the [value] * @property deltas on top of old [MemorySharingIntSet]. This is not guaranteed to be sorted! Though it is a * [MutableList] so a client is free to sort it. */ internal data class DeltaDeriveInfo<T>( val value: T, val previousState: MemorySharingIntSet?, val deltas: MutableList<SetDelta> ) /** * Takes a list of values whose [MemorySharingIntSet]s have changed and produces the new version of the [MemorySharingIntSet]s * for each value. Where it makes sense, persistent collections are used to make more * efficient use of memory, as they make it possible to share information between old and new * versions of [MemorySharingIntSet]. */ internal fun <T> aggregateDeltaDeriveInfos( deltaDeriveInfos: List<DeltaDeriveInfo<T>> ): Map<T, MemorySharingIntSet?> { /** We use [java.util.HashMap] so we can specify the [initialCapacity]. We use the fully qualified name here to clarify that this is NOT a [io.vavr.collection.HashMap]. */ val out = java.util.HashMap<T, MemorySharingIntSet?>(deltaDeriveInfos.size) deltaDeriveInfos.forEach { (value, previousState, deltas) -> out[value] = if (previousState == null) { // No one was depending on this value at the previous generation. All of the // deltas must be of type Add. check(deltas.all { it is SetDelta.Add }) { "There was a 'Remove' delta for a non-existent set." } deltas.sort() val values = IntArray(deltas.size) { index -> deltas[index].value } /** Even though [values] might be large, we create a unique copy of the data because we would prefer to use a more compact storage format if it turns out that it is not going to be updated very frequently. */ MemorySharingIntSet.Unique(values) } else { applyDeltas(previousState, deltas) } } return out } /** * If the size of the [MemorySharingIntSet] is below this size, we always choose Unique over Persistent. * NOTE: we should use telemetry to determine the right value for this constant. Currently, it is * completely pulled out of thin air. */ internal const val THRESHOLD_FOR_UNIQUE_VS_PERSISTENT = 10 /** * Derives a new [MemorySharingIntSet] from an existing one by applying some deltas. If applying all of the * deltas results in an empty set, returns [null]. * @param previousState original set * @param deltas is not required to be sorted, but it may be sorted as a result of invoking this * method. By construction, it should also be non-empty. */ private fun applyDeltas( previousState: MemorySharingIntSet, deltas: MutableList<SetDelta> ): MemorySharingIntSet? { val size = deltas.fold(previousState.size) { acc, delta -> when (delta) { is SetDelta.Add -> acc + 1 is SetDelta.Remove -> acc - 1 } } return when { size == 0 -> null size < THRESHOLD_FOR_UNIQUE_VS_PERSISTENT -> createSimpleSet(previousState, deltas, size) else -> { val existingSet = when (previousState) { is MemorySharingIntSet.Unique -> { /** The old version was [MemorySharingIntSet.Unique], but now we have exceeded [THRESHOLD_FOR_UNIQUE_VS_PERSISTENT], so now we want to use [MemorySharingIntSet.Persistent] for the new version. */ HashSet.ofAll(previousState) } is MemorySharingIntSet.Persistent -> { previousState.values } } deriveNewPersistentSet(existingSet, deltas) } } } private fun createSimpleSet( previousState: MemorySharingIntSet, deltas: MutableList<SetDelta>, expectedSize: Int ): MemorySharingIntSet.Unique { val oldSetSorted: IntArray = when (previousState) { is MemorySharingIntSet.Unique -> previousState.values is MemorySharingIntSet.Persistent -> { val array = previousState.values.toMutableList().toIntArray() array.sort() array } } deltas.sort() val newSet = IntArray(expectedSize) /** Now that both [oldSetSorted] and deltas are sorted, we walk forward and populate [newSet], as appropriate. */ var oldIndex = 0 var deltaIndex = 0 var index = 0 while (oldIndex < oldSetSorted.size && deltaIndex < deltas.size) { val oldValue = oldSetSorted[oldIndex] val delta = deltas[deltaIndex] val value = delta.value when { oldValue < value -> { // Next delta does not affect oldValue, so add oldValue to the output. newSet[index++] = oldValue ++oldIndex } oldValue > value -> when (delta) { is SetDelta.Add -> { newSet[index++] = value ++deltaIndex } is SetDelta.Remove -> error("Should not Remove when $value does not exist in the previous set.") } oldValue == value -> when (delta) { is SetDelta.Add -> { error("Should not Add when $value already exists in the previous set.") } is SetDelta.Remove -> { // We should omit this value from the output, so ++oldIndex ++deltaIndex } } else -> error("Case not yet implemented") } } while (oldIndex < oldSetSorted.size) { newSet[index++] = oldSetSorted[oldIndex++] } while (deltaIndex < deltas.size) { when (val delta = deltas[deltaIndex++]) { is SetDelta.Add -> newSet[index++] = delta.value is SetDelta.Remove -> error("Should not Remove when ${delta.value} does not exist in the previous set.") } } if (index != expectedSize) { error("Only assigned $index out of $expectedSize slots in output.") } return MemorySharingIntSet.Unique(newSet) } private fun deriveNewPersistentSet( previousState: Set<Int>, deltas: List<SetDelta> ): MemorySharingIntSet.Persistent { var out = previousState deltas.forEach { delta -> out = when (delta) { is SetDelta.Add -> out.add(delta.value) is SetDelta.Remove -> out.remove(delta.value) } } return MemorySharingIntSet.Persistent(out) }
apache-2.0
12efa816d977f08f07cfd39532e3c01f
37.449367
132
0.647407
4.513373
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/jdkDownloader/JdkDownloadDialog.kt
3
15298
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.projectRoots.impl.jdkDownloader import com.intellij.execution.wsl.WSLDistribution import com.intellij.execution.wsl.WslDistributionManager import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.ui.* import com.intellij.openapi.util.NlsSafe import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.* import com.intellij.ui.components.textFieldWithBrowseButton import com.intellij.ui.layout.* import com.intellij.util.text.VersionComparatorUtil import java.awt.Component import java.awt.event.ItemEvent import java.nio.file.Path import java.util.function.Function import javax.swing.* import javax.swing.event.DocumentEvent class JdkDownloaderModel( val versionGroups: List<JdkVersionItem>, val defaultItem: JdkItem, val defaultVersion: JdkVersionItem, val defaultVersionVendor: JdkVersionVendorItem, ) class JdkVersionItem( @NlsSafe val jdkVersion: String, /* we should prefer the default selected item from the JDKs.json feed, * the list below is sorted by vendor, and default item is not necessarily first */ val defaultSelectedItem: JdkVersionVendorItem, val includedItems: List<JdkVersionVendorItem>, val excludedItems: List<JdkVersionVendorItem> ) { //we reuse model to keep selected element in-memory! val model: ComboBoxModel<JdkVersionVendorElement> by lazy { require(this.includedItems.isNotEmpty()) { "No included items for $jdkVersion" } require(this.defaultSelectedItem in this.includedItems) { "Default selected item must be in the list of items for $jdkVersion" } val allItems = when { this.excludedItems.isNotEmpty() -> this.includedItems + JdkVersionVendorGroupSeparator + this.excludedItems else -> this.includedItems } DefaultComboBoxModel(allItems.toTypedArray()).also { it.selectedItem = defaultSelectedItem } } } sealed class JdkVersionVendorElement object JdkVersionVendorGroupSeparator : JdkVersionVendorElement() class JdkVersionVendorItem( val item: JdkItem ) : JdkVersionVendorElement() { var parent: JdkVersionItem? = null val selectItem get() = parent?.includedItems?.find { it.item == item } ?: this val canBeSelected: Boolean get() = parent == null } private class JdkVersionVendorCombobox: ComboBox<JdkVersionVendorElement>() { private val myActionItemSelectedListeners = mutableListOf<(item: JdkVersionVendorItem) -> Unit>() override fun setSelectedItem(anObject: Any?) { if (anObject !is JdkVersionVendorItem || selectedItem === anObject) return if (anObject.canBeSelected) { super.setSelectedItem(anObject) } else { myActionItemSelectedListeners.forEach { it(anObject) } } } // the listener is called for all JdkVersionVendorItem, event for non-selectable ones fun onActionItemSelected(action: (item: JdkVersionVendorItem) -> Unit) { myActionItemSelectedListeners += action } override fun setModel(aModel: ComboBoxModel<JdkVersionVendorElement>?) { if (model === aModel) return super.setModel(aModel) //change of data model does not file selected item change, which we'd like to receive selectedItemChanged() } init { isSwingPopup = false renderer = object: ColoredListCellRenderer<JdkVersionVendorElement>() { override fun getListCellRendererComponent(list: JList<out JdkVersionVendorElement>?, value: JdkVersionVendorElement?, index: Int, selected: Boolean, hasFocus: Boolean): Component { if (value === JdkVersionVendorGroupSeparator ) { return SeparatorWithText().apply { caption = ProjectBundle.message("dialog.row.jdk.other.versions") } } return super.getListCellRendererComponent(list, value, index, selected, hasFocus) } override fun customizeCellRenderer(list: JList<out JdkVersionVendorElement>, value: JdkVersionVendorElement?, index: Int, selected: Boolean, hasFocus: Boolean) { if (value !is JdkVersionVendorItem) { append("???") return } append(value.item.product.packagePresentationText, SimpleTextAttributes.REGULAR_ATTRIBUTES) val jdkVersion = value.item.jdkVersion if (jdkVersion != value.parent?.jdkVersion) { append(" $jdkVersion", SimpleTextAttributes.GRAYED_ATTRIBUTES, false) } value.item.presentableArchIfNeeded?.let { archIfNeeded -> append(" $archIfNeeded", SimpleTextAttributes.GRAYED_ATTRIBUTES, false) } } } } } private fun List<JdkVersionVendorItem>.sortedForUI() = this.sortedBy { it.item.product.packagePresentationText.toLowerCase() } fun buildJdkDownloaderModel(allItems: List<JdkItem>): JdkDownloaderModel { @NlsSafe fun JdkItem.versionGroupId() = this.presentableMajorVersionString val groups = allItems .groupBy { it.versionGroupId() } .mapValues { (jdkVersion, groupItems) -> val majorVersion = groupItems.first().jdkMajorVersion val includedItems = groupItems .map { JdkVersionVendorItem(item = it) } val includedProducts = groupItems.map { it.product }.toHashSet() val excludedItems = allItems .asSequence() .filter { it.product !in includedProducts } .filter { it !in groupItems } .groupBy { it.product } .mapValues { (_, jdkItems) -> val comparator = Comparator.comparing(Function<JdkItem, String> { it.jdkVersion }, VersionComparatorUtil.COMPARATOR) //first try to find closest newer version jdkItems .filter { it.jdkMajorVersion >= majorVersion } .minWithOrNull(comparator) // if not, let's try an older version too ?: jdkItems .filter { it.jdkMajorVersion < majorVersion } .maxWithOrNull(comparator) } //we assume the initial order of feed items contains vendors in the right order .mapNotNull { it.value } .map { JdkVersionVendorItem(item = it) } JdkVersionItem(jdkVersion, includedItems.firstOrNull() ?: error("Empty group of includeItems for $jdkVersion"), includedItems.sortedForUI(), excludedItems.sortedForUI()) } //assign parent relation groups.values.forEach { parent -> parent.excludedItems.forEach { it.parent = groups.getValue(it.item.versionGroupId()) } } val versionItems = groups.values .sortedWith(Comparator.comparing(Function<JdkVersionItem, String> { it.jdkVersion }, VersionComparatorUtil.COMPARATOR).reversed()) val defaultItem = allItems.firstOrNull { it.isDefaultItem } /*pick the newest default JDK */ ?: allItems.firstOrNull() /* pick just the newest JDK is no default was set (aka the JSON is broken) */ ?: error("There must be at least one JDK to install") /* totally broken JSON */ val defaultJdkVersionItem = versionItems.firstOrNull { group -> group.includedItems.any { it.item == defaultItem } } ?: error("Default item is not found in the list") val defaultVersionVendor = defaultJdkVersionItem.includedItems.find { it.item == defaultItem } ?: defaultJdkVersionItem.includedItems.first() return JdkDownloaderModel( versionGroups = versionItems, defaultItem = defaultItem, defaultVersion = defaultJdkVersionItem, defaultVersionVendor = defaultVersionVendor, ) } private val jdkVersionItemRenderer = object: ColoredListCellRenderer<JdkVersionItem>() { override fun customizeCellRenderer(list: JList<out JdkVersionItem>, value: JdkVersionItem?, index: Int, selected: Boolean, hasFocus: Boolean) { append(value?.jdkVersion ?: return, SimpleTextAttributes.REGULAR_ATTRIBUTES) } } internal class JdkDownloaderMergedModel( private val mainModel: JdkDownloaderModel, private val wslModel: JdkDownloaderModel?, val wslDistributions: List<WSLDistribution>, val projectWSLDistribution: WSLDistribution? ) { val hasWsl get() = wslModel != null fun selectModel(wsl: Boolean): JdkDownloaderModel = when { wsl && wslModel != null -> wslModel else -> mainModel } } internal class JdkDownloadDialog( val project: Project?, val parentComponent: Component?, val sdkType: SdkTypeId, val mergedModel: JdkDownloaderMergedModel, ) : DialogWrapper(project, parentComponent, false, IdeModalityType.PROJECT) { private val panel: JComponent private val versionComboBox : ComboBox<JdkVersionItem> private val vendorComboBox: JdkVersionVendorCombobox private val installDirTextField: TextFieldWithBrowseButton? private val installDirCombo: ComboBox<String>? private val installDirComponent: JComponent private var currentModel : JdkDownloaderModel? = null private lateinit var selectedItem: JdkItem private lateinit var selectedPath: String init { title = ProjectBundle.message("dialog.title.download.jdk") setResizable(false) versionComboBox = ComboBox() versionComboBox.renderer = jdkVersionItemRenderer versionComboBox.isSwingPopup = false vendorComboBox = JdkVersionVendorCombobox() if (mergedModel.hasWsl) { installDirCombo = ComboBox<String>() installDirCombo.isEditable = true installDirCombo.initBrowsableEditor( BrowseFolderRunnable( ProjectBundle.message("dialog.title.select.path.to.install.jdk"), null, project, FileChooserDescriptorFactory.createSingleFolderDescriptor(), installDirCombo, TextComponentAccessor.STRING_COMBOBOX_WHOLE_TEXT ), disposable) installDirCombo.addActionListener { onTargetPathChanged(installDirCombo.editor.item as String) } installDirTextField = null installDirComponent = installDirCombo } else { installDirTextField = textFieldWithBrowseButton( project = project, browseDialogTitle = ProjectBundle.message("dialog.title.select.path.to.install.jdk"), fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() ) installDirTextField.onTextChange { onTargetPathChanged(it) } installDirCombo = null installDirComponent = installDirTextField } vendorComboBox.onActionItemSelected(::onVendorActionItemSelected) vendorComboBox.onSelectionChange(::onVendorSelectionChange) versionComboBox.onSelectionChange(::onVersionSelectionChange) panel = panel { row(ProjectBundle.message("dialog.row.jdk.version")) { versionComboBox.invoke().sizeGroup("combo") } row(ProjectBundle.message("dialog.row.jdk.vendor")) { vendorComboBox.invoke().sizeGroup("combo").focused() } row(ProjectBundle.message("dialog.row.jdk.location")) { installDirComponent.invoke() } } myOKAction.putValue(Action.NAME, ProjectBundle.message("dialog.button.download.jdk")) setModel(mergedModel.projectWSLDistribution != null) init() } private fun setModel(forWsl: Boolean) { val model = mergedModel.selectModel(forWsl) if (currentModel === model) return val prevSelectedVersion = versionComboBox.selectedItem as? JdkVersionItem val prevSelectedJdk = (vendorComboBox.selectedItem as? JdkVersionVendorItem)?.takeIf { it.canBeSelected } currentModel = model versionComboBox.model = DefaultComboBoxModel(model.versionGroups.toTypedArray()) val newVersionItem = if (prevSelectedVersion != null) { model.versionGroups.singleOrNull { it.jdkVersion == prevSelectedVersion.jdkVersion } } else null val newVendorItem = if (newVersionItem != null && prevSelectedJdk != null) { (newVersionItem.includedItems + newVersionItem.excludedItems).singleOrNull { it.canBeSelected && it.item.suggestedSdkName == prevSelectedJdk.item.suggestedSdkName } } else null onVersionSelectionChange(newVersionItem ?: model.defaultVersion) onVendorSelectionChange(newVendorItem ?: model.defaultVersionVendor) } private fun onTargetPathChanged(path: String) { @Suppress("NAME_SHADOWING") val path = FileUtil.expandUserHome(path) selectedPath = path setModel(WslDistributionManager.isWslPath(path)) } private fun onVendorActionItemSelected(it: JdkVersionVendorElement?) { if (it !is JdkVersionVendorItem) return val parent = it.parent ?: return onVersionSelectionChange(parent) vendorComboBox.selectedItem = it.selectItem } private fun onVendorSelectionChange(it: JdkVersionVendorElement?) { if (it !is JdkVersionVendorItem || !it.canBeSelected) return vendorComboBox.selectedItem = it.selectItem val newVersion = it.item val path = JdkInstaller.getInstance().defaultInstallDir(newVersion, mergedModel.projectWSLDistribution).toString() val relativePath = FileUtil.getLocationRelativeToUserHome(path) if (installDirTextField != null) { installDirTextField.text = relativePath } else { installDirCombo!!.model = CollectionComboBoxModel(getSuggestedInstallDirs(newVersion), relativePath) } selectedPath = path selectedItem = newVersion } private fun getSuggestedInstallDirs(newVersion: JdkItem): List<String> { return (listOf(null) + mergedModel.wslDistributions).mapTo(LinkedHashSet()) { JdkInstaller.getInstance().defaultInstallDir(newVersion, it).toString() }.map { FileUtil.getLocationRelativeToUserHome(it) } } private fun onVersionSelectionChange(it: JdkVersionItem?) { if (it == null) return versionComboBox.selectedItem = it vendorComboBox.model = it.model } override fun doValidate(): ValidationInfo? { super.doValidate()?.let { return it } val (_, error) = JdkInstaller.getInstance().validateInstallDir(selectedPath) return error?.let { ValidationInfo(error, installDirComponent) } } override fun createCenterPanel() = panel fun selectJdkAndPath(): Pair<JdkItem, Path>? { if (!showAndGet()) { return null } val (selectedFile) = JdkInstaller.getInstance().validateInstallDir(selectedPath) if (selectedFile == null) { return null } return selectedItem to selectedFile } private inline fun TextFieldWithBrowseButton.onTextChange(crossinline action: (String) -> Unit) { textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) { action(text) } }) } private inline fun <reified T> ComboBox<T>.onSelectionChange(crossinline action: (T) -> Unit) { this.addItemListener { e -> if (e.stateChange == ItemEvent.SELECTED) action(e.item as T) } } }
apache-2.0
addea4f00b7138a3a9407b398080d93c
36.960298
167
0.707936
4.764248
false
false
false
false
JetBrains/teamcity-dnx-plugin
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/DotnetToolProvider.kt
1
2587
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.dotnet import jetbrains.buildServer.agent.* import org.apache.log4j.Logger import java.io.File /** * Lookups for .NET CLI utilities. */ class DotnetToolProvider( toolProvidersRegistry: ToolProvidersRegistry, private val _toolSearchService: ToolSearchService, private val _toolEnvironment: ToolEnvironment, private val _dotnetSdksProviderImpl: DotnetSdksProvider) : ToolProvider { init { toolProvidersRegistry.registerToolProvider(this) } override fun supports(toolName: String): Boolean = DotnetConstants.RUNNER_TYPE.equals(toolName, ignoreCase = true) override fun getPath(toolName: String): String = executablePath ?.absolutePath ?: throw ToolCannotBeFoundException(""" Unable to locate tool $toolName in the system. Please make sure that `PATH` variable contains .NET CLI toolchain directory or defined `${DotnetConstants.TOOL_HOME}` variable.""".trimIndent()) private val executablePath: File? by lazy { var dotnetRuntime: File? = null val executables = _toolSearchService.find(DotnetConstants.EXECUTABLE, _toolEnvironment.homePaths + _toolEnvironment.defaultPaths + _toolEnvironment.environmentPaths) for (dotnetExecutable in executables) { if (_dotnetSdksProviderImpl.getSdks(dotnetExecutable).any()) { return@lazy dotnetExecutable } else { LOG.debug("Cannot find .NET Core SDK for <${dotnetExecutable}>.") dotnetRuntime = dotnetExecutable } } dotnetRuntime?.let { LOG.warn(".NET Core SDK was not found (found .NET Core runtime at path <${it.absolutePath}>). Install .NET Core SDK into the default location or set ${DotnetConstants.TOOL_HOME} environment variable pointing to the installation directory.") } return@lazy null } @Throws(ToolCannotBeFoundException::class) override fun getPath(toolName: String, build: AgentRunningBuild, runner: BuildRunnerContext): String { return if (runner.virtualContext.isVirtual) { DotnetConstants.EXECUTABLE } else { getPath(toolName) } } companion object { private val LOG = Logger.getLogger(DotnetToolProvider::class.java) } }
apache-2.0
505fc4cb266ab54bf4e4afadbf4755db
37.058824
252
0.668342
4.899621
false
false
false
false
mrlem/happy-cows
core/src/org/mrlem/happycows/ui/actors/BottleActor.kt
1
1360
package org.mrlem.happycows.ui.actors import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.physics.box2d.Body import com.badlogic.gdx.utils.Align import org.mrlem.happycows.domain.model.DynamicEntity import org.mrlem.happycows.domain.model.DynamicEntity.Bottle.State.DESTROYED import org.mrlem.happycows.ui.caches.TextureCache import org.mrlem.happycows.ui.Sounds.playDing /** * The evil milk bottle the player is trying to destroy. * * @author Sébastien Guillemin <[email protected]> */ class BottleActor(body: Body, size: Vector2) : AbstractPhysicsActor(body, size) { private val texture = TextureCache.instance[TextureCache.BOTTLE_TEXTURE_ID] private val textureRegion = TextureRegion(texture) private val entity get() = body?.userData as? DynamicEntity.Bottle override fun draw(batch: Batch, parentAlpha: Float) { batch.setColor(color.r, color.g, color.b, color.a * parentAlpha) batch.draw(textureRegion, x, y, originX, originY, width, height, scaleX, scaleY, rotation) } override fun sizeChanged() { setOrigin(Align.center) } override fun act(delta: Float) { super.act(delta) if (entity?.state == DESTROYED) { playDing() remove() } } }
gpl-3.0
2bf9184db6fe9644a850e0e0944c96ce
31.357143
98
0.719647
3.614362
false
false
false
false
leafclick/intellij-community
platform/vcs-log/impl/test/com/intellij/vcs/log/history/FileHistoryTest.kt
1
13580
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.history import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.LocalFilePath import com.intellij.util.containers.MultiMap import com.intellij.vcs.log.data.index.VcsLogPathsIndex import com.intellij.vcs.log.data.index.VcsLogPathsIndex.ChangeKind.* import com.intellij.vcs.log.graph.TestGraphBuilder import com.intellij.vcs.log.graph.TestPermanentGraphInfo import com.intellij.vcs.log.graph.api.LinearGraph import com.intellij.vcs.log.graph.asTestGraphString import com.intellij.vcs.log.graph.graph import com.intellij.vcs.log.graph.impl.facade.BaseController import com.intellij.vcs.log.graph.impl.facade.FilteredController import gnu.trove.THashMap import gnu.trove.TIntObjectHashMap import org.junit.Assert import org.junit.Assume.assumeFalse import org.junit.Test class FileHistoryTest { fun LinearGraph.assert(startCommit: Int, startPath: FilePath, fileNamesData: FileHistoryData, result: TestGraphBuilder.() -> Unit) { val permanentGraphInfo = TestPermanentGraphInfo(this) val baseController = BaseController(permanentGraphInfo) val filteredController = object : FilteredController(baseController, permanentGraphInfo, fileNamesData.getCommits()) {} val historyBuilder = FileHistoryBuilder(startCommit, startPath, fileNamesData, EMPTY_HISTORY) historyBuilder.accept(filteredController, permanentGraphInfo) val expectedResultGraph = graph(result) val actualResultGraph = filteredController.collapsedGraph.compiledGraph Assert.assertEquals(expectedResultGraph.asTestGraphString(true), actualResultGraph.asTestGraphString(true)) } @Test fun linearHistory() { val path = LocalFilePath("file.txt", false) val fileNamesData = FileNamesDataBuilder(path) .addChange(path, 7, listOf(ADDED), listOf(7)) .addChange(path, 6, listOf(MODIFIED), listOf(7)) .addChange(path, 4, listOf(MODIFIED), listOf(5)) .addChange(path, 2, listOf(REMOVED), listOf(3)) .addChange(path, 0, listOf(ADDED), listOf(1)) .build() graph { 0(1) 1(2) 2(3) 3(4) 4(5) 5(6) 6(7) 7() }.assert(0, path, fileNamesData) { 0(2.dot) 2(4.dot) 4(6.dot) 6(7) 7() } } @Test fun historyWithRename() { val afterPath = LocalFilePath("after.txt", false) val beforePath = LocalFilePath("before.txt", false) val fileNamesData = FileNamesDataBuilder(afterPath) .addChange(beforePath, 6, listOf(ADDED), listOf(7)) .addChange(beforePath, 4, listOf(REMOVED), listOf(5)) .addChange(afterPath, 4, listOf(ADDED), listOf(5)) .addRename(5, 4, beforePath, afterPath) .addChange(afterPath, 2, listOf(MODIFIED), listOf(3)) .build() graph { 0(1) 1(2) 2(3) 3(4) 4(5) 5(6) 6(7) 7() }.assert(0, afterPath, fileNamesData) { 2(4.dot) 4(6.dot) 6() } } @Test fun historyForDeleted() { val path = LocalFilePath("file.txt", false) val fileNamesData = FileNamesDataBuilder(path) .addChange(path, 7, listOf(ADDED), listOf(7)) .addChange(path, 4, listOf(MODIFIED), listOf(5)) .addChange(path, 2, listOf(REMOVED), listOf(3)) .build() val graph = graph { 0(1) 1(2) 2(3) 3(4) 4(5) 5(6) 6(7) 7() } graph.assert(0, path, fileNamesData) { 2(4.dot) 4(7.dot) 7() } graph.assert(4, path, fileNamesData) { 2(4.dot) 4(7.dot) 7() } } @Test fun historyWithMerges() { val path = LocalFilePath("file.txt", false) val fileNamesData = FileNamesDataBuilder(path) .addChange(path, 7, listOf(ADDED), listOf(7)) .addChange(path, 6, listOf(MODIFIED), listOf(7)) .addChange(path, 4, listOf(NOT_CHANGED, MODIFIED), listOf(6, 5)) .addChange(path, 3, listOf(MODIFIED), listOf(6)) .addChange(path, 2, listOf(MODIFIED), listOf(4)) .addChange(path, 1, listOf(MODIFIED, MODIFIED), listOf(3, 2)) .addChange(path, 0, listOf(MODIFIED), listOf(1)) .build() graph { 0(1) 1(2, 3) 2(4) 3(6) 4(6, 5) 5(7) 6(7) 7() }.assert(0, path, fileNamesData) { 0(1) 1(3, 2) 2(6.dot) 3(6) 6(7) 7() } } /** * Rename happens in one branch, while the other branch only consists of couple of trivial merge commits. */ @Test fun historyWithUndetectedRename() { val after = LocalFilePath("after.txt", false) val before = LocalFilePath("before.txt", false) val fileNamesData = FileNamesDataBuilder(after) .addChange(before, 7, listOf(ADDED), listOf(7)) .addChange(before, 6, listOf(MODIFIED), listOf(7)) .addChange(before, 5, listOf(MODIFIED), listOf(6)) .addChange(before, 4, listOf(REMOVED), listOf(5)) .addChange(after, 4, listOf(ADDED), listOf(5)) .addRename(5, 4, before, after) .addChange(after, 3, listOf(MODIFIED), listOf(4)) .addChange(before, 2, listOf(MODIFIED, NOT_CHANGED), listOf(6, 5)) .addChange(before, 1, listOf(REMOVED, NOT_CHANGED), listOf(2, 3)) .addChange(after, 1, listOf(ADDED, NOT_CHANGED), listOf(2, 3)) // rename is not detected at merge commit 1 .addChange(after, 0, listOf(MODIFIED), listOf(1)) .build() graph { 0(1) 1(2, 3) 2(6, 5) 3(4) 4(5) 5(6) 6(7) 7() }.assert(0, after, fileNamesData) { 0(3.dot) 3(4) 4(5) 5(6) 6(7) 7() } } @Test fun historyWithCyclicRenames() { val aFile = LocalFilePath("a.txt", false) val bFile = LocalFilePath("b.txt", false) val fileNamesData = FileNamesDataBuilder(aFile) .addChange(aFile, 4, listOf(ADDED), listOf(4)) .addChange(aFile, 2, listOf(REMOVED), listOf(3)) .addChange(bFile, 2, listOf(ADDED), listOf(3)) .addRename(3, 2, aFile, bFile) .addChange(bFile, 0, listOf(REMOVED), listOf(1)) .addChange(aFile, 0, listOf(ADDED), listOf(1)) .addRename(1, 0, bFile, aFile) .build() graph { 0(1) 1(2) 2(3) 3(4) 4() }.assert(0, aFile, fileNamesData) { 0(2.dot) 2(4.dot) 4() } } @Test fun historyWithCyclicCaseOnlyRenames() { assumeFalse("Case insensitive fs is required", SystemInfo.isFileSystemCaseSensitive) val lowercasePath = LocalFilePath("file.txt", false) val uppercasePath = LocalFilePath("FILE.TXT", false) val mixedPath = LocalFilePath("FiLe.TxT", false) val fileNamesData = FileNamesDataBuilder(lowercasePath) .addChange(lowercasePath, 7, listOf(ADDED), listOf(7)) .addChange(lowercasePath, 6, listOf(MODIFIED), listOf(7)) .addChange(lowercasePath, 5, listOf(REMOVED), listOf(6)) .addChange(mixedPath, 5, listOf(ADDED), listOf(6)) .addRename(6, 5, lowercasePath, mixedPath) .addChange(mixedPath, 4, listOf(MODIFIED), listOf(5)) .addChange(mixedPath, 3, listOf(REMOVED), listOf(4)) .addChange(uppercasePath, 3, listOf(ADDED), listOf(4)) .addRename(4, 3, mixedPath, uppercasePath) .addChange(uppercasePath, 2, listOf(MODIFIED), listOf(3)) .addChange(uppercasePath, 1, listOf(REMOVED), listOf(2)) .addChange(lowercasePath, 1, listOf(ADDED), listOf(2)) .addRename(2, 1, uppercasePath, lowercasePath) .build() graph { 0(1) 1(2) 2(3) 3(4) 4(5) 5(6) 6(7) 7() }.assert(0, lowercasePath, fileNamesData) { 1(2) 2(3) 3(4) 4(5) 5(6) 6(7) 7() } } /* * Two file histories: `create initialFile.txt, rename to file.txt, rename to otherFile.txt` and some time later `create file.txt` */ @Test fun twoFileByTheSameName() { val file = LocalFilePath("file.txt", false) val otherFile = LocalFilePath("otherFile.txt", false) val initialFile = LocalFilePath("initialFile.txt", false) val fileNamesData = FileNamesDataBuilder(file) .addChange(file, 0, listOf(MODIFIED), listOf(1)) .addChange(otherFile, 1, listOf(MODIFIED), listOf(2)) .addChange(file, 2, listOf(ADDED), listOf(3)) .addChange(otherFile, 3, listOf(ADDED), listOf(4)) .addChange(file, 3, listOf(REMOVED), listOf(4)) .addRename(4, 3, file, otherFile) .addChange(file, 5, listOf(ADDED), listOf(6)) .addChange(initialFile, 5, listOf(REMOVED), listOf(6)) .addRename(6, 5, initialFile, file) .addChange(initialFile, 6, listOf(ADDED), listOf(6)) .build() graph { 0(1) 1(2) 2(3) 3(4) 4(5) 5(6) 6() }.assert(0, file, fileNamesData) { 0(2.dot) 2() } } @Test fun revertedDeletion() { val file = LocalFilePath("file.txt", false) val renamedFile = LocalFilePath("renamedFile.txt", false) val fileNamesData = FileNamesDataBuilder(file) .addChange(renamedFile, 0, listOf(ADDED), listOf(1)) .addChange(file, 0, listOf(REMOVED), listOf(1)) .addRename(1, 0, file, renamedFile) .addChange(file, 1, listOf(ADDED), listOf(2)) .addChange(file, 3, listOf(REMOVED), listOf(4)) .addChange(file, 4, listOf(MODIFIED), listOf(5)) .addChange(file, 5, listOf(ADDED), listOf(6)) .build() graph { 0(1) 1(2) 2(3) 3(4) 4(5) 5(6) 6() }.assert(0, renamedFile, fileNamesData) { 0(1) 1(3.dot) 3(4) 4(5) 5() } } @Test fun modifyRenameConflict() { val file = LocalFilePath("file.txt", false) val renamedFile = LocalFilePath("renamedFile.txt", false) val fileNamesData = FileNamesDataBuilder(file) .addChange(renamedFile, 0, listOf(MODIFIED), listOf(1)) .addChange(renamedFile, 1, listOf(MODIFIED, ADDED), listOf(3, 2)) .addChange(file, 1, listOf(NOT_CHANGED, REMOVED), listOf(3, 2)) .addRename(2, 1, file, renamedFile) .addChange(file, 2, listOf(MODIFIED), listOf(5)) .addChange(renamedFile, 4, listOf(ADDED), listOf(5)) .addChange(file, 4, listOf(REMOVED), listOf(5)) .addRename(5, 4, file, renamedFile) .addChange(file, 5, listOf(MODIFIED), listOf(6)) .addChange(file, 6, listOf(ADDED), listOf(6)) .build() // in order to trigger the bug, parent commits for node 1 in the filtered graph should be in the different order // than in the permanent graph // this is achieved by filtering out node 3, since in the filtered graph usual edges go first, and only then dotted edges graph { 0(1) 1(3, 2) 2(5) 3(4) 4(5) 5(6) 6() }.assert(0, renamedFile, fileNamesData) { 0(1) 1(4.dot, 2.u) 2(5) 4(5) 5(6) 6() } } @Test fun renamedDirectoryHack() { val directory = LocalFilePath("community/platform", true) val directoryBeforeRename = LocalFilePath("platform", true) val fileNamesData = FileNamesDataBuilder(directory) .addChange(directory, 0, listOf(MODIFIED), listOf(1)) .addChange(directoryBeforeRename, 1, listOf(MODIFIED), listOf(2)) // unrelated modification .addChange(directory, 2, listOf(ADDED, ADDED), listOf(3, 4)) .addChange(directoryBeforeRename, 2, listOf(REMOVED, REMOVED), listOf(3, 4)) .addRename(3, 2, directoryBeforeRename, directory) .addChange(directoryBeforeRename, 5, listOf(MODIFIED), listOf(7)) .addChange(directoryBeforeRename, 6, listOf(MODIFIED), listOf(8)) // unrelated modification .build() graph { 0(1) 1(2) 2(3, 4) 3(5) 4(6) 5(7) 6(8) 7() 8() }.assert(0, directory, fileNamesData) { 0(2.dot) 2(5.dot) 5() } } } private class FileNamesDataBuilder(private val path: FilePath) { private val commitsMap: MutableMap<FilePath, TIntObjectHashMap<TIntObjectHashMap<VcsLogPathsIndex.ChangeKind>>> = THashMap(FILE_PATH_HASHING_STRATEGY) private val renamesMap: MultiMap<EdgeData<Int>, EdgeData<FilePath>> = MultiMap.createSmart() fun addRename(parent: Int, child: Int, beforePath: FilePath, afterPath: FilePath): FileNamesDataBuilder { renamesMap.putValue(EdgeData(parent, child), EdgeData(beforePath, afterPath)) return this } fun addChange(path: FilePath, commit: Int, changes: List<VcsLogPathsIndex.ChangeKind>, parents: List<Int>): FileNamesDataBuilder { commitsMap.getOrPut(path) { TIntObjectHashMap() }.put(commit, parents.zip(changes).toIntObjectMap()) return this } fun build(): FileHistoryData { return object : FileHistoryData(path) { override fun findRename(parent: Int, child: Int, path: FilePath, isChildPath: Boolean): EdgeData<FilePath>? { return renamesMap[EdgeData(parent, child)].find { FILE_PATH_HASHING_STRATEGY.equals(if (isChildPath) it.child else it.parent, path) } } override fun getAffectedCommits(path: FilePath): TIntObjectHashMap<TIntObjectHashMap<VcsLogPathsIndex.ChangeKind>> { return commitsMap[path] ?: TIntObjectHashMap() } }.build() } } private fun <T> List<Pair<Int, T>>.toIntObjectMap(): TIntObjectHashMap<T> { val result = TIntObjectHashMap<T>() this.forEach { result.put(it.first, it.second) } return result }
apache-2.0
de9c90fa043bbafdfe42dbfb2d39d911
28.652838
140
0.632769
3.645638
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/Movie.kt
1
1999
package test.setup import slatekit.common.DateTime import slatekit.common.DateTimes import slatekit.entities.Column import slatekit.entities.EntityWithId import slatekit.entities.Id data class Movie( @property:Id() override val id :Long = 0L, @property:Column(required = true, length = 50) val title :String = "", @property:Column(length = 20) val category :String = "", @property:Column(required = true) val playing :Boolean = false, @property:Column(required = true) val cost:Int, @property:Column(required = true) val rating: Double, @property:Column(required = true) val released: DateTime, // These are the timestamp and audit fields. @property:Column(required = true) val createdAt : DateTime = DateTime.now(), @property:Column(required = true) val createdBy :Long = 0, @property:Column(required = true) val updatedAt : DateTime = DateTime.now(), @property:Column(required = true) val updatedBy :Long = 0 ) : EntityWithId<Long> { override fun isPersisted(): Boolean = id > 0 companion object { fun samples():List<Movie> = listOf( Movie( id = 1L, title = "Indiana Jones: Raiders of the Lost Ark", category = "Adventure", playing = false, cost = 10, rating = 4.5, released = DateTimes.of(1985, 8, 10) ), Movie( id = 2L, title = "WonderWoman", category = "action", playing = true, cost = 100, rating = 4.2, released = DateTimes.of(2017, 7, 4) ) ) } }
apache-2.0
945f7202a29cbee517596eb86bcb9063
23.096386
73
0.492746
4.770883
false
false
false
false
leafclick/intellij-community
platform/diff-impl/tests/testSrc/com/intellij/diff/DiffTestCase.kt
3
9796
/* * Copyright 2000-2016 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.diff import com.intellij.diff.comparison.ComparisonManagerImpl import com.intellij.diff.comparison.iterables.DiffIterableUtil import com.intellij.diff.util.DiffUtil import com.intellij.diff.util.ThreeSide import com.intellij.openapi.editor.Document import com.intellij.openapi.progress.DumbProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.LocalFilePath import com.intellij.testFramework.UsefulTestCase import com.intellij.util.text.CharSequenceSubSequence import junit.framework.ComparisonFailure import junit.framework.TestCase import org.junit.Assert import java.util.* import java.util.concurrent.atomic.AtomicLong abstract class DiffTestCase : TestCase() { private val DEFAULT_CHAR_COUNT = 12 private val DEFAULT_CHAR_TABLE: List<String> = listOf("\n", "\n", "\t", " ", " ", ".", "<", "!") val RNG: Random = Random() private var gotSeedException = false val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl() val chSmile = "\uD83D\uDE02" val chGun = "\uD83D\uDD2B" val chMan = "\uD83E\uDDD2" val chFace = "\uD83E\uDD2B" override fun setUp() { super.setUp() DiffIterableUtil.setVerifyEnabled(true) } override fun tearDown() { DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable")) super.tearDown() } fun getTestName() = UsefulTestCase.getTestName(name, true) // // Misc // fun getLineCount(document: Document): Int { return DiffUtil.getLineCount(document) } fun createFilePath(path: String) = LocalFilePath(path, path.endsWith('/') || path.endsWith('\\')) // // AutoTests // fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) { RNG.setSeed(seed) var lastSeed: Long = -1 val debugData = DebugData() for (i in 1..runs) { if (i % 1000 == 0) println(i) try { lastSeed = getCurrentSeed() test(debugData) debugData.reset() } catch (e: Throwable) { println("Seed: " + seed) println("Runs: " + runs) println("I: " + i) println("Current seed: " + lastSeed) debugData.dump() throw e } } } fun generateText(maxLength: Int, charCount: Int, predefinedChars: List<String>): String { val length = RNG.nextInt(maxLength + 1) val builder = StringBuilder(length) for (i in 1..length) { val rnd = RNG.nextInt(charCount) val char = predefinedChars.getOrElse(rnd) { (rnd + 97).toChar() } builder.append(char) } return builder.toString() } fun generateText(maxLength: Int, useHighSurrogates: Boolean = false): String { var count = DEFAULT_CHAR_COUNT var table = DEFAULT_CHAR_TABLE if (useHighSurrogates) { count += 4 table += listOf(chSmile, chFace, chGun, chMan) } return generateText(maxLength, count, table) } fun getCurrentSeed(): Long { if (gotSeedException) return -1 try { val seedField = RNG.javaClass.getDeclaredField("seed") seedField.isAccessible = true val seedFieldValue = seedField.get(RNG) as AtomicLong return seedFieldValue.get() xor 0x5DEECE66DL } catch (e: Exception) { gotSeedException = true System.err.println("Can't get random seed: " + e.message) return -1 } } class DebugData { private val data: MutableList<Pair<String, Any>> = ArrayList() fun put(key: String, value: Any) { data.add(Pair(key, value)) } fun reset() { data.clear() } fun dump() { data.forEach { println(it.first + ": " + it.second) } } } // // Helpers // open class Trio<out T>(val data1: T, val data2: T, val data3: T) { companion object { fun <V> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT)) } fun <V> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3)) fun <V> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT)) fun forEach(f: (T, ThreeSide) -> Unit) { f(data1, ThreeSide.LEFT) f(data2, ThreeSide.BASE) f(data3, ThreeSide.RIGHT) } operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T override fun toString(): String { return "($data1, $data2, $data3)" } override fun equals(other: Any?): Boolean { return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3 } override fun hashCode(): Int { var h = 0 if (data1 != null) h = h * 31 + data1.hashCode() if (data2 != null) h = h * 31 + data2.hashCode() if (data3 != null) h = h * 31 + data3.hashCode() return h } } companion object { // // Assertions // fun assertTrue(actual: Boolean, message: String = "") { assertTrue(message, actual) } fun assertFalse(actual: Boolean, message: String = "") { assertFalse(message, actual) } fun assertEquals(expected: Any?, actual: Any?, message: String = "") { assertEquals(message, expected, actual) } fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") { if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString()) } fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) { if (skipLastNewline && !ignoreSpaces) { assertTrue(StringUtil.equals(chunk1, chunk2) || StringUtil.equals(stripNewline(chunk1), chunk2) || StringUtil.equals(chunk1, stripNewline(chunk2))) } else { assertTrue(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces)) } } fun assertNotEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) { if (skipLastNewline && !ignoreSpaces) { assertTrue(!StringUtil.equals(chunk1, chunk2) || !StringUtil.equals(stripNewline(chunk1), chunk2) || !StringUtil.equals(chunk1, stripNewline(chunk2))) } else { assertFalse(isEqualsCharSequences(chunk1, chunk2, ignoreSpaces)) } } fun isEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean): Boolean { if (ignoreSpaces) { return StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2) } else { return StringUtil.equals(chunk1, chunk2) } } fun assertOrderedEquals(expected: Collection<*>, actual: Collection<*>, message: String = "") { UsefulTestCase.assertOrderedEquals(message, actual, expected) } fun assertSetsEquals(expected: BitSet, actual: BitSet, message: String = "") { val sb = StringBuilder(message) sb.append(": \"") for (i in 0..actual.length()) { sb.append(if (actual[i]) '-' else ' ') } sb.append('"') val fullMessage = sb.toString() Assert.assertEquals(fullMessage, expected, actual) } // // Parsing // fun textToReadableFormat(text: CharSequence?): String { if (text == null) return "null" return "\"" + text.toString().replace('\n', '*').replace('\t', '+') + "\"" } fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n') fun parseMatching(matching: String, text: Document): BitSet { val pattern = matching.filterNot { it == '.' } assertEquals(pattern.length, text.charsSequence.length) val set = BitSet() pattern.forEachIndexed { i, c -> if (c != ' ') set.set(i) } return set } fun parseLineMatching(matching: String, document: Document): BitSet { return parseLineMatching(matching, document.charsSequence) } fun parseLineMatching(matching: String, text: CharSequence): BitSet { assertEquals(matching.length, text.length) val lines1 = matching.split('_', '*') val lines2 = text.split('\n') assertEquals(lines1.size, lines2.size) for (i in 0..lines1.size - 1) { assertEquals(lines1[i].length, lines2[i].length, "line $i") } val set = BitSet() var index = 0 var lineNumber = 0 while (index < matching.length) { var end = matching.indexOfAny(listOf("_", "*"), index) + 1 if (end == 0) end = matching.length val line = matching.subSequence(index, end) if (line.find { it != ' ' && it != '_' } != null) { assert(!line.contains(' ')) set.set(lineNumber) } lineNumber++ index = end } return set } private fun stripNewline(text: CharSequence): CharSequence? { return when (StringUtil.endsWithChar(text, '\n')) { true -> CharSequenceSubSequence(text, 0, text.length - 1) false -> null } } } }
apache-2.0
5f842a5567bed4f0ebe8abd0693aede4
29.144615
134
0.637301
4.019696
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/dataClasses/equals/nullother.kt
5
195
class Dummy { override fun equals(other: Any?) = true } data class A(val v: Any?) fun box() : String { val a = A(Dummy()) val b: A? = null return if(a != b && b != a) "OK" else "fail" }
apache-2.0
a905762e2e1d368a3d9a1c247bb7f5d1
16.818182
46
0.558974
2.708333
false
false
false
false
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/CoroutinesUtils.kt
1
9328
@file:Suppress("FunctionName") package com.jetbrains.packagesearch.intellij.plugin.util import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.progress.impl.ProgressManagerImpl import com.intellij.openapi.project.Project import com.intellij.openapi.util.UserDataHolder import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.consumeAsFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.merge import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.toList import kotlinx.coroutines.job import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.selects.select import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import org.jetbrains.annotations.Nls import kotlin.coroutines.CoroutineContext import kotlin.coroutines.coroutineContext import kotlin.math.max import kotlin.time.Duration import kotlin.time.TimedValue import kotlin.time.measureTimedValue internal fun <T> Flow<T>.onEach(context: CoroutineContext, action: suspend (T) -> Unit) = onEach { withContext(context) { action(it) } } internal fun <T, R> Flow<T>.map(context: CoroutineContext, action: suspend (T) -> R) = map { withContext(context) { action(it) } } internal fun <T> Flow<T>.replayOnSignals(vararg signals: Flow<Any>) = channelFlow { var lastValue: T? = null onEach { send(it) } .onEach { lastValue = it } .launchIn(this) merge(*signals).mapNotNull { lastValue } .onEach { send(it) } .launchIn(this) } internal suspend fun <T, R> Iterable<T>.parallelMap(transform: suspend (T) -> R) = coroutineScope { map { async { transform(it) } }.awaitAll() } internal suspend fun <T> Iterable<T>.parallelFilterNot(transform: suspend (T) -> Boolean) = channelFlow { parallelForEach { if (!transform(it)) send(it) } }.toList() internal suspend fun <T, R> Iterable<T>.parallelMapNotNull(transform: suspend (T) -> R?) = channelFlow { parallelForEach { transform(it)?.let { send(it) } } }.toList() internal suspend fun <T> Iterable<T>.parallelForEach(action: suspend (T) -> Unit) = coroutineScope { forEach { launch { action(it) } } } internal suspend fun <T, R, K> Map<T, R>.parallelMap(transform: suspend (Map.Entry<T, R>) -> K) = coroutineScope { map { async { transform(it) } }.awaitAll() } internal suspend fun <T, R> Iterable<T>.parallelFlatMap(transform: suspend (T) -> Iterable<R>) = coroutineScope { map { async { transform(it) } }.flatMap { it.await() } } internal suspend inline fun <K, V> Map<K, V>.parallelUpdatedKeys(keys: Iterable<K>, crossinline action: suspend (K) -> V): Map<K, V> { val map = toMutableMap() keys.parallelForEach { map[it] = action(it) } return map } internal fun timer(each: Duration, emitAtStartup: Boolean = true) = flow { if (emitAtStartup) emit(Unit) while (true) { delay(each) emit(Unit) } } internal fun <T> Flow<T>.throttle(time: Duration, debounce: Boolean = true) = throttle(time.inWholeMilliseconds, debounce) internal fun <T> Flow<T>.throttle(timeMillis: Int, debounce: Boolean = true) = throttle(timeMillis.toLong(), debounce) internal fun <T> Flow<T>.throttle(timeMillis: Long, debounce: Boolean = true) = channelFlow { var last = System.currentTimeMillis() - timeMillis * 2 var refireJob: Job? = null collect { val elapsedTime = System.currentTimeMillis() - last refireJob?.cancel() when { elapsedTime > timeMillis -> { send(it) last = System.currentTimeMillis() } debounce -> refireJob = launch { delay(max(timeMillis - elapsedTime, 0)) send(it) } } } } internal inline fun <reified T, reified R> Flow<T>.modifiedBy( modifierFlow: Flow<R>, crossinline transform: suspend (T, R) -> T ): Flow<T> = flow { coroutineScope { val queue = Channel<Any?>(capacity = 1) val mutex = Mutex(locked = true) [email protected] { queue.send(it) if (mutex.isLocked) mutex.unlock() }.launchIn(this) mutex.lock() modifierFlow.onEach { queue.send(it) }.launchIn(this) var currentState: T = queue.receive() as T emit(currentState) for (e in queue) { when (e) { is T -> currentState = e is R -> currentState = transform(currentState, e) else -> continue } emit(currentState) } } } internal fun <T, R> Flow<T>.mapLatestTimedWithLoading( loggingContext: String, loadingFlow: MutableStateFlow<Boolean>? = null, transform: suspend CoroutineScope.(T) -> R ) = mapLatest { measureTimedValue { loadingFlow?.emit(true) val result = try { coroutineScope { transform(it) } } finally { loadingFlow?.emit(false) } result } }.map { logTrace(loggingContext) { "Took ${it.duration.absoluteValue} to elaborate" } it.value } internal fun <T> Flow<T>.catchAndLog(context: String, message: String, fallbackValue: T, retryChannel: SendChannel<Unit>? = null) = catch { logWarn(context, it) { message } retryChannel?.send(Unit) emit(fallbackValue) } internal suspend inline fun <R> MutableStateFlow<Boolean>.whileLoading(action: () -> R): TimedValue<R> { emit(true) val r = measureTimedValue { action() } emit(false) return r } internal inline fun <reified T> Flow<T>.batchAtIntervals(duration: Duration) = channelFlow { val mutex = Mutex() val buffer = mutableListOf<T>() var job: Job? = null collect { mutex.withLock { buffer.add(it) } if (job == null || job?.isCompleted == true) { job = launch { delay(duration) mutex.withLock { send(buffer.toTypedArray()) buffer.clear() } } } } } internal suspend fun showBackgroundLoadingBar( project: Project, @Nls title: String, @Nls upperMessage: String, cancellable: Boolean = false, isSafe: Boolean = true ): BackgroundLoadingBarController { val syncSignal = Mutex(true) val upperMessageChannel = Channel<String>() val lowerMessageChannel = Channel<String>() val cancellationRequested = Channel<Unit>() val externalScopeJob = coroutineContext.job val progressManager = ProgressManager.getInstance() progressManager.run(object : Task.Backgroundable(project, title, cancellable) { override fun run(indicator: ProgressIndicator) { if (isSafe && progressManager is ProgressManagerImpl && indicator is UserDataHolder) { progressManager.markProgressSafe(indicator) } indicator.text = upperMessage // ??? why does it work? runBlocking { upperMessageChannel.consumeAsFlow().onEach { indicator.text = it }.launchIn(this) lowerMessageChannel.consumeAsFlow().onEach { indicator.text2 = it }.launchIn(this) indicator.text = upperMessage // ??? why does it work? val indicatorCancelledPollingJob = launch { while (true) { if (indicator.isCanceled) { cancellationRequested.send(Unit) break } delay(50) } } val internalJob = launch { syncSignal.lock() } select<Unit> { internalJob.onJoin { } externalScopeJob.onJoin { internalJob.cancel() } } indicatorCancelledPollingJob.cancel() upperMessageChannel.close() lowerMessageChannel.close() } } }) return BackgroundLoadingBarController( syncSignal, upperMessageChannel, lowerMessageChannel, cancellationRequested.consumeAsFlow() ) } internal class BackgroundLoadingBarController( private val syncMutex: Mutex, val upperMessageChannel: SendChannel<String>, val lowerMessageChannel: SendChannel<String>, val cancellationFlow: Flow<Unit> ) { fun clear() = runCatching { syncMutex.unlock() }.getOrElse { } }
apache-2.0
5b812818fec5381cb2b2ed773d07c812
33.67658
134
0.64419
4.452506
false
false
false
false
google/intellij-community
java/idea-ui/src/com/intellij/projectImport/ProjectOpenProcessorBase.kt
3
7693
// 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.projectImport import com.intellij.CommonBundle import com.intellij.ide.IdeBundle import com.intellij.ide.JavaUiBundle import com.intellij.ide.highlighter.ProjectFileType import com.intellij.ide.impl.OpenProjectTask import com.intellij.ide.impl.ProjectUtil import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.components.StorageScheme import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.ex.JavaSdkUtil import com.intellij.openapi.roots.CompilerProjectExtension import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.ui.configuration.ModulesProvider import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.ApiStatus import java.io.IOException import java.nio.file.Files import javax.swing.Icon abstract class ProjectOpenProcessorBase<T : ProjectImportBuilder<*>> : ProjectOpenProcessor { companion object { @JvmStatic protected fun canOpenFile(file: VirtualFile, supported: Array<String>): Boolean = supported.contains(file.name) @JvmStatic fun getUrl(path: String): String { val resolvedPath = try { FileUtil.resolveShortWindowsName(path) } catch (ignored: IOException) { path } return VfsUtilCore.pathToUrl(resolvedPath) } } private val myBuilder: T? @Deprecated("Override {@link #doGetBuilder()} and use {@code ProjectImportBuilder.EXTENSIONS_POINT_NAME.findExtensionOrFail(yourClass.class)}.") @ApiStatus.ScheduledForRemoval protected constructor(builder: T) { myBuilder = builder } protected constructor() { myBuilder = null } open val builder: T get() = doGetBuilder() protected open fun doGetBuilder(): T = myBuilder!! override val name: String get() = builder.name override val icon: Icon? get() = builder.icon override fun canOpenProject(file: VirtualFile): Boolean { val supported = supportedExtensions if (file.isDirectory) { return getFileChildren(file).any { canOpenFile(it, supported) } } else { return canOpenFile(file, supported) } } protected open fun doQuickImport(file: VirtualFile, wizardContext: WizardContext): Boolean = false abstract val supportedExtensions: Array<String> override fun doOpenProject(virtualFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? { try { val wizardContext = WizardContext(null, null) builder.isUpdate = false var resolvedVirtualFile = virtualFile if (virtualFile.isDirectory) { val supported = supportedExtensions for (file in getFileChildren(virtualFile)) { if (canOpenFile(file, supported)) { resolvedVirtualFile = file break } } } wizardContext.setProjectFileDirectory(resolvedVirtualFile.parent.toNioPath(), false) if (!doQuickImport(resolvedVirtualFile, wizardContext)) { return null } if (wizardContext.projectName == null) { if (wizardContext.projectStorageFormat == StorageScheme.DEFAULT) { wizardContext.projectName = JavaUiBundle.message("project.import.default.name", name) + ProjectFileType.DOT_DEFAULT_EXTENSION } else { wizardContext.projectName = JavaUiBundle.message("project.import.default.name.dotIdea", name) } } wizardContext.projectJdk = ProjectRootManager.getInstance(ProjectManager.getInstance().defaultProject).projectSdk ?: ProjectJdkTable.getInstance().findMostRecentSdkOfType(JavaSdk.getInstance()) val dotIdeaFile = wizardContext.projectDirectory.resolve(Project.DIRECTORY_STORE_FOLDER) val projectFile = wizardContext.projectDirectory.resolve(wizardContext.projectName + ProjectFileType.DOT_DEFAULT_EXTENSION).normalize() var pathToOpen = if (wizardContext.projectStorageFormat == StorageScheme.DEFAULT) projectFile.toAbsolutePath() else dotIdeaFile.parent var shouldOpenExisting = false var importToProject = true if (Files.exists(projectFile) || Files.exists(dotIdeaFile)) { if (ApplicationManager.getApplication().isHeadlessEnvironment) { shouldOpenExisting = true importToProject = true } else { val existingName: String if (Files.exists(dotIdeaFile)) { existingName = "an existing project" pathToOpen = dotIdeaFile.parent } else { existingName = "'${projectFile.fileName}'" pathToOpen = projectFile } val result = Messages.showYesNoCancelDialog( projectToClose, JavaUiBundle.message("project.import.open.existing", existingName, projectFile.parent, virtualFile.name), IdeBundle.message("title.open.project"), JavaUiBundle.message("project.import.open.existing.openExisting"), JavaUiBundle.message("project.import.open.existing.reimport"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon()) if (result == Messages.CANCEL) { return null } shouldOpenExisting = result == Messages.YES importToProject = !shouldOpenExisting } } var options = OpenProjectTask { this.projectToClose = projectToClose this.forceOpenInNewFrame = forceOpenInNewFrame this.projectName = wizardContext.projectName } if (!shouldOpenExisting) { options = options.copy(isNewProject = true) } if (importToProject) { options = options.copy(beforeOpen = { project -> importToProject(project, projectToClose, wizardContext) }) } try { val project = ProjectManagerEx.getInstanceEx().openProject(pathToOpen, options) ProjectUtil.updateLastProjectLocation(pathToOpen) return project } catch (e: Exception) { logger<ProjectOpenProcessorBase<*>>().warn(e) } } finally { builder.cleanup() } return null } private fun importToProject(projectToOpen: Project, projectToClose: Project?, wizardContext: WizardContext): Boolean { return invokeAndWaitIfNeeded { if (!builder.validate(projectToClose, projectToOpen)) { return@invokeAndWaitIfNeeded false } ApplicationManager.getApplication().runWriteAction { wizardContext.projectJdk?.let { JavaSdkUtil.applyJdkToProject(projectToOpen, it) } val projectDirPath = wizardContext.projectFileDirectory val path = projectDirPath + if (projectDirPath.endsWith('/')) "classes" else "/classes" CompilerProjectExtension.getInstance(projectToOpen)?.let { it.compilerOutputUrl = getUrl(path) } } builder.commit(projectToOpen, null, ModulesProvider.EMPTY_MODULES_PROVIDER) true } } } private fun getFileChildren(file: VirtualFile) = file.children ?: VirtualFile.EMPTY_ARRAY
apache-2.0
b437be5a728c59c86f9b9ac470e8e336
35.633333
146
0.707786
4.995455
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/config/common/CommonGcloudConfig.kt
1
9561
package ftl.config.common import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import ftl.args.ArgsHelper import ftl.args.yml.IYmlKeys import ftl.args.yml.ymlKeys import ftl.config.Config import ftl.config.Device import ftl.config.FlankDefaults import ftl.config.defaultDevice import picocli.CommandLine /** * Common Gcloud parameters shared between iOS and Android * * https://cloud.google.com/sdk/gcloud/reference/firebase/test/android/run * https://cloud.google.com/sdk/gcloud/reference/alpha/firebase/test/ios/run */ @CommandLine.Command @JsonIgnoreProperties(ignoreUnknown = true) data class CommonGcloudConfig @JsonIgnore constructor( @JsonIgnore override val data: MutableMap<String, Any?> ) : Config { @set:JsonProperty("device") var devices: List<Device>? by data @set:CommandLine.Option( names = ["--results-bucket"], description = [ "The name of a Google Cloud Storage bucket where raw test " + "results will be stored (default: \"test-lab-<random-UUID>\"). Note that the bucket must be owned by a " + "billing-enabled project, and that using a non-default bucket will result in billing charges for the " + "storage used." ] ) @set:JsonProperty("results-bucket") var resultsBucket: String? by data @set:CommandLine.Option( names = ["--results-dir"], description = [ "The name of a unique Google Cloud Storage object within the results bucket where raw test results will be " + "stored (default: a timestamp with a random suffix). Caution: if specified, this argument must be unique for " + "each test matrix you create, otherwise results from multiple test matrices will be overwritten or " + "intermingled." ] ) @set:JsonProperty("results-dir") var resultsDir: String? by data @set:CommandLine.Option( names = ["--record-video"], description = [ "Enable video recording during the test. " + "Disabled by default." ] ) @set:JsonProperty("record-video") var recordVideo: Boolean? by data @CommandLine.Option( names = ["--no-record-video"], description = ["Disable video recording during the test (default behavior). Use --record-video to enable."] ) fun noRecordVideo(value: Boolean) { recordVideo = !value } @set:CommandLine.Option( names = ["--timeout"], description = [ "The max time this test execution can run before it is cancelled " + "(default: 15m). It does not include any time necessary to prepare and clean up the target device. The maximum " + "possible testing time is 45m on physical devices and 60m on virtual devices. The TIMEOUT units can be h, m, " + "or s. If no unit is given, seconds are assumed. " ] ) @set:JsonProperty("timeout") var timeout: String? by data @set:CommandLine.Option( names = ["--async"], description = ["Invoke a test asynchronously without waiting for test results."] ) @set:JsonProperty("async") var async: Boolean? by data @set:CommandLine.Option( names = ["--client-details"], split = ",", description = [ "Comma-separated, KEY=VALUE map of additional details to attach to the test matrix." + "Arbitrary KEY=VALUE pairs may be attached to a test matrix to provide additional context about the tests being run." + "When consuming the test results, such as in Cloud Functions or a CI system," + "these details can add additional context such as a link to the corresponding pull request." ] ) @set:JsonProperty("client-details") var clientDetails: Map<String, String>? by data @set:CommandLine.Option( names = ["--network-profile"], description = [ "The name of the network traffic profile, for example --network-profile=LTE, " + "which consists of a set of parameters to emulate network conditions when running the test " + "(default: no network shaping; see available profiles listed by the `flank test network-profiles list` command). " + "This feature only works on physical devices. " ] ) @set:JsonProperty("network-profile") var networkProfile: String? by data @set:CommandLine.Option( names = ["--results-history-name"], description = [ "The history name for your test results " + "(an arbitrary string label; default: the application's label from the APK manifest). All tests which use the " + "same history name will have their results grouped together in the Firebase console in a time-ordered test " + "history list." ] ) @set:JsonProperty("results-history-name") var resultsHistoryName: String? by data @set:CommandLine.Option( names = ["--num-flaky-test-attempts"], description = [ "The number of times a TestExecution should be re-attempted if one or more of its test cases " + "fail for any reason. The maximum number of reruns allowed is 10. Default is 0, which implies no reruns." ] ) @set:JsonProperty("num-flaky-test-attempts") var flakyTestAttempts: Int? by data @set:CommandLine.Option( names = ["--directories-to-pull"], split = ",", description = [ "A list of paths that will be copied from the device's " + "storage to the designated results bucket after the test is complete. For Android devices these must be absolute paths under " + "/sdcard or /data/local/tmp (for example, --directories-to-pull /sdcard/tempDir1,/data/local/tmp/tempDir2). " + "Path names are restricted to the characters a-zA-Z0-9_-./+. The paths /sdcard and /data will be made available " + "and treated as implicit path substitutions. E.g. if /sdcard on a particular device does not map to external " + "storage, the system will replace it with the external storage path prefix for that device. " + "For iOS devices these must be absolute paths under /private/var/mobile/Media or /Documents " + "of the app under test. If the path is under an app's /Documents, it must be prefixed with the app's bundle id and a colon" ] ) @set:JsonProperty("directories-to-pull") var directoriesToPull: List<String>? by data @set:CommandLine.Option( names = ["--other-files"], split = ",", description = [ "A list of device-path=file-path pairs that indicate the device paths to push files to the device before " + "starting tests, and the paths of files to push." ] ) @set:JsonProperty("other-files") var otherFiles: Map<String, String>? by data @set:CommandLine.Option( names = ["--scenario-numbers"], split = ",", description = [ "A list of game-loop scenario numbers which will be run as part of the test (default: all scenarios). " + "A maximum of 1024 scenarios may be specified in one test matrix, " + "but the maximum number may also be limited by the overall test --timeout setting." ] ) @set:JsonProperty("scenario-numbers") var scenarioNumbers: List<String>? by data @set:CommandLine.Option( names = ["--type"], description = ["The type of test to run. TYPE must be one of: instrumentation, robo, xctest, game-loop."] ) @set:JsonProperty("type") var type: String? by data @set:CommandLine.Option( names = ["--fail-fast"], description = [ "If true, only a single attempt at most will be made to run each " + "execution/shard in the matrix. Flaky test attempts are not affected. Normally, " + "2 or more attempts are made if a potential infrastructure issue is detected." + " This feature is for latency sensitive workloads." ] ) @set:JsonProperty("fail-fast") var failFast: Boolean? by data constructor() : this(mutableMapOf<String, Any?>().withDefault { null }) companion object : IYmlKeys { override val group = IYmlKeys.Group.GCLOUD override val keys by lazy { CommonGcloudConfig::class.ymlKeys } fun default(android: Boolean) = CommonGcloudConfig().apply { ArgsHelper.yamlMapper.readerFor(CommonGcloudConfig::class.java) resultsBucket = "" resultsDir = null recordVideo = FlankDefaults.DISABLE_VIDEO_RECORDING timeout = "15m" async = false resultsHistoryName = null flakyTestAttempts = 0 clientDetails = null networkProfile = null devices = listOf(defaultDevice(android)) directoriesToPull = emptyList() otherFiles = emptyMap() type = null scenarioNumbers = emptyList() failFast = false } } } fun CommonGcloudConfig.addDevice(device: Device?) { device?.let { devices = (devices ?: emptyList()) + device } }
apache-2.0
ce53fc249a1213d33fa1bb883efc52ed
40.211207
144
0.62619
4.572453
false
true
false
false
fabmax/kool
kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/DeferredDemo.kt
1
25184
package de.fabmax.kool.demo import de.fabmax.kool.KoolContext import de.fabmax.kool.demo.menu.DemoMenu import de.fabmax.kool.math.Mat4f import de.fabmax.kool.math.MutableVec3f import de.fabmax.kool.math.Random import de.fabmax.kool.math.Vec3f import de.fabmax.kool.modules.ksl.KslUnlitShader import de.fabmax.kool.modules.ksl.blocks.ColorSpaceConversion import de.fabmax.kool.modules.ksl.lang.* import de.fabmax.kool.modules.ui2.* import de.fabmax.kool.pipeline.Attribute import de.fabmax.kool.pipeline.DepthCompareOp import de.fabmax.kool.pipeline.deferred.DeferredPbrShader import de.fabmax.kool.pipeline.deferred.DeferredPipeline import de.fabmax.kool.pipeline.deferred.DeferredPipelineConfig import de.fabmax.kool.pipeline.deferred.DeferredPointLights import de.fabmax.kool.pipeline.ibl.EnvironmentHelper import de.fabmax.kool.pipeline.shadermodel.ShaderModel import de.fabmax.kool.pipeline.shadermodel.StageInterfaceNode import de.fabmax.kool.pipeline.shadermodel.fragmentStage import de.fabmax.kool.pipeline.shadermodel.vertexStage import de.fabmax.kool.pipeline.shading.Albedo import de.fabmax.kool.pipeline.shading.ModeledShader import de.fabmax.kool.pipeline.shading.PbrMaterialConfig import de.fabmax.kool.scene.* import de.fabmax.kool.scene.geometry.IndexedVertexList import de.fabmax.kool.scene.geometry.MeshBuilder import de.fabmax.kool.util.Color import de.fabmax.kool.util.MdColor import de.fabmax.kool.util.MutableColor import de.fabmax.kool.util.Time import kotlin.math.roundToInt import kotlin.math.sqrt class DeferredDemo : DemoScene("Deferred Shading") { private lateinit var deferredPipeline: DeferredPipeline private lateinit var objects: Mesh private lateinit var objectShader: DeferredPbrShader private lateinit var lightPositionMesh: Mesh private lateinit var lightVolumeMesh: LineMesh private val rand = Random(1337) private val isShowMaps = mutableStateOf(false) private val isAutoRotate = mutableStateOf(true) private val lightCount = mutableStateOf(2000) private val isObjects = mutableStateOf(true).onChange { objects.isVisible = it } private val isLightBodies = mutableStateOf(true).onChange { lightPositionMesh.isVisible = it } private val isLightVolumes = mutableStateOf(false).onChange { lightVolumeMesh.isVisible = it } private val roughness = mutableStateOf(0.15f).onChange { objectShader.roughness(it) } private val bloomStrength = mutableStateOf(0.75f).onChange { deferredPipeline.bloomStrength = it } private val bloomRadius = mutableStateOf(0.5f).onChange { deferredPipeline.bloomScale = it } private val bloomThreshold = mutableStateOf(0.5f).onChange { deferredPipeline.bloom?.lowerThreshold = it deferredPipeline.bloom?.upperThreshold = it + 0.5f } private val lights = mutableListOf<AnimatedLight>() private val colorMap = listOf( ColorMap("Colorful", listOf(MdColor.RED, MdColor.PINK, MdColor.PURPLE, MdColor.DEEP_PURPLE, MdColor.INDIGO, MdColor.BLUE, MdColor.LIGHT_BLUE, MdColor.CYAN, MdColor.TEAL, MdColor.GREEN, MdColor.LIGHT_GREEN, MdColor.LIME, MdColor.YELLOW, MdColor.AMBER, MdColor.ORANGE, MdColor.DEEP_ORANGE)), ColorMap("Hot-Cold", listOf(MdColor.PINK, MdColor.CYAN)), ColorMap("Summer", listOf(MdColor.ORANGE, MdColor.BLUE, MdColor.GREEN)), ColorMap("Sepia", listOf(MdColor.ORANGE tone 100)) ) val colorMapIdx = mutableStateOf(1) override fun lateInit(ctx: KoolContext) { updateLights() } override fun Scene.setupMainScene(ctx: KoolContext) { +orbitInputTransform { // Set some initial rotation so that we look down on the scene setMouseRotation(0f, -40f) // Add camera to the transform group +camera setZoom(28.0, max = 50.0) translation.set(0.0, -11.0, 0.0) onUpdate += { if (isAutoRotate.value) { verticalRotation += Time.deltaT * 3f } } } // don't use any global lights lighting.lights.clear() // no need to clear the screen, as we draw a fullscreen quad containing the deferred render output every frame mainRenderPass.clearColor = null val ibl = EnvironmentHelper.singleColorEnvironment(this, Color(0.15f, 0.15f, 0.15f)) val defCfg = DeferredPipelineConfig().apply { maxGlobalLights = 0 isWithAmbientOcclusion = true isWithScreenSpaceReflections = false isWithImageBasedLighting = false isWithBloom = true isWithVignette = true isWithChromaticAberration = true // set output depth compare op to ALWAYS, so that the skybox with maximum depth value is drawn outputDepthTest = DepthCompareOp.ALWAYS } deferredPipeline = DeferredPipeline(this, defCfg) deferredPipeline.apply { bloomScale = [email protected] bloomStrength = [email protected] setBloomBrightnessThresholds(bloomThreshold.value, bloomThreshold.value + 0.5f) lightingPassContent += Skybox.cube(ibl.reflectionMap, 1f, hdrOutput = true) } deferredPipeline.sceneContent.makeContent() +deferredPipeline.createDefaultOutputQuad() makeLightOverlays() onUpdate += { lights.forEach { it.animate(Time.deltaT) } } } private fun Scene.makeLightOverlays() { apply { lightVolumeMesh = wireframeMesh(deferredPipeline.dynamicPointLights.mesh.geometry).apply { isFrustumChecked = false isVisible = false isCastingShadow = false shader = ModeledShader(instancedLightVolumeModel()) } +lightVolumeMesh val lightPosInsts = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT, Attribute.COLORS), MAX_LIGHTS) val lightVolInsts = MeshInstanceList(listOf(Attribute.INSTANCE_MODEL_MAT, Attribute.COLORS), MAX_LIGHTS) lightPositionMesh.instances = lightPosInsts lightVolumeMesh.instances = lightVolInsts val lightModelMat = Mat4f() onUpdate += { if (lightPositionMesh.isVisible || lightVolumeMesh.isVisible) { lightPosInsts.clear() lightVolInsts.clear() val srgbColor = MutableColor() deferredPipeline.dynamicPointLights.lightInstances.forEach { light -> lightModelMat.setIdentity() lightModelMat.translate(light.position) if (lightPositionMesh.isVisible) { lightPosInsts.addInstance { put(lightModelMat.matrix) put(light.color.array) } } if (lightVolumeMesh.isVisible) { light.color.toSrgb(srgbColor) val s = sqrt(light.power) lightModelMat.scale(s, s, s) lightVolInsts.addInstance { put(lightModelMat.matrix) put(srgbColor.array) } } } } } } } private fun Group.makeContent() { objects = colorMesh { generate { val sphereProtos = mutableListOf<IndexedVertexList>() for (i in 0..10) { val builder = MeshBuilder(IndexedVertexList(Attribute.POSITIONS, Attribute.NORMALS, Attribute.COLORS)) sphereProtos += builder.geometry builder.apply { icoSphere { steps = 3 radius = rand.randomF(0.3f, 0.4f) center.set(0f, 0.1f + radius, 0f) } } } for (x in -19..19) { for (y in -19..19) { color = Color.WHITE withTransform { translate(x.toFloat(), 0f, y.toFloat()) if ((x + 100) % 2 == (y + 100) % 2) { cube { size.set(rand.randomF(0.6f, 0.8f), rand.randomF(0.6f, 0.95f), rand.randomF(0.6f, 0.8f)) origin.set(-size.x / 2, 0.1f, -size.z / 2) } } else { geometry(sphereProtos[rand.randomI(sphereProtos.indices)]) } } } } } val pbrCfg = PbrMaterialConfig().apply { roughness = 0.15f } objectShader = DeferredPbrShader(pbrCfg) shader = objectShader } +objects lightPositionMesh = mesh(listOf(Attribute.POSITIONS, Attribute.NORMALS)) { isFrustumChecked = false isVisible = true isCastingShadow = false generate { icoSphere { steps = 1 radius = 0.05f center.set(Vec3f.ZERO) } } shader = lightPosShader() } +lightPositionMesh +textureMesh(isNormalMapped = true) { generate { rotate(90f, Vec3f.NEG_X_AXIS) color = Color.WHITE rect { size.set(40f, 40f) origin.set(size.x, size.y, 0f).scale(-0.5f) generateTexCoords(30f) } } val pbrCfg = PbrMaterialConfig().apply { useAlbedoMap("${DemoLoader.materialPath}/futuristic-panels1/futuristic-panels1-albedo1.jpg") useNormalMap("${DemoLoader.materialPath}/futuristic-panels1/futuristic-panels1-normal.jpg") useRoughnessMap("${DemoLoader.materialPath}/futuristic-panels1/futuristic-panels1-roughness.jpg") useMetallicMap("${DemoLoader.materialPath}/futuristic-panels1/futuristic-panels1-metallic.jpg") useAmbientOcclusionMap("${DemoLoader.materialPath}/futuristic-panels1/futuristic-panels1-ao.jpg") } val groundShader = DeferredPbrShader(pbrCfg) shader = groundShader onDispose += { groundShader.albedoMap.dispose() groundShader.aoMap.dispose() groundShader.normalMap.dispose() groundShader.metallicMap.dispose() groundShader.roughnessMap.dispose() groundShader.displacementMap.dispose() } } } private fun updateLights(forced: Boolean = false) { val rows = 41 val travel = rows.toFloat() val start = travel / 2 val objOffset = if (objects.isVisible) 0.7f else 0f val lightGroups = listOf( LightGroup(Vec3f(1 - start, 0.45f, -start), Vec3f(1f, 0f, 0f), Vec3f(0f, 0f, 1f), rows - 1), LightGroup(Vec3f(-start, 0.45f, 1 - start), Vec3f(0f, 0f, 1f), Vec3f(1f, 0f, 0f), rows - 1), LightGroup(Vec3f(1.5f - start, 0.45f + objOffset, start), Vec3f(1f, 0f, 0f), Vec3f(0f, 0f, -1f), rows - 2), LightGroup(Vec3f(start, 0.45f + objOffset, 1.5f - start), Vec3f(0f, 0f, 1f), Vec3f(-1f, 0f, 0f), rows - 2) ) if (forced) { lights.clear() deferredPipeline.dynamicPointLights.lightInstances.clear() } else { while (lights.size > lightCount.value) { lights.removeAt(lights.lastIndex) deferredPipeline.dynamicPointLights.lightInstances.removeAt(deferredPipeline.dynamicPointLights.lightInstances.lastIndex) } } while (lights.size < lightCount.value) { val grp = lightGroups[rand.randomI(lightGroups.indices)] val x = rand.randomI(0 until grp.rows) val light = deferredPipeline.dynamicPointLights.addPointLight { power = 1.0f } val animLight = AnimatedLight(light).apply { startColor = colorMap[colorMapIdx.value].getColor(lights.size).toLinear() desiredColor = startColor colorMix = 1f } lights += animLight grp.setupLight(animLight, x, travel, rand.randomF()) } updateLightColors() } private fun updateLightColors() { lights.forEachIndexed { iLight, it -> it.startColor = it.desiredColor it.desiredColor = colorMap[colorMapIdx.value].getColor(iLight).toLinear() it.colorMix = 0f } } override fun createMenu(menu: DemoMenu, ctx: KoolContext) = menuSurface { val lblSize = UiSizes.baseSize * 2f val txtSize = UiSizes.baseSize * 0.75f MenuSlider2("Number of lights", lightCount.use().toFloat(), 1f, MAX_LIGHTS.toFloat(), { "${it.roundToInt()}" }) { lightCount.set(it.roundToInt()) updateLights() } MenuRow { LabeledSwitch("Show maps", isShowMaps) } MenuRow { LabeledSwitch("Light bodies", isLightBodies) } MenuRow { LabeledSwitch("Light volumes", isLightVolumes) } MenuRow { LabeledSwitch("Auto rotate view", isAutoRotate) } MenuRow { Text("Color theme") { labelStyle() } ComboBox { modifier .width(Grow.Std) .margin(start = sizes.largeGap) .items(colorMap) .selectedIndex(colorMapIdx.use()) .onItemSelected { colorMapIdx.set(it) updateLightColors() } } } Text("Bloom") { sectionTitleStyle() } MenuRow { Text("Strength") { labelStyle(lblSize) } MenuSlider(bloomStrength.use(), 0f, 2f, txtWidth = txtSize) { bloomStrength.set(it) } } MenuRow { Text("Radius") { labelStyle(lblSize) } MenuSlider(bloomRadius.use(), 0f, 2f, txtWidth = txtSize) { bloomRadius.set(it) } } MenuRow { Text("Threshold") { labelStyle(lblSize) } MenuSlider(bloomThreshold.use(), 0f, 2f, txtWidth = txtSize) { bloomThreshold.set(it) } } Text("Objects") { sectionTitleStyle() } MenuRow { LabeledSwitch("Show objects", isObjects) } MenuRow { Text("Roughness") { labelStyle(lblSize) } MenuSlider(roughness.use(), 0f, 1f, txtWidth = txtSize) { roughness.set(it) } } if (isShowMaps.value) { surface.popup().apply { modifier .zLayer(UiSurface.LAYER_BACKGROUND) .align(AlignmentX.Start, AlignmentY.Bottom) .layout(ColumnLayout) val albedoMetal = deferredPipeline.activePass.materialPass.albedoMetal val normalRough = deferredPipeline.activePass.materialPass.normalRoughness val positionFlags = deferredPipeline.activePass.materialPass.positionFlags val bloom = deferredPipeline.bloom?.bloomMap val ao = deferredPipeline.aoPipeline?.aoMap Row { modifier.margin(vertical = sizes.gap) Image { modifier .imageSize(ImageSize.FixedScale(0.3f)) .imageProvider(FlatImageProvider(albedoMetal, true).mirrorY()) .margin(horizontal = sizes.gap) .customShader(albedoMapShader.apply { colorMap = albedoMetal }) Text("Albedo") { imageLabelStyle() } } Image { modifier .imageSize(ImageSize.FixedScale(0.3f)) .imageProvider(FlatImageProvider(normalRough, true).mirrorY()) .margin(horizontal = sizes.gap) .customShader(normalMapShader.apply { colorMap = normalRough }) Text("Normals") { imageLabelStyle() } } } Row { modifier.margin(vertical = sizes.gap) Image { modifier .imageSize(ImageSize.FixedScale(0.3f)) .imageProvider(FlatImageProvider(positionFlags, true).mirrorY()) .margin(horizontal = sizes.gap) .customShader(positionMapShader.apply { colorMap = positionFlags }) Text("Position") { imageLabelStyle() } } Image(ao) { modifier .imageSize(ImageSize.FixedScale(0.3f / deferredPipeline.aoMapSize)) .imageProvider(FlatImageProvider(ao, true).mirrorY()) .margin(horizontal = sizes.gap) .customShader(AoDemo.aoMapShader.apply { colorMap = ao }) Text("Ambient occlusion") { imageLabelStyle() } } } Row { modifier.margin(vertical = sizes.gap) Image(positionFlags) { modifier .imageSize(ImageSize.FixedScale(0.3f)) .imageProvider(FlatImageProvider(positionFlags, true).mirrorY()) .margin(horizontal = sizes.gap) .customShader(metalRoughFlagsShader.apply { metal = albedoMetal rough = normalRough flags = deferredPipeline.activePass.materialPass.positionFlags }) Text("Metal (r), roughness (g), flags (b)") { imageLabelStyle() } } Image(bloom) { modifier .imageSize(ImageSize.FixedScale(0.3f * ((positionFlags.loadedTexture?.height ?: 1) / deferredPipeline.bloomMapSize))) .imageProvider(FlatImageProvider(bloom, true).mirrorY()) .margin(horizontal = sizes.gap) .customShader(bloomMapShader.apply { colorMap = bloom }) Text("Bloom") { imageLabelStyle() } } } } } } private fun TextScope.imageLabelStyle() { modifier .zLayer(UiSurface.LAYER_FLOATING) .backgroundColor(colors.background) .padding(horizontal = sizes.gap) } private inner class LightGroup(val startConst: Vec3f, val startIt: Vec3f, val travelDir: Vec3f, val rows: Int) { fun setupLight(light: AnimatedLight, x: Int, travelDist: Float, travelPos: Float) { light.startPos.set(startIt).scale(x.toFloat()).add(startConst) light.dir.set(travelDir) light.travelDist = travelDist light.travelPos = travelPos * travelDist light.speed = rand.randomF(1f, 3f) * 0.25f } } private class AnimatedLight(val light: DeferredPointLights.PointLight) { val startPos = MutableVec3f() val dir = MutableVec3f() var speed = 1.5f var travelPos = 0f var travelDist = 10f var startColor = Color.WHITE var desiredColor = Color.WHITE var colorMix = 0f fun animate(deltaT: Float) { travelPos += deltaT * speed if (travelPos > travelDist) { travelPos -= travelDist } light.position.set(dir).scale(travelPos).add(startPos) if (colorMix < 1f) { colorMix += deltaT * 2f if (colorMix > 1f) { colorMix = 1f } startColor.mix(desiredColor, colorMix, light.color) } } } private class ColorMap(val name: String, val colors: List<Color>) { fun getColor(idx: Int): Color = colors[idx % colors.size] override fun toString() = name } private fun instancedLightVolumeModel(): ShaderModel = ShaderModel("instancedLightIndicators").apply { val ifColors: StageInterfaceNode vertexStage { ifColors = stageInterfaceNode("ifColors", instanceAttributeNode(Attribute.COLORS).output) val modelMvp = premultipliedMvpNode().outMvpMat val instMvp = multiplyNode(modelMvp, instanceAttrModelMat().output).output positionOutput = vec4TransformNode(attrPositions().output, instMvp).outVec4 } fragmentStage { colorOutput(unlitMaterialNode(ifColors.output).outColor) } } private fun lightPosShader(): DeferredPbrShader { val cfg = PbrMaterialConfig().apply { albedoSource = Albedo.STATIC_ALBEDO albedo = Color.WHITE isInstanced = true } val model = DeferredPbrShader.defaultMrtPbrModel(cfg).apply { val ifColors: StageInterfaceNode vertexStage { ifColors = stageInterfaceNode("ifColors", instanceAttributeNode(Attribute.COLORS).output) } fragmentStage { findNodeByType<DeferredPbrShader.MrtMultiplexNode>()!!.inEmissive = multiplyNode(ifColors.output, 2f).output } } return DeferredPbrShader(cfg, model) } companion object { const val MAX_LIGHTS = 5000 private val albedoMapShader = gBufferShader(0f, 1f) private val normalMapShader = gBufferShader(1f, 0.5f) private val positionMapShader = gBufferShader(10f, 0.05f) private val metalRoughFlagsShader = MetalRoughFlagsShader() private val bloomMapShader = KslUnlitShader { pipeline { depthTest = DepthCompareOp.DISABLED } color { textureData() } colorSpaceConversion = ColorSpaceConversion.LINEAR_TO_sRGB modelCustomizer = { fragmentStage { main { val baseColorPort = getFloat4Port("baseColor") val inColor = float4Var(baseColorPort.input.input) baseColorPort.input(float4Value(inColor.rgb, 1f.const)) } } } } private fun gBufferShader(offset: Float, scale: Float) = KslUnlitShader { pipeline { depthTest = DepthCompareOp.DISABLED } color { textureData() } colorSpaceConversion = ColorSpaceConversion.AS_IS modelCustomizer = { fragmentStage { main { val baseColorPort = getFloat4Port("baseColor") val inColor = float4Var(baseColorPort.input.input) inColor.rgb set (inColor.rgb + offset.const) * scale.const baseColorPort.input(float4Value(inColor.rgb, 1f.const)) } } } } } private class MetalRoughFlagsShader : KslUnlitShader(cfg) { var flags by texture2d("tFlags") var rough by texture2d("tRough") var metal by texture2d("tMetal") companion object { val cfg = UnlitShaderConfig().apply { pipeline { depthTest = DepthCompareOp.DISABLED } colorSpaceConversion = ColorSpaceConversion.AS_IS modelCustomizer = { val uv = interStageFloat2() vertexStage { main { uv.input set vertexAttribFloat2(Attribute.TEXTURE_COORDS.name) } } fragmentStage { main { val metal = sampleTexture(texture2d("tMetal"), uv.output).a val rough = sampleTexture(texture2d("tRough"), uv.output).a val flags = sampleTexture(texture2d("tFlags"), uv.output).a val color = float4Var(float4Value(metal, rough, flags, 1f.const)) getFloat4Port("baseColor").input(color) } } } } } } }
apache-2.0
a56a97ac17cb792cfeb23eba6546e945
41.54223
145
0.554598
4.681041
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/IntroduceBackingPropertyIntention.kt
1
6045
// 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.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.impl.SyntheticFieldDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.util.hasJvmFieldAnnotation import org.jetbrains.kotlin.idea.util.isExpectDeclaration import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext class IntroduceBackingPropertyIntention : SelfTargetingIntention<KtProperty>( KtProperty::class.java, KotlinBundle.lazyMessage("introduce.backing.property") ) { override fun isApplicableTo(element: KtProperty, caretOffset: Int): Boolean { if (!canIntroduceBackingProperty(element)) return false return element.nameIdentifier?.textRange?.containsOffset(caretOffset) == true } override fun applyTo(element: KtProperty, editor: Editor?) = introduceBackingProperty(element) companion object { fun canIntroduceBackingProperty(property: KtProperty): Boolean { val name = property.name ?: return false if (property.hasModifier(KtTokens.CONST_KEYWORD)) return false if (property.hasJvmFieldAnnotation()) return false val bindingContext = property.getResolutionFacade().analyzeWithAllCompilerChecks(property).bindingContext val descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, property) as? PropertyDescriptor ?: return false if (bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor) != true) return false val containingClass = property.getStrictParentOfType<KtClassOrObject>() ?: return false if (containingClass.isExpectDeclaration()) return false return containingClass.declarations.none { it is KtProperty && it.name == "_$name" } } fun introduceBackingProperty(property: KtProperty) { createBackingProperty(property) property.removeModifier(KtTokens.LATEINIT_KEYWORD) if (property.typeReference == null) { val type = SpecifyTypeExplicitlyIntention.getTypeForDeclaration(property) SpecifyTypeExplicitlyIntention.addTypeAnnotation(null, property, type) } val getter = property.getter if (getter == null) { createGetter(property) } else { replaceFieldReferences(getter, property.name!!) } if (property.isVar) { val setter = property.setter if (setter == null) { createSetter(property) } else { replaceFieldReferences(setter, property.name!!) } } property.initializer = null } private fun createGetter(element: KtProperty) { val body = "get() = ${backingName(element)}" val newGetter = KtPsiFactory(element).createProperty("val x $body").getter!! element.addAccessor(newGetter) } private fun createSetter(element: KtProperty) { val body = "set(value) { ${backingName(element)} = value }" val newSetter = KtPsiFactory(element).createProperty("val x $body").setter!! element.addAccessor(newSetter) } private fun KtProperty.addAccessor(newAccessor: KtPropertyAccessor) { val semicolon = node.findChildByType(KtTokens.SEMICOLON) addBefore(newAccessor, semicolon?.psi) } private fun createBackingProperty(property: KtProperty) { val backingProperty = KtPsiFactory(property).buildDeclaration { appendFixedText("private ") appendFixedText(property.valOrVarKeyword.text) appendFixedText(" ") appendNonFormattedText(backingName(property)) if (property.typeReference != null) { appendFixedText(": ") appendTypeReference(property.typeReference) } if (property.initializer != null) { appendFixedText(" = ") appendExpression(property.initializer) } } if (property.hasModifier(KtTokens.LATEINIT_KEYWORD)) { backingProperty.addModifier(KtTokens.LATEINIT_KEYWORD) } property.parent.addBefore(backingProperty, property) } private fun backingName(property: KtProperty): String { return if (property.nameIdentifier?.text?.startsWith('`') == true) "`_${property.name}`" else "_${property.name}" } private fun replaceFieldReferences(element: KtElement, propertyName: String) { element.acceptChildren(object : KtTreeVisitorVoid() { override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) { val target = expression.resolveToCall()?.resultingDescriptor if (target is SyntheticFieldDescriptor) { expression.replace(KtPsiFactory(element).createSimpleName("_$propertyName")) } } override fun visitPropertyAccessor(accessor: KtPropertyAccessor) { // don't go into accessors of properties in local classes because 'field' will mean something different in them } }) } } }
apache-2.0
d47756ee33a538e680f558824b7f5f05
44.451128
158
0.653929
5.581717
false
false
false
false
zdary/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/expressions/JavaUAnnotationCallExpression.kt
4
2238
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.uast.java.expressions import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import com.intellij.psi.ResolveResult import org.jetbrains.uast.* import org.jetbrains.uast.java.JavaAbstractUExpression import org.jetbrains.uast.java.JavaConverter import org.jetbrains.uast.java.JavaUAnnotation import org.jetbrains.uast.java.lz import org.jetbrains.uast.visitor.UastVisitor class JavaUAnnotationCallExpression( override val sourcePsi: PsiAnnotation, givenParent: UElement? ) : JavaAbstractUExpression(givenParent), UCallExpressionEx, UMultiResolvable { val uAnnotation: JavaUAnnotation by lz { JavaUAnnotation(sourcePsi, this) } override val returnType: PsiType? get() = uAnnotation.qualifiedName?.let { PsiType.getTypeByName(it, sourcePsi.project, sourcePsi.resolveScope) } override val kind: UastCallKind get() = UastCallKind.CONSTRUCTOR_CALL override val methodName: String? get() = null override val receiver: UExpression? get() = null override val receiverType: PsiType? get() = null override val methodIdentifier: UIdentifier? get() = null override val classReference: UReferenceExpression? by lz { sourcePsi.nameReferenceElement?.let { ref -> JavaConverter.convertReference(ref, this) as? UReferenceExpression } } override val valueArgumentCount: Int get() = sourcePsi.parameterList.attributes.size override val valueArguments: List<UNamedExpression> by lz { uAnnotation.attributeValues } override fun getArgumentForParameter(i: Int): UExpression? = valueArguments.getOrNull(i) override fun accept(visitor: UastVisitor) { visitor.visitCallExpression(this) uAnnotation.accept(visitor) visitor.afterVisitCallExpression(this) } override val typeArgumentCount: Int = 0 override val typeArguments: List<PsiType> = emptyList() override fun resolve(): PsiMethod? = uAnnotation.resolve()?.constructors?.firstOrNull() override fun multiResolve(): Iterable<ResolveResult> = uAnnotation.multiResolve() }
apache-2.0
c5be6732db3ba8ec43c437aaa458c901
30.521127
140
0.770331
4.731501
false
false
false
false
siosio/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.kt
2
17944
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.wm.impl import com.intellij.configurationStore.deserializeInto import com.intellij.configurationStore.serialize import com.intellij.ide.lightEdit.LightEditCompatible import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponentWithModificationTracker import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.project.impl.createNewProjectFrame import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.wm.* import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.openapi.wm.impl.FrameInfoHelper.Companion.isFullScreenSupportedInCurrentOs import com.intellij.openapi.wm.impl.FrameInfoHelper.Companion.isMaximized import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame import com.intellij.ui.ComponentUtil import com.intellij.ui.ScreenUtil import com.sun.jna.platform.WindowUtils import org.jdom.Element import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import java.awt.* import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import java.util.function.Supplier import javax.swing.JDialog import javax.swing.JFrame import javax.swing.JWindow private val LOG = logger<WindowManagerImpl>() @NonNls private const val FOCUSED_WINDOW_PROPERTY_NAME = "focusedWindow" @NonNls private const val FRAME_ELEMENT = "frame" @State( name = "WindowManager", defaultStateAsResource = true, storages = [Storage(value = "window.state.xml", roamingType = RoamingType.DISABLED)] ) class WindowManagerImpl : WindowManagerEx(), PersistentStateComponentWithModificationTracker<Element> { private var alphaModeSupported: Boolean? = null internal val windowWatcher = WindowWatcher() // default layout private var layout = DesktopLayout() // null keys must be supported // null key - root frame private val projectToFrame: MutableMap<Project?, ProjectFrameHelper> = HashMap() internal val defaultFrameInfoHelper = FrameInfoHelper() private val frameStateListener = object : ComponentAdapter() { override fun componentMoved(e: ComponentEvent) { update(e) } override fun componentResized(e: ComponentEvent) { update(e) } private fun update(e: ComponentEvent) { val frame = e.component as IdeFrameImpl val rootPane = frame.rootPane if (rootPane != null && (rootPane.getClientProperty(ScreenUtil.DISPOSE_TEMPORARY) == true || rootPane.getClientProperty(IdeFrameImpl.TOGGLING_FULL_SCREEN_IN_PROGRESS) == true)) { return } val extendedState = frame.extendedState val bounds = frame.bounds if (extendedState == Frame.NORMAL && rootPane != null) { rootPane.putClientProperty(IdeFrameImpl.NORMAL_STATE_BOUNDS, bounds) } val frameHelper = ProjectFrameHelper.getFrameHelper(frame) ?: return val project = frameHelper.project if (project == null) { // Component moved during project loading - update myDefaultFrameInfo directly. // Cannot mark as dirty and compute later, because to convert user space info to device space, // we need graphicsConfiguration, but we can get graphicsConfiguration only from frame, // but later, when getStateModificationCount or getState is called, may be no frame at all. defaultFrameInfoHelper.updateFrameInfo(frameHelper, frame) } else if (!project.isDisposed) { ProjectFrameBounds.getInstance(project).markDirty(if (isMaximized(extendedState)) null else bounds) } } } init { val app = ApplicationManager.getApplication() if (!app.isUnitTestMode) { Disposer.register(app, Disposable { disposeRootFrame() }) app.messageBus.connect().subscribe(TitleInfoProvider.TOPIC, object : TitleInfoProvider.TitleInfoProviderListener { override fun configurationChanged() { for (frameHelper in projectToFrame.values) { frameHelper.updateTitle() } } }) } KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(FOCUSED_WINDOW_PROPERTY_NAME, windowWatcher) } override fun getAllProjectFrames() = projectToFrame.values.toTypedArray() override fun getProjectFrameHelpers() = projectToFrame.values.toList() override fun findVisibleFrame(): JFrame? { return projectToFrame.values.firstOrNull()?.frame ?: WelcomeFrame.getInstance() as? JFrame } override fun findFirstVisibleFrameHelper() = projectToFrame.values.firstOrNull() override fun getScreenBounds() = ScreenUtil.getAllScreensRectangle() override fun getScreenBounds(project: Project): Rectangle? { val onScreen = getFrame(project)!!.locationOnScreen val devices = GraphicsEnvironment.getLocalGraphicsEnvironment().screenDevices for (device in devices) { val bounds = device.defaultConfiguration.bounds if (bounds.contains(onScreen)) { return bounds } } return null } override fun isInsideScreenBounds(x: Int, y: Int, width: Int): Boolean { return ScreenUtil.getAllScreensShape().contains(x.toDouble(), y.toDouble(), width.toDouble(), 1.0) } override fun isAlphaModeSupported(): Boolean { var result = alphaModeSupported if (result == null) { result = calcAlphaModelSupported() alphaModeSupported = result } return result } override fun setAlphaModeRatio(window: Window, ratio: Float) { require(window.isDisplayable && window.isShowing) { "window must be displayable and showing. window=$window" } require(ratio in 0.0f..1.0f) { "ratio must be in [0..1] range. ratio=$ratio" } if (!isAlphaModeSupported || !isAlphaModeEnabled(window)) { return } setAlphaMode(window, ratio) } override fun setWindowMask(window: Window, mask: Shape?) { try { if (GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice.isWindowTranslucencySupported( GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) { window.shape = mask } else { WindowUtils.setWindowMask(window, mask) } } catch (e: Throwable) { LOG.debug(e) } } override fun setWindowShadow(window: Window, mode: WindowShadowMode) { if (window is JWindow) { val root = window.rootPane root.putClientProperty("Window.shadow", mode != WindowShadowMode.DISABLED) root.putClientProperty("Window.style", if (mode == WindowShadowMode.SMALL) "small" else null) } } override fun resetWindow(window: Window) { try { if (!isAlphaModeSupported) { return } setWindowMask(window, null) setAlphaMode(window, 0f) setWindowShadow(window, WindowShadowMode.NORMAL) } catch (e: Throwable) { LOG.debug(e) } } override fun isAlphaModeEnabled(window: Window): Boolean { require(window.isDisplayable && window.isShowing) { "window must be displayable and showing. window=$window" } return isAlphaModeSupported } override fun setAlphaModeEnabled(window: Window, state: Boolean) { require(window.isDisplayable && window.isShowing) { "window must be displayable and showing. window=$window" } } override fun isNotSuggestAsParent(window: Window): Boolean = windowWatcher.isNotSuggestAsParent(window) override fun doNotSuggestAsParent(window: Window) { windowWatcher.doNotSuggestAsParent(window) } override fun dispatchComponentEvent(e: ComponentEvent) { windowWatcher.dispatchComponentEvent(e) } override fun suggestParentWindow(project: Project?) = windowWatcher.suggestParentWindow(project, this) override fun getStatusBar(project: Project) = getFrameHelper(project)?.statusBar override fun getStatusBar(component: Component, project: Project?): StatusBar? { val parent = ComponentUtil.findUltimateParent(component) if (parent is IdeFrame) { return parent.statusBar!!.findChild(component) } val frame = findFrameFor(project) ?: return null return frame.statusBar!!.findChild(component) } override fun findFrameFor(project: Project?): IdeFrame? { return when { project == null -> ProjectFrameHelper.getFrameHelper(mostRecentFocusedWindow) ?: tryToFindTheOnlyFrame() project.isDefault -> WelcomeFrame.getInstance() else -> getFrameHelper(project) ?: getFrameHelper(null) } } override fun getFrame(project: Project?): IdeFrameImpl? { // no assert! otherwise WindowWatcher.suggestParentWindow fails for default project //LOG.assertTrue(myProject2Frame.containsKey(project)); return getFrameHelper(project)?.frame } @ApiStatus.Internal override fun getFrameHelper(project: Project?) = projectToFrame.get(project) override fun findFrameHelper(project: Project?): ProjectFrameHelper? { return getFrameHelper(project ?: IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project ?: return null) } @ApiStatus.Internal fun getProjectFrameRootPane(project: Project?) = projectToFrame.get(project)?.rootPane override fun getIdeFrame(project: Project?): IdeFrame? { if (project != null) { return getFrameHelper(project) } val window = KeyboardFocusManager.getCurrentKeyboardFocusManager().activeWindow if (window != null) { getIdeFrame(ComponentUtil.findUltimateParent(window))?.let { return it } } for (each in Frame.getFrames()) { getIdeFrame(each)?.let { return it } } return null } internal fun removeAndGetRootFrame() = projectToFrame.remove(null) fun assignFrame(frameHelper: ProjectFrameHelper, project: Project) { LOG.assertTrue(!projectToFrame.containsKey(project)) projectToFrame.put(project, frameHelper) frameHelper.setProject(project) val frame = frameHelper.frame!! // set only if not previously set (we remember previous project name and set it on frame creation) //if (Strings.isEmpty(frame.title)) { frame.title = FrameTitleBuilder.getInstance().getProjectTitle(project) //} frame.addComponentListener(frameStateListener) } /** * This method is not used in a normal conditions. Only in case of violation and early access to ToolWindowManager. */ fun allocateFrame(project: Project, projectFrameHelperFactory: Supplier<out ProjectFrameHelper> = Supplier { ProjectFrameHelper(createNewProjectFrame(forceDisableAutoRequestFocus = false, frameInfo = null), null) }): ProjectFrameHelper { var frame = getFrameHelper(project) if (frame != null) { return frame } frame = removeAndGetRootFrame() if (frame == null) { frame = projectFrameHelperFactory.get() allocateNewFrame(project, frame) } else { frame.setProject(project) projectToFrame.put(project, frame) } return frame } private fun allocateNewFrame(project: Project, frameHelper: ProjectFrameHelper) { frameHelper.init() var frameInfo: FrameInfo? = null val lastFocusedProjectFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame?.project?.let { getFrameHelper(it) } if (lastFocusedProjectFrame != null) { frameInfo = getFrameInfoByFrameHelper(lastFocusedProjectFrame) if (frameInfo?.bounds == null) { frameInfo = defaultFrameInfoHelper.info } } if (frameInfo?.bounds != null) { // update default frame info - newly opened project frame should be the same as last opened if (frameInfo !== defaultFrameInfoHelper.info) { defaultFrameInfoHelper.copyFrom(frameInfo) } val bounds = frameInfo.bounds if (bounds != null) { frameHelper.frame!!.bounds = FrameBoundsConverter.convertFromDeviceSpaceAndFitToScreen(bounds) } } frameHelper.setProject(project) projectToFrame.put(project, frameHelper) val uiFrame = frameHelper.frame!! if (frameInfo != null) { uiFrame.extendedState = frameInfo.extendedState } uiFrame.isVisible = true if (isFullScreenSupportedInCurrentOs() && frameInfo != null && frameInfo.fullScreen) { frameHelper.toggleFullScreen(true) } uiFrame.addComponentListener(frameStateListener) IdeMenuBar.installAppMenuIfNeeded(uiFrame) } override fun releaseFrame(frameHelper: ProjectFrameHelper) { val project = frameHelper.project!! frameHelper.frameReleased() projectToFrame.remove(project) if (projectToFrame.isEmpty() && project !is LightEditCompatible) { projectToFrame.put(null, frameHelper) } else { frameHelper.statusBar?.let { Disposer.dispose(it) } Disposer.dispose(frameHelper) } } fun disposeRootFrame() { if (projectToFrame.size == 1) { removeAndGetRootFrame()?.let { Disposer.dispose(it) } } } override fun getMostRecentFocusedWindow() = windowWatcher.focusedWindow override fun getFocusedComponent(window: Window) = windowWatcher.getFocusedComponent(window) override fun getFocusedComponent(project: Project?) = windowWatcher.getFocusedComponent(project) override fun noStateLoaded() { var anchor = ToolWindowAnchor.LEFT var order = 0 fun info(id: String, weight: Float = -1f, contentUiType: ToolWindowContentUiType? = null): WindowInfoImpl { val result = WindowInfoImpl() result.id = id result.anchor = anchor if (weight != -1f) { result.weight = weight } contentUiType?.let { result.contentUiType = it } result.order = order++ result.isFromPersistentSettings = false result.resetModificationCount() return result } val list = mutableListOf<WindowInfoImpl>() // left stripe list.add(info(id = "Project", weight = 0.25f, contentUiType = ToolWindowContentUiType.COMBO)) // bottom stripe anchor = ToolWindowAnchor.BOTTOM order = 0 list.add(info(id = "Version Control")) list.add(info(id = "Find")) list.add(info(id = "Run")) list.add(info(id = "Debug", weight = 0.4f)) list.add(info(id = "Inspection", weight = 0.4f)) for (info in list) { layout.addInfo(info.id!!, info) } } override fun loadState(state: Element) { val frameElement = state.getChild(FRAME_ELEMENT) if (frameElement != null) { val info = FrameInfo() frameElement.deserializeInto(info) if (info.extendedState and Frame.ICONIFIED > 0) { info.extendedState = Frame.NORMAL } defaultFrameInfoHelper.copyFrom(info) } state.getChild(DesktopLayout.TAG)?.let { layout.readExternal(it) } } override fun getStateModificationCount(): Long { return defaultFrameInfoHelper.getModificationCount() + layout.stateModificationCount } override fun getState(): Element { val state = Element("state") defaultFrameInfoHelper.info?.let { serialize(it) }?.let { state.addContent(it) } // save default layout layout.writeExternal(DesktopLayout.TAG)?.let { state.addContent(it) } return state } override fun getLayout() = layout override fun setLayout(layout: DesktopLayout) { this.layout = layout.copy() } override fun isFullScreenSupportedInCurrentOS() = isFullScreenSupportedInCurrentOs() override fun updateDefaultFrameInfoOnProjectClose(project: Project) { val frameHelper = getFrameHelper(project) ?: return val frameInfo = getFrameInfoByFrameHelper(frameHelper) ?: return defaultFrameInfoHelper.copyFrom(frameInfo) } } private fun calcAlphaModelSupported(): Boolean { val device = GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice if (device.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT)) { return true } return try { WindowUtils.isWindowAlphaSupported() } catch (e: Throwable) { false } } private fun setAlphaMode(window: Window, ratio: Float) { try { when { SystemInfoRt.isMac -> { when (window) { is JWindow -> { window.rootPane.putClientProperty("Window.alpha", 1.0f - ratio) } is JDialog -> { window.rootPane.putClientProperty("Window.alpha", 1.0f - ratio) } is JFrame -> { window.rootPane.putClientProperty("Window.alpha", 1.0f - ratio) } } } GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice.isWindowTranslucencySupported( GraphicsDevice.WindowTranslucency.TRANSLUCENT) -> { window.opacity = 1.0f - ratio } else -> { WindowUtils.setWindowAlpha(window, 1.0f - ratio) } } } catch (e: Throwable) { LOG.debug(e) } } private fun tryToFindTheOnlyFrame(): IdeFrame? { var candidate: IdeFrameImpl? = null for (each in Frame.getFrames()) { if (each is IdeFrameImpl) { if (candidate == null) { candidate = each } else { candidate = null break } } } return if (candidate == null) null else ProjectFrameHelper.getFrameHelper(candidate) } private fun getIdeFrame(component: Component): IdeFrame? { return when (component) { is IdeFrameImpl -> ProjectFrameHelper.getFrameHelper(component) is IdeFrame -> component else -> null } } private fun getFrameInfoByFrameHelper(frameHelper: ProjectFrameHelper): FrameInfo? { return updateFrameInfo(frameHelper, frameHelper.frame ?: return null, null, null) }
apache-2.0
e7f79e70c4d3484c9b3f6b8beaed9d15
32.41527
140
0.709151
4.533603
false
false
false
false
idea4bsd/idea4bsd
platform/script-debugger/backend/src/org/jetbrains/rpc/CommandSenderBase.kt
17
1838
/* * Copyright 2000-2015 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.rpc import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.catchError import org.jetbrains.jsonProtocol.Request abstract class CommandSenderBase<SUCCESS_RESPONSE> { protected abstract fun <RESULT> doSend(message: Request<RESULT>, callback: RequestPromise<SUCCESS_RESPONSE, RESULT>) fun <RESULT> send(message: Request<RESULT>): Promise<RESULT> { val callback = RequestPromise<SUCCESS_RESPONSE, RESULT>(message.methodName) doSend(message, callback) return callback } } class RequestPromise<SUCCESS_RESPONSE, RESULT>(private val methodName: String?) : AsyncPromise<RESULT>(), RequestCallback<SUCCESS_RESPONSE> { override fun onSuccess(response: SUCCESS_RESPONSE?, resultReader: ResultReader<SUCCESS_RESPONSE>?) { catchError { if (resultReader == null || response == null) { @Suppress("UNCHECKED_CAST") setResult(response as RESULT?) } else { if (methodName == null) { setResult(null) } else { setResult(resultReader.readResult(methodName, response)) } } } } override fun onError(error: Throwable) { setError(error) } }
apache-2.0
304ffe78883909448821a4fb303d8ab9
33.055556
141
0.71654
4.324706
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/attic/attic-1.kt
1
6230
package alraune.attic //fun ooUserComparison_bak(lhsUser: User?, rhsUser: User) { // val actions = SortedActions() // // fun consider10(it: KProperty1<User, Any?>) = // actions.add(100) {ooPropComparison(PropComparisonParams(it), lhsUser, rhsUser)} // rhsUser.acceptProps( // optimisticVersion = {}, id = {/*consider10(it)*/}, email = {consider10(it)}, // data = { // val data1 = lhsUser?.data // val data2 = rhsUser.data // fun consider20(it: KProperty1<User.Data, Any?>) = // actions.add(100) {ooPropComparison(PropComparisonParams(it), data1, data2)} // data2.acceptProps( // banReason = {consider20(it)}, lastOperationId = {}, passwordHash = {}, createdAt = {}, updatedAt = {}, // adminNotes = {if (isAdmin()) consider20(it)}, // variant = { // val writer1 = data1?.variant?.let {it as User.Variant.Writer} // val writer2 = data2.variant as User.Variant.Writer // fun consider30(it: KProperty1<User.Variant.Writer, Any?>) = // actions.add(100) {ooPropComparison(PropComparisonParams(it), writer1, writer2)} // writer2.acceptProps( // profile = { // val profile1 = writer1?.profile // val profile2 = writer2.profile // // if (profile2 == null) { // if (profile1 != null) // wtf("Profile cannot disappear") // else // actions.add(100) {oo(div(t("TOTE", "Профайл не заполнен")).style("margin-top: 0.5em; border-top: 3px solid ${Color.GRAY_300};"))} // } else { // var wrapper by notNullOnce<AlTag>() // // if (profile1 == null) // actions.add(100) { // oo(div(t("TOTE", "Появился профайл")).style("font-weight: bold;")) // wrapper = div().style("border-left: 2px solid ${Color.BLUE_GRAY_100}; padding-left: 1em;") // oo(wrapper) // pushTag(wrapper) // } // // fun consider40(it: KProperty1<User.Variant.Writer.Profile, Any?>, num: Int = 100) = // actions.add(num) {ooPropComparison(PropComparisonParams(it), profile1, profile2)} // profile2.acceptProps( // createdAt = {}, updatedAt = {}, state = {consider40(it)}, // rejectionReason = {consider40(it)}, // wasRejectionReason = {consider40(it)}, // lastRejectedByOperationId = {if (isAdmin()) consider40(it)}, // approvalTaskId = {if (isAdmin()) consider40(it)}, // fields = { // val fields1 = profile1?.fields // val fields2 = profile2.fields // fun consider50(it: KProperty1<User.Variant.Writer.Profile.Fields, Any?>, num: Int = 100) = // actions.add(num) {ooPropComparison(PropComparisonParams(it), fields1, fields2)} // fields2.acceptProps( // resume = {prop-> // val resume1 = fields1?.resume // val resume2 = fields2.resume // actions.add(1000) { // ooRichComparison(prop.name, resume1, resume2) // } // }, // firstName = {consider50(it)}, lastName = {consider50(it)}, phone = {consider50(it)}, timeZone = {consider50(it)}, // dateOfBirth = {consider50(it)}, country = {consider50(it)}, currentOccupation = {consider50(it)}, educationDegree = {consider50(it)}, // profession = {consider50(it)}, street = {consider50(it)}, city = {consider50(it)}, building = {consider50(it)}, apartment = {consider50(it)}, // experience = { // fun consider60(prop: KProperty1<Experience, Any?>, num: Int = 100) = // actions.add(num) { // !OoPropValueComparison(PropComparisonParams(prop, propNamePrefix = "${fields2::experience.name}."), // value1 = when { // profile1 == null -> null // else -> PropComparisonPile2.valueOrNa(fields1?.experience, prop)}, // value2 = PropComparisonPile2.valueOrNa(fields2.experience, prop)) // } // Experience().acceptProps(years = {consider60(it)}, details = {consider60(it)}) // } // ) // } // ) // // if (profile1 == null) // actions.add(100) {popTag()} // } // } // ) // } // ) // } // ) // // actions.goCrazy() //}
apache-2.0
28b4a42fbff2310ca52fd87a2d67599f
64.93617
187
0.388512
5.047231
false
false
false
false
tomekby/miscellaneous
kotlin-game/android/app/src/main/java/pl/vot/tomekby/mathGame/HighScoreAdapter.kt
1
1857
package pl.vot.tomekby.mathGame import android.annotation.SuppressLint import android.graphics.Typeface.DEFAULT_BOLD import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.LinearLayout.HORIZONTAL import org.jetbrains.anko.* import pl.vot.tomekby.mathGame.domain.HighScoreDTO import kotlin.collections.ArrayList class HighScoreAdapter(private val items: ArrayList<HighScoreDTO> = ArrayList()) : BaseAdapter() { @SuppressLint("SetTextI18n", "SimpleDateFormat") override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { return with(parent!!.context) { linearLayout { id = R.id.listItemContainer lparams(width = matchParent, height = wrapContent) orientation = HORIZONTAL padding = dip(10) val result = items[position] textView { text = result.member typeface = DEFAULT_BOLD padding = dip(5) width = 250 } textView { text = "%.3f s.".format(result.time) padding = dip(5) width = 250 } textView { text = "Data: ${result.dateFinished}" padding = dip(5) } } } } override fun getItem(position: Int): HighScoreDTO { return items[position] } override fun getItemId(position: Int): Long { return 0L } override fun getCount(): Int { return items.size } fun add(newItems: List<HighScoreDTO>) { items.addAll(newItems) notifyDataSetChanged() } }
mit
5316ff4f771909e64db72832cdcd2223
29.508475
98
0.546581
4.991935
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/ExtractionEngine.kt
4
5263
// 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.introduce.extractionEngine import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.ui.popup.Balloon import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.ui.awt.RelativePoint import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.refactoring.checkConflictsInteractively import org.jetbrains.kotlin.idea.refactoring.introduce.showErrorHint import org.jetbrains.kotlin.idea.util.ProgressIndicatorUtils import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.nonBlocking import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.safeAs import javax.swing.event.HyperlinkEvent abstract class ExtractionEngineHelper(@NlsContexts.DialogTitle val operationName: String) { open fun adjustExtractionData(data: ExtractionData): ExtractionData = data fun doRefactor(config: ExtractionGeneratorConfiguration, onFinish: (ExtractionResult) -> Unit = {}) { val project = config.descriptor.extractionData.project onFinish(project.executeWriteCommand<ExtractionResult>(operationName) { config.generateDeclaration() }) } open fun validate(descriptor: ExtractableCodeDescriptor): ExtractableCodeDescriptorWithConflicts = descriptor.validate() abstract fun configureAndRun( project: Project, editor: Editor, descriptorWithConflicts: ExtractableCodeDescriptorWithConflicts, onFinish: (ExtractionResult) -> Unit = {} ) } class ExtractionEngine( val helper: ExtractionEngineHelper ) { fun run( editor: Editor, extractionData: ExtractionData, onFinish: (ExtractionResult) -> Unit = {} ) { val project = extractionData.project val adjustExtractionData = helper.adjustExtractionData(extractionData) val analysisResult = ProgressIndicatorUtils.underModalProgress(project, KotlinBundle.message("progress.title.analyze.extraction.data") ) { adjustExtractionData.performAnalysis() } if (isUnitTestMode() && analysisResult.status != AnalysisResult.Status.SUCCESS) { throw BaseRefactoringProcessor.ConflictsInTestsException(analysisResult.messages.map { it.renderMessage() }) } fun validateAndRefactor() { nonBlocking(project, { try { helper.validate(analysisResult.descriptor!!) } catch (e: RuntimeException) { ExtractableCodeDescriptorWithException(e) } }) { result -> result.safeAs<ExtractableCodeDescriptorWithException>()?.let { throw it.exception } val validationResult = result.cast<ExtractableCodeDescriptorWithConflicts>() project.checkConflictsInteractively(validationResult.conflicts) { helper.configureAndRun(project, editor, validationResult) { try { onFinish(it) } finally { it.dispose() extractionData.dispose() } } } } } val message = analysisResult.messages.joinToString("\n") { it.renderMessage() } when (analysisResult.status) { AnalysisResult.Status.CRITICAL_ERROR -> { showErrorHint(project, editor, message, helper.operationName) } AnalysisResult.Status.NON_CRITICAL_ERROR -> { val anchorPoint = RelativePoint( editor.contentComponent, editor.visualPositionToXY(editor.selectionModel.selectionStartPosition!!) ) @NlsSafe val htmlContent = "$message<br/><br/><a href=\"EXTRACT\">${KotlinBundle.message("text.proceed.with.extraction")}</a>" JBPopupFactory.getInstance()!! .createHtmlTextBalloonBuilder( htmlContent, MessageType.WARNING ) { event -> if (event?.eventType == HyperlinkEvent.EventType.ACTIVATED) { validateAndRefactor() } } .setHideOnClickOutside(true) .setHideOnFrameResize(false) .setHideOnLinkClick(true) .createBalloon() .show(anchorPoint, Balloon.Position.below) } AnalysisResult.Status.SUCCESS -> validateAndRefactor() } } }
apache-2.0
7fbed8c5d27635d13cbbe273d2616206
43.226891
158
0.637469
5.646996
false
true
false
false
apollographql/apollo-android
tests/sample-server/src/main/kotlin/com/apollographql/apollo/sample/server/RootSubscription.kt
1
2231
package com.apollographql.apollo.sample.server import com.expediagroup.graphql.generator.annotations.GraphQLDescription import com.expediagroup.graphql.server.operations.Subscription import graphql.GraphQLError import graphql.GraphqlErrorException import graphql.execution.DataFetcherResult import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.reactive.asPublisher import org.reactivestreams.Publisher import org.springframework.stereotype.Component @Component class RootSubscription : Subscription { @GraphQLDescription("Count from 0 until 'to', waiting 'delayMillis' after each response") fun count(to: Int, delayMillis: Int) = flow { repeat(to) { emit(it) if (delayMillis > 0) { delay(delayMillis.toLong()) } } }.asPublisher() @GraphQLDescription("Count from 0 until 'to', waiting 'delayMillis' after each response and returns each result as a String") fun countString(to: Int, delayMillis: Int) = flow { repeat(to) { emit(it.toString()) if (delayMillis > 0) { delay(delayMillis.toLong()) } } }.asPublisher() fun time() = flow { repeat(100) { emit(it) delay(100) } }.asPublisher() @GraphQLDescription("Trigger an error when accessed") fun operationError() = flow<String> { throw Exception("Woops") }.asPublisher() @GraphQLDescription("Emits 'after' items and returns an error") fun graphqlAccessError(after: Int = 1): Publisher<DataFetcherResult<Int?>> = flow { repeat(after) { emit( DataFetcherResult.newResult<Int>() .data(it) .build() ) } emit( DataFetcherResult.newResult<Int>() .data(null) .error( /** * This should add an "errors" field to the payload but for some reason it doesn't * This is kept to indicate the intent of this code but should certainly be investigated */ GraphqlErrorException.newErrorException() .message("Woops") .build() ) .build() ) }.asPublisher() }
mit
f4381127e93cc9e8a51a58ff4a58939c
29.162162
127
0.646347
4.553061
false
false
false
false
androidx/androidx
compose/integration-tests/demos/src/main/java/androidx/compose/integration/demos/DemoFilter.kt
3
5023
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.integration.demos import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.integration.demos.common.Demo import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.key import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp /** * A scrollable list of [launchableDemos], filtered by [filterText]. */ @Composable fun DemoFilter(launchableDemos: List<Demo>, filterText: String, onNavigate: (Demo) -> Unit) { val filteredDemos = launchableDemos .filter { it.title.contains(filterText, ignoreCase = true) } .sortedBy { it.title } LazyColumn { items(filteredDemos) { demo -> FilteredDemoListItem( demo, filterText = filterText, onNavigate = onNavigate ) } } } /** * [TopAppBar] with a text field allowing filtering all the demos. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun FilterAppBar( filterText: String, onFilter: (String) -> Unit, onClose: () -> Unit, scrollBehavior: TopAppBarScrollBehavior ) { TopAppBar( navigationIcon = { IconButton(onClick = onClose) { Icon(Icons.Filled.Close, null) } }, title = { FilterField( filterText, onFilter, Modifier.fillMaxWidth() ) }, scrollBehavior = scrollBehavior ) } /** * [TextField] that edits the current [filterText], providing [onFilter] when edited. */ @Composable @OptIn(ExperimentalMaterial3Api::class) private fun FilterField( filterText: String, onFilter: (String) -> Unit, modifier: Modifier = Modifier ) { val focusRequester = remember { FocusRequester() } TextField( modifier = modifier.focusRequester(focusRequester), value = filterText, onValueChange = onFilter ) DisposableEffect(focusRequester) { focusRequester.requestFocus() onDispose { } } } /** * [ListItem] that displays a [demo] and highlights any matches for [filterText] inside [Demo.title] */ @Composable private fun FilteredDemoListItem( demo: Demo, filterText: String, onNavigate: (Demo) -> Unit ) { val primary = MaterialTheme.colorScheme.primary val annotatedString = buildAnnotatedString { val title = demo.title var currentIndex = 0 val pattern = filterText.toRegex(option = RegexOption.IGNORE_CASE) pattern.findAll(title).forEach { result -> val index = result.range.first if (index > currentIndex) { append(title.substring(currentIndex, index)) currentIndex = index } withStyle(SpanStyle(color = primary)) { append(result.value) } currentIndex = result.range.last + 1 } if (currentIndex <= title.lastIndex) { append(title.substring(currentIndex, title.length)) } } key(demo.title) { ListItem( onClick = { onNavigate(demo) }) { Text( modifier = Modifier .height(56.dp) .wrapContentSize(Alignment.Center), text = annotatedString ) } } }
apache-2.0
4f4dd02625c39b3ba6333838bc3d8054
30.993631
100
0.676488
4.599817
false
false
false
false
androidx/androidx
compose/animation/animation-core/src/commonMain/kotlin/androidx/compose/animation/core/Animation.kt
3
18961
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.animation.core import androidx.compose.animation.core.internal.JvmDefaultWithCompatibility /** * This interface provides a convenient way to query from an [VectorizedAnimationSpec] or * [FloatDecayAnimationSpec]: It spares the need to pass the starting conditions and in some cases * ending condition for each value or velocity query, and instead only requires the play time to be * passed for such queries. * * The implementation of this interface should cache the starting conditions and ending * conditions of animations as needed. * * __Note__: [Animation] does not track the lifecycle of an animation. It merely reacts to play time * change and returns the new value/velocity as a result. It can be used as a building block for * more lifecycle aware animations. In contrast, [Animatable] and [Transition] are * stateful and manage their own lifecycles. * * @see [Animatable] * @see [updateTransition] */ @JvmDefaultWithCompatibility interface Animation<T, V : AnimationVector> { /** * This amount of time in nanoseconds that the animation will run before it finishes */ @get:Suppress("MethodNameUnits") val durationNanos: Long /** * The [TwoWayConverter] that will be used to convert value/velocity from any arbitrary data * type to [AnimationVector]. This makes it possible to animate different dimensions of the * data object independently (e.g. x/y dimensions of the position data). */ val typeConverter: TwoWayConverter<T, V> /** * This is the value that the [Animation] will reach when it finishes uninterrupted. */ val targetValue: T /** * Whether or not the [Animation] represents an infinite animation. That is, one that will * not finish by itself, one that needs an external action to stop. For examples, an * indeterminate progress bar, which will only stop when it is removed from the composition. */ val isInfinite: Boolean /** * Returns the value of the animation at the given play time. * * @param playTimeNanos the play time that is used to determine the value of the animation. */ fun getValueFromNanos(playTimeNanos: Long): T /** * Returns the velocity (in [AnimationVector] form) of the animation at the given play time. * * @param playTimeNanos the play time that is used to calculate the velocity of the animation. */ fun getVelocityVectorFromNanos(playTimeNanos: Long): V /** * Returns whether the animation is finished at the given play time. * * @param playTimeNanos the play time used to determine whether the animation is finished. */ fun isFinishedFromNanos(playTimeNanos: Long): Boolean { return playTimeNanos >= durationNanos } } internal val Animation<*, *>.durationMillis: Long get() = durationNanos / MillisToNanos internal const val MillisToNanos: Long = 1_000_000L /** * Returns the velocity of the animation at the given play time. * * @param playTimeNanos the play time that is used to calculate the velocity of the animation. */ fun <T, V : AnimationVector> Animation<T, V>.getVelocityFromNanos(playTimeNanos: Long): T = typeConverter.convertFromVector(getVelocityVectorFromNanos(playTimeNanos)) /** * Creates a [TargetBasedAnimation] from a given [VectorizedAnimationSpec] of [AnimationVector] type. This * convenient method is intended for when the value being animated (i.e. start value, end value, * etc) is of [AnimationVector] type. * * @param initialValue the value that the animation will start from * @param targetValue the value that the animation will end at * @param initialVelocity the initial velocity to start the animation at * @suppress */ /*@VisibleForTesting(otherwise = PACKAGE_PRIVATE)*/ fun <V : AnimationVector> VectorizedAnimationSpec<V>.createAnimation( initialValue: V, targetValue: V, initialVelocity: V ): TargetBasedAnimation<V, V> = TargetBasedAnimation( animationSpec = this, initialValue = initialValue, targetValue = targetValue, initialVelocityVector = initialVelocity, typeConverter = TwoWayConverter({ it }, { it }) ) /** * Creates a [TargetBasedAnimation] with the given start/end conditions of the animation, and * the provided [animationSpec]. * * The resulting [Animation] assumes that the start value and velocity, as well as end value do * not change throughout the animation, and cache these values. This caching enables much more * convenient query for animation value and velocity (where only playtime needs to be passed * into the methods). * * __Note__: When interruptions happen to the [TargetBasedAnimation], a new instance should * be created that use the current value and velocity as the starting conditions. This type of * interruption handling is the default behavior for both [Animatable] and * [Transition]. Consider using those APIs for the interruption handling, as well as * built-in animation lifecycle management. * * @param animationSpec the [AnimationSpec] that will be used to calculate value/velocity * @param initialValue the start value of the animation * @param targetValue the end value of the animation * @param initialVelocity the start velocity (of type [T] of the animation * @param typeConverter the [TwoWayConverter] that is used to convert animation type [T] from/to [V] */ fun <T, V : AnimationVector> TargetBasedAnimation( animationSpec: AnimationSpec<T>, typeConverter: TwoWayConverter<T, V>, initialValue: T, targetValue: T, initialVelocity: T ) = TargetBasedAnimation( animationSpec, typeConverter, initialValue, targetValue, typeConverter.convertToVector(initialVelocity) ) /** * This is a convenient animation wrapper class that works for all target based animations, i.e. * animations that has a pre-defined end value, unlike decay. * * It assumes that the starting value and velocity, as well as ending value do not change throughout * the animation, and cache these values. This caching enables much more convenient query for * animation value and velocity (where only playtime needs to be passed into the methods). * * __Note__: When interruptions happen to the [TargetBasedAnimation], a new instance should * be created that use the current value and velocity as the starting conditions. This type of * interruption handling is the default behavior for both [Animatable] and * [Transition]. Consider using those APIs for the interruption handling, as well as * built-in animation lifecycle management. * * @param animationSpec the [VectorizedAnimationSpec] that will be used to calculate value/velocity * @param initialValue the start value of the animation * @param targetValue the end value of the animation * @param typeConverter the [TwoWayConverter] that is used to convert animation type [T] from/to [V] * @param initialVelocityVector the start velocity of the animation in the form of [AnimationVector] * * @see [Transition] * @see [updateTransition] * @see [Animatable] */ class TargetBasedAnimation<T, V : AnimationVector> internal constructor( internal val animationSpec: VectorizedAnimationSpec<V>, override val typeConverter: TwoWayConverter<T, V>, val initialValue: T, override val targetValue: T, initialVelocityVector: V? = null ) : Animation<T, V> { /** * Creates a [TargetBasedAnimation] with the given start/end conditions of the animation, and * the provided [animationSpec]. * * The resulting [Animation] assumes that the start value and velocity, as well as end value do * not change throughout the animation, and cache these values. This caching enables much more * convenient query for animation value and velocity (where only playtime needs to be passed * into the methods). * * __Note__: When interruptions happen to the [TargetBasedAnimation], a new instance should * be created that use the current value and velocity as the starting conditions. This type of * interruption handling is the default behavior for both [Animatable] and * [Transition]. Consider using those APIs for the interruption handling, as well as * built-in animation lifecycle management. * * @param animationSpec the [AnimationSpec] that will be used to calculate value/velocity * @param typeConverter the [TwoWayConverter] that is used to convert animation type [T] from/to [V] * @param initialValue the start value of the animation * @param targetValue the end value of the animation * @param initialVelocityVector the start velocity vector, null by default (meaning 0 velocity). */ constructor( animationSpec: AnimationSpec<T>, typeConverter: TwoWayConverter<T, V>, initialValue: T, targetValue: T, initialVelocityVector: V? = null ) : this( animationSpec.vectorize(typeConverter), typeConverter, initialValue, targetValue, initialVelocityVector ) private val initialValueVector = typeConverter.convertToVector(initialValue) private val targetValueVector = typeConverter.convertToVector(targetValue) private val initialVelocityVector = initialVelocityVector?.copy() ?: typeConverter.convertToVector(initialValue) .newInstance() override val isInfinite: Boolean get() = animationSpec.isInfinite override fun getValueFromNanos(playTimeNanos: Long): T { return if (!isFinishedFromNanos(playTimeNanos)) { animationSpec.getValueFromNanos( playTimeNanos, initialValueVector, targetValueVector, initialVelocityVector ).let { // TODO: Remove after b/232030217 for (i in 0 until it.size) { check(!it.get(i).isNaN()) { "AnimationVector cannot contain a NaN. $it. Animation: $this," + " playTimeNanos: $playTimeNanos" } } typeConverter.convertFromVector(it) } } else { targetValue } } @get:Suppress("MethodNameUnits") override val durationNanos: Long = animationSpec.getDurationNanos( initialValue = initialValueVector, targetValue = targetValueVector, initialVelocity = this.initialVelocityVector ) private val endVelocity = animationSpec.getEndVelocity( initialValueVector, targetValueVector, this.initialVelocityVector ) override fun getVelocityVectorFromNanos(playTimeNanos: Long): V { return if (!isFinishedFromNanos(playTimeNanos)) { animationSpec.getVelocityFromNanos( playTimeNanos, initialValueVector, targetValueVector, initialVelocityVector ) } else { endVelocity } } override fun toString(): String { return "TargetBasedAnimation: $initialValue -> $targetValue," + "initial velocity: $initialVelocityVector, duration: $durationMillis ms," + "animationSpec: $animationSpec" } } /** * [DecayAnimation] is an animation that slows down from [initialVelocityVector] as * time goes on. [DecayAnimation] is stateless, and it does not have any concept of lifecycle. It * serves as an animation calculation engine that supports convenient query of value/velocity * given a play time. To achieve that, [DecayAnimation] stores all the animation related * information: [initialValue], [initialVelocityVector], decay animation spec, [typeConverter]. * * __Note__: Unless there's a need to control the timing manually, it's * generally recommended to use higher level animation APIs that build on top [DecayAnimation], * such as [Animatable.animateDecay], [AnimationState.animateDecay], etc. * * @see Animatable.animateDecay * @see AnimationState.animateDecay */ class DecayAnimation<T, V : AnimationVector> /*@VisibleForTesting*/ constructor( private val animationSpec: VectorizedDecayAnimationSpec<V>, override val typeConverter: TwoWayConverter<T, V>, val initialValue: T, initialVelocityVector: V ) : Animation<T, V> { private val initialValueVector: V = typeConverter.convertToVector(initialValue) val initialVelocityVector: V = initialVelocityVector.copy() private val endVelocity: V override val targetValue: T = typeConverter.convertFromVector( animationSpec.getTargetValue(initialValueVector, initialVelocityVector) ) @get:Suppress("MethodNameUnits") override val durationNanos: Long // DecayAnimation finishes by design override val isInfinite: Boolean = false /** * [DecayAnimation] is an animation that slows down from [initialVelocityVector] as time goes * on. [DecayAnimation] is stateless, and it does not have any concept of lifecycle. It * serves as an animation calculation engine that supports convenient query of value/velocity * given a play time. To achieve that, [DecayAnimation] stores all the animation related * information: [initialValue], [initialVelocityVector], decay animation spec, [typeConverter]. * * __Note__: Unless there's a need to control the timing manually, it's * generally recommended to use higher level animation APIs that build on top [DecayAnimation], * such as [Animatable.animateDecay], [AnimationState.animateDecay], etc. * * @param animationSpec Decay animation spec that defines the slow-down curve of the animation * @param typeConverter Type converter to convert the type [T] from and to [AnimationVector] * @param initialValue The starting value of the animation * @param initialVelocityVector The starting velocity of the animation in [AnimationVector] form * * @see Animatable.animateDecay * @see AnimationState.animateDecay */ constructor( animationSpec: DecayAnimationSpec<T>, typeConverter: TwoWayConverter<T, V>, initialValue: T, initialVelocityVector: V ) : this( animationSpec.vectorize(typeConverter), typeConverter, initialValue, initialVelocityVector ) /** * [DecayAnimation] is an animation that slows down from [initialVelocity] as time goes on. * [DecayAnimation] is stateless, and it does not have any concept of lifecycle. It * serves as an animation calculation engine that supports convenient query of value/velocity * given a play time. To achieve that, [DecayAnimation] stores all the animation related * information: [initialValue], [initialVelocity], [animationSpec], [typeConverter]. * * __Note__: Unless there's a need to control the timing manually, it's * generally recommended to use higher level animation APIs that build on top [DecayAnimation], * such as [Animatable.animateDecay], [AnimationState.animateDecay], etc. * * @param animationSpec Decay animation spec that defines the slow-down curve of the animation * @param typeConverter Type converter to convert the type [T] from and to [AnimationVector] * @param initialValue The starting value of the animation * @param initialVelocity The starting velocity of the animation * * @see Animatable.animateDecay * @see AnimationState.animateDecay */ constructor( animationSpec: DecayAnimationSpec<T>, typeConverter: TwoWayConverter<T, V>, initialValue: T, initialVelocity: T ) : this( animationSpec.vectorize(typeConverter), typeConverter, initialValue, typeConverter.convertToVector(initialVelocity) ) init { durationNanos = animationSpec.getDurationNanos( initialValueVector, initialVelocityVector ) endVelocity = animationSpec.getVelocityFromNanos( durationNanos, initialValueVector, initialVelocityVector ).copy() for (i in 0 until endVelocity.size) { endVelocity[i] = endVelocity[i].coerceIn( -animationSpec.absVelocityThreshold, animationSpec.absVelocityThreshold ) } } override fun getValueFromNanos(playTimeNanos: Long): T { if (!isFinishedFromNanos(playTimeNanos)) { return typeConverter.convertFromVector( animationSpec.getValueFromNanos( playTimeNanos, initialValueVector, initialVelocityVector ) ) } else { return targetValue } } override fun getVelocityVectorFromNanos(playTimeNanos: Long): V { if (!isFinishedFromNanos(playTimeNanos)) { return animationSpec.getVelocityFromNanos( playTimeNanos, initialValueVector, initialVelocityVector ) } else { return endVelocity } } } /** * [DecayAnimation] is an animation that slows down from [initialVelocity] as * time goes on. [DecayAnimation] is stateless, and it does not have any concept of lifecycle. It * serves as an animation calculation engine that supports convenient query of value/velocity * given a play time. To achieve that, [DecayAnimation] stores all the animation related * information: [initialValue], [initialVelocity], decay animation spec. * * __Note__: Unless there's a need to control the timing manually, it's * generally recommended to use higher level animation APIs that build on top [DecayAnimation], * such as [Animatable.animateDecay], [animateDecay], etc. * * @param animationSpec decay animation that will be used * @param initialValue starting value that will be passed to the decay animation * @param initialVelocity starting velocity for the decay animation, 0f by default */ fun DecayAnimation( animationSpec: FloatDecayAnimationSpec, initialValue: Float, initialVelocity: Float = 0f ) = DecayAnimation( animationSpec.generateDecayAnimationSpec(), Float.VectorConverter, initialValue, AnimationVector(initialVelocity) )
apache-2.0
6f8d40b7350dc8e610aac973e41b4b6b
41.135556
106
0.704182
4.994995
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/Decoration.kt
2
2382
package tornadofx import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.scene.Node import javafx.scene.Parent import javafx.scene.control.Control import javafx.scene.control.Tooltip import javafx.scene.paint.Color import javafx.scene.shape.Polygon interface Decorator { fun decorate(node: Node) fun undecorate(node: Node) } fun Node.addDecorator(decorator: Decorator) { decorators += decorator decorator.decorate(this) } fun Node.removeDecorator(decorator: Decorator) { decorators -= decorator decorator.undecorate(this) } @Suppress("UNCHECKED_CAST") val Node.decorators: MutableList<Decorator> get() = properties.getOrPut("tornadofx.decorators", { mutableListOf<Decorator>() }) as MutableList<Decorator> class SimpleMessageDecorator(val message: String?, severity: ValidationSeverity) : Decorator { val color: Color = when (severity) { ValidationSeverity.Error -> Color.RED ValidationSeverity.Warning -> Color.ORANGE ValidationSeverity.Success -> Color.GREEN else -> Color.BLUE } var tag: Polygon? = null var tooltip: Tooltip? = null var attachedToNode: Node? = null var focusListener = ChangeListener<Boolean> { _, _, newValue -> if (newValue == true) showTooltip(attachedToNode!!) else tooltip?.hide() } override fun decorate(node: Node) { attachedToNode = node if (node is Parent) { tag = node.polygon(0.0, 0.0, 0.0, 10.0, 10.0, 0.0) { isManaged = false fill = color } } if (message?.isNotBlank() ?: false) { tooltip = Tooltip(message) if (node is Control) node.tooltip = tooltip else Tooltip.install(node, tooltip) if (node.isFocused) showTooltip(node) node.focusedProperty().addListener(focusListener) } } private fun showTooltip(node: Node) { tooltip?.apply { if (isShowing) return val b = node.localToScreen(node.boundsInLocal) if (b != null) show(node, b.minX + 5, b.maxY) } } override fun undecorate(node: Node) { tag?.removeFromParent() tooltip?.apply { hide() Tooltip.uninstall(node, this) } node.focusedProperty().removeListener(focusListener) } }
apache-2.0
f27b76a696452c007a70918e555435dc
29.551282
153
0.644836
4.268817
false
false
false
false
androidx/androidx
compose/ui/ui-text/src/androidAndroidTest/kotlin/androidx/compose/ui/text/font/FontFamilyResolverImplTest.kt
3
27681
/* * 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.text.font import android.content.Context import android.graphics.Typeface import android.os.Build import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.FontTestData import androidx.compose.ui.text.UncachedFontFamilyResolver import androidx.compose.ui.text.font.testutils.AsyncFauxFont import androidx.compose.ui.text.font.testutils.AsyncTestTypefaceLoader import androidx.compose.ui.text.font.testutils.BlockingFauxFont import androidx.compose.ui.text.font.testutils.OptionalFauxFont import androidx.compose.ui.text.matchers.assertThat import androidx.compose.ui.text.platform.bitmap import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @SmallTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalTextApi::class) @ExperimentalCoroutinesApi class FontFamilyResolverImplTest { private lateinit var scope: TestScope private lateinit var typefaceLoader: AsyncTestTypefaceLoader private lateinit var dispatcher: TestDispatcher private lateinit var asyncTypefaceCache: AsyncTypefaceCache private lateinit var typefaceCache: TypefaceRequestCache private val context = InstrumentationRegistry.getInstrumentation().context private val fontLoader = AndroidFontLoader(context) // This is the default value that Android uses private val accessibilityFontWeightAdjustment = 300 private lateinit var subject: FontFamilyResolverImpl @Before fun setup() { asyncTypefaceCache = AsyncTypefaceCache() typefaceCache = TypefaceRequestCache() dispatcher = UnconfinedTestDispatcher() scope = TestScope(dispatcher) initializeSubject() typefaceLoader = AsyncTestTypefaceLoader() } private fun initializeSubject( platformResolveInterceptor: PlatformResolveInterceptor = AndroidFontResolveInterceptor(context) ) { val injectedContext = scope.coroutineContext.minusKey(CoroutineExceptionHandler) subject = FontFamilyResolverImpl( fontLoader, platformResolveInterceptor = platformResolveInterceptor, typefaceRequestCache = typefaceCache, fontListFontFamilyTypefaceAdapter = FontListFontFamilyTypefaceAdapter( asyncTypefaceCache, injectedContext ) ) } private fun resolveAsTypeface( fontFamily: FontFamily? = null, fontWeight: FontWeight = FontWeight.Normal, fontStyle: FontStyle = FontStyle.Normal, fontSynthesis: FontSynthesis = FontSynthesis.All, ): Typeface { return subject.resolve( fontFamily, fontWeight, fontStyle, fontSynthesis ).value as Typeface } @Test fun createDefaultTypeface() { val typeface: Typeface = resolveAsTypeface() assertThat(typeface).hasWeightAndStyle(FontWeight.Normal, FontStyle.Normal) } @Test fun fontWeightItalicCreatesItalicFont() { val typeface = resolveAsTypeface(fontStyle = FontStyle.Italic) assertThat(typeface).hasWeightAndStyle(FontWeight.Normal, FontStyle.Italic) } @Test fun fontWeightBoldCreatesBoldFont() { val typeface = resolveAsTypeface(fontWeight = FontWeight.Bold) assertThat(typeface).hasWeightAndStyle(FontWeight.Bold, FontStyle.Normal) } @Test fun fontWeightBoldFontStyleItalicCreatesBoldItalicFont() { val typeface = resolveAsTypeface( fontStyle = FontStyle.Italic, fontWeight = FontWeight.Bold ) assertThat(typeface).hasWeightAndStyle(FontWeight.Bold, FontStyle.Italic) } @Test fun serifAndSansSerifPaintsDifferent() { val typefaceSans = resolveAsTypeface(FontFamily.SansSerif) val typefaceSerif = resolveAsTypeface(FontFamily.Serif) assertThat(typefaceSans).hasWeightAndStyle(FontWeight.Normal, FontStyle.Normal) assertThat(typefaceSerif).hasWeightAndStyle(FontWeight.Normal, FontStyle.Normal) assertThat(typefaceSans.bitmap()).isNotEqualToBitmap(typefaceSerif.bitmap()) } @Test fun getTypefaceStyleSnapToNormalFor100to500() { val fontWeights = arrayOf( FontWeight.W100, FontWeight.W200, FontWeight.W300, FontWeight.W400, FontWeight.W500 ) for (fontWeight in fontWeights) { for (fontStyle in FontStyle.values()) { val typefaceStyle = resolveAsTypeface( fontWeight = fontWeight, fontStyle = fontStyle ) assertThat(typefaceStyle).hasWeightAndStyle(fontWeight, fontStyle) } } } @Test fun getTypefaceStyleSnapToBoldFor600to900() { val fontWeights = arrayOf( FontWeight.W600, FontWeight.W700, FontWeight.W800, FontWeight.W900 ) for (fontWeight in fontWeights) { for (fontStyle in FontStyle.values()) { val typefaceStyle = resolveAsTypeface( fontWeight = fontWeight, fontStyle = fontStyle ) assertThat(typefaceStyle).hasWeightAndStyle(fontWeight, fontStyle) } } } @Test @SdkSuppress(maxSdkVersion = 27) fun fontWeights100To500SnapToNormalBeforeApi28() { val fontWeights = arrayOf( FontWeight.W100, FontWeight.W200, FontWeight.W300, FontWeight.W400, FontWeight.W500 ) for (fontWeight in fontWeights) { for (fontStyle in FontStyle.values()) { val typeface = resolveAsTypeface( fontWeight = fontWeight, fontStyle = fontStyle ) assertThat(typeface).hasWeightAndStyle(fontWeight, fontStyle) } } } @Test @SdkSuppress(maxSdkVersion = 27) fun fontWeights600To900SnapToBoldBeforeApi28() { val fontWeights = arrayOf( FontWeight.W600, FontWeight.W700, FontWeight.W800, FontWeight.W900 ) for (fontWeight in fontWeights) { for (fontStyle in FontStyle.values()) { val typeface = resolveAsTypeface( fontWeight = fontWeight, fontStyle = fontStyle ) assertThat(typeface).hasWeightAndStyle(fontWeight, fontStyle) } } } @Test @SdkSuppress(minSdkVersion = 28) fun typefaceCreatedWithCorrectFontWeightAndFontStyle() { for (fontWeight in FontWeight.values) { for (fontStyle in FontStyle.values()) { val typeface = resolveAsTypeface( fontWeight = fontWeight, fontStyle = fontStyle ) assertThat(typeface).hasWeightAndStyle(fontWeight, fontStyle) } } } @Test @MediumTest fun customSingleFont() { val defaultTypeface = resolveAsTypeface() val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface(fontFamily = fontFamily) assertThat(typeface).hasWeightAndStyle(FontWeight.W100, FontStyle.Normal) assertThat(typeface.bitmap()).isNotEqualToBitmap(defaultTypeface.bitmap()) } @Test @MediumTest fun customSingleFontBoldItalic() { val defaultTypeface = resolveAsTypeface() val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface( fontFamily = fontFamily, fontStyle = FontStyle.Italic, fontWeight = FontWeight.Bold ) assertThat(typeface).hasWeightAndStyle(FontWeight.Bold, FontStyle.Italic) assertThat(typeface.bitmap()).isNotEqualToBitmap(defaultTypeface.bitmap()) } @Test @MediumTest fun customSingleFontFamilyExactMatch() { val fontFamily = FontFamily( FontTestData.FONT_100_REGULAR, FontTestData.FONT_100_ITALIC, FontTestData.FONT_200_REGULAR, FontTestData.FONT_200_ITALIC, FontTestData.FONT_300_REGULAR, FontTestData.FONT_300_ITALIC, FontTestData.FONT_400_REGULAR, FontTestData.FONT_400_ITALIC, FontTestData.FONT_500_REGULAR, FontTestData.FONT_500_ITALIC, FontTestData.FONT_600_REGULAR, FontTestData.FONT_600_ITALIC, FontTestData.FONT_700_REGULAR, FontTestData.FONT_700_ITALIC, FontTestData.FONT_800_REGULAR, FontTestData.FONT_800_ITALIC, FontTestData.FONT_900_REGULAR, FontTestData.FONT_900_ITALIC ) for (fontWeight in FontWeight.values) { for (fontStyle in FontStyle.values()) { val typeface = resolveAsTypeface( fontWeight = fontWeight, fontStyle = fontStyle, fontFamily = fontFamily ) assertThat(typeface).isNotNull() assertThat(typeface).isTypefaceOf(fontWeight = fontWeight, fontStyle = fontStyle) } } } @Test fun resultsAreCached_defaultTypeface() { val typeface = resolveAsTypeface() // getting typeface with same parameters should hit the cache // therefore return the same typeface val otherTypeface = resolveAsTypeface() assertThat(typeface).isSameInstanceAs(otherTypeface) } @Test fun resultsNotSame_forDifferentFontWeight() { val typeface = resolveAsTypeface(fontWeight = FontWeight.Normal) // getting typeface with different parameters should not hit the cache // therefore return some other typeface val otherTypeface = resolveAsTypeface(fontWeight = FontWeight.Bold) assertThat(typeface).isNotSameInstanceAs(otherTypeface) } @Test fun resultsNotSame_forDifferentFontStyle() { val typeface = resolveAsTypeface(fontStyle = FontStyle.Normal) val otherTypeface = resolveAsTypeface(fontStyle = FontStyle.Italic) assertThat(typeface).isNotSameInstanceAs(otherTypeface) } @Test fun resultsAreCached_withCustomTypeface() { val fontFamily = FontFamily.SansSerif val fontWeight = FontWeight.Normal val fontStyle = FontStyle.Italic val typeface = resolveAsTypeface(fontFamily, fontWeight, fontStyle) val otherTypeface = resolveAsTypeface(fontFamily, fontWeight, fontStyle) assertThat(typeface).isSameInstanceAs(otherTypeface) } @Test fun cacheCanHoldTwoResults() { val serifTypeface = resolveAsTypeface(FontFamily.Serif) val otherSerifTypeface = resolveAsTypeface(FontFamily.Serif) val sansTypeface = resolveAsTypeface(FontFamily.SansSerif) val otherSansTypeface = resolveAsTypeface(FontFamily.SansSerif) assertThat(serifTypeface).isSameInstanceAs(otherSerifTypeface) assertThat(sansTypeface).isSameInstanceAs(otherSansTypeface) assertThat(sansTypeface).isNotSameInstanceAs(serifTypeface) } @Test fun resultsAreCached_forLoadedTypeface() { val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface(fontFamily) val otherTypeface = resolveAsTypeface(fontFamily) assertThat(typeface).isSameInstanceAs(otherTypeface) } @Test fun resultsAreEvicted_whenCacheOverfills_cacheSize16() { val font = BlockingFauxFont(typefaceLoader, Typeface.MONOSPACE, FontWeight.W100) val font800 = BlockingFauxFont( typefaceLoader, Typeface.SANS_SERIF, FontWeight.W800 ) val fontFamily = FontFamily( font, font800 ) subject.resolve(fontFamily, FontWeight.W100) for (weight in 801..816) { // don't use test resolver for cache busting subject.resolve(fontFamily, FontWeight(weight)) } assertThat(typefaceCache.get( TypefaceRequest( fontFamily, FontWeight.W100, FontStyle.Normal, FontSynthesis.All, fontLoader.cacheKey ))).isNull() } @Test fun resultsAreNotEvicted_whenCacheOverfills_ifUsedRecently_cacheSize16() { val font = BlockingFauxFont(typefaceLoader, Typeface.MONOSPACE, FontWeight.W100) val font800 = BlockingFauxFont( typefaceLoader, Typeface.SANS_SERIF, FontWeight.W800 ) val fontFamily = FontFamily( font, font800 ) subject.resolve(fontFamily, FontWeight.W100) for (weight in 801..816) { subject.resolve(fontFamily, FontWeight.W100) subject.resolve(fontFamily, FontWeight(weight)) } assertThat(typefaceCache.get( TypefaceRequest( fontFamily, FontWeight.W100, FontStyle.Normal, FontSynthesis.All, fontLoader.cacheKey ))).isNotNull() } @Test fun changingResourceLoader_doesInvalidateCache() { val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface(fontFamily) /* definitely not same instance :) */ val newFontLoader = object : PlatformFontLoader { override fun loadBlocking(font: Font): Any = Typeface.DEFAULT override suspend fun awaitLoad(font: Font): Any = Typeface.DEFAULT override val cacheKey: String = "Not the default resource loader" } val otherTypeface = UncachedFontFamilyResolver( newFontLoader, PlatformResolveInterceptor.Default ) .resolve(fontFamily).value as Typeface assertThat(typeface).isNotSameInstanceAs(otherTypeface) } @Test fun changingResourceLoader_toAndroidResourceLoader_doesNotInvalidateCache() { var first = true val unstableLoader = object : AndroidFont.TypefaceLoader { override fun loadBlocking(context: Context, font: AndroidFont): Typeface? { return if (first) { first = false Typeface.DEFAULT } else { Typeface.MONOSPACE } } override suspend fun awaitLoad(context: Context, font: AndroidFont): Typeface? { TODO("Not yet implemented") } } val fontFamily = FontFamily( object : AndroidFont( FontLoadingStrategy.Blocking, unstableLoader, FontVariation.Settings() ) { override val weight: FontWeight = FontWeight.Normal override val style: FontStyle = FontStyle.Normal } ) val firstAndroidResourceLoader = AndroidFontLoader(context) val androidResolveInterceptor = AndroidFontResolveInterceptor(context) val typeface = FontFamilyResolverImpl( fontLoader, androidResolveInterceptor, typefaceCache, FontListFontFamilyTypefaceAdapter(asyncTypefaceCache) ).resolve(fontFamily).value as Typeface val secondAndroidResourceLoader = AndroidFontLoader(context) val otherTypeface = FontFamilyResolverImpl( fontLoader, androidResolveInterceptor, typefaceCache, FontListFontFamilyTypefaceAdapter(asyncTypefaceCache) ).resolve(fontFamily).value as Typeface assertThat(firstAndroidResourceLoader).isNotSameInstanceAs(secondAndroidResourceLoader) assertThat(typeface).isSameInstanceAs(otherTypeface) assertThat(typeface).isSameInstanceAs(Typeface.DEFAULT) } @Test(expected = IllegalStateException::class) fun throwsExceptionIfFontIsNotIncludedInTheApp() { val fontFamily = FontFamily(Font(resId = -1)) resolveAsTypeface(fontFamily) } @Test(expected = IllegalStateException::class) fun throwsExceptionIfFontIsNotReadable() { val fontFamily = FontFamily(FontTestData.FONT_INVALID) resolveAsTypeface(fontFamily) } @Test fun fontSynthesisDefault_synthesizeTheFontToItalicBold() { val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic, fontSynthesis = FontSynthesis.All ) assertThat(typeface).hasWeightAndStyle(FontWeight.Bold, FontStyle.Italic) } @Test fun fontSynthesisStyle_synthesizeTheFontToItalic() { val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic, fontSynthesis = FontSynthesis.Style ) assertThat(typeface).hasWeightAndStyle(FontWeight.W100, FontStyle.Italic) } @Test fun fontSynthesisWeight_synthesizeTheFontToBold() { val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic, fontSynthesis = FontSynthesis.Weight ) assertThat(typeface).hasWeightAndStyle(FontWeight.Bold, FontStyle.Normal) } @Test fun fontSynthesisStyle_forMatchingItalicDoesNotSynthesize() { val fontFamily = FontTestData.FONT_100_ITALIC.toFontFamily() val typeface = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.W700, fontStyle = FontStyle.Italic, fontSynthesis = FontSynthesis.Style ) assertThat(typeface).hasWeightAndStyle(FontWeight.W100, FontStyle.Normal) } @Test fun fontSynthesisAll_doesNotSynthesizeIfFontIsTheSame_beforeApi28() { val fontFamily = FontTestData.FONT_700_ITALIC.toFontFamily() val typeface = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.W700, fontStyle = FontStyle.Italic, fontSynthesis = FontSynthesis.All ) val expectedWeight = if (Build.VERSION.SDK_INT < 23) { FontWeight.Normal } else { FontWeight.W700 } assertThat(typeface).hasWeightAndStyle(expectedWeight, FontStyle.Normal) } @Test fun fontSynthesisNone_doesNotSynthesize() { val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic, fontSynthesis = FontSynthesis.None ) assertThat(typeface).hasWeightAndStyle(FontWeight.W100, FontStyle.Normal) } @Test fun fontSynthesisWeight_doesNotSynthesizeIfRequestedWeightIsLessThan600() { val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() // Less than 600 is not synthesized val typeface500 = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.W500, fontSynthesis = FontSynthesis.Weight ) // 600 or more is synthesized val typeface600 = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.W600, fontSynthesis = FontSynthesis.Weight ) assertThat(typeface500).hasWeightAndStyle(FontWeight.W100, FontStyle.Normal) assertThat(typeface600).hasWeightAndStyle(FontWeight.W600, FontStyle.Normal) } @Test fun androidFontResolveInterceptor_affectsTheFontWeight() { initializeSubject(AndroidFontResolveInterceptor(accessibilityFontWeightAdjustment)) val typefaceLoader = AsyncTestTypefaceLoader() val w700Font = BlockingFauxFont(typefaceLoader, Typeface.DEFAULT, weight = FontWeight.W700) val fontFamily = FontFamily( BlockingFauxFont(typefaceLoader, Typeface.DEFAULT, weight = FontWeight.W400), BlockingFauxFont(typefaceLoader, Typeface.DEFAULT, weight = FontWeight.W500), BlockingFauxFont(typefaceLoader, Typeface.DEFAULT, weight = FontWeight.W600), w700Font, BlockingFauxFont(typefaceLoader, Typeface.DEFAULT, weight = FontWeight.W800), BlockingFauxFont(typefaceLoader, Typeface.DEFAULT, weight = FontWeight.W900), ) resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.W400 ) assertThat(typefaceLoader.blockingRequests).containsExactly(w700Font) } @Test fun androidFontResolveInterceptor_doesNotAffectTheFontStyle() { initializeSubject(AndroidFontResolveInterceptor(accessibilityFontWeightAdjustment)) val typeface = resolveAsTypeface( fontWeight = FontWeight.W400, fontStyle = FontStyle.Italic ) assertThat(typeface).hasWeightAndStyle(FontWeight.W700, FontStyle.Italic) } @Test fun platformResolveInterceptor_affectsTheResolvedFontStyle() { initializeSubject( platformResolveInterceptor = object : PlatformResolveInterceptor { override fun interceptFontStyle(fontStyle: FontStyle) = FontStyle.Italic } ) val typeface = resolveAsTypeface( fontWeight = FontWeight.Normal, fontStyle = FontStyle.Normal ) assertThat(typeface).hasWeightAndStyle(FontWeight.Normal, FontStyle.Italic) } @Test fun platformResolveInterceptor_affectsTheResolvedFontSynthesis() { initializeSubject( platformResolveInterceptor = object : PlatformResolveInterceptor { override fun interceptFontSynthesis(fontSynthesis: FontSynthesis) = FontSynthesis.All } ) val fontFamily = FontTestData.FONT_100_REGULAR.toFontFamily() val typeface = resolveAsTypeface( fontFamily = fontFamily, fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic, fontSynthesis = FontSynthesis.None ) assertThat(typeface).hasWeightAndStyle(FontWeight.Bold, FontStyle.Italic) } @Test fun platformResolveInterceptor_affectsTheResolvedFontFamily() { initializeSubject( platformResolveInterceptor = object : PlatformResolveInterceptor { override fun interceptFontFamily(fontFamily: FontFamily?) = FontTestData.FONT_100_REGULAR.toFontFamily() } ) val typeface = resolveAsTypeface(fontFamily = FontFamily.Cursive) assertThat(typeface).hasWeightAndStyle(FontWeight.W100, FontStyle.Normal) } @Test fun androidResolveInterceptor_affectsAsyncFontResolution_withFallback() { initializeSubject(AndroidFontResolveInterceptor(accessibilityFontWeightAdjustment)) val loader = AsyncTestTypefaceLoader() val asyncFauxFontW400 = AsyncFauxFont(loader, FontWeight.W400) val asyncFauxFontW700 = AsyncFauxFont(loader, FontWeight.W700) val blockingFauxFontW400 = BlockingFauxFont(loader, Typeface.DEFAULT, FontWeight.W400) val fontFamily = FontFamily( asyncFauxFontW400, blockingFauxFontW400, asyncFauxFontW700 ) val fallbackTypeface = resolveAsTypeface(fontFamily, FontWeight.W400) assertThat(fallbackTypeface).hasWeightAndStyle(FontWeight.W700, FontStyle.Normal) // loads the W700 async font which should be the matched font loader.completeOne(asyncFauxFontW700, Typeface.MONOSPACE) val typeface = resolveAsTypeface(fontFamily, FontWeight.W400) assertThat(typeface).isSameInstanceAs(Typeface.MONOSPACE) } @Test fun androidResolveInterceptor_affectsAsyncFontResolution_withBlockingFont() { initializeSubject(AndroidFontResolveInterceptor(accessibilityFontWeightAdjustment)) val loader = AsyncTestTypefaceLoader() val asyncFauxFontW400 = AsyncFauxFont(loader, FontWeight.W400) val asyncFauxFontW700 = AsyncFauxFont(loader, FontWeight.W700) val blockingFauxFontW700 = BlockingFauxFont(loader, Typeface.SANS_SERIF, FontWeight.W700) val fontFamily = FontFamily( asyncFauxFontW400, asyncFauxFontW700, blockingFauxFontW700 ) val blockingTypeface = resolveAsTypeface(fontFamily, FontWeight.W400) assertThat(blockingTypeface).isSameInstanceAs(Typeface.SANS_SERIF) // loads the W700 async font which should be the matched font loader.completeOne(asyncFauxFontW700, Typeface.MONOSPACE) val typeface = resolveAsTypeface(fontFamily, FontWeight.W400) assertThat(typeface).isSameInstanceAs(Typeface.MONOSPACE) } @Test fun androidResolveInterceptor_choosesOptionalFont_whenWeightMatches() { val loader = AsyncTestTypefaceLoader() val optionalFauxFontW400 = OptionalFauxFont(loader, Typeface.MONOSPACE, FontWeight.W400) val optionalFauxFontW700 = OptionalFauxFont(loader, Typeface.SERIF, FontWeight.W700) val blockingFauxFontW700 = BlockingFauxFont(loader, Typeface.SANS_SERIF, FontWeight.W700) initializeSubject() val fontFamily = FontFamily( optionalFauxFontW400, optionalFauxFontW700, blockingFauxFontW700 ) val typefaceNoAdjustment = resolveAsTypeface(fontFamily, FontWeight.W400) assertThat(typefaceNoAdjustment).isSameInstanceAs(Typeface.MONOSPACE) initializeSubject(AndroidFontResolveInterceptor(accessibilityFontWeightAdjustment)) val typeface = resolveAsTypeface(fontFamily, FontWeight.W400) assertThat(typeface).isSameInstanceAs(Typeface.SERIF) } }
apache-2.0
8f20ebd4bb062341323854f83966bf8b
34.398977
99
0.663162
5.163402
false
true
false
false
androidx/androidx
navigation/navigation-compose/integration-tests/navigation-demos/src/main/java/androidx/navigation/compose/demos/NavSingleTopDemo.kt
3
2468
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.navigation.compose.demos import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Divider import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.compose.samples.NavigateButton @Composable fun NavSingleTopDemo() { val navController = rememberNavController() val query = rememberSaveable { mutableStateOf("") } Column(Modifier.fillMaxSize().then(Modifier.padding(8.dp))) { TextField( value = query.value, onValueChange = { query.value = it }, placeholder = { Text("Search") } ) NavigateButton("Search") { navController.navigate("search/" + query.value) { launchSingleTop = true } } NavHost(navController, startDestination = "start") { composable("start") { StartScreen() } composable("search/{query}") { backStackEntry -> SearchResultScreen( backStackEntry.arguments!!.getString("query", "no query entered") ) } } } } @Composable fun StartScreen() { Divider(color = Color.Black) Text(text = "Start a search above") } @Composable fun SearchResultScreen(query: String) { Text("You searched for $query") }
apache-2.0
f64f42eb949ceaa0a233b2657b20a374
33.760563
85
0.709076
4.621723
false
false
false
false